#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_log.h"
#include "esp_err.h"
#include "esp_check.h"
#include "i2c-lcd44780.h"

#define LCD44780_I2C_ADDR             (0x38)
#define LCD44780_I2C_PORT             CONFIG_LCD44780_I2C_NUM
#define LCD44780_SDA_GPIO             CONFIG_LCD44780_I2C_SDA  
#define LCD44780_SCL_GPIO             CONFIG_LCD44780_I2C_SCL  

static const char* TAG = "I2C-LCD44780";

i2c_master_bus_handle_t i2c_bus_init(uint8_t sda_io, uint8_t scl_io);

void app_main(void)
{
    esp_err_t err;
    i2c_master_bus_handle_t bus_handle;
    I2C_LCD_HANDLE          lcd_handle;
    
    bus_handle = i2c_bus_init(LCD44780_SDA_GPIO, LCD44780_SCL_GPIO);
    
    lcd_handle = I2cLcd44780_Create(bus_handle, LCD44780_I2C_ADDR, 100000, 2u, 40u);
    
    err = i2c_master_probe(bus_handle, LCD44780_I2C_ADDR, 200);  

    if (err == ESP_OK) {
      ESP_LOGI(TAG,"Found LCD");
    } else {
      //I2cLcd44780_Remove(lcd_handle->DevHandle);
      ESP_LOGI(TAG,"Not found LCD");
    }
  
    I2cLcd44780_Init(lcd_handle);
    I2cLcd44780_OnBacklight(lcd_handle); 

    char buf1[41];
    char buf2[41];     
    
    sprintf(buf1,"   ESP32 & I2C-LCD44780 - I2C-BUS LCD   ");
    sprintf(buf2,"  ERE Company Limited. www.ereshop.com  ");
          
    for (uint8_t col = 0; col < 40; col++) {
        I2cLcd44780_DispChrAt(lcd_handle, 0, col, (INT08S)buf1[col]);
    }
    
    for (uint8_t col = 0; col < 40; col++) {
        I2cLcd44780_DispChrAt(lcd_handle, 1, col, (INT08S)buf2[col]);
    }
        
    while (1) {
        vTaskDelay(1000/portTICK_PERIOD_MS);
    } 
}

i2c_master_bus_handle_t i2c_bus_init (uint8_t sda_io, uint8_t scl_io)
{
    i2c_master_bus_handle_t bus_handle;
    
    i2c_master_bus_config_t  bus_cfg = { 
        .i2c_port   = LCD44780_I2C_PORT,
        .scl_io_num = scl_io,
        .sda_io_num = sda_io,
        .clk_source = I2C_CLK_SRC_DEFAULT,
        .glitch_ignore_cnt = 7,
        .flags.enable_internal_pullup = true,                                      
    };

    ESP_ERROR_CHECK(i2c_new_master_bus(&bus_cfg, &bus_handle));
    ESP_LOGI(TAG, "I2C master bus created");

    return (bus_handle);        
}
