@@ -77,6 +77,24 @@ def _crc16(data):
77
77
return crc
78
78
79
79
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
+
80
98
class AM2320 :
81
99
"""A driver for the AM2320 temperature and humidity sensor.
82
100
@@ -93,7 +111,7 @@ def __init__(self, i2c_bus, address=AM2320_DEFAULT_ADDR):
93
111
except ValueError :
94
112
pass
95
113
time .sleep (0.25 )
96
- raise ValueError ( " AM2320 not found" )
114
+ raise AM2320DeviceNotFound ( ' AM2320 not found' )
97
115
98
116
def _read_register (self , register , length ):
99
117
with self ._i2c as i2c :
@@ -114,12 +132,12 @@ def _read_register(self, register, length):
114
132
# print("$%02X => %s" % (register, [hex(i) for i in result]))
115
133
# Check preamble indicates correct readings
116
134
if result [0 ] != 0x3 or result [1 ] != length :
117
- raise RuntimeError ('I2C read failure' )
135
+ raise AM2320ReadError ('I2C read failure' )
118
136
# Check CRC on all but last 2 bytes
119
137
crc1 = struct .unpack ("<H" , bytes (result [- 2 :]))[0 ]
120
138
crc2 = _crc16 (result [0 :- 2 ])
121
139
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 ))
123
141
return result [2 :- 2 ]
124
142
125
143
@property
0 commit comments