Skip to content

Commit

Permalink
Adds exception check to MQTT class
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexxIT committed Dec 1, 2021
1 parent ac33276 commit f346c56
Showing 1 changed file with 23 additions and 7 deletions.
30 changes: 23 additions & 7 deletions custom_components/xiaomi_gateway3/core/mini_mqtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@
"""
import asyncio
import json
import logging
import random
from asyncio import StreamReader, StreamWriter
from typing import Optional

_LOGGER = logging.getLogger(__name__)

CONNECT = 1
CONNACK = 2
PUBLISH = 3
Expand Down Expand Up @@ -177,14 +180,20 @@ async def connect(self, host: str):

async def disconnect(self):
msg = RawMessage.disconnect()
self.writer.write(msg)
await self.writer.drain()
try:
self.writer.write(msg)
await self.writer.drain()
except:
_LOGGER.exception("Can't disconnect from gateway")

async def subscribe(self, topic: str):
self.msg_id += 1
msg = RawMessage.subscribe(self.msg_id, topic)
self.writer.write(msg)
await self.writer.drain()
try:
self.writer.write(msg)
await self.writer.drain()
except:
_LOGGER.exception(f"Can't subscribe to {topic}")

async def publish(self, topic: str, payload, retain=False):
if isinstance(payload, str):
Expand All @@ -194,8 +203,11 @@ async def publish(self, topic: str, payload, retain=False):

# no response for QoS 0
msg = RawMessage.publish(topic, payload, retain)
self.writer.write(msg)
await self.writer.drain()
try:
self.writer.write(msg)
await self.writer.drain()
except:
_LOGGER.exception(f"Can't publish {payload} to {topic}")

async def read(self) -> Optional[MQTTMessage]:
raw = await self.reader.read(1)
Expand Down Expand Up @@ -231,9 +243,13 @@ async def read(self) -> Optional[MQTTMessage]:
return msg

async def close(self):
if self.writer:
if not self.writer:
return
try:
self.writer.close()
await self.writer.wait_closed()
except:
_LOGGER.exception("Can't close connection")

def __aiter__(self):
return self
Expand Down

0 comments on commit f346c56

Please sign in to comment.