2020-10-15 14:44:34 +00:00
|
|
|
import json
|
2020-10-15 17:48:48 +00:00
|
|
|
import os
|
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-15 14:44:34 +00:00
|
|
|
|
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-15 17:48:48 +00:00
|
|
|
if not os.path.exists(database_file):
|
|
|
|
with open(database_file, 'w') as database_blank:
|
|
|
|
database_blank.write("{}")
|
2020-10-15 17:07:17 +00:00
|
|
|
|
2020-10-15 17:48:48 +00:00
|
|
|
with open(database_file, 'r') as infile:
|
|
|
|
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-15 17:48:48 +00:00
|
|
|
def subscribe(broker_hostname, broker_port, topic="torch", ca_file=None, cert_file=None, key_file=None):
|
|
|
|
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-15 17:07:17 +00:00
|
|
|
tls={
|
2020-10-15 17:48:48 +00:00
|
|
|
'ca_certs': ca_file,
|
|
|
|
'certfile': cert_file,
|
|
|
|
'keyfile': key_file
|
|
|
|
})
|