craftbeerpi4-pione/cbpi/extension/mqtt/__init__.py

43 lines
1.3 KiB
Python
Raw Normal View History

2019-07-31 07:58:54 +02:00
import json
from cbpi.utils.encoder import ComplexEncoder
from hbmqtt.mqtt.constants import QOS_0
from hbmqtt.client import MQTTClient
2021-02-02 21:22:59 +01:00
from hbmqtt.mqtt.constants import QOS_1, QOS_2
from asyncio_mqtt import Client, MqttError, Will
import asyncio
2019-07-31 07:58:54 +02:00
class CBPiMqttClient:
def __init__(self, cbpi):
self.cbpi = cbpi
self.cbpi.bus.register("#", self.listen)
self.client = None
2021-02-02 21:22:59 +01:00
self._loop = asyncio.get_event_loop()
self._loop.create_task(self.init_client(self.cbpi))
2019-07-31 07:58:54 +02:00
async def init_client(self, cbpi):
2021-02-02 21:22:59 +01:00
async with Client("localhost", will=Will(topic="cbpi/diconnect", payload="MY CLIENT"))as client:
async with client.filtered_messages("cbpi/#") as messages:
await client.subscribe("cbpi/#")
async for message in messages:
await self.cbpi.actor.on("YwGzXvWMpmbLb6XobesL8n")
print(message.topic, message.payload.decode())
2019-07-31 07:58:54 +02:00
async def listen(self, topic, **kwargs):
if self.client is not None:
await self.client.publish(topic, str.encode(json.dumps(kwargs, cls=ComplexEncoder)), QOS_0)
def setup(cbpi):
'''
This method is called by the server during startup
Here you need to register your plugins at the server
:param cbpi: the cbpi core
:return:
'''
2021-02-02 21:22:59 +01:00
2019-08-05 23:00:18 +02:00
client = CBPiMqttClient(cbpi)