-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathremote.py
More file actions
592 lines (441 loc) · 16.5 KB
/
remote.py
File metadata and controls
592 lines (441 loc) · 16.5 KB
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
"""
Basic API to access remote instance of Home Assistant.
If a connection error occurs while communicating with the API a
HomeAssistantCliError will be raised.
"""
import asyncio
import collections
from datetime import datetime
import enum
import json
import logging
from typing import Any, Callable, Dict, List, Optional, cast
import urllib.parse
from urllib.parse import urlencode
import aiohttp
import requests
from homeassistant_cli.config import Configuration, resolve_server
from homeassistant_cli.exceptions import HomeAssistantCliError
import homeassistant_cli.hassconst as hass
_LOGGER = logging.getLogger(__name__)
# Copied from aiohttp.hdrs
CONTENT_TYPE = 'Content-Type'
METH_DELETE = 'DELETE'
METH_GET = 'GET'
METH_POST = 'POST'
class APIStatus(enum.Enum):
"""Representation of an API status."""
OK = "ok"
INVALID_PASSWORD = "invalid_password"
CANNOT_CONNECT = "cannot_connect"
UNKNOWN = "unknown"
def __str__(self) -> str:
"""Return the state."""
return self.value # type: ignore
def restapi(
ctx: Configuration, method: str, path: str, data: Optional[Dict] = None
) -> requests.Response:
"""Make a call to the Home Assistant REST API."""
if data is None:
data_str = None
else:
data_str = json.dumps(data, cls=JSONEncoder)
if not ctx.session:
ctx.session = requests.Session()
ctx.session.verify = not ctx.insecure
if ctx.cert:
ctx.session.cert = ctx.cert
_LOGGER.debug(
"Session: verify(%s), cert(%s)",
ctx.session.verify,
ctx.session.cert,
)
headers = {CONTENT_TYPE: hass.CONTENT_TYPE_JSON} # type: Dict[str, Any]
if ctx.token:
headers["Authorization"] = f"Bearer {ctx.token}"
if ctx.password:
headers["x-ha-access"] = ctx.password
url = urllib.parse.urljoin(resolve_server(ctx) + path, "")
try:
if method == METH_GET:
return requests.get(url, params=data_str, headers=headers)
return requests.request(method, url, data=data_str, headers=headers)
except requests.exceptions.ConnectionError:
raise HomeAssistantCliError(f"Error connecting to {url}")
except requests.exceptions.Timeout:
error = f"Timeout when talking to {url}"
_LOGGER.exception(error)
raise HomeAssistantCliError(error)
def wsapi(
ctx: Configuration,
frame: Dict,
callback: Optional[Callable[[Dict], Any]] = None,
) -> Optional[Dict]:
"""Make a call to Home Assistant using WS API.
if callback provided will keep listening and call
on every message.
If no callback return data returned.
"""
loop = asyncio.get_event_loop()
async def fetcher() -> Optional[Dict]:
async with aiohttp.ClientSession() as session:
async with session.ws_connect(
resolve_server(ctx) + "/api/websocket",
max_msg_size=16 * 1024 * 1024, # 16MB to handle large responses
) as wsconn:
await wsconn.send_str(
json.dumps({'type': 'auth', 'access_token': ctx.token})
)
frame['id'] = 1
await wsconn.send_str(json.dumps(frame))
while True:
msg = await wsconn.receive()
if msg.type == aiohttp.WSMsgType.ERROR:
break
elif msg.type == aiohttp.WSMsgType.CLOSED:
break
elif msg.type == aiohttp.WSMsgType.TEXT:
mydata = json.loads(msg.data) # type: Dict
if callback:
callback(mydata)
elif mydata['type'] == 'result':
return mydata
elif mydata['type'] == 'auth_invalid':
raise HomeAssistantCliError(mydata.get('message'))
return None
result = loop.run_until_complete(fetcher())
return result
class JSONEncoder(json.JSONEncoder):
"""JSONEncoder that supports Home Assistant objects."""
# pylint: disable=method-hidden
def default(self, o: Any) -> Any:
"""Convert Home Assistant objects.
Hand other objects to the original method.
"""
if isinstance(o, datetime):
return o.isoformat()
if isinstance(o, set):
return list(o)
if hasattr(o, "as_dict"):
return o.as_dict()
return json.JSONEncoder.default(self, o)
def get_areas(ctx: Configuration) -> List[Dict[str, Any]]:
"""Return all areas."""
frame = {'type': hass.WS_TYPE_AREA_REGISTRY_LIST}
areas = cast(Dict, wsapi(ctx, frame))[
'result'
] # type: List[Dict[str, Any]]
return areas
def find_area(ctx: Configuration, id_or_name: str) -> Optional[Dict[str, str]]:
"""Find area first by id and if no match by name."""
areas = get_areas(ctx)
area = next((x for x in areas if x['area_id'] == id_or_name), None)
if not area:
area = next((x for x in areas if x['name'] == id_or_name), None)
return area
def create_area(ctx: Configuration, name: str) -> Dict[str, Any]:
"""Create area."""
frame = {'type': hass.WS_TYPE_AREA_REGISTRY_CREATE, 'name': name}
return cast(Dict[str, Any], wsapi(ctx, frame))
def delete_area(ctx: Configuration, area_id: str) -> Dict[str, Any]:
"""Delete area."""
frame = {'type': hass.WS_TYPE_AREA_REGISTRY_DELETE, 'area_id': area_id}
return cast(Dict[str, Any], wsapi(ctx, frame))
def rename_area(
ctx: Configuration, area_id: str, new_name: str
) -> Dict[str, Any]:
"""Rename area."""
frame = {
'type': hass.WS_TYPE_AREA_REGISTRY_UPDATE,
'area_id': area_id,
'name': new_name,
}
return cast(Dict[str, Any], wsapi(ctx, frame))
def rename_entity(
ctx: Configuration,
entity_id: str,
new_id: Optional[str],
new_name: Optional[str],
) -> Dict[str, Any]:
"""Rename entity."""
frame = {
'type': hass.WS_TYPE_ENTITY_REGISTRY_UPDATE,
'entity_id': entity_id,
}
if new_name:
frame['name'] = new_name
if new_id:
frame['new_entity_id'] = new_id
return cast(Dict[str, Any], wsapi(ctx, frame))
def rename_device(
ctx: Configuration, device_id: str, new_name: str
) -> Dict[str, Any]:
"""Rename device."""
frame = {
'type': hass.WS_TYPE_DEVICE_REGISTRY_UPDATE,
'device_id': device_id,
'name_by_user': new_name,
}
return cast(Dict[str, Any], wsapi(ctx, frame))
def assign_area(
ctx: Configuration, device_id: str, area_id: str
) -> Dict[str, Any]:
"""Assign area."""
frame = {
'type': hass.WS_TYPE_DEVICE_REGISTRY_UPDATE,
'area_id': area_id,
'device_id': device_id,
}
return cast(Dict[str, Any], wsapi(ctx, frame))
def assign_entity_area(
ctx: Configuration, entity_id: str, area_id: str
) -> Dict[str, Any]:
"""Assign area to entity."""
frame = {
'type': hass.WS_TYPE_ENTITY_REGISTRY_UPDATE,
'area_id': area_id,
'entity_id': entity_id,
}
return cast(Dict[str, Any], wsapi(ctx, frame))
def get_health(ctx: Configuration) -> Dict[str, Any]:
"""Get system Health."""
frame = {'type': 'system_health/info'}
info = cast(Dict[str, Dict[str, Any]], wsapi(ctx, frame))['result']
return info
def get_devices(ctx: Configuration) -> List[Dict[str, Any]]:
"""Return all devices."""
frame = {'type': hass.WS_TYPE_DEVICE_REGISTRY_LIST}
devices = cast(Dict[str, List[Dict[str, Any]]], wsapi(ctx, frame))[
'result'
]
return devices
def get_entities(ctx: Configuration) -> List[Dict[str, Any]]:
"""Return all entities."""
frame = {'type': hass.WS_TYPE_ENTITY_REGISTRY_LIST}
devices = cast(Dict[str, List[Dict[str, Any]]], wsapi(ctx, frame))[
'result'
]
return devices
def get_entity(ctx: Configuration, entity_id: str) -> List[Dict[str, Any]]:
"""Return id."""
frame = {'type': hass.WS_TYPE_ENTITY_REGISTRY_GET, 'entity_id': entity_id}
result = cast(Dict[str, List[Dict[str, Any]]], wsapi(ctx, frame))
return result['id']
def validate_api(ctx: Configuration) -> APIStatus:
"""Make a call to validate API."""
try:
req = restapi(ctx, METH_GET, hass.URL_API)
if req.status_code == 200:
return APIStatus.OK
if req.status_code == 401:
return APIStatus.INVALID_PASSWORD
return APIStatus.UNKNOWN
except HomeAssistantCliError:
return APIStatus.CANNOT_CONNECT
def get_info(ctx: Configuration) -> Dict[str, Any]:
"""Get basic info about the Home Assistant instance."""
try:
req = restapi(ctx, METH_GET, hass.URL_API_DISCOVERY_INFO)
req.raise_for_status()
return (
cast(Dict[str, Any], req.json()) if req.status_code == 200 else {}
)
except (HomeAssistantCliError, ValueError):
raise HomeAssistantCliError("Unexpected error retrieving information")
# ValueError if req.json() can't parse the json
def get_events(ctx: Configuration) -> Dict[str, Any]:
"""Return all events."""
try:
req = restapi(ctx, METH_GET, hass.URL_API_EVENTS)
except HomeAssistantCliError as ex:
raise HomeAssistantCliError(f"Unexpected error getting events: {ex}")
if req.status_code == 200:
return cast(Dict[str, Any], req.json())
raise HomeAssistantCliError(f"Error while getting all events: {req.text}")
def get_history(
ctx: Configuration,
entities: Optional[List] = None,
start_time: Optional[datetime] = None,
end_time: Optional[datetime] = None,
) -> List[Dict[str, Any]]:
"""Return History."""
try:
if start_time:
method = hass.URL_API_HISTORY_PERIOD.format(start_time.isoformat())
else:
method = hass.URL_API_HISTORY
params = collections.OrderedDict() # type: Dict[str, str]
if entities:
params["filter_entity_id"] = ",".join(entities)
if end_time:
params["end_time"] = end_time.isoformat()
if params:
method = f"{method}?{urlencode(params)}"
req = restapi(ctx, METH_GET, method)
except HomeAssistantCliError as ex:
raise HomeAssistantCliError(f"Unexpected error getting history: {ex}")
if req.status_code == 200:
return cast(List[Dict[str, Any]], req.json())
raise HomeAssistantCliError(f"Error while getting all events: {req.text}")
def get_states(ctx: Configuration) -> List[Dict[str, Any]]:
"""Return all states."""
try:
req = restapi(ctx, METH_GET, hass.URL_API_STATES)
except HomeAssistantCliError as ex:
raise HomeAssistantCliError(f"Unexpected error getting state: {ex}")
if req.status_code == 200:
data = req.json() # type: List[Dict[str, Any]]
return data
raise HomeAssistantCliError(f"Error while getting all states: {req.text}")
def get_raw_error_log(ctx: Configuration) -> str:
"""Return the error log."""
try:
req = restapi(ctx, METH_GET, hass.URL_API_ERROR_LOG)
req.raise_for_status()
except HomeAssistantCliError as ex:
raise HomeAssistantCliError(
f"Unexpected error getting error log: {ex}"
)
return req.text
def get_config(ctx: Configuration) -> Dict[str, Any]:
"""Return the running configuration."""
try:
req = restapi(ctx, METH_GET, hass.URL_API_CONFIG)
except HomeAssistantCliError as ex:
raise HomeAssistantCliError(
f"Unexpected error getting configuration: {ex}"
)
if req.status_code == 200:
return cast(Dict[str, str], req.json())
raise HomeAssistantCliError(
f"Error while getting all configuration: {req.text}"
)
def get_state(ctx: Configuration, entity_id: str) -> Optional[Dict[str, Any]]:
"""Get entity state. If ok, return dictionary with state.
If no entity found return None - otherwise excepton raised
with details.
"""
try:
req = restapi(
ctx, METH_GET, hass.URL_API_STATES_ENTITY.format(entity_id)
)
except HomeAssistantCliError as ex:
raise HomeAssistantCliError(f"Unexpected error getting state: {ex}")
if req.status_code == 200:
return cast(Dict[str, Any], req.json())
if req.status_code == 404:
return None
raise HomeAssistantCliError(
f"Error while getting Entity {entity_id}: {req.text}"
)
def remove_state(ctx: Configuration, entity_id: str) -> bool:
"""Call API to remove state for entity_id.
If success return True, if could not find the entity return False.
Otherwise raise exception with details.
"""
try:
req = restapi(
ctx, METH_DELETE, hass.URL_API_STATES_ENTITY.format(entity_id)
)
if req.status_code == 200:
return True
if req.status_code == 404:
return False
except HomeAssistantCliError:
raise HomeAssistantCliError("Unexpected error removing state")
raise HomeAssistantCliError(
f"Error removing state: {req.status_code} - {req.text}"
)
def set_state(
ctx: Configuration, entity_id: str, data: Dict
) -> Dict[str, Any]:
"""Set/update state for entity id."""
try:
req = restapi(
ctx, METH_POST, hass.URL_API_STATES_ENTITY.format(entity_id), data
)
except HomeAssistantCliError as exception:
raise HomeAssistantCliError(
"Error updating state for entity {}: {}".format(
entity_id, exception
)
)
if req.status_code not in (200, 201):
raise HomeAssistantCliError(
"Error changing state for entity {}: {} - {}".format(
entity_id, req.status_code, req.text
)
)
return cast(Dict[str, Any], req.json())
def render_template(ctx: Configuration, template: str, variables: Dict) -> str:
"""Render template."""
data = {"template": template, "variables": variables}
try:
req = restapi(ctx, METH_POST, hass.URL_API_TEMPLATE, data)
except HomeAssistantCliError as exception:
raise HomeAssistantCliError(f"Error applying template: {exception}")
if req.status_code not in (200, 201):
raise HomeAssistantCliError(
"Error applying template: {} - {}".format(
req.status_code, req.text
)
)
return req.text
def get_event_listeners(ctx: Configuration) -> Dict:
"""List of events that is being listened for."""
try:
req = restapi(ctx, METH_GET, hass.URL_API_EVENTS)
return req.json() if req.status_code == 200 else {} # type: ignore
except (HomeAssistantCliError, ValueError):
# ValueError if req.json() can't parse the json
_LOGGER.exception("Unexpected result retrieving event listeners")
return {}
def fire_event(
ctx: Configuration, event_type: str, data: Optional[Dict[str, Any]] = None
) -> Optional[Dict[str, Any]]:
"""Fire an event at remote API."""
try:
req = restapi(
ctx, METH_POST, hass.URL_API_EVENTS_EVENT.format(event_type), data
)
if req.status_code != 200:
_LOGGER.error(
"Error firing event: %d - %s", req.status_code, req.text
)
return cast(Dict[str, Any], req.json())
except HomeAssistantCliError as exception:
raise HomeAssistantCliError(f"Error firing event: {exception}")
def call_service(
ctx: Configuration,
domain: str,
service: str,
service_data: Optional[Dict] = None,
) -> List[Dict[str, Any]]:
"""Call a service."""
try:
req = restapi(
ctx,
METH_POST,
hass.URL_API_SERVICES_SERVICE.format(domain, service),
service_data,
)
except HomeAssistantCliError as ex:
raise HomeAssistantCliError(f"Error calling service: {ex}")
if req.status_code != 200:
raise HomeAssistantCliError(
f"Error calling service: {req.status_code} - {req.text}"
)
return cast(List[Dict[str, Any]], req.json())
def get_services(
ctx: Configuration,
) -> List[Dict[str, Any]]:
"""Get list of services."""
try:
req = restapi(ctx, METH_GET, hass.URL_API_SERVICES)
except HomeAssistantCliError as ex:
raise HomeAssistantCliError(f"Unexpected error getting services: {ex}")
if req.status_code == 200:
return cast(List[Dict[str, Any]], req.json())
raise HomeAssistantCliError(
f"Error while getting all services: {req.text}"
)