ClassControllCamera.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047
  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 <sys/stat.h>
  20. #include "freertos/FreeRTOS.h"
  21. #include "freertos/task.h"
  22. #include "esp_camera.h"
  23. #include "driver/ledc.h"
  24. #include "MainFlowControl.h"
  25. #include "ov2640_sharpness.h"
  26. #if (ESP_IDF_VERSION_MAJOR >= 5)
  27. #include "soc/periph_defs.h"
  28. #include "esp_private/periph_ctrl.h"
  29. #include "soc/gpio_sig_map.h"
  30. #include "soc/gpio_periph.h"
  31. #include "soc/io_mux_reg.h"
  32. #include "esp_rom_gpio.h"
  33. #define gpio_pad_select_gpio esp_rom_gpio_pad_select_gpio
  34. #define gpio_matrix_in(a,b,c) esp_rom_gpio_connect_in_signal(a,b,c)
  35. #define gpio_matrix_out(a,b,c,d) esp_rom_gpio_connect_out_signal(a,b,c,d)
  36. #define ets_delay_us(a) esp_rom_delay_us(a)
  37. #endif
  38. static const char *TAG = "CAM";
  39. /* Camera live stream */
  40. #define PART_BOUNDARY "123456789000000000000987654321"
  41. static const char* _STREAM_CONTENT_TYPE = "multipart/x-mixed-replace;boundary=" PART_BOUNDARY;
  42. static const char* _STREAM_BOUNDARY = "\r\n--" PART_BOUNDARY "\r\n";
  43. static const char* _STREAM_PART = "Content-Type: image/jpeg\r\nContent-Length: %u\r\n\r\n";
  44. // OV2640 Camera SDE Indirect Register Access
  45. #define OV2640_IRA_BPADDR 0x7C
  46. #define OV2640_IRA_BPDATA 0x7D
  47. static camera_config_t camera_config = {
  48. .pin_pwdn = CAM_PIN_PWDN,
  49. .pin_reset = CAM_PIN_RESET,
  50. .pin_xclk = CAM_PIN_XCLK,
  51. .pin_sscb_sda = CAM_PIN_SIOD,
  52. .pin_sscb_scl = CAM_PIN_SIOC,
  53. .pin_d7 = CAM_PIN_D7,
  54. .pin_d6 = CAM_PIN_D6,
  55. .pin_d5 = CAM_PIN_D5,
  56. .pin_d4 = CAM_PIN_D4,
  57. .pin_d3 = CAM_PIN_D3,
  58. .pin_d2 = CAM_PIN_D2,
  59. .pin_d1 = CAM_PIN_D1,
  60. .pin_d0 = CAM_PIN_D0,
  61. .pin_vsync = CAM_PIN_VSYNC,
  62. .pin_href = CAM_PIN_HREF,
  63. .pin_pclk = CAM_PIN_PCLK,
  64. //XCLK 20MHz or 10MHz for OV2640 double FPS (Experimental)
  65. .xclk_freq_hz = 20000000, // Orginal value
  66. // .xclk_freq_hz = 5000000, // Test to get rid of the image errors !!!! Hangs in version 9.2 !!!!
  67. .ledc_timer = LEDC_TIMER_0,
  68. .ledc_channel = LEDC_CHANNEL_0,
  69. .pixel_format = PIXFORMAT_JPEG, //YUV422,GRAYSCALE,RGB565,JPEG
  70. .frame_size = FRAMESIZE_VGA, //QQVGA-UXGA Do not use sizes above QVGA when not JPEG
  71. // .frame_size = FRAMESIZE_UXGA, //QQVGA-UXGA Do not use sizes above QVGA when not JPEG
  72. .jpeg_quality = 12, //0-63 lower number means higher quality
  73. .fb_count = 1, //if more than one, i2s runs in continuous mode. Use only with JPEG
  74. .fb_location = CAMERA_FB_IN_PSRAM, /*!< The location where the frame buffer will be allocated */
  75. .grab_mode = CAMERA_GRAB_LATEST, // only from new esp32cam version
  76. };
  77. CCamera Camera;
  78. uint8_t *demoImage = NULL; // Buffer holding the demo image in bytes
  79. #define DEMO_IMAGE_SIZE 30000 // Max size of demo image in bytes
  80. typedef struct {
  81. httpd_req_t *req;
  82. size_t len;
  83. } jpg_chunking_t;
  84. bool CCamera::testCamera(void) {
  85. bool success;
  86. camera_fb_t *fb = esp_camera_fb_get();
  87. if (fb) {
  88. success = true;
  89. }
  90. else {
  91. success = false;
  92. }
  93. esp_camera_fb_return(fb);
  94. return success;
  95. }
  96. void CCamera::ledc_init(void)
  97. {
  98. #ifdef USE_PWM_LEDFLASH
  99. // Prepare and then apply the LEDC PWM timer configuration
  100. ledc_timer_config_t ledc_timer = { };
  101. ledc_timer.speed_mode = LEDC_MODE;
  102. ledc_timer.timer_num = LEDC_TIMER;
  103. ledc_timer.duty_resolution = LEDC_DUTY_RES;
  104. ledc_timer.freq_hz = LEDC_FREQUENCY; // Set output frequency at 5 kHz
  105. ledc_timer.clk_cfg = LEDC_AUTO_CLK;
  106. ESP_ERROR_CHECK(ledc_timer_config(&ledc_timer));
  107. // Prepare and then apply the LEDC PWM channel configuration
  108. ledc_channel_config_t ledc_channel = { };
  109. ledc_channel.speed_mode = LEDC_MODE;
  110. ledc_channel.channel = LEDC_CHANNEL;
  111. ledc_channel.timer_sel = LEDC_TIMER;
  112. ledc_channel.intr_type = LEDC_INTR_DISABLE;
  113. ledc_channel.gpio_num = LEDC_OUTPUT_IO;
  114. ledc_channel.duty = 0; // Set duty to 0%
  115. ledc_channel.hpoint = 0;
  116. ESP_ERROR_CHECK(ledc_channel_config(&ledc_channel));
  117. #endif
  118. }
  119. static size_t jpg_encode_stream(void * arg, size_t index, const void* data, size_t len)
  120. {
  121. jpg_chunking_t *j = (jpg_chunking_t *)arg;
  122. if(!index) {
  123. j->len = 0;
  124. }
  125. if(httpd_resp_send_chunk(j->req, (const char *)data, len) != ESP_OK) {
  126. return 0;
  127. }
  128. j->len += len;
  129. return len;
  130. }
  131. bool CCamera::SetBrightnessContrastSaturation(int _brightness, int _contrast, int _saturation, int _autoExposureLevel, bool _grayscale, bool _negative, bool _aec2, int _sharpnessLevel)
  132. {
  133. _brightness = min(2, max(-2, _brightness));
  134. _contrast = min(2, max(-2, _contrast));
  135. _saturation = min(2, max(-2, _saturation));
  136. _autoExposureLevel = min(2, max(-2, _autoExposureLevel));
  137. bool _autoSharpness = false;
  138. if (_sharpnessLevel <= -4)
  139. _autoSharpness = true;
  140. _sharpnessLevel = min(3, max(-3, _sharpnessLevel));
  141. sensor_t * s = esp_camera_sensor_get();
  142. if (s) {
  143. // camera gives precedence to negative over grayscale, so it's easier to do negative ourselves.
  144. // if (_negative) {
  145. // s->set_special_effect(s, 1); // 0 - no effect, 1 - negative, 2 - grayscale, 3 - reddish, 4 - greenish, 5 - blue, 6 - retro
  146. // }
  147. if (_grayscale) {
  148. s->set_special_effect(s, 2); // 0 - no effect, 1 - negative, 2 - grayscale, 3 - reddish, 4 - greenish, 5 - blue, 6 - retro
  149. }
  150. // auto exposure controls
  151. s->set_aec2(s, _aec2 ? 1 : 0);
  152. s->set_ae_level(s, _autoExposureLevel); // -2 to 2
  153. s->set_gainceiling(s, GAINCEILING_2X); // GAINCEILING_2X 4X 8X 16X 32X 64X 128X
  154. // post processing
  155. if (_autoSharpness) {
  156. s->set_sharpness(s, 0); // auto-sharpness is not officially supported, default to 0
  157. }
  158. s->set_saturation(s, _saturation);
  159. s->set_contrast(s, _contrast);
  160. s->set_brightness(s, _brightness);
  161. camera_sensor_info_t *sensor_info = esp_camera_sensor_get_info(&(s->id));
  162. if (sensor_info != NULL) {
  163. if (sensor_info->model == CAMERA_OV2640) {
  164. if (_autoSharpness) {
  165. ov2640_enable_auto_sharpness(s);
  166. } else {
  167. ov2640_set_sharpness(s, _sharpnessLevel);
  168. }
  169. /* Workaround - bug in cam library - enable bits are set without using bitwise OR logic -> only latest enable setting is used */
  170. /* Library version: https://github.com/espressif/esp32-camera/commit/5c8349f4cf169c8a61283e0da9b8cff10994d3f3 */
  171. /* Reference: https://esp32.com/viewtopic.php?f=19&t=14376#p93178 */
  172. /* The memory structure is as follows for
  173. byte_0 = enable_bits
  174. byte_0->bit0 = enable saturation and hue --> OK
  175. byte_0->bit1 = enable saturation --> OK
  176. byte_0->bit2 = enable brightness and contrast --> OK
  177. byte_0->bit3 = enable green -> blue spitial effect (Antique and blunish and greenish and readdish and b&w) enable
  178. byte_0->bit4 = anable gray -> read spitial effect (Antique and blunish and greenish and readdish and b&w) enable
  179. byte_0->bit5 = remove (UV) in YUV color system
  180. byte_0->bit6 = enable negative
  181. byte_0->bit7 = remove (Y) in YUV color system
  182. byte_1 = saturation1 0-255 --> ?
  183. byte_2 = hue 0-255 --> OK
  184. byte_3 = saturation2 0-255 --> OK
  185. byte_4 = reenter saturation2 in documents --> ?
  186. byte_5 = spital effect green -> blue 0-255 --> ?
  187. byte_6 = spital effect gray -> read 0-255 --> ?
  188. byte_7 = contrast lower byte 0-255 --> OK
  189. byte_8 = contrast higher byte 0-255 --> OK
  190. byte_9 = brightness 0-255 --> OK
  191. byte_10= if byte_10==4 contrast effective --> ?
  192. */
  193. //s->set_reg(s, 0x7C, 0xFF, 2); // Optional feature - hue setting: Select byte 2 in register 0x7C to set hue value
  194. //s->set_reg(s, 0x7D, 0xFF, 0); // Optional feature - hue setting: Hue value 0 - 255
  195. int indirectReg0 = 0x07; // Set bit 0, 1, 2 to enable saturation, contrast, brightness and hue control
  196. if (_grayscale) {
  197. indirectReg0 |= 0x18;
  198. }
  199. // camera gives precedence to negative over grayscale, so it's easier to do negative ourselves.
  200. // if (_negative) {
  201. // indirectReg0 |= 0x40;
  202. // }
  203. // Indirect register access
  204. s->set_reg(s, 0xFF, 0x01, 0); // Select DSP bank
  205. s->set_reg(s, OV2640_IRA_BPADDR, 0xFF, 0x00); // Address 0x00
  206. s->set_reg(s, OV2640_IRA_BPDATA, 0xFF, indirectReg0);
  207. s->set_reg(s, OV2640_IRA_BPADDR, 0xFF, 0x05); // Address 0x05
  208. s->set_reg(s, OV2640_IRA_BPDATA, 0xFF, 0x80);
  209. s->set_reg(s, OV2640_IRA_BPDATA, 0xFF, 0x80);
  210. }
  211. }
  212. }
  213. else {
  214. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "SetBrightnessContrastSaturation: Failed to get control structure");
  215. }
  216. if (((_brightness != brightness) || (_contrast != contrast) || (_saturation != saturation)) && isFixedExposure)
  217. EnableAutoExposure(waitbeforepicture_org);
  218. brightness = _brightness;
  219. contrast = _contrast;
  220. saturation = _saturation;
  221. autoExposureLevel = _autoExposureLevel;
  222. imageGrayscale = _grayscale;
  223. imageNegative = _negative;
  224. imageAec2 = _aec2;
  225. imageAutoSharpness = _autoSharpness;
  226. imageSharpnessLevel = _sharpnessLevel;
  227. ESP_LOGD(TAG, "brightness %d, contrast: %d, saturation %d, autoExposureLevel %d, grayscale %d", brightness, contrast, saturation, autoExposureLevel, (int)imageGrayscale);
  228. return true;
  229. }
  230. /*
  231. * resolution = 0 \\ 1600 x 1200
  232. * resolution = 1 \\ 800 x 600
  233. * resolution = 2 \\ 400 x 296
  234. */
  235. void CCamera::SetCamWindow(sensor_t *s, int resolution, int xOffset, int yOffset, int xLength, int yLength)
  236. {
  237. s->set_res_raw(s, resolution, 0, 0, 0, xOffset, yOffset, xLength, yLength, xLength, yLength, false, false);
  238. }
  239. void CCamera::SetImageWidthHeightFromResolution(framesize_t resol)
  240. {
  241. if (resol == FRAMESIZE_QVGA)
  242. {
  243. image_height = 240;
  244. image_width = 320;
  245. }
  246. else if (resol == FRAMESIZE_VGA)
  247. {
  248. image_height = 480;
  249. image_width = 640;
  250. }
  251. else if (resol == FRAMESIZE_SVGA)
  252. {
  253. image_height = 600;
  254. image_width = 800;
  255. }
  256. else if (resol == FRAMESIZE_XGA)
  257. {
  258. image_height = 768;
  259. image_width = 1024;
  260. }
  261. else if (resol == FRAMESIZE_HD)
  262. {
  263. image_height = 720;
  264. image_width = 1280;
  265. }
  266. else if (resol == FRAMESIZE_SXGA)
  267. {
  268. image_height = 1024;
  269. image_width = 1280;
  270. }
  271. else if (resol == FRAMESIZE_UXGA)
  272. {
  273. image_height = 1200;
  274. image_width = 1600;
  275. }
  276. }
  277. void CCamera::SetZoom(bool zoomEnabled, int zoomMode, int zoomOffsetX, int zoomOffsetY)
  278. {
  279. imageZoomEnabled = zoomEnabled;
  280. imageZoomMode = zoomMode;
  281. imageZoomOffsetX = zoomOffsetX;
  282. imageZoomOffsetY = zoomOffsetY;
  283. sensor_t *s = esp_camera_sensor_get();
  284. if (s) {
  285. if (imageZoomEnabled) {
  286. int z = imageZoomMode;
  287. int x = imageZoomOffsetX;
  288. int y = imageZoomOffsetY;
  289. if (z > 1)
  290. z = 1;
  291. if (image_width >= 800 || image_height >= 600) {
  292. z = 0;
  293. }
  294. int maxX = 1600 - image_width;
  295. int maxY = 1200 - image_height;
  296. if (z == 1) {
  297. maxX = 800 - image_width;
  298. maxY = 600 - image_height;
  299. }
  300. if (x > maxX)
  301. x = maxX;
  302. if (y > maxY)
  303. y = maxY;
  304. SetCamWindow(s, z, x, y, image_width, image_height);
  305. } else {
  306. s->set_framesize(s, ActualResolution);
  307. }
  308. }
  309. }
  310. void CCamera::SetQualitySize(int qual, framesize_t resol, bool zoomEnabled, int zoomMode, int zoomOffsetX, int zoomOffsetY)
  311. {
  312. qual = min(63, max(8, qual)); // Limit quality from 8..63 (values lower than 8 tent to be unstable)
  313. ActualResolution = resol;
  314. ActualQuality = qual;
  315. imageZoomEnabled = zoomEnabled;
  316. imageZoomMode = zoomMode;
  317. imageZoomOffsetX = zoomOffsetX;
  318. imageZoomOffsetY = zoomOffsetY;
  319. SetImageWidthHeightFromResolution(resol);
  320. sensor_t * s = esp_camera_sensor_get();
  321. if (s) {
  322. s->set_quality(s, qual);
  323. SetZoom(zoomEnabled, zoomMode, zoomOffsetX, zoomOffsetY);
  324. }
  325. else {
  326. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "SetQualitySize: Failed to get control structure");
  327. }
  328. }
  329. void CCamera::EnableAutoExposure(int flash_duration)
  330. {
  331. ESP_LOGD(TAG, "EnableAutoExposure");
  332. LEDOnOff(true);
  333. if (flash_duration > 0) {
  334. LightOnOff(true);
  335. const TickType_t xDelay = flash_duration / portTICK_PERIOD_MS;
  336. vTaskDelay( xDelay );
  337. }
  338. camera_fb_t * fb = esp_camera_fb_get();
  339. esp_camera_fb_return(fb);
  340. fb = esp_camera_fb_get();
  341. if (!fb) {
  342. LEDOnOff(false);
  343. LightOnOff(false);
  344. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "EnableAutoExposure: Capture Failed. "
  345. "Check camera module and/or proper electrical connection");
  346. //doReboot();
  347. }
  348. esp_camera_fb_return(fb);
  349. sensor_t * s = esp_camera_sensor_get();
  350. if (s) {
  351. s->set_gain_ctrl(s, 0);
  352. s->set_exposure_ctrl(s, 0);
  353. }
  354. else {
  355. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "EnableAutoExposure: Failed to get control structure to set gain+exposure");
  356. }
  357. LEDOnOff(false);
  358. LightOnOff(false);
  359. isFixedExposure = true;
  360. waitbeforepicture_org = flash_duration;
  361. }
  362. esp_err_t CCamera::CaptureToBasisImage(CImageBasis *_Image, int delay)
  363. {
  364. #ifdef DEBUG_DETAIL_ON
  365. LogFile.WriteHeapInfo("CaptureToBasisImage - Start");
  366. #endif
  367. _Image->EmptyImage(); //Delete previous stored raw image -> black image
  368. LEDOnOff(true);
  369. if (delay > 0) {
  370. LightOnOff(true);
  371. const TickType_t xDelay = delay / portTICK_PERIOD_MS;
  372. vTaskDelay( xDelay );
  373. }
  374. #ifdef DEBUG_DETAIL_ON
  375. LogFile.WriteHeapInfo("CaptureToBasisImage - After LightOn");
  376. #endif
  377. camera_fb_t * fb = esp_camera_fb_get();
  378. esp_camera_fb_return(fb);
  379. fb = esp_camera_fb_get();
  380. if (!fb) {
  381. LEDOnOff(false);
  382. LightOnOff(false);
  383. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "is not working anymore (CaptureToBasisImage) - most probably caused "
  384. "by a hardware problem (instablility, ...). System will reboot.");
  385. doReboot();
  386. return ESP_FAIL;
  387. }
  388. if (demoMode) { // Use images stored on SD-Card instead of camera image
  389. /* Replace Framebuffer with image from SD-Card */
  390. loadNextDemoImage(fb);
  391. }
  392. CImageBasis* _zwImage = new CImageBasis("zwImage");
  393. if (_zwImage) {
  394. _zwImage->LoadFromMemory(fb->buf, fb->len);
  395. }
  396. else {
  397. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: Can't allocate _zwImage");
  398. }
  399. esp_camera_fb_return(fb);
  400. #ifdef DEBUG_DETAIL_ON
  401. LogFile.WriteHeapInfo("CaptureToBasisImage - After fb_get");
  402. #endif
  403. LEDOnOff(false);
  404. if (delay > 0)
  405. LightOnOff(false);
  406. // TickType_t xDelay = 1000 / portTICK_PERIOD_MS;
  407. // vTaskDelay( xDelay ); // wait for power to recover
  408. #ifdef DEBUG_DETAIL_ON
  409. LogFile.WriteHeapInfo("CaptureToBasisImage - After LoadFromMemory");
  410. #endif
  411. if (_zwImage == NULL) {
  412. return ESP_OK;
  413. }
  414. if (imageNegative) {
  415. _zwImage->Negative();
  416. }
  417. stbi_uc* p_target;
  418. stbi_uc* p_source;
  419. int channels = 3;
  420. int width = image_width;
  421. int height = image_height;
  422. #ifdef DEBUG_DETAIL_ON
  423. std::string _zw = "Targetimage: " + std::to_string((int) _Image->rgb_image) + " Size: " + std::to_string(_Image->width) + ", " + std::to_string(_Image->height);
  424. _zw = _zw + " _zwImage: " + std::to_string((int) _zwImage->rgb_image) + " Size: " + std::to_string(_zwImage->width) + ", " + std::to_string(_zwImage->height);
  425. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, _zw);
  426. #endif
  427. for (int x = 0; x < width; ++x)
  428. for (int y = 0; y < height; ++y)
  429. {
  430. p_target = _Image->rgb_image + (channels * (y * width + x));
  431. p_source = _zwImage->rgb_image + (channels * (y * width + x));
  432. for (int c = 0; c < channels; c++) {
  433. p_target[c] = p_source[c];
  434. }
  435. }
  436. delete _zwImage;
  437. #ifdef DEBUG_DETAIL_ON
  438. LogFile.WriteHeapInfo("CaptureToBasisImage - Done");
  439. #endif
  440. return ESP_OK;
  441. }
  442. esp_err_t CCamera::CaptureToFile(std::string nm, int delay)
  443. {
  444. string ftype;
  445. LEDOnOff(true); // Switched off to save power !
  446. if (delay > 0) {
  447. LightOnOff(true);
  448. const TickType_t xDelay = delay / portTICK_PERIOD_MS;
  449. vTaskDelay( xDelay );
  450. }
  451. camera_fb_t * fb = esp_camera_fb_get();
  452. esp_camera_fb_return(fb);
  453. fb = esp_camera_fb_get();
  454. if (!fb) {
  455. LEDOnOff(false);
  456. LightOnOff(false);
  457. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToFile: Capture Failed. "
  458. "Check camera module and/or proper electrical connection");
  459. //doReboot();
  460. return ESP_FAIL;
  461. }
  462. LEDOnOff(false);
  463. #ifdef DEBUG_DETAIL_ON
  464. ESP_LOGD(TAG, "w %d, h %d, size %d", fb->width, fb->height, fb->len);
  465. #endif
  466. nm = FormatFileName(nm);
  467. #ifdef DEBUG_DETAIL_ON
  468. ESP_LOGD(TAG, "Save Camera to: %s", nm.c_str());
  469. #endif
  470. ftype = toUpper(getFileType(nm));
  471. #ifdef DEBUG_DETAIL_ON
  472. ESP_LOGD(TAG, "Filetype: %s", ftype.c_str());
  473. #endif
  474. uint8_t * buf = NULL;
  475. size_t buf_len = 0;
  476. bool converted = false;
  477. if (ftype.compare("BMP") == 0)
  478. {
  479. frame2bmp(fb, &buf, &buf_len);
  480. converted = true;
  481. }
  482. if (ftype.compare("JPG") == 0)
  483. {
  484. if(fb->format != PIXFORMAT_JPEG){
  485. bool jpeg_converted = frame2jpg(fb, ActualQuality, &buf, &buf_len);
  486. converted = true;
  487. if(!jpeg_converted){
  488. ESP_LOGE(TAG, "JPEG compression failed");
  489. }
  490. } else {
  491. buf_len = fb->len;
  492. buf = fb->buf;
  493. }
  494. }
  495. FILE * fp = fopen(nm.c_str(), "wb");
  496. if (fp == NULL) { // If an error occurs during the file creation
  497. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToFile: Failed to open file " + nm);
  498. }
  499. else {
  500. fwrite(buf, sizeof(uint8_t), buf_len, fp);
  501. fclose(fp);
  502. }
  503. if (converted)
  504. free(buf);
  505. esp_camera_fb_return(fb);
  506. if (delay > 0)
  507. LightOnOff(false);
  508. return ESP_OK;
  509. }
  510. esp_err_t CCamera::CaptureToHTTP(httpd_req_t *req, int delay)
  511. {
  512. esp_err_t res = ESP_OK;
  513. size_t fb_len = 0;
  514. int64_t fr_start = esp_timer_get_time();
  515. LEDOnOff(true);
  516. if (delay > 0) {
  517. LightOnOff(true);
  518. const TickType_t xDelay = delay / portTICK_PERIOD_MS;
  519. vTaskDelay( xDelay );
  520. }
  521. camera_fb_t *fb = esp_camera_fb_get();
  522. esp_camera_fb_return(fb);
  523. fb = esp_camera_fb_get();
  524. if (!fb) {
  525. LEDOnOff(false);
  526. LightOnOff(false);
  527. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToFile: Capture Failed. "
  528. "Check camera module and/or proper electrical connection");
  529. httpd_resp_send_500(req);
  530. // doReboot();
  531. return ESP_FAIL;
  532. }
  533. LEDOnOff(false);
  534. res = httpd_resp_set_type(req, "image/jpeg");
  535. if(res == ESP_OK){
  536. res = httpd_resp_set_hdr(req, "Content-Disposition", "inline; filename=raw.jpg");
  537. }
  538. if(res == ESP_OK){
  539. if (demoMode) { // Use images stored on SD-Card instead of camera image
  540. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Using Demo image!");
  541. /* Replace Framebuffer with image from SD-Card */
  542. loadNextDemoImage(fb);
  543. res = httpd_resp_send(req, (const char *)fb->buf, fb->len);
  544. }
  545. else {
  546. if(fb->format == PIXFORMAT_JPEG){
  547. fb_len = fb->len;
  548. res = httpd_resp_send(req, (const char *)fb->buf, fb->len);
  549. } else {
  550. jpg_chunking_t jchunk = {req, 0};
  551. res = frame2jpg_cb(fb, 80, jpg_encode_stream, &jchunk)?ESP_OK:ESP_FAIL;
  552. httpd_resp_send_chunk(req, NULL, 0);
  553. fb_len = jchunk.len;
  554. }
  555. }
  556. }
  557. esp_camera_fb_return(fb);
  558. int64_t fr_end = esp_timer_get_time();
  559. ESP_LOGI(TAG, "JPG: %dKB %dms", (int)(fb_len/1024), (int)((fr_end - fr_start)/1000));
  560. if (delay > 0)
  561. LightOnOff(false);
  562. return res;
  563. }
  564. esp_err_t CCamera::CaptureToStream(httpd_req_t *req, bool FlashlightOn)
  565. {
  566. esp_err_t res = ESP_OK;
  567. size_t fb_len = 0;
  568. int64_t fr_start;
  569. char * part_buf[64];
  570. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Live stream started");
  571. if (FlashlightOn) {
  572. LEDOnOff(true);
  573. LightOnOff(true);
  574. }
  575. //httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); //stream is blocking web interface, only serving to local
  576. httpd_resp_set_type(req, _STREAM_CONTENT_TYPE);
  577. httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY));
  578. while(1)
  579. {
  580. fr_start = esp_timer_get_time();
  581. camera_fb_t *fb = esp_camera_fb_get();
  582. esp_camera_fb_return(fb);
  583. fb = esp_camera_fb_get();
  584. if (!fb) {
  585. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToStream: Camera framebuffer not available");
  586. break;
  587. }
  588. fb_len = fb->len;
  589. if (res == ESP_OK){
  590. size_t hlen = snprintf((char *)part_buf, sizeof(part_buf), _STREAM_PART, fb_len);
  591. res = httpd_resp_send_chunk(req, (const char *)part_buf, hlen);
  592. }
  593. if (res == ESP_OK){
  594. res = httpd_resp_send_chunk(req, (const char *)fb->buf, fb_len);
  595. }
  596. if (res == ESP_OK){
  597. res = httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY));
  598. }
  599. esp_camera_fb_return(fb);
  600. int64_t fr_end = esp_timer_get_time();
  601. ESP_LOGD(TAG, "JPG: %dKB %dms", (int)(fb_len/1024), (int)((fr_end - fr_start)/1000));
  602. if (res != ESP_OK){ // Exit loop, e.g. also when closing the webpage
  603. break;
  604. }
  605. int64_t fr_delta_ms = (fr_end - fr_start) / 1000;
  606. if (CAM_LIVESTREAM_REFRESHRATE > fr_delta_ms) {
  607. const TickType_t xDelay = (CAM_LIVESTREAM_REFRESHRATE - fr_delta_ms) / portTICK_PERIOD_MS;
  608. ESP_LOGD(TAG, "Stream: sleep for: %ldms", (long) xDelay*10);
  609. vTaskDelay(xDelay);
  610. }
  611. }
  612. LEDOnOff(false);
  613. LightOnOff(false);
  614. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Live stream stopped");
  615. return res;
  616. }
  617. void CCamera::LightOnOff(bool status)
  618. {
  619. GpioHandler* gpioHandler = gpio_handler_get();
  620. if ((gpioHandler != NULL) && (gpioHandler->isEnabled())) {
  621. ESP_LOGD(TAG, "Use gpioHandler to trigger flashlight");
  622. gpioHandler->flashLightEnable(status);
  623. }
  624. else {
  625. #ifdef USE_PWM_LEDFLASH
  626. if (status) {
  627. ESP_LOGD(TAG, "Internal Flash-LED turn on with PWM %d", led_intensity);
  628. ESP_ERROR_CHECK(ledc_set_duty(LEDC_MODE, LEDC_CHANNEL, led_intensity));
  629. // Update duty to apply the new value
  630. ESP_ERROR_CHECK(ledc_update_duty(LEDC_MODE, LEDC_CHANNEL));
  631. }
  632. else {
  633. ESP_LOGD(TAG, "Internal Flash-LED turn off PWM");
  634. ESP_ERROR_CHECK(ledc_set_duty(LEDC_MODE, LEDC_CHANNEL, 0));
  635. ESP_ERROR_CHECK(ledc_update_duty(LEDC_MODE, LEDC_CHANNEL));
  636. }
  637. #else
  638. // Init the GPIO
  639. gpio_pad_select_gpio(FLASH_GPIO);
  640. // Set the GPIO as a push/pull output
  641. gpio_set_direction(FLASH_GPIO, GPIO_MODE_OUTPUT);
  642. if (status)
  643. gpio_set_level(FLASH_GPIO, 1);
  644. else
  645. gpio_set_level(FLASH_GPIO, 0);
  646. #endif
  647. }
  648. }
  649. void CCamera::LEDOnOff(bool status)
  650. {
  651. if (xHandle_task_StatusLED == NULL) {
  652. // Init the GPIO
  653. gpio_pad_select_gpio(BLINK_GPIO);
  654. /* Set the GPIO as a push/pull output */
  655. gpio_set_direction(BLINK_GPIO, GPIO_MODE_OUTPUT);
  656. if (!status)
  657. gpio_set_level(BLINK_GPIO, 1);
  658. else
  659. gpio_set_level(BLINK_GPIO, 0);
  660. }
  661. }
  662. void CCamera::GetCameraParameter(httpd_req_t *req, int &qual, framesize_t &resol, bool &zoomEnabled, int &zoomMode, int &zoomOffsetX, int &zoomOffsetY)
  663. {
  664. char _query[100];
  665. char _value[10];
  666. resol = ActualResolution;
  667. qual = ActualQuality;
  668. zoomEnabled = imageZoomEnabled;
  669. zoomMode = imageZoomMode;
  670. zoomOffsetX = imageZoomOffsetX;
  671. zoomOffsetY = imageZoomOffsetY;
  672. if (httpd_req_get_url_query_str(req, _query, 100) == ESP_OK)
  673. {
  674. ESP_LOGD(TAG, "Query: %s", _query);
  675. if (httpd_query_key_value(_query, "size", _value, sizeof(_value)) == ESP_OK)
  676. {
  677. #ifdef DEBUG_DETAIL_ON
  678. ESP_LOGD(TAG, "Size: %s", _size);
  679. #endif
  680. if (strcmp(_value, "QVGA") == 0)
  681. resol = FRAMESIZE_QVGA; // 320x240
  682. else if (strcmp(_value, "VGA") == 0)
  683. resol = FRAMESIZE_VGA; // 640x480
  684. else if (strcmp(_value, "SVGA") == 0)
  685. resol = FRAMESIZE_SVGA; // 800x600
  686. else if (strcmp(_value, "XGA") == 0)
  687. resol = FRAMESIZE_XGA; // 1024x768
  688. else if (strcmp(_value, "SXGA") == 0)
  689. resol = FRAMESIZE_SXGA; // 1280x1024
  690. else if (strcmp(_value, "UXGA") == 0)
  691. resol = FRAMESIZE_UXGA; // 1600x1200
  692. }
  693. if (httpd_query_key_value(_query, "quality", _value, sizeof(_value)) == ESP_OK)
  694. {
  695. #ifdef DEBUG_DETAIL_ON
  696. ESP_LOGD(TAG, "Quality: %s", _qual);
  697. #endif
  698. qual = atoi(_value);
  699. if (qual > 63) // Limit to max. 63
  700. qual = 63;
  701. else if (qual < 8) // Limit to min. 8
  702. qual = 8;
  703. }
  704. if (httpd_query_key_value(_query, "z", _value, sizeof(_value)) == ESP_OK)
  705. {
  706. #ifdef DEBUG_DETAIL_ON
  707. ESP_LOGD(TAG, "Zoom: %s", _value);
  708. #endif
  709. if (atoi(_value) != 0)
  710. zoomEnabled = true;
  711. else
  712. zoomEnabled = false;
  713. }
  714. if (httpd_query_key_value(_query, "zm", _value, sizeof(_value)) == ESP_OK)
  715. {
  716. #ifdef DEBUG_DETAIL_ON
  717. ESP_LOGD(TAG, "Zoom mode: %s", _value);
  718. #endif
  719. zoomMode = atoi(_value);
  720. if (zoomMode > 2)
  721. zoomMode = 2;
  722. else if (zoomMode < 0)
  723. zoomMode = 0;
  724. }
  725. if (httpd_query_key_value(_query, "x", _value, sizeof(_value)) == ESP_OK)
  726. {
  727. #ifdef DEBUG_DETAIL_ON
  728. ESP_LOGD(TAG, "X offset: %s", _value);
  729. #endif
  730. zoomOffsetX = atoi(_value);
  731. if (zoomOffsetX < 0)
  732. zoomOffsetX = 0;
  733. }
  734. if (httpd_query_key_value(_query, "y", _value, sizeof(_value)) == ESP_OK)
  735. {
  736. #ifdef DEBUG_DETAIL_ON
  737. ESP_LOGD(TAG, "Y offset: %s", _value);
  738. #endif
  739. zoomOffsetY = atoi(_value);
  740. if (zoomOffsetY < 0)
  741. zoomOffsetY = 0;
  742. }
  743. }
  744. }
  745. framesize_t CCamera::TextToFramesize(const char * _size)
  746. {
  747. if (strcmp(_size, "QVGA") == 0)
  748. return FRAMESIZE_QVGA; // 320x240
  749. else if (strcmp(_size, "VGA") == 0)
  750. return FRAMESIZE_VGA; // 640x480
  751. else if (strcmp(_size, "SVGA") == 0)
  752. return FRAMESIZE_SVGA; // 800x600
  753. else if (strcmp(_size, "XGA") == 0)
  754. return FRAMESIZE_XGA; // 1024x768
  755. else if (strcmp(_size, "SXGA") == 0)
  756. return FRAMESIZE_SXGA; // 1280x1024
  757. else if (strcmp(_size, "UXGA") == 0)
  758. return FRAMESIZE_UXGA; // 1600x1200
  759. return ActualResolution;
  760. }
  761. CCamera::CCamera()
  762. {
  763. #ifdef DEBUG_DETAIL_ON
  764. ESP_LOGD(TAG, "CreateClassCamera");
  765. #endif
  766. brightness = 0;
  767. contrast = 0;
  768. saturation = 0;
  769. isFixedExposure = false;
  770. ledc_init();
  771. }
  772. esp_err_t CCamera::InitCam()
  773. {
  774. ESP_LOGD(TAG, "Init Camera");
  775. ActualQuality = camera_config.jpeg_quality;
  776. ActualResolution = camera_config.frame_size;
  777. //initialize the camera
  778. esp_camera_deinit(); // De-init in case it was already initialized
  779. esp_err_t err = esp_camera_init(&camera_config);
  780. if (err != ESP_OK) {
  781. ESP_LOGE(TAG, "Camera Init Failed");
  782. return err;
  783. }
  784. CameraInitSuccessful = true;
  785. return ESP_OK;
  786. }
  787. void CCamera::SetLEDIntensity(float _intrel)
  788. {
  789. _intrel = min(_intrel, (float) 100);
  790. _intrel = max(_intrel, (float) 0);
  791. _intrel = _intrel / 100;
  792. led_intensity = (int) (_intrel * 8191);
  793. ESP_LOGD(TAG, "Set led_intensity to %d of 8191", led_intensity);
  794. }
  795. bool CCamera::getCameraInitSuccessful()
  796. {
  797. return CameraInitSuccessful;
  798. }
  799. std::vector<std::string> demoFiles;
  800. void CCamera::useDemoMode()
  801. {
  802. char line[50];
  803. FILE *fd = fopen("/sdcard/demo/files.txt", "r");
  804. if (!fd) {
  805. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can not start Demo mode, the folder '/sdcard/demo/' does not contain the needed files!");
  806. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "See Details on https://jomjol.github.io/AI-on-the-edge-device-docs/Demo-Mode!");
  807. return;
  808. }
  809. demoImage = (uint8_t*)malloc(DEMO_IMAGE_SIZE);
  810. if (demoImage == NULL) {
  811. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to acquire required memory for demo image!");
  812. return;
  813. }
  814. while (fgets(line, sizeof(line), fd) != NULL) {
  815. line[strlen(line) - 1] = '\0';
  816. demoFiles.push_back(line);
  817. }
  818. fclose(fd);
  819. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Using Demo mode (" + std::to_string(demoFiles.size()) +
  820. " files) instead of real camera image!");
  821. for (auto file : demoFiles) {
  822. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, file);
  823. }
  824. demoMode = true;
  825. }
  826. bool CCamera::loadNextDemoImage(camera_fb_t *fb) {
  827. char filename[50];
  828. int readBytes;
  829. long fileSize;
  830. snprintf(filename, sizeof(filename), "/sdcard/demo/%s", demoFiles[getCountFlowRounds() % demoFiles.size()].c_str());
  831. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Using " + std::string(filename) + " as demo image");
  832. /* Inject saved image */
  833. FILE * fp = fopen(filename, "rb");
  834. if (!fp) {
  835. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to read file: " + std::string(filename) +"!");
  836. return false;
  837. }
  838. fileSize = GetFileSize(filename);
  839. if (fileSize > DEMO_IMAGE_SIZE) {
  840. char buf[100];
  841. snprintf(buf, sizeof(buf), "Demo Image (%d bytes) is larger than provided buffer (%d bytes)!",
  842. (int)fileSize, DEMO_IMAGE_SIZE);
  843. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, std::string(buf));
  844. return false;
  845. }
  846. readBytes = fread(demoImage, 1, DEMO_IMAGE_SIZE, fp);
  847. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "read " + std::to_string(readBytes) + " bytes");
  848. fclose(fp);
  849. fb->buf = demoImage; // Update pointer
  850. fb->len = readBytes;
  851. // ToDo do we also need to set height, width, format and timestamp?
  852. return true;
  853. }
  854. long CCamera::GetFileSize(std::string filename)
  855. {
  856. struct stat stat_buf;
  857. long rc = stat(filename.c_str(), &stat_buf);
  858. return rc == 0 ? stat_buf.st_size : -1;
  859. }