Example #1
0
    def launcher(self):
        """
        启动获取传感器温湿度值,写入文件到指定目录
        :return:
        """
        conf_dht11 = SensorConf.get_aiot_sensor_conf_dict('dht11')
        if conf_dht11 is None:
            raise ValueError('tips dht11 params conf error, please check')
        time.sleep(1)

        while True:
            humidity, temperature = DHT.read_retry(DHT.DHT11, self.GPIO_PIN)
            print('dht11->temperature:{},humidity:{}'.format(
                temperature, humidity))
            if temperature is not None or humidity is not None:
                gather_time = datetime.datetime.now().strftime(
                    '%Y-%m-%d %H:%M:%S')
                origin_value = dict(productid=EdgeConf.get_product_id(),
                                    edgeid=EdgeConf.get_edge_id(),
                                    devicedata=[
                                        dict(deviceid=conf_dht11['deviceid'],
                                             gathertime=gather_time,
                                             dataname='temperature',
                                             datavalue=temperature,
                                             datatype='float'),
                                        dict(deviceid=conf_dht11['deviceid'],
                                             gathertime=gather_time,
                                             dataname='humidity',
                                             datavalue=humidity,
                                             datatype='float')
                                    ])
                with open(FileUtil.generate_sensor_data_file_name(), 'w') as f:
                    json.dump(origin_value, f)
            time.sleep(conf_dht11['gatherfrequency'])
 def run(self) -> None:
     # mqtt方式订阅手环消息
     wristband_conf = SensorConf.get_aiot_sensor_conf_dict('wristband')
     if wristband_conf is not None:
         topic = 'aiot/' + EdgeConf.get_product_id(
         ) + '/' + EdgeConf.get_edge_id() + '/' + wristband_conf['deviceid']
         print('initiate mqtt subscribe,topic:{}'.format(topic))
         MqttClient.subscribe(topic, subscribe_receive_message)
     else:
         print('start wristband subscribe failure, params not config')
 def generate_sensor_data_file_name() -> str:
     """
     统一生成传感设备数据文件名称
     :return: 新文件名称(绝对路径)
     """
     postfix = EdgeConf.get_product_id() + '_' + EdgeConf.get_edge_id(
     ) + '_GD_' + datetime.datetime.now().strftime(
         '%Y%m%d%H%M%S') + '_' + FileUtil.__generate_count_sequence(
         ) + '.json'
     if not os.path.exists(EdgeConf.get_sensor_data_storage_directory()):
         os.makedirs(EdgeConf.get_sensor_data_storage_directory())
     return os.path.join(EdgeConf.get_sensor_data_storage_directory(),
                         postfix)
 def publish(messages):
     """
     发布主题数据(多主题)
     :param messages:
     :return:
     """
     publish.multiple(msgs=messages,
                      hostname=EdgeConf.get_mqtt_host(),
                      port=EdgeConf.get_mqtt_port(),
                      client_id=EdgeConf.get_mqtt_client_id(),
                      keepalive=15,
                      will=None,
                      auth=dict(
                          username=EdgeConf.get_mqtt_publish_username(),
                          password=EdgeConf.get_mqtt_publish_password()),
                      tls=None,
                      protocol=client.MQTTv311,
                      transport='tcp')
     print('publish success')
Example #5
0
    def launcher(self):
        """
        启动获取传感器温度值,写入文件到指定目录
        :return:
        """

        conf_ds18b20 = SensorConf.get_aiot_sensor_conf_dict('ds18b20')
        if conf_ds18b20 is None:
            raise ValueError('tips dsl8b20 params conf error, please check')

        while True:
            for df in self.__ds18b20_data_files:
                value = self.gather_data(df)
                if value:
                    origin_value = dict(productid=EdgeConf.get_product_id(), edgeid=EdgeConf.get_edge_id(), devicedata=[
                        dict(deviceid=conf_ds18b20['deviceid'], gathertime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), dataname='temperature', datavalue=value, datatype='float')
                    ])
                    with open(FileUtil.generate_sensor_data_file_name(), 'w') as f:
                        json.dump(origin_value, f)
            time.sleep(conf_ds18b20['gatherfrequency'])
 def publish(topic: str, message: str):
     """
     发布主题数据(单主题)
     :param topic: 主题
     :param message: 数据
     :return:
     """
     publish.single(topic=topic,
                    payload=message,
                    qos=2,
                    retain=False,
                    hostname=EdgeConf.get_mqtt_host(),
                    port=EdgeConf.get_mqtt_port(),
                    client_id=EdgeConf.get_mqtt_client_id(),
                    keepalive=15,
                    will=None,
                    auth=dict(
                        username=EdgeConf.get_mqtt_publish_username(),
                        password=EdgeConf.get_mqtt_publish_password()),
                    tls=None,
                    protocol=client.MQTTv311,
                    transport='tcp')
     print('publish success')
 def subscribe(topics, callback):
     """
     订阅主题数据
     :param topics: 主题(字符串或列表)
     :param callback: 主题数据回调
     :return:
     """
     subscribe.callback(
         callback=callback,
         topics=topics,
         qos=2,
         userdata=None,
         hostname=EdgeConf.get_mqtt_host(),
         port=EdgeConf.get_mqtt_port(),
         client_id=EdgeConf.get_mqtt_client_id(),
         keepalive=15,
         will=None,
         auth=dict(username=EdgeConf.get_mqtt_subscribe_username(),
                   password=EdgeConf.get_mqtt_subscribe_password()),
         tls=None,
         protocol=client.MQTTv311,
         transport='tcp',
         clean_session=True)
     print('subscribe success')
Example #8
0
    def launcher(self):
        """
        启动
        主机对从机读数据操作,modbus-rtc协议:
          0x01	  03	  00 01	  00 01	     D5 CA
        从机地址	 功能号	数据地址	读取数据个数	CRC校验

        设备地址	功能代码	数据格式	CRC校验L	 CRC校验H
        8bit	8bit	N*8bit	8bit	 8bit

        从机对主机返回内容:
        0x01	03	     02	        00 17	    F8 4A
        从机地址	功能号	数据字节个数	两个字节数据	CRC校验
        :return:
        """
        if self.__serial_handle is None:
            print('pzem016 {} start fail, because usb port open error'.format(
                self.serial_port))
            return

        if self.__serial_handle.isOpen():
            self.__serial_handle.close()
        self.__serial_handle.open()
        print('/dev/ttyUSB* open success')
        time.sleep(1)

        conf_pzem016 = SensorConf.get_aiot_sensor_conf_dict('pzem016')
        if conf_pzem016 is None:
            raise ValueError('tips pzem016 params conf error, please check')

        # calibration slave
        # hex_calibration_result = self.exec_command(self.__pzem_calibration_command, 10)
        # if hex_calibration_result is not None and str(hex_calibration_result) == self.__pzem_calibration_command:
        #     print('pzem016 calibration success')
        # else:
        #     print('pzem016 calibration failure')

        # reset energy
        hex_reset_energy_result = self.exec_command(
            self.__pzem_reset_energy_command)
        if hex_reset_energy_result is not None and str(
                hex_reset_energy_result) == self.__pzem_reset_energy_command:
            print('pzem016 reset energy success')
        else:
            print('pzem016 reset energy failure')

        # 读取输入寄存器数据
        while True:
            hex_input_register_result = self.exec_command(
                self.__pzem_read_input_register_command)
            if hex_input_register_result is None or hex_input_register_result[
                    2:4] is '84':
                print('pzem016 current gather data invalid')
                continue

            voltage = SensorUtil.hex_to_dec(
                hex_input_register_result[6:10])  # parse voltage data 2B
            current = SensorUtil.hex_to_dec(
                hex_input_register_result[10:18])  # parse current data 4B
            power = SensorUtil.hex_to_dec(
                hex_input_register_result[18:26])  # parse power data 4B
            energy = SensorUtil.hex_to_dec(
                hex_input_register_result[26:34])  # parse energy data 4B
            frequency = SensorUtil.hex_to_dec(
                hex_input_register_result[34:38])  # parse frequency data 2B
            powerfactor = SensorUtil.hex_to_dec(
                hex_input_register_result[38:42])  # parse powerfactor data 2B
            alarmstatus = SensorUtil.hex_to_dec(
                hex_input_register_result[42:46])  # parse alarmstatus data 2B

            # 格式化数据
            # if float(energy) < 10000.0:     #
            #     energy = float(energy) * 0.00001
            # print('pzem016 dec data->:voltage:{},current:{},power:{},energy:{},frequency:{},powerfactor:{},alarmstatus:{}'.format(voltage, current, power, energy, frequency, powerfactor, alarmstatus))
            voltage = '{:.1f}'.format(float(voltage) * 0.1)
            current = '{:.3f}'.format(float(current) * 0.00000001)
            power = '{:.1f}'.format(float(power) * 0.000001)
            energy = '{:.1f}'.format(
                float(energy) *
                0.00001)  # 原数据单位是Wh,这里转换为kWh,所以乘0.00001,1kWh=1000Wh
            frequency = '{:.1f}'.format(float(frequency) * 0.1)
            powerfactor = '{:.2f}'.format(float(powerfactor) * 0.01)

            print(
                'pzem016 dec format data->:voltage:{}V,current:{}A,power:{}W,energy:{}kWh,frequency:{}Hz,powerfactor:{},alarmstatus:{}'
                .format(voltage, current, power, energy, frequency,
                        powerfactor, alarmstatus))
            # dec_data = SensorUtil.hex_to_dec(hex_data)
            # voltage = dec_data[6:10]       # parse voltage data 2B
            # current = dec_data[10:18]      # parse current data 4B
            # power = dec_data[18:26]        # parse power data 4B
            # energy = dec_data[26:34]       # parse energy data 4B
            # frequency = dec_data[34:38]    # parse frequency data 2B
            # powerfactor = dec_data[38:42]  # parse powerfactor data 2B
            # alarmstatus = dec_data[42:46]  # parse alarmstatus data 2B
            gather_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            origin_value = dict(productid=EdgeConf.get_product_id(),
                                edgeid=EdgeConf.get_edge_id(),
                                devicedata=[
                                    dict(deviceid=conf_pzem016['deviceid'],
                                         gathertime=gather_time,
                                         dataname='voltage',
                                         datavalue=voltage,
                                         datatype='float'),
                                    dict(deviceid=conf_pzem016['deviceid'],
                                         gathertime=gather_time,
                                         dataname='current',
                                         datavalue=current,
                                         datatype='float'),
                                    dict(deviceid=conf_pzem016['deviceid'],
                                         gathertime=gather_time,
                                         dataname='power',
                                         datavalue=power,
                                         datatype='float'),
                                    dict(deviceid=conf_pzem016['deviceid'],
                                         gathertime=gather_time,
                                         dataname='energy',
                                         datavalue=energy,
                                         datatype='float'),
                                    dict(deviceid=conf_pzem016['deviceid'],
                                         gathertime=gather_time,
                                         dataname='frequency',
                                         datavalue=frequency,
                                         datatype='float'),
                                    dict(deviceid=conf_pzem016['deviceid'],
                                         gathertime=gather_time,
                                         dataname='powerfactor',
                                         datavalue=powerfactor,
                                         datatype='float'),
                                    dict(deviceid=conf_pzem016['deviceid'],
                                         gathertime=gather_time,
                                         dataname='alarmstatus',
                                         datavalue=alarmstatus,
                                         datatype='int')
                                ])
            with open(FileUtil.generate_sensor_data_file_name(), 'w') as f:
                json.dump(origin_value, f)
            time.sleep(conf_pzem016['gatherfrequency'])