/
rpc_device.py
225 lines (176 loc) · 6.53 KB
/
rpc_device.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
"""Shelly Gen2 RPC based device."""
from __future__ import annotations
import asyncio
from typing import Any, Callable, cast
import aiohttp
from aiohttp.client import ClientSession
from .common import ConnectionOptions, IpOrOptionsType, get_info, process_ip_or_options
from .exceptions import AuthRequired, NotInitialized, WrongShellyGen
from .wsrpc import WsRPC
def mergedicts(dict1: dict, dict2: dict) -> dict:
"""Deep dicts merge."""
result = dict(dict1)
result.update(dict2)
for key, value in result.items():
if isinstance(value, dict) and isinstance(dict1.get(key), dict):
result[key] = mergedicts(dict1[key], value)
return result
class RpcDevice:
"""Shelly RPC device reppresentation."""
def __init__(
self,
aiohttp_session: aiohttp.ClientSession,
options: ConnectionOptions,
):
"""Device init."""
self.aiohttp_session: ClientSession = aiohttp_session
self.options: ConnectionOptions = options
self.shelly: dict[str, Any] | None = None
self._status: dict[str, Any] | None = None
self._event: dict[str, Any] | None = None
self._device_info: dict[str, Any] | None = None
self._config: dict[str, Any] | None = None
self._wsrpc = WsRPC(options.ip_address, self._on_notification)
self._update_listener: Callable | None = None
self.initialized: bool = False
self._initializing: bool = False
@classmethod
async def create(
cls,
aiohttp_session: aiohttp.ClientSession,
ip_or_options: IpOrOptionsType,
initialize: bool = True,
) -> RpcDevice:
"""Device creation."""
options = await process_ip_or_options(ip_or_options)
instance = cls(aiohttp_session, options)
if initialize:
await instance.initialize()
return instance
def _on_notification(
self, method: str, params: dict[str, Any] | None = None
) -> None:
if params is not None:
if method == "NotifyStatus":
if self._status is None:
return
self._status = dict(mergedicts(self._status, params))
elif method == "NotifyEvent":
self._event = params
if self._update_listener:
self._update_listener(self)
@property
def ip_address(self) -> str:
"""Device ip address."""
return self.options.ip_address
async def initialize(self) -> None:
"""Device initialization."""
if self._initializing:
raise RuntimeError("Already initializing")
self._initializing = True
self.initialized = False
try:
self.shelly = await get_info(self.aiohttp_session, self.options.ip_address)
if self.options.auth or not self.requires_auth:
await self._wsrpc.connect(self.aiohttp_session)
await asyncio.gather(
self.update_device_info(),
self.update_config(),
self.update_status(),
)
self.initialized = True
finally:
self._initializing = False
if self._update_listener:
self._update_listener(self)
async def shutdown(self) -> None:
"""Shutdown device."""
self._update_listener = None
await self._wsrpc.disconnect()
def subscribe_updates(self, update_listener: Callable) -> None:
"""Subscribe to device status updates."""
self._update_listener = update_listener
async def trigger_ota_update(self, beta: bool = False) -> None:
"""Trigger an ota update."""
params = {"stage": "beta"} if beta else {"stage": "stable"}
await self._wsrpc.call("Shelly.Update", params)
async def trigger_reboot(self) -> None:
"""Trigger a device reboot."""
await self._wsrpc.call("Shelly.Reboot")
async def update_status(self) -> None:
"""Get device status from 'Shelly.GetStatus'."""
self._status = await self._wsrpc.call("Shelly.GetStatus")
async def update_device_info(self) -> None:
"""Get device info from 'Shelly.GetDeviceInfo'."""
self._device_info = await self._wsrpc.call("Shelly.GetDeviceInfo")
async def update_config(self) -> None:
"""Get device config from 'Shelly.GetConfig'."""
self._config = await self._wsrpc.call("Shelly.GetConfig")
@property
def requires_auth(self) -> bool:
"""Device check for authentication."""
assert self.shelly
if "auth_en" not in self.shelly:
raise WrongShellyGen
return bool(self.shelly["auth_en"])
async def call_rpc(
self, method: str, params: dict[str, Any] | None
) -> dict[str, Any]:
"""Call RPC method."""
return await self._wsrpc.call(method, params)
@property
def status(self) -> dict[str, Any]:
"""Get device status."""
if not self.initialized:
raise NotInitialized
if self._status is None:
raise AuthRequired
return self._status
@property
def event(self) -> dict[str, Any] | None:
"""Get device event."""
if not self.initialized:
raise NotInitialized
return self._event
@property
def device_info(self) -> dict[str, Any]:
"""Get device info."""
if not self.initialized:
raise NotInitialized
if self._device_info is None:
raise AuthRequired
return self._device_info
@property
def config(self) -> dict[str, Any]:
"""Get device config."""
if not self.initialized:
raise NotInitialized
if self._config is None:
raise AuthRequired
return self._config
@property
def gen(self) -> int:
"""Device generation: GEN2 - RPC."""
return 2
@property
def firmware_version(self) -> str:
"""Device firmware version."""
assert self.shelly
if not self.initialized:
raise NotInitialized
return cast(str, self.shelly["fw_id"])
@property
def model(self) -> str:
"""Device model."""
assert self.shelly
if not self.initialized:
raise NotInitialized
return cast(str, self.shelly["model"])
@property
def hostname(self) -> str:
"""Device hostname."""
return cast(str, self.device_info["id"])
@property
def connected(self) -> bool:
"""Return true if device is connected."""
return self._wsrpc.connected