Advertisement
Guest User

Untitled

a guest
Jul 16th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. from time import gmtime, strftime
  2. import paho.mqtt.client as mqtt
  3. import sqlite3
  4.  
  5. temperature_topic = "temperature"
  6. humidity_topic = "humidity"
  7. dbFile = "data.db"
  8.  
  9. dataTuple = [-1,-1]
  10.  
  11. # The callback for when the clientreceives a CONNACK responsefrom the server.
  12. def on_connect(client, userdata, flags, rc):
  13. print("Connected with result code "+str(rc))
  14.  
  15. # Subscribing in on_connect() meansthat if welose the connection and
  16. # reconnect then subscriptions will be renewed.
  17. client.subscribe(temperature_topic)
  18. client.subscribe(humidity_topic)
  19.  
  20. # The callbackfor when a PUBLISH message is received from the server.
  21. def on_message(client, userdata, msg):
  22. theTime = strftime("%Y-%m-%d %H:%M:%S", gmtime())
  23.  
  24. result = (theTime + "t" + str(msg.payload))
  25. print(msg.topic + ":t" + result)
  26. if (msg.topic == temperature_topic):
  27. dataTuple[0] = str(msg.payload)
  28. if (msg.topic == humidity_topic):
  29. dataTuple[1] = str(msg.payload)
  30. #return
  31. if (dataTuple[0] != -1 and dataTuple[1] != -1):
  32. writeToDb(theTime, dataTuple[0], dataTuple[1])
  33. return
  34.  
  35. def writeToDb(theTime, temperature, humidity):
  36. conn = sqlite3.connect(dbFile)
  37. c = conn.cursor()
  38. print "Writing to db..."
  39. c.execute("INSERT INTO climate VALUES (?,?,?)", (theTime, temperature, humidity))
  40. conn.commit()
  41.  
  42. global dataTuple
  43. dataTuple = [-1, -1]
  44.  
  45. client = mqtt.Client()
  46. client.on_connect = on_connect
  47. client.on_message = on_message
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement