Advertisement
vitareinforce

log.py

Dec 4th, 2018
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.13 KB | None | 0 0
  1. import paho.mqtt.client as mqtt
  2. import csv
  3. import json
  4. import time
  5.  
  6. mqtt_host = "127.0.0.1"
  7. mqtt_port = "1883"
  8. mqtt_user = "/vendingmachine:fahmi"
  9. mqtt_pass = "12345678"
  10. vending_id = "VMTB001"
  11. file_csv = "logs.csv"
  12. file_mode = "ab"
  13.  
  14. def on_connect(client, userdata, flags, rc):
  15.     global loop_flag
  16.     print ("Connected with rc: " + str(rc))
  17.     client.subscribe("vending/machine/" + vending_id + "/logs")
  18.  
  19. def on_message(client, userdata, msg):
  20.     print ("get data")
  21.     data = json.loads(msg.payload)
  22.     print (msg.payload)
  23.     print ("encode to json")
  24.     csv_file = open(file_csv, file_mode)
  25.     writelog = csv.writer(csv_file)
  26.     print ("open file")
  27.     count = 0
  28.     for item in data:
  29.         print ("write value to csv")
  30.         writelog.writerow(item.values())
  31.     csv_file.close()
  32.    
  33. def run():
  34.     client = mqtt.Client()
  35.     client.on_connect = on_connect
  36.     client.on_message = on_message
  37.     client.username_pw_set(mqtt_user, mqtt_pass)
  38.     client.connect(mqtt_host, mqtt_port, 60)
  39.     client.loop_forever()  
  40.    
  41. try:
  42.     run()
  43. except:
  44.     print("connection failed")
  45.     time.sleep(45)
  46.     run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement