#include "i2c.h"
#include "esp_log.h"
#include "esp_err.h"
#include "driver/i2c.h"

static const char *TAG = "i2c";

SemaphoreHandle_t main_i2c_mutex;

void init_i2c() {
    ESP_LOGI(TAG, "Initializing i2c...");

    i2c_config_t conf = {
        .mode = I2C_MODE_MASTER,
        .sda_io_num = PIN_I2C_SDA,
        .scl_io_num = PIN_I2C_SCL,
        .sda_pullup_en = GPIO_PULLUP_DISABLE,
        .scl_pullup_en = GPIO_PULLUP_DISABLE,
        // .sda_pullup_en = GPIO_PULLUP_ENABLE,
        // .scl_pullup_en = GPIO_PULLUP_ENABLE,
        .master = {
            // TODO: 400k?
            .clk_speed = 100*1000,
        },
        .clk_flags = I2C_SCLK_SRC_FLAG_FOR_NOMAL
    };

    ESP_ERROR_CHECK(i2c_param_config(MAIN_I2C_BUS_NUM, &conf));
    ESP_ERROR_CHECK(i2c_driver_install(MAIN_I2C_BUS_NUM, conf.mode, 0, 0, 0));

    main_i2c_mutex = xSemaphoreCreateMutex();
    assert(main_i2c_mutex != NULL);

    ESP_LOGI(TAG, "i2c initialized!");
}
