mqtt_client.py: move implemntation into MqttClient class

This commit is contained in:
coon 2025-09-26 23:35:19 +02:00
parent 5ae6d1f832
commit 6acb919486
2 changed files with 44 additions and 38 deletions

View file

@ -15,44 +15,54 @@ MQTT_COMMAND_TOPIC = "livingroom/voc/allen_heath_qu16_mixer"
m: Mixer = None
def mqtt_autodiscovery(client):
j = json.dumps(
{
"name": "Reset Settings",
"command_topic": MQTT_COMMAND_TOPIC,
"command_template": '{"command": "scene_recall", "args": {"scene_id": 0}}',
"device": {
"name": "Mischpult",
"model": "Qu-16",
"manufacturer": "Allen & Heath",
"suggested_area": "livingroom",
"identifiers": "Mischpult",
},
"unique_id": "mischpult_reset_settings",
}
)
class MqttClient:
def __init__(self):
self.client = mqtt.Client(callback_api_version=mqtt.CallbackAPIVersion.VERSION2)
client.publish(MQTT_DISCOVERY_TOPIC, payload=j, qos=0, retain=False)
def mqtt_autodiscovery(self, client):
j = json.dumps(
{
"name": "Reset Settings",
"command_topic": MQTT_COMMAND_TOPIC,
"command_template": '{"command": "scene_recall", "args": {"scene_id": 0}}',
"device": {
"name": "Mischpult",
"model": "Qu-16",
"manufacturer": "Allen & Heath",
"suggested_area": "livingroom",
"identifiers": "Mischpult",
},
"unique_id": "mischpult_reset_settings",
}
)
self, client.publish(MQTT_DISCOVERY_TOPIC, payload=j, qos=0, retain=False)
def on_connect(client, userdata, flags, reason_code, properties):
print(f"Connected: {reason_code}")
client.subscribe(MQTT_COMMAND_TOPIC)
mqtt_autodiscovery(client)
def on_connect(self, client, userdata, flags, reason_code, properties):
print(f"Connected: {reason_code}")
client.subscribe(MQTT_COMMAND_TOPIC)
self.mqtt_autodiscovery(client)
def on_message(client, userdata, msg):
payload = msg.payload.decode()
def on_message(self, client, userdata, msg):
payload = msg.payload.decode()
print(f"{msg.topic}: {payload}")
print(f"{msg.topic}: {payload}")
j = json.loads(payload)
j = json.loads(payload)
match j["command"]:
case "scene_recall":
m.scene_recall(j["args"]["scene_id"])
case "shutdown":
m.shutdown()
match j["command"]:
case "scene_recall":
m.scene_recall(j["args"]["scene_id"])
case "shutdown":
m.shutdown()
def run(self, hostname):
self.client.on_connect = self.on_connect
self.client.on_message = self.on_message
self.client.connect(hostname, MQTT_SERVER_PORT, 60)
self.client.loop_forever()
def main():
@ -78,12 +88,8 @@ def main():
global m
m = mixer.Mixer(args.mixer_ip)
client = mqtt.Client(callback_api_version=mqtt.CallbackAPIVersion.VERSION2)
client.on_connect = on_connect
client.on_message = on_message
client.connect(args.mqtt_hostname, MQTT_SERVER_PORT, 60)
client.loop_forever()
client = MqttClient()
client.run(args.mqtt_hostname)
if __name__ == "__main__":