Skip to content
Merged
Show file tree
Hide file tree
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
16 changes: 16 additions & 0 deletions Adafruit_IO/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@

import json

# MQTT RC Error Types
MQTT_ERRORS = [ 'Connection successful',
'Incorrect protocol version',
'Invalid Client ID',
'Server unavailable ',
'Bad username or password',
'Not authorized' ]

class AdafruitIOError(Exception):
"""Base class for all Adafruit IO request failures."""
pass
Expand Down Expand Up @@ -49,3 +57,11 @@ def __init__(self):
super(ThrottlingError, self).__init__("Exceeded the limit of Adafruit IO " \
"requests in a short period of time. Please reduce the rate of requests " \
"and try again later.")

class MQTTError(Exception):
"""Handles connection attempt failed errors.
"""
def __init__(self, response):
error = MQTT_ERRORS[response]
super(MQTTError, self).__init__(error)
pass
13 changes: 8 additions & 5 deletions Adafruit_IO/mqtt_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
import logging

import paho.mqtt.client as mqtt

import sys
from .errors import MQTTError, RequestError

# How long to wait before sending a keep alive (paho-mqtt configuration).
KEEP_ALIVE_SEC = 60 # One minute
Expand Down Expand Up @@ -62,11 +63,12 @@ def _mqtt_connect(self, client, userdata, flags, rc):
# Check if the result code is success (0) or some error (non-zero) and
# raise an exception if failed.
if rc == 0:
#raise RequestError(rc)
self._connected = True
print('Connected to Adafruit IO!')
else:
# TODO: Make explicit exception classes for these failures:
# 0: Connection successful 1: Connection refused - incorrect protocol version 2: Connection refused - invalid client identifier 3: Connection refused - server unavailable 4: Connection refused - bad username or password 5: Connection refused - not authorised 6-255: Currently unused.
raise RuntimeError('Error connecting to Adafruit IO with rc: {0}'.format(rc))
# handle RC errors within `errors.py`'s MQTTError class
raise MQTTError(rc)
# Call the on_connect callback if available.
if self.on_connect is not None:
self.on_connect(self)
Expand All @@ -78,7 +80,8 @@ def _mqtt_disconnect(self, client, userdata, rc):
# log the RC as an error. Continue on to call any disconnect handler
# so clients can potentially recover gracefully.
if rc != 0:
logger.debug('Unexpected disconnect with rc: {0}'.format(rc))
raise MQTTError(rc)
print('Disconnected from Adafruit IO!')
# Call the on_disconnect callback if available.
if self.on_disconnect is not None:
self.on_disconnect(self)
Expand Down