ClassControllCamera.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  1. #include "ClassControllCamera.h"
  2. #include "ClassLogFile.h"
  3. #include <stdio.h>
  4. #include "driver/gpio.h"
  5. #include "esp_timer.h"
  6. #include "esp_log.h"
  7. #include "Helper.h"
  8. #include "CImageBasis.h"
  9. #include "server_ota.h"
  10. #include "server_GPIO.h"
  11. #include "../../include/defines.h"
  12. #include <esp_event.h>
  13. #include <esp_log.h>
  14. #include <esp_system.h>
  15. #include <nvs_flash.h>
  16. #include <sys/param.h>
  17. #include <string.h>
  18. #include "freertos/FreeRTOS.h"
  19. #include "freertos/task.h"
  20. #include "esp_camera.h"
  21. #include "driver/ledc.h"
  22. #include "server_tflite.h"
  23. static const char *TAG = "CAM";
  24. static camera_config_t camera_config = {
  25. .pin_pwdn = CAM_PIN_PWDN,
  26. .pin_reset = CAM_PIN_RESET,
  27. .pin_xclk = CAM_PIN_XCLK,
  28. .pin_sscb_sda = CAM_PIN_SIOD,
  29. .pin_sscb_scl = CAM_PIN_SIOC,
  30. .pin_d7 = CAM_PIN_D7,
  31. .pin_d6 = CAM_PIN_D6,
  32. .pin_d5 = CAM_PIN_D5,
  33. .pin_d4 = CAM_PIN_D4,
  34. .pin_d3 = CAM_PIN_D3,
  35. .pin_d2 = CAM_PIN_D2,
  36. .pin_d1 = CAM_PIN_D1,
  37. .pin_d0 = CAM_PIN_D0,
  38. .pin_vsync = CAM_PIN_VSYNC,
  39. .pin_href = CAM_PIN_HREF,
  40. .pin_pclk = CAM_PIN_PCLK,
  41. //XCLK 20MHz or 10MHz for OV2640 double FPS (Experimental)
  42. .xclk_freq_hz = 20000000, // Orginal value
  43. // .xclk_freq_hz = 5000000, // Test to get rid of the image errors !!!! Hangs in version 9.2 !!!!
  44. .ledc_timer = LEDC_TIMER_0,
  45. .ledc_channel = LEDC_CHANNEL_0,
  46. .pixel_format = PIXFORMAT_JPEG, //YUV422,GRAYSCALE,RGB565,JPEG
  47. .frame_size = FRAMESIZE_VGA, //QQVGA-UXGA Do not use sizes above QVGA when not JPEG
  48. // .frame_size = FRAMESIZE_UXGA, //QQVGA-UXGA Do not use sizes above QVGA when not JPEG
  49. .jpeg_quality = 12, //0-63 lower number means higher quality
  50. .fb_count = 1, //if more than one, i2s runs in continuous mode. Use only with JPEG
  51. .fb_location = CAMERA_FB_IN_PSRAM, /*!< The location where the frame buffer will be allocated */
  52. .grab_mode = CAMERA_GRAB_LATEST, // only from new esp32cam version
  53. };
  54. CCamera Camera;
  55. uint8_t *demoImage = NULL; // Buffer holding the demo image in bytes
  56. #define DEMO_IMAGE_SIZE 30000 // Max size of demo image in bytes
  57. typedef struct {
  58. httpd_req_t *req;
  59. size_t len;
  60. } jpg_chunking_t;
  61. bool CCamera::testCamera(void) {
  62. bool success;
  63. camera_fb_t *fb = esp_camera_fb_get();
  64. if (fb) {
  65. success = true;
  66. }
  67. else {
  68. success = false;
  69. }
  70. esp_camera_fb_return(fb);
  71. return success;
  72. }
  73. void CCamera::ledc_init(void)
  74. {
  75. #ifdef USE_PWM_LEDFLASH
  76. // Prepare and then apply the LEDC PWM timer configuration
  77. ledc_timer_config_t ledc_timer = { };
  78. ledc_timer.speed_mode = LEDC_MODE;
  79. ledc_timer.timer_num = LEDC_TIMER;
  80. ledc_timer.duty_resolution = LEDC_DUTY_RES;
  81. ledc_timer.freq_hz = LEDC_FREQUENCY; // Set output frequency at 5 kHz
  82. ledc_timer.clk_cfg = LEDC_AUTO_CLK;
  83. ESP_ERROR_CHECK(ledc_timer_config(&ledc_timer));
  84. // Prepare and then apply the LEDC PWM channel configuration
  85. ledc_channel_config_t ledc_channel = { };
  86. ledc_channel.speed_mode = LEDC_MODE;
  87. ledc_channel.channel = LEDC_CHANNEL;
  88. ledc_channel.timer_sel = LEDC_TIMER;
  89. ledc_channel.intr_type = LEDC_INTR_DISABLE;
  90. ledc_channel.gpio_num = LEDC_OUTPUT_IO;
  91. ledc_channel.duty = 0; // Set duty to 0%
  92. ledc_channel.hpoint = 0;
  93. ESP_ERROR_CHECK(ledc_channel_config(&ledc_channel));
  94. #endif
  95. }
  96. static size_t jpg_encode_stream(void * arg, size_t index, const void* data, size_t len)
  97. {
  98. jpg_chunking_t *j = (jpg_chunking_t *)arg;
  99. if(!index) {
  100. j->len = 0;
  101. }
  102. if(httpd_resp_send_chunk(j->req, (const char *)data, len) != ESP_OK) {
  103. return 0;
  104. }
  105. j->len += len;
  106. return len;
  107. }
  108. bool CCamera::SetBrightnessContrastSaturation(int _brightness, int _contrast, int _saturation)
  109. {
  110. _brightness = min(2, max(-2, _brightness));
  111. _contrast = min(2, max(-2, _contrast));
  112. _saturation = min(2, max(-2, _saturation));
  113. sensor_t * s = esp_camera_sensor_get();
  114. if (s) {
  115. s->set_saturation(s, _saturation);
  116. s->set_contrast(s, _contrast);
  117. s->set_brightness(s, _brightness);
  118. /* Workaround - bug in cam library - enable bits are set without using bitwise OR logic -> only latest enable setting is used */
  119. /* Library version: https://github.com/espressif/esp32-camera/commit/5c8349f4cf169c8a61283e0da9b8cff10994d3f3 */
  120. /* Reference: https://esp32.com/viewtopic.php?f=19&t=14376#p93178 */
  121. /* The memory structure is as follows for
  122. byte_0 = enable_bits
  123. byte_0->bit0 = enable saturation and hue --> OK
  124. byte_0->bit1 = enable saturation --> OK
  125. byte_0->bit2 = enable brightness and contrast --> OK
  126. byte_0->bit3 = enable green -> blue spitial effect (Antique and blunish and greenish and readdish and b&w) enable
  127. byte_0->bit4 = anable gray -> read spitial effect (Antique and blunish and greenish and readdish and b&w) enable
  128. byte_0->bit5 = remove (UV) in YUV color system
  129. byte_0->bit6 = enable negative
  130. byte_0->bit7 = remove (Y) in YUV color system
  131. byte_1 = saturation1 0-255 --> ?
  132. byte_2 = hue 0-255 --> OK
  133. byte_3 = saturation2 0-255 --> OK
  134. byte_4 = reenter saturation2 in documents --> ?
  135. byte_5 = spital effect green -> blue 0-255 --> ?
  136. byte_6 = spital effect gray -> read 0-255 --> ?
  137. byte_7 = contrast lower byte 0-255 --> OK
  138. byte_8 = contrast higher byte 0-255 --> OK
  139. byte_9 = brightness 0-255 --> OK
  140. byte_10= if byte_10==4 contrast effective --> ?
  141. */
  142. //s->set_reg(s, 0x7C, 0xFF, 2); // Optional feature - hue setting: Select byte 2 in register 0x7C to set hue value
  143. //s->set_reg(s, 0x7D, 0xFF, 0); // Optional feature - hue setting: Hue value 0 - 255
  144. s->set_reg(s, 0xFF, 0x01, 0); // Select DSP bank
  145. s->set_reg(s, 0x7C, 0xFF, 0); // Select byte 0 in register 0x7C
  146. s->set_reg(s, 0x7D, 7, 7); // Set bit 0, 1, 2 in register 0x7D to enable saturation, contrast, brightness and hue control
  147. }
  148. else {
  149. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "SetBrightnessContrastSaturation: Failed to get control structure");
  150. }
  151. if (((_brightness != brightness) || (_contrast != contrast) || (_saturation != saturation)) && isFixedExposure)
  152. EnableAutoExposure(waitbeforepicture_org);
  153. brightness = _brightness;
  154. contrast = _contrast;
  155. saturation = _saturation;
  156. ESP_LOGD(TAG, "brightness %d, contrast: %d, saturation %d", brightness, contrast, saturation);
  157. return true;
  158. }
  159. void CCamera::SetQualitySize(int qual, framesize_t resol)
  160. {
  161. qual = min(63, max(8, qual)); // Limit quality from 8..63 (values lower than 8 tent to be unstable)
  162. sensor_t * s = esp_camera_sensor_get();
  163. if (s) {
  164. s->set_quality(s, qual);
  165. s->set_framesize(s, resol);
  166. }
  167. else {
  168. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "SetQualitySize: Failed to get control structure");
  169. }
  170. ActualResolution = resol;
  171. ActualQuality = qual;
  172. if (resol == FRAMESIZE_QVGA)
  173. {
  174. image_height = 240;
  175. image_width = 320;
  176. }
  177. else if (resol == FRAMESIZE_VGA)
  178. {
  179. image_height = 480;
  180. image_width = 640;
  181. }
  182. }
  183. void CCamera::EnableAutoExposure(int flash_duration)
  184. {
  185. ESP_LOGD(TAG, "EnableAutoExposure");
  186. LEDOnOff(true);
  187. if (flash_duration > 0) {
  188. LightOnOff(true);
  189. const TickType_t xDelay = flash_duration / portTICK_PERIOD_MS;
  190. vTaskDelay( xDelay );
  191. }
  192. camera_fb_t * fb = esp_camera_fb_get();
  193. esp_camera_fb_return(fb);
  194. fb = esp_camera_fb_get();
  195. if (!fb) {
  196. LEDOnOff(false);
  197. LightOnOff(false);
  198. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "EnableAutoExposure: Capture Failed. "
  199. "Check camera module and/or proper electrical connection");
  200. //doReboot();
  201. }
  202. esp_camera_fb_return(fb);
  203. sensor_t * s = esp_camera_sensor_get();
  204. if (s) {
  205. s->set_gain_ctrl(s, 0);
  206. s->set_exposure_ctrl(s, 0);
  207. }
  208. else {
  209. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "EnableAutoExposure: Failed to get control structure to set gain+exposure");
  210. }
  211. LEDOnOff(false);
  212. LightOnOff(false);
  213. isFixedExposure = true;
  214. waitbeforepicture_org = flash_duration;
  215. }
  216. esp_err_t CCamera::CaptureToBasisImage(CImageBasis *_Image, int delay)
  217. {
  218. #ifdef DEBUG_DETAIL_ON
  219. LogFile.WriteHeapInfo("CaptureToBasisImage - Start");
  220. #endif
  221. _Image->EmptyImage(); //Delete previous stored raw image -> black image
  222. LEDOnOff(true);
  223. if (delay > 0) {
  224. LightOnOff(true);
  225. const TickType_t xDelay = delay / portTICK_PERIOD_MS;
  226. vTaskDelay( xDelay );
  227. }
  228. #ifdef DEBUG_DETAIL_ON
  229. LogFile.WriteHeapInfo("CaptureToBasisImage - After LightOn");
  230. #endif
  231. camera_fb_t * fb = esp_camera_fb_get();
  232. esp_camera_fb_return(fb);
  233. fb = esp_camera_fb_get();
  234. if (!fb) {
  235. LEDOnOff(false);
  236. LightOnOff(false);
  237. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "is not working anymore (CaptureToBasisImage) - most probably caused "
  238. "by a hardware problem (instablility, ...). System will reboot.");
  239. doReboot();
  240. return ESP_FAIL;
  241. }
  242. if (demoMode) { // Use images stored on SD-Card instead of camera image
  243. /* Replace Framebuffer with image from SD-Card */
  244. loadNextDemoImage(fb);
  245. }
  246. CImageBasis* _zwImage = new CImageBasis();
  247. if (_zwImage) {
  248. _zwImage->LoadFromMemory(fb->buf, fb->len);
  249. }
  250. else {
  251. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: Can't allocate _zwImage");
  252. }
  253. esp_camera_fb_return(fb);
  254. #ifdef DEBUG_DETAIL_ON
  255. LogFile.WriteHeapInfo("CaptureToBasisImage - After fb_get");
  256. #endif
  257. LEDOnOff(false);
  258. if (delay > 0)
  259. LightOnOff(false);
  260. // TickType_t xDelay = 1000 / portTICK_PERIOD_MS;
  261. // vTaskDelay( xDelay ); // wait for power to recover
  262. #ifdef DEBUG_DETAIL_ON
  263. LogFile.WriteHeapInfo("CaptureToBasisImage - After LoadFromMemory");
  264. #endif
  265. stbi_uc* p_target;
  266. stbi_uc* p_source;
  267. int channels = 3;
  268. int width = image_width;
  269. int height = image_height;
  270. #ifdef DEBUG_DETAIL_ON
  271. std::string _zw = "Targetimage: " + std::to_string((int) _Image->rgb_image) + " Size: " + std::to_string(_Image->width) + ", " + std::to_string(_Image->height);
  272. _zw = _zw + " _zwImage: " + std::to_string((int) _zwImage->rgb_image) + " Size: " + std::to_string(_zwImage->width) + ", " + std::to_string(_zwImage->height);
  273. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, _zw);
  274. #endif
  275. for (int x = 0; x < width; ++x)
  276. for (int y = 0; y < height; ++y)
  277. {
  278. p_target = _Image->rgb_image + (channels * (y * width + x));
  279. p_source = _zwImage->rgb_image + (channels * (y * width + x));
  280. p_target[0] = p_source[0];
  281. p_target[1] = p_source[1];
  282. p_target[2] = p_source[2];
  283. }
  284. delete _zwImage;
  285. #ifdef DEBUG_DETAIL_ON
  286. LogFile.WriteHeapInfo("CaptureToBasisImage - Done");
  287. #endif
  288. return ESP_OK;
  289. }
  290. esp_err_t CCamera::CaptureToFile(std::string nm, int delay)
  291. {
  292. string ftype;
  293. LEDOnOff(true); // Switched off to save power !
  294. if (delay > 0) {
  295. LightOnOff(true);
  296. const TickType_t xDelay = delay / portTICK_PERIOD_MS;
  297. vTaskDelay( xDelay );
  298. }
  299. camera_fb_t * fb = esp_camera_fb_get();
  300. esp_camera_fb_return(fb);
  301. fb = esp_camera_fb_get();
  302. if (!fb) {
  303. LEDOnOff(false);
  304. LightOnOff(false);
  305. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToFile: Capture Failed. "
  306. "Check camera module and/or proper electrical connection");
  307. //doReboot();
  308. return ESP_FAIL;
  309. }
  310. LEDOnOff(false);
  311. #ifdef DEBUG_DETAIL_ON
  312. ESP_LOGD(TAG, "w %d, h %d, size %d", fb->width, fb->height, fb->len);
  313. #endif
  314. nm = FormatFileName(nm);
  315. #ifdef DEBUG_DETAIL_ON
  316. ESP_LOGD(TAG, "Save Camera to: %s", nm.c_str());
  317. #endif
  318. ftype = toUpper(getFileType(nm));
  319. #ifdef DEBUG_DETAIL_ON
  320. ESP_LOGD(TAG, "Filetype: %s", ftype.c_str());
  321. #endif
  322. uint8_t * buf = NULL;
  323. size_t buf_len = 0;
  324. bool converted = false;
  325. if (ftype.compare("BMP") == 0)
  326. {
  327. frame2bmp(fb, &buf, &buf_len);
  328. converted = true;
  329. }
  330. if (ftype.compare("JPG") == 0)
  331. {
  332. if(fb->format != PIXFORMAT_JPEG){
  333. bool jpeg_converted = frame2jpg(fb, ActualQuality, &buf, &buf_len);
  334. converted = true;
  335. if(!jpeg_converted){
  336. ESP_LOGE(TAG, "JPEG compression failed");
  337. }
  338. } else {
  339. buf_len = fb->len;
  340. buf = fb->buf;
  341. }
  342. }
  343. FILE * fp = fopen(nm.c_str(), "wb");
  344. if (fp == NULL) { // If an error occurs during the file creation
  345. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToFile: Failed to open file " + nm);
  346. }
  347. else {
  348. fwrite(buf, sizeof(uint8_t), buf_len, fp);
  349. fclose(fp);
  350. }
  351. if (converted)
  352. free(buf);
  353. esp_camera_fb_return(fb);
  354. if (delay > 0)
  355. LightOnOff(false);
  356. return ESP_OK;
  357. }
  358. esp_err_t CCamera::CaptureToHTTP(httpd_req_t *req, int delay)
  359. {
  360. esp_err_t res = ESP_OK;
  361. size_t fb_len = 0;
  362. int64_t fr_start = esp_timer_get_time();
  363. LEDOnOff(true);
  364. if (delay > 0) {
  365. LightOnOff(true);
  366. const TickType_t xDelay = delay / portTICK_PERIOD_MS;
  367. vTaskDelay( xDelay );
  368. }
  369. camera_fb_t *fb = esp_camera_fb_get();
  370. esp_camera_fb_return(fb);
  371. fb = esp_camera_fb_get();
  372. if (!fb) {
  373. LEDOnOff(false);
  374. LightOnOff(false);
  375. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToFile: Capture Failed. "
  376. "Check camera module and/or proper electrical connection");
  377. httpd_resp_send_500(req);
  378. // doReboot();
  379. return ESP_FAIL;
  380. }
  381. LEDOnOff(false);
  382. res = httpd_resp_set_type(req, "image/jpeg");
  383. if(res == ESP_OK){
  384. res = httpd_resp_set_hdr(req, "Content-Disposition", "inline; filename=raw.jpg");
  385. }
  386. if(res == ESP_OK){
  387. if (demoMode) { // Use images stored on SD-Card instead of camera image
  388. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Using Demo image!");
  389. /* Replace Framebuffer with image from SD-Card */
  390. loadNextDemoImage(fb);
  391. res = httpd_resp_send(req, (const char *)fb->buf, fb->len);
  392. }
  393. else {
  394. if(fb->format == PIXFORMAT_JPEG){
  395. fb_len = fb->len;
  396. res = httpd_resp_send(req, (const char *)fb->buf, fb->len);
  397. } else {
  398. jpg_chunking_t jchunk = {req, 0};
  399. res = frame2jpg_cb(fb, 80, jpg_encode_stream, &jchunk)?ESP_OK:ESP_FAIL;
  400. httpd_resp_send_chunk(req, NULL, 0);
  401. fb_len = jchunk.len;
  402. }
  403. }
  404. }
  405. esp_camera_fb_return(fb);
  406. int64_t fr_end = esp_timer_get_time();
  407. ESP_LOGI(TAG, "JPG: %uKB %ums", (uint32_t)(fb_len/1024), (uint32_t)((fr_end - fr_start)/1000));
  408. if (delay > 0)
  409. LightOnOff(false);
  410. return res;
  411. }
  412. void CCamera::LightOnOff(bool status)
  413. {
  414. GpioHandler* gpioHandler = gpio_handler_get();
  415. if ((gpioHandler != NULL) && (gpioHandler->isEnabled())) {
  416. ESP_LOGD(TAG, "Use gpioHandler to trigger flashlight");
  417. gpioHandler->flashLightEnable(status);
  418. }
  419. else {
  420. #ifdef USE_PWM_LEDFLASH
  421. if (status) {
  422. ESP_LOGD(TAG, "Internal Flash-LED turn on with PWM %d", led_intensity);
  423. ESP_ERROR_CHECK(ledc_set_duty(LEDC_MODE, LEDC_CHANNEL, led_intensity));
  424. // Update duty to apply the new value
  425. ESP_ERROR_CHECK(ledc_update_duty(LEDC_MODE, LEDC_CHANNEL));
  426. }
  427. else {
  428. ESP_LOGD(TAG, "Internal Flash-LED turn off PWM");
  429. ESP_ERROR_CHECK(ledc_set_duty(LEDC_MODE, LEDC_CHANNEL, 0));
  430. ESP_ERROR_CHECK(ledc_update_duty(LEDC_MODE, LEDC_CHANNEL));
  431. }
  432. #else
  433. // Init the GPIO
  434. gpio_pad_select_gpio(FLASH_GPIO);
  435. // Set the GPIO as a push/pull output
  436. gpio_set_direction(FLASH_GPIO, GPIO_MODE_OUTPUT);
  437. if (status)
  438. gpio_set_level(FLASH_GPIO, 1);
  439. else
  440. gpio_set_level(FLASH_GPIO, 0);
  441. #endif
  442. }
  443. }
  444. void CCamera::LEDOnOff(bool status)
  445. {
  446. // Init the GPIO
  447. gpio_pad_select_gpio(BLINK_GPIO);
  448. /* Set the GPIO as a push/pull output */
  449. gpio_set_direction(BLINK_GPIO, GPIO_MODE_OUTPUT);
  450. if (!status)
  451. gpio_set_level(BLINK_GPIO, 1);
  452. else
  453. gpio_set_level(BLINK_GPIO, 0);
  454. }
  455. void CCamera::GetCameraParameter(httpd_req_t *req, int &qual, framesize_t &resol)
  456. {
  457. char _query[100];
  458. char _qual[10];
  459. char _size[10];
  460. resol = ActualResolution;
  461. qual = ActualQuality;
  462. if (httpd_req_get_url_query_str(req, _query, 100) == ESP_OK)
  463. {
  464. ESP_LOGD(TAG, "Query: %s", _query);
  465. if (httpd_query_key_value(_query, "size", _size, 10) == ESP_OK)
  466. {
  467. #ifdef DEBUG_DETAIL_ON
  468. ESP_LOGD(TAG, "Size: %s", _size);
  469. #endif
  470. if (strcmp(_size, "QVGA") == 0)
  471. resol = FRAMESIZE_QVGA; // 320x240
  472. else if (strcmp(_size, "VGA") == 0)
  473. resol = FRAMESIZE_VGA; // 640x480
  474. else if (strcmp(_size, "SVGA") == 0)
  475. resol = FRAMESIZE_SVGA; // 800x600
  476. else if (strcmp(_size, "XGA") == 0)
  477. resol = FRAMESIZE_XGA; // 1024x768
  478. else if (strcmp(_size, "SXGA") == 0)
  479. resol = FRAMESIZE_SXGA; // 1280x1024
  480. else if (strcmp(_size, "UXGA") == 0)
  481. resol = FRAMESIZE_UXGA; // 1600x1200
  482. }
  483. if (httpd_query_key_value(_query, "quality", _qual, 10) == ESP_OK)
  484. {
  485. #ifdef DEBUG_DETAIL_ON
  486. ESP_LOGD(TAG, "Quality: %s", _qual);
  487. #endif
  488. qual = atoi(_qual);
  489. if (qual > 63) // Limit to max. 63
  490. qual = 63;
  491. else if (qual < 8) // Limit to min. 8
  492. qual = 8;
  493. }
  494. }
  495. }
  496. framesize_t CCamera::TextToFramesize(const char * _size)
  497. {
  498. if (strcmp(_size, "QVGA") == 0)
  499. return FRAMESIZE_QVGA; // 320x240
  500. else if (strcmp(_size, "VGA") == 0)
  501. return FRAMESIZE_VGA; // 640x480
  502. else if (strcmp(_size, "SVGA") == 0)
  503. return FRAMESIZE_SVGA; // 800x600
  504. else if (strcmp(_size, "XGA") == 0)
  505. return FRAMESIZE_XGA; // 1024x768
  506. else if (strcmp(_size, "SXGA") == 0)
  507. return FRAMESIZE_SXGA; // 1280x1024
  508. else if (strcmp(_size, "UXGA") == 0)
  509. return FRAMESIZE_UXGA; // 1600x1200
  510. return ActualResolution;
  511. }
  512. CCamera::CCamera()
  513. {
  514. #ifdef DEBUG_DETAIL_ON
  515. ESP_LOGD(TAG, "CreateClassCamera");
  516. #endif
  517. brightness = 0;
  518. contrast = 0;
  519. saturation = 0;
  520. isFixedExposure = false;
  521. ledc_init();
  522. }
  523. esp_err_t CCamera::InitCam()
  524. {
  525. ESP_LOGD(TAG, "Init Camera");
  526. ActualQuality = camera_config.jpeg_quality;
  527. ActualResolution = camera_config.frame_size;
  528. //initialize the camera
  529. esp_camera_deinit(); // De-init in case it was already initialized
  530. esp_err_t err = esp_camera_init(&camera_config);
  531. if (err != ESP_OK) {
  532. ESP_LOGE(TAG, "Camera Init Failed");
  533. return err;
  534. }
  535. CameraInitSuccessful = true;
  536. return ESP_OK;
  537. }
  538. void CCamera::SetLEDIntensity(float _intrel)
  539. {
  540. _intrel = min(_intrel, (float) 100);
  541. _intrel = max(_intrel, (float) 0);
  542. _intrel = _intrel / 100;
  543. led_intensity = (int) (_intrel * 8191);
  544. ESP_LOGD(TAG, "Set led_intensity to %d of 8191", led_intensity);
  545. }
  546. bool CCamera::getCameraInitSuccessful()
  547. {
  548. return CameraInitSuccessful;
  549. }
  550. std::vector<std::string> demoFiles;
  551. void CCamera::useDemoMode()
  552. {
  553. char line[50];
  554. FILE *fd = fopen("/sdcard/demo/files.txt", "r");
  555. if (!fd) {
  556. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can not start Demo mode, the folder '/sdcard/demo/' does not contain the needed files!");
  557. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "See Details on https://jomjol.github.io/AI-on-the-edge-device-docs/Demo-Mode!");
  558. return;
  559. }
  560. demoImage = (uint8_t*)malloc(DEMO_IMAGE_SIZE);
  561. if (demoImage == NULL) {
  562. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to acquire required memory for demo image!");
  563. return;
  564. }
  565. while (fgets(line, sizeof(line), fd) != NULL) {
  566. line[strlen(line) - 1] = '\0';
  567. demoFiles.push_back(line);
  568. }
  569. fclose(fd);
  570. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Using Demo mode (" + std::to_string(demoFiles.size()) +
  571. " files) instead of real camera image!");
  572. for (auto file : demoFiles) {
  573. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, file);
  574. }
  575. demoMode = true;
  576. }
  577. bool CCamera::loadNextDemoImage(camera_fb_t *fb) {
  578. char filename[50];
  579. int readBytes;
  580. long fileSize;
  581. snprintf(filename, sizeof(filename), "/sdcard/demo/%s", demoFiles[getCountFlowRounds() % demoFiles.size()].c_str());
  582. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Using " + std::string(filename) + " as demo image");
  583. /* Inject saved image */
  584. FILE * fp = fopen(filename, "rb");
  585. if (!fp) {
  586. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to read file: " + std::string(filename) +"!");
  587. return false;
  588. }
  589. fileSize = GetFileSize(filename);
  590. if (fileSize > DEMO_IMAGE_SIZE) {
  591. char buf[100];
  592. snprintf(buf, sizeof(buf), "Demo Image (%d bytes) is larger than provided buffer (%d bytes)!",
  593. (int)fileSize, DEMO_IMAGE_SIZE);
  594. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, std::string(buf));
  595. return false;
  596. }
  597. readBytes = fread(demoImage, 1, DEMO_IMAGE_SIZE, fp);
  598. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "read " + std::to_string(readBytes) + " bytes");
  599. fclose(fp);
  600. fb->buf = demoImage; // Update pointer
  601. fb->len = readBytes;
  602. // ToDo do we also need to set height, width, format and timestamp?
  603. return true;
  604. }
  605. long CCamera::GetFileSize(std::string filename)
  606. {
  607. struct stat stat_buf;
  608. long rc = stat(filename.c_str(), &stat_buf);
  609. return rc == 0 ? stat_buf.st_size : -1;
  610. }