#include <WiFi.h>
#include <math.h>
#include "esp_camera.h"

#define PWDN_GPIO_NUM -1
#define RESET_GPIO_NUM -1
#define XCLK_GPIO_NUM 10
#define SIOD_GPIO_NUM 40
#define SIOC_GPIO_NUM 39
#define Y9_GPIO_NUM 48
#define Y8_GPIO_NUM 11
#define Y7_GPIO_NUM 12
#define Y6_GPIO_NUM 14
#define Y5_GPIO_NUM 16
#define Y4_GPIO_NUM 18
#define Y3_GPIO_NUM 17
#define Y2_GPIO_NUM 15
#define VSYNC_GPIO_NUM 38
#define HREF_GPIO_NUM 47
#define PCLK_GPIO_NUM 13

// add wifi information
const char *ssid = "SSID";
const char *password = "password";
// server ip address here
IPAddress server(1, 2, 3, 4);
WiFiClient client;

String response;

void send_bytes()
{
  camera_fb_t *framebuffer = NULL;
  size_t header_length, jpg_length;
  uint8_t *jpg_buffer;
  uint8_t *rgb_buffer = NULL;
  uint8_t *motion_buffer = NULL;
  char part_buffer[64];
  uint32_t width, height, len, row, col, intensity, motion;

  // forever reads from camera buffer, sends to server, waits for reply, and updates the led accordingly
  while (true)
  {
    uint32_t start = millis();
    //
    // get frame
    //
    framebuffer = esp_camera_fb_get();
    width = framebuffer->width;
    height = framebuffer->height;
    len = width * height * 3;

    //
    // convert to RGB
    //
    if (!(rgb_buffer))
      rgb_buffer = (uint8_t *)ps_malloc(len);
    fmt2rgb888(framebuffer->buf, framebuffer->len, PIXFORMAT_JPEG, rgb_buffer);
    esp_camera_fb_return(framebuffer);

    Serial.print("time to read frame: ");
    Serial.println(millis() - start);

    // post bytes
    delay(5);
    if (client.connected())
    {
      client.println("POST / HTTP/1.1");
      client.println("Host: 1.2.3.4");
      client.println("User-Agent: Arduino/1.0");
      client.println("Connection: Keep-Alive");
      client.print("Content-Length: ");
      client.println(len);
      client.println();

      client.write(rgb_buffer, len);

      Serial.println("sent post");
    }
    else
    {
      // try to reconnect
      client.flush();
      client.stop();
      Serial.println("server not found");
      while (!client.connect(server, 8000))
      {
      }
    }

    Serial.print("time to send post");
    Serial.println(millis() - start);

    Serial.println(response);
    delay(5);

    start = millis();

    // wait for reply
    while (client.available() == 0 && millis() - start < 5000)
    {
    };

    Serial.print("time to receive");
    Serial.println(millis() - start);

    // if no response received try to reconnect
    if (client.available() == 0)
    {
      Serial.println("no response received");
      client.flush();
      client.stop();
      while (!client.connect(server, 8000))
      {
      }
    }

    delay(5);
    // read response
    response = "";
    while (client.available() > 0)
    {
      char c = client.read();
      response.concat(c);
    }
    Serial.print("time to process response");
    Serial.println(millis() - start);

    Serial.print("the response:");
    Serial.println(response);

    // set led based on response
    if (response.indexOf("banana") >= 0)
    {
      digitalWrite(D0, HIGH);
      Serial.println("THERE'S a banana");
    }

    if (response.indexOf("nope") >= 0)
    {
      digitalWrite(D0, LOW);
      Serial.println("THERE'S not a banana");
    }

    Serial.print("total cycle:");
    Serial.println(millis() - start);
    delay(5);
  }
}

void setup()
{
  Serial.begin(9600);
  camera_config_t config;
  config.grab_mode = CAMERA_GRAB_LATEST;
  config.ledc_channel = LEDC_CHANNEL_0;
  config.ledc_timer = LEDC_TIMER_0;
  config.pin_d0 = Y2_GPIO_NUM;
  config.pin_d1 = Y3_GPIO_NUM;
  config.pin_d2 = Y4_GPIO_NUM;
  config.pin_d3 = Y5_GPIO_NUM;
  config.pin_d4 = Y6_GPIO_NUM;
  config.pin_d5 = Y7_GPIO_NUM;
  config.pin_d6 = Y8_GPIO_NUM;
  config.pin_d7 = Y9_GPIO_NUM;
  config.pin_xclk = XCLK_GPIO_NUM;
  config.pin_pclk = PCLK_GPIO_NUM;
  config.pin_vsync = VSYNC_GPIO_NUM;
  config.pin_href = HREF_GPIO_NUM;
  config.pin_sscb_sda = SIOD_GPIO_NUM;
  config.pin_sscb_scl = SIOC_GPIO_NUM;
  config.pin_pwdn = PWDN_GPIO_NUM;
  config.pin_reset = RESET_GPIO_NUM;
  config.xclk_freq_hz = 20000000;
  config.fb_location = CAMERA_FB_IN_PSRAM;
  config.pixel_format = PIXFORMAT_JPEG;
  config.frame_size = FRAMESIZE_QVGA; // 320x240
  config.jpeg_quality = 10;
  config.fb_count = 2;

  esp_camera_init(&config);
  WiFi.begin(ssid, password);
  Serial.print("Connecting WiFi ");
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println(WiFi.localIP());
  Serial.print("Connecting to the server");
  while (!client.connect(server, 8000))
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("connected");

  if (client.connected())
  {
    // for debugging starts by sending a get request
    client.println("GET / HTTP/1.1");
    client.println("Host: 1.2.3.4");
    client.println("User-Agent: Arduino/1.0");
    client.println("Connection: Keep-Alive");
    client.println();

    Serial.println("sent get");
  }

  // make sure led starts off
  pinMode(D0, OUTPUT);
  digitalWrite(D0, LOW);

  send_bytes();
}

void loop()
{
  ;
}