From c9ece6ca0403cab9e399322a739ca51199907863 Mon Sep 17 00:00:00 2001 From: "Austin S. Hemmelgarn" Date: Tue, 8 Oct 2019 13:55:33 -0400 Subject: [PATCH] Add custom exception classes instead of using plain error types. This adds custom exception classes so that users do not have to match on generic exception types in code that uses this module. The new custom classes are structured so that existing code that is matching on the generic exception types will still work, and so that there's a primary exception type that can be matched on to catch all errors specific to this module. --- adafruit_am2320.py | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/adafruit_am2320.py b/adafruit_am2320.py index 59fac53..26d56f2 100644 --- a/adafruit_am2320.py +++ b/adafruit_am2320.py @@ -77,6 +77,24 @@ def _crc16(data): return crc +class AM2320Exception(Exception): + """Base class for exceptions.""" + pass + + +class AM2320DeviceNotFound(AM2320Exception, ValueError): + """Indicates that a device couldn't be found.""" + pass + + +class AM2320ReadError(AM2320Exception, RuntimeError): + """indicates that valid data could not be read from the sensor. + + This may be due to a regular I2C read failure, or due to a checksum + mismatch.""" + pass + + class AM2320: """A driver for the AM2320 temperature and humidity sensor. @@ -93,7 +111,7 @@ def __init__(self, i2c_bus, address=AM2320_DEFAULT_ADDR): except ValueError: pass time.sleep(0.25) - raise ValueError("AM2320 not found") + raise AM2320DeviceNotFound('AM2320 not found') def _read_register(self, register, length): with self._i2c as i2c: @@ -114,12 +132,12 @@ def _read_register(self, register, length): # print("$%02X => %s" % (register, [hex(i) for i in result])) # Check preamble indicates correct readings if result[0] != 0x3 or result[1] != length: - raise RuntimeError('I2C read failure') + raise AM2320ReadError('I2C read failure') # Check CRC on all but last 2 bytes crc1 = struct.unpack("