Пример #1
0
    def load_sensor(self):
        name = self.device_id
        mac = self._poller._mac
        try:
            print_line('Update Sensor fill cache {}'.format(self.device_id))
            self._poller.clear_cache()
            self._poller.fill_cache()
            print_line('Success Update Sensor fill cache {}'.format(
                self.device_id))
            firmware = self._poller.firmware_version()
            for param, _ in self.parameters.items():
                self._data[param] = self._poller.parameter_value(param)
            print_line('Update sensor "{}" ({}) successful'.format(
                self.device_id, json.dumps(self._data)))
        except (IOError, BluetoothBackendException):
            print_line(
                'Initial connection to Mi Sensor "{}" ({}) failed.'.format(
                    name, mac),
                error=True)
            self.status = False
            return

        if self.status:
            return
        print('Device Id:   "{}"'.format(name))
        print('MAC address:   {}'.format(mac))
        print('Firmware:      {}'.format(firmware))
        print_line(
            'Initial connection to Mi Sensor "{}" ({}) successful'.format(
                name, mac))
        self.status = True
Пример #2
0
    def load_client(self, node_id, mqtt_config):
        topic = "{}/sensor/{}/device".format(self._base_topic, node_id).lower()
        client = mqtt.Client(node_id)
        client.on_connect = on_connect
        client.on_message = on_message
        client.on_subscribe = on_subscribe
        client.on_disconnect = on_disconnect
        client.will_set(topic, 'off', qos=1, retain=True)
        if mqtt_config.get('tls', False):
            # According to the docs, setting PROTOCOL_SSLv23 "Selects the highest protocol version
            # that both the client and server support. Despite the name, this option can select
            # “TLS” protocols as well as “SSL”" - so this seems like a resonable default
            client.tls_set(ca_certs=mqtt_config.get('tls_ca_cert', None),
                           keyfile=mqtt_config.get('tls_keyfile', None),
                           certfile=mqtt_config.get('tls_certfile', None),
                           tls_version=ssl.PROTOCOL_SSLv23)

        if mqtt_config.get('username'):
            client.username_pw_set(mqtt_config.get('username'),
                                   mqtt_config.get('password', None))

        try:
            client.connect(mqtt_config['host'],
                           mqtt_config['port'],
                           keepalive=60)
        except:
            print_line(
                'MQTT connection error. Please check your settings in the configuration file "config.json"',
                error=True)
            sys.exit(1)
        client.loop_start()
        client.user_data_set({"topic": topic})
        return client
Пример #3
0
 def run(self):
     print_line("--> Load Data:" + self._mqtt_node.node_id)
     data = self._sensor.update()
     if not self._sensor.status:
         print_line("--> Load Data Fail:" + self._mqtt_node.node_id)
         return
     topic = '{}/sensor/{}/state'.format(self._mqtt_node.base_topic,
                                         self._mqtt_node.node_id).lower()
     print_line("--> Send Data:%s %s" % (topic, json.dumps(data)))
     self._mqtt_node.client.publish(topic, json.dumps(data), 1, True)
Пример #4
0
        topic = '{}/sensor/{}/state'.format(self._mqtt_node.base_topic,
                                            self._mqtt_node.node_id).lower()
        print_line("--> Send Data:%s %s" % (topic, json.dumps(data)))
        self._mqtt_node.client.publish(topic, json.dumps(data), 1, True)


if __name__ == '__main__':
    # Load configuration file
    config_dir = parse_args.config_dir

    with open(os.path.join(config_dir, 'config.json')) as f:
        config = json.loads(f.read())

    sd_notifier.notify('READY=1')

    print_line("--> Start Load Sensor")
    sensors_list = load_sensors(config)
    print_line("--> Finish Load Sensor")

    while True:
        print_line("--> Start Load GateWay Sensors")
        for item in sensors_list:
            send_job = SendDataThread(item['sensor'], item['mqtt_node'])
            print_line("--> Sensor Update Load Job:" + send_job.getName() +
                       "," + send_job.mqtt_node.node_id)
            send_job.start()
            start = time.time()
            while True:
                if send_job.isAlive():
                    time.sleep(1)
                else:
Пример #5
0
def on_disconnect(client, userdata, rc):
    if rc != 0:
        print_line("Unexpected disconnection %s" % rc)
Пример #6
0
def on_subscribe(client, userdata, mid, granted_qos):
    print_line("On Subscribed: qos = %d" % granted_qos)
Пример #7
0
def on_message(client, userdata, msg):
    print_line("SEND:" + msg.topic + " " + str(msg.payload.decode('utf-8')))
    if msg.topic in _sub_dict:
        _sub_dict[msg.topic](userdata, msg)
Пример #8
0
def on_connect(client, userdata, flags, rc):
    client.publish(userdata['topic'], 'on', qos=1, retain=True)
    print_line("Connected with result code " + str(rc) + userdata + flags)