-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodels.py
373 lines (283 loc) · 11.3 KB
/
models.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
from dataclasses import dataclass, field, InitVar, fields
import marshmallow
import inspect
from marshmallow_dataclass import class_schema
from typing import Optional, List, Dict, Union, Tuple, Any
from .enums import Energy
from .utilities import SignalQuality
from datetime import datetime
class TimeStamp(marshmallow.fields.DateTime):
"""
Class extends marshmallow standard DateTime with "timestamp" format.
"""
SERIALIZATION_FUNCS = \
marshmallow.fields.DateTime.SERIALIZATION_FUNCS.copy()
DESERIALIZATION_FUNCS = \
marshmallow.fields.DateTime.DESERIALIZATION_FUNCS.copy()
SERIALIZATION_FUNCS['timestamp'] = lambda x: int(x.timestamp()) * 1000
DESERIALIZATION_FUNCS['timestamp'] = datetime.fromtimestamp
DEFAULT_FORMAT = "timestamp"
# api models
class BaseSchema(marshmallow.Schema):
TYPE_MAPPING = {datetime: TimeStamp}
@marshmallow.pre_load
def pre_load(self, data, **kwargs):
if 'client' in self.context:
data['_client'] = self.context['client']
if 'unit' not in self.context:
return data
data['unit'] = str(self.context['unit'])
keys = [*data.keys()]
if self.context['unit'] == Energy.Killowatts:
for k in keys:
if k.endswith('Kw'):
newK = 'e' + k[1:len(k) - 2]
data[newK] = data[k]
elif self.context['unit'] == Energy.KillowattHours:
for k in keys:
if k.endswith('Kwh'):
newK = 'e' + k[1:len(k) - 3]
data[newK] = data[k]
return data
def on_bind_field(self, field_name, field_obj):
name = field_obj.data_key or field_name
field_obj.data_key = name[0].lower() + name[1:]
@dataclass
class RateLimits:
TotalPerDay: int = field(metadata=dict(data_key='X-RateLimit-TpdLimit'), default=None)
RemainingPerDay: int = field(metadata=dict(data_key='X-RateLimit-TpdRemaining'), default=None)
TotalPerDayResetCounter: int = field(metadata=dict(data_key='X-RateLimit-TpdReset'), default=None)
TotalPerSecond: int = field(metadata=dict(data_key='X-RateLimit-TpsLimit'), default=None)
RemainingPerSecond: int = field(metadata=dict(data_key='X-RateLimit-TpsRemaining'), default=None)
TotalPerSecondResetCounter: float = field(metadata=dict(data_key='X-RateLimit-TpsReset'), default=None)
RetryAfter: Optional[int] = field(metadata=dict(data_key='Retry-After'), default=None)
class Meta:
unknown = marshmallow.EXCLUDE
RateLimitsSchema = class_schema(RateLimits)
@dataclass
class ChannelCategory:
Id: int
Label: str
Description: str
class Meta:
unknown = marshmallow.EXCLUDE
ChannelCategorySchema = class_schema(ChannelCategory, base_schema=BaseSchema)
@dataclass
class DeviceModel:
Code: str = None
DisplayName: str = None
ChannelsCount: int = None
SwitchesCount: int = None
Communications: str = None
class Meta:
unknown = marshmallow.EXCLUDE
DeviceModelSchema = class_schema(DeviceModel, base_schema=BaseSchema)
@dataclass
class DevicePending:
ShortEnergyReportingInterval: int = None
CtRating: int = None
State: str = None
@dataclass
class DeviceComms:
Type: str = None
LastHeardAt: datetime = None
SignalQualityDbm: int = None
networkId: str = None
APN: Optional[str] = field(metadata=dict(data_key='apn'), default=None)
SimId: Optional[str] = None
IMSI: Optional[str] = field(metadata=dict(data_key='imsi'), default=None)
@property
def SignalQuality(self) -> str:
if self.Type == 'wifi':
commsType = 'wifi'
elif self.Type == 'cellular':
commsType = '4G' # need to guess at this stage
else:
return None
return SignalQuality(commsType, self.SignalQualityDbm)
class Meta:
unknown = marshmallow.EXCLUDE
DeviceCommsSchema = class_schema(DeviceComms, base_schema=BaseSchema)
@dataclass
class ChannelAttribute:
Id: str = None
CtRating: int = None
Label: str = None
CategoryId: int = None
CategoryLabel: str = None
pending: DevicePending = field(default=DevicePending)
def __post_init__(self):
self._dirtyFields = {}
def __setattr__(self, name, value):
if '_' not in name and name != 'Id' and hasattr(self, '_dirtyFields'):
object.__getattribute__(self, '_dirtyFields')[name] = value
object.__setattr__(self, name, value)
class Meta:
unknown = marshmallow.EXCLUDE
ChannelAttributeSchema = class_schema(ChannelAttribute, base_schema=BaseSchema)
@dataclass
class ChannelGrouping:
Included: List[str] = field(default_factory=list)
class Meta:
unknown = marshmallow.EXCLUDE
ChannelGroupingSchema = class_schema(ChannelGrouping, base_schema=BaseSchema)
@dataclass
class PhaseConfiguration:
Count: int = None
Grouping: List[ChannelGrouping] = field(default_factory=list)
def __post_init__(self):
self._dirtyFields = {}
def __setattr__(self, name, value):
if '_' not in name and name != 'Id' and hasattr(self, '_dirtyFields'):
object.__getattribute__(self, '_dirtyFields')[name] = value
object.__setattr__(self, name, value)
class Meta:
unknown = marshmallow.EXCLUDE
PhaseConfigurationSchema = class_schema(PhaseConfiguration, base_schema=BaseSchema)
@dataclass
class SwitchAttribute:
Id: str = None
State: str = None
Label: str = None
ContactorType: str = None
ClosedStateLabel: str = None
OpenStateLabel: str = None
Pending: DevicePending = field(default=DevicePending)
def __post_init__(self):
self._dirtyFields = {}
def __setattr__(self, name, value):
if '_' not in name and name != 'Id' and hasattr(self, '_dirtyFields'):
object.__getattribute__(self, '_dirtyFields')[name] = value
object.__setattr__(self, name, value)
class Meta:
unknown = marshmallow.EXCLUDE
SwitchAttributeSchema = class_schema(SwitchAttribute, base_schema=BaseSchema)
@dataclass
class ShortData:
Timestamp: datetime = None
Duration: int = None
Frequency: float = None
Unit: str = None
GroupedBy: Optional[str] = None
Real: List[float] = field(metadata=dict(data_key='eReal'), default=None)
Reactive: List[float] = field(metadata=dict(data_key='eReactive'), default=None)
VoltageRMS: List[float] = field(metadata=dict(data_key='vRMS'), default=None)
CurrentRMS: List[float] = field(metadata=dict(data_key='iRMS'), default=None)
class Meta:
unknown = marshmallow.EXCLUDE
ShortDataSchema = class_schema(ShortData, base_schema=BaseSchema)
@dataclass
class LongData:
Timestamp: datetime = None
Duration: int = None
Unit: str = None
Real: List[int] = field(metadata=dict(data_key='eReal'), default=None)
RealNegative: List[float] = field(metadata=dict(data_key='eRealNegative'), default=None)
RealPositive: List[float] = field(metadata=dict(data_key='eRealPositive'), default=None)
Reactive: List[float] = field(metadata=dict(data_key='eReactive'), default=None)
ReactiveNegative: List[float] = field(metadata=dict(data_key='eReactiveNegative'), default=None)
ReactivePositive: List[float] = field(metadata=dict(data_key='eReactivePositive'), default=None)
VoltageRMSMin: List[float] = field(metadata=dict(data_key='vRMSMin'), default=None)
VoltageRMSMax: List[float] = field(metadata=dict(data_key='vRMSMax'), default=None)
CurrentRMSMin: List[float] = field(metadata=dict(data_key='iRMSMin'), default=None)
CurrentRMSMax: List[float] = field(metadata=dict(data_key='iRMSMax'), default=None)
class Meta:
unknown = marshmallow.EXCLUDE
LongDataSchema = class_schema(LongData, base_schema=BaseSchema)
@dataclass
class ModbusData:
_Ia: float = None
_Ib: float = None
_Ic: float = None
_PFa: float = None
_PFb: float = None
_PFc: float = None
_Uan: float = None
_Ubn: float = None
_Ucn: float = None
kVAh: int = None
kWh_Exp: int = None
kWh_Imp: int = None
kWh_Net: int = None
kWh_Tot: int = None
kvarh_Q1: int = None
kvarh_Q2: int = None
kvarh_Q3: int = None
kvarh_Q4: int = None
kvarh_Exp: int = None
kvarh_Imp: int = None
kvarh_Net: int = None
kvarh_Tot: int = None
Model: str = None
Timestamp: datetime = None
class Meta:
unknown = marshmallow.EXCLUDE
ModbusDataSchema = class_schema(ModbusData, base_schema=BaseSchema)
@dataclass
class Device:
Id: str
Label: str = None
Timezone: str = None
Model: str = None
FirmwareVersion: str = None
LatestStatus: int = None
ShortEnergyReportingInterval: int = None
Pending: DevicePending = field(default=DevicePending)
Comms: DeviceComms = field(default=DeviceComms)
Channels: List[ChannelAttribute] = field(default_factory=list)
Phases: PhaseConfiguration = field(default=PhaseConfiguration)
Switches: List[SwitchAttribute] = field(default_factory=list)
_client: Optional[Any] = None
_dirtyFields = {}
_isPartial = False
def __post_init__(self, *args, **kwargs):
self._isPartial = self.Model == None
def update(self):
if self.Phases._dirtyFields != {}:
self._dirtyFields['phases'] = PhaseConfigurationSchema().dump(self.Phases)
dirtyChannels = []
for c in self.Channels:
if c._dirtyFields != {}:
dirtyChannels.append(c)
dirtySwitches = []
for s in self.Switches:
if s._dirtyFields != {}:
dirtySwitches.append(s)
if dirtyChannels:
schema = ChannelAttributeSchema()
self._dirtyFields['channels'] = []
for c in dirtyChannels:
dc = schema.dump(c)
del dc['categoryLabel']; del dc['pending']
self._dirtyFields['channels'].append(dc)
if dirtySwitches:
schema = SwitchAttributeSchema()
self._dirtyFields['switches'] = [schema.dump(s) for s in dirtySwitches]
self._client.updateDevice(self.Id, self._dirtyFields)
if 'phases' in self._dirtyFields:
self.Phases._dirtyFields = {}
for c in dirtyChannels:
c._dirtyFields = {}
for s in dirtySwitches:
c._dirtyFields = {}
self._dirtyFields = {}
def __setattr__(self, name, value):
if '_' not in name and name != 'Id':
object.__getattribute__(self, '_dirtyFields')[name] = value
object.__setattr__(self, name, value)
def __getattribute__(self, name):
if name != 'Id' and '_' not in name and object.__getattribute__(self, '_isPartial'):
device = self._client.device(self.Id)
members = fields(Device)
for dname in [n.name for n in members if '_' not in n.name]:
setattr(self, dname, getattr(device, dname))
self._isPartial = False
self._dirtyFields = {}
return object.__getattribute__(self, name)
def __str__(self):
return '<Device(Id:{device_id})>'.format(device_id=self.Id)
def __repr__(self):
return '<Device(Id:{device_id})>'.format(device_id=self.Id)
class Meta:
unknown = marshmallow.EXCLUDE
DeviceSchema = class_schema(Device, base_schema=BaseSchema)