Skip to content

Commit 6d57740

Browse files
committed
Improve sub-devices connection process. rospogrigio#194
* Sub-device now will check the localkey of the gateway if it doesn't match it will raise an expectation.
1 parent 5302f85 commit 6d57740

File tree

1 file changed

+8
-9
lines changed

1 file changed

+8
-9
lines changed

custom_components/localtuya/coordinator.py

+8-9
Original file line numberDiff line numberDiff line change
@@ -119,10 +119,14 @@ async def get_gateway(self):
119119
return
120120
gateway: TuyaDevice
121121
node_host = self._device_config.host
122-
devices: dict = self._hass_entry.devices
122+
devices = self._hass_entry.devices
123123

124124
# Sub to gateway.
125125
if gateway := devices.get(node_host):
126+
# Ensure that sub-device still on the same gateway device.
127+
if gateway._local_key != self._local_key:
128+
raise Exception("Sub-device key doesn't match the gateway localkey")
129+
126130
self._gwateway = gateway
127131
gateway._sub_devices[self._node_id] = self
128132
return gateway
@@ -197,28 +201,23 @@ async def _make_connection(self):
197201
await self._interface.reset(reset_dpids, cid=self._node_id)
198202

199203
self.debug("Retrieving initial state")
200-
201204
# Usually we use status instead of detect_available_dps, but some device doesn't reports all dps when ask for status.
202205
status = await self._interface.detect_available_dps(cid=self._node_id)
203206
if status is None: # and not self.is_subdevice
204207
raise Exception("Failed to retrieve status")
208+
205209
self._interface.start_heartbeat()
206210
self.status_updated(status)
207211

208-
except UnicodeDecodeError as e:
209-
self.exception(f"Connect to {host} failed: due to: {type(e)}")
210-
await self.abort_connect()
211-
update_localkey = True
212-
except pytuya.DecodeError as derror:
213-
self.info(f"Initial update state failed {derror}, trying key update")
212+
except (UnicodeDecodeError, pytuya.DecodeError) as e:
213+
self.exception(f"Connect to {host} failed: due to {type(e)}: {e}")
214214
await self.abort_connect()
215215
update_localkey = True
216216
except Exception as e:
217217
if not (self._fake_gateway and "Not found" in str(e)):
218218
e = "Sub device is not connected" if self.is_subdevice else e
219219
self.warning(f"Connect to {host} failed: {e}")
220220
await self.abort_connect()
221-
update_localkey = True
222221
except:
223222
if self._fake_gateway:
224223
self.warning(f"Failed to use {name} as gateway.")

0 commit comments

Comments
 (0)