Skip to content

Commit ac789fb

Browse files
committed
Convert _generate_crc() to function outside of class
1 parent 50be0df commit ac789fb

File tree

1 file changed

+17
-16
lines changed

1 file changed

+17
-16
lines changed

adafruit_ags02ma.py

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,21 @@
4848
_AGS02MA_CRC8_POLYNOMIAL = const(0x31)
4949

5050

51+
def _generate_crc(data):
52+
"""8-bit CRC algorithm for checking data"""
53+
crc = _AGS02MA_CRC8_INIT
54+
# calculates 8-Bit checksum with given polynomial
55+
for byte in data:
56+
crc ^= byte
57+
for _ in range(8):
58+
if crc & 0x80:
59+
crc = (crc << 1) ^ _AGS02MA_CRC8_POLYNOMIAL
60+
else:
61+
crc <<= 1
62+
crc &= 0xFF
63+
return crc & 0xFF
64+
65+
5166
class AGS02MA:
5267
"""Driver for the AGS02MA air quality sensor
5368
:param ~busio.I2C i2c_bus: The I2C bus the AGS02MA is connected to.
@@ -95,7 +110,7 @@ def set_address(self, new_addr):
95110
0,
96111
]
97112
)
98-
_buf[5] = self._generate_crc(_buf[1:5])
113+
_buf[5] = _generate_crc(_buf[1:5])
99114
with self.i2c_device as i2c:
100115
i2c.write(_buf)
101116

@@ -106,22 +121,8 @@ def _read_reg(self, addr, delayms):
106121
time.sleep(delayms / 1000)
107122
i2c.readinto(self._buf)
108123
# print([hex(x) for x in self._buf])
109-
if self._generate_crc(self._buf) != 0:
124+
if _generate_crc(self._buf) != 0:
110125
raise RuntimeError("CRC check failed")
111126
val, crc = struct.unpack(">IB", self._buf) # pylint: disable=unused-variable
112127
# print(hex(val), hex(crc))
113128
return val
114-
115-
def _generate_crc(self, data):
116-
"""8-bit CRC algorithm for checking data"""
117-
crc = _AGS02MA_CRC8_INIT
118-
# calculates 8-Bit checksum with given polynomial
119-
for byte in data:
120-
crc ^= byte
121-
for _ in range(8):
122-
if crc & 0x80:
123-
crc = (crc << 1) ^ _AGS02MA_CRC8_POLYNOMIAL
124-
else:
125-
crc <<= 1
126-
crc &= 0xFF
127-
return crc & 0xFF

0 commit comments

Comments
 (0)