# Path: IoTPy/errors.py
# class IoTPy_ThingError(Exception):
#     pass


from time import sleep
from struct import unpack
from IoTPy.errors import IoTPy_ThingError

    :param interface:  I2C communication interface.
    :type interface: :class:`IoTPy.pyuper.i2c.I2C`
    :param sensor_address: AM2321 sensor I2C address. Optional, default 0x5C (92).
    :type sensor_address: int
    """

    def __init__(self, interface, sensor_address= 0x5c):
        self.interface = interface
        self.address = sensor_address
        self.temperature = -1000.0
        self.humidity = -1

    def __enter__(self):
        return self

    def __exit__(self, ex_type, ex_value, traceback):
        pass

    def _read_raw(self, command, regaddr, regcount):
        self.interface.transaction(self.address, b'\0', 0)
        self.interface.transaction(self.address, command+regaddr+chr(regcount).encode('latin-1'), 0)
        sleep(0.002)
        buf, err = self.interface.transaction(self.address, b'', regcount + 4)

        if err:
            raise IoTPy_ThingError("AM2321 reading error.")

        crc = unpack('<H', buf[-2:])[0]
        if crc != self._am_crc16(buf[:-2]):

# Path: IoTPy/errors.py
# class IoTPy_ThingError(Exception):
#     pass


# Path: IoTPy/things/am2321.py
from time import sleep
from struct import unpack
from IoTPy.errors import IoTPy_ThingError


    :param interface:  I2C communication interface.
    :type interface: :class:`IoTPy.pyuper.i2c.I2C`
    :param sensor_address: AM2321 sensor I2C address. Optional, default 0x5C (92).
    :type sensor_address: int
    """

    def __init__(self, interface, sensor_address= 0x5c):
        self.interface = interface
        self.address = sensor_address
        self.temperature = -1000.0
        self.humidity = -1

    def __enter__(self):
        return self

    def __exit__(self, ex_type, ex_value, traceback):
        pass

    def _read_raw(self, command, regaddr, regcount):
        self.interface.transaction(self.address, b'\0', 0)
        self.interface.transaction(self.address, command+regaddr+chr(regcount).encode('latin-1'), 0)
        sleep(0.002)
        buf, err = self.interface.transaction(self.address, b'', regcount + 4)

        if err:
            raise IoTPy_ThingError("AM2321 reading error.")

        crc = unpack('<H', buf[-2:])[0]
        if crc != self._am_crc16(buf[:-2]):

            raise IoTPy_ThingError("AM2321 CRC error.")