diff --git a/broadlink/__init__.py b/broadlink/__init__.py index 5253d7c..2910e16 100644 --- a/broadlink/__init__.py +++ b/broadlink/__init__.py @@ -138,6 +138,7 @@ def discover(timeout=None, local_ip_address=None, discover_ip_address='255.255.2 name = responsepacket[0x40:].split(b'\x00')[0].decode('utf-8') cloud = bool(responsepacket[-1]) device = gendevice(devtype, host, mac, name=name, cloud=cloud) + cs.close() return device while (time.time() - starttime) < timeout: @@ -145,6 +146,7 @@ def discover(timeout=None, local_ip_address=None, discover_ip_address='255.255.2 try: response = cs.recvfrom(1024) except socket.timeout: + cs.close() return devices responsepacket = bytearray(response[0]) host = response[1] @@ -154,6 +156,7 @@ def discover(timeout=None, local_ip_address=None, discover_ip_address='255.255.2 cloud = bool(responsepacket[-1]) device = gendevice(devtype, host, mac, name=name, cloud=cloud) devices.append(device) + cs.close() return devices @@ -169,10 +172,6 @@ class device: self.iv = bytearray( [0x56, 0x2e, 0x17, 0x99, 0x6d, 0x09, 0x3d, 0x28, 0xdd, 0xb3, 0xba, 0x69, 0x5a, 0x2e, 0x6f, 0x58]) self.id = bytearray([0, 0, 0, 0]) - self.cs = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - self.cs.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - self.cs.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) - self.cs.bind(('', 0)) self.type = "Unknown" self.lock = threading.Lock() @@ -290,15 +289,20 @@ class device: start_time = time.time() with self.lock: + cs = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + cs.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + while True: try: - self.cs.sendto(packet, self.host) - self.cs.settimeout(1) - response = self.cs.recvfrom(2048) + cs.sendto(packet, self.host) + cs.settimeout(1) + response = cs.recvfrom(2048) break except socket.timeout: if (time.time() - start_time) > self.timeout: raise + finally: + cs.close() return bytearray(response[0]) @@ -1116,3 +1120,4 @@ def setup(ssid, password, security_mode): sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) sock.sendto(payload, ('255.255.255.255', 80)) + sock.close()