Пример #1
0
    def test_integration_with_listener_class(self):

        service_added = Event()
        service_removed = Event()
        service_updated = Event()

        subtype_name = u"My special Subtype"
        type_ = u"_http._tcp.local."
        subtype = subtype_name + u"._sub." + type_
        name = u"xxxyyy"
        registration_name = u"%s.%s" % (name, subtype)

        class MyListener(object):
            def add_service(self, zeroconf, type, name):
                zeroconf.get_service_info(type, name)
                service_added.set()

            def remove_service(self, zeroconf, type, name):
                service_removed.set()

        class MySubListener(r.ServiceListener):
            def add_service(self, zeroconf, type, name):
                pass

            def remove_service(self, zeroconf, type, name):
                pass

            def update_service(self, zeroconf, type, name):
                service_updated.set()

        listener = MyListener()
        zeroconf_browser = Zeroconf(interfaces=["127.0.0.1"])
        zeroconf_browser.add_service_listener(subtype, listener)

        properties = dict(
            prop_none=None,
            prop_string=b"a_prop",
            prop_float=1.0,
            prop_blank=b"a blanked string",
            prop_true=1,
            prop_false=0,
        )

        zeroconf_registrar = Zeroconf(interfaces=["127.0.0.1"])
        desc = {"path": "/~paulsm/"}
        desc.update(properties)
        info_service = ServiceInfo(
            subtype,
            registration_name,
            socket.inet_aton("10.0.1.2"),
            80,
            0,
            0,
            desc,
            "ash-2.local.",
        )
        zeroconf_registrar.register_service(info_service)

        try:
            service_added.wait(1)
            assert service_added.is_set()

            # short pause to allow multicast timers to expire
            time.sleep(3)

            # clear the answer cache to force query
            for record in zeroconf_browser.cache.entries():
                zeroconf_browser.cache.remove(record)

            # get service info without answer cache
            info = zeroconf_browser.get_service_info(type_, registration_name)

            assert info.properties[b"prop_none"] is False
            assert info.properties[b"prop_string"] == properties["prop_string"]
            assert info.properties[b"prop_float"] is False
            assert info.properties[b"prop_blank"] == properties["prop_blank"]
            assert info.properties[b"prop_true"] is True
            assert info.properties[b"prop_false"] is False

            info = zeroconf_browser.get_service_info(subtype,
                                                     registration_name)
            assert info.properties[b"prop_none"] is False

            # Begin material test addition
            sublistener = MySubListener()
            zeroconf_browser.add_service_listener(registration_name,
                                                  sublistener)
            properties["prop_blank"] = b"an updated string"
            desc.update(properties)
            info_service = ServiceInfo(
                subtype,
                registration_name,
                socket.inet_aton("10.0.1.2"),
                80,
                0,
                0,
                desc,
                "ash-2.local.",
            )
            zeroconf_registrar.update_service(info_service)
            service_updated.wait(2)
            assert service_updated.is_set()

            info = zeroconf_browser.get_service_info(type_, registration_name)
            assert info is not None
            assert info.properties[b"prop_blank"] == properties["prop_blank"]
            # End material test addition

            zeroconf_registrar.unregister_service(info_service)
            service_removed.wait(2)
            assert service_removed.is_set()

        finally:
            zeroconf_registrar.close()
            zeroconf_browser.remove_service_listener(listener)
            zeroconf_browser.close()
Пример #2
0
    def test_integration_with_listener_class(self):

        service_added = Event()
        service_removed = Event()
        service_updated = Event()

        subtype_name = "My special Subtype"
        type_ = "_http._tcp.local."
        subtype = subtype_name + "._sub." + type_
        name = "xxxyyyæøå"
        registration_name = "%s.%s" % (name, subtype)

        class MyListener(r.ServiceListener):
            def add_service(self, zeroconf, type, name):
                zeroconf.get_service_info(type, name)
                service_added.set()

            def remove_service(self, zeroconf, type, name):
                service_removed.set()

        class MySubListener(r.ServiceListener):
            def add_service(self, zeroconf, type, name):
                pass

            def remove_service(self, zeroconf, type, name):
                pass

            def update_service(self, zeroconf, type, name):
                service_updated.set()

        listener = MyListener()
        zeroconf_browser = Zeroconf(interfaces=['127.0.0.1'])
        zeroconf_browser.add_service_listener(subtype, listener)

        properties = dict(
            prop_none=None,
            prop_string=b'a_prop',
            prop_float=1.0,
            prop_blank=b'a blanked string',
            prop_true=1,
            prop_false=0,
        )

        zeroconf_registrar = Zeroconf(interfaces=['127.0.0.1'])
        desc = {'path': '/~paulsm/'}  # type: r.ServicePropertiesType
        desc.update(properties)
        addresses = [socket.inet_aton("10.0.1.2")]
        if socket.has_ipv6:
            addresses.append(socket.inet_pton(socket.AF_INET6, "2001:db8::1"))
        info_service = ServiceInfo(
            subtype, registration_name, port=80, properties=desc, server="ash-2.local.", addresses=addresses
        )
        zeroconf_registrar.register_service(info_service)

        try:
            service_added.wait(1)
            assert service_added.is_set()

            # short pause to allow multicast timers to expire
            time.sleep(3)

            # clear the answer cache to force query
            for record in zeroconf_browser.cache.entries():
                zeroconf_browser.cache.remove(record)

            # get service info without answer cache
            info = zeroconf_browser.get_service_info(type_, registration_name)
            assert info is not None
            assert info.properties[b'prop_none'] is False
            assert info.properties[b'prop_string'] == properties['prop_string']
            assert info.properties[b'prop_float'] is False
            assert info.properties[b'prop_blank'] == properties['prop_blank']
            assert info.properties[b'prop_true'] is True
            assert info.properties[b'prop_false'] is False
            assert info.addresses == addresses[:1]  # no V6 by default
            all_addresses = info.addresses_by_version(r.IPVersion.All)
            assert all_addresses == addresses, all_addresses

            info = zeroconf_browser.get_service_info(subtype, registration_name)
            assert info is not None
            assert info.properties[b'prop_none'] is False

            # Begin material test addition
            sublistener = MySubListener()
            zeroconf_browser.add_service_listener(registration_name, sublistener)
            properties['prop_blank'] = b'an updated string'
            desc.update(properties)
            info_service = ServiceInfo(
                subtype, registration_name, socket.inet_aton("10.0.1.2"), 80, 0, 0, desc, "ash-2.local."
            )
            zeroconf_registrar.update_service(info_service)
            service_updated.wait(1)
            assert service_updated.is_set()

            info = zeroconf_browser.get_service_info(type_, registration_name)
            assert info is not None
            assert info.properties[b'prop_blank'] == properties['prop_blank']
            # End material test addition

            zeroconf_registrar.unregister_service(info_service)
            service_removed.wait(1)
            assert service_removed.is_set()

        finally:
            zeroconf_registrar.close()
            zeroconf_browser.remove_service_listener(listener)
            zeroconf_browser.close()
Пример #3
0
class SonoffLANModeDeviceMock:
    def __init__(self, name, sonoff_type, api_key, ip, port, error_mock=None):

        self._name = name
        self._sonoff_type = sonoff_type
        self._api_key = api_key
        self._ip = ip
        self._port = port
        self._error_code = 0

        if self._name is None:
            self._name = ""

        print("Device __init__ %s" % self._name)

        if self._sonoff_type is None:
            self._sonoff_type = "plug"

        if self._api_key == "None" or self._api_key is None:
            print("No Encryption")
            self._encrypt = False
        else:
            self._encrypt = True

        if self._ip is None:
            self._ip = "127.0.0.1"

        if self._port is None:
            global next_port
            self._port = next_port
            next_port += 1

        self._status = "off"

        self.register()

        self.mock_error(error_mock)

    def mock_error(self, error_mock):

        if error_mock == "Disconnect":

            def disconnect():
                self.disconnect()

            self._p = threading.Thread(target=disconnect)
            self._p.start()

        elif error_mock == "Reconnect":

            def reconnect():
                self.reconnect()

            self._p = threading.Thread(target=reconnect)
            self._p.start()

    def reconnect(self):

        try:
            print("....waiting")

            time.sleep(5)

            print("....deregister")

            self._error_code = 0
            self.deregister()

            time.sleep(5)

            print("....register")

            self.register()

        except Exception as Ex:
            print(Ex)

    def disconnect(self):

        try:
            print("....waiting")

            time.sleep(5)

            print("....deregister")

            self._error_code = 500
            self.deregister()

            time.sleep(5)

            print("....register")

            self.register()

        except Exception as Ex:
            print(Ex)

    def run_server(self):

        api = Flask(self._name)

        @api.route("/zeroconf/switch", methods=["POST"])
        @api.route("/zeroconf/switches", methods=["POST"])
        # pylint: disable=unused-variable
        def post_switch():

            try:

                print("Device %s, Received: %s" % (self._name, request.json))

                if request.json["deviceid"] == self._name:
                    self.process_request(request.json)

                    return (
                        json.dumps({
                            "seq": 1,
                            "sequence": "1577725767",
                            "error": 0
                        }),
                        200,
                    )

                else:
                    print("wrong device")
                    abort(404)

            except Exception as Ex:
                print(Ex)
                abort(500)

        @api.route("/zeroconf/signal_strength", methods=["POST"])
        # pylint: disable=unused-variable
        def post_signal():

            print("Device %s, Received: %s" % (self._name, request.json))

            if request.json["deviceid"] == self._name:

                if self._error_code != 0:
                    abort(self._error_code)

                else:

                    return (
                        json.dumps({
                            "seq": 1,
                            "sequence": "1577725767",
                            "error": 0
                        }),
                        200,
                    )

            else:
                print("wrong device")
                abort(404)

        def start():
            api.run(host=self._ip, port=self._port)

        print("starting device: %s" % self._name)
        t = threading.Thread(target=start)
        t.daemon = True
        t.start()
        print("device started: %s" % self._name)

    def register(self):

        self._properties = dict(
            id=self._name,
            type=self._sonoff_type,
        )

        self.set_data()
        self._zeroconf_registrar = Zeroconf(interfaces=[self._ip])
        self._zeroconf_registrar.register_service(self.get_service_info())

    def deregister(self):

        self._zeroconf_registrar.unregister_service(self.get_service_info())

    def get_service_info(self):

        type_ = "_ewelink._tcp.local."
        registration_name = "eWeLink_%s.%s" % (self._name, type_)

        service_info = ServiceInfo(
            type_,
            registration_name,
            socket.inet_aton(self._ip),
            port=self._port,
            properties=self._properties,
            server="eWeLink_" + self._name + ".local.",
        )

        return service_info

    def set_data(self):

        if self._sonoff_type == "strip":

            data = (
                '{"sledOnline":"on",'
                '"configure":['
                '{"startup":"off","outlet":0},{"startup":"off","outlet":1},'
                '{"startup":"off","outlet":2},{"startup":"off","outlet":3}],'
                '"pulses":['
                '{"pulse":"off","width":1000,"outlet":0},'
                '{"pulse":"off","width":1000,"outlet":1},'
                '{"pulse":"off","width":1000,"outlet":2},'
                '{"pulse":"off","width":1000,"outlet":3}],')

            if self._status == "on":
                data += ('"switches":[{"switch":"on","outlet":0},'
                         '{"switch":"off","outlet":1},{"switch":"off",'
                         '"outlet":2},{"switch":"on","outlet":3}]}')

            else:
                data += ('"switches":[{"switch":"off","outlet":0},'
                         '{"switch":"off","outlet":1},'
                         '{"switch":"off","outlet":2},'
                         '{"switch":"on","outlet":3}]}')

        else:

            if self._status == "on":
                data = ('{"switch":"on","startup":"stay","pulse":"off",'
                        '"sledOnline":"off","pulseWidth":500,"rssi":-55}')
            else:
                data = ('{"switch":"off","startup":"stay","pulse":"off",'
                        '"sledOnline":"off","pulseWidth":500,"rssi":-55}')

        if self._encrypt:
            data = sonoffcrypto.format_encryption_txt(self._properties, data,
                                                      self._api_key)

        self.split_data(data)

    def split_data(self, data):

        if len(data) <= 249:
            self._properties["data1"] = data

        else:
            self._properties["data1"] = data[0:249]
            data = data[249:]

            if len(data) <= 249:
                self._properties["data2"] = data

            else:
                self._properties["data2"] = data[0:249]
                data = data[249:]

                if len(data) <= 249:
                    self._properties["data3"] = data

                else:
                    self._properties["data3"] = data[0:249]
                    self._properties["data4"] = data[249:]

    def get_status_from_data(self, data):

        if self._sonoff_type == "strip":
            return data["switches"][0]["switch"]

        else:
            return data["switch"]

    def process_request(self, json_):

        if json_["encrypt"] is True:
            iv = json_["iv"]
            data = sonoffcrypto.decrypt(json_["data"], iv, self._api_key)
            import json

            data = json.loads(data.decode("utf-8"))

        else:
            print(json_)
            data = json_["data"]

        print(data)

        self._status = self.get_status_from_data(data)
        self.set_data()

        print("Updated Properties: %s" % self._properties)

        self._zeroconf_registrar.update_service(self.get_service_info())
Пример #4
0
    def test_integration_with_listener_class(self):

        service_added = Event()
        service_removed = Event()
        service_updated = Event()
        service_updated2 = Event()

        subtype_name = "My special Subtype"
        type_ = "_http._tcp.local."
        subtype = subtype_name + "._sub." + type_
        name = "UPPERxxxyyyæøå"
        registration_name = "%s.%s" % (name, subtype)

        class MyListener(r.ServiceListener):
            def add_service(self, zeroconf, type, name):
                zeroconf.get_service_info(type, name)
                service_added.set()

            def remove_service(self, zeroconf, type, name):
                service_removed.set()

            def update_service(self, zeroconf, type, name):
                service_updated2.set()

        class MySubListener(r.ServiceListener):
            def add_service(self, zeroconf, type, name):
                pass

            def remove_service(self, zeroconf, type, name):
                pass

            def update_service(self, zeroconf, type, name):
                service_updated.set()

        listener = MyListener()
        zeroconf_browser = Zeroconf(interfaces=['127.0.0.1'])
        zeroconf_browser.add_service_listener(subtype, listener)

        properties = dict(
            prop_none=None,
            prop_string=b'a_prop',
            prop_float=1.0,
            prop_blank=b'a blanked string',
            prop_true=1,
            prop_false=0,
        )

        zeroconf_registrar = Zeroconf(interfaces=['127.0.0.1'])
        desc = {'path': '/~paulsm/'}  # type: Dict
        desc.update(properties)
        addresses = [socket.inet_aton("10.0.1.2")]
        if has_working_ipv6() and not os.environ.get('SKIP_IPV6'):
            addresses.append(socket.inet_pton(socket.AF_INET6, "6001:db8::1"))
            addresses.append(socket.inet_pton(socket.AF_INET6, "2001:db8::1"))
        info_service = ServiceInfo(
            subtype, registration_name, port=80, properties=desc, server="ash-2.local.", addresses=addresses
        )
        zeroconf_registrar.register_service(info_service)

        try:
            service_added.wait(1)
            assert service_added.is_set()

            # short pause to allow multicast timers to expire
            time.sleep(3)

            # clear the answer cache to force query
            _clear_cache(zeroconf_browser)

            cached_info = ServiceInfo(type_, registration_name)
            cached_info.load_from_cache(zeroconf_browser)
            assert cached_info.properties == {}

            # get service info without answer cache
            info = zeroconf_browser.get_service_info(type_, registration_name)
            assert info is not None
            assert info.properties[b'prop_none'] is None
            assert info.properties[b'prop_string'] == properties['prop_string']
            assert info.properties[b'prop_float'] == b'1.0'
            assert info.properties[b'prop_blank'] == properties['prop_blank']
            assert info.properties[b'prop_true'] == b'1'
            assert info.properties[b'prop_false'] == b'0'
            assert info.addresses == addresses[:1]  # no V6 by default
            assert set(info.addresses_by_version(r.IPVersion.All)) == set(addresses)

            cached_info = ServiceInfo(type_, registration_name)
            cached_info.load_from_cache(zeroconf_browser)
            assert cached_info.properties is not None

            # Populate the cache
            zeroconf_browser.get_service_info(subtype, registration_name)

            # get service info with only the cache
            cached_info = ServiceInfo(subtype, registration_name)
            cached_info.load_from_cache(zeroconf_browser)
            assert cached_info.properties is not None
            assert cached_info.properties[b'prop_float'] == b'1.0'

            # get service info with only the cache with the lowercase name
            cached_info = ServiceInfo(subtype, registration_name.lower())
            cached_info.load_from_cache(zeroconf_browser)
            # Ensure uppercase output is preserved
            assert cached_info.name == registration_name
            assert cached_info.key == registration_name.lower()
            assert cached_info.properties is not None
            assert cached_info.properties[b'prop_float'] == b'1.0'

            info = zeroconf_browser.get_service_info(subtype, registration_name)
            assert info is not None
            assert info.properties is not None
            assert info.properties[b'prop_none'] is None

            cached_info = ServiceInfo(subtype, registration_name.lower())
            cached_info.load_from_cache(zeroconf_browser)
            assert cached_info.properties is not None
            assert cached_info.properties[b'prop_none'] is None

            # test TXT record update
            sublistener = MySubListener()
            zeroconf_browser.add_service_listener(registration_name, sublistener)
            properties['prop_blank'] = b'an updated string'
            desc.update(properties)
            info_service = ServiceInfo(
                subtype,
                registration_name,
                80,
                0,
                0,
                desc,
                "ash-2.local.",
                addresses=[socket.inet_aton("10.0.1.2")],
            )
            zeroconf_registrar.update_service(info_service)
            service_updated.wait(1)
            assert service_updated.is_set()

            info = zeroconf_browser.get_service_info(type_, registration_name)
            assert info is not None
            assert info.properties[b'prop_blank'] == properties['prop_blank']

            cached_info = ServiceInfo(subtype, registration_name)
            cached_info.load_from_cache(zeroconf_browser)
            assert cached_info.properties is not None
            assert cached_info.properties[b'prop_blank'] == properties['prop_blank']

            zeroconf_registrar.unregister_service(info_service)
            service_removed.wait(1)
            assert service_removed.is_set()

        finally:
            zeroconf_registrar.close()
            zeroconf_browser.remove_service_listener(listener)
            zeroconf_browser.close()
Пример #5
0
class ZeroconfPublisher(object):
    def __init__(self, address, host, port, service_name, service_type=XPRA_MDNS_TYPE, text_dict=None):
        log("ZeroconfPublisher%s", (address, host, port, service_name, service_type, text_dict))
        self.address = address
        self.host = host
        self.port = port
        self.zeroconf = None
        self.service = None
        self.args = None
        self.registered = False
        try:
            #ie: service_name = localhost.localdomain :2 (ssl)
            parts = service_name.split(" ", 1)
            regname = parts[0].split(".")[0]
            if len(parts)==2:
                regname += parts[1]
            regname = regname.replace(":", "-")
            regname = regname.replace(" ", "-")
            regname = regname.replace("(", "")
            regname = regname.replace(")", "")
            #ie: regname = localhost:2-ssl
            st = service_type+"local."
            regname += "."+st
            td = self.txt_rec(text_dict or {})
            self.args = (st, regname, self.address, port, 0, 0, td)
            service = ServiceInfo(*self.args)
            log("ServiceInfo%s=%s", self.args, service)
            self.service = service
        except Exception as e:
            log("zeroconf ServiceInfo", exc_info=True)
            log.error(" for port %i", port)
            log.error(" %s", e)

    def start(self):
        try:
            self.zeroconf = Zeroconf(interfaces=[self.host])
        except OSError:
            log("start()", exc_info=True)
            log.error("Error: failed to create Zeroconf instance for address '%s'", self.host)
            return
        try:
            self.zeroconf.register_service(self.service)
        except Exception:
            log("start failed on %s", self.service, exc_info=True)
        else:
            self.registered = True

    def stop(self):
        log("ZeroConfPublishers.stop(): %s", self.service)
        if self.registered:
            self.zeroconf.unregister_service(self.service)
        self.zeroconf = None

    def txt_rec(self, text_dict):
        #prevent zeroconf from mangling our ints into booleans:
        from collections import OrderedDict
        new_dict = OrderedDict()
        for k,v in text_dict.items():
            if isinstance(v, int):
                new_dict[k] = str(v)
            else:
                new_dict[k] = v
        return new_dict

    def update_txt(self, txt):
        args = list(self.args)
        args[6] = self.txt_rec(txt)
        self.args = tuple(args)
        si = ServiceInfo(*self.args)
        try:
            self.zeroconf.update_service(si)
            self.service = si
        except KeyError as e:
            #probably a race condition with cleanup
            log("update_txt(%s)", txt, exc_info=True)
            log.warn("Warning: failed to update service")
            log.warn(" %s", e)
        except Exception:
            log.error("Error: failed to update service", exc_info=True)
Пример #6
0
    def test_integration_with_listener_class(self):

        service_added = Event()
        service_removed = Event()
        service_updated = Event()

        subtype_name = "My special Subtype"
        type_ = "_http._tcp.local."
        subtype = subtype_name + "._sub." + type_
        name = "xxxyyyæøå"
        registration_name = "%s.%s" % (name, subtype)

        class MyListener(r.ServiceListener):
            def add_service(self, zeroconf, type, name):
                zeroconf.get_service_info(type, name)
                service_added.set()

            def remove_service(self, zeroconf, type, name):
                service_removed.set()

        class MySubListener(r.ServiceListener):
            def add_service(self, zeroconf, type, name):
                pass

            def remove_service(self, zeroconf, type, name):
                pass

            def update_service(self, zeroconf, type, name):
                service_updated.set()

        listener = MyListener()
        zeroconf_browser = Zeroconf(interfaces=['127.0.0.1'])
        zeroconf_browser.add_service_listener(subtype, listener)

        properties = dict(
            prop_none=None,
            prop_string=b'a_prop',
            prop_float=1.0,
            prop_blank=b'a blanked string',
            prop_true=1,
            prop_false=0,
        )

        zeroconf_registrar = Zeroconf(interfaces=['127.0.0.1'])
        desc = {'path': '/~paulsm/'}  # type: r.ServicePropertiesType
        desc.update(properties)
        info_service = ServiceInfo(
            subtype, registration_name, socket.inet_aton("10.0.1.2"), 80, 0, 0, desc, "ash-2.local."
        )
        zeroconf_registrar.register_service(info_service)

        try:
            service_added.wait(1)
            assert service_added.is_set()

            # short pause to allow multicast timers to expire
            time.sleep(3)

            # clear the answer cache to force query
            for record in zeroconf_browser.cache.entries():
                zeroconf_browser.cache.remove(record)

            # get service info without answer cache
            info = zeroconf_browser.get_service_info(type_, registration_name)
            assert info is not None
            assert info.properties[b'prop_none'] is False
            assert info.properties[b'prop_string'] == properties['prop_string']
            assert info.properties[b'prop_float'] is False
            assert info.properties[b'prop_blank'] == properties['prop_blank']
            assert info.properties[b'prop_true'] is True
            assert info.properties[b'prop_false'] is False

            info = zeroconf_browser.get_service_info(subtype, registration_name)
            assert info is not None
            assert info.properties[b'prop_none'] is False

            # Begin material test addition
            sublistener = MySubListener()
            zeroconf_browser.add_service_listener(registration_name, sublistener)
            properties['prop_blank'] = b'an updated string'
            desc.update(properties)
            info_service = ServiceInfo(
                subtype, registration_name, socket.inet_aton("10.0.1.2"), 80, 0, 0, desc, "ash-2.local."
            )
            zeroconf_registrar.update_service(info_service)
            service_updated.wait(1)
            assert service_updated.is_set()

            info = zeroconf_browser.get_service_info(type_, registration_name)
            assert info is not None
            assert info.properties[b'prop_blank'] == properties['prop_blank']
            # End material test addition

            zeroconf_registrar.unregister_service(info_service)
            service_removed.wait(1)
            assert service_removed.is_set()

        finally:
            zeroconf_registrar.close()
            zeroconf_browser.remove_service_listener(listener)
            zeroconf_browser.close()
Пример #7
0
class AccessoryDriver:
    """
    An AccessoryDriver mediates between incoming requests from the HAPServer and
    the Accessory.

    The driver starts and stops the HAPServer, the mDNS advertisements and responds
    to events from the HAPServer.
    """
    def __init__(self,
                 *,
                 address=None,
                 port=51234,
                 persist_file="accessory.state",
                 pincode=None,
                 encoder=None,
                 loader=None,
                 loop=None,
                 mac=None,
                 listen_address=None,
                 advertised_address=None,
                 interface_choice=None,
                 zeroconf_instance=None):
        """
        Initialize a new AccessoryDriver object.

        :param pincode: The pincode that HAP clients must prove they know in order
            to pair with this `Accessory`. Defaults to None, in which case a random
            pincode is generated. The pincode has the format "xxx-xx-xxx", where x is
            a digit.
        :type pincode: bytearray

        :param port: The local port on which the accessory will be accessible.
            In other words, this is the port of the HAPServer.
        :type port: int

        :param address: The local address on which the accessory will be accessible.
            In other words, this is the address of the HAPServer. If not given, the
            driver will try to select an address.
        :type address: str

        :param persist_file: The file name in which the state of the accessory
            will be persisted. This uses `expandvars`, so may contain `~` to
            refer to the user's home directory.
        :type persist_file: str

        :param encoder: The encoder to use when persisting/loading the Accessory state.
        :type encoder: AccessoryEncoder

        :param mac: The MAC address which will be used to identify the accessory.
            If not given, the driver will try to select a MAC address.
        :type mac: str

        :param listen_address: The local address on the HAPServer will listen.
            If not given, the value of the address parameter will be used.
        :type listen_address: str

        :param advertised_address: The address of the HAPServer announced via mDNS.
            This can be used to announce an external address from behind a NAT.
            If not given, the value of the address parameter will be used.
        :type advertised_address: str

        :param interface_choice: The zeroconf interfaces to listen on.
        :type InterfacesType: [InterfaceChoice.Default, InterfaceChoice.All]

        :param zeroconf_instance: A Zeroconf instance. When running multiple accessories or
            bridges a single zeroconf instance can be shared to avoid the overhead
            of processing the same data multiple times.
        """
        if loop is None:
            if sys.platform == "win32":
                loop = asyncio.ProactorEventLoop()
            else:
                loop = asyncio.new_event_loop()

            executor_opts = {"max_workers": None}
            if sys.version_info >= (3, 6):
                executor_opts["thread_name_prefix"] = "SyncWorker"

            self.executor = ThreadPoolExecutor(**executor_opts)
            loop.set_default_executor(self.executor)
            self.tid = threading.current_thread()
        else:
            self.tid = threading.main_thread()
            self.executor = None

        self.loop = loop

        self.accessory = None
        if zeroconf_instance is not None:
            self.advertiser = zeroconf_instance
        elif interface_choice is not None:
            self.advertiser = Zeroconf(interfaces=interface_choice)
        else:
            self.advertiser = Zeroconf()
        self.persist_file = os.path.expanduser(persist_file)
        self.encoder = encoder or AccessoryEncoder()
        self.topics = {}  # topic: set of (address, port) of subscribed clients
        self.loader = loader or Loader()
        self.aio_stop_event = None
        self.stop_event = threading.Event()

        self.safe_mode = False

        self.mdns_service_info = None
        self.srp_verifier = None

        address = address or util.get_local_address()
        advertised_address = advertised_address or address
        self.state = State(address=advertised_address,
                           mac=mac,
                           pincode=pincode,
                           port=port)

        listen_address = listen_address or address
        network_tuple = (listen_address, self.state.port)
        self.http_server = HAPServer(network_tuple, self)

    def start(self):
        """Start the event loop and call `start_service`.

        Pyhap will be stopped gracefully on a KeyBoardInterrupt.
        """
        try:
            logger.info("Starting the event loop")
            if threading.current_thread() is threading.main_thread():
                logger.debug("Setting child watcher")
                watcher = asyncio.SafeChildWatcher()
                watcher.attach_loop(self.loop)
                asyncio.set_child_watcher(watcher)
            else:
                logger.debug(
                    "Not setting a child watcher. Set one if "
                    "subprocesses will be started outside the main thread.")
            self.add_job(self.async_start())
            self.loop.run_forever()
        except KeyboardInterrupt:
            logger.debug("Got a KeyboardInterrupt, stopping driver")
            self.loop.call_soon_threadsafe(self.loop.create_task,
                                           self.async_stop())
            self.loop.run_forever()
        finally:
            self.loop.close()
            logger.info("Closed the event loop")

    def start_service(self):
        """Start the service."""
        self._validate_start()
        self.add_job(self.async_start)

    def _validate_start(self):
        """Validate we can start."""
        if self.accessory is None:
            raise ValueError("You must assign an accessory to the driver, "
                             "before you can start it.")

    async def async_start(self):
        """Starts the accessory.

        - Call the accessory's run method.
        - Start handling accessory events.
        - Start the HAP server.
        - Publish a mDNS advertisement.
        - Print the setup QR code if the accessory is not paired.

        All of the above are started in separate threads. Accessory thread is set as
        daemon.
        """
        self._validate_start()
        self.aio_stop_event = asyncio.Event()

        logger.info(
            "Starting accessory %s on address %s, port %s.",
            self.accessory.display_name,
            self.state.address,
            self.state.port,
        )

        # Start listening for requests
        logger.debug("Starting server.")
        await self.http_server.async_start(self.loop)

        # Advertise the accessory as a mDNS service.
        logger.debug("Starting mDNS.")
        self.mdns_service_info = AccessoryMDNSServiceInfo(
            self.accessory, self.state)
        await self.loop.run_in_executor(None, self.advertiser.register_service,
                                        self.mdns_service_info)

        # Print accessory setup message
        if not self.state.paired:
            self.accessory.setup_message()

        # Start the accessory so it can do stuff.
        logger.debug("Starting accessory %s", self.accessory.display_name)
        self.add_job(self.accessory.run)
        logger.debug("AccessoryDriver for %s started successfully",
                     self.accessory.display_name)

    def stop(self):
        """Method to stop pyhap."""
        self.add_job(self.async_stop)

    async def async_stop(self):
        """Stops the AccessoryDriver and shutdown all remaining tasks."""
        await self.async_add_job(self._do_stop)
        logger.debug("Stopping HAP server and event sending")

        self.aio_stop_event.set()

        self.http_server.async_stop()

        logger.info(
            "Stopping accessory %s on address %s, port %s.",
            self.accessory.display_name,
            self.state.address,
            self.state.port,
        )

        await self.async_add_job(self.accessory.stop)

        logger.debug("AccessoryDriver for %s stopped successfully",
                     self.accessory.display_name)

        # Executor=None means a loop wasn't passed in
        if self.executor is not None:
            logger.debug("Shutdown executors")
            self.executor.shutdown()
            self.loop.stop()

        logger.debug("Stop completed")

    def _do_stop(self):
        """Stop the mDNS and set the stop event."""
        logger.debug("Setting stop events, stopping accessory")
        self.stop_event.set()

        logger.debug("Stopping mDNS advertising for %s",
                     self.accessory.display_name)
        self.advertiser.unregister_service(self.mdns_service_info)
        self.advertiser.close()

    def add_job(self, target, *args):
        """Add job to executor pool."""
        if target is None:
            raise ValueError("Don't call add_job with None.")
        self.loop.call_soon_threadsafe(self.async_add_job, target, *args)

    @util.callback
    def async_add_job(self, target, *args):
        """Add job from within the event loop."""
        task = None

        if asyncio.iscoroutine(target):
            task = self.loop.create_task(target)
        elif util.is_callback(target):
            self.loop.call_soon(target, *args)
        elif util.iscoro(target):
            task = self.loop.create_task(target(*args))
        else:
            task = self.loop.run_in_executor(None, target, *args)

        return task

    def add_accessory(self, accessory):
        """Add top level accessory to driver."""
        self.accessory = accessory
        if accessory.aid is None:
            accessory.aid = STANDALONE_AID
        elif accessory.aid != STANDALONE_AID:
            raise ValueError("Top-level accessory must have the AID == 1.")
        if os.path.exists(self.persist_file):
            logger.info("Loading Accessory state from `%s`", self.persist_file)
            self.load()
        else:
            logger.info("Storing Accessory state in `%s`", self.persist_file)
            self.persist()

    @util.callback
    def async_subscribe_client_topic(self, client, topic, subscribe=True):
        """(Un)Subscribe the given client from the given topic.

        This method must be run in the event loop.

        :param client: A client (address, port) tuple that should be subscribed.
        :type client: tuple <str, int>

        :param topic: The topic to which to subscribe.
        :type topic: str

        :param subscribe: Whether to subscribe or unsubscribe the client. Both subscribing
            an already subscribed client and unsubscribing a client that is not subscribed
            do nothing.
        :type subscribe: bool
        """
        if subscribe:
            subscribed_clients = self.topics.get(topic)
            if subscribed_clients is None:
                subscribed_clients = set()
                self.topics[topic] = subscribed_clients
            subscribed_clients.add(client)
            return

        if topic not in self.topics:
            return
        subscribed_clients = self.topics[topic]
        subscribed_clients.discard(client)
        if not subscribed_clients:
            del self.topics[topic]

    def connection_lost(self, client):
        """Called when a connection is lost to a client.

        This method must be run in the event loop.

        :param client: A client (address, port) tuple that should be unsubscribed.
        :type client: tuple <str, int>
        """
        client_topics = []
        for topic, subscribed_clients in self.topics.items():
            if client in subscribed_clients:
                # Make a copy to avoid changing
                # self.topics during iteration
                client_topics.append(topic)

        for topic in client_topics:
            self.async_subscribe_client_topic(client, topic, subscribe=False)

    def publish(self, data, sender_client_addr=None):
        """Publishes an event to the client.

        The publishing occurs only if the current client is subscribed to the topic for
        the aid and iid contained in the data.

        :param data: The data to publish. It must at least contain the keys "aid" and
            "iid".
        :type data: dict
        """
        topic = get_topic(data[HAP_REPR_AID], data[HAP_REPR_IID])
        if topic not in self.topics:
            return

        data = {HAP_REPR_CHARS: [data]}
        bytedata = json.dumps(data).encode()

        if threading.current_thread() == self.tid:
            self.async_send_event(topic, bytedata, sender_client_addr)
            return

        self.loop.call_soon_threadsafe(self.async_send_event, topic, bytedata,
                                       sender_client_addr)

    def async_send_event(self, topic, bytedata, sender_client_addr):
        """Send an event to a client.

        Must be called in the event loop
        """
        if self.aio_stop_event.is_set():
            return

        subscribed_clients = self.topics.get(topic, [])
        logger.debug(
            "Send event: topic(%s), data(%s), sender_client_addr(%s)",
            topic,
            bytedata,
            sender_client_addr,
        )
        unsubs = []
        for client_addr in subscribed_clients:
            if sender_client_addr and sender_client_addr == client_addr:
                logger.debug(
                    "Skip sending event to client since "
                    "its the client that made the characteristic change: %s",
                    client_addr,
                )
                continue
            logger.debug("Sending event to client: %s", client_addr)
            pushed = self.http_server.push_event(bytedata, client_addr)
            if not pushed:
                logger.debug(
                    "Could not send event to %s, probably stale socket.",
                    client_addr)
                unsubs.append(client_addr)
                # Maybe consider removing the client_addr from every topic?

        for client_addr in unsubs:
            self.async_subscribe_client_topic(client_addr, topic, False)

    def config_changed(self):
        """Notify the driver that the accessory's configuration has changed.

        Persists the accessory, so that the new configuration is available on
        restart. Also, updates the mDNS advertisement, so that iOS clients know they need
        to fetch new data.
        """
        self.state.config_version += 1
        if self.state.config_version > MAX_CONFIG_VERSION:
            self.state.config_version = 1
        self.persist()
        self.update_advertisement()

    def update_advertisement(self):
        """Updates the mDNS service info for the accessory."""
        logger.debug("Updating mDNS advertisement")
        self.mdns_service_info = AccessoryMDNSServiceInfo(
            self.accessory, self.state)
        self.advertiser.update_service(self.mdns_service_info)

    @callback
    def async_persist(self):
        """Saves the state of the accessory.

        Must be run in the event loop.
        """
        loop = asyncio.get_event_loop()
        asyncio.ensure_future(loop.run_in_executor(None, self.persist))

    def persist(self):
        """Saves the state of the accessory.

        Must run in executor.
        """
        tmp_filename = None
        try:
            temp_dir = os.path.dirname(self.persist_file)
            with tempfile.NamedTemporaryFile(mode="w",
                                             dir=temp_dir,
                                             delete=False) as file_handle:
                tmp_filename = file_handle.name
                self.encoder.persist(file_handle, self.state)
            os.replace(tmp_filename, self.persist_file)
        finally:
            if tmp_filename and os.path.exists(tmp_filename):
                os.remove(tmp_filename)

    def load(self):
        """Load the persist file.

        Must run in executor.
        """
        with open(self.persist_file, "r") as file_handle:
            self.encoder.load_into(file_handle, self.state)

    @callback
    def pair(self, client_uuid, client_public):
        """Called when a client has paired with the accessory.

        Persist the new accessory state.

        :param client_uuid: The client uuid.
        :type client_uuid: uuid.UUID

        :param client_public: The client's public key.
        :type client_public: bytes

        :return: Whether the pairing is successful.
        :rtype: bool
        """
        logger.info("Paired with %s.", client_uuid)
        self.state.add_paired_client(client_uuid, client_public)
        self.async_persist()
        return True

    @callback
    def unpair(self, client_uuid):
        """Removes the paired client from the accessory.

        Persist the new accessory state.

        :param client_uuid: The client uuid.
        :type client_uuid: uuid.UUID
        """
        logger.info("Unpairing client %s.", client_uuid)
        self.state.remove_paired_client(client_uuid)
        self.async_persist()

    def finish_pair(self):
        """Finishing pairing or unpairing.

        Updates the accessory and updates the mDNS service.

        The mDNS announcement must not be updated until AFTER
        the final pairing response is sent or homekit will
        see that the accessory is already paired and assume
        it should stop pairing.
        """
        # Safe mode added to avoid error during pairing, see
        # https://github.com/home-assistant/home-assistant/issues/14567
        #
        # This may no longer be needed now that we defer
        # updating the advertisement until after the final
        # pairing response is sent.
        #
        if not self.safe_mode:
            self.update_advertisement()

    def setup_srp_verifier(self):
        """Create an SRP verifier for the accessory's info."""
        # TODO: Move the below hard-coded values somewhere nice.
        ctx = get_srp_context(3072, hashlib.sha512, 16)
        verifier = SrpServer(ctx, b"Pair-Setup", self.state.pincode)
        self.srp_verifier = verifier

    def get_accessories(self):
        """Returns the accessory in HAP format.

        :return: An example HAP representation is:

        .. code-block:: python

           {
              "accessories": [
                 "aid": 1,
                 "services": [
                    "iid": 1,
                    "type": ...,
                    "characteristics": [{
                       "iid": 2,
                       "type": ...,
                       "description": "CurrentTemperature",
                       ...
                    }]
                 ]
              ]
           }

        :rtype: dict
        """
        hap_rep = self.accessory.to_HAP()
        if not isinstance(hap_rep, list):
            hap_rep = [
                hap_rep,
            ]
        logger.debug("Get accessories response: %s", hap_rep)
        return {HAP_REPR_ACCS: hap_rep}

    def get_characteristics(self, char_ids):
        """Returns values for the required characteristics.

        :param char_ids: A list of characteristic "paths", e.g. "1.2" is aid 1, iid 2.
        :type char_ids: list<str>

        :return: Status success for each required characteristic. For example:

        .. code-block:: python

           {
              "characteristics: [{
                 "aid": 1,
                 "iid": 2,
                 "status" 0
              }]
           }

        :rtype: dict
        """
        chars = []
        for aid_iid in char_ids:
            aid, iid = (int(i) for i in aid_iid.split("."))
            rep = {
                HAP_REPR_AID: aid,
                HAP_REPR_IID: iid,
                HAP_REPR_STATUS:
                HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE,
            }

            try:
                if aid == STANDALONE_AID:
                    char = self.accessory.iid_manager.get_obj(iid)
                    available = True
                else:
                    acc = self.accessory.accessories.get(aid)
                    if acc is None:
                        continue
                    available = acc.available
                    char = acc.iid_manager.get_obj(iid)

                if available:
                    rep[HAP_REPR_VALUE] = char.get_value()
                    rep[HAP_REPR_STATUS] = HAP_SERVER_STATUS.SUCCESS
            except CharacteristicError:
                logger.error("Error getting value for characteristic %s.", id)
            except Exception:  # pylint: disable=broad-except
                logger.exception(
                    "Unexpected error getting value for characteristic %s.",
                    id)

            chars.append(rep)
        logger.debug("Get chars response: %s", chars)
        return {HAP_REPR_CHARS: chars}

    def set_characteristics(self, chars_query, client_addr):
        """Called from ``HAPServerHandler`` when iOS configures the characteristics.

        :param chars_query: A configuration query. For example:

        .. code-block:: python

           {
              "characteristics": [{
                 "aid": 1,
                 "iid": 2,
                 "value": False, # Value to set
                 "ev": True # (Un)subscribe for events from this characteristics.
              }]
           }

        :type chars_query: dict
        """
        # TODO: Add support for chars that do no support notifications.
        accessory_callbacks = {}
        setter_results = {}
        had_error = False

        for cq in chars_query[HAP_REPR_CHARS]:
            aid, iid = cq[HAP_REPR_AID], cq[HAP_REPR_IID]
            setter_results.setdefault(aid, {})
            char = self.accessory.get_characteristic(aid, iid)

            if HAP_PERMISSION_NOTIFY in cq:
                char_topic = get_topic(aid, iid)
                logger.debug("Subscribed client %s to topic %s", client_addr,
                             char_topic)
                self.async_subscribe_client_topic(client_addr, char_topic,
                                                  cq[HAP_PERMISSION_NOTIFY])

            if HAP_REPR_VALUE not in cq:
                continue

            value = cq[HAP_REPR_VALUE]

            try:
                char.client_update_value(value, client_addr)
            except Exception:  # pylint: disable=broad-except
                logger.exception(
                    "%s: Error while setting characteristic %s to %s",
                    client_addr,
                    char.display_name,
                    value,
                )
                setter_results[aid][
                    iid] = HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE
                had_error = True
            else:
                setter_results[aid][iid] = HAP_SERVER_STATUS.SUCCESS

            # For some services we want to send all the char value
            # changes at once.  This resolves an issue where we send
            # ON and then BRIGHTNESS and the light would go to 100%
            # and then dim to the brightness because each callback
            # would only send one char at a time.
            if not char.service or not char.service.setter_callback:
                continue

            services = accessory_callbacks.setdefault(aid, {})

            if char.service.display_name not in services:
                services[char.service.display_name] = {
                    SERVICE_CALLBACK: char.service.setter_callback,
                    SERVICE_CHARS: {},
                    SERVICE_IIDS: [],
                }

            service_data = services[char.service.display_name]
            service_data[SERVICE_CHARS][char.display_name] = value
            service_data[SERVICE_IIDS].append(iid)

        for aid, services in accessory_callbacks.items():
            for service_name, service_data in services.items():
                try:
                    service_data[SERVICE_CALLBACK](service_data[SERVICE_CHARS])
                except Exception:  # pylint: disable=broad-except
                    logger.exception(
                        "%s: Error while setting characteristics to %s for the %s service",
                        service_data[SERVICE_CHARS],
                        client_addr,
                        service_name,
                    )
                    set_result = HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE
                    had_error = True
                else:
                    set_result = HAP_SERVER_STATUS.SUCCESS

                for iid in service_data[SERVICE_IIDS]:
                    setter_results[aid][iid] = set_result

        if not had_error:
            return None

        return {
            HAP_REPR_CHARS: [{
                HAP_REPR_AID: aid,
                HAP_REPR_IID: iid,
                HAP_REPR_STATUS: status,
            } for aid, iid_status in setter_results.items()
                             for iid, status in iid_status.items()]
        }

    def signal_handler(self, _signal, _frame):
        """Stops the AccessoryDriver for a given signal.

        An AccessoryDriver can be registered as a signal handler with this method. For
        example, you can register it for a KeyboardInterrupt as follows:
        >>> import signal
        >>> signal.signal(signal.SIGINT, anAccDriver.signal_handler)

        Now, when the user hits Ctrl+C, the driver will stop its accessory, the HAP server
        and everything else that needs stopping and will exit gracefully.
        """
        try:
            self.stop()
        except Exception as e:
            logger.error("Could not stop AccessoryDriver because of error: %s",
                         e)
            raise
Пример #8
0
class ZeroconfPublisher:
    def __init__(self,
                 address,
                 host,
                 port,
                 service_name,
                 service_type=XPRA_MDNS_TYPE,
                 text_dict=None):
        log("ZeroconfPublisher%s",
            (address, host, port, service_name, service_type, text_dict))
        self.address = address
        self.host = host
        self.port = port
        self.zeroconf = None
        self.service = None
        self.args = ()
        self.kwargs = {}
        self.registered = False
        try:
            #ie: service_name = localhost.localdomain :2 (ssl)
            parts = service_name.split(" ", 1)
            regname = parts[0].split(".")[0]
            if len(parts) == 2:
                regname += parts[1]
            regname = regname.replace(":", "-")
            regname = regname.replace(" ", "-")
            regname = regname.replace("(", "")
            regname = regname.replace(")", "")
            #ie: regname = localhost:2-ssl
            st = service_type + "local."
            regname += "." + st
            td = self.txt_rec(text_dict or {})
            if zeroconf_version < "0.23":
                self.args = (st, regname, self.address, port, 0, 0, td)
            else:
                self.kwargs = {
                    "type_": st,  #_xpra._tcp.local.
                    "name": regname,
                    "port": port,
                    "properties": td,
                    "addresses": [self.address],
                }
            service = ServiceInfo(*self.args, **self.kwargs)
            log("ServiceInfo(%s, %s)=%s", self.args, self.kwargs, service)
            self.service = service
        except Exception as e:
            log("zeroconf ServiceInfo", exc_info=True)
            log.error(" for port %i", port)
            log.error(" %s", e)

    def start(self):
        try:
            self.zeroconf = Zeroconf(interfaces=[self.host])
        except OSError:
            log("start()", exc_info=True)
            log.error(
                "Error: failed to create Zeroconf instance for address '%s'",
                self.host)
            return
        try:
            self.zeroconf.register_service(self.service)
        except Exception:
            log("start failed on %s", self.service, exc_info=True)
        else:
            self.registered = True

    def stop(self):
        log("ZeroConfPublishers.stop(): %s", self.service)
        if self.registered:
            self.zeroconf.unregister_service(self.service)
        self.zeroconf = None

    def txt_rec(self, text_dict):
        #prevent zeroconf from mangling our ints into booleans:
        new_dict = {}
        for k, v in text_dict.items():
            if isinstance(v, int):
                new_dict[k] = str(v)
            else:
                new_dict[k] = v
        return new_dict

    def update_txt(self, txt):
        if not hasattr(self.zeroconf, "update_service"):
            log("no update_service with zeroconf version %s", zeroconf_version)
            return
        props = self.txt_rec(txt)
        if self.args:
            args = list(self.args)
            args[6] = props
            self.args = tuple(args)
        else:
            self.kwargs["properties"] = props
        si = ServiceInfo(*self.args, **self.kwargs)
        try:
            self.zeroconf.update_service(si)
            self.service = si
        except KeyError as e:
            #probably a race condition with cleanup
            log("update_txt(%s)", txt, exc_info=True)
            log.warn("Warning: failed to update service")
            log.warn(" %s", e)
        except Exception:
            log.error("Error: failed to update service", exc_info=True)
Пример #9
0
class MusicAssistant:
    """Main MusicAssistant object."""

    def __init__(self, datapath: str, debug: bool = False, port: int = 8095) -> None:
        """
        Create an instance of MusicAssistant.

            :param datapath: file location to store the data
        """

        self._exit = False
        self._loop = None
        self._debug = debug
        self._http_session = None
        self._event_listeners = []
        self._providers = {}
        self._background_tasks = None

        # init core managers/controllers
        self._config = ConfigManager(self, datapath)
        self._database = DatabaseManager(self)
        self._cache = Cache(self)
        self._metadata = MetaDataManager(self)
        self._web = WebServer(self, port)
        self._music = MusicManager(self)
        self._library = LibraryManager(self)
        self._players = PlayerManager(self)
        self._streams = StreamManager(self)
        # shared zeroconf instance
        self.zeroconf = Zeroconf(interfaces=InterfaceChoice.All)

    async def start(self) -> None:
        """Start running the music assistant server."""
        # initialize loop
        self._loop = asyncio.get_event_loop()
        self._loop.set_exception_handler(global_exception_handler)
        self._loop.set_debug(self._debug)
        # create shared aiohttp ClientSession
        self._http_session = aiohttp.ClientSession(
            loop=self.loop,
            connector=aiohttp.TCPConnector(enable_cleanup_closed=True, ssl=False),
        )
        # run migrations if needed
        await check_migrations(self)
        await self._config.setup()
        await self._cache.setup()
        await self._music.setup()
        await self._players.setup()
        await self._preload_providers()
        await self.setup_discovery()
        await self._web.setup()
        await self._library.setup()
        self.loop.create_task(self.__process_background_tasks())

    async def stop(self) -> None:
        """Stop running the music assistant server."""
        self._exit = True
        LOGGER.info("Application shutdown")
        self.signal_event(EVENT_SHUTDOWN)
        await self.config.close()
        await self._web.stop()
        for prov in self._providers.values():
            await prov.on_stop()
        await self._players.close()
        await self._http_session.connector.close()
        self._http_session.detach()

    @property
    def loop(self) -> asyncio.AbstractEventLoop:
        """Return the running event loop."""
        return self._loop

    @property
    def exit(self) -> bool:
        """Return bool if the main process is exiting."""
        return self._exit

    @property
    def players(self) -> PlayerManager:
        """Return the Players controller/manager."""
        return self._players

    @property
    def music(self) -> MusicManager:
        """Return the Music controller/manager."""
        return self._music

    @property
    def library(self) -> LibraryManager:
        """Return the Library controller/manager."""
        return self._library

    @property
    def config(self) -> ConfigManager:
        """Return the Configuration controller/manager."""
        return self._config

    @property
    def cache(self) -> Cache:
        """Return the Cache instance."""
        return self._cache

    @property
    def streams(self) -> StreamManager:
        """Return the Streams controller/manager."""
        return self._streams

    @property
    def database(self) -> DatabaseManager:
        """Return the Database controller/manager."""
        return self._database

    @property
    def metadata(self) -> MetaDataManager:
        """Return the Metadata controller/manager."""
        return self._metadata

    @property
    def web(self) -> WebServer:
        """Return the webserver instance."""
        return self._web

    @property
    def http_session(self) -> aiohttp.ClientSession:
        """Return the default http session."""
        return self._http_session

    async def register_provider(self, provider: Provider) -> None:
        """Register a new Provider/Plugin."""
        assert provider.id and provider.name
        if provider.id in self._providers:
            LOGGER.debug("Provider %s is already registered.", provider.id)
            return
        provider.mass = self  # make sure we have the mass object
        provider.available = False
        self._providers[provider.id] = provider
        if self.config.get_provider_config(provider.id, provider.type)[CONF_ENABLED]:
            if await provider.on_start() is not False:
                provider.available = True
                LOGGER.debug("Provider registered: %s", provider.name)
                self.signal_event(EVENT_PROVIDER_REGISTERED, provider.id)
            else:
                LOGGER.debug(
                    "Provider registered but loading failed: %s", provider.name
                )
        else:
            LOGGER.debug("Not loading provider %s as it is disabled", provider.name)

    async def unregister_provider(self, provider_id: str) -> None:
        """Unregister an existing Provider/Plugin."""
        if provider_id in self._providers:
            # unload it if it's loaded
            await self._providers[provider_id].on_stop()
            LOGGER.debug("Provider unregistered: %s", provider_id)
            self.signal_event(EVENT_PROVIDER_UNREGISTERED, provider_id)
        return self._providers.pop(provider_id, None)

    async def reload_provider(self, provider_id: str) -> None:
        """Reload an existing Provider/Plugin."""
        provider = await self.unregister_provider(provider_id)
        if provider is not None:
            # simply re-register the same provider again
            await self.register_provider(provider)
        else:
            # try preloading all providers
            self.add_job(self._preload_providers())

    @callback
    def get_provider(self, provider_id: str) -> Provider:
        """Return provider/plugin by id."""
        if provider_id not in self._providers:
            LOGGER.warning("Provider %s is not available", provider_id)
            return None
        return self._providers[provider_id]

    @callback
    def get_providers(
        self,
        filter_type: Optional[ProviderType] = None,
        include_unavailable: bool = False,
    ) -> Tuple[Provider]:
        """Return all providers, optionally filtered by type."""
        return tuple(
            item
            for item in self._providers.values()
            if (filter_type is None or item.type == filter_type)
            and (include_unavailable or item.available)
        )

    @callback
    def signal_event(self, event_msg: str, event_details: Any = None) -> None:
        """
        Signal (systemwide) event.

            :param event_msg: the eventmessage to signal
            :param event_details: optional details to send with the event.
        """
        for cb_func, event_filter in self._event_listeners:
            if not event_filter or event_msg in event_filter:
                self.add_job(cb_func, event_msg, event_details)

    @callback
    def add_event_listener(
        self,
        cb_func: Callable[..., Union[None, Awaitable]],
        event_filter: Union[None, str, Tuple] = None,
    ) -> Callable:
        """
        Add callback to event listeners.

        Returns function to remove the listener.
            :param cb_func: callback function or coroutine
            :param event_filter: Optionally only listen for these events
        """
        listener = (cb_func, event_filter)
        self._event_listeners.append(listener)

        def remove_listener():
            self._event_listeners.remove(listener)

        return remove_listener

    @callback
    def add_background_task(self, task: Coroutine):
        """Add a coroutine/task to the end of the job queue."""
        if self._background_tasks is None:
            self._background_tasks = asyncio.Queue()
        self._background_tasks.put_nowait(task)

    @callback
    def add_job(
        self, target: Callable[..., Any], *args: Any, **kwargs: Any
    ) -> Optional[asyncio.Task]:
        """Add a job/task to the event loop.

        target: target to call.
        args: parameters for method to call.
        """
        task = None

        # Check for partials to properly determine if coroutine function
        check_target = target
        while isinstance(check_target, functools.partial):
            check_target = check_target.func

        if threading.current_thread() is not threading.main_thread():
            # called from other thread
            if asyncio.iscoroutine(check_target):
                task = asyncio.run_coroutine_threadsafe(target, self.loop)  # type: ignore
            elif asyncio.iscoroutinefunction(check_target):
                task = asyncio.run_coroutine_threadsafe(
                    target(*args, **kwargs), self.loop
                )
            elif is_callback(check_target):
                task = self.loop.call_soon_threadsafe(target, *args, **kwargs)
            else:
                task = self.loop.run_in_executor(None, target, *args, **kwargs)  # type: ignore
        else:
            # called from mainthread
            if asyncio.iscoroutine(check_target):
                task = self.loop.create_task(target)  # type: ignore
            elif asyncio.iscoroutinefunction(check_target):
                task = self.loop.create_task(target(*args, **kwargs))
            elif is_callback(check_target):
                task = self.loop.call_soon(target, *args, *kwargs)
            else:
                task = self.loop.run_in_executor(None, target, *args, *kwargs)  # type: ignore
        return task

    async def __process_background_tasks(self):
        """Background tasks that takes care of slowly handling jobs in the queue."""
        if self._background_tasks is None:
            self._background_tasks = asyncio.Queue()
        while not self.exit:
            task = await self._background_tasks.get()
            await task
            if self._background_tasks.qsize() > 200:
                await asyncio.sleep(0.5)
            elif self._background_tasks.qsize() == 0:
                await asyncio.sleep(10)
            else:
                await asyncio.sleep(1)

    async def setup_discovery(self) -> None:
        """Make this Music Assistant instance discoverable on the network."""

        def _setup_discovery():
            zeroconf_type = "_music-assistant._tcp.local."

            info = ServiceInfo(
                zeroconf_type,
                name=f"{self.web.server_id}.{zeroconf_type}",
                addresses=[get_ip_pton()],
                port=self.web.port,
                properties=self.web.discovery_info,
                server=f"mass_{self.web.server_id}.local.",
            )
            LOGGER.debug("Starting Zeroconf broadcast...")
            try:
                existing = getattr(self, "mass_zc_service_set", None)
                if existing:
                    self.zeroconf.update_service(info)
                else:
                    self.zeroconf.register_service(info)
                setattr(self, "mass_zc_service_set", True)
            except NonUniqueNameException:
                LOGGER.error(
                    "Music Assistant instance with identical name present in the local network!"
                )

        self.add_job(_setup_discovery)

    async def _preload_providers(self) -> None:
        """Dynamically load all providermodules."""
        base_dir = os.path.dirname(os.path.abspath(__file__))
        modules_path = os.path.join(base_dir, "providers")
        # load modules
        for dir_str in os.listdir(modules_path):
            dir_path = os.path.join(modules_path, dir_str)
            if not os.path.isdir(dir_path):
                continue
            # get files in directory
            for file_str in os.listdir(dir_path):
                file_path = os.path.join(dir_path, file_str)
                if not os.path.isfile(file_path):
                    continue
                if not file_str == "__init__.py":
                    continue
                module_name = dir_str
                if module_name in [i.id for i in self._providers.values()]:
                    continue
                # try to load the module
                try:
                    prov_mod = importlib.import_module(
                        f".{module_name}", "music_assistant.providers"
                    )
                    await prov_mod.setup(self)
                # pylint: disable=broad-except
                except Exception as exc:
                    LOGGER.exception("Error preloading module %s: %s", module_name, exc)
                else:
                    LOGGER.debug("Successfully preloaded module %s", module_name)
Пример #10
0
class StreamAdvert(threading.Thread):
    def __init__(self, config):
        threading.Thread.__init__(self)
        self.daemon = True
        self.config = config
        self.logger = logging.getLogger("visiond." + __name__)

        # Attempt to redirect the default handler into our log files
        default_zeroconf_logger = logging.getLogger("zeroconf")
        default_zeroconf_logger.setLevel(logging.INFO)  # TODO: Set based on config
        default_zeroconf_logger.propagate = True
        for handler in logging.getLogger("visiond").handlers:
            default_zeroconf_logger.addHandler(handler)

        self.zeroconf = None
        self._should_shutdown = threading.Event()
        self._q = queue.Queue()

        self.ip_version = IPVersion.V4Only  # IPVersion.All
        self.service_info = self.build_service_info()

    def build_service_info(self, props=None, _type='visiond'):
        if _type == 'visiond':
            _subdesc = "{}:{}".format(socket.gethostname(), self.config.args.name if self.config.args.name else self.config.args.output_port)
            _rtspurl = f"rtsp://{socket.getfqdn()}:{self.config.args.output_port}/video"
            return ServiceInfo(
                "_rtsp._udp.local.",
                f"{_type} ({_subdesc}) ._rtsp._udp.local.",
                addresses=[socket.inet_aton(self.config.args.output_dest)],
                port=int(self.config.args.output_port),
                properties={
                    "port": self.config.args.output_port, 
                    "name": _subdesc, 
                    "service_type": "visiond",
                    "rtspUrl": _rtspurl,
                    "uuid": self.instance_uuid(_rtspurl),
                }
            )
        elif _type == 'webrtc':
            _subdesc = "{}:{}".format(socket.gethostname(), self.config.args.name if self.config.args.name else 6011)
            _wsEndpoint = f"wss://{socket.getfqdn()}:6011"
            return ServiceInfo(
                "_webrtc._udp.local.",
                f"visiond-webrtc ({_subdesc})._webrtc._udp.local.",
                addresses=[socket.inet_aton('0.0.0.0')],
                port=6011,
                properties={
                    "hostname": socket.getfqdn(),
                    "port": 6011, 
                    "name": _subdesc, 
                    "service_type": "webrtc", 
                    "wsEndpoint": _wsEndpoint,
                    "uuid": self.instance_uuid(_wsEndpoint),
                },
            )

    def instance_uuid(self, url):
        # Create a repeatable uuid based on unique url
        return str(uuid.uuid5(uuid.NAMESPACE_URL, url))

    def run(self):
        self.logger.info("Zeroconf advertisement thread is starting...")
        try:
            self.zeroconf = Zeroconf(ip_version=self.ip_version)
            self.register_service(self.service_info)
        except OSError as e:
            # the port was blocked
            self.logger.info.error(
                f"Unable to start zeroconf advertisement thread due to {e}"
            )
            self.clean_up()

        while not self._should_shutdown.is_set():
            try:
                # The following will block for at most [timeout] seconds
                desc_update = self._q.get(block=True, timeout=2)
            except queue.Empty:
                desc_update = None
            if desc_update:
                self.update_service(desc_update)

        # We only get here when shutdown has been called
        self.clean_up()

    def clean_up(self):
        self.logger.info("Zeroconf advertisement thread is stopping...")
        if self.zeroconf:
            self.zeroconf.unregister_all_services()
            self.zeroconf.close()
        self.logger.info("Zeroconf advertisement thread has stopped.")

    def register_service(self, service_info):
        self.zeroconf.register_service(service_info, cooperating_responders=True)

    def update_service(self, desc_update):
        # it does not look like there is a nice way to update
        #  the properties field of a service.
        #  Make a new service with the same details,
        #  but update the properties.

        # Merge the dicts and apply the updates
        self.service_info = self.build_service_info(desc_update)
        self.zeroconf.update_service(self.service_info)

    def unregister_service(self):
        self.zeroconf.unregister_service(self.service_info)

    def shutdown(self):
        self._should_shutdown.set()

    def update(self, desc_update):
        self._q.put_nowait(desc_update)