torch-subscriber-simple/torch_sub/torch_sub.py

40 lines
1023 B
Python
Raw Normal View History

import json
import os
2020-10-16 09:47:37 +00:00
import threading
import paho.mqtt.subscribe as mqtt
2020-10-16 09:48:12 +00:00
database_filename = "clients.json"
2020-10-16 09:47:37 +00:00
database_lock = threading.Lock()
# noinspection PyUnusedLocal
def update_client_record(client, userdata, message):
2020-10-16 09:47:37 +00:00
database_lock.acquire()
2020-10-16 09:48:12 +00:00
if not os.path.exists(database_filename):
with open(database_filename, 'w') as database_blank:
2020-10-16 09:47:37 +00:00
json.dump({}, database_blank)
2020-10-16 09:48:12 +00:00
with open(database_filename, 'r') as infile:
2020-10-16 09:47:37 +00:00
database = json.load(infile)
payload = message.payload.decode('utf-8')
response = json.loads(payload)
database[response['clientId']] = response
2020-10-16 09:48:12 +00:00
with open(database_filename, 'w') as outfile:
json.dump(database, outfile)
2020-10-16 09:47:37 +00:00
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)