generated from ludeeus/integration_blueprint
-
Notifications
You must be signed in to change notification settings - Fork 185
/
websocket.py
410 lines (359 loc) · 12.8 KB
/
websocket.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
"""Websocket API for Node-RED."""
import json
import logging
from typing import Any
from hassil.recognize import RecognizeResult
from homeassistant.components import device_automation
from homeassistant.components.conversation import (
HOME_ASSISTANT_AGENT,
_get_agent_manager,
)
from homeassistant.components.conversation.default_agent import DefaultAgent
from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.components.device_automation.exceptions import (
DeviceNotFound,
InvalidDeviceAutomationConfig,
)
from homeassistant.components.device_automation.trigger import TRIGGER_SCHEMA
from homeassistant.components.webhook import SUPPORTED_METHODS
from homeassistant.components.websocket_api import (
async_register_command,
async_response,
error_message,
event_message,
require_admin,
result_message,
websocket_command,
)
from homeassistant.components.websocket_api.connection import ActiveConnection
from homeassistant.const import (
CONF_DOMAIN,
CONF_ID,
CONF_NAME,
CONF_STATE,
CONF_TYPE,
CONF_WEBHOOK_ID,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import (
config_validation as cv,
device_registry as dr,
trigger,
)
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.entity_registry import async_entries_for_device, async_get
from homeassistant.helpers.typing import HomeAssistantType
import voluptuous as vol
from .const import (
CONF_ATTRIBUTES,
CONF_COMPONENT,
CONF_CONFIG,
CONF_DEVICE_INFO,
CONF_DEVICE_TRIGGER,
CONF_NODE_ID,
CONF_REMOVE,
CONF_SERVER_ID,
CONF_SUB_TYPE,
DOMAIN,
NODERED_CONFIG_UPDATE,
NODERED_DISCOVERY,
NODERED_ENTITY,
VERSION,
)
from .utils import NodeRedJSONEncoder
CONF_ALLOWED_METHODS = "allowed_methods"
CONF_LOCAL_ONLY = "local_only"
_LOGGER = logging.getLogger(__name__)
def register_websocket_handlers(hass: HomeAssistantType):
"""Register the websocket handlers."""
async_register_command(hass, websocket_device_action)
async_register_command(hass, websocket_device_remove)
async_register_command(hass, websocket_device_trigger)
async_register_command(hass, websocket_discovery)
async_register_command(hass, websocket_entity)
async_register_command(hass, websocket_config_update)
async_register_command(hass, websocket_version)
async_register_command(hass, websocket_webhook)
async_register_command(hass, websocket_sentence)
@require_admin
@websocket_command(
{
vol.Required(CONF_TYPE): "nodered/device/action",
vol.Required("action"): cv.DEVICE_ACTION_SCHEMA,
}
)
@async_response
async def websocket_device_action(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Sensor command."""
context = connection.context(msg)
platform = await device_automation.async_get_device_automation_platform(
hass, msg["action"][CONF_DOMAIN], DeviceAutomationType.ACTION
)
try:
await platform.async_call_action_from_config(hass, msg["action"], {}, context)
connection.send_message(result_message(msg[CONF_ID]))
except InvalidDeviceAutomationConfig as err:
connection.send_message(error_message(msg[CONF_ID], "invalid_config", str(err)))
except DeviceNotFound as err:
connection.send_message(
error_message(msg[CONF_ID], "device_not_found", str(err))
)
except Exception as err:
connection.send_message(error_message(msg[CONF_ID], "unknown_error", str(err)))
@require_admin
@websocket_command(
{
vol.Required(CONF_TYPE): "nodered/device/remove",
vol.Required(CONF_NODE_ID): cv.string,
vol.Optional(CONF_CONFIG, default={}): dict,
}
)
@async_response
async def websocket_device_remove(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Remove a device."""
device_registry = dr.async_get(hass)
device = device_registry.async_get_device({(DOMAIN, msg[CONF_NODE_ID])})
if device is not None:
entity_registry = async_get(hass)
entries = async_entries_for_device(entity_registry, device.id)
# Remove entities from device before removing device so the entities are not removed from HA
if entries:
for entry in entries:
entity_registry.async_update_entity(entry.entity_id, device_id=None)
device_registry.async_remove_device(device.id)
connection.send_message(result_message(msg[CONF_ID]))
@require_admin
@websocket_command(
{
vol.Required(CONF_TYPE): "nodered/discovery",
vol.Required(CONF_COMPONENT): cv.string,
vol.Required(CONF_SERVER_ID): cv.string,
vol.Required(CONF_NODE_ID): cv.string,
vol.Optional(CONF_CONFIG, default={}): dict,
vol.Optional(CONF_STATE): vol.Any(bool, str, int, float, None),
vol.Optional(CONF_ATTRIBUTES): dict,
vol.Optional(CONF_REMOVE): bool,
vol.Optional(CONF_DEVICE_INFO): dict,
vol.Optional(CONF_DEVICE_TRIGGER): TRIGGER_SCHEMA,
vol.Optional(CONF_SUB_TYPE): str,
}
)
def websocket_discovery(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Sensor command."""
async_dispatcher_send(
hass, NODERED_DISCOVERY.format(msg[CONF_COMPONENT]), msg, connection
)
connection.send_message(result_message(msg[CONF_ID]))
@require_admin
@websocket_command(
{
vol.Required(CONF_TYPE): "nodered/entity",
vol.Required(CONF_SERVER_ID): cv.string,
vol.Required(CONF_NODE_ID): cv.string,
vol.Required(CONF_STATE): vol.Any(bool, str, int, float, None),
vol.Optional(CONF_ATTRIBUTES, default={}): dict,
}
)
def websocket_entity(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Sensor command."""
async_dispatcher_send(
hass, NODERED_ENTITY.format(msg[CONF_SERVER_ID], msg[CONF_NODE_ID]), msg
)
connection.send_message(result_message(msg[CONF_ID]))
@require_admin
@websocket_command(
{
vol.Required(CONF_TYPE): "nodered/entity/update_config",
vol.Required(CONF_SERVER_ID): cv.string,
vol.Required(CONF_NODE_ID): cv.string,
vol.Optional(CONF_CONFIG, default={}): dict,
}
)
def websocket_config_update(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Sensor command."""
async_dispatcher_send(
hass, NODERED_CONFIG_UPDATE.format(msg[CONF_SERVER_ID], msg[CONF_NODE_ID]), msg
)
connection.send_message(result_message(msg[CONF_ID]))
@require_admin
@websocket_command({vol.Required(CONF_TYPE): "nodered/version"})
def websocket_version(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Version command."""
connection.send_message(result_message(msg[CONF_ID], VERSION))
@require_admin
@websocket_command(
{
vol.Required(CONF_TYPE): "nodered/webhook",
vol.Required(CONF_SERVER_ID): cv.string,
vol.Required(CONF_NAME): cv.string,
vol.Required(CONF_WEBHOOK_ID): cv.string,
vol.Optional(CONF_ALLOWED_METHODS): vol.All(
cv.ensure_list,
[vol.All(vol.Upper, vol.In(SUPPORTED_METHODS))],
vol.Unique(),
),
}
)
@async_response
async def websocket_webhook(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Create webhook command."""
webhook_id = msg[CONF_WEBHOOK_ID]
allowed_methods = msg.get(CONF_ALLOWED_METHODS)
@callback
async def handle_webhook(hass, id, request):
"""Handle webhook callback."""
body = await request.text()
try:
payload = json.loads(body) if body else {}
except ValueError:
payload = body
data = {
"payload": payload,
"headers": dict(request.headers),
"params": dict(request.query),
}
_LOGGER.debug(f"Webhook received {id[:15]}..: {data}")
connection.send_message(event_message(msg[CONF_ID], {"data": data}))
def remove_webhook() -> None:
"""Remove webhook command."""
try:
hass.components.webhook.async_unregister(webhook_id)
except ValueError:
pass
_LOGGER.info(f"Webhook removed: {webhook_id[:15]}..")
connection.send_message(result_message(msg[CONF_ID]))
try:
hass.components.webhook.async_register(
DOMAIN,
msg[CONF_NAME],
webhook_id,
handle_webhook,
allowed_methods=allowed_methods,
)
except ValueError as err:
connection.send_message(error_message(msg[CONF_ID], "value_error", str(err)))
return
except Exception as err:
connection.send_message(error_message(msg[CONF_ID], "unknown_error", str(err)))
return
_LOGGER.info(f"Webhook created: {webhook_id[:15]}..")
connection.subscriptions[msg[CONF_ID]] = remove_webhook
connection.send_message(result_message(msg[CONF_ID]))
@require_admin
@websocket_command(
{
vol.Required(CONF_TYPE): "nodered/sentence",
vol.Required(CONF_SERVER_ID): cv.string,
vol.Required("sentences", default=[]): [cv.string],
vol.Optional("response", default="Done"): cv.string,
}
)
@async_response
async def websocket_sentence(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Create sentence trigger."""
sentences = msg["sentences"]
response = msg["response"]
@callback
async def handle_trigger(sentence: str, result: RecognizeResult = None) -> str:
"""Handle Sentence trigger."""
"""RecognizeResult was added in 2023.8.0"""
_LOGGER.debug(f"Sentence trigger: {sentence}")
connection.send_message(
event_message(
msg[CONF_ID], {"data": {"sentence": sentence, "result": result}}
)
)
return response
def remove_trigger() -> None:
"""Remove sentence trigger."""
_remove_trigger()
_LOGGER.info(f"Sentence trigger removed: {sentences}")
try:
default_agent = await _get_agent_manager(hass).async_get_agent(
HOME_ASSISTANT_AGENT
)
assert isinstance(default_agent, DefaultAgent)
_remove_trigger = default_agent.register_trigger(sentences, handle_trigger)
except ValueError as err:
connection.send_message(error_message(msg[CONF_ID], "value_error", str(err)))
return
except Exception as err:
connection.send_message(error_message(msg[CONF_ID], "unknown_error", str(err)))
return
_LOGGER.info(f"Sentence trigger created: {sentences}")
connection.subscriptions[msg[CONF_ID]] = remove_trigger
connection.send_message(result_message(msg[CONF_ID]))
@require_admin
@websocket_command(
{
vol.Required(CONF_TYPE): "nodered/device/trigger",
vol.Required(CONF_NODE_ID): cv.string,
vol.Required(CONF_DEVICE_TRIGGER, default={}): dict,
}
)
@async_response
async def websocket_device_trigger(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Create device trigger."""
node_id = msg[CONF_NODE_ID]
trigger_data = msg[CONF_DEVICE_TRIGGER]
def forward_trigger(event, context=None):
"""Forward events to websocket."""
message = event_message(
msg[CONF_ID],
{"type": "device_trigger", "data": event["trigger"]},
)
connection.send_message(
json.dumps(message, cls=NodeRedJSONEncoder, allow_nan=False)
)
def unsubscribe() -> None:
"""Remove device trigger."""
remove_trigger()
_LOGGER.info(f"Device trigger removed: {node_id}")
try:
trigger_config = await trigger.async_validate_trigger_config(
hass, [trigger_data]
)
remove_trigger = await trigger.async_initialize_triggers(
hass,
trigger_config,
forward_trigger,
DOMAIN,
DOMAIN,
_LOGGER.log,
)
except vol.MultipleInvalid as err:
_LOGGER.error(
f"Error initializing device trigger '{node_id}': {str(err)}",
)
connection.send_message(
error_message(msg[CONF_ID], "invalid_trigger", str(err))
)
return
except Exception as err:
_LOGGER.error(
f"Error initializing device trigger '{node_id}': {str(err)}",
)
connection.send_message(error_message(msg[CONF_ID], "unknown_error", str(err)))
return
_LOGGER.info(f"Device trigger created: {node_id}")
_LOGGER.debug(f"Device trigger config for {node_id}: {trigger_data}")
connection.subscriptions[msg[CONF_ID]] = unsubscribe
connection.send_message(result_message(msg[CONF_ID]))