/*
 * MCINM.PL
 * https://mcinm.pl..
 *
 * interkom esp32 - test peryferiów
 *
 */

#include <stdint.h>
#include <stdio.h>
#include <inttypes.h>
#include "driver/i2s_common.h"
#include "driver/i2s_types.h"
#include "esp_err.h"
#include "hal/i2s_types.h"
#include "lwip/inet.h"
#include "lwip/timeouts.h"
#include "portmacro.h"
#include "sdkconfig.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_netif.h"
#include "esp_wifi.h"
#include "nvs.h"
#include "nvs_flash.h"
#include "esp_log.h"

#include "lwip/err.h"
#include "lwip/sockets.h"
#include "lwip/sys.h"
#include <lwip/netdb.h>
#include <sys/_timeval.h>

#include "driver/i2s_std.h"
#include "driver/gpio.h"



#define SAMPLE_BUFFER_SIZE 128
#define SAMPLE_RATE 6000
#define BIT_RATE 32


#define GPIO_BCLK GPIO_NUM_3
#define GPIO_DIN GPIO_NUM_2
#define GPIO_WS GPIO_NUM_1
#define GPIO_DOUT GPIO_NUM_5


static i2s_chan_handle_t                rx_chan;
static i2s_chan_handle_t                tx_chan;


static const char *TAG = "mcinm_mikro_echo_test";



static void i2s_init(void) {

  i2s_chan_config_t i2s_channel_cfg;
  i2s_channel_cfg.id = I2S_NUM_0;
  i2s_channel_cfg.role = I2S_ROLE_MASTER;
  i2s_channel_cfg.dma_desc_num = 4;
  i2s_channel_cfg.dma_frame_num = 100,
  i2s_channel_cfg.allow_pd = false;
  i2s_channel_cfg.intr_priority = 0;

  i2s_new_channel(&i2s_channel_cfg, &tx_chan, &rx_chan);

  i2s_std_config_t i2s_cfg;
  i2s_std_clk_config_t clk_config = {
    .clk_src = I2S_CLK_SRC_DEFAULT,
    .sample_rate_hz = SAMPLE_RATE,
    .mclk_multiple = I2S_MCLK_MULTIPLE_192,
   };

  i2s_std_slot_config_t slot_config = {
    .data_bit_width = 32,
    .slot_bit_width = I2S_SLOT_BIT_WIDTH_32BIT,
    .slot_mode = I2S_SLOT_MODE_MONO,
    .slot_mask = I2S_STD_SLOT_LEFT,
    .ws_width = 32,
    .ws_pol = false,
    .bit_shift = true,
    };

  i2s_std_gpio_config_t i2s_gpio_config = {
    .mclk = I2S_GPIO_UNUSED,
    .bclk = GPIO_BCLK,
    .ws = GPIO_WS,
    .dout = GPIO_DOUT,
    .din = GPIO_DIN,
    .invert_flags = {
      .bclk_inv = false,
      .mclk_inv = false,
      .ws_inv = false,
     },
   };

  i2s_cfg.clk_cfg = clk_config;
  i2s_cfg.slot_cfg = slot_config;
  i2s_cfg.gpio_cfg = i2s_gpio_config;

  ESP_ERROR_CHECK(i2s_channel_init_std_mode(tx_chan, &i2s_cfg));
  ESP_ERROR_CHECK(i2s_channel_init_std_mode(rx_chan, &i2s_cfg));
  ESP_ERROR_CHECK(i2s_channel_enable(tx_chan));
  ESP_ERROR_CHECK(i2s_channel_enable(rx_chan));
}





void app_main(void)
{
  wifi_init();
  printf("MCINM - I2S TEST!\n");
  sleep(5); // Dajmy czas na nawiązanie połączenia z wifi

  i2s_init();

  int32_t i2s_bufor_tx[128];

  while (1) {

    size_t bytes_read = 0;
    i2s_channel_read(rx_chan, i2s_bufor_tx, 128, &bytes_read, 100);
    int samples_read = bytes_read / sizeof(int);
    for (uint8_t i=0; i<samples_read; i++) {

      i2s_bufor_tx[i] = i2s_bufor_tx[i]*40;
     }
	  i2s_channel_write(tx_chan, i2s_bufor_tx, 128, NULL, 10);
   }
}
