Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import paho.mqtt.client as mqtt
- import csv
- import json
- import time
- mqtt_host = "127.0.0.1"
- mqtt_port = "1883"
- mqtt_user = "/vendingmachine:fahmi"
- mqtt_pass = "12345678"
- vending_id = "VMTB001"
- file_csv = "logs.csv"
- file_mode = "ab"
- def on_connect(client, userdata, flags, rc):
- global loop_flag
- print ("Connected with rc: " + str(rc))
- client.subscribe("vending/machine/" + vending_id + "/logs")
- def on_message(client, userdata, msg):
- print ("get data")
- data = json.loads(msg.payload)
- print (msg.payload)
- print ("encode to json")
- csv_file = open(file_csv, file_mode)
- writelog = csv.writer(csv_file)
- print ("open file")
- count = 0
- for item in data:
- print ("write value to csv")
- writelog.writerow(item.values())
- csv_file.close()
- def run():
- client = mqtt.Client()
- client.on_connect = on_connect
- client.on_message = on_message
- client.username_pw_set(mqtt_user, mqtt_pass)
- client.connect(mqtt_host, mqtt_port, 60)
- client.loop_forever()
- try:
- run()
- except:
- print("connection failed")
- time.sleep(45)
- run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement