Untitled
unknown
plain_text
a month ago
2.0 kB
1
Indexable
Never
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 = [] 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_LIST.append(message_data) 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: time.sleep(5) # Пауза в 5 секунд для сбора данных current_time = str(datetime.now()) # Запись времени после сбора данных for data in JSON_LIST: data['time'] = current_time with open('data.json', 'w') as json_file: json_string = json.dumps(JSON_LIST, indent=4) json_file.write(json_string) JSON_LIST = [] # Очищаем список данных if __name__ == "__main__": main()