Untitled
unknown
plain_text
2 years ago
1.1 kB
11
Indexable
import paho.mqtt.client as mqtt
import json
import xml.etree.ElementTree as ET
from datetime import datetime
import time
# ... (previous code remains the same)
# Dictionary to store data by timestamp
JSON_DICT_BY_TIME = {}
def on_message(client, userdata, msg):
payload = msg.payload.decode()
topic = msg.topic
param_name = SUB_TOPICS[topic]
current_time = str(datetime.now())
# Update the data in JSON_DICT and JSON_DICT_BY_TIME
JSON_DICT[param_name] = payload
JSON_DICT['time'] = current_time
JSON_DICT_BY_TIME[current_time] = JSON_DICT
# Write data to JSON file with only the most recent data per timestamp
JSON_LIST = list(JSON_DICT_BY_TIME.values())
with open('data.json', 'w') as json_file:
json_string = json.dumps(JSON_LIST)
json_file.write(json_string)
# Update data in XML
for key, value in XML_DICT.items():
value.text = JSON_DICT[key]
tree = ET.ElementTree(root)
tree.write('data.xml')
print(topic + " " + payload)
# ... (rest of the code remains the same)
if __name__ == "__main__":
main()
Editor is loading...