2022-02-12 21:08:13 +01:00
|
|
|
//! Maps retrieval and caching.
|
|
|
|
//!
|
|
|
|
//! This module provides a task that keeps maps up-to-date using a maps-specific refresh interval.
|
|
|
|
//! It stores all the maps as [`DynamicImage`]s in memory.
|
2022-02-12 15:58:56 +01:00
|
|
|
|
2022-02-19 15:29:50 +01:00
|
|
|
use std::collections::HashMap;
|
2022-02-18 22:59:21 +01:00
|
|
|
use std::f64::consts::PI;
|
2022-02-13 11:16:19 +01:00
|
|
|
use std::sync::{Arc, Mutex};
|
|
|
|
|
2022-02-18 21:25:06 +01:00
|
|
|
use chrono::serde::ts_seconds;
|
2022-05-10 13:21:21 +02:00
|
|
|
use chrono::{DateTime, Duration, NaiveDateTime, Utc};
|
2022-02-22 12:49:42 +01:00
|
|
|
use image::{DynamicImage, GenericImage, GenericImageView, ImageFormat, Pixel, Rgb, Rgba};
|
2022-02-13 13:10:12 +01:00
|
|
|
use reqwest::Url;
|
2022-02-18 21:25:06 +01:00
|
|
|
use rocket::serde::Serialize;
|
2022-02-16 22:02:32 +01:00
|
|
|
use rocket::tokio;
|
2022-02-19 16:45:37 +01:00
|
|
|
use rocket::tokio::time::sleep;
|
2022-02-12 15:58:56 +01:00
|
|
|
|
2022-02-22 12:49:42 +01:00
|
|
|
use crate::forecast::Metric;
|
2022-02-18 21:25:06 +01:00
|
|
|
use crate::position::Position;
|
|
|
|
|
2022-02-13 11:16:19 +01:00
|
|
|
/// A handle to access the in-memory cached maps.
|
|
|
|
pub(crate) type MapsHandle = Arc<Mutex<Maps>>;
|
2022-02-12 17:20:36 +01:00
|
|
|
|
2022-02-19 15:29:50 +01:00
|
|
|
/// A histogram mapping map key colors to occurences/counts.
|
|
|
|
type MapKeyHistogram = HashMap<Rgb<u8>, u32>;
|
|
|
|
|
|
|
|
/// The Buienradar map key used for determining the score of a coordinate by mapping its color.
|
|
|
|
///
|
|
|
|
/// Note that the actual score starts from 1, not 0 as per this array.
|
|
|
|
#[rustfmt::skip]
|
|
|
|
const MAP_KEY: [[u8; 3]; 10] = [
|
2022-05-21 09:47:01 +02:00
|
|
|
[0x49, 0xDA, 0x21],
|
|
|
|
[0x30, 0xD2, 0x00],
|
|
|
|
[0xFF, 0xF8, 0x8B],
|
|
|
|
[0xFF, 0xF6, 0x42],
|
|
|
|
[0xFD, 0xBB, 0x31],
|
|
|
|
[0xFD, 0x8E, 0x24],
|
|
|
|
[0xFC, 0x10, 0x3E],
|
2022-05-21 09:47:23 +02:00
|
|
|
[0x97, 0x0A, 0x33],
|
2022-05-21 09:47:01 +02:00
|
|
|
[0xA6, 0x6D, 0xBC],
|
|
|
|
[0xB3, 0x30, 0xA1],
|
2022-02-19 15:29:50 +01:00
|
|
|
];
|
|
|
|
|
|
|
|
/// The Buienradar map sample size.
|
|
|
|
///
|
|
|
|
/// Determiess the number of pixels in width/height that is samples around the sampling coordinate.
|
|
|
|
const MAP_SAMPLE_SIZE: [u32; 2] = [11, 11];
|
|
|
|
|
2022-02-12 15:58:56 +01:00
|
|
|
/// The interval between map refreshes (in seconds).
|
2022-02-19 16:45:37 +01:00
|
|
|
const REFRESH_INTERVAL: tokio::time::Duration = tokio::time::Duration::from_secs(60);
|
2022-02-12 21:08:13 +01:00
|
|
|
|
2022-02-13 11:16:19 +01:00
|
|
|
/// The base URL for retrieving the pollen maps from Buienradar.
|
2022-02-12 21:08:13 +01:00
|
|
|
const POLLEN_BASE_URL: &str =
|
|
|
|
"https://image.buienradar.nl/2.0/image/sprite/WeatherMapPollenRadarHourlyNL\
|
2022-02-13 13:10:12 +01:00
|
|
|
?width=820&height=988&extension=png&renderBackground=False&renderBranding=False\
|
|
|
|
&renderText=False&history=0&forecast=24&skip=0";
|
2022-02-12 21:08:13 +01:00
|
|
|
|
|
|
|
/// The interval for retrieving pollen maps.
|
2022-02-13 21:24:26 +01:00
|
|
|
///
|
|
|
|
/// The endpoint provides a map for every hour, 24 in total.
|
2022-02-19 16:45:37 +01:00
|
|
|
const POLLEN_INTERVAL: i64 = 3_600;
|
2022-02-12 21:08:13 +01:00
|
|
|
|
2022-02-15 17:04:04 +01:00
|
|
|
/// The number of pollen maps retained.
|
2022-02-17 21:03:24 +01:00
|
|
|
const POLLEN_MAP_COUNT: u32 = 24;
|
|
|
|
|
|
|
|
/// The number of seconds each pollen map is for.
|
2022-02-19 16:45:37 +01:00
|
|
|
const POLLEN_MAP_INTERVAL: i64 = 3_600;
|
2022-02-15 17:04:04 +01:00
|
|
|
|
2022-02-18 21:25:06 +01:00
|
|
|
/// The position reference points for the pollen map.
|
|
|
|
///
|
|
|
|
/// Maps the gecoded positions of two reference points as follows:
|
|
|
|
/// * Latitude and longitude of Vlissingen to its y- and x-position
|
|
|
|
/// * Latitude of Lauwersoog to its y-position and longitude of Enschede to its x-position
|
|
|
|
const POLLEN_MAP_REF_POINTS: [(Position, (u32, u32)); 2] = [
|
2022-02-18 22:59:21 +01:00
|
|
|
(Position::new(51.44, 3.57), (745, 84)), // Vlissingen
|
|
|
|
(Position::new(53.40, 6.90), (111, 694)), // Lauwersoog (lat/y) and Enschede (lon/x)
|
2022-02-18 21:25:06 +01:00
|
|
|
];
|
|
|
|
|
2022-02-13 11:16:19 +01:00
|
|
|
/// The base URL for retrieving the UV index maps from Buienradar.
|
2022-02-12 21:08:13 +01:00
|
|
|
const UVI_BASE_URL: &str = "https://image.buienradar.nl/2.0/image/sprite/WeatherMapUVIndexNL\
|
2022-02-13 16:55:20 +01:00
|
|
|
?width=820&height=988&extension=png&&renderBackground=False&renderBranding=False\
|
2022-02-13 13:10:12 +01:00
|
|
|
&renderText=False&history=0&forecast=5&skip=0";
|
2022-02-12 21:08:13 +01:00
|
|
|
|
|
|
|
/// The interval for retrieving UV index maps.
|
2022-02-13 21:24:26 +01:00
|
|
|
///
|
|
|
|
/// The endpoint provides a map for every day, 5 in total.
|
2022-02-19 16:45:37 +01:00
|
|
|
const UVI_INTERVAL: i64 = 24 * 3_600;
|
2022-02-12 21:08:13 +01:00
|
|
|
|
2022-02-15 17:04:04 +01:00
|
|
|
/// The number of UV index maps retained.
|
2022-02-17 21:03:24 +01:00
|
|
|
const UVI_MAP_COUNT: u32 = 5;
|
|
|
|
|
|
|
|
/// The number of seconds each UV index map is for.
|
2022-02-19 16:45:37 +01:00
|
|
|
const UVI_MAP_INTERVAL: i64 = 24 * 3_600;
|
2022-02-15 17:04:04 +01:00
|
|
|
|
2022-02-18 21:25:06 +01:00
|
|
|
/// The position reference points for the UV index map.
|
2022-02-18 22:59:21 +01:00
|
|
|
const UVI_MAP_REF_POINTS: [(Position, (u32, u32)); 2] = POLLEN_MAP_REF_POINTS;
|
2022-02-18 21:25:06 +01:00
|
|
|
|
2022-02-13 11:16:19 +01:00
|
|
|
/// The `MapsRefresh` trait is used to reduce the time a lock needs to be held when updating maps.
|
|
|
|
///
|
|
|
|
/// When refreshing maps, the lock only needs to be held when checking whether a refresh is
|
|
|
|
/// necessary and when the new maps have been retrieved and can be updated.
|
|
|
|
trait MapsRefresh {
|
2022-02-17 21:12:35 +01:00
|
|
|
/// Determines whether the pollen maps need to be refreshed.
|
2022-02-13 11:16:19 +01:00
|
|
|
fn needs_pollen_refresh(&self) -> bool;
|
2022-02-12 21:35:58 +01:00
|
|
|
|
2022-02-17 21:12:35 +01:00
|
|
|
/// Determines whether the UV index maps need to be refreshed.
|
2022-02-13 11:16:19 +01:00
|
|
|
fn needs_uvi_refresh(&self) -> bool;
|
|
|
|
|
2022-02-17 21:12:35 +01:00
|
|
|
/// Determines whether the pollen maps are stale.
|
|
|
|
fn is_pollen_stale(&self) -> bool;
|
|
|
|
|
|
|
|
/// Determines whether the UV index maps are stale.
|
|
|
|
fn is_uvi_stale(&self) -> bool;
|
|
|
|
|
2022-02-13 11:16:19 +01:00
|
|
|
/// Updates the pollen maps.
|
2022-05-10 14:19:09 +02:00
|
|
|
fn set_pollen(&self, result: Option<RetrievedMaps>);
|
2022-02-13 11:16:19 +01:00
|
|
|
|
|
|
|
/// Updates the UV index maps.
|
2022-05-10 14:19:09 +02:00
|
|
|
fn set_uvi(&self, result: Option<RetrievedMaps>);
|
2022-02-12 21:08:13 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Container type for all in-memory cached maps.
|
2022-05-10 14:19:09 +02:00
|
|
|
#[derive(Debug, Default)]
|
2022-02-12 21:08:13 +01:00
|
|
|
pub(crate) struct Maps {
|
|
|
|
/// The pollen maps (from Buienradar).
|
2022-05-10 14:19:09 +02:00
|
|
|
pub(crate) pollen: Option<RetrievedMaps>,
|
2022-02-12 21:08:13 +01:00
|
|
|
|
|
|
|
/// The UV index maps (from Buienradar).
|
2022-05-10 14:19:09 +02:00
|
|
|
pub(crate) uvi: Option<RetrievedMaps>,
|
2022-02-12 21:08:13 +01:00
|
|
|
}
|
2022-02-12 15:58:56 +01:00
|
|
|
|
|
|
|
impl Maps {
|
2022-02-15 17:04:04 +01:00
|
|
|
/// Creates a new maps cache.
|
|
|
|
///
|
|
|
|
/// It contains an [`DynamicImage`] per maps type, if downloaded, and the timestamp of the last
|
|
|
|
/// update.
|
2022-02-12 21:08:13 +01:00
|
|
|
pub(crate) fn new() -> Self {
|
|
|
|
Self {
|
|
|
|
pollen: None,
|
|
|
|
uvi: None,
|
|
|
|
}
|
|
|
|
}
|
2022-02-15 17:04:04 +01:00
|
|
|
|
2022-02-22 12:49:42 +01:00
|
|
|
/// Returns a current pollen map that marks the provided position.
|
2022-02-17 21:03:24 +01:00
|
|
|
///
|
2022-02-22 12:49:42 +01:00
|
|
|
/// This returns [`None`] if the maps are not in the cache yet, there is no matching map for
|
|
|
|
/// the current moment or if the provided position is not within the bounds of the map.
|
|
|
|
pub(crate) fn pollen_mark(&self, position: Position) -> Option<DynamicImage> {
|
2022-02-19 15:08:05 +01:00
|
|
|
self.pollen.as_ref().and_then(|maps| {
|
2022-05-10 14:19:09 +02:00
|
|
|
let image = &maps.image;
|
|
|
|
let stamp = maps.timestamp_base;
|
|
|
|
let marked_image = map_at(
|
|
|
|
image,
|
|
|
|
stamp,
|
2022-02-22 12:49:42 +01:00
|
|
|
POLLEN_MAP_INTERVAL,
|
|
|
|
POLLEN_MAP_COUNT,
|
|
|
|
Utc::now(),
|
|
|
|
)?;
|
2022-05-10 14:19:09 +02:00
|
|
|
let coords = project(&marked_image, POLLEN_MAP_REF_POINTS, position)?;
|
2022-02-19 15:08:05 +01:00
|
|
|
|
2022-05-10 14:19:09 +02:00
|
|
|
Some(mark(marked_image, coords))
|
2022-02-19 15:08:05 +01:00
|
|
|
})
|
2022-02-18 21:25:06 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Samples the pollen maps for the given position.
|
|
|
|
///
|
|
|
|
/// This returns [`None`] if the maps are not in the cache yet.
|
|
|
|
/// Otherwise, it returns [`Some`] with a list of pollen sample, one for each map
|
|
|
|
/// in the series of maps.
|
2022-02-22 12:49:42 +01:00
|
|
|
pub(crate) fn pollen_samples(&self, position: Position) -> Option<Vec<Sample>> {
|
2022-02-19 15:29:50 +01:00
|
|
|
self.pollen.as_ref().and_then(|maps| {
|
2022-05-10 14:19:09 +02:00
|
|
|
let image = &maps.image;
|
|
|
|
let map = image.view(0, 0, image.width() / UVI_MAP_COUNT, image.height());
|
2022-02-22 12:49:42 +01:00
|
|
|
let coords = project(&*map, POLLEN_MAP_REF_POINTS, position)?;
|
2022-05-10 14:19:09 +02:00
|
|
|
let stamp = maps.timestamp_base;
|
2022-02-19 15:29:50 +01:00
|
|
|
|
2022-05-10 14:19:09 +02:00
|
|
|
sample(image, stamp, POLLEN_MAP_INTERVAL, POLLEN_MAP_COUNT, coords)
|
2022-02-19 15:29:50 +01:00
|
|
|
})
|
2022-02-18 21:25:06 +01:00
|
|
|
}
|
|
|
|
|
2022-02-22 12:49:42 +01:00
|
|
|
/// Returns a current UV index map that marks the provided position.
|
2022-02-17 21:03:24 +01:00
|
|
|
///
|
2022-02-22 12:49:42 +01:00
|
|
|
/// This returns [`None`] if the maps are not in the cache yet, there is no matching map for
|
|
|
|
/// the current moment or if the provided position is not within the bounds of the map.
|
|
|
|
pub(crate) fn uvi_mark(&self, position: Position) -> Option<DynamicImage> {
|
2022-02-19 15:08:05 +01:00
|
|
|
self.uvi.as_ref().and_then(|maps| {
|
2022-05-10 14:19:09 +02:00
|
|
|
let image = &maps.image;
|
|
|
|
let stamp = maps.timestamp_base;
|
|
|
|
let marked_image = map_at(image, stamp, UVI_MAP_INTERVAL, UVI_MAP_COUNT, Utc::now())?;
|
|
|
|
let coords = project(&marked_image, POLLEN_MAP_REF_POINTS, position)?;
|
2022-02-19 15:08:05 +01:00
|
|
|
|
2022-05-10 14:19:09 +02:00
|
|
|
Some(mark(marked_image, coords))
|
2022-02-19 15:08:05 +01:00
|
|
|
})
|
2022-02-18 21:25:06 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Samples the UV index maps for the given position.
|
|
|
|
///
|
|
|
|
/// This returns [`None`] if the maps are not in the cache yet.
|
|
|
|
/// Otherwise, it returns [`Some`] with a list of UV index sample, one for each map
|
|
|
|
/// in the series of maps.
|
2022-02-22 12:49:42 +01:00
|
|
|
pub(crate) fn uvi_samples(&self, position: Position) -> Option<Vec<Sample>> {
|
2022-02-19 15:29:50 +01:00
|
|
|
self.uvi.as_ref().and_then(|maps| {
|
2022-05-10 14:19:09 +02:00
|
|
|
let image = &maps.image;
|
|
|
|
let map = image.view(0, 0, image.width() / UVI_MAP_COUNT, image.height());
|
2022-02-22 12:49:42 +01:00
|
|
|
let coords = project(&*map, UVI_MAP_REF_POINTS, position)?;
|
2022-05-10 14:19:09 +02:00
|
|
|
let stamp = maps.timestamp_base;
|
2022-02-19 15:29:50 +01:00
|
|
|
|
2022-05-10 14:19:09 +02:00
|
|
|
sample(image, stamp, UVI_MAP_INTERVAL, UVI_MAP_COUNT, coords)
|
2022-02-19 15:29:50 +01:00
|
|
|
})
|
2022-02-18 21:25:06 +01:00
|
|
|
}
|
2022-02-13 11:16:19 +01:00
|
|
|
}
|
2022-02-12 21:08:13 +01:00
|
|
|
|
2022-02-13 11:16:19 +01:00
|
|
|
impl MapsRefresh for MapsHandle {
|
2022-02-17 21:12:35 +01:00
|
|
|
fn is_pollen_stale(&self) -> bool {
|
|
|
|
let maps = self.lock().expect("Maps handle mutex was poisoned");
|
|
|
|
|
2022-05-10 14:19:09 +02:00
|
|
|
match &maps.pollen {
|
|
|
|
Some(pollen_maps) => {
|
|
|
|
Utc::now().signed_duration_since(pollen_maps.mtime)
|
|
|
|
> Duration::seconds(POLLEN_MAP_COUNT as i64 * POLLEN_MAP_INTERVAL)
|
|
|
|
}
|
|
|
|
None => false,
|
|
|
|
}
|
2022-02-17 21:12:35 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
fn is_uvi_stale(&self) -> bool {
|
|
|
|
let maps = self.lock().expect("Maps handle mutex was poisoned");
|
|
|
|
|
2022-05-10 14:19:09 +02:00
|
|
|
match &maps.uvi {
|
|
|
|
Some(uvi_maps) => {
|
|
|
|
Utc::now().signed_duration_since(uvi_maps.mtime)
|
|
|
|
> Duration::seconds(UVI_MAP_COUNT as i64 * UVI_MAP_INTERVAL)
|
|
|
|
}
|
|
|
|
None => false,
|
|
|
|
}
|
2022-02-17 21:12:35 +01:00
|
|
|
}
|
|
|
|
|
2022-02-13 11:16:19 +01:00
|
|
|
fn needs_pollen_refresh(&self) -> bool {
|
2022-02-13 16:55:03 +01:00
|
|
|
let maps = self.lock().expect("Maps handle mutex was poisoned");
|
2022-02-19 16:45:37 +01:00
|
|
|
|
2022-05-10 14:19:09 +02:00
|
|
|
match &maps.pollen {
|
|
|
|
Some(pollen_maps) => {
|
|
|
|
Utc::now()
|
|
|
|
.signed_duration_since(pollen_maps.mtime)
|
|
|
|
.num_seconds()
|
|
|
|
> POLLEN_INTERVAL
|
|
|
|
}
|
|
|
|
None => true,
|
|
|
|
}
|
2022-02-12 21:08:13 +01:00
|
|
|
}
|
2022-02-12 17:20:36 +01:00
|
|
|
|
2022-02-13 11:16:19 +01:00
|
|
|
fn needs_uvi_refresh(&self) -> bool {
|
2022-02-13 16:55:03 +01:00
|
|
|
let maps = self.lock().expect("Maps handle mutex was poisoned");
|
2022-02-19 16:45:37 +01:00
|
|
|
|
2022-05-10 14:19:09 +02:00
|
|
|
match &maps.uvi {
|
|
|
|
Some(uvi_maps) => {
|
|
|
|
Utc::now()
|
|
|
|
.signed_duration_since(uvi_maps.mtime)
|
|
|
|
.num_seconds()
|
|
|
|
> UVI_INTERVAL
|
|
|
|
}
|
|
|
|
None => true,
|
|
|
|
}
|
2022-02-12 21:08:13 +01:00
|
|
|
}
|
|
|
|
|
2022-05-10 14:19:09 +02:00
|
|
|
fn set_pollen(&self, retrieved_maps: Option<RetrievedMaps>) {
|
|
|
|
if retrieved_maps.is_some() || self.is_pollen_stale() {
|
2022-02-17 21:12:35 +01:00
|
|
|
let mut maps = self.lock().expect("Maps handle mutex was poisoned");
|
2022-05-10 14:19:09 +02:00
|
|
|
maps.pollen = retrieved_maps;
|
2022-02-17 21:12:35 +01:00
|
|
|
}
|
2022-02-13 11:16:19 +01:00
|
|
|
}
|
2022-02-12 21:08:13 +01:00
|
|
|
|
2022-05-10 14:19:09 +02:00
|
|
|
fn set_uvi(&self, retrieved_maps: Option<RetrievedMaps>) {
|
|
|
|
if retrieved_maps.is_some() || self.is_uvi_stale() {
|
2022-02-17 21:12:35 +01:00
|
|
|
let mut maps = self.lock().expect("Maps handle mutex was poisoned");
|
2022-05-10 14:19:09 +02:00
|
|
|
maps.uvi = retrieved_maps;
|
2022-02-17 21:12:35 +01:00
|
|
|
}
|
2022-02-12 15:58:56 +01:00
|
|
|
}
|
|
|
|
}
|
2022-02-12 21:08:13 +01:00
|
|
|
|
2022-02-19 15:29:50 +01:00
|
|
|
/// A Buienradar map sample.
|
2022-02-18 21:25:06 +01:00
|
|
|
///
|
|
|
|
/// This represents a value at a given time.
|
2022-05-08 12:53:09 +02:00
|
|
|
#[derive(Clone, Debug, PartialEq, Serialize)]
|
2022-02-18 21:25:06 +01:00
|
|
|
#[serde(crate = "rocket::serde")]
|
2022-02-19 15:29:50 +01:00
|
|
|
pub(crate) struct Sample {
|
2022-02-18 21:25:06 +01:00
|
|
|
/// The time(stamp) of the forecast.
|
|
|
|
#[serde(serialize_with = "ts_seconds::serialize")]
|
2022-02-24 20:23:33 +01:00
|
|
|
pub(crate) time: DateTime<Utc>,
|
2022-02-18 21:25:06 +01:00
|
|
|
|
2022-02-19 15:29:50 +01:00
|
|
|
/// The forecasted score.
|
2022-02-18 21:25:06 +01:00
|
|
|
///
|
|
|
|
/// A value in the range `1..=10`.
|
2022-02-19 15:29:50 +01:00
|
|
|
#[serde(rename(serialize = "value"))]
|
2022-02-24 20:23:33 +01:00
|
|
|
pub(crate) score: u8,
|
2022-02-19 15:29:50 +01:00
|
|
|
}
|
|
|
|
|
2022-05-08 13:54:17 +02:00
|
|
|
impl Sample {
|
|
|
|
#[cfg(test)]
|
|
|
|
pub(crate) fn new(time: DateTime<Utc>, score: u8) -> Self {
|
|
|
|
Self { time, score }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-19 15:29:50 +01:00
|
|
|
/// Builds a scoring histogram for the map key.
|
|
|
|
fn map_key_histogram() -> MapKeyHistogram {
|
|
|
|
MAP_KEY
|
|
|
|
.into_iter()
|
|
|
|
.fold(HashMap::new(), |mut hm, channels| {
|
|
|
|
hm.insert(Rgb::from(channels), 0);
|
|
|
|
hm
|
|
|
|
})
|
2022-02-18 21:25:06 +01:00
|
|
|
}
|
|
|
|
|
2022-02-19 15:29:50 +01:00
|
|
|
/// Samples the provided maps at the given (map-relative) coordinates and starting timestamp.
|
|
|
|
/// It assumes the provided coordinates are within bounds of at least one map.
|
|
|
|
/// The interval is the number of seconds the timestamp is bumped for each map.
|
2022-02-18 21:25:06 +01:00
|
|
|
///
|
2022-02-19 15:29:50 +01:00
|
|
|
/// Returns [`None`] if it encounters no known colors in any of the samples.
|
|
|
|
fn sample<I: GenericImageView<Pixel = Rgba<u8>>>(
|
2022-05-10 14:19:09 +02:00
|
|
|
image: &I,
|
2022-02-19 16:45:37 +01:00
|
|
|
stamp: DateTime<Utc>,
|
|
|
|
interval: i64,
|
2022-02-19 15:29:50 +01:00
|
|
|
count: u32,
|
|
|
|
coords: (u32, u32),
|
|
|
|
) -> Option<Vec<Sample>> {
|
|
|
|
let (x, y) = coords;
|
2022-05-10 14:19:09 +02:00
|
|
|
let width = image.width() / count;
|
|
|
|
let height = image.height();
|
2022-02-19 15:29:50 +01:00
|
|
|
let max_sample_width = (width - x).min(MAP_SAMPLE_SIZE[0]);
|
|
|
|
let max_sample_height = (height - y).min(MAP_SAMPLE_SIZE[1]);
|
|
|
|
let mut samples = Vec::with_capacity(count as usize);
|
2022-02-19 16:45:37 +01:00
|
|
|
let mut time = stamp;
|
2022-02-19 15:29:50 +01:00
|
|
|
let mut offset = 0;
|
|
|
|
|
2022-05-10 14:19:09 +02:00
|
|
|
while offset < image.width() {
|
|
|
|
let map = image.view(
|
2022-02-19 15:29:50 +01:00
|
|
|
x.saturating_sub(MAP_SAMPLE_SIZE[0] / 2) + offset,
|
|
|
|
y.saturating_sub(MAP_SAMPLE_SIZE[1] / 2),
|
|
|
|
max_sample_width,
|
|
|
|
max_sample_height,
|
|
|
|
);
|
|
|
|
let histogram = map
|
|
|
|
.pixels()
|
|
|
|
.fold(map_key_histogram(), |mut h, (_px, _py, color)| {
|
|
|
|
h.entry(color.to_rgb()).and_modify(|count| *count += 1);
|
|
|
|
h
|
|
|
|
});
|
|
|
|
let (max_color, &count) = histogram
|
|
|
|
.iter()
|
|
|
|
.max_by_key(|(_color, count)| *count)
|
|
|
|
.expect("Map key is never empty");
|
|
|
|
if count == 0 {
|
|
|
|
return None;
|
|
|
|
}
|
2022-02-18 21:25:06 +01:00
|
|
|
|
2022-02-19 15:29:50 +01:00
|
|
|
let score = MAP_KEY
|
|
|
|
.iter()
|
|
|
|
.position(|&color| &Rgb::from(color) == max_color)
|
|
|
|
.map(|score| score + 1) // Scores go from 1..=10, not 0..=9!
|
|
|
|
.expect("Maximum color is always a map key color") as u8;
|
|
|
|
|
|
|
|
samples.push(Sample { time, score });
|
|
|
|
time = time + chrono::Duration::seconds(interval as i64);
|
|
|
|
offset += width;
|
|
|
|
}
|
|
|
|
|
|
|
|
Some(samples)
|
2022-02-18 21:25:06 +01:00
|
|
|
}
|
|
|
|
|
2022-05-10 14:19:09 +02:00
|
|
|
/// A retrieved image with some metadata.
|
|
|
|
#[derive(Debug)]
|
|
|
|
pub(crate) struct RetrievedMaps {
|
|
|
|
/// The image data.
|
|
|
|
pub(crate) image: DynamicImage,
|
|
|
|
|
|
|
|
/// The date/time the image was last modified.
|
|
|
|
pub(crate) mtime: DateTime<Utc>,
|
|
|
|
|
|
|
|
/// The starting date/time the image corresponds with.
|
|
|
|
pub(crate) timestamp_base: DateTime<Utc>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl RetrievedMaps {
|
|
|
|
#[cfg(test)]
|
|
|
|
pub(crate) fn new(image: DynamicImage) -> Self {
|
|
|
|
let mtime = Utc::now();
|
|
|
|
let timestamp_base = Utc::now();
|
|
|
|
|
|
|
|
Self {
|
|
|
|
image,
|
|
|
|
mtime,
|
|
|
|
timestamp_base,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-12 21:08:13 +01:00
|
|
|
/// Retrieves an image from the provided URL.
|
2022-02-13 11:22:22 +01:00
|
|
|
///
|
2022-02-19 16:45:37 +01:00
|
|
|
/// This returns [`None`] if it fails in either performing the request, parsing the `Last-Modified`
|
|
|
|
/// reponse HTTP header, retrieving the bytes from the image or loading and the decoding the data
|
|
|
|
/// into [`DynamicImage`].
|
2022-05-10 14:19:09 +02:00
|
|
|
async fn retrieve_image(url: Url) -> Option<RetrievedMaps> {
|
2022-02-12 21:08:13 +01:00
|
|
|
// TODO: Handle or log errors!
|
|
|
|
let response = reqwest::get(url).await.ok()?;
|
2022-02-19 16:45:37 +01:00
|
|
|
let mtime = response
|
|
|
|
.headers()
|
|
|
|
.get(reqwest::header::LAST_MODIFIED)
|
|
|
|
.and_then(|dt| dt.to_str().ok())
|
|
|
|
.map(chrono::DateTime::parse_from_rfc2822)?
|
|
|
|
.map(DateTime::<Utc>::from)
|
|
|
|
.ok()?;
|
2022-05-10 13:21:21 +02:00
|
|
|
let timestamp_base = {
|
|
|
|
let path = response.url().path();
|
|
|
|
let (_, filename) = path.rsplit_once('/')?;
|
|
|
|
let (timestamp_str, _) = filename.split_once("__")?;
|
|
|
|
let timestamp = NaiveDateTime::parse_from_str(timestamp_str, "%Y%m%d%H%M").ok()?;
|
|
|
|
|
|
|
|
DateTime::<Utc>::from_utc(timestamp, Utc)
|
|
|
|
};
|
2022-02-12 21:08:13 +01:00
|
|
|
let bytes = response.bytes().await.ok()?;
|
|
|
|
|
2022-02-16 22:02:32 +01:00
|
|
|
tokio::task::spawn_blocking(move || {
|
2022-02-19 16:45:37 +01:00
|
|
|
if let Ok(image) = image::load_from_memory_with_format(&bytes, ImageFormat::Png) {
|
2022-05-10 14:19:09 +02:00
|
|
|
Some(RetrievedMaps {
|
|
|
|
image,
|
|
|
|
mtime,
|
|
|
|
timestamp_base,
|
|
|
|
})
|
2022-02-19 16:45:37 +01:00
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
2022-02-16 22:02:32 +01:00
|
|
|
})
|
|
|
|
.await
|
|
|
|
.ok()?
|
2022-02-12 21:08:13 +01:00
|
|
|
}
|
2022-02-13 11:16:19 +01:00
|
|
|
|
|
|
|
/// Retrieves the pollen maps from Buienradar.
|
|
|
|
///
|
|
|
|
/// See [`POLLEN_BASE_URL`] for the base URL and [`retrieve_image`] for the retrieval function.
|
2022-05-10 14:19:09 +02:00
|
|
|
async fn retrieve_pollen_maps() -> Option<RetrievedMaps> {
|
2022-02-13 13:10:12 +01:00
|
|
|
let timestamp = format!("{}", chrono::Local::now().format("%y%m%d%H%M"));
|
|
|
|
let mut url = Url::parse(POLLEN_BASE_URL).unwrap();
|
|
|
|
url.query_pairs_mut().append_pair("timestamp", ×tamp);
|
2022-02-13 11:16:19 +01:00
|
|
|
|
2022-06-05 21:29:12 +02:00
|
|
|
println!("🗺️ Refreshing pollen maps from: {}", url);
|
2022-02-13 13:10:12 +01:00
|
|
|
retrieve_image(url).await
|
2022-02-13 11:16:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Retrieves the UV index maps from Buienradar.
|
|
|
|
///
|
|
|
|
/// See [`UVI_BASE_URL`] for the base URL and [`retrieve_image`] for the retrieval function.
|
2022-05-10 14:19:09 +02:00
|
|
|
async fn retrieve_uvi_maps() -> Option<RetrievedMaps> {
|
2022-02-13 13:10:12 +01:00
|
|
|
let timestamp = format!("{}", chrono::Local::now().format("%y%m%d%H%M"));
|
|
|
|
let mut url = Url::parse(UVI_BASE_URL).unwrap();
|
|
|
|
url.query_pairs_mut().append_pair("timestamp", ×tamp);
|
2022-02-13 11:16:19 +01:00
|
|
|
|
2022-06-05 21:29:12 +02:00
|
|
|
println!("🗺️ Refreshing UV index maps from: {}", url);
|
2022-02-13 13:10:12 +01:00
|
|
|
retrieve_image(url).await
|
2022-02-13 11:16:19 +01:00
|
|
|
}
|
|
|
|
|
2022-02-22 12:49:42 +01:00
|
|
|
/// Returns the map for the given instant.
|
|
|
|
///
|
|
|
|
/// This returns [`None`] if `instant` is too far in the future with respect to the number of
|
|
|
|
/// cached maps.
|
|
|
|
fn map_at(
|
2022-05-10 14:19:09 +02:00
|
|
|
image: &DynamicImage,
|
|
|
|
stamp: DateTime<Utc>,
|
2022-02-22 12:49:42 +01:00
|
|
|
interval: i64,
|
|
|
|
count: u32,
|
|
|
|
instant: DateTime<Utc>,
|
|
|
|
) -> Option<DynamicImage> {
|
2022-05-10 14:19:09 +02:00
|
|
|
let duration = instant.signed_duration_since(stamp);
|
2022-02-22 12:49:42 +01:00
|
|
|
let offset = (duration.num_seconds() / interval) as u32;
|
|
|
|
// Check if out of bounds.
|
2022-03-07 19:19:08 +01:00
|
|
|
if offset >= count {
|
2022-02-22 12:49:42 +01:00
|
|
|
return None;
|
|
|
|
}
|
2022-05-10 14:19:09 +02:00
|
|
|
let width = image.width() / count;
|
2022-02-22 12:49:42 +01:00
|
|
|
|
2022-05-10 14:19:09 +02:00
|
|
|
Some(image.crop_imm(offset * width, 0, width, image.height()))
|
2022-02-22 12:49:42 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Marks the provided coordinates on the map using a horizontal and vertical line.
|
2022-05-10 14:19:09 +02:00
|
|
|
fn mark(mut image: DynamicImage, coords: (u32, u32)) -> DynamicImage {
|
2022-02-22 12:49:42 +01:00
|
|
|
let (x, y) = coords;
|
|
|
|
|
2022-05-10 14:19:09 +02:00
|
|
|
for py in 0..image.height() {
|
|
|
|
image.put_pixel(x, py, Rgba::from([0x00, 0x00, 0x00, 0x70]));
|
2022-02-22 12:49:42 +01:00
|
|
|
}
|
2022-05-10 14:19:09 +02:00
|
|
|
for px in 0..image.width() {
|
|
|
|
image.put_pixel(px, y, Rgba::from([0x00, 0x00, 0x00, 0x70]));
|
2022-02-22 12:49:42 +01:00
|
|
|
}
|
|
|
|
|
2022-05-10 14:19:09 +02:00
|
|
|
image
|
2022-02-22 12:49:42 +01:00
|
|
|
}
|
|
|
|
|
2022-02-19 15:08:05 +01:00
|
|
|
/// Projects the provided geocoded position to a coordinate on a map.
|
|
|
|
///
|
|
|
|
/// This uses two reference points and a Mercator projection on the y-coordinates of those points
|
|
|
|
/// to calculate how the map scales with respect to the provided position.
|
2022-02-18 22:59:21 +01:00
|
|
|
///
|
|
|
|
/// Returns [`None`] if the resulting coordinate is not within the bounds of the map.
|
2022-02-19 15:08:05 +01:00
|
|
|
fn project<I: GenericImageView>(
|
2022-05-10 14:19:09 +02:00
|
|
|
image: &I,
|
2022-02-18 22:59:21 +01:00
|
|
|
ref_points: [(Position, (u32, u32)); 2],
|
|
|
|
pos: Position,
|
|
|
|
) -> Option<(u32, u32)> {
|
|
|
|
// Get the data from the reference points.
|
|
|
|
let (ref1, (ref1_y, ref1_x)) = ref_points[0];
|
|
|
|
let (ref2, (ref2_y, ref2_x)) = ref_points[1];
|
|
|
|
|
|
|
|
// For the x-coordinate, use a linear scale.
|
|
|
|
let scale_x = ((ref2_x - ref1_x) as f64) / (ref2.lon_as_rad() - ref1.lon_as_rad());
|
|
|
|
let x = ((pos.lon_as_rad() - ref1.lon_as_rad()) * scale_x + ref1_x as f64).round() as u32;
|
|
|
|
|
|
|
|
// For the y-coordinate, use a Mercator-projected scale.
|
|
|
|
let mercator_y = |lat: f64| (lat / 2.0 + PI / 4.0).tan().ln();
|
|
|
|
let ref1_merc_y = mercator_y(ref1.lat_as_rad());
|
|
|
|
let ref2_merc_y = mercator_y(ref2.lat_as_rad());
|
|
|
|
let scale_y = ((ref1_y - ref2_y) as f64) / (ref2_merc_y - ref1_merc_y);
|
|
|
|
let y = ((ref2_merc_y - mercator_y(pos.lat_as_rad())) * scale_y + ref2_y as f64).round() as u32;
|
|
|
|
|
2022-05-10 14:19:09 +02:00
|
|
|
if image.in_bounds(x, y) {
|
2022-02-18 22:59:21 +01:00
|
|
|
Some((x, y))
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-22 12:49:42 +01:00
|
|
|
/// Returns the data of a map with a crosshair drawn on it for the given position.
|
|
|
|
///
|
|
|
|
/// The map that is used is determined by the provided metric.
|
|
|
|
pub(crate) async fn mark_map(
|
|
|
|
position: Position,
|
|
|
|
metric: Metric,
|
|
|
|
maps_handle: &MapsHandle,
|
|
|
|
) -> Option<Vec<u8>> {
|
|
|
|
use std::io::Cursor;
|
|
|
|
|
|
|
|
let maps_handle = Arc::clone(maps_handle);
|
|
|
|
tokio::task::spawn_blocking(move || {
|
|
|
|
let maps = maps_handle.lock().expect("Maps handle lock was poisoned");
|
|
|
|
let image = match metric {
|
|
|
|
Metric::PAQI => maps.pollen_mark(position),
|
|
|
|
Metric::Pollen => maps.pollen_mark(position),
|
|
|
|
Metric::UVI => maps.uvi_mark(position),
|
|
|
|
_ => return None, // Unsupported metric
|
|
|
|
}?;
|
|
|
|
drop(maps);
|
|
|
|
|
|
|
|
// Encode the image as PNG image data.
|
|
|
|
let mut image_data = Cursor::new(Vec::new());
|
|
|
|
image
|
|
|
|
.write_to(
|
|
|
|
&mut image_data,
|
|
|
|
image::ImageOutputFormat::from(image::ImageFormat::Png),
|
|
|
|
)
|
|
|
|
.ok()?;
|
|
|
|
|
|
|
|
Some(image_data.into_inner())
|
|
|
|
})
|
|
|
|
.await
|
|
|
|
.ok()
|
|
|
|
.flatten()
|
|
|
|
}
|
|
|
|
|
2022-02-13 11:16:19 +01:00
|
|
|
/// Runs a loop that keeps refreshing the maps when necessary.
|
|
|
|
///
|
|
|
|
/// Use [`MapsRefresh`] trait methods on `maps_handle` to check whether each maps type needs to be
|
|
|
|
/// refreshed and uses its retrieval function to update it if necessary.
|
2022-03-15 09:23:01 +01:00
|
|
|
pub(crate) async fn run(maps_handle: MapsHandle) {
|
2022-02-13 11:16:19 +01:00
|
|
|
loop {
|
|
|
|
println!("🕔 Refreshing the maps (if necessary)...");
|
|
|
|
|
|
|
|
if maps_handle.needs_pollen_refresh() {
|
2022-05-10 14:19:09 +02:00
|
|
|
let retrieved_maps = retrieve_pollen_maps().await;
|
|
|
|
maps_handle.set_pollen(retrieved_maps);
|
2022-02-13 11:16:19 +01:00
|
|
|
}
|
2022-02-17 21:47:01 +01:00
|
|
|
|
2022-02-13 11:16:19 +01:00
|
|
|
if maps_handle.needs_uvi_refresh() {
|
2022-05-10 14:19:09 +02:00
|
|
|
let retrieved_maps = retrieve_uvi_maps().await;
|
|
|
|
maps_handle.set_uvi(retrieved_maps);
|
2022-02-13 11:16:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
sleep(REFRESH_INTERVAL).await;
|
|
|
|
}
|
|
|
|
}
|