diff --git a/torch_sub/torch_sub.py b/torch_sub/torch_sub.py index e2cc45c..b318d5f 100644 --- a/torch_sub/torch_sub.py +++ b/torch_sub/torch_sub.py @@ -1,20 +1,23 @@ 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: - database_blank.write("{}") + json.dump({}, database_blank) with open(database_file, 'r') as infile: - database = json.loads(infile.read()) + database = json.load(infile) payload = message.payload.decode('utf-8') response = json.loads(payload) @@ -24,6 +27,8 @@ def update_client_record(client, userdata, message): 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,