48
48
"""
49
49
import asyncio
50
50
import logging
51
+ from datetime import timedelta , datetime
51
52
52
53
from homeassistant .config_entries import SOURCE_IMPORT , ConfigEntry
53
54
from homeassistant .core import HomeAssistant
54
55
from homeassistant .const import (
56
+ CONF_DEVICE_ID ,
55
57
CONF_PLATFORM ,
56
58
CONF_ENTITIES ,
57
59
)
60
+ from homeassistant .helpers .event import async_track_time_interval
61
+ from homeassistant .helpers .dispatcher import async_dispatcher_send
58
62
59
63
from .const import DOMAIN , TUYA_DEVICE
60
64
from .config_flow import config_schema
63
67
_LOGGER = logging .getLogger (__name__ )
64
68
65
69
UNSUB_LISTENER = "unsub_listener"
70
+ UNSUB_TRACK = "unsub_track"
71
+
72
+ POLL_INTERVAL = 30
66
73
67
74
CONFIG_SCHEMA = config_schema ()
68
75
@@ -85,17 +92,43 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
85
92
"""Set up LocalTuya integration from a config entry."""
86
93
unsub_listener = entry .add_update_listener (update_listener )
87
94
95
+ device = TuyaDevice (entry .data )
96
+
97
+ def update_state (now ):
98
+ """Read device status and update platforms."""
99
+ status = None
100
+ try :
101
+ status = device .status ()
102
+ except Exception :
103
+ _LOGGER .exception ("update failed" )
104
+
105
+ signal = f"localtuya_{ entry .data [CONF_DEVICE_ID ]} "
106
+ async_dispatcher_send (hass , signal , status )
107
+
108
+ unsub_track = async_track_time_interval (
109
+ hass , update_state , timedelta (seconds = POLL_INTERVAL )
110
+ )
111
+
88
112
hass .data [DOMAIN ][entry .entry_id ] = {
89
113
UNSUB_LISTENER : unsub_listener ,
90
- TUYA_DEVICE : TuyaDevice (entry .data ),
114
+ UNSUB_TRACK : unsub_track ,
115
+ TUYA_DEVICE : device ,
91
116
}
92
117
93
- for entity in entry .data [CONF_ENTITIES ]:
94
- platform = entity [CONF_PLATFORM ]
95
- hass .async_create_task (
96
- hass .config_entries .async_forward_entry_setup (entry , platform )
118
+ async def setup_entities ():
119
+ await asyncio .gather (
120
+ * [
121
+ hass .config_entries .async_forward_entry_setup (
122
+ entry , entity [CONF_PLATFORM ]
123
+ )
124
+ for entity in entry .data [CONF_ENTITIES ]
125
+ ]
97
126
)
98
127
128
+ update_state (datetime .now ())
129
+
130
+ hass .async_create_task (setup_entities ())
131
+
99
132
return True
100
133
101
134
@@ -113,6 +146,7 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
113
146
)
114
147
115
148
hass .data [DOMAIN ][entry .entry_id ][UNSUB_LISTENER ]()
149
+ hass .data [DOMAIN ][entry .entry_id ][UNSUB_TRACK ]()
116
150
if unload_ok :
117
151
hass .data [DOMAIN ].pop (entry .entry_id )
118
152
0 commit comments