#include <stdio.h>
#include "esp_log.h"
#include "driver/i2c.h"
#include "gw_grayscale_sensor.h"

static const char *TAG = "gw gray i2c example";

#define I2C_MASTER_SCL_IO           22      /*!< I2C 时钟针脚号  */
#define I2C_MASTER_SDA_IO           21      /*!< I2C 数据针脚号  */
#define I2C_MASTER_NUM              0       /*!< I2C 通道       */
#define I2C_MASTER_FREQ_HZ          100000  /*!< I2C 主的时钟频率 */
#define I2C_MASTER_TX_BUF_DISABLE   0       /*!< I2C 不设输出缓冲 */
#define I2C_MASTER_RX_BUF_DISABLE   0       /*!< I2C 不设输入缓冲 */
#define I2C_MASTER_TIMEOUT_MS       0

#define GW_GRAY_ADDR GW_GRAY_ADDR_DEF /*! 使用默认地址 */

static esp_err_t gw_gray_write_cmd(uint8_t cmd)
{
	esp_err_t err;
	err = i2c_master_write_to_device(I2C_MASTER_NUM, GW_GRAY_ADDR,
							   &cmd, 1, pdMS_TO_TICKS(I2C_MASTER_TIMEOUT_MS));
	return err;
}

static esp_err_t gw_gray_read_byte(uint8_t *byte_read)
{
	esp_err_t err;
	err = i2c_master_read_from_device(I2C_MASTER_NUM, GW_GRAY_ADDR,
								byte_read, 1, pdMS_TO_TICKS(I2C_MASTER_TIMEOUT_MS));
	return err;
}

static esp_err_t gw_gray_read(uint8_t *read_arr, size_t read_size)
{
	esp_err_t err;
	err = i2c_master_read_from_device(I2C_MASTER_NUM, GW_GRAY_ADDR,
	                                  read_arr, read_size, pdMS_TO_TICKS(I2C_MASTER_TIMEOUT_MS));
	return err;
}

static esp_err_t i2c_master_init(void)
{
    int i2c_master_port = I2C_MASTER_NUM;

    i2c_config_t conf = {
        .mode = I2C_MODE_MASTER,
        .sda_io_num = I2C_MASTER_SDA_IO,
        .scl_io_num = I2C_MASTER_SCL_IO,
        .sda_pullup_en = GPIO_PULLUP_ENABLE,
        .scl_pullup_en = GPIO_PULLUP_ENABLE,
        .master.clk_speed = I2C_MASTER_FREQ_HZ,
    };

    i2c_param_config(i2c_master_port, &conf);

    return i2c_driver_install(i2c_master_port, conf.mode, I2C_MASTER_RX_BUF_DISABLE, I2C_MASTER_TX_BUF_DISABLE, 0);
}


void app_main(void)
{
	uint8_t ping_rsp = 0;
	uint8_t recv_value = 0;
	int err;
    ESP_ERROR_CHECK(i2c_master_init());
    ESP_LOGI(TAG, "I2C initialized successfully");

	/* PING 通为止 */
	while (ping_rsp != GW_GRAY_PING_OK) {
		ping_rsp = 0;
		err = gw_gray_write_cmd(GW_GRAY_PING);
		err = gw_gray_read_byte(&ping_rsp);
		ESP_LOGI(TAG, "ping_rsp = %X", ping_rsp);
		vTaskDelay(pdMS_TO_TICKS(500));
	}
	ESP_LOGI(TAG, "PING OK");

	/* 设置探头1单发模式 */
	err = gw_gray_write_cmd(GW_GRAY_ANALOG(1));
	ESP_ERROR_CHECK_WITHOUT_ABORT(err);

	/* 循环读取探头1模拟数据 */
	while (1) {
		err = gw_gray_read_byte(&recv_value);
		ESP_LOGI(TAG, "recv_value: %d", recv_value);
		vTaskDelay(pdMS_TO_TICKS(100));
	}
}