10 Nisan 2020 Cuma

Esp32 Camera Taking Picture And Send To Server With AspNetMvc With Timer

Hi, we will use esp32camera to take picture and send to remote server with HttpClient library.

RequiredItems: 
  • Esp32Camera 
  • Ftdi Programmer.
  • 1Sd Card
  • Arduino Programing IDE
  • Min 5 unit  female to female jumper wire for setting connection esp32cam to Ftid
  • Visual Studio IDE and a little bit .net c# codding information.

Step:1

Adjust your esp32cam wires as below image  notice that if gray wire is connected to IO0 with GND it means that ready to upload codes! After uploding codes to esp32cam we need to remove jumper IO0 to start esp32cam. 




















Be sure that your arduino board configuration must be as below. Port is must be selected connected esp32cam usb on your computer.


Format your SD Card Fat32 Formart before inserting to esp32cam

After all upload finished you need to reset or repower esp32cam to run codes. 

Step:2

Below copy blue colored codes and paste to arudnio ide.

//******Code Starts.

#include <WiFi.h>
#include <HTTPClient.h>
#include "esp_camera.h"
#include "FS.h"
#include "SPI.h"
#include "SD_MMC.h"
#include "EEPROM.h"
#include "driver/rtc_io.h"

// Select camera model
//#define CAMERA_MODEL_WROVER_KIT // Has PSRAM
//#define CAMERA_MODEL_ESP_EYE // Has PSRAM
//#define CAMERA_MODEL_M5STACK_PSRAM // Has PSRAM
//#define CAMERA_MODEL_M5STACK_WIDE // Has PSRAM
//#define CAMERA_MODEL_TTGO_T_JOURNAL // No PSRAM
#define CAMERA_MODEL_AI_THINKER 

#include "camera_pins.h"

#define ID_ADDRESS            0x00
#define COUNT_ADDRESS         0x01
#define ID_BYTE               0xAA
#define EEPROM_SIZE           0x0F

#define TIME_TO_SLEEP  30            //time ESP32 will go to sleep (in seconds)
#define uS_TO_S_FACTOR 1000000ULL   //conversion factor for micro seconds to seconds */

uint16_t nextImageNumber = 0;

#define SSID "YOURSSID" //target network name to conenct
#define PSK "YOURSSIDPASSWORD" //target network password

void setup()
{
  Serial.begin(115200);
  Serial.println();
  Serial.println("Booting...");


  WiFi.begin(SSID, PSK);
  while (!WiFi.isConnected()) {
    Serial.println(".");
    delay(1000);
  }
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());


  pinMode(4, INPUT);              //GPIO for LED flash
  digitalWrite(4, LOW);
  rtc_gpio_hold_dis(GPIO_NUM_4);  //diable pin hold if it was enabled before sleeping

  camera_config_t config;
  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.pixel_format = PIXFORMAT_JPEG;

  //init with high specs to pre-allocate larger buffers
  if (psramFound())
  {
    config.frame_size = FRAMESIZE_SXGA;
    config.jpeg_quality = 10;
    config.fb_count = 2;
  }
  else
  {
    config.frame_size = FRAMESIZE_SVGA;
    config.jpeg_quality = 12;
    config.fb_count = 1;
  }



#if defined(CAMERA_MODEL_ESP_EYE)
  pinMode(13, INPUT_PULLUP);
  pinMode(14, INPUT_PULLUP);
#endif

  //initialize camera
  esp_err_t err = esp_camera_init(&config);

  if (err != ESP_OK)
  {
    Serial.printf("Camera init failed with error 0x%x", err);
    return;
  }

  //initialize & mount SD card
  if (!SD_MMC.begin())
  {
    Serial.println("Card Mount Failed");
    return;
  }


  //initialize EEPROM & get file number
  if (!EEPROM.begin(EEPROM_SIZE))
  {
    Serial.println("Failed to initialise EEPROM");
    Serial.println("Exiting now");
    while (1);  //wait here as something is not right
  }


  if (EEPROM.read(ID_ADDRESS) != ID_BYTE)   //there will not be a valid picture number
  {
    Serial.println("Initializing ID byte & restarting picture count");
    nextImageNumber = 0;
    EEPROM.write(ID_ADDRESS, ID_BYTE);
    EEPROM.commit();
  }
  else                                      //obtain next picture number
  {
    EEPROM.get(COUNT_ADDRESS, nextImageNumber);
    nextImageNumber +=  1;
    Serial.print("Next image number:");
    Serial.println(nextImageNumber);
  }

  //take new image
  camera_fb_t * fb = NULL;
  //obtain camera frame buffer
  fb = esp_camera_fb_get();
  if (!fb)
  {
    Serial.println("Camera capture failed");
    Serial.println("Exiting now");
    while (1);  //wait here as something is not right
  }

  //save to SD card
  //generate file path
  String path = "/IMG" + String(nextImageNumber) + ".jpg";

  fs::FS &fs = SD_MMC;

  //create new file
  File file = fs.open(path.c_str(), FILE_WRITE);
  if (!file)
  {
    Serial.println("Failed to create file");
    Serial.println("Exiting now");
    while (1);  //wait here as something is not right
  }
  else
  {
    file.write(fb->buf, fb->len);
    EEPROM.put(COUNT_ADDRESS, nextImageNumber);
    EEPROM.commit();
  }
  file.close();
  SD_MMC.end();
  delay(1000);
  PostData(path);
  //return camera frame buffer
  esp_camera_fb_return(fb);
  Serial.printf("Image saved: %s\n", path.c_str());

  pinMode(4, OUTPUT);              //GPIO for LED flash
  digitalWrite(4, LOW);            //turn OFF flash LED
  rtc_gpio_hold_en(GPIO_NUM_4);    //make sure flash is held LOW in sleep
  delay(500);
  Serial.println("Entering deep sleep mode");
  Serial.flush();

  esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
  esp_deep_sleep_start();
}
void loop()
{
}
void PostData(String path)
{
  SD_MMC.begin();
  fs::FS &fs = SD_MMC;
  HTTPClient http;
  Serial.println("connetion starting.");
  File file = fs.open(path.c_str(), FILE_READ);
  const auto f_size = file.size();
  Serial.println("File Size");
  Serial.println(f_size);

  http.begin("http://iot.rtayazilim.net/Esp32SaveImg");
  http.addHeader("Content-Type", "application/octet-stream");
  http.addHeader("LocalFileName", path);
  http.sendRequest("POST", &file, f_size);
  http.writeToStream(&Serial);
  http.end();
  file.close();
  SD_MMC.end();
}

Notice: This code block will take picture and post to server every 30 second if need to change interval go to TIME_TO_SLEEP  defination.

Step:3


After this process we need to get posted files to save to remote addres so i will use visual studio programing tool i can can be downoad from official website and has community edition.

Install to your computer and create new Empty Asp.Net Project. Fallow steps below.







After these steps your project created successfully.
On Visual studio right side solution explorer tab you will see all folders right click to controller folder and add 


Select EmptyController and create it, after that there will prompt controller name box, give the name Home instead of Default.





Now we are ready to coding.

Creation Mvc Filter:

using System;
using System.IO;
using System.Text;
using System.Web.Mvc;


namespace IotTest.Filters
{
    public class TestFilter : System.Web.Mvc.ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var Path = filterContext.RequestContext.HttpContext.Server.MapPath("~/Logs/");

            System.Text.StringBuilder sb = new StringBuilder();            

            for (int i = 0; i < filterContext.RequestContext.HttpContext.Request.Headers.Keys.Count; i++)
            {
                sb.AppendLine("---------------HEADER---------------");
                var Key = filterContext.RequestContext.HttpContext.Request.Headers.Keys[i];
                var Value = filterContext.RequestContext.HttpContext.Request.Headers.Get(i);
                sb.AppendLine(string.Format("{0}:{1}", Key, Value));

            }

            //Save Requested Stream as file
            var RequestPath = string.Format("{0}{1}RawRequest.jpg", Path, DateTime.Now.ToString("ddMMyyyHHmm"));
            filterContext.RequestContext.HttpContext.Request.SaveAs(RequestPath, false);
       



            LogX(Path, "OnActionExecuted", sb.ToString());
            base.OnActionExecuted(filterContext);
        }



        public void LogX(string Path, string Metod, string StrData = "")
        {
            Path += "Log.txt";
            StreamWriter sr = new StreamWriter(Path, true);
            sr.WriteLine(string.Format("{0}: {1} {2}", Metod, DateTime.Now.ToString(), StrData));
            sr.Close();

        }
    }
}


Inside Home control:

using IotTest.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace IotTest.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home        
        public ActionResult Index()
        {
            return View();
        }
        

        [TestFilter]
        [HttpPost]
        public ActionResult Esp32SaveImg()
        {
            return Json("ok");
        }
    }
}

Finaly Esp32Cam worked perfect and our site can show taken and posted file on server side. 



After that you need to pusblish your project any domain or ip adress based hosting addres.
Project files can be download from here




Hiç yorum yok:

Yorum Gönder