#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 /*! 使用默认地址 */

/**
 * @brief 配置I2C以及初始化
 * @return ESP-IDF错误代码
 */
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 recv_byte = 0; // 传感器返回值
	uint8_t i2c_cmd; // 发送命令用
	uint8_t err;

    ESP_ERROR_CHECK(i2c_master_init());
    ESP_LOGI(TAG, "I2C 初始化成功");

	i2c_cmd = GW_GRAY_PING; // ping命令 x

	/* PING 通为止 */
	while (recv_byte != GW_GRAY_PING_OK) {
		recv_byte = 0;
		err = i2c_master_write_read_device(I2C_MASTER_NUM, GW_GRAY_ADDR, &i2c_cmd, 1,
		                                   &recv_byte, 1, I2C_MASTER_TIMEOUT_MS / portTICK_PERIOD_MS);
		if (err != ESP_OK) {
			ESP_LOGE(TAG, "%s", esp_err_to_name(err));
		} else {
			ESP_LOGI(TAG, "recv_byte = %X", recv_byte);
		}
		vTaskDelay(pdMS_TO_TICKS(500));
	}

	ESP_LOGI(TAG, "PING OK");
	i2c_cmd = GW_GRAY_FIRMWARE;
	err = i2c_master_write_read_device(I2C_MASTER_NUM, GW_GRAY_ADDR, &i2c_cmd, 1,
	                                   &recv_byte, 1, I2C_MASTER_TIMEOUT_MS / portTICK_PERIOD_MS);
	if (err != ESP_OK) {
		ESP_LOGE(TAG, "%s", esp_err_to_name(err));
	} else {
		ESP_LOGI(TAG, "固件版本号 : v%d.%d", recv_byte >> 4, recv_byte & 0x0F);
	}

	while (1) {
		vTaskDelay(portMAX_DELAY);
	}
}