Ejemplo n.º 1
0
 def start(self):
     super().start()
     if self.polling_interval().total_seconds() > 0:
         self._poll_job = Job(self.poll, self.polling_interval(), True)
         spawn(self.poll)
     else:
         self.logger.info("No poll job")
Ejemplo n.º 2
0
 def connect(self):
     connecting_to = []
     for addr in self._configs:
         if addr not in self._tags:
             connecting_to.append(addr)
             spawn(self._connect_tag, self._configs[addr])
     return connecting_to
Ejemplo n.º 3
0
 def _connect_tag(self, cfg, read_on_connect=False):
     addy = cfg["address"]
     name = cfg["name"]
     try:
         self.logger.info("Push {} side button NOW".format(name))
         self.logger.info("Connecting to device {}".format(addy))
         self._notify_status_signal('Connecting', addy)
         tag = SensorTag(addy)
         self._enable_sensors(addy, tag)
         # Save the tag to the list after connection and sensors enabled.
         self._tags[addy] = tag
     except Exception as e:
         self.logger.exception(
             "Failed to connect to {} ({}). Retrying...".format(name, addy))
         self._notify_status_signal('Retrying', addy)
         # Make sure to remove tag if connect fails
         self._tags.pop(addy, None)
         sleep(5)
         self._connect_tag(cfg)
     else:
         self.logger.info("Connected to device {}".format(addy))
         self._notify_status_signal('Connected', addy)
         self._read_counter = 0
         if cfg["sensors"].get('keypress', False):
             self.logger.info(
                 "Enabling notification listening for keypress")
             spawn(self._listen_for_notifications, addy)
         if read_on_connect:
             self.logger.debug(
                 "Reading from sensors on reconnect")
             self._read_from_tag(addy)
Ejemplo n.º 4
0
 def connect(self):
     connecting_to = []
     for addr in self._configs:
         if addr not in self._tags:
             connecting_to.append(addr)
             spawn(self._connect_tag, self._configs[addr])
     return connecting_to
Ejemplo n.º 5
0
 def _connect_tag(self, cfg, read_on_connect=False):
     addy = cfg["address"]
     name = cfg["name"]
     try:
         self.logger.info("Push {} side button NOW".format(name))
         self.logger.info("Connecting to device {}".format(addy))
         self._notify_status_signal('Connecting', addy)
         tag = SensorTag(addy)
         self._enable_sensors(addy, tag)
         # Save the tag to the list after connection and sensors enabled.
         self._tags[addy] = tag
     except Exception as e:
         self.logger.exception(
             "Failed to connect to {} ({}). Retrying...".format(name, addy))
         self._notify_status_signal('Retrying', addy)
         # Make sure to remove tag if connect fails
         self._tags.pop(addy, None)
         sleep(5)
         self._connect_tag(cfg)
     else:
         self.logger.info("Connected to device {}".format(addy))
         self._notify_status_signal('Connected', addy)
         self._read_counter = 0
         if cfg["sensors"].get('keypress', False):
             self.logger.info(
                 "Enabling notification listening for keypress")
             spawn(self._listen_for_notifications, addy)
         if read_on_connect:
             self.logger.debug(
                 "Reading from sensors on reconnect")
             self._read_from_tag(addy)
Ejemplo n.º 6
0
 def register_request(self, timeout):
     """ Register a request in a new thread and return the ID and resp """
     req_id = str(uuid4())
     mock_rsp = self.get_mocked_response()
     mock_req = self.get_mocked_request()
     RequestResponseBroker.register_request(
         req_id, mock_req, mock_rsp, timeout)
     spawn(RequestResponseBroker.wait_for_response, req_id)
     return req_id, mock_rsp
Ejemplo n.º 7
0
 def start(self):
     super().start()
     self._authorize()
     self._start()
     spawn(self._run_stream)
     self._notify_job = Job(
         self._notify_results,
         self.notify_freq(),
         True
     )
Ejemplo n.º 8
0
 def start(self):
     super().start()
     if self.polling_interval().total_seconds() > 0:
         self._poll_job = Job(
             self.poll,
             self.polling_interval(),
             True
         )
         spawn(self.poll)
     else:
         self.logger.info("No poll job")
Ejemplo n.º 9
0
 def _place_calls(self, signal):
     try:
         msg = self.message(signal)
         msg_id = uuid4().hex
         self._messages[msg_id] = msg
         for rcp in self.recipients():
             spawn(target=self._call, recipient=rcp, message_id=msg_id)
     except Exception as e:
         self.logger.error(
             "Message evaluation failed: {0}: {1}".format(
                 type(e).__name__, str(e))
         )
Ejemplo n.º 10
0
 def _place_calls(self, signal):
     try:
         msg = self.message(signal)
         msg_id = uuid4().hex
         self._messages[msg_id] = msg
         for rcp in self.recipients():
             spawn(target=self._call, recipient=rcp, message_id=msg_id)
     except Exception as e:
         self.logger.error(
             "Message evaluation failed: {0}: {1}".format(
                 type(e).__name__, str(e))
         )
Ejemplo n.º 11
0
 def before_retry(self, *args, **kwargs):
     self.logger.warning('Failed to send {}, reconnecting'.format(args))
     self._main_thread.join(1)
     if self._conn:
         self._cleanup()
     self._connect()
     self._main_thread = spawn(self._receive)
Ejemplo n.º 12
0
    def start(self):
        self._main_thread = spawn(self._server)
        self.logger.debug('server started on localhost:{}'.format(self.port()))

        self.data = self.data_dict_to_data_list(self.data_dict)
        figure = {'data': self.data, 'layout': {'title': self.title()}}
        app_layout = [
            dcc.Graph(id=self.title(), figure=figure),
            dcc.Interval(id='interval-component', interval=self.update_interval() * 1000)
        ]

        self.app.layout = html.Div(app_layout)

        @self.app.callback(Output(self.title(), 'figure'),
                           events=[Event('interval-component', 'interval')])
        def update_graph_live():
            return {'data': self.data, 'layout': {'title': self.title()}}

        @self.app.server.route('/shutdown', methods=['GET'])
        def shutdown():
            shutdown_server()
            return 'OK'

        def shutdown_server():
            func = request.environ.get('werkzeug.server.shutdown')
            if func is None:
                self.logger.warning('Not running with the Werkzeug Server')
            func()
        super().start()
    def test_table_lock(self, put_func, count_func, create_func, connect_func):
        """ Make sure that if a table is creating it locks """
        # We should return the error that the table is not found.
        # We should only see this error returned once though, subsequent calls
        # should use the cached version of the table.
        count_func.side_effect = [
            JSONResponseError(
                400,
                "{'message': 'Requested resource not found: Table: T notfound', "
                "'__type': 'com.amazonaws.dynamodb.v20120810"
                "#ResourceNotFoundException'}")
        ]
        blk = SaveCounterDynamoDB()
        self.configure_block(blk, {'log_level': 'DEBUG', 'hash_key': 'hash'})
        # Simulate a table that is creating for a while
        blk._get_table_status = MagicMock(
            side_effect=['CREATING', 'CREATING', 'ACTIVE'])

        # Send two threads to process signals at once
        spawn(blk.process_signals, [Signal({'hash': 'value1'})])
        spawn(blk.process_signals, [Signal({'hash': 'value2'})])

        # We shouldn't have any save calls until the table creates.
        # That takes 1.5 seconds, so let's see what we have after some of that.
        sleep(0.7)
        self.assertEqual(blk._count, 0)

        # Give the table time to create...
        sleep(1)

        # Make sure the table create function only gets called once.  This
        # should happen due to the presence of the lock around _get_table
        self.assertEqual(create_func.call_count, 1)

        # Ok, it's created, we should see both signals get saved
        self.assertEqual(blk._count, 2)
Ejemplo n.º 14
0
    def _tcp_server(self):
        self.logger.debug('started server thread')
        buffer_size = 1024
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.bind((self.host(), self.port()))
            s.listen(1)
            while not self._kill:
                self.logger.debug('listening for connections')
                conn, addr = s.accept()
                host = addr[0]

                # keep track of all accepted connections
                if host not in self._connections:
                    # new connection
                    self._connections[host] = conn
                else:
                    # the address has already been connected to, and it never
                    # closed itself (likely due to power loss).
                    # Tear down the old connection and make a new one on the
                    # same address

                    # closing the connection should cause the thread used by
                    # that connection to exit
                    self.logger.debug('Accepted a connection from an address '
                                      'already in use: {}, closing connection '
                                      'object: {}'.format(
                                          host, self._connections[host]))
                    self._connections[host].close()
                    try:
                        self._recv_threads[host].join()
                    except:
                        self.logger.debug('recv thread already exited before '
                                          'join')
                    self._connections[host] = conn

                self.logger.debug('{} connected'.format(addr))

                recv_thread = spawn(self._recv, conn, addr, buffer_size)
                self._recv_threads[host] = recv_thread
Ejemplo n.º 15
0
    def start(self):
        self._main_thread = spawn(self._server)
        self.logger.debug('server started on localhost:8050')
        super().start()

        self.data_dict = {
            s.name(): {'x': [], 'y': [], 'name': s.name()}
            for s in self.graph_series()
        }
        self.data = self.data_dict_to_data_list(self.data_dict)
        figure = {'data': self.data, 'layout': {'title': self.title()}}
        app_layout = [
            dcc.Graph(id=self.title(), figure=figure),
            dcc.Interval(id='interval-component', interval=1 * 1000)
        ]

        self.app.layout = html.Div(app_layout)

        @self.app.callback(Output(self.title(), 'figure'),
                           events=[Event('interval-component', 'interval')])
        def update_graph_live():
            return {'data': self.data, 'layout': {'title': self.title()}}
Ejemplo n.º 16
0
 def start(self):
     super().start()
     self._main_thread = spawn(self._tcp_server)
Ejemplo n.º 17
0
 def start(self):
     super().start()
     if self._server:
         spawn(self._server.serve_forever)
     else:
         self.logger.warning("Server did not exist, so it was not started")
Ejemplo n.º 18
0
 def _reconnect(self, addy, read_on_connect=True):
     spawn(self._reconnect_thread, addy, read_on_connect)
Ejemplo n.º 19
0
 def _reconnect(self):
     self.logger.debug(
         'Attempting reconnect in {} seconds'.format(self._reconnect_delay))
     sleep(self._reconnect_delay)
     self._reconnect_delay *= 2
     spawn(self._connect)
Ejemplo n.º 20
0
 def start(self):
     super().start()
     # start gathering messages
     self._stop_message_loop_event = Event()
     self._message_loop_thread = spawn(self._receive_messages)
Ejemplo n.º 21
0
 def start(self):
     super().start()
     if self._server:
         spawn(self._server.serve_forever)
     else:
         self.logger.warning("Server did not exist, so it was not started")
Ejemplo n.º 22
0
 def start(self):
     super().start()
     self._connect_thread = spawn(self._connect_gage)
Ejemplo n.º 23
0
 def _reconnect(self):
     self.logger.debug('Attempting reconnect in {} seconds'.format(
         self._reconnect_delay))
     sleep(self._reconnect_delay)
     self._reconnect_delay *= 2
     spawn(self._connect)
Ejemplo n.º 24
0
 def _reconnect(self, addy, read_on_connect=True):
     spawn(self._reconnect_thread, addy, read_on_connect)
Ejemplo n.º 25
0
 def start(self):
     super().start()
     self._connect()
     self._main_thread = spawn(self._receive)