import json import os import threading import paho.mqtt.subscribe as mqtt database_file = "clients.json" database_lock = threading.Lock() # noinspection PyUnusedLocal def update_client_record(client, userdata, message): database_lock.acquire() if not os.path.exists(database_file): with open(database_file, 'w') as database_blank: json.dump({}, database_blank) with open(database_file, 'r') as infile: database = json.load(infile) 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) database_lock.release() 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)