-
Notifications
You must be signed in to change notification settings - Fork 429
Expand file tree
/
Copy pathhassapi.py
More file actions
1849 lines (1546 loc) · 81.3 KB
/
hassapi.py
File metadata and controls
1849 lines (1546 loc) · 81.3 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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import re
from ast import literal_eval
from collections.abc import Iterable
from copy import deepcopy
from datetime import datetime, timedelta
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Literal, Type, overload
from appdaemon import exceptions as ade
from appdaemon import utils
from appdaemon.adapi import ADAPI
from appdaemon.adbase import ADBase
from appdaemon.appdaemon import AppDaemon
from appdaemon.models.notification.android import AndroidData
from appdaemon.models.notification.base import NotificationData
from appdaemon.models.notification.iOS import iOSData
from appdaemon.plugins.hass.exceptions import ScriptNotFound
from appdaemon.plugins.hass.hassplugin import HassPlugin
from appdaemon.plugins.hass.notifications import AndroidNotification
from appdaemon.services import ServiceCallback
# Check if the module is being imported using the legacy method
if __name__ == Path(__file__).name:
from appdaemon.logging import Logging
# It's possible to instantiate the Logging system again here because it's a singleton, and it will already have been
# created at this point if the legacy import method is being used by an app. Using this accounts for the user maybe
# having configured the error logger to use a different name than 'Error'
Logging().get_error().warning(
"Importing 'hassapi' directly is deprecated and will be removed in a future version. "
"To use the Hass plugin use 'from appdaemon.plugins.hass import Hass' instead.",
)
if TYPE_CHECKING:
from ...models.config.app import AppConfig
class Hass(ADBase, ADAPI):
"""HASS API class for the users to inherit from.
This class provides an interface to the HassPlugin object that connects to Home Assistant.
"""
_plugin: HassPlugin
def __init__(self, ad: AppDaemon, config_model: "AppConfig"):
# Call Super Classes
ADBase.__init__(self, ad, config_model)
ADAPI.__init__(self, ad, config_model)
#
# Register specific constraints
#
self.register_constraint("constrain_presence")
self.register_constraint("constrain_person")
self.register_constraint("constrain_input_boolean")
self.register_constraint("constrain_input_select")
@utils.sync_decorator
async def ping(self) -> float | None:
"""Gets the number of seconds """
if (plugin := self._plugin) is not None:
match await plugin.ping():
case {"ad_status": "OK", "ad_duration": ad_duration}:
return ad_duration
case _:
return None
@utils.sync_decorator
async def call_ws(self, namespace: str | None = None, **message) -> dict:
"""Sends an arbitrary WebSocket message to Home Assistant and returns the full response.
This is a low-level escape hatch for accessing any Home Assistant WebSocket API command,
including those that do not have a dedicated helper method in AppDaemon.
The ``type`` key is required in the message.
The ``id`` key must **not** be included — it is assigned automatically by the plugin.
Args:
namespace (str, optional): Namespace to use for the call. See the section on
`namespaces <APPGUIDE.html#namespaces>`__ for a detailed description.
In most cases it is safe to ignore this parameter.
**message: Keyword arguments that form the JSON body of the WebSocket message.
Returns:
dict: The full response dictionary from Home Assistant, containing keys such as
``success``, ``result``, and ``error``.
Examples:
Get a list of all registered panels:
>>> result = self.call_ws(type="get_panels")
Subscribe to an event type:
>>> result = self.call_ws(type="subscribe_events", event_type="state_changed")
Call a service via raw WebSocket:
>>> result = self.call_ws(
... type="call_service",
... domain="light",
... service="turn_on",
... target={"entity_id": "light.living_room"},
... )
"""
if 'type' not in message:
self.logger.warning("call_ws: 'type' key is required in the message")
return {"error": "'type' key is required"}
if 'id' in message:
self.logger.warning("call_ws: 'id' key must not be included — it is assigned automatically")
return {"error": "'id' key must not be included"}
namespace = namespace if namespace is not None else self.namespace
match self.AD.plugins.get_plugin_object(namespace):
case HassPlugin() as plugin:
return await plugin.websocket_send_json(**message)
case _:
self.logger.warning("call_ws: namespace '%s' is not a Home Assistant namespace", namespace)
return {"error": f"namespace '{namespace}' is not a Home Assistant namespace"}
@utils.sync_decorator
async def check_for_entity(self, entity_id: str, namespace: str | None = None) -> bool:
"""Uses the REST API to check if an entity exists instead of checking AppDaemon's internal state.
Args:
entity_id (str): Fully qualified id.
namespace (str, optional): Namespace to use for the call. See the section on
`namespaces <APPGUIDE.html#namespaces>`__ for a detailed description.
In most cases it is safe to ignore this parameter.
Returns:
Bool of whether the entity exists.
"""
namespace = namespace if namespace is not None else self.namespace
match self.AD.plugins.get_plugin_object(namespace):
case HassPlugin() as plugin:
match await plugin.check_for_entity(entity_id):
case dict():
return True
return False
#
# Internal Helpers
# Methods that other methods
async def _entity_service_call(self, service: str, entity_id: str, namespace: str | None = None, **kwargs):
"""Wraps up a common pattern in methods that use a service call with an entity_id
Namespace defaults to that of the plugin
Displays a warning if the entity doesn't exist in the namespace.
"""
namespace = namespace or self.namespace
self._check_entity(namespace, entity_id)
return await self.call_service(
service=service,
namespace=namespace,
entity_id=entity_id,
**kwargs
)
async def _domain_service_call(
self,
service: str,
entity_id: str | Iterable[str],
namespace: str | None = None,
**kwargs
):
"""Wraps up a common pattern in methods that have to use a certain domain.
- Namespace defaults to that of the plugin.
- Asserts that the entity is in the right domain.
- Displays a warning if the entity doesn't exist in the namespace.
"""
namespace = namespace if namespace is not None else self.namespace
service_domain = service.split('/')[0]
def _check(entity_ids: Iterable[str]) -> None:
for eid in entity_ids:
entity_domain = eid.split('.')[0]
# This check needs to work for domains like "number" and "input_number"
assert entity_domain in service_domain, (
f"Entity domain '{entity_domain}' does not match service domain '{service_domain}'"
)
self._check_entity(namespace, eid)
match entity_id:
case str():
_check([entity_id])
case list(entity_ids):
_check(entity_ids)
case Iterable() as entity_ids:
entity_id = entity_ids if isinstance(entity_ids, list) else list(entity_ids)
_check(entity_id)
case _:
raise TypeError('entity_id must be a string or an iterable of strings')
return await self.call_service(
service=service,
namespace=namespace,
entity_id=entity_id,
**kwargs
)
async def _create_helper(
self,
friendly_name: str,
initial_val: Any,
type: str,
entity_id: str = None,
namespace: str | None = None
) -> dict:
"""Creates a new input number entity by using ``set_state`` on a non-existent one with the right format
Entities created this way do not persist after Home Assistant restarts.
"""
assert type.startswith('input')
if entity_id is None:
cleaned_name = friendly_name.lower().replace(' ', '_').replace('-', '_')
entity_id = f'{type}.{cleaned_name}'
assert entity_id.startswith(f'{type}.')
if not (await self.entity_exists(entity_id, namespace)):
return await self.set_state(
entity_id=entity_id,
state=initial_val,
friendly_name=friendly_name,
namespace=namespace,
check_existence=False,
)
else:
self.log(f'Entity already exists: {friendly_name}')
return self.get_state(entity_id, 'all')
#
# Device Trackers
# Methods relating to entities in the person and device_tracker domains
def get_tracker_details(self, person: bool = True, namespace: str | None = None, copy: bool = True) -> dict[str, Any]:
"""Returns a list of all device tracker and the associated states.
Args:
person (boolean, optional): If set to True, use person rather than device_tracker
as the device type to query
namespace (str, optional): Namespace to use for the call. See the section on
`namespaces <APPGUIDE.html#namespaces>`__ for a detailed description.
In most cases it is safe to ignore this parameter.
copy (bool, optional): Whether to return a copy of the state dictionary. This is usually
the desired behavior because it prevents accidental modification of the internal AD
data structures. Defaults to True.
Examples:
>>> trackers = self.get_tracker_details()
>>> for tracker in trackers:
>>> do something
"""
device = "person" if person else "device_tracker"
return self.get_state(device, namespace=namespace, copy=copy)
def get_trackers(self, person: bool = True, namespace: str | None = None) -> list[str]:
"""Returns a list of all device tracker names.
Args:
person (boolean, optional): If set to True, use person rather than device_tracker
as the device type to query
namespace (str, optional): Namespace to use for the call. See the section on
`namespaces <APPGUIDE.html#namespaces>`__ for a detailed description.
In most cases it is safe to ignore this parameter.
Examples:
>>> trackers = self.get_trackers()
>>> for tracker in trackers:
>>> do something
>>> people = self.get_trackers(person=True)
>>> for person in people:
>>> do something
"""
return list(self.get_tracker_details(person, namespace, copy=False).keys())
@overload
def get_tracker_state(
self,
entity_id: str,
attribute: str | None = None,
default: Any | None = None,
namespace: str | None = None,
copy: bool = True,
) -> str: ...
def get_tracker_state(self, *args, **kwargs) -> str:
"""Gets the state of a tracker.
Args:
entity_id (str): Fully qualified entity id of the device tracker or person to query, e.g.,
``device_tracker.andrew`` or ``person.andrew``.
attribute (str, optional): Name of the attribute to return
default (Any, optional): Default value to return when the attribute isn't found
namespace (str, optional): Namespace to use for the call. See the section on
`namespaces <APPGUIDE.html#namespaces>`__ for a detailed description.
In most cases it is safe to ignore this parameter.
copy (bool, optional): Whether to return a copy of the state dictionary. This is usually
the desired behavior because it prevents accidental modification of the internal AD
data structures. Defaults to True.
Returns:
The values returned depend in part on the
configuration and type of device trackers in the system. Simpler tracker
types like ``Locative`` or ``NMAP`` will return one of 2 states:
- ``home``
- ``not_home``
Some types of device tracker are in addition able to supply locations
that have been configured as Geofences, in which case the name of that
location can be returned.
Examples:
>>> state = self.get_tracker_state("device_tracker.andrew")
>>> self.log(f"state is {state}")
>>> state = self.get_tracker_state("person.andrew")
>>> self.log(f"state is {state}")
"""
return self.get_state(*args, **kwargs)
@utils.sync_decorator
async def anyone_home(self, person: bool = True, namespace: str | None = None) -> bool:
"""Determines if the house/apartment is occupied.
A convenience function to determine if one or more person is home. Use
this in preference to getting the state of ``group.all_devices()`` as it
avoids a race condition when using state change callbacks for device
trackers.
Args:
person (boolean, optional): If set to True, use person rather than device_tracker
as the device type to query
namespace (str, optional): Namespace to use for the call. See the section on
`namespaces <APPGUIDE.html#namespaces>`__ for a detailed description.
In most cases it is safe to ignore this parameter.
Returns:
Returns ``True`` if anyone is at home, ``False`` otherwise.
Examples:
>>> if self.anyone_home():
>>> do something
>>> if self.anyone_home(person=True):
>>> do something
"""
details = await self.get_tracker_details(person, namespace, copy=False)
return any(state['state'] == 'home' for state in details.values())
@utils.sync_decorator
async def everyone_home(self, person: bool = True, namespace: str | None = None) -> bool:
"""Determine if all family's members at home.
A convenience function to determine if everyone is home. Use this in
preference to getting the state of ``group.all_devices()`` as it avoids
a race condition when using state change callbacks for device trackers.
Args:
person (boolean, optional): If set to True, use person rather than device_tracker
as the device type to query
namespace (str, optional): Namespace to use for the call. See the section on
`namespaces <APPGUIDE.html#namespaces>`__ for a detailed description.
In most cases it is safe to ignore this parameter.
Returns:
Returns ``True`` if everyone is at home, ``False`` otherwise.
Examples:
>>> if self.everyone_home():
>>> do something
>>> if self.everyone_home(person=True):
>>> do something
"""
details = await self.get_tracker_details(person, namespace, copy=False)
return all(state['state'] == 'home' for state in details.values())
@utils.sync_decorator
async def noone_home(self, person: bool = True, namespace: str | None = None) -> bool:
"""Determines if the house/apartment is empty.
A convenience function to determine if no people are at home. Use this
in preference to getting the state of ``group.all_devices()`` as it avoids
a race condition when using state change callbacks for device trackers.
Args:
person (boolean, optional): If set to True, use person rather than device_tracker
as the device type to query
namespace (str, optional): Namespace to use for the call. See the section on
`namespaces <APPGUIDE.html#namespaces>`__ for a detailed description.
In most cases it is safe to ignore this parameter.
**kwargs (optional): Zero or more keyword arguments.
Returns:
Returns ``True`` if no one is home, ``False`` otherwise.
Examples:
>>> if self.noone_home():
>>> do something
>>> if self.noone_home(person=True):
>>> do something
"""
return not await self.anyone_home(person, namespace)
#
# Built-in constraints
#
def constrain_presence(self, value: Literal["everyone", "anyone", "noone"] | None = None) -> bool:
"""Returns True if unconstrained"""
match value:
case None:
return True
case str(value_str):
match value_str.strip().lower():
case "everyone":
return self.everyone_home()
case "anyone":
return self.anyone_home()
case "noone":
return self.noone_home()
raise ValueError(f'Invalid presence constraint: {value}')
def constrain_person(self, value: Literal["everyone", "anyone", "noone"] | None = None) -> bool:
"""Returns True if unconstrained"""
match value:
case None:
return True
case str(value_str):
match value_str.strip().lower():
case "everyone":
return self.everyone_home(person=True)
case "anyone":
return self.anyone_home(person=True)
case "noone":
return self.noone_home(person=True)
raise ValueError(f'Invalid presence constraint: {value}')
def constrain_input_boolean(self, value: str | Iterable[str]) -> bool:
"""Returns True if unconstrained - all input_booleans match the desired
state. Desired state defaults to ``on``
"""
match value:
case str():
constraints = [value]
case Iterable():
constraints = value if isinstance(value, list) else list(value)
assert isinstance(constraints, list) and all(isinstance(v, str) for v in constraints)
for constraint in constraints:
parts = re.split(r',\s*', constraint)
match len(parts):
case 2:
entity, desired_state = parts
case 1:
entity = constraint
desired_state = "on"
if self.get_state(entity, copy=False) != desired_state.strip():
return False
return True
def constrain_input_select(self, value: str | Iterable[str]) -> bool:
"""Returns True if unconstrained - all inputs match a desired state."""
match value:
case str():
constraints = [value]
case Iterable():
constraints = value if isinstance(value, list) else list(value)
assert isinstance(constraints, list) and all(isinstance(v, str) for v in constraints)
for constraint in constraints:
# using re.split allows for an arbitrary amount of whitespace after the comma
parts = re.split(r',\s*', constraint)
entity = parts[0]
desired_states = parts[1:]
if self.get_state(entity, copy=False) not in desired_states:
return False
return True
#
# Helper functions for services
#
@overload
@utils.sync_decorator
async def call_service(
self,
service: str,
namespace: str | None = None,
timeout: str | int | float | None = None,
callback: ServiceCallback | None = None,
hass_timeout: str | int | float | None = None,
suppress_log_messages: bool = False,
return_response: bool | None = None,
**data,
) -> Any: ...
@utils.sync_decorator
async def call_service(
self,
service: str,
namespace: str | None = None,
timeout: str | int | float | None = None, # used by the sync_decorator
callback: Callable[[Any], Any] | None = None,
**kwargs,
) -> Any:
"""Calls a Service within AppDaemon.
Services represent specific actions, and are generally registered by plugins or provided by AppDaemon itself.
The app calls the service only by referencing the service with a string in the format ``<domain>/<service>``, so
there is no direct coupling between apps and services. This allows any app to call any service, even ones from
other plugins.
Services often require additional parameters, such as ``entity_id``, which AppDaemon will pass to the service
call as appropriate, if used when calling this function. This allows arbitrary data to be passed to the service
calls.
Apps can also register their own services using their ``self.regsiter_service`` method.
Args:
service (str): The service name in the format `<domain>/<service>`. For example, `light/turn_on`.
namespace (str, optional): It's safe to ignore this parameter in most cases because the default namespace
will be used. However, if a `namespace` is provided, the service call will be made in that namespace. If
there's a plugin associated with that namespace, it will do the service call. If no namespace is given,
AppDaemon will use the app's namespace, which can be set using the ``self.set_namespace`` method. See
the section on `namespaces <APPGUIDE.html#namespaces>`__ for more information.
timeout (str | int | float, optional): The internal AppDaemon timeout for the service call. If no value is
specified, the default timeout is 60s. The default value can be changed using the
``appdaemon.internal_function_timeout`` config setting.
callback (callable): The non-async callback to be executed when complete. It should accept a single
argument, which will be the result of the service call. This is the recommended method for calling
services which might take a long time to complete. This effectively bypasses the ``timeout`` argument
because it only applies to this function, which will return immediately instead of waiting for the
result if a `callback` is specified.
hass_timeout (str | int | float, optional): Only applicable to the Hass plugin. Sets the amount of time to
wait for a response from Home Assistant. If no value is specified, the default timeout is 10s. The
default value can be changed using the ``ws_timeout`` setting the in the Hass plugin configuration in
``appdaemon.yaml``. Even if no data is returned from the service call, Home Assistant will still send an
acknowledgement back to AppDaemon, which this timeout applies to. Note that this is separate from the
``timeout``. If ``timeout`` is shorter than this one, it will trigger before this one does.
suppress_log_messages (bool, optional): Only applicable to the Hass plugin. If this is set to ``True``,
Appdaemon will suppress logging of warnings for service calls to Home Assistant, specifically timeouts
and non OK statuses. Use this flag and set it to ``True`` to suppress these log messages if you are
performing your own error checking as described `here <APPGUIDE.html#some-notes-on-service-calls>`__
return_response (bool, optional): Indicates whether Home Assistant should return a response to the service
call. This is only supported for some services and Home Assistant will return an error if used with a
service that doesn't support it. If returning a response is required or optional (based on the service
definitions given by Home Assistant), this will automatically be set to ``True``.
service_data (dict, optional): Used as an additional dictionary to pass arguments into the ``service_data``
field of the JSON that goes to Home Assistant. This is useful if you have a dictionary that you want to
pass in that has a key like ``target`` which is otherwise used for the ``target`` argument.
**data: Any other keyword arguments get passed to the service call as ``service_data``. Each service takes
different parameters, so this will vary from service to service. For example, most services require
``entity_id``. The parameters for each service can be found in the actions tab of developer tools in
the Home Assistant web interface.
Returns:
Result of the `call_service` function if any, see
`service call notes <APPGUIDE.html#some-notes-on-service-calls>`__ for more details.
Examples:
HASS
^^^^
>>> self.call_service("light/turn_on", entity_id="light.office_lamp", color_name="red")
>>> self.call_service("notify/notify", title="Hello", message="Hello World")
>>> events = self.call_service(
"calendar/get_events",
entity_id="calendar.home",
start_date_time="2024-08-25 00:00:00",
end_date_time="2024-08-27 00:00:00",
)["result"]["response"]["calendar.home"]["events"]
MQTT
^^^^
>>> self.call_service("mqtt/subscribe", topic="homeassistant/living_room/light", qos=2)
>>> self.call_service("mqtt/publish", topic="homeassistant/living_room/light", payload="on")
Utility
^^^^^^^
It's important that the ``namespace`` arg is set to ``admin`` for these services, as they do not exist
within the default namespace, and apps cannot exist in the ``admin`` namespace. If the namespace is not
specified, calling the method will raise an exception.
>>> self.call_service("app/restart", app="notify_app", namespace="admin")
>>> self.call_service("app/stop", app="lights_app", namespace="admin")
>>> self.call_service("app/reload", namespace="admin")
"""
# We just wrap the ADAPI.call_service method here to add some additional arguments and docstrings
kwargs = utils.remove_literals(kwargs, (None,))
# We intentionally don't pass the timeout kwarg here because it's applied by the sync_decorator
return await super().call_service(service, namespace, callback=callback, **kwargs)
def get_service_info(self, service: str) -> dict | None:
"""Get some information about what kind of data the service expects to receive, which is helpful for debugging.
The resulting dict is identical to the one returned sending ``get_services`` to the websocket. See
`fetching service actions <https://developers.home-assistant.io/docs/api/websocket#fetching-service-actions>`__
for more information.
Args:
service (str): The service name in the format ``<domain>/<service>``. For example, ``light/turn_on``.
Returns:
Information about the service in a dict with the following keys: ``name``, ``description``, ``target``, and
``fields``.
"""
match self._plugin:
case HassPlugin() as plugin:
domain, service_name = service.split("/", 2)
if info := plugin.services.get(domain, {}).get(service_name):
# Return a copy of the info dict to prevent accidental modification
return deepcopy(info)
self.logger.warning("Service info not found for domain '%s", domain)
# Methods that use self.call_service
# Home Assistant General
@utils.sync_decorator
async def turn_on(self, entity_id: str, namespace: str | None = None, **kwargs) -> dict:
"""Turns `on` a Home Assistant entity.
This is a convenience function for the ``homeassistant.turn_on``
function. It can turn ``on`` pretty much anything in Home Assistant
that can be turned ``on`` or ``run`` (e.g., `Lights`, `Switches`,
`Scenes`, `Scripts`, etc.).
Note that Home Assistant will return a success even if the entity name is invalid.
Args:
entity_id (str): Fully qualified id of the thing to be turned ``on`` (e.g.,
`light.office_lamp`, `scene.downstairs_on`).
namespace (str, optional): Namespace to use for the call. See the section on
`namespaces <APPGUIDE.html#namespaces>`__ for a detailed description.
In most cases it is safe to ignore this parameter.
**kwargs (optional): Zero or more keyword arguments that get passed to the
service call.
Returns:
Result of the `turn_on` function if any, see `service call notes <APPGUIDE.html#some-notes-on-service-calls>`__ for more details.
Examples:
Turn `on` a switch.
>>> self.turn_on("switch.backyard_lights")
Turn `on` a scene.
>>> self.turn_on("scene.bedroom_on")
Turn `on` a light and set its color to green.
>>> self.turn_on("light.office_1", color_name = "green")
"""
return await self._entity_service_call(
service="homeassistant/turn_on",
entity_id=entity_id,
namespace=namespace,
**kwargs
)
@utils.sync_decorator
async def turn_off(self, entity_id: str, namespace: str | None = None, **kwargs) -> dict:
"""Turns `off` a Home Assistant entity.
This is a convenience function for the ``homeassistant.turn_off``
function. It can turn ``off`` pretty much anything in Home Assistant
that can be turned ``off`` (e.g., `Lights`, `Switches`, etc.).
Args:
entity_id (str): Fully qualified id of the thing to be turned ``off`` (e.g.,
`light.office_lamp`, `scene.downstairs_on`).
namespace (str, optional): Namespace to use for the call. See the section on
`namespaces <APPGUIDE.html#namespaces>`__ for a detailed description.
In most cases it is safe to ignore this parameter.
**kwargs (optional): Zero or more keyword arguments that get passed to the
service call.
Returns:
Result of the `turn_off` function if any, see `service call notes
<APPGUIDE.html#some-notes-on-service-calls>`__ for more details.
Examples:
Turn `off` a switch.
>>> self.turn_off("switch.backyard_lights")
Turn `off` a scene.
>>> self.turn_off("scene.bedroom_on")
"""
return await self._entity_service_call(
service="homeassistant/turn_off",
entity_id=entity_id,
namespace=namespace,
**kwargs
)
@utils.sync_decorator
async def toggle(self, entity_id: str, namespace: str | None = None, **kwargs) -> dict:
"""Toggles between ``on`` and ``off`` for the selected entity.
This is a convenience function for the ``homeassistant.toggle`` function.
It is able to flip the state of pretty much anything in Home Assistant
that can be turned ``on`` or ``off``.
Args:
entity_id (str): Fully qualified id of the thing to be turned ``off`` (e.g.,
`light.office_lamp`, `scene.downstairs_on`).
namespace (str, optional): Namespace to use for the call. See the section on
`namespaces <APPGUIDE.html#namespaces>`__ for a detailed description.
In most cases it is safe to ignore this parameter.
**kwargs (optional): Zero or more keyword arguments that get passed to the
service call.
Returns:
Result of the `toggle` function if any, see `service call notes <APPGUIDE.html#some-notes-on-service-calls>`__ for more details.
Examples:
>>> self.toggle("switch.backyard_lights")
>>> self.toggle("light.office_1", color_name="green")
"""
return await self._entity_service_call(
service="homeassistant/toggle",
entity_id=entity_id,
namespace=namespace,
**kwargs
)
@utils.sync_decorator
async def get_history(
self,
entity_id: str | list[str],
days: int | None = None,
start_time: datetime | str | None = None,
end_time: datetime | str | None = None,
minimal_response: bool = False,
no_attributes: bool = False,
significant_changes_only: bool = False,
callback: Callable | None = None,
namespace: str | None = None,
) -> list[list[dict[str, Any]]] | None:
"""Gets access to the HA Database.
This is a convenience function that allows accessing the HA Database, so the
history state of a device can be retrieved. It allows for a level of flexibility
when retrieving the data, and returns it as a dictionary list. Caution must be
taken when using this, as depending on the size of the database, it can take
a long time to process.
Hits the ``/api/history/period/<timestamp>`` endpoint. See
https://developers.home-assistant.io/docs/api/rest for more information
Args:
entity_id (str, optional): Fully qualified id of the device to be querying, e.g.,
``light.office_lamp`` or ``scene.downstairs_on`` This can be any entity_id
in the database. If this is left empty, the state of all entities will be
retrieved within the specified time. If both ``end_time`` and ``start_time``
explained below are declared, and ``entity_id`` is specified, the specified
``entity_id`` will be ignored and the history states of `all` entity_id in
the database will be retrieved within the specified time.
days (int, optional): The days from the present-day walking backwards that is
required from the database.
start_time (optional): The start time from when the data should be retrieved.
This should be the furthest time backwards, like if we wanted to get data from
now until two days ago. Your start time will be the last two days datetime.
``start_time`` time can be either a UTC aware time string like ``2019-04-16 12:00:03+01:00``
or a ``datetime.datetime`` object.
end_time (optional): The end time from when the data should be retrieved. This should
be the latest time like if we wanted to get data from now until two days ago. Your
end time will be today's datetime ``end_time`` time can be either a UTC aware time
string like ``2019-04-16 12:00:03+01:00`` or a ``datetime.datetime`` object. It should
be noted that it is not possible to declare only ``end_time``. If only ``end_time``
is declared without ``start_time`` or ``days``, it will revert to default to the latest
history state. When ``end_time`` is specified, it is not possible to declare ``entity_id``.
If ``entity_id`` is specified, ``end_time`` will be ignored.
minimal_response (bool, optional):
no_attributes (bool, optional):
significant_changes_only (bool, optional):
callback (callable, optional): If wanting to access the database to get a large amount of data,
using a direct call to this function will take a long time to run and lead to AD cancelling the task.
To get around this, it is better to pass a function, which will be responsible of receiving the result
from the database. The signature of this function follows that of a scheduler call.
namespace (str, optional): Namespace to use for the call. See the section on
`namespaces <APPGUIDE.html#namespaces>`__ for a detailed description.
In most cases it is safe to ignore this parameter.
Returns:
An iterable list of entity_ids and their history state.
Examples:
Get device state over the last 5 days.
>>> data = self.get_history(entity_id = "light.office_lamp", days = 5)
Get device state over the last 2 days and walk forward.
>>> import datetime
>>> from datetime import timedelta
>>> start_time = datetime.datetime.now() - timedelta(days = 2)
>>> data = self.get_history(entity_id = "light.office_lamp", start_time = start_time)
Get device state from yesterday and walk 5 days back.
>>> import datetime
>>> from datetime import timedelta
>>> end_time = datetime.datetime.now() - timedelta(days = 1)
>>> data = self.get_history(end_time = end_time, days = 5)
"""
if days is not None:
end_time = self.parse_datetime(end_time) if end_time is not None else await self.get_now()
start_time = end_time - timedelta(days=days)
namespace = namespace if namespace is not None else self.namespace
match self.AD.plugins.get_plugin_object(namespace):
case HassPlugin() as plugin:
coro = plugin.get_history(
filter_entity_id=entity_id,
timestamp=start_time,
end_time=end_time,
minimal_response=minimal_response,
no_attributes=no_attributes,
significant_changes_only=significant_changes_only,
)
if callback is not None and callable(callback):
self.create_task(coro, callback)
else:
return await coro
case _:
self.logger.warning("HASS plugin not found in namespace '%s'", namespace)
@utils.sync_decorator
async def get_logbook(
self,
entity: str | None = None,
start_time: datetime | str | None = None,
end_time: datetime | str | None = None,
days: int | None = None,
callback: Callable | None = None,
namespace: str | None = None,
) -> list[dict[str, str | datetime]] | None:
"""Gets access to the HA Database.
This is a convenience function that allows accessing the HA Database.
Caution must be taken when using this, as depending on the size of the
database, it can take a long time to process.
Hits the ``/api/logbook/<timestamp>`` endpoint. See
https://developers.home-assistant.io/docs/api/rest for more information
Args:
entity (str, optional): Fully qualified id of the device to be
querying, e.g., ``light.office_lamp`` or
``scene.downstairs_on``. This can be any entity_id in the
database. This method does not support multiple entity IDs. If
no ``entity`` is specified, then all logbook entries for the
period will be returned.
start_time (datetime, optional): The start time of the period
covered. Defaults to 1 day before the time of the request.
end_time (datetime, optional): The end time of the period covered.
Defaults to the current time if the ``days`` argument is also used.
days (int, optional): Number of days before the end time to include
callback (Callable, optional): Callback to run with the results of the
request. The callback needs to take a single argument, a future object.
namespace (str, optional): Namespace to use for the call. See the section on
`namespaces <APPGUIDE.html#namespaces>`__ for a detailed description.
In most cases it is safe to ignore this parameter.
Returns:
A list of dictionaries, each representing a single entry for a
single entity. The value for the ``when`` key of each dictionary
gets converted to a ``datetime`` object with a timezone.
Examples:
>>> data = self.get_logbook("light.office_lamp")
>>> data = self.get_logbook("light.office_lamp", days=5)
"""
if days is not None:
end_time = self.parse_datetime(end_time) if end_time is not None else await self.get_now()
start_time = end_time - timedelta(days=days)
namespace = namespace if namespace is not None else self.namespace
match self.AD.plugins.get_plugin_object(namespace):
case HassPlugin() as plugin:
coro = plugin.get_logbook(
entity=entity,
timestamp=start_time,
end_time=end_time,
)
if callback is not None and callable(callback):
self.create_task(coro, callback)
else:
return await coro
case _:
self.logger.warning("HASS plugin not found in namespace '%s'", namespace)
# Input Helpers
@utils.sync_decorator
async def set_value(self, entity_id: str, value: int | float, namespace: str | None = None) -> None:
"""Sets the value of an `input_number`.
This is a convenience function for the ``input_number.set_value``
function. It can set the value of an ``input_number`` in Home Assistant.
Args:
entity_id (str): Fully qualified id of `input_number` to be changed (e.g.,
`input_number.alarm_hour`).
value (int or float): The new value to set the `input_number` to.
namespace (str, optional): Namespace to use for the call. See the section on
`namespaces <APPGUIDE.html#namespaces>`__ for a detailed description.
In most cases it is safe to ignore this parameter.
**kwargs (optional): Zero or more keyword arguments that get passed to the
service call.
Returns:
Result of the `set_value` function if any, see `service call notes <APPGUIDE.html#some-notes-on-service-calls>`__ for more details.
Examples:
>>> self.set_value("input_number.alarm_hour", 6)
"""
return await self._domain_service_call(
service="input_number/set_value",
entity_id=entity_id,
value=value,
namespace=namespace
)
@utils.sync_decorator
async def set_textvalue(self, entity_id: str, value: str, namespace: str | None = None) -> None:
"""Sets the value of an `input_text`.
This is a convenience function for the ``input_text.set_value``
function. It can set the value of an `input_text` in Home Assistant.
Args:
entity_id (str): Fully qualified id of `input_text` to be changed (e.g.,
`input_text.text1`).
value (str): The new value to set the `input_text` to.
namespace (str, optional): Namespace to use for the call. See the section on
`namespaces <APPGUIDE.html#namespaces>`__ for a detailed description.
In most cases it is safe to ignore this parameter.
Returns:
Result of the `set_textvalue` function if any, see `service call notes <APPGUIDE.html#some-notes-on-service-calls>`__ for more details.
Examples:
>>> self.set_textvalue("input_text.text1", "hello world")
"""
# https://www.home-assistant.io/integrations/input_text/
return await self._domain_service_call(
service="input_text/set_value",
entity_id=entity_id,
value=value,
namespace=namespace
)
@utils.sync_decorator
async def set_options(self, entity_id: str, options: list[str], namespace: str | None = None) -> dict:
# https://www.home-assistant.io/integrations/input_select/#actions
return await self._domain_service_call(
service="input_select/set_options",
entity_id=entity_id,
options=options,
namespace=namespace,
)
@utils.sync_decorator
async def select_option(self, entity_id: str, option: str, namespace: str | None = None) -> None: