code-grappe/mqtt-python

56 lines
1.7 KiB
Plaintext
Raw Permalink Normal View History

2021-06-21 11:29:53 +02:00
import paho.mqtt.client as mqttClient
from influxdb import InfluxDBClient
import time
TOPIC = "test1"
broker_address= "localhost"
port = 1883
database = "thermo-bibli"
nom_client = "capteurs1"
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe(TOPIC, 2)
def addData(database, time, numero_grappe, numero_capteur, temp, hum, batterie): # ajoute donnée à base de donnée influxDB
client = InfluxDBClient(host='localhost', port=8086)
client.create_database(database)
client.switch_database(database)
data = [
{
"measurement": numero_grappe,
"tags": {"numero_capteur": numero_capteur},
"time": time,
"fields": {"temperature": temp, "humidite": hum, "batterie": batterie}
}
]
client.write_points(data)
def on_message(client, userdata, message):
message = (message.payload).decode("utf-8") # convertit type bytes en string
print("Message reçu")
tab = message.split("|")
temp = tab[2].split()
hum = tab[3].split()
batterie = tab[4]
L = len(temp)
for i in range(L):
addData(database, tab[0], tab[1], "capteur" + str(i+1), temp[i], hum[i], batterie)
client = mqttClient.Client(nom_client, False)
client.username_pw_set(username="capteurs",password="Fablab")
client.on_connect= on_connect #callback
client.on_message= on_message #callback
client.connect(broker_address, port, 65535)
client.loop_start()
try:
while True:
time.sleep(0.1)
except KeyboardInterrupt:
print ("exiting")
client.disconnect()
client.loop_stop()