50 lines
1.5 KiB
Python
Executable File
50 lines
1.5 KiB
Python
Executable File
#!/usr/bin/python3
|
|
import json
|
|
import os.path
|
|
import sys
|
|
from collections import defaultdict
|
|
|
|
import paho.mqtt.client as mqtt
|
|
|
|
|
|
# The callback for when the client receives a CONNACK response from the server.
|
|
def on_connect(client, userdata, flags, rc):
|
|
print("Connected with result code " + str(rc))
|
|
|
|
# Subscribing in on_connect() means that if we lose the connection and
|
|
# reconnect then subscriptions will be renewed.
|
|
client.subscribe("router7/#")
|
|
|
|
|
|
def get_leases():
|
|
msgs = defaultdict(lambda: defaultdict(str))
|
|
|
|
# The callback for when a PUBLISH message is received from the server.
|
|
def on_message(client, userdata, msg):
|
|
lease = json.loads(msg.payload)
|
|
lease["identifier"] = os.path.basename(msg.topic)
|
|
msgs[lease["hardware_addr"].lower()] = defaultdict(str, lease)
|
|
with open(sys.argv[1], mode="w", encoding="utf-8") as file:
|
|
file.write(json.dumps(msgs) + "\n")
|
|
|
|
client = mqtt.Client()
|
|
client.username_pw_set(os.getenv("MQTT_USERNAME"), os.getenv("MQTT_PASSWORD"))
|
|
client.on_connect = on_connect
|
|
client.on_message = on_message
|
|
|
|
client.connect("hassio.narnian.us", 1883, 60)
|
|
|
|
# Blocking call that processes network traffic, dispatches callbacks and
|
|
# handles reconnecting.
|
|
# Other loop*() functions are available that give a threaded interface and a
|
|
# manual interface.
|
|
|
|
cont = True
|
|
while cont:
|
|
client.loop(timeout=0.5)
|
|
return msgs
|
|
|
|
|
|
for m in get_leases():
|
|
print(json.dumps(m))
|