Skip to content

Commit cbc1863

Browse files
authored
Merge pull request #9 from Ferroin/master
Add custom exception classes instead of using plain error types.
2 parents a29fe90 + c9ece6c commit cbc1863

File tree

1 file changed

+21
-3
lines changed

1 file changed

+21
-3
lines changed

adafruit_am2320.py

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,24 @@ def _crc16(data):
7777
return crc
7878

7979

80+
class AM2320Exception(Exception):
81+
"""Base class for exceptions."""
82+
pass
83+
84+
85+
class AM2320DeviceNotFound(AM2320Exception, ValueError):
86+
"""Indicates that a device couldn't be found."""
87+
pass
88+
89+
90+
class AM2320ReadError(AM2320Exception, RuntimeError):
91+
"""indicates that valid data could not be read from the sensor.
92+
93+
This may be due to a regular I2C read failure, or due to a checksum
94+
mismatch."""
95+
pass
96+
97+
8098
class AM2320:
8199
"""A driver for the AM2320 temperature and humidity sensor.
82100
@@ -93,7 +111,7 @@ def __init__(self, i2c_bus, address=AM2320_DEFAULT_ADDR):
93111
except ValueError:
94112
pass
95113
time.sleep(0.25)
96-
raise ValueError("AM2320 not found")
114+
raise AM2320DeviceNotFound('AM2320 not found')
97115

98116
def _read_register(self, register, length):
99117
with self._i2c as i2c:
@@ -114,12 +132,12 @@ def _read_register(self, register, length):
114132
# print("$%02X => %s" % (register, [hex(i) for i in result]))
115133
# Check preamble indicates correct readings
116134
if result[0] != 0x3 or result[1] != length:
117-
raise RuntimeError('I2C read failure')
135+
raise AM2320ReadError('I2C read failure')
118136
# Check CRC on all but last 2 bytes
119137
crc1 = struct.unpack("<H", bytes(result[-2:]))[0]
120138
crc2 = _crc16(result[0:-2])
121139
if crc1 != crc2:
122-
raise RuntimeError('CRC failure 0x%04X vs 0x%04X' % (crc1, crc2))
140+
raise AM2320ReadError('CRC failure 0x%04X vs 0x%04X' % (crc1, crc2))
123141
return result[2:-2]
124142

125143
@property

0 commit comments

Comments
 (0)