Passed
Pull Request — main (#85)
by Guy
01:31 queued 10s
created

ims_envista.meteo_data   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 254
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 186
dl 0
loc 254
rs 10
c 0
b 0
f 0
wmc 16
1
"""Data Class for IMS Meteorological Readings."""
2
3
from __future__ import annotations
4
5
import datetime
6
import textwrap
7
import time
8
from dataclasses import dataclass, field
9
10
import pytz
11
12
from .const import (
13
    API_BP,
14
    API_CHANNELS,
15
    API_DATA,
16
    API_DATETIME,
17
    API_DIFF,
18
    API_GRAD,
19
    API_NAME,
20
    API_NIP,
21
    API_RAIN,
22
    API_RAIN_1_MIN,
23
    API_RH,
24
    API_STATION_ID,
25
    API_STATUS,
26
    API_STD_WD,
27
    API_TD,
28
    API_TD_MAX,
29
    API_TD_MIN,
30
    API_TG,
31
    API_TIME,
32
    API_TW,
33
    API_VALID,
34
    API_VALUE,
35
    API_WD,
36
    API_WD_MAX,
37
    API_WS,
38
    API_WS_1MM,
39
    API_WS_10MM,
40
    API_WS_MAX,
41
    VARIABLES,
42
)
43
44
MAX_HOUR_INT = 24
45
46
@dataclass
47
class MeteorologicalData:
48
    """Meteorological Data."""
49
50
    station_id: int
51
    """Station ID"""
52
    datetime: datetime.datetime
53
    """Date and time of the data"""
54
    rain: float
55
    """Rainfall in mm"""
56
    ws: float
57
    """Wind speed in m/s"""
58
    ws_max: float
59
    """Gust wind speed in m/s"""
60
    wd: float
61
    """Wind direction in deg"""
62
    wd_max: float
63
    """Gust wind direction in deg"""
64
    std_wd: float
65
    """Standard deviation wind direction in deg"""
66
    td: float
67
    """Temperature in °C"""
68
    td_max: float
69
    """Maximum Temperature in °C"""
70
    td_min: float
71
    """Minimum Temperature in °C"""
72
    tg: float
73
    """Ground Temperature in °C"""
74
    tw: float
75
    """TW Temperature (?) in °C"""
76
    rh: float
77
    """Relative humidity in %"""
78
    ws_1mm: float
79
    """Maximum 1 minute wind speed in m/s"""
80
    ws_10mm: float
81
    """Maximum 10 minute wind speed in m/s"""
82
    time: datetime.time
83
    """Time"""
84
    bp: float
85
    """Maximum barometric pressure in mb"""
86
    diff_r: float
87
    """Distributed radiation in w/m^2"""
88
    grad: float
89
    """Global radiation in w/m^2"""
90
    nip: float
91
    """Direct radiation in w/m^2"""
92
    rain_1_min: float
93
    """Rainfall per minute in mm"""
94
95
    def _prety_print_field(self, value: float | str | None, unit: str | None) -> str:
96
        """Pretty Print a specific field."""
97
        if value:
98
            return f"{value!s}{unit if unit else ''}"
99
        return "None"
100
101
    def _pretty_print(self) -> str:
102
        """Pretty Print."""
103
        return (
104
                f"StationID: {self._prety_print_field(self.station_id, None)}, "
105
                f"Date: {self._prety_print_field(self.datetime, None)}, "
106
                f"Readings: ["
107
                f"(TD: {self._prety_print_field(self.td, VARIABLES[API_TD].unit)}), "
108
                f"(TDmax: {self._prety_print_field(self.td_max, VARIABLES[API_TD_MAX].unit)}), "
109
                f"(TDmin: {self._prety_print_field(self.td_min, VARIABLES[API_TD_MIN].unit)}), "
110
                f"(TG: {self._prety_print_field(self.tg, VARIABLES[API_TG].unit)}), "
111
                f"(RH: {self._prety_print_field(self.rh, VARIABLES[API_RH].unit)}), "
112
                f"(Rain: {self._prety_print_field(self.rain, VARIABLES[API_RAIN].unit)}), "
113
                f"(WS: {self._prety_print_field(self.ws, VARIABLES[API_WS].unit)}), "
114
                f"(WSmax: {self._prety_print_field(self.ws_max, VARIABLES[API_WS_MAX].unit)}), "
115
                f"(WD: {self._prety_print_field(self.wd, VARIABLES[API_WD].unit)}), "
116
                f"(WDmax: {self._prety_print_field(self.wd_max, VARIABLES[API_WD_MAX].unit)}), "
117
                f"(STDwd: {self._prety_print_field(self.std_wd, VARIABLES[API_STD_WD].unit)}), "
118
                f"(WS1mm: {self._prety_print_field(self.ws_1mm, VARIABLES[API_WS_1MM].unit)}), "
119
                f"(WS10mm: {self._prety_print_field(self.ws_10mm, VARIABLES[API_WS_10MM].unit)}), "
120
                f"(Time: {self._prety_print_field(self.time.strftime("%H:%m") if self.time else None, VARIABLES[API_TIME].unit)})]"
121
            )
122
123
    def __str__(self) -> str:
124
        return self._pretty_print()
125
126
    def __repr__(self) -> str:
127
        return self._pretty_print().replace("\n", " ")
128
129
130
@dataclass
131
class StationMeteorologicalReadings:
132
    """Station Meteorological Readings."""
133
134
    station_id: int
135
    """ Station Id"""
136
    data: list[MeteorologicalData] = field(default_factory=list)
137
    """ List of Meteorological Data """
138
139
    def __repr__(self) -> str:
140
        return textwrap.dedent("""Station ({}), Data: {}""").format(
141
            self.station_id, self.data
142
        )
143
144
tz = pytz.timezone("Asia/Jerusalem")
145
146
147
def _fix_datetime_offset(dt: datetime.datetime) -> tuple[datetime.datetime, bool]:
148
    dt = dt.replace(tzinfo=None)
149
    dt = tz.localize(dt)
150
151
    # Get the UTC offset in seconds
152
    offset_seconds = dt.utcoffset().total_seconds()
153
154
    # Create a fixed timezone with the same offset and name
155
    fixed_timezone = datetime.timezone(datetime.timedelta(seconds=offset_seconds), dt.tzname())
156
157
    # Replace the pytz tzinfo with the fixed timezone
158
    dt = dt.replace(tzinfo=fixed_timezone)
159
160
    is_dst = dt.dst() and dt.dst() != datetime.timedelta(0)
161
    if is_dst:
162
        dt = dt + datetime.timedelta(hours=1)
163
164
    return dt,is_dst
165
166
167
def meteo_data_from_json(station_id: int, data: dict) -> MeteorologicalData:
168
    """Create a MeteorologicalData object from a JSON object."""
169
    dt = datetime.datetime.fromisoformat(data[API_DATETIME])
170
    dt, is_dst = _fix_datetime_offset(dt)
171
172
    channel_value_dict = {}
173
    for channel_value in data[API_CHANNELS]:
174
        if channel_value[API_VALID] is True and channel_value[API_STATUS] == 1:
175
            channel_value_dict[channel_value[API_NAME]] = float(
176
                channel_value[API_VALUE]
177
            )
178
179
    rain = channel_value_dict.get(API_RAIN)
180
    ws_max = channel_value_dict.get(API_WS_MAX)
181
    wd_max = channel_value_dict.get(API_WD_MAX)
182
    ws = channel_value_dict.get(API_WS)
183
    wd = channel_value_dict.get(API_WD)
184
    std_wd = channel_value_dict.get(API_STD_WD)
185
    td = channel_value_dict.get(API_TD)
186
    rh = channel_value_dict.get(API_RH)
187
    td_max = channel_value_dict.get(API_TD_MAX)
188
    td_min = channel_value_dict.get(API_TD_MIN)
189
    ws_1mm = channel_value_dict.get(API_WS_1MM)
190
    ws_10mm = channel_value_dict.get(API_WS_10MM)
191
    tg = channel_value_dict.get(API_TG)
192
    tw = channel_value_dict.get(API_TW)
193
    time_val = channel_value_dict.get(API_TIME)
194
    if time_val:
195
        time_int = int(time_val)
196
        if time_int <= MAX_HOUR_INT:
197
            t = time.strptime(str(time_int), "%H")
198
        else :
199
            t = time.strptime(str(time_int), "%H%M")
200
        time_val = datetime.time(t.tm_hour, t.tm_min, tzinfo=tz)
201
    bp = channel_value_dict.get(API_BP)
202
    diff_r = channel_value_dict.get(API_DIFF)
203
    grad = channel_value_dict.get(API_GRAD)
204
    nip = channel_value_dict.get(API_NIP)
205
    rain_1_min = channel_value_dict.get(API_RAIN_1_MIN)
206
207
    if is_dst and time_val:
208
        # Strange IMS logic :o
209
        dt = dt + datetime.timedelta(hours=1)
210
        time_val = time_val.replace(hour=(time_val.hour+1)%24)
211
212
    return MeteorologicalData(
213
        station_id=station_id,
214
        datetime=dt,
215
        rain=rain,
216
        ws=ws,
217
        ws_max=ws_max,
218
        wd=wd,
219
        wd_max=wd_max,
220
        std_wd=std_wd,
221
        td=td,
222
        td_max=td_max,
223
        td_min=td_min,
224
        tg=tg,
225
        tw=tw,
226
        rh=rh,
227
        ws_1mm=ws_1mm,
228
        ws_10mm=ws_10mm,
229
        time=time_val,
230
        bp=bp,
231
        diff_r=diff_r,
232
        grad=grad,
233
        nip=nip,
234
        rain_1_min=rain_1_min
235
    )
236
237
238
def station_meteo_data_from_json(json: dict) -> StationMeteorologicalReadings | None:
239
    station_id = int(json[API_STATION_ID])
240
    data = json.get(API_DATA)
241
    if not data:
242
        return None
243
    meteo_data = [meteo_data_from_json(station_id, single_meteo_data) for single_meteo_data in data]
244
    return StationMeteorologicalReadings(station_id, meteo_data)
245