-
Notifications
You must be signed in to change notification settings - Fork 415
/
adapi.py
2851 lines (2134 loc) · 109 KB
/
adapi.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
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 asyncio
import datetime
import inspect
import iso8601
import re
from datetime import timedelta
from copy import deepcopy
# needed for fake coro cb that looks like scheduler
import uuid
import appdaemon.utils as utils
from appdaemon.appdaemon import AppDaemon
class ADAPI:
"""AppDaemon API class.
This class includes all native API calls to AppDaemon
"""
#
# Internal parameters
#
def __init__(self, ad: AppDaemon, name, logging_obj, args, config, app_config, global_vars):
# Store args
self.AD = ad
self.name = name
self._logging = logging_obj
self.config = config
self.app_config = app_config
self.args = deepcopy(args)
self.app_dir = self.AD.app_dir
self.config_dir = self.AD.config_dir
self.dashboard_dir = None
if self.AD.http is not None:
self.dashboard_dir = self.AD.http.dashboard_dir
self.global_vars = global_vars
self._namespace = "default"
self.logger = self._logging.get_child(name)
self.err = self._logging.get_error().getChild(name)
self.user_logs = {}
if "log_level" in args:
self.logger.setLevel(args["log_level"])
self.err.setLevel(args["log_level"])
if "log" in args:
userlog = self.get_user_log(args["log"])
if userlog is not None:
self.logger = userlog
self.dialogflow_v = 2
@staticmethod
def _sub_stack(msg):
# If msg is a data structure of some type, don't sub
if type(msg) is str:
stack = inspect.stack()
if msg.find("__module__") != -1:
msg = msg.replace("__module__", stack[2][1])
if msg.find("__line__") != -1:
msg = msg.replace("__line__", str(stack[2][2]))
if msg.find("__function__") != -1:
msg = msg.replace("__function__", stack[2][3])
return msg
def _get_namespace(self, **kwargs):
if "namespace" in kwargs:
namespace = kwargs["namespace"]
del kwargs["namespace"]
else:
namespace = self._namespace
return namespace
#
# Logging
#
def _log(self, logger, msg, *args, **kwargs):
#
# Internal
#
if "level" in kwargs:
level = kwargs.pop("level", "INFO")
else:
level = "INFO"
ascii_encode = kwargs.pop("ascii_encode", True)
if ascii_encode is True:
msg = str(msg).encode("utf-8", "replace").decode("ascii", "replace")
logger.log(self._logging.log_levels[level], msg, *args, **kwargs)
def log(self, msg, *args, **kwargs):
"""Logs a message to AppDaemon's main logfile.
Args:
msg (str): The message to log.
**kwargs (optional): Zero or more keyword arguments.
Keyword Args:
level (str, optional): The log level of the message - takes a string representing the
standard logger levels (Default: ``"WARNING"``).
ascii_encode (bool, optional): Switch to disable the encoding of all log messages to
ascii. Set this to true if you want to log UTF-8 characters (Default: ``True``).
log (str, optional): Send the message to a specific log, either system or user_defined.
System logs are ``main_log``, ``error_log``, ``diag_log`` or ``access_log``.
Any other value in use here must have a corresponding user-defined entity in
the ``logs`` section of appdaemon.yaml.
stack_info (bool, optional): If ``True`` the stack info will included.
Returns:
None.
Examples:
Log a message to the main logfile of the system.
>>> self.log("Log Test: Parameter is %s", some_variable)
Log a message to the specified logfile.
>>> self.log("Log Test: Parameter is %s", some_variable, log="test_log")
Log a message with error-level to the main logfile of the system.
>>> self.log("Log Test: Parameter is %s", some_variable, level = "ERROR")
Log a message using `placeholders` to the main logfile of the system.
>>> self.log("Line: __line__, module: __module__, function: __function__, Msg: Something bad happened")
Log a WARNING message (including the stack info) to the main logfile of the system.
>>> self.log("Stack is", some_value, level="WARNING", stack_info=True)
"""
if "log" in kwargs:
# Its a user defined log
logger = self.get_user_log(kwargs["log"])
kwargs.pop("log")
else:
logger = self.logger
msg = self._sub_stack(msg)
self._log(logger, msg, *args, **kwargs)
def error(self, msg, *args, **kwargs):
"""Logs a message to AppDaemon's error logfile.
Args:
msg (str): The message to log.
**kwargs (optional): Zero or more keyword arguments.
Keyword Args:
level (str, optional): The log level of the message - takes a string representing the
standard logger levels.
ascii_encode (bool, optional): Switch to disable the encoding of all log messages to
ascii. Set this to true if you want to log UTF-8 characters (Default: ``True``).
log (str, optional): Send the message to a specific log, either system or user_defined.
System logs are ``main_log``, ``error_log``, ``diag_log`` or ``access_log``.
Any other value in use here must have a corresponding user-defined entity in
the ``logs`` section of appdaemon.yaml.
Returns:
None.
Examples:
Log an error message to the error logfile of the system.
>>> self.error("Some Warning string")
Log an error message with critical-level to the error logfile of the system.
>>> self.error("Some Critical string", level = "CRITICAL")
"""
self._log(self.err, msg, *args, **kwargs)
@utils.sync_wrapper
async def listen_log(self, callback, level="INFO", **kwargs):
"""Registers the App to receive a callback every time an App logs a message.
Args:
callback (function): Function to be called when a message is logged.
level (str): Logging level to be used - lower levels will not be forwarded
to the app (Default: ``"INFO"``).
**kwargs (optional): Zero or more keyword arguments.
Keyword Args:
log (str, optional): Name of the log to listen to, default is all logs. The name
should be one of the 4 built in types ``main_log``, ``error_log``, ``diag_log``
or ``access_log`` or a user defined log entry.
pin (bool, optional): If True, the callback will be pinned to a particular thread.
pin_thread (int, optional): Specify which thread from the worker pool the callback
will be run by (0 - number of threads -1).
Returns:
A unique identifier that can be used to cancel the callback if required.
Since variables created within object methods are local to the function they are
created in, and in all likelihood, the cancellation will be invoked later in a
different function, it is recommended that handles are stored in the object
namespace, e.g., self.handle.
Examples:
Listen to all ``WARNING`` log messages of the system.
>>> self.handle = self.listen_log(self.cb, "WARNING")
Listen to all ``WARNING`` log messages of the `main_log`.
>>> self.handle = self.listen_log(self.cb, "WARNING", log="main_log")
Listen to all ``WARNING`` log messages of a user-defined logfile.
>>> self.handle = self.listen_log(self.cb, "WARNING", log="my_custom_log")
"""
namespace = kwargs.pop("namespace", "admin")
return await self.AD.logging.add_log_callback(namespace, self.name, callback, level, **kwargs)
@utils.sync_wrapper
async def cancel_listen_log(self, handle):
"""Cancels the log callback for the App.
Args:
handle: The handle returned when the `listen_log` call was made.
Returns:
None.
Examples:
>>> self.cancel_listen_log(handle)
"""
self.logger.debug("Canceling listen_log for %s", self.name)
await self.AD.logging.cancel_log_callback(self.name, handle)
def get_main_log(self):
"""Returns the underlying logger object used for the main log.
Examples:
Log a critical message to the `main` logfile of the system.
>>> log = self.get_main_log()
>>> log.critical("Log a critical error")
"""
return self.logger
def get_error_log(self):
"""Returns the underlying logger object used for the error log.
Examples:
Log an error message to the `error` logfile of the system.
>>> error_log = self.get_error_log()
>>> error_log.error("Log an error", stack_info=True, exc_info=True)
"""
return self.err
def get_user_log(self, log):
"""Gets the specified-user logger of the App.
Args:
log (str): The name of the log you want to get the underlying logger object from,
as described in the ``logs`` section of ``appdaemon.yaml``.
Returns:
The underlying logger object used for the error log.
Examples:
Log an error message to a user-defined logfile.
>>> log = self.get_user_log("test_log")
>>> log.error("Log an error", stack_info=True, exc_info=True)
"""
logger = None
if log in self.user_logs:
# Did we use it already?
logger = self.user_logs[log]
else:
# Build it on the fly
parent = self.AD.logging.get_user_log(self, log)
if parent is not None:
logger = parent.getChild(self.name)
self.user_logs[log] = logger
if "log_level" in self.args:
logger.setLevel(self.args["log_level"])
return logger
def set_log_level(self, level):
"""Sets a specific log level for the App.
Args:
level (str): Log level.
Returns:
None.
Notes:
Supported log levels: ``INFO``, ``WARNING``, ``ERROR``, ``CRITICAL``,
``DEBUG``, ``NOTSET``.
Examples:
>>> self.set_log_level("DEBUG")
"""
self.logger.setLevel(self._logging.log_levels[level])
self.err.setLevel(self._logging.log_levels[level])
for log in self.user_logs:
self.user_logs[log].setLevel(self._logging.log_levels[level])
def set_error_level(self, level):
"""Sets the log level to send to the `error` logfile of the system.
Args:
level (str): Error level.
Returns:
None.
Notes:
Supported log levels: ``INFO``, ``WARNING``, ``ERROR``, ``CRITICAL``,
``DEBUG``, ``NOTSET``.
"""
self.err.setLevel(self._logging.log_levels[level])
#
# Threading
#
@utils.sync_wrapper
async def set_app_pin(self, pin):
"""Sets an App to be pinned or unpinned.
Args:
pin (bool): Sets whether the App becomes pinned or not.
Returns:
None.
Examples:
The following line should be put inside the `initialize()` function.
>>> self.set_app_pin(True)
"""
await self.AD.threading.set_app_pin(self.name, pin)
@utils.sync_wrapper
async def get_app_pin(self):
"""Finds out if the current App is currently pinned or not.
Returns:
bool: ``True`` if the App is pinned, ``False`` otherwise.
Examples:
>>> if self.get_app_pin(True):
>>> self.log("App pinned!")
"""
return await self.AD.threading.get_app_pin(self.name)
@utils.sync_wrapper
async def set_pin_thread(self, thread):
"""Sets the thread that the App will be pinned to.
Args:
thread (int): Number of the thread to pin to. Threads start at 0 and go up to the number
of threads specified in ``appdaemon.yaml`` -1.
Returns:
None.
Examples:
The following line should be put inside the `initialize()` function.
>>> self.set_pin_thread(5)
"""
return await self.AD.threading.set_pin_thread(self.name, thread)
@utils.sync_wrapper
async def get_pin_thread(self):
"""Finds out which thread the App is pinned to.
Returns:
int: The thread number or -1 if the App is not pinned.
Examples:
>>> thread = self.get_pin_thread():
>>> self.log(f"I'm pinned to thread: {thread}")
"""
return await self.AD.threading.get_pin_thread(self.name)
#
# Namespace
#
def set_namespace(self, namespace):
"""Sets a new namespace for the App to use from that point forward.
Args:
namespace (str): Name of the new namespace
Returns:
None.
Examples:
>>> self.set_namespace("hass1")
"""
self._namespace = namespace
def get_namespace(self):
"""Returns the App's namespace."""
return self._namespace
@utils.sync_wrapper
async def list_namespaces(self):
"""Returns a list of available namespaces.
Examples:
>>> self.list_namespaces()
"""
return await self.AD.state.list_namespaces()
@utils.sync_wrapper
async def save_namespace(self, **kwargs):
"""Saves entities created in user-defined namespaces into a file.
This way, when AD restarts these entities will be reloaded into AD with its
previous states within the namespace. This can be used as a basic form of
non-volatile storage of entity data. Depending on the configuration of the
namespace, this function can be setup to constantly be running automatically
or only when AD shutdown. This function also allows for users to manually
execute the command as when needed.
Args:
**kwargs (optional): Zero or more keyword arguments.
Keyword 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.
Returns:
None.
Examples:
Save all entities of the default namespace.
>>> self.save_namespace()
"""
namespace = self._get_namespace(**kwargs)
await self.AD.state.save_namespace(namespace)
#
# Utility
#
@utils.sync_wrapper
async def get_app(self, name):
"""Gets the instantiated object of another app running within the system.
This is useful for calling functions or accessing variables that reside
in different apps without requiring duplication of code.
Args:
name (str): Name of the app required. This is the name specified in
header section of the config file, not the module or class.
Returns:
An object reference to the class.
Examples:
>>> MyApp = self.get_app("MotionLights")
>>> MyApp.turn_light_on()
"""
return await self.AD.app_management.get_app(name)
@utils.sync_wrapper
async def _check_entity(self, namespace, entity):
if "." not in entity:
raise ValueError("{}: Invalid entity ID: {}".format(self.name, entity))
if not await self.AD.state.entity_exists(namespace, entity):
self.logger.warning("%s: Entity %s not found in namespace %s", self.name, entity, namespace)
@staticmethod
def get_ad_version():
"""Returns a string with the current version of AppDaemon.
Examples:
>>> version = self.get_ad_version()
"""
return utils.__version__
@utils.sync_wrapper
async def entity_exists(self, entity_id, **kwargs):
"""Checks the existence of an entity in Home Assistant.
When working with multiple Home Assistant instances, it is possible to specify the
namespace, so that it checks within the right instance in in the event the app is
working in a different instance. Also when using this function, it is also possible
to check if an AppDaemon entity exists.
Args:
entity_id (str): The fully qualified entity id (including the device type).
**kwargs (optional): Zero or more keyword arguments.
Keyword 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.
Returns:
bool: ``True`` if the entity id exists, ``False`` otherwise.
Examples:
Check if the entity light.living_room exist within the app's namespace
>>> if self.entity_exists("light.living_room"):
>>> #do something
Check if the entity mqtt.security_settings exist within the `mqtt` namespace
if the app is operating in a different namespace like default
>>> if self.entity_exists("mqtt.security_settings", namespace = "mqtt"):
>>> #do something
"""
namespace = self._get_namespace(**kwargs)
return await self.AD.state.entity_exists(namespace, entity_id)
@utils.sync_wrapper
async def split_entity(self, entity_id, **kwargs):
"""Splits an entity into parts.
This utility function will take a fully qualified entity id of the form ``light.hall_light``
and split it into 2 values, the device and the entity, e.g. light and hall_light.
Args:
entity_id (str): The fully qualified entity id (including the device type).
**kwargs (optional): Zero or more keyword arguments.
Keyword 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.
Returns:
A list with 2 entries, the device and entity respectively.
Examples:
Do some action if the device of the entity is `scene`.
>>> device, entity = self.split_entity(entity_id)
>>> if device == "scene":
>>> #do something specific to scenes
"""
await self._check_entity(self._get_namespace(**kwargs), entity_id)
return entity_id.split(".")
@utils.sync_wrapper
async def remove_entity(self, entity_id, **kwargs):
"""Deletes an entity created within a namespaces.
If an entity was created, and its deemed no longer needed, by using this function,
the entity can be removed from AppDaemon permanently.
Args:
entity_id (str): The fully qualified entity id (including the device type).
**kwargs (optional): Zero or more keyword arguments.
Keyword 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.
Returns:
None.
Examples:
Delete the entity in the present namespace.
>>> self.remove_entity('sensor.living_room')
Delete the entity in the `mqtt` namespace.
>>> self.remove_entity('mqtt.living_room_temperature', namespace = 'mqtt')
"""
namespace = self._get_namespace(**kwargs)
await self.AD.state.remove_entity(namespace, entity_id)
return None
@staticmethod
def split_device_list(devices):
"""Converts a comma-separated list of device types to an iterable list.
This is intended to assist in use cases where the App takes a list of
entities from an argument, e.g., a list of sensors to monitor. If only
one entry is provided, an iterable list will still be returned to avoid
the need for special processing.
Args:
devices (str): A comma-separated list of devices to be split (without spaces).
Returns:
A list of split devices with 1 or more entries.
Examples:
>>> for sensor in self.split_device_list(self.args["sensors"]):
>>> #do something for each sensor, e.g., make a state subscription
"""
return devices.split(",")
@utils.sync_wrapper
async def get_plugin_config(self, **kwargs):
"""Gets any useful metadata that the plugin may have available.
For instance, for the HASS plugin, this will return Home Assistant configuration
data such as latitude and longitude.
Args:
**kwargs (optional): Zero or more keyword arguments.
Keyword Args:
namespace (str): Select the namespace of the plugin for which data is desired.
Returns:
A dictionary containing all the configuration information available
from the Home Assistant ``/api/config`` endpoint.
Examples:
>>> config = self.get_plugin_config()
>>> self.log(f'My current position is {config["latitude"]}(Lat), {config["longitude"]}(Long)')
My current position is 50.8333(Lat), 4.3333(Long)
"""
namespace = self._get_namespace(**kwargs)
return await self.AD.plugins.get_plugin_meta(namespace)
@utils.sync_wrapper
async def friendly_name(self, entity_id, **kwargs):
"""Gets the Friendly Name of an entity.
Args:
entity_id (str): The fully qualified entity id (including the device type).
**kwargs (optional): Zero or more keyword arguments.
Keyword 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.
Returns:
str: The friendly name of the entity if it exists or the entity id if not.
Examples:
>>> tracker = "device_tracker.andrew"
>>> friendly_name = self.friendly_name(tracker)
>>> tracker_state = self.get_tracker_state(tracker)
>>> self.log(f"{tracker} ({friendly_name}) is {tracker_state}.")
device_tracker.andrew (Andrew Tracker) is on.
"""
await self._check_entity(self._get_namespace(**kwargs), entity_id)
state = await self.get_state(**kwargs)
if entity_id in state:
if "friendly_name" in state[entity_id]["attributes"]:
return state[entity_id]["attributes"]["friendly_name"]
else:
return entity_id
return None
@utils.sync_wrapper
async def set_production_mode(self, mode=True):
"""Deactivates or activates the production mode in AppDaemon.
When called without declaring passing any arguments, mode defaults to ``True``.
Args:
mode (bool): If it is ``True`` the production mode is activated, or deactivated
otherwise.
Returns:
The specified mode or ``None`` if a wrong parameter is passed.
"""
if not isinstance(mode, bool):
self.logger.warning("%s not a valid parameter for Production Mode", mode)
return None
await self.AD.utility.set_production_mode(mode)
return mode
#
# Internal Helper functions
#
def start_app(self, app, **kwargs):
"""Starts an App which can either be running or not.
This Api call cannot start an app which has already been disabled in the App Config.
It essentially only runs the initialize() function in the app, and changes to attributes
like class name or app config is not taken into account.
Args:
app (str): Name of the app.
**kwargs (optional): Zero or more keyword arguments.
Returns:
None.
Examples:
>>> self.start_app("lights_app")
"""
kwargs["app"] = app
kwargs["namespace"] = "appdaemon"
self.call_service("app/start", **kwargs)
return None
def stop_app(self, app, **kwargs):
"""Stops an App which is running.
Args:
app (str): Name of the app.
**kwargs (optional): Zero or more keyword arguments.
Returns:
None.
Examples:
>>> self.stop_app("lights_app")
"""
kwargs["app"] = app
kwargs["namespace"] = "appdaemon"
self.call_service("app/stop", **kwargs)
return None
def restart_app(self, app, **kwargs):
"""Restarts an App which can either be running or not.
Args:
app (str): Name of the app.
**kwargs (optional): Zero or more keyword arguments.
Returns:
None.
Examples:
>>> self.restart_app("lights_app")
"""
kwargs["app"] = app
kwargs["namespace"] = "appdaemon"
self.call_service("app/restart", **kwargs)
return None
def reload_apps(self, **kwargs):
"""Reloads the apps, and loads up those that have changes made to their .yaml or .py files.
This utility function can be used if AppDaemon is running in production mode, and it is
needed to reload apps that changes have been made to.
Args:
**kwargs (optional): Zero or more keyword arguments.
Returns:
None.
Examples:
>>> self.reload_apps()
"""
kwargs["namespace"] = "appdaemon"
self.call_service("app/reload", **kwargs)
return None
#
# Dialogflow
#
def get_dialogflow_intent(self, data):
"""Gets the intent's action from the Google Home response.
Args:
data: Response received from Google Home.
Returns:
A string representing the Intent from the interaction model that was requested,
or ``None``, if no action was received.
Examples:
>>> intent = ADAPI.get_dialogflow_intent(data)
"""
if "result" in data and "action" in data["result"]:
self.dialogflow_v = 1
return data["result"]["action"]
elif "queryResult" in data and "action" in data["queryResult"]:
self.dialogflow_v = 2
return data["queryResult"]["action"]
else:
return None
@staticmethod
def get_dialogflow_slot_value(data, slot=None):
"""Gets slots' values from the interaction model.
Args:
data: Response received from Google Home.
slot (str): Name of the slot. If a name is not specified, all slots will be returned
as a dictionary. If a name is specified but is not found, ``None`` will be returned.
Returns:
A string representing the value of the slot from the interaction model, or a hash of slots.
Examples:
>>> beer_type = ADAPI.get_dialogflow_intent(data, "beer_type")
>>> all_slots = ADAPI.get_dialogflow_intent(data)
"""
if "result" in data:
# using V1 API
contexts = data["result"]["contexts"][0]
if contexts:
parameters = contexts.get("parameters")
else:
parameters = data["result"]["parameters"]
if slot is None:
return parameters
elif slot in parameters:
return parameters[slot]
else:
return None
elif "queryResult" in data:
# using V2 API
contexts = data["queryResult"]["outputContexts"][0]
if contexts:
parameters = contexts.get("parameters")
else:
parameters = data["queryResult"]["parameters"]
if slot is None:
return parameters
elif slot in parameters:
return parameters[slot]
else:
return None
else:
return None
def format_dialogflow_response(self, speech=None):
"""Formats a response to be returned to Google Home, including speech.
Args:
speech (str): The text for Google Home to say.
Returns:
None.
Examples:
>>> ADAPI.format_dialogflow_response(speech = "Hello World")
"""
if self.dialogflow_v == 1:
speech = {"speech": speech, "source": "Appdaemon", "displayText": speech}
elif self.dialogflow_v == 2:
speech = {"fulfillmentText": speech, "source": "Appdaemon"}
else:
speech = None
return speech
#
# Alexa
#
@staticmethod
def format_alexa_response(speech=None, card=None, title=None):
"""Formats a response to be returned to Alex including speech and a card.
Args:
speech (str): The text for Alexa to say.
card (str): Text for the card.
title (str): Title for the card.
Returns:
None.
Examples:
>>> ADAPI.format_alexa_response(speech = "Hello World", card = "Greetings to the world", title = "Hello")
"""
response = {"shouldEndSession": True}
if speech is not None:
response["outputSpeech"] = {"type": "PlainText", "text": speech}
if card is not None:
response["card"] = {"type": "Simple", "title": title, "content": card}
speech = {"version": "1.0", "response": response, "sessionAttributes": {}}
return speech
@staticmethod
def get_alexa_error(data):
"""Gets the error message from the Alexa API response.
Args:
data: Response received from the Alexa API .
Returns:
A string representing the value of message, or ``None`` if no error message was received.
"""
if "request" in data and "err" in data["request"] and "message" in data["request"]["err"]:
return data["request"]["err"]["message"]
else:
return None
@staticmethod
def get_alexa_intent(data):
"""Gets the Intent's name from the Alexa response.
Args:
data: Response received from Alexa.
Returns:
A string representing the Intent's name from the interaction model that was requested,
or ``None``, if no Intent was received.
Examples:
>>> intent = ADAPI.get_alexa_intent(data)
"""
if "request" in data and "intent" in data["request"] and "name" in data["request"]["intent"]:
return data["request"]["intent"]["name"]
else:
return None
@staticmethod
def get_alexa_slot_value(data, slot=None):
"""Gets values for slots from the interaction model.
Args:
data: The request data received from Alexa.
slot: Name of the slot. If a name is not specified, all slots will be returned as
a dictionary. If a name is specified but is not found, None will be returned.
Returns:
A ``string`` representing the value of the slot from the interaction model, or a ``hash`` of slots.
Examples:
>>> beer_type = ADAPI.get_alexa_intent(data, "beer_type")
>>> all_slots = ADAPI.get_alexa_intent(data)
"""
if "request" in data and "intent" in data["request"] and "slots" in data["request"]["intent"]:
if slot is None:
return data["request"]["intent"]["slots"]
else:
if slot in data["request"]["intent"]["slots"] and "value" in data["request"]["intent"]["slots"][slot]:
return data["request"]["intent"]["slots"][slot]["value"]
else:
return None
else:
return None
#
# API
#
@utils.sync_wrapper
async def register_endpoint(self, callback, name=None):
"""Registers an endpoint for API calls into the current App.
Args:
callback: The function to be called when a request is made to the named endpoint.
name (str, optional): The name of the endpoint to be used for the call (Default: ``None``).
Returns:
A handle that can be used to remove the registration.