2020-10-15 14:44:34 +00:00
|
|
|
import json
|
2020-10-15 17:48:48 +00:00
|
|
|
import os
|
2020-10-16 09:47:37 +00:00
|
|
|
import threading
|
2020-10-15 14:44:34 +00:00
|
|
|
|
2020-10-15 17:07:17 +00:00
|
|
|
import paho.mqtt.subscribe as mqtt
|
2020-10-15 14:44:34 +00:00
|
|
|
|
2020-10-15 17:48:48 +00:00
|
|
|
database_file = "clients.json"
|
2020-10-16 09:47:37 +00:00
|
|
|
database_lock = threading.Lock()
|
2020-10-15 17:07:17 +00:00
|
|
|
|
2020-10-15 17:48:48 +00:00
|
|
|
# noinspection PyUnusedLocal
|
|
|
|
def update_client_record(client, userdata, message):
|
2020-10-15 17:07:17 +00:00
|
|
|
|
2020-10-16 09:47:37 +00:00
|
|
|
database_lock.acquire()
|
|
|
|
|
2020-10-15 17:48:48 +00:00
|
|
|
if not os.path.exists(database_file):
|
|
|
|
with open(database_file, 'w') as database_blank:
|
2020-10-16 09:47:37 +00:00
|
|
|
json.dump({}, database_blank)
|
2020-10-15 17:07:17 +00:00
|
|
|
|
2020-10-15 17:48:48 +00:00
|
|
|
with open(database_file, 'r') as infile:
|
2020-10-16 09:47:37 +00:00
|
|
|
database = json.load(infile)
|
2020-10-15 17:07:17 +00:00
|
|
|
|
2020-10-15 17:48:48 +00:00
|
|
|
payload = message.payload.decode('utf-8')
|
2020-10-15 17:07:17 +00:00
|
|
|
response = json.loads(payload)
|
|
|
|
|
|
|
|
database[response['clientId']] = response
|
|
|
|
|
2020-10-15 17:48:48 +00:00
|
|
|
with open(database_file, 'w') as outfile:
|
2020-10-15 17:07:17 +00:00
|
|
|
json.dump(database, outfile)
|
|
|
|
|
2020-10-16 09:47:37 +00:00
|
|
|
database_lock.release()
|
|
|
|
|
2020-10-15 17:07:17 +00:00
|
|
|
|
2020-10-16 08:57:38 +00:00
|
|
|
def subscribe(broker_hostname, broker_port, topic="torch", tls=None, auth=None):
|
2020-10-15 17:48:48 +00:00
|
|
|
mqtt.callback(update_client_record,
|
2020-10-15 17:07:17 +00:00
|
|
|
topic,
|
2020-10-15 17:48:48 +00:00
|
|
|
hostname=broker_hostname,
|
|
|
|
port=broker_port,
|
2020-10-16 08:57:38 +00:00
|
|
|
tls=tls,
|
|
|
|
auth=auth)
|