Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lazy discovery on demand #215

Merged
merged 4 commits into from
Feb 13, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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