예제 #1
0
def on_mqtt_connect(client, userdata, flags, rc):
    print("Connected to mqtt server with result code " + str(rc))
    client.subscribe(config.subscribe_topic)


def on_mqtt_message(client, userdata, msg):
    print("Received '%s' - '%s'" % (msg.topic, str(msg.payload)))
    try:
        data = json.loads(msg.payload)
        p = Point(msg.topic)
        for key in data:
            if key == "timestamp":
                if isinstance(data["timestamp"], numbers.Number):
                    p.time(data["timestamp"])
                else:
                    p.time(
                        datetime.strptime(data["timestamp"],
                                          "%Y-%m-%d %H:%M:%S"))
            else:
                p.field(key, data[key])
        influx_write.write(bucket=config.bucket, record=p)
    except json.decoder.JSONDecodeError:
        print("### Message payload is invalid JSON! ###")


client = mqtt.Client()
client.on_connect = on_mqtt_connect
client.on_message = on_mqtt_message
client.connect(config.mqtt_host, config.mqtt_port, 60)
client.loop_forever()
예제 #2
0
        p = Point("ventilation").field(message.topic, itho_info)
        write_api.write(bucket=bucket, record=p)

        logging.debug(message.topic)
        logging.debug(itho_info)

    except Exception as e:
        return


bucket = "homehub-bucket"

client = paho.Client(
    "client-itho"
)  #create client object client1.on_publish = on_publish #assign function to callback client1.connect(broker,port) #establish connection client1.publish("house/bulb1","on")
######Bind function to callback
client.on_message = on_message
#####
logging.info(f"connecting to broker {broker}")
client.connect(broker)  #connect
client.loop_start()  #start loop to process received messages

# client.publish("itho/cmd",'20')
# time.sleep(4)
# exit()
logging.info("subscribing ")
client.subscribe("itho/#")  #subscribe
# client.subscribe("zigbee2mqtt/#")#subscribe
while True:
    time.sleep(2)