aiopytedapi 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.
aiopytedapi/models.py ADDED
@@ -0,0 +1,404 @@
1
+ """What the gateway reports, as plain frozen dataclasses.
2
+
3
+ Each model is built from the gateway's protobuf answer (``from_proto``) and
4
+ renders a JSON-safe dict (``to_dict``). Values that identify a home or a
5
+ person (Wi-Fi SSID, MAC and IP addresses, key descriptions) are kept out of
6
+ ``repr`` so they don't end up in debug logs, and ``to_dict`` only includes
7
+ them with ``details=True``. The gateway's Wi-Fi password is never parsed: the
8
+ schema doesn't model that field.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import base64
14
+ import math
15
+ from dataclasses import dataclass, field
16
+ from datetime import datetime, timezone
17
+ from ipaddress import IPv4Address
18
+ from typing import Any, Dict, List, Optional, Tuple, Union
19
+
20
+ from google.protobuf.internal.enum_type_wrapper import EnumTypeWrapper
21
+
22
+ from ._proto import tedapi_pb2 as pb
23
+ from .keys import fingerprint
24
+
25
+ Number = Union[int, float]
26
+
27
+
28
+ def enum_name(enum_type: EnumTypeWrapper, value: int, prefix: str = "") -> str:
29
+ """The name of a protobuf enum value without ``prefix``, or
30
+ ``"UNKNOWN (<value>)"`` for a value this schema doesn't define, so newer
31
+ firmware can't break the output."""
32
+ try:
33
+ name = enum_type.Name(value)
34
+ except ValueError:
35
+ return f"UNKNOWN ({value})"
36
+ return name[len(prefix) :] if prefix and name.startswith(prefix) else name
37
+
38
+
39
+ # ── Network status ───────────────────────────────────────────────────
40
+
41
+ #: Interface keys in the order the gateway reports them.
42
+ INTERFACES = ("wifi", "eth", "gsm")
43
+
44
+
45
+ def format_ipv4(value: int) -> Optional[str]:
46
+ """Dotted quad for a fixed32 IPv4 value (first octet in the most
47
+ significant byte), or None when unset (0)."""
48
+ return str(IPv4Address(value)) if value else None
49
+
50
+
51
+ def format_mac(value: bytes) -> Optional[str]:
52
+ """``aa:bb:cc:dd:ee:ff`` for MAC address bytes, or None when there is
53
+ none (the cellular interface has no MAC)."""
54
+ return ":".join(f"{octet:02x}" for octet in value) if value else None
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class IPv4Settings:
59
+ """An interface's IPv4 settings."""
60
+
61
+ dhcp_enabled: bool
62
+ address: Optional[str]
63
+ subnet_mask: Optional[str]
64
+ gateway: Optional[str]
65
+ dns: Tuple[str, ...]
66
+
67
+ def to_dict(self) -> Dict[str, Any]:
68
+ return {
69
+ "dhcp_enabled": self.dhcp_enabled,
70
+ "address": self.address,
71
+ "subnet_mask": self.subnet_mask,
72
+ "gateway": self.gateway,
73
+ "dns": list(self.dns),
74
+ }
75
+
76
+
77
+ @dataclass(frozen=True)
78
+ class NetworkInterfaceStatus:
79
+ """Status of one gateway network interface.
80
+
81
+ ``signal_strength_percent``, ``rssi`` and ``snr`` are None when the
82
+ gateway doesn't report them (a Powerwall 3 on firmware 26.34.3 reports
83
+ only the percentage)."""
84
+
85
+ enabled: bool = False
86
+ active_route: bool = False # carries the default route
87
+ connected_physical: bool = False # link / association is up
88
+ connected_internet: bool = False
89
+ connected_tesla: bool = False # can reach Tesla's servers
90
+ signal_strength_percent: Optional[int] = None
91
+ rssi: Optional[int] = None # dBm
92
+ snr: Optional[int] = None # dB
93
+ device_state: str = "NETWORK_DEVICE_STATE_INVALID"
94
+ device_state_reason: str = "NETWORK_DEVICE_STATE_REASON_INVALID"
95
+ mac_address: Optional[str] = field(default=None, repr=False)
96
+ ipv4: Optional[IPv4Settings] = field(default=None, repr=False)
97
+
98
+ @classmethod
99
+ def from_proto(cls, interface: pb.NetworkInterface) -> NetworkInterfaceStatus:
100
+ status = interface.connectivity_status
101
+ rssi = status.rssi
102
+ ipv4 = None
103
+ if interface.HasField("ipv4_config"):
104
+ config = interface.ipv4_config
105
+ ipv4 = IPv4Settings(
106
+ dhcp_enabled=config.dhcp_enabled,
107
+ address=format_ipv4(config.address),
108
+ subnet_mask=format_ipv4(config.subnet_mask),
109
+ gateway=format_ipv4(config.gateway),
110
+ dns=tuple(str(IPv4Address(dns)) for dns in config.dns if dns),
111
+ )
112
+ return cls(
113
+ enabled=interface.enabled,
114
+ active_route=interface.active_route,
115
+ connected_physical=status.connected_physical,
116
+ connected_internet=status.connected_internet,
117
+ connected_tesla=status.connected_tesla,
118
+ # A wrapper type: presence is explicit, so a real 0 % is kept.
119
+ signal_strength_percent=(
120
+ rssi.signal_strength_percent.value if rssi.HasField("signal_strength_percent") else None
121
+ ),
122
+ # A plain sint32 can't tell unset from 0, and 0 dBm is not a
123
+ # reading a radio reports: 0 means "not reported".
124
+ rssi=rssi.value or None,
125
+ snr=status.snr.value if status.HasField("snr") else None,
126
+ device_state=enum_name(pb.NetworkDeviceState, interface.device_state),
127
+ device_state_reason=enum_name(pb.NetworkDeviceStateReason, interface.device_state_reason),
128
+ mac_address=format_mac(interface.mac_address),
129
+ ipv4=ipv4,
130
+ )
131
+
132
+ def to_dict(self, details: bool = False) -> Dict[str, Any]:
133
+ data: Dict[str, Any] = {
134
+ "enabled": self.enabled,
135
+ "active_route": self.active_route,
136
+ "connected_physical": self.connected_physical,
137
+ "connected_internet": self.connected_internet,
138
+ "connected_tesla": self.connected_tesla,
139
+ "signal_strength_percent": self.signal_strength_percent,
140
+ "rssi": self.rssi,
141
+ "snr": self.snr,
142
+ "device_state": self.device_state,
143
+ "device_state_reason": self.device_state_reason,
144
+ }
145
+ if details:
146
+ data["mac_address"] = self.mac_address
147
+ data["ipv4"] = self.ipv4.to_dict() if self.ipv4 else None
148
+ return data
149
+
150
+
151
+ @dataclass(frozen=True)
152
+ class NetworkStatus:
153
+ """The gateway's networking status: one entry per interface (None when
154
+ the gateway left it out), and the configured Wi-Fi network's SSID and
155
+ security type (never its password)."""
156
+
157
+ wifi: Optional[NetworkInterfaceStatus] = None
158
+ eth: Optional[NetworkInterfaceStatus] = None
159
+ gsm: Optional[NetworkInterfaceStatus] = None
160
+ wifi_ssid: Optional[str] = field(default=None, repr=False)
161
+ wifi_security_type: Optional[str] = None
162
+
163
+ @classmethod
164
+ def from_proto(cls, response: pb.CommonAPIGetNetworkingStatusResponse) -> NetworkStatus:
165
+ has_config = response.HasField("wifi_config")
166
+ return cls(
167
+ wifi=NetworkInterfaceStatus.from_proto(response.wifi) if response.HasField("wifi") else None,
168
+ eth=NetworkInterfaceStatus.from_proto(response.eth) if response.HasField("eth") else None,
169
+ gsm=NetworkInterfaceStatus.from_proto(response.gsm) if response.HasField("gsm") else None,
170
+ wifi_ssid=(response.wifi_config.ssid or None) if has_config else None,
171
+ wifi_security_type=(
172
+ enum_name(pb.WifiNetworkSecurityType, response.wifi_config.security_type) if has_config else None
173
+ ),
174
+ )
175
+
176
+ @property
177
+ def interfaces(self) -> List[str]:
178
+ """Names of the interfaces the gateway reported."""
179
+ return [name for name in INTERFACES if getattr(self, name) is not None]
180
+
181
+ @property
182
+ def active(self) -> Optional[str]:
183
+ """The interface carrying the default route, if any."""
184
+ for name in INTERFACES:
185
+ interface: Optional[NetworkInterfaceStatus] = getattr(self, name)
186
+ if interface is not None and interface.active_route:
187
+ return name
188
+ return None
189
+
190
+ def to_dict(self, details: bool = False) -> Dict[str, Any]:
191
+ data: Dict[str, Any] = {}
192
+ for name in INTERFACES:
193
+ interface: Optional[NetworkInterfaceStatus] = getattr(self, name)
194
+ data[name] = None if interface is None else interface.to_dict(details=details)
195
+ if details:
196
+ data["wifi_config"] = (
197
+ None
198
+ if self.wifi_security_type is None
199
+ else {"ssid": self.wifi_ssid, "security_type": self.wifi_security_type}
200
+ )
201
+ return data
202
+
203
+
204
+ # ── Battery calibration delay ────────────────────────────────────────
205
+
206
+ MAX_UINT32 = 2**32 - 1
207
+
208
+
209
+ def validate_calibration_delay(delay_hours: int) -> None:
210
+ """Reject an invalid delay before any I/O. ``delay_hours`` is a uint32 on
211
+ the wire; the gateway's own limit is not documented."""
212
+ if type(delay_hours) is not int or not 1 <= delay_hours <= MAX_UINT32:
213
+ raise ValueError("delay_hours must be a positive integer")
214
+
215
+
216
+ @dataclass(frozen=True)
217
+ class CalibrationDelayStatus:
218
+ """The gateway's battery calibration delay counters, as reported."""
219
+
220
+ calibration_delays_left: int = 0
221
+ calibration_delay_remaining_seconds: int = 0
222
+ max_calibration_delays: int = 0
223
+
224
+ @classmethod
225
+ def from_proto(cls, response: pb.TEGAPIGetDelayBatteryCalibrationStatusResponse) -> CalibrationDelayStatus:
226
+ return cls(
227
+ calibration_delays_left=response.calibration_delays_left,
228
+ calibration_delay_remaining_seconds=response.calibration_delay_remaining_seconds,
229
+ max_calibration_delays=response.max_calibration_delays,
230
+ )
231
+
232
+ def to_dict(self) -> Dict[str, int]:
233
+ return {
234
+ "calibration_delays_left": self.calibration_delays_left,
235
+ "calibration_delay_remaining_seconds": self.calibration_delay_remaining_seconds,
236
+ "max_calibration_delays": self.max_calibration_delays,
237
+ }
238
+
239
+
240
+ # ── Site import / export limits ──────────────────────────────────────
241
+
242
+ IMPORT_LIMIT_KEY = "max_site_meter_power_ac"
243
+ EXPORT_LIMIT_KEY = "min_site_meter_power_ac"
244
+ #: The magnitude the gateway stores when the site has no limit (kW).
245
+ UNLIMITED_KW = 1000000000
246
+
247
+
248
+ def validate_site_limit(kilowatts: Optional[Number]) -> None:
249
+ """Reject an invalid limit before any I/O: a number of kilowatts from 0
250
+ up to (not including) the gateway's "no limit" value, or None for no
251
+ limit. NaN and infinity fail the range check."""
252
+ if kilowatts is None:
253
+ return
254
+ if isinstance(kilowatts, bool) or not isinstance(kilowatts, (int, float)) or not 0 <= kilowatts < UNLIMITED_KW:
255
+ raise ValueError("limit must be None or a number of kilowatts, 0 or more")
256
+
257
+
258
+ def _normalize(kilowatts: Number) -> Number:
259
+ """Whole numbers as int, the way the gateway stores them; never -0.0."""
260
+ return int(kilowatts) if float(kilowatts).is_integer() else float(kilowatts)
261
+
262
+
263
+ def import_limit_value(kilowatts: Optional[Number]) -> Number:
264
+ """The stored ``max_site_meter_power_ac`` for an import limit (None: no limit)."""
265
+ validate_site_limit(kilowatts)
266
+ return UNLIMITED_KW if kilowatts is None else _normalize(kilowatts)
267
+
268
+
269
+ def export_limit_value(kilowatts: Optional[Number]) -> Number:
270
+ """The stored ``min_site_meter_power_ac`` for an export limit (None: no
271
+ limit). The gateway stores it as a negative site meter power."""
272
+ validate_site_limit(kilowatts)
273
+ return -UNLIMITED_KW if kilowatts is None else -_normalize(kilowatts)
274
+
275
+
276
+ def _limit(value: Any, sign: int) -> Optional[Number]:
277
+ """A stored site meter power as a limit in kW: None when absent, not a
278
+ number, or at the "no limit" value. A value on the wrong side of zero
279
+ leaves no room in that direction, so it reads as 0."""
280
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or math.isnan(value):
281
+ return None
282
+ limit = sign * value
283
+ if limit >= UNLIMITED_KW:
284
+ return None
285
+ return _normalize(max(0, limit))
286
+
287
+
288
+ @dataclass(frozen=True)
289
+ class SiteLimits:
290
+ """The site import and export limits in kW, both positive. None means the
291
+ gateway reports no limit.
292
+
293
+ An installer may have set these to meet the site's grid connection
294
+ agreement (for example a network export limit)."""
295
+
296
+ import_limit_kw: Optional[Number] = None
297
+ export_limit_kw: Optional[Number] = None
298
+
299
+ @classmethod
300
+ def from_config(cls, config: Dict[str, Any]) -> SiteLimits:
301
+ site_info = config.get("site_info") if isinstance(config, dict) else None
302
+ if not isinstance(site_info, dict):
303
+ site_info = {}
304
+ return cls(
305
+ import_limit_kw=_limit(site_info.get(IMPORT_LIMIT_KEY), 1),
306
+ export_limit_kw=_limit(site_info.get(EXPORT_LIMIT_KEY), -1),
307
+ )
308
+
309
+ def to_dict(self) -> Dict[str, Optional[Number]]:
310
+ return {"import_limit_kw": self.import_limit_kw, "export_limit_kw": self.export_limit_kw}
311
+
312
+
313
+ # ── Authorized clients (registered keys) ─────────────────────────────
314
+
315
+
316
+ def _timestamp(value: Any) -> Optional[datetime]:
317
+ if not value.seconds and not value.nanos:
318
+ return None
319
+ return datetime.fromtimestamp(value.seconds + value.nanos / 1e9, tz=timezone.utc)
320
+
321
+
322
+ @dataclass(frozen=True)
323
+ class AuthorizedClient:
324
+ """One authorized client: a public key that may send signed commands.
325
+
326
+ ``state`` is ``VERIFIED``, ``PENDING_VERIFICATION``,
327
+ ``PENDING_VERIFICATION_TIMEOUT``, and so on. The description (often a
328
+ person's or device's name), identifier and key are kept out of ``repr``."""
329
+
330
+ fingerprint: str
331
+ type: str
332
+ key_type: str
333
+ roles: Tuple[str, ...]
334
+ state: str
335
+ verification: str
336
+ added_time: Optional[datetime]
337
+ authorized_by: Optional[str] # fingerprint of the key that vouched for it
338
+ public_key: bytes = field(repr=False)
339
+ description: str = field(default="", repr=False)
340
+ identifier: str = field(default="", repr=False)
341
+
342
+ @classmethod
343
+ def from_proto(cls, record: pb.AuthorizationRecord) -> AuthorizedClient:
344
+ return cls(
345
+ fingerprint=fingerprint(record.public_key),
346
+ type=enum_name(pb.AuthorizedClientType, record.type, "AUTHORIZED_CLIENT_TYPE_"),
347
+ key_type=enum_name(pb.AuthorizedKeyType, record.key_type, "AUTHORIZED_KEY_TYPE_"),
348
+ roles=tuple(enum_name(pb.AuthorizationRole, role, "AUTHORIZATION_ROLE_") for role in record.roles),
349
+ state=enum_name(pb.AuthorizedState, record.state, "AUTHORIZED_STATE_"),
350
+ verification=enum_name(pb.AuthorizedVerificationType, record.verification, "AUTHORIZED_VERIFICATION_TYPE_"),
351
+ added_time=_timestamp(record.added_time) if record.HasField("added_time") else None,
352
+ authorized_by=fingerprint(record.authorized_by_public_key) if record.authorized_by_public_key else None,
353
+ public_key=bytes(record.public_key),
354
+ description=record.description,
355
+ identifier=record.identifier,
356
+ )
357
+
358
+ def to_dict(self, details: bool = False, current_key: Optional[bytes] = None) -> Dict[str, Any]:
359
+ """JSON-safe dict. ``current_key`` (the key this connection signs
360
+ with) sets ``current_key``; ``details`` adds the description,
361
+ identifier and base64 public key."""
362
+ data: Dict[str, Any] = {
363
+ "fingerprint": self.fingerprint,
364
+ "type": self.type,
365
+ "key_type": self.key_type,
366
+ "roles": list(self.roles),
367
+ "state": self.state,
368
+ "verification": self.verification,
369
+ "added_time": self.added_time.isoformat() if self.added_time else None,
370
+ "authorized_by": self.authorized_by,
371
+ "current_key": None if current_key is None else self.public_key == current_key,
372
+ }
373
+ if details:
374
+ data["description"] = self.description or None
375
+ data["identifier"] = self.identifier or None
376
+ data["public_key"] = base64.b64encode(self.public_key).decode("ascii") if self.public_key else None
377
+ return data
378
+
379
+
380
+ @dataclass(frozen=True)
381
+ class AuthorizedClients:
382
+ """Every authorized client, in the gateway's order, and its
383
+ ``enable_line_switch_off`` flag (meaning not documented)."""
384
+
385
+ clients: Tuple[AuthorizedClient, ...] = ()
386
+ enable_line_switch_off: bool = False
387
+
388
+ @classmethod
389
+ def from_proto(cls, response: pb.AuthorizationAPIListAuthorizedClientsResponse) -> AuthorizedClients:
390
+ return cls(
391
+ clients=tuple(AuthorizedClient.from_proto(r) for r in response.clients),
392
+ enable_line_switch_off=response.enable_line_switch_off,
393
+ )
394
+
395
+ def find(self, prefix: str) -> List[AuthorizedClient]:
396
+ """Clients whose fingerprint starts with ``prefix`` (case-insensitive)."""
397
+ prefix = prefix.strip().lower()
398
+ return [client for client in self.clients if client.fingerprint.startswith(prefix)]
399
+
400
+ def to_dict(self, details: bool = False, current_key: Optional[bytes] = None) -> Dict[str, Any]:
401
+ return {
402
+ "clients": [client.to_dict(details=details, current_key=current_key) for client in self.clients],
403
+ "enable_line_switch_off": self.enable_line_switch_off,
404
+ }
aiopytedapi/py.typed ADDED
File without changes