Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
3.0 kB
3
Indexable
Never
import paho.mqtt.client as mqtt
import json
import xml.etree.ElementTree as ET
from datetime import datetime
import time

# Параметры подключения к MQTT-брокеру
HOST = "192.168.2.23"  # IP чемодана
PORT = 1883  # Стандартный порт подключения для Mosquitto
KEEPALIVE = 60  # Время ожидания доставки сообщения, если при отправке оно будет превышено, брокер будет считаться недоступным

# Словарь с топиками и собираемыми из них параметрами
SUB_TOPICS = {
    '/devices/wb-msw-v3_21/controls/Temperature': 'temperature',
    '/devices/wb-msw-v3_21/controls/Sound Level': 'sound',
    '/devices/wb-msw-v3_21/controls/CO2': 'concentration',
    '/devices/wb-msw-v3_21/controls/Air Quality (VOC)': 'value'
}

JSON_LIST = []

# Создание корневого элемента XML
root = ET.Element("data")

# Создание словарей для хранения данных JSON и XML
JSON_DICT = {}
XML_DICT = {}
for value in SUB_TOPICS.values():
    JSON_DICT[value] = 0
    XML_DICT[value] = ET.SubElement(root, value)


def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    for topic in SUB_TOPICS.keys():
        client.subscribe(topic)

global time
def on_message(client, userdata, msg):
    payload = msg.payload.decode()
    topic = msg.topic
    param_name = SUB_TOPICS[topic]
    JSON_DICT[param_name] = payload
    #time.sleep(5)
    timE = datetime.now()
    JSON_DICT['time'] = str(timE)
    JSON_DICT['id'] = str(23)
    # Запись данных в JSON файл
    JSON_LIST.append(JSON_DICT.copy())
    with open('data.json', 'w') as json_file:
        json_string = json.dumps(JSON_LIST) + "\n"
        json_file.write(json_string)

    # Запись данных в XML файл
    for key, value in XML_DICT.items():
        value.text = JSON_DICT[key]
    tree = ET.ElementTree(root)
    tree.write('data.xml')


def read_json_data(file_path):
    try:
        with open(file_path, 'r') as json_file:
            data = json.load(json_file)
            print("JSON Data:")
            print(data)
    except FileNotFoundError:
        print(f"File {file_path} not found")


def read_xml_data(file_path):
    try:
        tree = ET.parse(file_path)
        root = tree.getroot()
        print("XML Data:")
        for element in root.iter():
            if element.text is not None and element.text.strip() != "":
                print(f"{element.tag}: {element.text}")
    except FileNotFoundError:
        print(f"File {file_path} not found")


def main():
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect(HOST, PORT, KEEPALIVE)
    client.loop_start()

    while True:
        read_json_data('data.json')
        read_xml_data('data.xml')
        time.sleep(5)


if __name__ == "__main__":
    main()