import hashlib
import json
import zlib
from hbmqtt.client import MQTTClient
from hbmqtt.mqtt.constants import QOS_1
from pot_libs.settings import SETTING
class Publisher(object):
@classmethod
async def publish(cls, topic, sid, data):
host, port = SETTING.mqtt_host, SETTING.mqtt_port
client = MQTTClient(f'eems/td/{sid}')
pwd = hashlib.sha1(sid.encode('utf-8')).hexdigest()
uri = f'mqtt://{sid}:{pwd}@{host}:{port}'
await client.connect(uri)
data_str = json.dumps(data)
compress = zlib.compress(data_str.encode('utf-8'))
payload = bytearray(compress)
topic = f'eems/td/{topic}/{sid}'
try:
return await client.publish(topic, payload, qos=QOS_1)
finally:
await client.disconnect()
-
lcn authored7d4d2d0a