Skip to content

Add option to suppress error and more init checks #8

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 14, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 27 additions & 12 deletions adafruit_funhouse/network.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ def __init__(
debug=debug,
)
self._mqtt_client = None
self.mqtt_connect = None

def init_io_mqtt(self):
"""Initialize MQTT for Adafruit IO"""
Expand Down Expand Up @@ -99,34 +98,50 @@ def init_mqtt(
)
if use_io:
self._mqtt_client = IO_MQTT(self._mqtt_client)
self.mqtt_connect = self._mqtt_client.connect

return self._mqtt_client

# pylint: enable=too-many-arguments

def _get_mqtt_client(self):
print(self._mqtt_client)
if self._mqtt_client is not None:
return self._mqtt_client
raise RuntimeError("Please initialize MQTT before using")

def mqtt_loop(self, *args, **kwargs):
def mqtt_loop(self, *args, suppress_mqtt_errors=True, **kwargs):
"""Run the MQTT Loop"""
try:
self._get_mqtt_client()
if suppress_mqtt_errors:
try:
if self._mqtt_client is not None:
self._mqtt_client.loop(*args, **kwargs)
except MQTT.MMQTTException as err:
print("MMQTTException: {0}".format(err))
except OSError as err:
print("OSError: {0}".format(err))
else:
if self._mqtt_client is not None:
self._mqtt_client.loop(*args, **kwargs)
except MQTT.MMQTTException as err:
print("MMQTTException: {0}".format(err))
except OSError as err:
print("OSError: {0}".format(err))

def mqtt_publish(self, *args, **kwargs):
def mqtt_publish(self, *args, suppress_mqtt_errors=True, **kwargs):
"""Publish to MQTT"""
try:
self._get_mqtt_client()
if suppress_mqtt_errors:
try:
if self._mqtt_client is not None:
self._mqtt_client.publish(*args, **kwargs)
except OSError as err:
print("OSError: {0}".format(err))
else:
if self._mqtt_client is not None:
self._mqtt_client.publish(*args, **kwargs)
except OSError as err:
print("OSError: {0}".format(err))

def mqtt_connect(self, *args, **kwargs):
"""Connect to MQTT"""
self._get_mqtt_client()
if self._mqtt_client is not None:
self._mqtt_client.connect(*args, **kwargs)

@property
def on_mqtt_connect(self):
Expand Down