-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmessages.py
445 lines (346 loc) · 10.9 KB
/
messages.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
import logging
import pprint
from datetime import datetime, timedelta
import pytz
from constants import classAtlas, summaryAtlas, airDensityCalc
from WeatherUnits.defaults.WeatherFlow import Wind
from WeatherUnits.length import Length
from WeatherUnits.others import Direction, Humidity, Lux, RadiantFlux, Volts
from WeatherUnits.pressure import Pressure
from WeatherUnits.time import Minute, Second
from WeatherUnits.temperature import Temperature
class DataMessage(dict):
def __init__(self):
super().__init__()
@property
def data(self) -> dict:
return self['data']
@property
def time(self) -> datetime:
return self['time']
@property
def formatMessage(self) -> str:
return pprint.pformat(self)
class Observation(DataMessage):
messAtlas = {'serial_number': 'serial',
'hub_sn': 'hub',
'deviceID': 'device_id'}
atlas = ['time']
def __init__(self, udpData):
udpData = self.translate(udpData, self.messAtlas)
if 'data' in udpData:
udpData['data'] = self.convert(udpData['data'], self.atlas)
udpData['time'] = datetime.fromtimestamp(int(udpData['data'].pop('time')), pytz.timezone('America/New_York'))
self.update(udpData)
super(Observation, self).__init__()
@staticmethod
def translate(udpData: dict, atlas: dict[str:str]):
translated = {}
for key in udpData:
if key in atlas:
newKey = atlas[key]
translated[newKey] = udpData[key]
else:
translated[key] = udpData[key]
return translated
# return {key: udpData[value] for key, value in atlas.items()}
# translated = {}
# for native, foreign in atlas.items():
# try:
# translated.update({native: udpData[foreign]})
# except KeyError:
# logging.error('Unable to translate: {}'.format(native))
# return translated
@staticmethod
def convert(data, atlas):
converted = {}
if isinstance(data, list):
if len(data) == 1:
data = data[0]
for key, value in zip(atlas, data):
try:
converted[key] = classAtlas[key](value).localized
except AttributeError:
converted[key] = classAtlas[key](value)
elif isinstance(data, dict):
for key, value in data.items():
try:
converted[key] = classAtlas[key](value).localized
except AttributeError:
converted[key] = classAtlas[key](value)
return converted
def __setitem__(self, *args):
logging.error('UDP Messages are immutable')
class StatusMessage(dict):
atlas = {'time': 'timestamp',
'type': 'type',
'serial': 'serial_number',
'uptime': 'uptime',
'firmware': 'firmware_revision',
'rssi': 'rssi',
}
def __init__(self, udpData):
data = {key: udpData[value] for key, value in self.atlas.items()}
super(StatusMessage, self).__init__(data)
def __setitem__(self, *args):
logging.error('UDP Messages are immutable')
@property
def uptime(self):
value = timedelta(seconds=self['uptime'])
if value.days > 0:
return "{} days".format(value.days)
if value.days > 30:
return "{:2.1f} months".format(value.days / 30.5)
elif value.min // 60 > 0:
return "{:2.1f} hours".format(value.min / 60)
elif value.min > 0:
return "{} hours".format(value.min)
else:
return "{} seconds".format(value.seconds)
@property
def firmware(self):
return "v{}".format(self['firmware'])
@property
def serial(self):
return "{}".format(self['serial'])
class DeviceStatusMessage(StatusMessage):
atlas = {**StatusMessage.atlas,
'serialHub': 'hub_sn',
'battery': 'voltage',
'rssiHub': 'hub_rssi',
'sensorStatus': 'sensor_status',
'debug': 'debug'}
deviceStatus = {0: 'All OK', 1: 'Lightning failed'}
def __init__(self, udpData):
super(DeviceStatusMessage, self).__init__(udpData)
@property
def serialHub(self):
return "{}".format(self['serialHub'])
@property
def rssi(self):
return str(self['rssi'])
@property
def battery(self) -> Volts:
return Volts(self['battery'])
@property
def rssiHub(self):
return str(self['rssiHub'])
@property
def sensorStatus(self):
return SensorStatus(self['sensorStatus'])
class SensorStatus:
failed = []
masks = {
0b000000001: 'Lightning',
0b000000010: 'LightningNoise',
0b000000100: 'LightningDisturber',
0b000001000: 'Pressure',
0b000010000: 'Temperature',
0b000100000: 'Humidity',
0b001000000: 'Wind',
0b010000000: 'Precipitation',
0b100000000: 'Light/UV'
}
def __init__(self, value: int):
for mask in self.masks:
if mask & value:
self.failed.append(self.masks[mask])
def __str__(self):
failures = len(self.failed)
if not failures:
string = 'All OK'
elif failures == 1:
string = '{}: Failed'.format(self.failed[0])
elif failures == 2:
string = '{}: Failed\n{}: Failed\n'.format(self.failed[0], self.failed[1])
else:
string = 'Multiple Failures'
return string
def __repr__(self) -> str:
return str(self)
class HubStatusMessage(StatusMessage):
def __init__(self, udpData):
super(HubStatusMessage, self).__init__(udpData)
class RainStartMessage(Observation):
def __init__(self, udpData):
self.messAtlas['data'] = 'evt'
super().__init__(udpData)
@staticmethod
def print():
print('Rain event started')
class WindMessage(Observation):
atlas = [*Observation.atlas, 'speed', 'direction']
def __init__(self, udpData):
self.messAtlas['ob'] = 'data'
super(WindMessage, self).__init__(udpData)
@property
def speed(self) -> Wind:
return self.data['speed']
@property
def direction(self) -> Direction:
return self.data['direction']
@property
def messsage(self):
return 'Wind recorded {}km/h at {} ({}º)'.format(self.speed, self.direction.cardinal, self.direction)
class LightMessage(Observation):
"""
I haven't quite figured out what this message contains.
I am confident the item at index 2 is irradiance, but the
item a index 1 alludes me. It could be illuminance, but I
can not figure out what the unit is.
"""
atlas = [*Observation.atlas, 'illuminance', 'irradiance', 'zero', 'zero']
def __init__(self, udpData):
self.messAtlas['data'] = 'ob'
super(LightMessage, self).__init__(udpData)
delattr(self, 'atlas')
class _Air(DataMessage):
@property
def pressure(self) -> Pressure:
return self.data['pressure']
@property
def temperature(self) -> Temperature:
return self.data['temperature']
@property
def humidity(self) -> Humidity:
return self.data['humidity']
@property
def strikeDistance(self) -> Length:
return self.data['strikeDistance']
@property
def strikes(self) -> int:
return self.data['strikes']
class AirMessage(Observation, _Air):
atlas = [*Observation.atlas, 'pressure', 'temperature', 'humidity', 'lightning',
'lightningDistance', 'battery', 'reportInterval']
def __init__(self, udpData):
self.messAtlas['obs'] = 'data'
super(AirMessage, self).__init__(udpData)
class _Sky(DataMessage):
@property
def uvi(self) -> int:
return self.data['uvi']
@property
def accumulation(self) -> Length:
return self.data['accumulation']
@property
def lullSpeed(self) -> Wind:
return self.data['lullSpeed']
@property
def windSpeed(self) -> Wind:
return self.data['windSpeed']
@property
def wind(self) -> Wind:
return self.data['windSpeed']
@property
def gustSpeed(self) -> Wind:
return self.data['gustSpeed']
@property
def windDirection(self) -> Direction:
return self.data['windDirection']
@property
def battery(self) -> Volts:
return self.data['battery']
@property
def reportInterval(self) -> Minute:
return self.data['reportInterval']
@property
def irradiance(self) -> RadiantFlux:
return self.data['irradiance']
@property
def illuminance(self) -> Lux:
return self.data['illuminance']
@property
def accumulationDay(self) -> Length:
return self.data['accumulationDay']
@property
def precipitationType(self) -> int:
return self.data['precipitationType']
@property
def windSampleInterval(self) -> Second:
return self.data['windSampleInterval']
class SkyMessage(Observation, _Sky):
atlas = [*Observation.atlas, 'illuminance', 'uvi', 'accumulation', 'lullSpeed', 'windSpeed',
'gustSpeed', 'windDirection', 'battery', 'reportInterval', 'irradiance',
'accumulationDay', 'precipitationType', 'windSampleInterval']
def __init__(self, udpData):
self.messAtlas['obs'] = 'data'
super(SkyMessage, self).__init__(udpData)
if len(udpData['data'][0] == 16):
self.atlas += ['dailyAccumulationRainCheck', 'localDailyAccumulationRainCheck', 'rainCheck']
class TempestMessage(Observation, _Sky, _Air):
atlas = [*Observation.atlas, 'lullSpeed', 'windSpeed', 'gustSpeed', 'windDirection',
'windSampleInterval', 'pressure', 'temperature', 'humidity',
'illuminance', 'uvi', 'irradiance', 'accumulation',
'precipitationType', 'strikeDistance', 'strikes',
'battery', 'reportInterval']
def __init__(self, udpData):
self.messAtlas['obs'] = 'data'
super(TempestMessage, self).__init__(udpData)
if len(self.data) == 21:
self.atlas += ['dailyAccumulationRaw', 'dailyAccumulationRainCheck',
'localDailyAccumulationRainCheck', 'rainCheck']
if 'summary' in self:
summary = self.translate(self['summary'], summaryAtlas)
summary = self.convert(summary, classAtlas)
self.data.update(summary)
if 'rainCheck' in self.data:
# Always assume rainCheck is on unless specified as false
self.data['rainCheck'] = False if self.data['rainCheck'] == 2 else True
else:
self.data['rainCheck'] = False
@property
def rainCheck(self) -> bool:
return self.data['rainCheck']
@property
def precipRate(self):
from WeatherUnits.derived import Precipitation
return Precipitation(self.accumulation.inch, self.reportInterval.hour)
@property
def dailyAccumulation(self) -> Length:
return self.data['localDailyAccumulationRainCheck'] if self.rainCheck else self.data['dailyAccumulationRaw']
@property
def dewpoint(self):
try:
value = self.data['dewpoint']
except KeyError:
value = self.temperature.dewpoint(self.humidity)
return value.localized
@property
def heatIndex(self):
try:
value = self.data['heatIndex']
except KeyError:
value = self.temperature.heatIndex(self.humidity)
return value.localized
@property
def windChill(self):
try:
value = self.data['windChill']
except KeyError:
value = self.temperature.windChill(self.wind)
return value.localized
@property
def feelsLike(self):
try:
return self.data['feelsLike']
except KeyError:
if self.temperature.c > 27:
return self.heatIndex
elif self.temperature.c < 10:
return self.windChill
else:
return self.temperature
@property
def airDensity(self):
try:
value = self.data['airDensity']
except KeyError:
value = classAtlas['airDensity'](airDensityCalc(self.temperature, self.pressure))
return value
class LightningMessage(Observation):
def __init__(self, udpData):
self.messAtlas['evt'] = 'data'
self.atlas = [*self.atlas, 'distance', 'energy']
super(LightningMessage, self).__init__(udpData)
delattr(self, 'atlas')