Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.4 kB
4
Indexable
import paho.mqtt.client as mqtt
import json
from datetime import datetime
import time

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

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

JSON_LIST = []

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

record_time_flag = False  # Flag to record time after all sensor data

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

def on_message(client, userdata, msg):
    payload = msg.payload.decode()
    topic = msg.topic
    param_name = SUB_TOPICS[topic]

    message_data = {}
    message_data[param_name] = payload

    # Запись данных в JSON файл
    JSON_LIST.append(message_data)

    global record_time_flag
    if not record_time_flag:
        JSON_LIST[-1]['time'] = str(datetime.now())
        record_time_flag = True

def read_json_data(file_path):
    try:
        with open(file_path, 'r') as json_file:
            data = json.load(json_file)  # Загружаем JSON-данные
            print("JSON Data:")
            print(data)
    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')
        time.sleep(5)

if __name__ == "__main__":
    main()