Skip to content

Commit 69afcd7

Browse files
committed
Timeout improvements
1 parent 664eabc commit 69afcd7

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed

broadlink/device.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -70,13 +70,14 @@ def scan(
7070
packet[0x20] = checksum & 0xFF
7171
packet[0x21] = checksum >> 8
7272

73-
starttime = time.time()
73+
start_time = time.time()
7474
discovered = []
7575

7676
try:
77-
while (time.time() - starttime) < timeout:
77+
while (time.time() - start_time) < timeout:
78+
time_left = timeout - (time.time() - start_time)
79+
conn.settimeout(min(1, time_left))
7880
conn.sendto(packet, (discover_ip_address, discover_ip_port))
79-
conn.settimeout(1)
8081

8182
while True:
8283
try:
@@ -307,17 +308,21 @@ def send_packet(self, command: int, payload: bytes) -> bytes:
307308
packet[0x20] = checksum & 0xFF
308309
packet[0x21] = checksum >> 8
309310

310-
start_time = time.time()
311311
with self.lock:
312312
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as conn:
313+
timeout = self.timeout
314+
start_time = time.time()
315+
313316
while True:
317+
time_left = timeout - (time.time() - start_time)
318+
conn.settimeout(min(1, time_left))
319+
conn.sendto(packet, self.host)
320+
314321
try:
315-
conn.sendto(packet, self.host)
316-
conn.settimeout(1)
317-
resp, _ = conn.recvfrom(2048)
322+
resp = conn.recvfrom(2048)[0]
318323
break
319324
except socket.timeout:
320-
if (time.time() - start_time) > self.timeout:
325+
if (time.time() - start_time) > timeout:
321326
raise exception(-4000) # Network timeout.
322327

323328
if len(resp) < 0x30:

0 commit comments

Comments
 (0)