-
-
Notifications
You must be signed in to change notification settings - Fork 28.4k
/
capabilities.py
2342 lines (1921 loc) · 74.3 KB
/
capabilities.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
"""Alexa capabilities."""
from __future__ import annotations
from collections.abc import Generator
import logging
from typing import Any
from homeassistant.components import (
button,
climate,
cover,
fan,
humidifier,
image_processing,
input_button,
input_number,
light,
media_player,
number,
timer,
vacuum,
water_heater,
)
from homeassistant.components.alarm_control_panel import (
AlarmControlPanelEntityFeature,
CodeFormat,
)
from homeassistant.components.climate import HVACMode
from homeassistant.const import (
ATTR_CODE_FORMAT,
ATTR_SUPPORTED_FEATURES,
ATTR_TEMPERATURE,
ATTR_UNIT_OF_MEASUREMENT,
PERCENTAGE,
STATE_ALARM_ARMED_AWAY,
STATE_ALARM_ARMED_CUSTOM_BYPASS,
STATE_ALARM_ARMED_HOME,
STATE_ALARM_ARMED_NIGHT,
STATE_IDLE,
STATE_LOCKED,
STATE_LOCKING,
STATE_OFF,
STATE_ON,
STATE_PAUSED,
STATE_PLAYING,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
STATE_UNLOCKED,
STATE_UNLOCKING,
UnitOfLength,
UnitOfMass,
UnitOfTemperature,
UnitOfVolume,
)
from homeassistant.core import HomeAssistant, State
import homeassistant.util.color as color_util
import homeassistant.util.dt as dt_util
from .const import (
API_TEMP_UNITS,
API_THERMOSTAT_MODES,
API_THERMOSTAT_PRESETS,
DATE_FORMAT,
PRESET_MODE_NA,
Inputs,
)
from .errors import UnsupportedProperty
from .resources import (
AlexaCapabilityResource,
AlexaGlobalCatalog,
AlexaModeResource,
AlexaPresetResource,
AlexaSemantics,
)
_LOGGER = logging.getLogger(__name__)
UNIT_TO_CATALOG_TAG = {
UnitOfTemperature.CELSIUS: AlexaGlobalCatalog.UNIT_TEMPERATURE_CELSIUS,
UnitOfTemperature.FAHRENHEIT: AlexaGlobalCatalog.UNIT_TEMPERATURE_FAHRENHEIT,
UnitOfTemperature.KELVIN: AlexaGlobalCatalog.UNIT_TEMPERATURE_KELVIN,
UnitOfLength.METERS: AlexaGlobalCatalog.UNIT_DISTANCE_METERS,
UnitOfLength.KILOMETERS: AlexaGlobalCatalog.UNIT_DISTANCE_KILOMETERS,
UnitOfLength.INCHES: AlexaGlobalCatalog.UNIT_DISTANCE_INCHES,
UnitOfLength.FEET: AlexaGlobalCatalog.UNIT_DISTANCE_FEET,
UnitOfLength.YARDS: AlexaGlobalCatalog.UNIT_DISTANCE_YARDS,
UnitOfLength.MILES: AlexaGlobalCatalog.UNIT_DISTANCE_MILES,
UnitOfMass.GRAMS: AlexaGlobalCatalog.UNIT_MASS_GRAMS,
UnitOfMass.KILOGRAMS: AlexaGlobalCatalog.UNIT_MASS_KILOGRAMS,
UnitOfMass.POUNDS: AlexaGlobalCatalog.UNIT_WEIGHT_POUNDS,
UnitOfMass.OUNCES: AlexaGlobalCatalog.UNIT_WEIGHT_OUNCES,
UnitOfVolume.LITERS: AlexaGlobalCatalog.UNIT_VOLUME_LITERS,
UnitOfVolume.CUBIC_FEET: AlexaGlobalCatalog.UNIT_VOLUME_CUBIC_FEET,
UnitOfVolume.CUBIC_METERS: AlexaGlobalCatalog.UNIT_VOLUME_CUBIC_METERS,
UnitOfVolume.GALLONS: AlexaGlobalCatalog.UNIT_VOLUME_GALLONS,
PERCENTAGE: AlexaGlobalCatalog.UNIT_PERCENT,
"preset": AlexaGlobalCatalog.SETTING_PRESET,
}
def get_resource_by_unit_of_measurement(entity: State) -> str:
"""Translate the unit of measurement to an Alexa Global Catalog keyword."""
unit: str = entity.attributes.get("unit_of_measurement", "preset")
return UNIT_TO_CATALOG_TAG.get(unit, AlexaGlobalCatalog.SETTING_PRESET)
class AlexaCapability:
"""Base class for Alexa capability interfaces.
The Smart Home Skills API defines a number of "capability interfaces",
roughly analogous to domains in Home Assistant. The supported interfaces
describe what actions can be performed on a particular device.
https://developer.amazon.com/docs/device-apis/message-guide.html
"""
_resource: AlexaCapabilityResource | None
_semantics: AlexaSemantics | None
supported_locales: set[str] = {"en-US"}
def __init__(
self,
entity: State,
instance: str | None = None,
non_controllable_properties: bool | None = None,
) -> None:
"""Initialize an Alexa capability."""
self.entity = entity
self.instance = instance
self._non_controllable_properties = non_controllable_properties
def name(self) -> str:
"""Return the Alexa API name of this interface."""
raise NotImplementedError
def properties_supported(self) -> list[dict]:
"""Return what properties this entity supports."""
return []
def properties_proactively_reported(self) -> bool:
"""Return True if properties asynchronously reported."""
return False
def properties_retrievable(self) -> bool:
"""Return True if properties can be retrieved."""
return False
def properties_non_controllable(self) -> bool | None:
"""Return True if non controllable."""
return self._non_controllable_properties
def get_property(self, name: str) -> dict[str, Any]:
"""Read and return a property.
Return value should be a dict, or raise UnsupportedProperty.
Properties can also have a timeOfSample and uncertaintyInMilliseconds,
but returning those metadata is not yet implemented.
"""
raise UnsupportedProperty(name)
def supports_deactivation(self) -> bool | None:
"""Applicable only to scenes."""
def capability_proactively_reported(self) -> bool | None:
"""Return True if the capability is proactively reported.
Set properties_proactively_reported() for proactively reported properties.
Applicable to DoorbellEventSource.
"""
def capability_resources(self) -> dict[str, list[dict[str, Any]]]:
"""Return the capability object.
Applicable to ToggleController, RangeController, and ModeController interfaces.
"""
return {}
def configuration(self) -> dict[str, Any] | None:
"""Return the configuration object.
Applicable to the ThermostatController, SecurityControlPanel, ModeController,
RangeController, and EventDetectionSensor.
"""
def configurations(self) -> dict[str, Any] | None:
"""Return the configurations object.
The plural configurations object is different that the singular configuration
object. Applicable to EqualizerController interface.
"""
def inputs(self) -> list[dict[str, str]] | None:
"""Applicable only to media players."""
def semantics(self) -> dict[str, Any] | None:
"""Return the semantics object.
Applicable to ToggleController, RangeController, and ModeController interfaces.
"""
def supported_operations(self) -> list[str]:
"""Return the supportedOperations object."""
return []
def camera_stream_configurations(self) -> list[dict[str, Any]] | None:
"""Applicable only to CameraStreamController."""
def serialize_discovery(self) -> dict[str, Any]:
"""Serialize according to the Discovery API."""
result: dict[str, Any] = {
"type": "AlexaInterface",
"interface": self.name(),
"version": "3",
}
if (instance := self.instance) is not None:
result["instance"] = instance
if properties_supported := self.properties_supported():
result["properties"] = {
"supported": properties_supported,
"proactivelyReported": self.properties_proactively_reported(),
"retrievable": self.properties_retrievable(),
}
if (proactively_reported := self.capability_proactively_reported()) is not None:
result["proactivelyReported"] = proactively_reported
if (non_controllable := self.properties_non_controllable()) is not None:
result["properties"]["nonControllable"] = non_controllable
if (supports_deactivation := self.supports_deactivation()) is not None:
result["supportsDeactivation"] = supports_deactivation
if capability_resources := self.capability_resources():
result["capabilityResources"] = capability_resources
if configuration := self.configuration():
result["configuration"] = configuration
# The plural configurations object is different than the singular
# configuration object above.
if configurations := self.configurations():
result["configurations"] = configurations
if semantics := self.semantics():
result["semantics"] = semantics
if supported_operations := self.supported_operations():
result["supportedOperations"] = supported_operations
if inputs := self.inputs():
result["inputs"] = inputs
if camera_stream_configurations := self.camera_stream_configurations():
result["cameraStreamConfigurations"] = camera_stream_configurations
return result
def serialize_properties(self) -> Generator[dict[str, Any], None, None]:
"""Return properties serialized for an API response."""
for prop in self.properties_supported():
prop_name = prop["name"]
try:
prop_value = self.get_property(prop_name)
except UnsupportedProperty:
raise
except Exception: # pylint: disable=broad-except
_LOGGER.exception(
"Unexpected error getting %s.%s property from %s",
self.name(),
prop_name,
self.entity,
)
prop_value = None
if prop_value is None:
continue
result = {
"name": prop_name,
"namespace": self.name(),
"value": prop_value,
"timeOfSample": dt_util.utcnow().strftime(DATE_FORMAT),
"uncertaintyInMilliseconds": 0,
}
if (instance := self.instance) is not None:
result["instance"] = instance
yield result
class Alexa(AlexaCapability):
"""Implements Alexa Interface.
Although endpoints implement this interface implicitly,
The API suggests you should explicitly include this interface.
https://developer.amazon.com/docs/device-apis/alexa-interface.html
"""
supported_locales = {
"ar-SA",
"de-DE",
"en-AU",
"en-CA",
"en-GB",
"en-IN",
"en-US",
"es-ES",
"es-MX",
"es-US",
"fr-CA",
"fr-FR",
"hi-IN",
"it-IT",
"ja-JP",
"pt-BR",
}
def name(self) -> str:
"""Return the Alexa API name of this interface."""
return "Alexa"
class AlexaEndpointHealth(AlexaCapability):
"""Implements Alexa.EndpointHealth.
https://developer.amazon.com/docs/smarthome/state-reporting-for-a-smart-home-skill.html#report-state-when-alexa-requests-it
"""
supported_locales = {
"ar-SA",
"de-DE",
"en-AU",
"en-CA",
"en-GB",
"en-IN",
"en-US",
"es-ES",
"es-MX",
"es-US",
"fr-CA",
"fr-FR",
"hi-IN",
"it-IT",
"ja-JP",
"pt-BR",
}
def __init__(self, hass: HomeAssistant, entity: State) -> None:
"""Initialize the entity."""
super().__init__(entity)
self.hass = hass
def name(self) -> str:
"""Return the Alexa API name of this interface."""
return "Alexa.EndpointHealth"
def properties_supported(self) -> list[dict[str, str]]:
"""Return what properties this entity supports."""
return [{"name": "connectivity"}]
def properties_proactively_reported(self) -> bool:
"""Return True if properties asynchronously reported."""
return True
def properties_retrievable(self) -> bool:
"""Return True if properties can be retrieved."""
return True
def get_property(self, name: str) -> Any:
"""Read and return a property."""
if name != "connectivity":
raise UnsupportedProperty(name)
if self.entity.state == STATE_UNAVAILABLE:
return {"value": "UNREACHABLE"}
return {"value": "OK"}
class AlexaPowerController(AlexaCapability):
"""Implements Alexa.PowerController.
https://developer.amazon.com/docs/device-apis/alexa-powercontroller.html
"""
supported_locales = {
"ar-SA",
"de-DE",
"en-AU",
"en-CA",
"en-GB",
"en-IN",
"en-US",
"es-ES",
"es-MX",
"es-US",
"fr-CA",
"fr-FR",
"hi-IN",
"it-IT",
"ja-JP",
"pt-BR",
}
def name(self) -> str:
"""Return the Alexa API name of this interface."""
return "Alexa.PowerController"
def properties_supported(self) -> list[dict[str, str]]:
"""Return what properties this entity supports."""
return [{"name": "powerState"}]
def properties_proactively_reported(self) -> bool:
"""Return True if properties asynchronously reported."""
return True
def properties_retrievable(self) -> bool:
"""Return True if properties can be retrieved."""
return True
def get_property(self, name: str) -> Any:
"""Read and return a property."""
if name != "powerState":
raise UnsupportedProperty(name)
if self.entity.domain == climate.DOMAIN:
is_on = self.entity.state != climate.HVACMode.OFF
elif self.entity.domain == fan.DOMAIN:
is_on = self.entity.state == fan.STATE_ON
elif self.entity.domain == humidifier.DOMAIN:
is_on = self.entity.state == humidifier.STATE_ON
elif self.entity.domain == vacuum.DOMAIN:
is_on = self.entity.state == vacuum.STATE_CLEANING
elif self.entity.domain == timer.DOMAIN:
is_on = self.entity.state != STATE_IDLE
elif self.entity.domain == water_heater.DOMAIN:
is_on = self.entity.state not in (STATE_OFF, STATE_UNKNOWN)
else:
is_on = self.entity.state != STATE_OFF
return "ON" if is_on else "OFF"
class AlexaLockController(AlexaCapability):
"""Implements Alexa.LockController.
https://developer.amazon.com/docs/device-apis/alexa-lockcontroller.html
"""
supported_locales = {
"ar-SA",
"de-DE",
"en-AU",
"en-CA",
"en-GB",
"en-IN",
"en-US",
"es-ES",
"es-MX",
"es-US",
"fr-CA",
"fr-FR",
"hi-IN",
"it-IT",
"ja-JP",
"pt-BR",
}
def name(self) -> str:
"""Return the Alexa API name of this interface."""
return "Alexa.LockController"
def properties_supported(self) -> list[dict[str, str]]:
"""Return what properties this entity supports."""
return [{"name": "lockState"}]
def properties_retrievable(self) -> bool:
"""Return True if properties can be retrieved."""
return True
def properties_proactively_reported(self) -> bool:
"""Return True if properties asynchronously reported."""
return True
def get_property(self, name: str) -> Any:
"""Read and return a property."""
if name != "lockState":
raise UnsupportedProperty(name)
# If its unlocking its still locked and not unlocked yet
if self.entity.state in (STATE_UNLOCKING, STATE_LOCKED):
return "LOCKED"
# If its locking its still unlocked and not locked yet
if self.entity.state in (STATE_LOCKING, STATE_UNLOCKED):
return "UNLOCKED"
return "JAMMED"
class AlexaSceneController(AlexaCapability):
"""Implements Alexa.SceneController.
https://developer.amazon.com/docs/device-apis/alexa-scenecontroller.html
"""
supported_locales = {
"de-DE",
"en-AU",
"en-CA",
"en-GB",
"en-IN",
"en-US",
"es-ES",
"es-MX",
"es-US",
"fr-CA",
"fr-FR",
"hi-IN",
"it-IT",
"ja-JP",
"pt-BR",
}
def __init__(self, entity: State, supports_deactivation: bool) -> None:
"""Initialize the entity."""
self._supports_deactivation = supports_deactivation
super().__init__(entity)
def supports_deactivation(self) -> bool | None:
"""Return True if the Scene controller supports deactivation."""
return self._supports_deactivation
def name(self) -> str:
"""Return the Alexa API name of this interface."""
return "Alexa.SceneController"
class AlexaBrightnessController(AlexaCapability):
"""Implements Alexa.BrightnessController.
https://developer.amazon.com/docs/device-apis/alexa-brightnesscontroller.html
"""
supported_locales = {
"ar-SA",
"de-DE",
"en-AU",
"en-CA",
"en-GB",
"en-IN",
"en-US",
"es-ES",
"es-MX",
"es-US",
"fr-CA",
"fr-FR",
"hi-IN",
"it-IT",
"ja-JP",
"pt-BR",
}
def name(self) -> str:
"""Return the Alexa API name of this interface."""
return "Alexa.BrightnessController"
def properties_supported(self) -> list[dict[str, str]]:
"""Return what properties this entity supports."""
return [{"name": "brightness"}]
def properties_proactively_reported(self) -> bool:
"""Return True if properties asynchronously reported."""
return True
def properties_retrievable(self) -> bool:
"""Return True if properties can be retrieved."""
return True
def get_property(self, name: str) -> Any:
"""Read and return a property."""
if name != "brightness":
raise UnsupportedProperty(name)
if brightness := self.entity.attributes.get("brightness"):
return round(brightness / 255.0 * 100)
return 0
class AlexaColorController(AlexaCapability):
"""Implements Alexa.ColorController.
https://developer.amazon.com/docs/device-apis/alexa-colorcontroller.html
"""
supported_locales = {
"de-DE",
"en-AU",
"en-CA",
"en-GB",
"en-IN",
"en-US",
"es-ES",
"es-MX",
"es-US",
"fr-CA",
"fr-FR",
"hi-IN",
"it-IT",
"ja-JP",
"pt-BR",
}
def name(self) -> str:
"""Return the Alexa API name of this interface."""
return "Alexa.ColorController"
def properties_supported(self) -> list[dict[str, str]]:
"""Return what properties this entity supports."""
return [{"name": "color"}]
def properties_proactively_reported(self) -> bool:
"""Return True if properties asynchronously reported."""
return True
def properties_retrievable(self) -> bool:
"""Return True if properties can be retrieved."""
return True
def get_property(self, name: str) -> Any:
"""Read and return a property."""
if name != "color":
raise UnsupportedProperty(name)
hue_saturation: tuple[float, float] | None
if (hue_saturation := self.entity.attributes.get(light.ATTR_HS_COLOR)) is None:
hue_saturation = (0, 0)
if (brightness := self.entity.attributes.get(light.ATTR_BRIGHTNESS)) is None:
brightness = 0
return {
"hue": hue_saturation[0],
"saturation": hue_saturation[1] / 100.0,
"brightness": brightness / 255.0,
}
class AlexaColorTemperatureController(AlexaCapability):
"""Implements Alexa.ColorTemperatureController.
https://developer.amazon.com/docs/device-apis/alexa-colortemperaturecontroller.html
"""
supported_locales = {
"de-DE",
"en-AU",
"en-CA",
"en-GB",
"en-IN",
"en-US",
"es-ES",
"es-MX",
"es-US",
"fr-CA",
"fr-FR",
"hi-IN",
"it-IT",
"ja-JP",
"pt-BR",
}
def name(self) -> str:
"""Return the Alexa API name of this interface."""
return "Alexa.ColorTemperatureController"
def properties_supported(self) -> list[dict[str, str]]:
"""Return what properties this entity supports."""
return [{"name": "colorTemperatureInKelvin"}]
def properties_proactively_reported(self) -> bool:
"""Return True if properties asynchronously reported."""
return True
def properties_retrievable(self) -> bool:
"""Return True if properties can be retrieved."""
return True
def get_property(self, name: str) -> Any:
"""Read and return a property."""
if name != "colorTemperatureInKelvin":
raise UnsupportedProperty(name)
if color_temp := self.entity.attributes.get("color_temp"):
return color_util.color_temperature_mired_to_kelvin(color_temp)
return None
class AlexaSpeaker(AlexaCapability):
"""Implements Alexa.Speaker.
https://developer.amazon.com/docs/device-apis/alexa-speaker.html
"""
supported_locales = {
"de-DE",
"en-AU",
"en-CA",
"en-GB",
"en-IN",
"en-US",
"es-ES",
"es-MX",
"fr-FR", # Not documented as of 2021-12-04, see PR #60489
"it-IT",
"ja-JP",
}
def name(self) -> str:
"""Return the Alexa API name of this interface."""
return "Alexa.Speaker"
def properties_supported(self) -> list[dict[str, str]]:
"""Return what properties this entity supports."""
properties = [{"name": "volume"}]
supported = self.entity.attributes.get(ATTR_SUPPORTED_FEATURES, 0)
if supported & media_player.MediaPlayerEntityFeature.VOLUME_MUTE:
properties.append({"name": "muted"})
return properties
def properties_proactively_reported(self) -> bool:
"""Return True if properties asynchronously reported."""
return True
def properties_retrievable(self) -> bool:
"""Return True if properties can be retrieved."""
return True
def get_property(self, name: str) -> Any:
"""Read and return a property."""
if name == "volume":
current_level = self.entity.attributes.get(
media_player.ATTR_MEDIA_VOLUME_LEVEL
)
if current_level is not None:
return round(float(current_level) * 100)
if name == "muted":
return bool(
self.entity.attributes.get(media_player.ATTR_MEDIA_VOLUME_MUTED)
)
return None
class AlexaStepSpeaker(AlexaCapability):
"""Implements Alexa.StepSpeaker.
https://developer.amazon.com/docs/device-apis/alexa-stepspeaker.html
"""
supported_locales = {
"de-DE",
"en-AU",
"en-CA",
"en-GB",
"en-IN",
"en-US",
"es-ES",
"fr-FR", # Not documented as of 2021-12-04, see PR #60489
"it-IT",
}
def name(self) -> str:
"""Return the Alexa API name of this interface."""
return "Alexa.StepSpeaker"
class AlexaPlaybackController(AlexaCapability):
"""Implements Alexa.PlaybackController.
https://developer.amazon.com/docs/device-apis/alexa-playbackcontroller.html
"""
supported_locales = {
"ar-SA",
"de-DE",
"en-AU",
"en-CA",
"en-GB",
"en-IN",
"en-US",
"es-ES",
"es-MX",
"es-US",
"fr-CA",
"fr-FR",
"hi-IN",
"it-IT",
"ja-JP",
"pt-BR",
}
def name(self) -> str:
"""Return the Alexa API name of this interface."""
return "Alexa.PlaybackController"
def supported_operations(self) -> list[str]:
"""Return the supportedOperations object.
Supported Operations: FastForward, Next, Pause, Play, Previous, Rewind,
StartOver, Stop
"""
supported_features = self.entity.attributes.get(ATTR_SUPPORTED_FEATURES, 0)
operations = {
media_player.MediaPlayerEntityFeature.NEXT_TRACK: "Next",
media_player.MediaPlayerEntityFeature.PAUSE: "Pause",
media_player.MediaPlayerEntityFeature.PLAY: "Play",
media_player.MediaPlayerEntityFeature.PREVIOUS_TRACK: "Previous",
media_player.MediaPlayerEntityFeature.STOP: "Stop",
}
return [
value
for operation, value in operations.items()
if operation & supported_features
]
class AlexaInputController(AlexaCapability):
"""Implements Alexa.InputController.
https://developer.amazon.com/docs/device-apis/alexa-inputcontroller.html
"""
supported_locales = {
"ar-SA",
"de-DE",
"en-AU",
"en-CA",
"en-GB",
"en-IN",
"en-US",
"es-ES",
"es-MX",
"es-US",
"fr-CA",
"fr-FR",
"hi-IN",
"it-IT",
"ja-JP",
"pt-BR",
}
def name(self) -> str:
"""Return the Alexa API name of this interface."""
return "Alexa.InputController"
def inputs(self) -> list[dict[str, str]] | None:
"""Return the list of valid supported inputs."""
source_list: list[Any] = self.entity.attributes.get(
media_player.ATTR_INPUT_SOURCE_LIST, []
)
return AlexaInputController.get_valid_inputs(source_list)
@staticmethod
def get_valid_inputs(source_list: list[Any]) -> list[dict[str, str]]:
"""Return list of supported inputs."""
input_list: list[dict[str, str]] = []
for source in source_list:
if not isinstance(source, str):
continue
formatted_source = (
source.lower().replace("-", "").replace("_", "").replace(" ", "")
)
if formatted_source in Inputs.VALID_SOURCE_NAME_MAP:
input_list.append(
{"name": Inputs.VALID_SOURCE_NAME_MAP[formatted_source]}
)
return input_list
class AlexaTemperatureSensor(AlexaCapability):
"""Implements Alexa.TemperatureSensor.
https://developer.amazon.com/docs/device-apis/alexa-temperaturesensor.html
"""
supported_locales = {
"ar-SA",
"de-DE",
"en-AU",
"en-CA",
"en-GB",
"en-IN",
"en-US",
"es-ES",
"es-MX",
"es-US",
"fr-CA",
"fr-FR",
"hi-IN",
"it-IT",
"ja-JP",
"pt-BR",
}
def __init__(self, hass: HomeAssistant, entity: State) -> None:
"""Initialize the entity."""
super().__init__(entity)
self.hass = hass
def name(self) -> str:
"""Return the Alexa API name of this interface."""
return "Alexa.TemperatureSensor"
def properties_supported(self) -> list[dict[str, str]]:
"""Return what properties this entity supports."""
return [{"name": "temperature"}]
def properties_proactively_reported(self) -> bool:
"""Return True if properties asynchronously reported."""
return True
def properties_retrievable(self) -> bool:
"""Return True if properties can be retrieved."""
return True
def get_property(self, name: str) -> Any:
"""Read and return a property."""
if name != "temperature":
raise UnsupportedProperty(name)
unit: str = self.entity.attributes.get(
ATTR_UNIT_OF_MEASUREMENT, self.hass.config.units.temperature_unit
)
temp: str | None = self.entity.state
if self.entity.domain == climate.DOMAIN:
unit = self.hass.config.units.temperature_unit
temp = self.entity.attributes.get(climate.ATTR_CURRENT_TEMPERATURE)
elif self.entity.domain == water_heater.DOMAIN:
unit = self.hass.config.units.temperature_unit
temp = self.entity.attributes.get(water_heater.ATTR_CURRENT_TEMPERATURE)
if temp is None or temp in (STATE_UNAVAILABLE, STATE_UNKNOWN):
return None
try:
temp_float = float(temp)
except ValueError:
_LOGGER.warning("Invalid temp value %s for %s", temp, self.entity.entity_id)
return None
# Alexa displays temperatures with one decimal digit, we don't need to do
# rounding for presentation here.
return {"value": temp_float, "scale": API_TEMP_UNITS[UnitOfTemperature(unit)]}
class AlexaContactSensor(AlexaCapability):
"""Implements Alexa.ContactSensor.
The Alexa.ContactSensor interface describes the properties and events used
to report the state of an endpoint that detects contact between two
surfaces. For example, a contact sensor can report whether a door or window
is open.
https://developer.amazon.com/docs/device-apis/alexa-contactsensor.html
"""
supported_locales = {
"de-DE",
"en-AU",
"en-CA",
"en-GB",
"en-IN",
"en-US",
"es-ES",
"es-MX",
"es-US",
"fr-CA",
"fr-FR",
"hi-IN",
"it-IT",
"ja-JP",
"pt-BR",
}
def __init__(self, hass: HomeAssistant, entity: State) -> None:
"""Initialize the entity."""
super().__init__(entity)
self.hass = hass
def name(self) -> str:
"""Return the Alexa API name of this interface."""
return "Alexa.ContactSensor"
def properties_supported(self) -> list[dict[str, str]]:
"""Return what properties this entity supports."""