Skip to content

Commit 664eabc

Browse files
committed
Use context manager for connection
1 parent 330127b commit 664eabc

File tree

1 file changed

+10
-14
lines changed

1 file changed

+10
-14
lines changed

broadlink/device.py

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -309,20 +309,16 @@ def send_packet(self, command: int, payload: bytes) -> bytes:
309309

310310
start_time = time.time()
311311
with self.lock:
312-
conn = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
313-
conn.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
314-
315-
while True:
316-
try:
317-
conn.sendto(packet, self.host)
318-
conn.settimeout(1)
319-
resp, _ = conn.recvfrom(2048)
320-
break
321-
except socket.timeout:
322-
if (time.time() - start_time) > self.timeout:
323-
conn.close()
324-
raise exception(-4000) # Network timeout.
325-
conn.close()
312+
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as conn:
313+
while True:
314+
try:
315+
conn.sendto(packet, self.host)
316+
conn.settimeout(1)
317+
resp, _ = conn.recvfrom(2048)
318+
break
319+
except socket.timeout:
320+
if (time.time() - start_time) > self.timeout:
321+
raise exception(-4000) # Network timeout.
326322

327323
if len(resp) < 0x30:
328324
raise exception(-4007) # Length error.

0 commit comments

Comments
 (0)