|
| 1 | +# Copyright (c) 2019 Anki, Inc. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License in the file LICENSE.txt or at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +""" |
| 16 | +This contains the :class:`VectorMdns` class for discovering Vector (without already knowing |
| 17 | +the IP address) on a LAN (Local Area Network) over mDNS. |
| 18 | +
|
| 19 | +mDNS (multicast DNS) is a protocol for sending UDP packets containing a DNS query to all |
| 20 | +devices on your Local Area Network. If a device knows how to answer the DNS query, it |
| 21 | +will respond by multicasting a UDP packet containing the relevant DNS records. |
| 22 | +""" |
| 23 | +from threading import Condition |
| 24 | +import sys |
| 25 | + |
| 26 | + |
| 27 | +class VectorMdns: # pylint: disable=too-few-public-methods |
| 28 | + """`VectorMdns` provides a static method for discovering a Vector on the same LAN as |
| 29 | + the SDK program and retrieving its IP address. |
| 30 | + """ |
| 31 | + |
| 32 | + @staticmethod |
| 33 | + def find_vector(name: str, timeout=5): |
| 34 | + """ |
| 35 | + :param name: A name like `"Vector-A1B2"`. If :code:`None`, will search for any Vector. |
| 36 | + :param timeout: The discovery will timeout in :code:`timeout` seconds. Default value is :code:`5`. |
| 37 | + :returns: **dict** or **None** -- if Vector found, **dict** contains keys `"name"` and `"ipv4"` |
| 38 | +
|
| 39 | + .. testcode:: |
| 40 | +
|
| 41 | + import anki_vector |
| 42 | + vector_mdns = anki_vector.mdns.VectorMdns.find_vector("Vector-A1B2") |
| 43 | +
|
| 44 | + if vector_mdns is not None: |
| 45 | + print(vector_mdns['ipv4']) |
| 46 | + else: |
| 47 | + print("No Vector found on your local network!") |
| 48 | + """ |
| 49 | + |
| 50 | + # synchronously search for Vector for up to 5 seconds |
| 51 | + vector_name = name # should be like 'Vector-V3C7' |
| 52 | + return VectorMdns._start_mdns_listener(vector_name, timeout) |
| 53 | + |
| 54 | + @staticmethod |
| 55 | + def _start_mdns_listener(name, timeout): |
| 56 | + try: |
| 57 | + from zeroconf import ServiceBrowser, Zeroconf |
| 58 | + except ImportError: |
| 59 | + sys.exit("Cannot import from Zeroconf: Do `pip3 install --user zeroconf` to install") |
| 60 | + |
| 61 | + # create a Condition object and acquire the underlying lock |
| 62 | + cond = Condition() |
| 63 | + cond.acquire() |
| 64 | + |
| 65 | + # instantiate zeroconf and our MdnsListner object for listening to events |
| 66 | + zeroconf = Zeroconf() |
| 67 | + vector_fullname = None |
| 68 | + |
| 69 | + if name is not None: |
| 70 | + vector_fullname = name + ".local." |
| 71 | + |
| 72 | + listener = _MdnsListener(vector_fullname, cond) |
| 73 | + |
| 74 | + # browse for the _ankivector TCP MDNS service, sending events to our listener |
| 75 | + ServiceBrowser(zeroconf, "_ankivector._tcp.local.", listener) |
| 76 | + |
| 77 | + # block until 'timeout' seconds or until we discover vector |
| 78 | + cond.wait(timeout) |
| 79 | + |
| 80 | + # close zeroconf |
| 81 | + zeroconf.close() |
| 82 | + |
| 83 | + # return an IPv4 string (or None) |
| 84 | + if listener.ipv4 is None: |
| 85 | + return None |
| 86 | + |
| 87 | + return {'ipv4': listener.ipv4, 'name': listener.name} |
| 88 | + |
| 89 | + |
| 90 | +class _MdnsListener: |
| 91 | + """_MdnsListener is an internal helper class which listens for mDNS messages. |
| 92 | +
|
| 93 | + :param name_filter: A String to filter the mDNS responses by name (e.g., `"Vector-A1B2"`). |
| 94 | + :param condition: A Condition object to be used for signaling to caller when robot has been discovered. |
| 95 | + """ |
| 96 | + |
| 97 | + def __init__(self, name_filter: str, condition): |
| 98 | + self.name_filter = name_filter |
| 99 | + self.cond = condition |
| 100 | + self.ipv4 = None |
| 101 | + self.name = "" |
| 102 | + |
| 103 | + @staticmethod |
| 104 | + def _bytes_to_str_ipv4(ip_bytes): |
| 105 | + return str(ip_bytes[0]) + "." + \ |
| 106 | + str(ip_bytes[1]) + "." + \ |
| 107 | + str(ip_bytes[2]) + "." + \ |
| 108 | + str(ip_bytes[3]) |
| 109 | + |
| 110 | + def remove_service(self, zeroconf, mdns_type, name): |
| 111 | + # detect service removal |
| 112 | + pass |
| 113 | + |
| 114 | + def add_service(self, zeroconf, mdns_type, name): |
| 115 | + # detect service |
| 116 | + info = zeroconf.get_service_info(mdns_type, name) |
| 117 | + |
| 118 | + if (self.name_filter is None) or (info.server.lower() == self.name_filter.lower()): |
| 119 | + # found a match for our filter or there is no filter |
| 120 | + self.cond.acquire() |
| 121 | + self.ipv4 = _MdnsListener._bytes_to_str_ipv4(info.address) # info.address is IPv4 (DNS record type 'A') |
| 122 | + self.name = info.server |
| 123 | + |
| 124 | + # cause anything waiting for this condition to end waiting |
| 125 | + # and release so the other thread can continue |
| 126 | + self.cond.notify() |
| 127 | + self.cond.release() |
0 commit comments