#include "mgos.h"
#include "tests_autogen.h"
#include <fcntl.h>
#include <math.h>
#include <sys/ioctl.h>

#define I2CBUSNR    7

bool i2c_dumpregs(struct mgos_i2c *i2c, uint8_t i2caddr);
void i2c_scanner(struct mgos_i2c *i2c, bool dumpregs);

void i2c_scanner(struct mgos_i2c *i2c, bool dumpregs) {
  int i;

  if (!i2c) {
    LOG(LL_ERROR, ("No global I2C bus configured"));
    return;
  }

  for (i = 0x3; i < 0x77; i++) {
    bool ret;
    ret = mgos_i2c_read(i2c, i, NULL, 0, true);
    if (ret) {
      LOG(LL_INFO, ("I2C Address 0x%02x %s", i, ret ? "true" : "false"));
      if (dumpregs) i2c_dumpregs(i2c, i);
    }
  }
}

bool i2c_dumpregs(struct mgos_i2c *i2c, uint8_t i2caddr) {
  uint16_t reg;
  int      value;

  for (reg = 0; reg < 256; reg++) {
    value = mgos_i2c_read_reg_b(i2c, i2caddr, reg);
    if (value < 0) {
      printf(" XX");
    }else {
      printf(" %02x", value);
    }
    if (reg % 16 == 15) {
      printf("\n");
    }
  }
  printf("\n");
  return true;
}

int main(int argc, char **argv, char **environ) {
  struct mgos_i2c *    i2c = NULL;

  if (!mgos_i2c_open(I2CBUSNR)) {
    LOG(LL_ERROR, ("Cannot open I2C bus %u", I2CBUSNR));
    return -1;
  }
  if (!(i2c = mgos_i2c_get_global())) {
    LOG(LL_ERROR, ("Cannot open I2C bus"));
    return -2;
  }

  i2c_scanner(i2c, true);

  tests_create();
  tests_run();
  tests_destroy();

  return 0;
  (void)argc;
  (void)argv;
  (void)environ;
}
