/*
 * LEIGH:plc
 * Copyright 2022 Alex Leigh
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program.  If not, see <http://www.gnu.org/licenses/>.
 */

// THIS CODE IS A FORK OF APACHE/CC LICENSE CODE

#include <driver/i2c.h>
#include <esp_log.h>
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <esp_system.h>

#include "emon.h"
#include "esp.h"
#include "tlm.h"

static const char *TAG = "emon";

#ifdef BOARD_WESP32
#define I2C_MASTER_SCL_IO 5         /*!< gpio number for I2C master clock */
#define I2C_MASTER_SDA_IO 33        /*!< gpio number for I2C master data  */
#elif BOARD_ESPRESSIF_DEV
// These are wrong
#define I2C_MASTER_SCL_IO 5         /*!< gpio number for I2C master clock */
#define I2C_MASTER_SDA_IO 33        /*!< gpio number for I2C master data  */
#endif

#define I2C_MASTER_NUM 1            /*!< I2C port number for master dev */
#define I2C_MASTER_FREQ_HZ 100000   /*!< I2C master clock frequency */
#define I2C_MASTER_TX_BUF_DISABLE 0 /*!< I2C master doesn't need buffer */
#define I2C_MASTER_RX_BUF_DISABLE 0 /*!< I2C master doesn't need buffer */

#define STEMMA_SENSOR_ADDR 0x36 /*!< slave address for Stemma soil moisture sensor */

#define STEMMA_MOISTURE_BASE_REG 0x0F /*!< Stemma sensor Base register */
#define STEMMA_MOISTURE_FUNC_REG 0x10 /*!< Stemma sensor function register */

#define STEMMA_TEMP_BASE_REG 0x00 /*!< Stemma sensor Base register */
#define STEMMA_TEMP_FUNC_REG 0x04 /*!< Stemma sensor function register */

#define WRITE_BIT I2C_MASTER_WRITE /*!< I2C master write */
#define READ_BIT I2C_MASTER_READ   /*!< I2C master read */
#define ACK_CHECK_EN 0x1           /*!< I2C master will check ack from slave*/
#define ACK_CHECK_DIS 0x0          /*!< I2C master will not check ack from slave */
#define ACK_VAL 0x0                /*!< I2C ack value */
#define NACK_VAL 0x1               /*!< I2C nack value */

#define DELAY_TIME_BETWEEN_READINGS_MS 1000

/**
 * @brief i2c master initialization
 */
static esp_err_t i2c_master_init(void)
{
    int i2c_master_port = I2C_MASTER_NUM;
    i2c_config_t conf;
    conf.mode = I2C_MODE_MASTER;
    conf.sda_io_num = I2C_MASTER_SDA_IO;
    conf.sda_pullup_en = GPIO_PULLUP_ENABLE;
    conf.scl_io_num = I2C_MASTER_SCL_IO;
    conf.scl_pullup_en = GPIO_PULLUP_ENABLE;
    conf.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);
}

/**
 * @brief test code to operate on STEMMA soil sensor
 *
 * 1. set operation mode
 * _______________________________________________________________________________________
 * | start | slave_addr + wr_bit + ack | write 1 byte + ack  | write 1 byte + ack  | stop |
 * --------|---------------------------|---------------------|---------------------|------|
 * 2. wait 50 ms
 * 3. read data
 * ______________________________________________________________________________________
 * | start | slave_addr + rd_bit + ack | read 1 byte + ack  | read 1 byte + nack | stop |
 * --------|---------------------------|--------------------|--------------------|------|
 *
 * To read temp value replace STEMMA_MOISTURE_BASE_REG and STEMMA_MOISTURE_FUNC_REG
 * with STEMMA_TEMP_BASE_REG and STEMMA_TEMP_FUNC_REG
 */

static esp_err_t emonF_sensor_read(i2c_port_t i2c_num, uint8_t base_reg, uint8_t func_reg, char *value, size_t value_len)
{
    esp_err_t ret;
    int len = 2;
    uint8_t *moisture_data = malloc(len);

    // First tell the sensor that you want to read the moisture value
    i2c_cmd_handle_t read_moisture_cmd = i2c_cmd_link_create();
    i2c_master_start(read_moisture_cmd);
    i2c_master_write_byte(read_moisture_cmd, STEMMA_SENSOR_ADDR << 1 | WRITE_BIT, ACK_CHECK_EN);
    i2c_master_write_byte(read_moisture_cmd, base_reg, ACK_CHECK_EN);
    i2c_master_write_byte(read_moisture_cmd, func_reg, ACK_CHECK_EN);
    i2c_master_stop(read_moisture_cmd);
    ret = i2c_master_cmd_begin(i2c_num, read_moisture_cmd, 1000 / portTICK_PERIOD_MS);
    i2c_cmd_link_delete(read_moisture_cmd);
    vTaskDelay((50) / portTICK_PERIOD_MS);

    // Now read sensor value
    read_moisture_cmd = i2c_cmd_link_create();
    i2c_master_start(read_moisture_cmd);
    i2c_master_write_byte(read_moisture_cmd, STEMMA_SENSOR_ADDR << 1 | READ_BIT, ACK_CHECK_EN);
    i2c_master_read(read_moisture_cmd, moisture_data, len - 1, ACK_VAL);
    i2c_master_read_byte(read_moisture_cmd, moisture_data + len - 1, NACK_VAL); // second parameter is pointer to byte len-1 in data buffer
    i2c_master_stop(read_moisture_cmd);
    ret = i2c_master_cmd_begin(i2c_num, read_moisture_cmd, 1000 / portTICK_PERIOD_MS);

    if (ret == ESP_OK)
    {
        // Assemble an unsigned integer from the two bytes in data and convert it to string
        snprintf(value, value_len, "%u", ((uint16_t)moisture_data[0] << 8) | moisture_data[1]);
    }
    else if (ret == ESP_ERR_TIMEOUT)
    {
        ESP_LOGW(TAG, "Bus is busy");
    }
    else
    {
        ESP_LOGW(TAG, "Read I2C sensor failed");
    }
    i2c_cmd_link_delete(read_moisture_cmd);
    // End reading I2C Moisture Sensor
    return ret;
}

void emonFinit()
{
    ESP_LOGI(TAG, "Initializing");
    esp_log_level_set("*", ESP_LOG_INFO);
    ESP_ERROR_CHECK(i2c_master_init());
}

void emonFtask()
{
    while (1)
    {
        char buf[32];

        cJSON *frame = tlmFframe_alloc();

        emonF_sensor_read(I2C_MASTER_NUM, STEMMA_MOISTURE_BASE_REG, STEMMA_MOISTURE_FUNC_REG, buf, sizeof(buf));
        cJSON *s_moist = tlmFframe_symbol_alloc("lc.env.soil.moisture", buf, "wet");

        emonF_sensor_read(I2C_MASTER_NUM, STEMMA_TEMP_BASE_REG, STEMMA_TEMP_FUNC_REG, buf, sizeof(buf));
        cJSON *a_temp = tlmFframe_symbol_alloc("lc.env.sensor.die.temp", buf, "degC");

        cJSON *symbols = tlmFframe_get_symbols(frame);

        cJSON_AddItemToArray(symbols, a_temp);
        cJSON_AddItemToArray(symbols, s_moist);

        cJSON *tags = cJSON_CreateObject();
        cJSON_AddStringToObject(tags, "esp.tlm.site", "us-iqh0");
        cJSON_AddStringToObject(tags, "esp.tlm.container", "16veb");

        // espFsend() will delete these JSON objects
        espFsend("LC/GLOBAL/ENV/MON/TLM", frame, tags);

        vTaskDelay((DELAY_TIME_BETWEEN_READINGS_MS) / portTICK_PERIOD_MS);
    }
}
