Skip to content

Commit

Permalink
Lazy discovery on demand (#215)
Browse files Browse the repository at this point in the history
* Discover once vs. always. Just for testing.

* Discover the device again on failure. A discovery is required after power loss for example.

* Lazy discovery added.

* Lazy discovery enabled per default.
  • Loading branch information
syssi authored and rytilahti committed Feb 13, 2018
1 parent a675ef0 commit deb072c
Showing 1 changed file with 8 additions and 2 deletions.
10 changes: 8 additions & 2 deletions miio/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ class Device:
This class should not be initialized directly but a device-specific class inheriting
it should be used instead of it."""
def __init__(self, ip: str = None, token: str = None,
start_id: int=0, debug: int=0) -> None:
start_id: int=0, debug: int=0, lazy_discover: bool=True) -> None:
"""
Create a :class:`Device` instance.
:param ip: IP address or a hostname for the device
Expand All @@ -114,8 +114,10 @@ def __init__(self, ip: str = None, token: str = None,
if token is not None:
self.token = bytes.fromhex(token)
self.debug = debug
self.lazy_discover = lazy_discover

self._timeout = 5
self._discovered = False
self._device_ts = None # type: datetime.datetime
self.__id = start_id
self._device_id = None
Expand All @@ -133,6 +135,7 @@ def do_discover(self) -> Message:
if m is not None:
self._device_id = m.header.value.device_id
self._device_ts = m.header.value.ts
self._discovered = True
if self.debug > 1:
_LOGGER.debug(m)
_LOGGER.debug("Discovered %s with ts: %s, token: %s",
Expand Down Expand Up @@ -201,7 +204,9 @@ def send(self, command: str, parameters: Any=None, retry_count=3) -> Any:
:param dict parameters: Parameters to send, or an empty list FIXME
:param retry_count: How many times to retry in case of failure
:raises DeviceException: if an error has occured during communication."""
self.do_discover()

if not self.lazy_discover or not self._discovered:
self.do_discover()

cmd = {
"id": self._id,
Expand Down Expand Up @@ -264,6 +269,7 @@ def send(self, command: str, parameters: Any=None, retry_count=3) -> Any:
_LOGGER.warning("Retrying with incremented id, "
"retries left: %s", retry_count)
self.__id += 100
self._discovered = False
return self.send(command, parameters, retry_count - 1)
raise DeviceException("No response from the device") from ex

Expand Down

0 comments on commit deb072c

Please sign in to comment.