Advertisement
Guest User

Untitled

a guest
Jan 18th, 2020
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. import paho.mqtt.client as mqtt #client
  2. import mysql.connector
  3. import sys
  4. import time
  5.  
  6.  
  7.  
  8. intervall = 5
  9.  
  10. try:
  11. intervall = int(sys.argv[1])
  12. except ValueError:
  13. print("PLEASE USE A NUMBER EQUAL TO 5 OR HIGHER")
  14. sys.exit(0)
  15.  
  16.  
  17. if intervall<5:
  18. print("ERROR: YOU MUST ENTER A TIME INTERVAL EQUAL TO 5 SECONDS OR HIGHER. USING 5 SECONDS AS INTERVAL")
  19. intervall = 5
  20.  
  21.  
  22.  
  23.  
  24. n = 0
  25. WertphaseA = 0
  26. WertphaseB = 0
  27. WertphaseC = 0
  28.  
  29. mydb = mysql.connector.connect(
  30. host = "localhost",
  31. user = "StromMessung",
  32. passwd = "Irms",
  33. database = "Irms"
  34. )
  35.  
  36. def on_log(client, userdata, level, buf):
  37. print("log: " + buf)
  38.  
  39. def on_connect(client, userdata, flags, rc):
  40. if rc == 0:
  41. print("connected OK")
  42. else :
  43. print("Bad connection Returned code=", rc)
  44.  
  45. def on_message(client, userdata, msg): #callback function
  46. topic = msg.topic
  47. global n
  48. global WertphaseA
  49. global WertphaseB
  50. global WertphaseC
  51. m_decode = str(msg.payload.decode("utf-8", "ignore"))
  52. print("n ist bei", n)
  53. print("message received", m_decode)
  54. n += 1
  55.  
  56. if topic == "PhaseA":
  57. WertphaseA = m_decode
  58. print("TOPIC A WAS RECEIVED")
  59.  
  60. elif topic == "PhaseB":
  61. WertphaseB = m_decode
  62. print("TOPIC B WAS RECEIVED")
  63.  
  64. elif topic == "PhaseC":
  65. WertphaseC = m_decode
  66. print("TOPIC C WAS RECEIVED")
  67.  
  68. if n == 3:
  69. global n
  70. print("Writing into database")
  71. mycursor = mydb.cursor()
  72. sql = 'INSERT INTO Momentanwerte (phaseA, phaseB, phaseC) VALUES (%s,%s,%s)'
  73. val = (WertphaseA, WertphaseB, WertphaseC)
  74. mycursor.execute(sql, val)
  75. mydb.commit()
  76. print("Data Written")
  77. n = 0
  78.  
  79. broker = "localhost"
  80. client = mqtt.Client("Sensor")
  81. client.connect(broker)
  82. print("Connecting to broker", broker)
  83. client.publish("Zeitintervall", intervall)
  84. client.on_connect = on_connect
  85. client.on_message = on_message
  86. client.on_log = on_log
  87. client.subscribe([("PhaseA", 0), ("PhaseB", 0), ("PhaseC", 0)])
  88. client.loop_forever()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement