From c3bb598e27d27ec1e86f8a83efa3f9a3d1887c17 Mon Sep 17 00:00:00 2001 From: Felipe Martins Diel Date: Sat, 9 Jan 2021 22:18:56 -0300 Subject: [PATCH] Timeout improvements (#464) - Only start to count the timer inside the lock. - Improve precision of the timeout option. - Use a context manager for the connection. - Remove SO_REUSEADDR option. Amend: Revert retry_intvl (#506) --- broadlink/device.py | 33 +++++++++++++++++---------------- broadlink/remote.py | 12 +++++++----- broadlink/sensor.py | 13 ++++++++++--- 3 files changed, 34 insertions(+), 24 deletions(-) diff --git a/broadlink/device.py b/broadlink/device.py index 5582209..6a0c2de 100644 --- a/broadlink/device.py +++ b/broadlink/device.py @@ -70,13 +70,14 @@ def scan( packet[0x20] = checksum & 0xFF packet[0x21] = checksum >> 8 - starttime = time.time() + start_time = time.time() discovered = [] try: - while (time.time() - starttime) < timeout: + while (time.time() - start_time) < timeout: + time_left = timeout - (time.time() - start_time) + conn.settimeout(min(1, time_left)) conn.sendto(packet, (discover_ip_address, discover_ip_port)) - conn.settimeout(1) while True: try: @@ -307,22 +308,22 @@ class device: packet[0x20] = checksum & 0xFF packet[0x21] = checksum >> 8 - start_time = time.time() with self.lock: - conn = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - conn.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as conn: + timeout = self.timeout + start_time = time.time() - while True: - try: + while True: + time_left = timeout - (time.time() - start_time) + conn.settimeout(min(1, time_left)) conn.sendto(packet, self.host) - conn.settimeout(1) - resp, _ = conn.recvfrom(2048) - break - except socket.timeout: - if (time.time() - start_time) > self.timeout: - conn.close() - raise exception(-4000) # Network timeout. - conn.close() + + try: + resp = conn.recvfrom(2048)[0] + break + except socket.timeout: + if (time.time() - start_time) > timeout: + raise exception(-4000) # Network timeout. if len(resp) < 0x30: raise exception(-4007) # Length error. diff --git a/broadlink/remote.py b/broadlink/remote.py index 88498b6..6cf32f2 100644 --- a/broadlink/remote.py +++ b/broadlink/remote.py @@ -58,7 +58,9 @@ class rm(device): def check_sensors(self) -> dict: """Return the state of the sensors.""" resp = self._send(0x1) - return {"temperature": resp[0x0] + resp[0x1] / 10.0} + temperature = struct.unpack(" dict: """Return the state of the sensors.""" resp = self._send(0x24) - return { - "temperature": resp[0x0] + resp[0x1] / 100.0, - "humidity": resp[0x2] + resp[0x3] / 100.0, - } + temperature = struct.unpack("