|
| 1 | +""" |
| 2 | + zbnt/python-client |
| 3 | + Copyright (C) 2020 Oscar R. |
| 4 | +
|
| 5 | + This program is free software: you can redistribute it and/or modify |
| 6 | + it under the terms of the GNU General Public License as published by |
| 7 | + the Free Software Foundation, either version 3 of the License, or |
| 8 | + (at your option) any later version. |
| 9 | +
|
| 10 | + This program is distributed in the hope that it will be useful, |
| 11 | + but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | + GNU General Public License for more details. |
| 14 | +
|
| 15 | + You should have received a copy of the GNU General Public License |
| 16 | + along with this program. If not, see <https://www.gnu.org/licenses/>. |
| 17 | +""" |
| 18 | + |
| 19 | +import random |
| 20 | +import asyncio |
| 21 | +import netifaces |
| 22 | +import ipaddress |
| 23 | + |
| 24 | +from .MessageReceiver import * |
| 25 | + |
| 26 | +class DiscoveryClient(MessageReceiver): |
| 27 | + MSG_DISCOVERY_PORT = 5466 |
| 28 | + |
| 29 | + def __init__(self, address_list, on_device_discovered): |
| 30 | + super().__init__(self.send_broadcast, self.message_received, None) |
| 31 | + |
| 32 | + self.address_list = address_list |
| 33 | + self.on_device_discovered = on_device_discovered |
| 34 | + |
| 35 | + def datagram_received(self, data, addr): |
| 36 | + self.remote_addr = addr |
| 37 | + super().bytes_received(data) |
| 38 | + |
| 39 | + self.status = MsgRxStatus.MSG_RX_MAGIC |
| 40 | + self.buffer = b"\x00\x00\x00\x00" |
| 41 | + |
| 42 | + def send_broadcast(self): |
| 43 | + self.validator = random.randint(0, 2**64 - 1) |
| 44 | + |
| 45 | + message = MessageReceiver.MSG_MAGIC_IDENTIFIER |
| 46 | + message += Messages.MSG_ID_DISCOVERY.to_bytes(2, byteorder="little") |
| 47 | + message += b"\x08\x00" |
| 48 | + message += self.validator.to_bytes(8, byteorder="little") |
| 49 | + |
| 50 | + for address in self.address_list: |
| 51 | + self.transport.sendto(message, (address, DiscoveryClient.MSG_DISCOVERY_PORT)) |
| 52 | + |
| 53 | + def message_received(self, msg_id, msg_payload): |
| 54 | + if msg_id != Messages.MSG_ID_DISCOVERY or len(msg_payload) <= 67: |
| 55 | + return |
| 56 | + |
| 57 | + validator = int.from_bytes(msg_payload[0:8], byteorder='little', signed=False) |
| 58 | + |
| 59 | + if validator != self.validator: |
| 60 | + return |
| 61 | + |
| 62 | + device = dict() |
| 63 | + |
| 64 | + device["version"] = ( |
| 65 | + msg_payload[11], |
| 66 | + msg_payload[10], |
| 67 | + int.from_bytes(msg_payload[8:10], byteorder='little', signed=False), |
| 68 | + msg_payload[12:28].strip(b"\x00").decode("UTF-8"), |
| 69 | + msg_payload[28:44].strip(b"\x00").decode("UTF-8"), |
| 70 | + "d" if msg_payload[44] else "" |
| 71 | + ) |
| 72 | + |
| 73 | + device["versionstr"] = "{0}.{1}.{2}".format(*device["version"][0:3]) |
| 74 | + |
| 75 | + if len(device["version"][3]) != 0: |
| 76 | + device["versionstr"] += "-" + device["version"][3] |
| 77 | + |
| 78 | + if len(device["version"][4]) != 0: |
| 79 | + device["versionstr"] += "+" + device["version"][4] |
| 80 | + |
| 81 | + if len(device["version"][5]) != 0: |
| 82 | + device["versionstr"] += ".d" |
| 83 | + elif len(device["version"][5]) != 0: |
| 84 | + device["versionstr"] += "+d" |
| 85 | + |
| 86 | + msg_ip, _ = self.remote_addr |
| 87 | + ip4 = str(ipaddress.IPv4Address(msg_payload[48:44:-1])) |
| 88 | + ip6 = str(ipaddress.IPv6Address(msg_payload[49:65])) |
| 89 | + address_list = [] |
| 90 | + |
| 91 | + if ip4 != msg_ip: |
| 92 | + return |
| 93 | + |
| 94 | + if ip4 != "0.0.0.0": |
| 95 | + address_list.append(ip4) |
| 96 | + |
| 97 | + if ip6 != "::": |
| 98 | + address_list.append(ip6) |
| 99 | + |
| 100 | + if len(address_list) == 0: |
| 101 | + return |
| 102 | + |
| 103 | + device["address"] = address_list |
| 104 | + device["port"] = int.from_bytes(msg_payload[65:67], byteorder='little', signed=False) |
| 105 | + device["name"] = msg_payload[67:].decode("UTF-8") |
| 106 | + |
| 107 | + self.on_device_discovered(device) |
| 108 | + |
| 109 | + @staticmethod |
| 110 | + async def create(addr, callback): |
| 111 | + loop = asyncio.get_running_loop() |
| 112 | + |
| 113 | + _, protocol = await loop.create_datagram_endpoint( |
| 114 | + lambda: DiscoveryClient(addr, callback), |
| 115 | + remote_addr=None, |
| 116 | + family=socket.AF_INET, |
| 117 | + allow_broadcast=True |
| 118 | + ) |
| 119 | + |
| 120 | + return protocol |
| 121 | + |
| 122 | +async def discover_devices(timeout): |
| 123 | + address_list = [] |
| 124 | + device_list = [] |
| 125 | + |
| 126 | + # Get broadcast address of every available interface |
| 127 | + for iface in netifaces.interfaces(): |
| 128 | + for addr_family, addr_list in netifaces.ifaddresses(iface).items(): |
| 129 | + if netifaces.address_families[addr_family] == "AF_INET": |
| 130 | + for addr in addr_list: |
| 131 | + if "broadcast" in addr: |
| 132 | + address_list.append(addr["broadcast"]) |
| 133 | + |
| 134 | + # Broadcast DISCOVERY message on every interface |
| 135 | + await DiscoveryClient.create( |
| 136 | + address_list, |
| 137 | + lambda dev: device_list.append(dev) |
| 138 | + ) |
| 139 | + |
| 140 | + await asyncio.sleep(timeout) |
| 141 | + return device_list |
0 commit comments