ClassControllCamera.cpp 22 KB

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