-
Notifications
You must be signed in to change notification settings - Fork 0
/
switch.py
92 lines (67 loc) · 2.4 KB
/
switch.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
from collections import OrderedDict
from .coolkit_client.device import CoolkitDeviceSwitch
from .coolkit_client import CoolkitDevicesRepository
from homeassistant.components.switch import SwitchDevice, DOMAIN
from homeassistant.const import STATE_ON, STATE_OFF
from homeassistant.core import HomeAssistant
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .coolkit_client import CoolkitDevice
async def async_setup_platform(
hass: HomeAssistant,
config: OrderedDict,
async_add_entities,
discovery_info=None
):
ha_entities = []
devices = CoolkitDevicesRepository.get_devices()
for device in devices.values():
for i in range(0, len(device.switches)):
ha_entities.append(SonoffSwitch(device, i))
async_add_entities(ha_entities, update_before_add=False)
class SonoffSwitch(SwitchDevice):
_state = True
def __init__(self, device: 'CoolkitDevice', index: int):
self._index = index
self._device = device
self._switch: CoolkitDeviceSwitch = self._device.switches[self._index]
self._switch.add_state_callback(
callback_name='hass',
callable=self._on_state_change
)
async def _on_state_change(
self,
switch: CoolkitDeviceSwitch,
new_state: bool
) -> None:
self._state = new_state
await self.async_update_ha_state()
@property
def entity_id(self) -> str:
if len(self._device.switches) > 1:
return DOMAIN + '.sonoff_' + self._device.device_id + '_' + str(self._index + 1)
else:
return DOMAIN + '.sonoff_' + self._device.device_id
@property
def available(self) -> bool:
return self._device.is_online
@property
def name(self) -> str:
if len(self._device.switches) > 1:
return self._device.name + ' ' + str(self._index + 1)
else:
return self._device.name
@property
def should_poll(self) -> bool:
return True
@property
def is_on(self) -> bool:
return self._switch.get_state()
@property
def state(self) -> str:
"""Return the state."""
return STATE_ON if self.is_on else STATE_OFF
async def async_turn_on(self, **kwargs) -> None:
await self._switch.set_state(True)
async def async_turn_off(self, **kwargs) -> None:
await self._switch.set_state(False)