Exemplo n.º 1
0
    def run(self):
        """ Starts the backend thread. To be implemented in the derived classes if the loop method isn't defined. """
        self.thread_id = get_ident()
        set_thread_name(self._thread_name)
        if not callable(self.loop):
            return

        while not self.should_stop():
            try:
                with self:
                    has_error = False

                    while not self.should_stop() and not has_error:
                        try:
                            # pylint: disable=not-callable
                            self.loop()
                        except Exception as e:
                            has_error = True
                            self.logger.error(str(e))
                            self.logger.exception(e)
                        finally:
                            if self.poll_seconds:
                                time.sleep(self.poll_seconds)
                            elif has_error:
                                time.sleep(5)
            except Exception as e:
                self.logger.error('{} initialization error: {}'.format(
                    self.__class__.__name__, str(e)))
                self.logger.exception(e)
                time.sleep(self.poll_seconds or 5)
Exemplo n.º 2
0
    def websocket(self):
        """ Websocket main server """
        set_thread_name('WebsocketServer')

        async def register_websocket(websocket, path):
            address = websocket.remote_address if websocket.remote_address \
                else '<unknown client>'

            self.logger.info('New websocket connection from {} on path {}'.format(address, path))
            self.active_websockets.add(websocket)

            try:
                await websocket.recv()
            except ConnectionClosed:
                self.logger.info('Websocket client {} closed connection'.format(address))
                self.active_websockets.remove(websocket)
                if address in self._websocket_locks:
                    del self._websocket_locks[address]

        websocket_args = {}
        if self.ssl_context:
            websocket_args['ssl'] = self.ssl_context

        self._websocket_loop = get_or_create_event_loop()
        self._websocket_loop.run_until_complete(
            websocket_serve(register_websocket, self.bind_address, self.websocket_port,
                             **websocket_args))
        self._websocket_loop.run_forever()
Exemplo n.º 3
0
        def _thread_func():
            set_thread_name('HttpPoll')
            is_first_call = self.last_request_timestamp == 0
            self.last_request_timestamp = time.time()

            try:
                method = getattr(requests, self.args.method.lower())
                response = method(self.args.url, *self.args.args,
                                  **self.args.kwargs)
                new_items = self.get_new_items(response)

                if isinstance(new_items, HttpEvent):
                    event = new_items
                    new_items = event.args['response']
                else:
                    event = HttpEvent(dict(self), new_items)

                if new_items and self.bus:
                    if not self.skip_first_call or (self.skip_first_call
                                                    and not is_first_call):
                        self.bus.post(event)

                response.raise_for_status()
            except Exception as e:
                self.logger.exception(e)
                self.logger.warning(
                    'Encountered an error while retrieving {}: {}'.format(
                        self.args.url, str(e)))
Exemplo n.º 4
0
        def _thread():
            set_thread_name(thread_name)

            while not self.should_stop():
                try:
                    sock = self._connect(host, port)
                    msgs = self._recv(sock)

                    if not isinstance(msgs, list):
                        msgs = [msgs]

                    for msg in msgs:
                        self.logger.debug(
                            'Received message on {host}:{port}: {msg}'.format(
                                host=host, port=port, msg=msg))

                        evt = self._parse_msg(host=host, msg=msg)
                        if evt:
                            self.bus.post(evt)
                except Exception as e:
                    self.logger.warning('Exception while getting the status ' +
                                        'of the Snapcast server {}:{}: {}'.
                                        format(host, port, str(e)))

                    self._disconnect(host, port)
                finally:
                    time.sleep(self.poll_seconds)
Exemplo n.º 5
0
    def run(self):
        # noinspection PyPackageRequirements
        from google.cloud import pubsub_v1
        # noinspection PyPackageRequirements
        from google.api_core.exceptions import AlreadyExists

        super().run()
        set_thread_name('GooglePubSub')
        plugin = self._get_plugin()
        project_id = plugin.get_project_id()
        credentials = plugin.get_credentials(plugin.subscriber_audience)
        subscriber = pubsub_v1.SubscriberClient(credentials=credentials)

        for topic in self.topics:
            if not topic.startswith('projects/{}/topics/'.format(project_id)):
                topic = 'projects/{}/topics/{}'.format(project_id, topic)
            subscription_name = '/'.join(
                [*topic.split('/')[:2], 'subscriptions',
                 topic.split('/')[-1]])

            try:
                subscriber.create_subscription(name=subscription_name,
                                               topic=topic)
            except AlreadyExists:
                pass

            subscriber.subscribe(subscription_name,
                                 self._message_callback(topic))

        self.wait_stop()
Exemplo n.º 6
0
            def response_thread(msg):
                set_thread_name('MQTTProcessor')
                response = self.get_message_response(msg)
                if not response:
                    return
                response_topic = '{}/responses/{}'.format(self.topic, msg.id)

                self.logger.info('Processing response on the MQTT topic {}: {}'.
                                format(response_topic, response))

                self.send_message(response)
Exemplo n.º 7
0
        def _animate_thread(lights):
            set_thread_name('HueAnimate')
            get_bus().post(
                LightAnimationStartedEvent(lights=lights,
                                           groups=groups,
                                           animation=animation))

            lights = _initialize_light_attrs(lights)
            animation_start_time = time.time()
            stop_animation = False

            while not stop_animation and not (duration and time.time() -
                                              animation_start_time > duration):
                try:
                    if animation == self.Animation.COLOR_TRANSITION:
                        for (light, attrs) in lights.items():
                            self.logger.debug('Setting {} to {}'.format(
                                light, attrs))
                            self.bridge.set_light(light, attrs)
                    elif animation == self.Animation.BLINK:
                        conf = lights[list(lights.keys())[0]]
                        self.logger.debug('Setting lights to {}'.format(conf))

                        if groups:
                            self.bridge.set_group([g.name for g in groups],
                                                  conf)
                        else:
                            self.bridge.set_light(lights.keys(), conf)

                    if transition_seconds:
                        time.sleep(transition_seconds)

                    stop_animation = _should_stop()
                except Exception as e:
                    self.logger.warning(e)
                    time.sleep(2)

                lights = _next_light_attrs(lights)

            get_bus().post(
                LightAnimationStoppedEvent(lights=lights,
                                           groups=groups,
                                           animation=animation))
            self.animation_thread = None
Exemplo n.º 8
0
        def _animate_thread(lights):
            set_thread_name('HueAnimate')
            self.logger.info('Starting {} animation'.format(
                animation, (lights or groups)))

            lights = _initialize_light_attrs(lights)
            animation_start_time = time.time()
            stop_animation = False

            while True:
                if stop_animation or \
                        (duration and time.time() - animation_start_time > duration):
                    break

                try:
                    if animation == self.Animation.COLOR_TRANSITION:
                        for (light, attrs) in lights.items():
                            self.logger.debug('Setting {} to {}'.format(
                                light, attrs))
                            self.bridge.set_light(light, attrs)
                            stop_animation = _should_stop()
                            if stop_animation: break
                    elif animation == self.Animation.BLINK:
                        conf = lights[list(lights.keys())[0]]
                        self.logger.debug('Setting lights to {}'.format(conf))

                        if groups:
                            self.bridge.set_group([g.name for g in groups],
                                                  conf)
                        else:
                            self.bridge.set_light(lights.keys(), conf)

                        stop_animation = _should_stop()
                        if stop_animation: break
                except Exception as e:
                    self.logger.warning(e)
                    time.sleep(2)

                lights = _next_light_attrs(lights)

            self.logger.info('Stopping animation')
            self.animation_thread = None
            self.redis = None
Exemplo n.º 9
0
 def run(self):
     """ Starts the backend thread. To be implemented in the derived classes """
     self.thread_id = threading.get_ident()
     set_thread_name(self._thread_name)
Exemplo n.º 10
0
 def _f_wrapper():
     set_thread_name('TCPListener')
     try:
         _f()
     finally:
         sock.close()
Exemplo n.º 11
0
 def _thread_func(result):
     set_thread_name('Event-' + self.name)
     self.actions.execute(event=event, **result.parsed_args)
Exemplo n.º 12
0
 def start(self):
     set_thread_name(self.__class__.__name__)
     self._thread = threading.Thread(target=self._runner)
     self._thread.start()