Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import paho.mqtt.client as mqtt #client
- import mysql.connector
- import sys
- import time
- intervall = 5
- try:
- intervall = int(sys.argv[1])
- except ValueError:
- print("PLEASE USE A NUMBER EQUAL TO 5 OR HIGHER")
- sys.exit(0)
- if intervall<5:
- print("ERROR: YOU MUST ENTER A TIME INTERVAL EQUAL TO 5 SECONDS OR HIGHER. USING 5 SECONDS AS INTERVAL")
- intervall = 5
- n = 0
- WertphaseA = 0
- WertphaseB = 0
- WertphaseC = 0
- mydb = mysql.connector.connect(
- host = "localhost",
- user = "StromMessung",
- passwd = "Irms",
- database = "Irms"
- )
- def on_log(client, userdata, level, buf):
- print("log: " + buf)
- def on_connect(client, userdata, flags, rc):
- if rc == 0:
- print("connected OK")
- else :
- print("Bad connection Returned code=", rc)
- def on_message(client, userdata, msg): #callback function
- topic = msg.topic
- global n
- global WertphaseA
- global WertphaseB
- global WertphaseC
- m_decode = str(msg.payload.decode("utf-8", "ignore"))
- print("n ist bei", n)
- print("message received", m_decode)
- n += 1
- if topic == "PhaseA":
- WertphaseA = m_decode
- print("TOPIC A WAS RECEIVED")
- elif topic == "PhaseB":
- WertphaseB = m_decode
- print("TOPIC B WAS RECEIVED")
- elif topic == "PhaseC":
- WertphaseC = m_decode
- print("TOPIC C WAS RECEIVED")
- if n == 3:
- global n
- print("Writing into database")
- mycursor = mydb.cursor()
- sql = 'INSERT INTO Momentanwerte (phaseA, phaseB, phaseC) VALUES (%s,%s,%s)'
- val = (WertphaseA, WertphaseB, WertphaseC)
- mycursor.execute(sql, val)
- mydb.commit()
- print("Data Written")
- n = 0
- broker = "localhost"
- client = mqtt.Client("Sensor")
- client.connect(broker)
- print("Connecting to broker", broker)
- client.publish("Zeitintervall", intervall)
- client.on_connect = on_connect
- client.on_message = on_message
- client.on_log = on_log
- client.subscribe([("PhaseA", 0), ("PhaseB", 0), ("PhaseC", 0)])
- client.loop_forever()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement