#ifndef AHT20_H
#define AHT20_H

#include <stdint.h>

#define AHT20_ADDR 0x38           // AHT default i2c address
#define AHT20_CMD_CALIBRATE 0xBE  // Calibration command
#define AHT20_CMD_TRIGGER 0xAC    // Trigger reading command
#define AHT20_CMD_SOFTRESET 0xBA  // Soft reset command
#define AHT20_CMD_STATUS 0x71
#define AHT20_STATUS_BUSY 0x80        // Status bit for busy
#define AHT20_STATUS_CALIBRATED 0x08  // Status bit for calibrated

#define AHT20_OK 0x00
#define AHT20_ERR_INIT 0x01  // Initialization or Calibration failed
#define AHT20_ERR_BUSY 0x02  // Sensor measurement timeout
#define AHT20_ERR_CRC 0x03   // Data corruption detected
#define AHT20_ERR_I2C 0x04   // Generic I2C Bus error (NACK)

#define STATUS_BUSY_BIT (1 << 7)
#define STATUS_CAL_BIT (1 << 3)

typedef struct {
  uint32_t hum_p_x100;  // %RH * 100
  int32_t temp_c_x100;  // DegC * 100
} aht20_data;

/**
 * Init sensor
 * Checks status 0x71 and performs calibration (0xBE) if required
 */
uint8_t aht20_init(void);

/**
 * Trigger measurement, wait >80ms, poll busy bit, and read data
 * Checks CRC8
 */
uint8_t aht20_read(aht20_data* out_data);

#endif  // AHT20_H
