torch-subscriber-simple/torch_sub/torch_sub.py

35 lines
901 B
Python

import json
import os
import paho.mqtt.subscribe as mqtt
database_file = "clients.json"
# noinspection PyUnusedLocal
def update_client_record(client, userdata, message):
if not os.path.exists(database_file):
with open(database_file, 'w') as database_blank:
database_blank.write("{}")
with open(database_file, 'r') as infile:
database = json.loads(infile.read())
payload = message.payload.decode('utf-8')
response = json.loads(payload)
database[response['clientId']] = response
with open(database_file, 'w') as outfile:
json.dump(database, outfile)
def subscribe(broker_hostname, broker_port, topic="torch", tls=None, auth=None):
mqtt.callback(update_client_record,
topic,
hostname=broker_hostname,
port=broker_port,
tls=tls,
auth=auth)