aioarpapiemonte 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,481 @@
1
+ """Models of the real-time data of Arpa Piemonte.
2
+
3
+ Every model is a frozen dataclass of plain values and tuples: two downloads of
4
+ the same data compare equal.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import datetime as dt
10
+ from dataclasses import dataclass
11
+ from enum import IntEnum, StrEnum
12
+ from typing import TYPE_CHECKING, Any, Final, Self
13
+
14
+ from .const import STATION_PAGE_URL
15
+
16
+ if TYPE_CHECKING:
17
+ from collections.abc import Collection, Iterator, Mapping
18
+
19
+
20
+ class _NamedLevel(IntEnum):
21
+ """Ordered level shown by its lower-case name: ``str(level) == "suspect"``."""
22
+
23
+ def __str__(self) -> str:
24
+ return self.name.lower()
25
+
26
+ def __format__(self, format_spec: str) -> str:
27
+ return format(str(self), format_spec)
28
+
29
+ @property
30
+ def code(self) -> int:
31
+ """Return the numeric code of the value: its number."""
32
+ return int(self)
33
+
34
+ @classmethod
35
+ def from_code(cls, code: int) -> Self | None:
36
+ """Return the value of a numeric code; None when no value has it."""
37
+ return next((member for member in cls if member.code == code), None)
38
+
39
+
40
+ class _Coded(StrEnum):
41
+ """A value named by the text Arpa Piemonte uses, with a numeric code."""
42
+
43
+ @property
44
+ def code(self) -> int:
45
+ """Return the numeric code of the value."""
46
+ return _CODES[type(self)][self]
47
+
48
+ @classmethod
49
+ def from_code(cls, code: int) -> Self | None:
50
+ """Return the value of a numeric code; None when no value has it."""
51
+ return next((member for member in cls if member.code == code), None)
52
+
53
+
54
+ class Param(_Coded):
55
+ """A quantity of the real-time files of the Arpa website, by its folder.
56
+
57
+ Units are those the files state (``units_sym``).
58
+ """
59
+
60
+ LEVEL = "idro"
61
+ """Water level, in m above the hydrometric zero, at the end of the hour."""
62
+ RAIN_10_MIN = "pluv"
63
+ """Rain, in mm: "Livello pioggia sui 10 minuti", as the files describe it.
64
+
65
+ Not the rain of the hour: it was lower than the rain of the hour of the
66
+ api_realtime in 5 of 73 hours, and equal in the others, mostly without
67
+ rain (measured on 2026-11-17). For the rain of the hours, read
68
+ ``RealtimeField.CUM_RAIN_1H`` and the others.
69
+ """
70
+ TEMPERATURE = "terma"
71
+ """Air temperature, in °C, at the end of the hour."""
72
+ HUMIDITY = "igro"
73
+ """Relative humidity, in %, at the end of the hour."""
74
+ PRESSURE = "baro"
75
+ """Air pressure, in hPa."""
76
+ SNOW_DEPTH = "nivo"
77
+ """Snow depth, in cm."""
78
+ RADIATION = "radd"
79
+ """Global solar radiation, in W/m²."""
80
+ WIND_SPEED = "velv"
81
+ """Wind speed, in m/s."""
82
+ WIND_SPEED_SECONDARY = "vels"
83
+ """Wind speed of a second sensor, in m/s: the station page shows it when
84
+ ``velv`` is missing."""
85
+ GUST_SPEED = "velr"
86
+ """Speed of the strongest gust of the hour, in m/s."""
87
+ WIND_DIRECTION = "dirv"
88
+ """Direction the wind comes from, in degrees."""
89
+
90
+ @property
91
+ def unit(self) -> str:
92
+ """Return the unit of the quantity."""
93
+ return PARAM_UNITS[self]
94
+
95
+
96
+ PARAM_CODES: Final[Mapping[Param, int]] = {
97
+ Param.LEVEL: 1,
98
+ Param.RAIN_10_MIN: 2,
99
+ Param.TEMPERATURE: 3,
100
+ Param.HUMIDITY: 4,
101
+ Param.PRESSURE: 5,
102
+ Param.SNOW_DEPTH: 6,
103
+ Param.RADIATION: 7,
104
+ Param.WIND_SPEED: 8,
105
+ Param.WIND_SPEED_SECONDARY: 9,
106
+ Param.GUST_SPEED: 10,
107
+ Param.WIND_DIRECTION: 11,
108
+ }
109
+ """Codes of the quantities of the files, proposed by aioarpapiemonte."""
110
+
111
+ PARAM_UNITS: Final[Mapping[Param, str]] = {
112
+ Param.LEVEL: "m",
113
+ Param.RAIN_10_MIN: "mm",
114
+ Param.TEMPERATURE: "°C",
115
+ Param.HUMIDITY: "%",
116
+ Param.PRESSURE: "hPa",
117
+ Param.SNOW_DEPTH: "cm",
118
+ Param.RADIATION: "W/m²",
119
+ Param.WIND_SPEED: "m/s",
120
+ Param.WIND_SPEED_SECONDARY: "m/s",
121
+ Param.GUST_SPEED: "m/s",
122
+ Param.WIND_DIRECTION: "°",
123
+ }
124
+ """Units of the quantities, as the files state them (measured on 2026-11-17)."""
125
+
126
+
127
+ class RealtimeField(_Coded):
128
+ """A quantity of the records of the api_realtime, by its field."""
129
+
130
+ AIR_TEMPERATURE = "air_temperature"
131
+ """Air temperature, in °C."""
132
+ HUMIDITY = "humidity"
133
+ """Relative humidity, in %."""
134
+ CUM_RAIN_1H = "cum_rain_1h"
135
+ """Rain in the hour that ends at the time of the record, in mm."""
136
+ CUM_RAIN_3H = "cum_rain_3h"
137
+ """Rain in the 3 hours that end at the time of the record, in mm."""
138
+ CUM_RAIN_6H = "cum_rain_6h"
139
+ """Rain in the 6 hours that end at the time of the record, in mm."""
140
+ CUM_RAIN_12H = "cum_rain_12h"
141
+ """Rain in the 12 hours that end at the time of the record, in mm."""
142
+ CUM_RAIN_24H = "cum_rain_24h"
143
+ """Rain in the 24 hours that end at the time of the record, in mm."""
144
+ WIND = "wind"
145
+ """Wind speed, in km/h."""
146
+ WIND_DIRECTION = "wind_direction"
147
+ """Direction the wind comes from, in degrees."""
148
+ GUST_OF_WIND = "gust_of_wind"
149
+ """Speed of the strongest gust, in km/h."""
150
+ GUST_DIRECTION = "gust_direction"
151
+ """Direction the strongest gust comes from, in degrees."""
152
+ SNOW_HEIGHT = "snow_height"
153
+ """Snow depth, in cm."""
154
+ HYDROMETRIC_LEVEL = "hydrometric_level"
155
+ """Water level, in m above the hydrometric zero."""
156
+
157
+ @property
158
+ def unit(self) -> str:
159
+ """Return the unit of the quantity."""
160
+ return REALTIME_FIELD_UNITS[self]
161
+
162
+
163
+ REALTIME_FIELD_CODES: Final[Mapping[RealtimeField, int]] = {
164
+ RealtimeField.AIR_TEMPERATURE: 1,
165
+ RealtimeField.HUMIDITY: 2,
166
+ RealtimeField.CUM_RAIN_1H: 3,
167
+ RealtimeField.CUM_RAIN_3H: 4,
168
+ RealtimeField.CUM_RAIN_6H: 5,
169
+ RealtimeField.CUM_RAIN_12H: 6,
170
+ RealtimeField.CUM_RAIN_24H: 7,
171
+ RealtimeField.WIND: 8,
172
+ RealtimeField.WIND_DIRECTION: 9,
173
+ RealtimeField.GUST_OF_WIND: 10,
174
+ RealtimeField.GUST_DIRECTION: 11,
175
+ RealtimeField.SNOW_HEIGHT: 12,
176
+ RealtimeField.HYDROMETRIC_LEVEL: 13,
177
+ }
178
+ """Codes of the fields of the api_realtime, proposed by aioarpapiemonte."""
179
+
180
+ REALTIME_FIELD_UNITS: Final[Mapping[RealtimeField, str]] = {
181
+ RealtimeField.AIR_TEMPERATURE: "°C",
182
+ RealtimeField.HUMIDITY: "%",
183
+ RealtimeField.CUM_RAIN_1H: "mm",
184
+ RealtimeField.CUM_RAIN_3H: "mm",
185
+ RealtimeField.CUM_RAIN_6H: "mm",
186
+ RealtimeField.CUM_RAIN_12H: "mm",
187
+ RealtimeField.CUM_RAIN_24H: "mm",
188
+ RealtimeField.WIND: "km/h",
189
+ RealtimeField.WIND_DIRECTION: "°",
190
+ RealtimeField.GUST_OF_WIND: "km/h",
191
+ RealtimeField.GUST_DIRECTION: "°",
192
+ RealtimeField.SNOW_HEIGHT: "cm",
193
+ RealtimeField.HYDROMETRIC_LEVEL: "m",
194
+ }
195
+ """Units of the fields of the api_realtime, which states none.
196
+
197
+ Measured on 2026-11-17 against the files of the Arpa website, which state
198
+ theirs: level, temperature, humidity and snow are equal; wind and gust are 3.6
199
+ times the files in m/s (3.5 to 3.67, from the rounding), so in km/h.
200
+ """
201
+
202
+ _CODES: Final[Mapping[type[_Coded], Mapping[Any, int]]] = {
203
+ Param: PARAM_CODES,
204
+ RealtimeField: REALTIME_FIELD_CODES,
205
+ }
206
+ """The table of codes of each enum named by a text."""
207
+
208
+
209
+ class Validation(_NamedLevel):
210
+ """The automatic validation of a reading of the files (``valid_type``).
211
+
212
+ Arpa writes a code of three letters; its first letter gives the color of
213
+ the station page: green, yellow, orange or red. Measured on 2026-11-17:
214
+ OK; VTA, VIA, VIC, VSD; WTB, WSD; AIC, ASA; MMM. The A and M codes came
215
+ without a value.
216
+ """
217
+
218
+ UNKNOWN = 0
219
+ """A code aioarpapiemonte does not know."""
220
+ OK = 1
221
+ """Valid ("OK", green)."""
222
+ TO_VERIFY = 2
223
+ """To be verified (V..., yellow): the latest hours, often."""
224
+ SUSPECT = 3
225
+ """Suspect (W..., orange)."""
226
+ INVALID = 4
227
+ """Invalid (A..., red)."""
228
+ MISSING = 5
229
+ """Missing (M..., or no code: grey)."""
230
+
231
+ @classmethod
232
+ def of(cls, valid_type: str | None) -> Validation:
233
+ """Return the validation of a ``valid_type``."""
234
+ if not valid_type:
235
+ return cls.MISSING
236
+ return _VALIDATION_LETTERS.get(valid_type[0].upper(), cls.UNKNOWN)
237
+
238
+
239
+ _VALIDATION_LETTERS: Final[Mapping[str, Validation]] = {
240
+ "O": Validation.OK,
241
+ "V": Validation.TO_VERIFY,
242
+ "W": Validation.SUSPECT,
243
+ "A": Validation.INVALID,
244
+ "M": Validation.MISSING,
245
+ }
246
+ """Validation of each first letter of ``valid_type``, from the station page."""
247
+
248
+ USABLE: Final = frozenset(
249
+ {Validation.OK, Validation.TO_VERIFY, Validation.SUSPECT, Validation.UNKNOWN}
250
+ )
251
+ """The validations of a reading worth showing: all but invalid and missing.
252
+
253
+ A fast rise of a river can be suspect for the automatic validation while true:
254
+ it is shown, with its validation.
255
+ """
256
+
257
+
258
+ class LevelStatus(_NamedLevel):
259
+ """The water level against the thresholds of the station, ordered."""
260
+
261
+ UNKNOWN = 0
262
+ """The station has no thresholds."""
263
+ NORMAL = 1
264
+ """Below every threshold."""
265
+ PRE_ALARM = 2
266
+ """At or above the pre-alarm threshold."""
267
+ GUARD = 3
268
+ """At or above the guard threshold."""
269
+ DANGER = 4
270
+ """At or above the danger threshold."""
271
+
272
+
273
+ @dataclass(frozen=True, slots=True)
274
+ class Thresholds:
275
+ """Alert thresholds of a hydrometer, in metres above the hydrometric zero."""
276
+
277
+ pre_alarm: float | None = None
278
+ """Pre-alarm threshold."""
279
+ guard: float | None = None
280
+ """Guard threshold."""
281
+ danger: float | None = None
282
+ """Danger threshold."""
283
+
284
+ def status(self, level: float) -> LevelStatus:
285
+ """Return the highest threshold the level reaches.
286
+
287
+ A missing threshold is skipped; without any, the status is UNKNOWN.
288
+ """
289
+ limits = (
290
+ (LevelStatus.DANGER, self.danger),
291
+ (LevelStatus.GUARD, self.guard),
292
+ (LevelStatus.PRE_ALARM, self.pre_alarm),
293
+ )
294
+ known = [(status, limit) for status, limit in limits if limit is not None]
295
+ if not known:
296
+ return LevelStatus.UNKNOWN
297
+ return next(
298
+ (status for status, limit in known if level >= limit), LevelStatus.NORMAL
299
+ )
300
+
301
+
302
+ @dataclass(frozen=True, slots=True)
303
+ class Reading:
304
+ """A value measured at a time."""
305
+
306
+ time: dt.datetime
307
+ """Time of the measurement, in UTC."""
308
+ value: float
309
+ """The value, in the unit of its quantity."""
310
+
311
+
312
+ @dataclass(frozen=True, slots=True)
313
+ class Sensor:
314
+ """A station of the Arpa website (``sensors.geojson``).
315
+
316
+ Its identifier is the ISTAT code of its municipality when it was set up,
317
+ which can be an old one, and its number in that municipality.
318
+ """
319
+
320
+ id: str
321
+ """Identifier of the station on the website, 9 digits ("002105900")."""
322
+ name: str
323
+ """Name of the station."""
324
+ latitude: float
325
+ """Latitude, WGS84."""
326
+ longitude: float
327
+ """Longitude, WGS84."""
328
+ altitude: float | None
329
+ """Altitude, in metres."""
330
+ params: frozenset[Param]
331
+ """The quantities the station publishes."""
332
+ municipality: str | None = None
333
+ """Municipality of the station."""
334
+ river: str | None = None
335
+ """River a hydrometer measures."""
336
+ basin: str | None = None
337
+ """Basin of the station."""
338
+ other_params: tuple[str, ...] = ()
339
+ """Quantities of the station aioarpapiemonte does not know."""
340
+
341
+ def page_url(self, param: Param | None = None) -> str:
342
+ """Return the public page of the station; its first quantity by default."""
343
+ if param is None:
344
+ param = min(self.params, key=lambda item: item.code, default=Param.LEVEL)
345
+ return station_page_url(self.id, param)
346
+
347
+
348
+ @dataclass(frozen=True, slots=True)
349
+ class ParamReading:
350
+ """A reading of a file of the Arpa website."""
351
+
352
+ time: dt.datetime
353
+ """End of the hour of the reading, in UTC."""
354
+ value: float
355
+ """The value, in the unit of its quantity."""
356
+ validation: Validation
357
+ """The automatic validation of the reading."""
358
+ valid_type: str | None = None
359
+ """The validation code as published ("OK", "VTA")."""
360
+
361
+
362
+ @dataclass(frozen=True, slots=True)
363
+ class ParamSeries:
364
+ """The hourly readings of a quantity of a station, about the last 6 days."""
365
+
366
+ sensor_id: str
367
+ """Identifier of the station on the website."""
368
+ param: Param
369
+ """The quantity."""
370
+ name: str
371
+ """Name of the station."""
372
+ readings: tuple[ParamReading, ...]
373
+ """The readings with a value, from the oldest."""
374
+ river: str | None = None
375
+ """River a hydrometer measures."""
376
+ basin: str | None = None
377
+ """Basin of the station."""
378
+ hydrometric_zero: float | None = None
379
+ """Altitude of the zero of the level, in metres."""
380
+ thresholds: Thresholds | None = None
381
+ """Alert thresholds of a hydrometer; None for the other quantities."""
382
+ description: str | None = None
383
+ """Description of the quantity by Arpa ("Livello idrometrico")."""
384
+
385
+ def __iter__(self) -> Iterator[ParamReading]:
386
+ """Iterate over the readings, from the oldest."""
387
+ return iter(self.readings)
388
+
389
+ def __len__(self) -> int:
390
+ """Return the number of readings."""
391
+ return len(self.readings)
392
+
393
+ def latest(self, accept: Collection[Validation] = USABLE) -> ParamReading | None:
394
+ """Return the newest reading whose validation is accepted."""
395
+ return next(
396
+ (
397
+ reading
398
+ for reading in reversed(self.readings)
399
+ if reading.validation in accept
400
+ ),
401
+ None,
402
+ )
403
+
404
+ @property
405
+ def page_url(self) -> str:
406
+ """Return the public page of the station for this quantity."""
407
+ return station_page_url(self.sensor_id, self.param)
408
+
409
+
410
+ @dataclass(frozen=True, slots=True)
411
+ class RealtimeStation:
412
+ """A station of the api_realtime (``pie_anag``)."""
413
+
414
+ station_code: str
415
+ """Code of the station in the network, leading zeros kept ("188")."""
416
+ name: str
417
+ """Name of the station, in capitals."""
418
+ latitude: float
419
+ """Latitude, WGS84, rounded to 4 decimals."""
420
+ longitude: float
421
+ """Longitude, WGS84."""
422
+ altitude: float | None
423
+ """Altitude, in metres."""
424
+ station_type: str
425
+ """Letters of the sensors of the station ("IPT"), as published."""
426
+ municipality: str
427
+ """Municipality of the station."""
428
+ municipality_code: str
429
+ """ISTAT code of the municipality, the current one."""
430
+ river: str | None
431
+ """River a hydrometer measures."""
432
+ basin: str | None
433
+ """Basin of the station."""
434
+ hydrometric_zero: float | None
435
+ """Altitude of the zero of the level, in metres."""
436
+ thresholds: Thresholds
437
+ """Alert thresholds of the level; all None without hydrometer."""
438
+ sensor_id: str | None
439
+ """Identifier of the station on the Arpa website ("002105900").
440
+
441
+ Made of ``codice_istat_comune`` and ``progr_punto_com``; None when either
442
+ is missing. 373 of the 374 stations have a file on the website
443
+ (measured on 2026-11-17).
444
+ """
445
+
446
+
447
+ @dataclass(frozen=True, slots=True)
448
+ class RealtimeRecord:
449
+ """The values of a station at an hour, from the api_realtime."""
450
+
451
+ time: dt.datetime
452
+ """Time of the record, in UTC."""
453
+ values: tuple[tuple[RealtimeField, float], ...]
454
+ """The fields with a value."""
455
+
456
+ def get(self, field: RealtimeField) -> float | None:
457
+ """Return the value of a field; None when it has none."""
458
+ return next((value for key, value in self.values if key is field), None)
459
+
460
+
461
+ @dataclass(frozen=True, slots=True)
462
+ class RealtimeData:
463
+ """The records of a station, about the last 3 days, from the oldest."""
464
+
465
+ station_code: str
466
+ """Code of the station in the network."""
467
+ records: tuple[RealtimeRecord, ...]
468
+ """The records, at strictly increasing times."""
469
+
470
+ def latest(self, field: RealtimeField) -> Reading | None:
471
+ """Return the newest value of a field; None when there is none."""
472
+ for record in reversed(self.records):
473
+ value = record.get(field)
474
+ if value is not None:
475
+ return Reading(record.time, value)
476
+ return None
477
+
478
+
479
+ def station_page_url(sensor_id: str, param: Param) -> str:
480
+ """Return the public page of a station on the Arpa website."""
481
+ return STATION_PAGE_URL.format(sensor_id=sensor_id, param=param.value)