ClassControllCamera.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140
  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. CCamera Camera;
  39. camera_controll_config_temp_t CCstatus;
  40. static const char *TAG = "CAM";
  41. /* Camera live stream */
  42. #define PART_BOUNDARY "123456789000000000000987654321"
  43. static const char *_STREAM_CONTENT_TYPE = "multipart/x-mixed-replace;boundary=" PART_BOUNDARY;
  44. static const char *_STREAM_BOUNDARY = "\r\n--" PART_BOUNDARY "\r\n";
  45. static const char *_STREAM_PART = "Content-Type: image/jpeg\r\nContent-Length: %u\r\n\r\n";
  46. uint8_t *demoImage = NULL; // Buffer holding the demo image in bytes
  47. #define DEMO_IMAGE_SIZE 30000 // Max size of demo image in bytes
  48. // Camera module bus communications frequency.
  49. // Originally: config.xclk_freq_mhz = 20000000, but this lead to visual artifacts on many modules.
  50. // See https://github.com/espressif/esp32-camera/issues/150#issuecomment-726473652 et al.
  51. #if !defined(XCLK_FREQ_MHZ)
  52. // int xclk = 8;
  53. int xclk = 20; // Orginal value
  54. #else
  55. int xclk = XCLK_FREQ_MHZ;
  56. #endif
  57. static camera_config_t camera_config = {
  58. .pin_pwdn = CAM_PIN_PWDN,
  59. .pin_reset = CAM_PIN_RESET,
  60. .pin_xclk = CAM_PIN_XCLK,
  61. .pin_sscb_sda = CAM_PIN_SIOD,
  62. .pin_sscb_scl = CAM_PIN_SIOC,
  63. .pin_d7 = CAM_PIN_D7,
  64. .pin_d6 = CAM_PIN_D6,
  65. .pin_d5 = CAM_PIN_D5,
  66. .pin_d4 = CAM_PIN_D4,
  67. .pin_d3 = CAM_PIN_D3,
  68. .pin_d2 = CAM_PIN_D2,
  69. .pin_d1 = CAM_PIN_D1,
  70. .pin_d0 = CAM_PIN_D0,
  71. .pin_vsync = CAM_PIN_VSYNC,
  72. .pin_href = CAM_PIN_HREF,
  73. .pin_pclk = CAM_PIN_PCLK,
  74. .xclk_freq_hz = (xclk * 1000000),
  75. .ledc_timer = LEDC_TIMER_0, // LEDC timer to be used for generating XCLK
  76. .ledc_channel = LEDC_CHANNEL_0, // LEDC channel to be used for generating XCLK
  77. .pixel_format = PIXFORMAT_JPEG, // YUV422,GRAYSCALE,RGB565,JPEG
  78. .frame_size = FRAMESIZE_VGA, // QQVGA-UXGA Do not use sizes above QVGA when not JPEG
  79. // .frame_size = FRAMESIZE_UXGA, //QQVGA-UXGA Do not use sizes above QVGA when not JPEG
  80. .jpeg_quality = 6, // 0-63 lower number means higher quality
  81. .fb_count = 1, // if more than one, i2s runs in continuous mode. Use only with JPEG
  82. .fb_location = CAMERA_FB_IN_PSRAM, /*!< The location where the frame buffer will be allocated */
  83. .grab_mode = CAMERA_GRAB_LATEST, // only from new esp32cam version
  84. };
  85. typedef struct
  86. {
  87. httpd_req_t *req;
  88. size_t len;
  89. } jpg_chunking_t;
  90. CCamera::CCamera(void)
  91. {
  92. #ifdef DEBUG_DETAIL_ON
  93. ESP_LOGD(TAG, "CreateClassCamera");
  94. #endif
  95. CCstatus.WaitBeforePicture = 2;
  96. ledc_init();
  97. }
  98. esp_err_t CCamera::InitCam(void)
  99. {
  100. ESP_LOGD(TAG, "Init Camera");
  101. CCstatus.ImageQuality = camera_config.jpeg_quality;
  102. CCstatus.ImageFrameSize = camera_config.frame_size;
  103. // initialize the camera
  104. esp_camera_deinit(); // De-init in case it was already initialized
  105. esp_err_t err = esp_camera_init(&camera_config);
  106. if (err != ESP_OK)
  107. {
  108. ESP_LOGE(TAG, "Camera Init Failed");
  109. return err;
  110. }
  111. CCstatus.CameraInitSuccessful = true;
  112. // Get a reference to the sensor
  113. sensor_t *s = esp_camera_sensor_get();
  114. if (s != NULL)
  115. {
  116. // Dump camera module, warn for unsupported modules.
  117. switch (s->id.PID)
  118. {
  119. case OV2640_PID:
  120. ESP_LOGI(TAG, "OV2640 camera module detected");
  121. break;
  122. case OV3660_PID:
  123. ESP_LOGI(TAG, "OV3660 camera module detected");
  124. break;
  125. default:
  126. ESP_LOGE(TAG, "Camera module is unknown and not properly supported!");
  127. CCstatus.CameraInitSuccessful = false;
  128. }
  129. }
  130. if (CCstatus.CameraInitSuccessful)
  131. {
  132. return ESP_OK;
  133. }
  134. else
  135. {
  136. return ESP_FAIL;
  137. }
  138. }
  139. bool CCamera::testCamera(void)
  140. {
  141. bool success;
  142. camera_fb_t *fb = esp_camera_fb_get();
  143. if (fb)
  144. {
  145. success = true;
  146. }
  147. else
  148. {
  149. success = false;
  150. }
  151. esp_camera_fb_return(fb);
  152. return success;
  153. }
  154. void CCamera::ledc_init(void)
  155. {
  156. #ifdef USE_PWM_LEDFLASH
  157. // Prepare and then apply the LEDC PWM timer configuration
  158. ledc_timer_config_t ledc_timer = {};
  159. ledc_timer.speed_mode = LEDC_MODE;
  160. ledc_timer.timer_num = LEDC_TIMER;
  161. ledc_timer.duty_resolution = LEDC_DUTY_RES;
  162. ledc_timer.freq_hz = LEDC_FREQUENCY; // Set output frequency at 5 kHz
  163. ledc_timer.clk_cfg = LEDC_AUTO_CLK;
  164. ESP_ERROR_CHECK(ledc_timer_config(&ledc_timer));
  165. // Prepare and then apply the LEDC PWM channel configuration
  166. ledc_channel_config_t ledc_channel = {};
  167. ledc_channel.speed_mode = LEDC_MODE;
  168. ledc_channel.channel = LEDC_CHANNEL;
  169. ledc_channel.timer_sel = LEDC_TIMER;
  170. ledc_channel.intr_type = LEDC_INTR_DISABLE;
  171. ledc_channel.gpio_num = LEDC_OUTPUT_IO;
  172. ledc_channel.duty = 0; // Set duty to 0%
  173. ledc_channel.hpoint = 0;
  174. // ledc_channel.flags.output_invert = LEDC_OUTPUT_INVERT;
  175. ESP_ERROR_CHECK(ledc_channel_config(&ledc_channel));
  176. #endif
  177. }
  178. void CCamera::SetLEDIntensity(float _intrel)
  179. {
  180. _intrel = min(_intrel, (float)100);
  181. _intrel = max(_intrel, (float)0);
  182. _intrel = _intrel / 100;
  183. CCstatus.ImageLedIntensity = (int)(_intrel * 8191);
  184. ESP_LOGD(TAG, "Set led_intensity to %d of 8191", CCstatus.ImageLedIntensity);
  185. }
  186. bool CCamera::getCameraInitSuccessful(void)
  187. {
  188. return CCstatus.CameraInitSuccessful;
  189. }
  190. esp_err_t CCamera::setSensorDatenFromCCstatus(void)
  191. {
  192. sensor_t *s = esp_camera_sensor_get();
  193. if (s != NULL)
  194. {
  195. s->set_framesize(s, CCstatus.ImageFrameSize);
  196. s->set_gainceiling(s, CCstatus.ImageGainceiling); // Image gain (GAINCEILING_x2, x4, x8, x16, x32, x64 or x128)
  197. s->set_quality(s, CCstatus.ImageQuality); // 0 - 63
  198. s->set_brightness(s, CCstatus.ImageBrightness); // -2 to 2
  199. s->set_contrast(s, CCstatus.ImageContrast); // -2 to 2
  200. s->set_saturation(s, CCstatus.ImageSaturation); // -2 to 2
  201. // s->set_sharpness(s, CCstatus.ImageSharpness); // auto-sharpness is not officially supported, default to 0
  202. SetCamSharpness(CCstatus.ImageAutoSharpness, CCstatus.ImageSharpness);
  203. s->set_exposure_ctrl(s, CCstatus.ImageAec); // 0 = disable , 1 = enable
  204. s->set_ae_level(s, CCstatus.ImageAeLevel); // -2 to 2
  205. s->set_aec_value(s, CCstatus.ImageAecValue); // 0 to 1200
  206. s->set_aec2(s, CCstatus.ImageAec2); // 0 = disable , 1 = enable
  207. s->set_gain_ctrl(s, CCstatus.ImageAgc); // 0 = disable , 1 = enable
  208. s->set_agc_gain(s, CCstatus.ImageAgcGain); // 0 to 30
  209. s->set_bpc(s, CCstatus.ImageBpc); // 0 = disable , 1 = enable
  210. s->set_wpc(s, CCstatus.ImageWpc); // 0 = disable , 1 = enable
  211. s->set_raw_gma(s, CCstatus.ImageRawGma); // 0 = disable , 1 = enable
  212. s->set_lenc(s, CCstatus.ImageLenc); // 0 = disable , 1 = enable
  213. s->set_hmirror(s, CCstatus.ImageHmirror); // 0 = disable , 1 = enable
  214. s->set_vflip(s, CCstatus.ImageVflip); // 0 = disable , 1 = enable
  215. s->set_dcw(s, CCstatus.ImageDcw); // 0 = disable , 1 = enable
  216. s->set_wb_mode(s, CCstatus.ImageWbMode); // 0 to 4 - if awb_gain enabled (0 - Auto, 1 - Sunny, 2 - Cloudy, 3 - Office, 4 - Home)
  217. s->set_awb_gain(s, CCstatus.ImageAwbGain); // 0 = disable , 1 = enable
  218. s->set_whitebal(s, CCstatus.ImageAwb); // 0 = disable , 1 = enable
  219. // special_effect muß als Letztes gesetzt werden, sonst geht es nicht
  220. s->set_special_effect(s, CCstatus.ImageSpecialEffect); // 0 to 6 (0 - No Effect, 1 - Negative, 2 - Grayscale, 3 - Red Tint, 4 - Green Tint, 5 - Blue Tint, 6 - Sepia)
  221. TickType_t xDelay2 = 1000 / portTICK_PERIOD_MS;
  222. vTaskDelay(xDelay2);
  223. return ESP_OK;
  224. }
  225. else
  226. {
  227. return ESP_FAIL;
  228. }
  229. }
  230. esp_err_t CCamera::getSensorDatenToCCstatus(void)
  231. {
  232. sensor_t *s = esp_camera_sensor_get();
  233. if (s != NULL)
  234. {
  235. CCstatus.ImageFrameSize = (framesize_t)s->status.framesize;
  236. CCstatus.ImageGainceiling = (gainceiling_t)s->status.gainceiling;
  237. CCstatus.ImageQuality = s->status.quality;
  238. CCstatus.ImageBrightness = s->status.brightness;
  239. CCstatus.ImageContrast = s->status.contrast;
  240. CCstatus.ImageSaturation = s->status.saturation;
  241. // CCstatus.ImageSharpness = s->status.sharpness; // gibt -1 zurück, da es nicht unterstützt wird
  242. CCstatus.ImageWbMode = s->status.wb_mode;
  243. CCstatus.ImageAwb = s->status.awb;
  244. CCstatus.ImageAwbGain = s->status.awb_gain;
  245. CCstatus.ImageAec = s->status.aec;
  246. CCstatus.ImageAec2 = s->status.aec2;
  247. CCstatus.ImageAeLevel = s->status.ae_level;
  248. CCstatus.ImageAecValue = s->status.aec_value;
  249. CCstatus.ImageAgc = s->status.agc;
  250. CCstatus.ImageAgcGain = s->status.agc_gain;
  251. CCstatus.ImageBpc = s->status.bpc;
  252. CCstatus.ImageWpc = s->status.wpc;
  253. CCstatus.ImageRawGma = s->status.raw_gma;
  254. CCstatus.ImageLenc = s->status.lenc;
  255. CCstatus.ImageSpecialEffect = s->status.special_effect;
  256. CCstatus.ImageHmirror = s->status.hmirror;
  257. CCstatus.ImageVflip = s->status.vflip;
  258. CCstatus.ImageDcw = s->status.dcw;
  259. return ESP_OK;
  260. }
  261. else
  262. {
  263. return ESP_FAIL;
  264. }
  265. }
  266. void CCamera::SetZoomSize(bool zoomEnabled, int zoomOffsetX, int zoomOffsetY, int imageSize)
  267. {
  268. sensor_t *s = esp_camera_sensor_get();
  269. if (s != NULL)
  270. {
  271. if (zoomEnabled)
  272. {
  273. // ov2640_sensor_mode_t _mode = OV2640_MODE_UXGA; // 1600x1200
  274. // ov2640_sensor_mode_t _mode = OV2640_MODE_SVGA; // 800x600
  275. // ov2640_sensor_mode_t _mode = OV2640_MODE_CIF; // 400x296
  276. int _mode = 0;
  277. int _offsetx = zoomOffsetX;
  278. int _offsety = zoomOffsetY;
  279. int _imageSize_temp = 0;
  280. int _maxX = 0;
  281. int _maxY = 0;
  282. if (imageSize < 29)
  283. {
  284. _imageSize_temp = (29 - imageSize);
  285. }
  286. // This works only if the aspect ratio of 4:3 is preserved in the window size.
  287. // use values divisible by 8 without remainder
  288. int _imageWidth = CCstatus.ImageWidth + (_imageSize_temp * 4 * 8);
  289. int _imageHeight = CCstatus.ImageHeight + (_imageSize_temp * 3 * 8);
  290. _maxX = 1600 - _imageWidth;
  291. _maxY = 1200 - _imageHeight;
  292. if ((abs(_offsetx) * 2) > _maxX)
  293. {
  294. if (_offsetx > 0)
  295. {
  296. _offsetx = _maxX;
  297. }
  298. else
  299. {
  300. _offsetx = 0;
  301. }
  302. }
  303. else
  304. {
  305. if (_offsetx > 0)
  306. {
  307. // wenn der Wert von _offsetx nicht durch 8 teilbar ist,
  308. // werden die Farben sehr oft vertauscht(insbesondere Rot mit Blau)
  309. _offsetx = ((_maxX / 2) + _offsetx);
  310. }
  311. else
  312. {
  313. // wenn der Wert von _offsetx nicht durch 8 teilbar ist,
  314. // werden die Farben sehr oft vertauscht(insbesondere Rot mit Blau)
  315. _offsetx = ((_maxX / 2) + _offsetx);
  316. }
  317. }
  318. if ((abs(_offsety) * 2) > _maxY)
  319. {
  320. if (_offsety > 0)
  321. {
  322. _offsety = _maxY;
  323. }
  324. else
  325. {
  326. _offsety = 0;
  327. }
  328. }
  329. else
  330. {
  331. if (_offsety > 0)
  332. {
  333. // wenn der Wert von _offsety nicht durch 8 teilbar ist,
  334. // werden die Farben sehr oft vertauscht(insbesondere Rot mit Blau)
  335. _offsety = ((_maxY / 2) + _offsety);
  336. }
  337. else
  338. {
  339. // wenn der Wert von _offsety nicht durch 8 teilbar ist,
  340. // werden die Farben sehr oft vertauscht(insbesondere Rot mit Blau)
  341. _offsety = ((_maxY / 2) + _offsety);
  342. }
  343. }
  344. // _mode sets the sensor resolution (3 options available),
  345. // _offsetx and _offsety set the start of the ROI,
  346. // _imageWidth and _imageHeight set the size of the ROI,
  347. // CCstatus.ImageWidth and CCstatus.ImageHeight set the output window size.
  348. SetCamWindow(s, _mode, _offsetx, _offsety, _imageWidth, _imageHeight, CCstatus.ImageWidth, CCstatus.ImageHeight);
  349. }
  350. else
  351. {
  352. s->set_framesize(s, CCstatus.ImageFrameSize);
  353. }
  354. }
  355. }
  356. void CCamera::SetQualityZoomSize(int qual, framesize_t resol, bool zoomEnabled, int zoomOffsetX, int zoomOffsetY, int imageSize)
  357. {
  358. qual = min(63, max(8, qual)); // Limit quality from 8..63 (values lower than 8 tent to be unstable)
  359. SetImageWidthHeightFromResolution(resol);
  360. sensor_t *s = esp_camera_sensor_get();
  361. if (s != NULL)
  362. {
  363. s->set_quality(s, qual);
  364. SetZoomSize(zoomEnabled, zoomOffsetX, zoomOffsetY, imageSize);
  365. }
  366. else
  367. {
  368. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "SetQualityZoomSize, Failed to get Cam control structure");
  369. }
  370. }
  371. void CCamera::SetCamSharpness(bool _autoSharpnessEnabled, int _sharpnessLevel)
  372. {
  373. _sharpnessLevel = min(2, max(-2, _sharpnessLevel));
  374. sensor_t *s = esp_camera_sensor_get();
  375. if (s != NULL)
  376. {
  377. // post processing
  378. if (_autoSharpnessEnabled)
  379. {
  380. s->set_sharpness(s, 0);
  381. ov2640_enable_auto_sharpness(s);
  382. }
  383. else
  384. {
  385. ov2640_set_sharpness(s, _sharpnessLevel);
  386. }
  387. }
  388. else
  389. {
  390. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "SetCamSharpness, Failed to get Cam control structure");
  391. }
  392. }
  393. /*
  394. * resolution = 0 \\ OV2640_MODE_UXGA -> 1600 x 1200
  395. * resolution = 1 \\ OV2640_MODE_SVGA -> 800 x 600
  396. * resolution = 2 \\ OV2640_MODE_CIF -> 400 x 296
  397. * resolution = 3 \\ OV2640_MODE_MAX
  398. */
  399. void CCamera::SetCamWindow(sensor_t *s, int resolution, int xOffset, int yOffset, int xTotal, int yTotal, int xOutput, int yOutput)
  400. {
  401. // - (xOffset,yOffset) is the origin of the window in pixels and (xLength,yLength) is the size of the window in pixels.
  402. // - (xOffset,yOffset) ist der Ursprung des Fensters in Pixel und (xLength,yLength) ist die Größe des Fensters in Pixel.
  403. // - Be aware that changing the resolution will effectively overwrite these settings.
  404. // - Beachten Sie, dass eine Änderung der Auflösung diese Einstellungen effektiv überschreibt.
  405. // - This works only if the aspect ratio of 4:3 is preserved in the window size.
  406. // - Dies funktioniert nur, wenn das Seitenverhältnis von 4:3 in der Fenstergröße beibehalten wird.
  407. // - total_x and total_y defines the size on the sensor
  408. // - total_x und total_y definieren die Größe des Sensors
  409. // - width and height defines the resulting image(may be smaller than the size on the sensor)
  410. // - width und height definieren das resultierende Bild (kann kleiner sein als die Größe des Sensor)
  411. // - keep the aspect total_x : total_y == width : height
  412. // - Behalten Sie den Aspekt total_x : total_y == width : height bei
  413. // - use values divisible by 8 without remainder
  414. // - Verwenden Sie Werte, die ohne Rest durch 8 teilbar sind
  415. // - start with total_x = width and total_y = height, reduce both values by eg.32 pixels
  416. // - Beginnen Sie mit total_x = width und total_y = height und reduzieren Sie beide Werte um z.B.32 Pixel
  417. // - next try moving with offset_x or offset_y by 8 pixels
  418. // - Versuchen Sie als Nächstes, mit offset_x oder offset_y um 8 Pixel zu verschieben
  419. // set_res_raw(sensor_t *sensor, int startX, int startY, int endX, int endY, int offsetX, int offsetY, int totalX, int totalY, int outputX, int outputY, bool scale, bool binning)
  420. // set_window(sensor, (ov2640_sensor_mode_t)startX, offsetX, offsetY, totalX, totalY, outputX, outputY);
  421. // set_window(sensor, mode, offset_x, offset_y, max_x, max_y, w, h);
  422. int unused = 0;
  423. s->set_res_raw(s, resolution, unused, unused, unused, xOffset, yOffset, xTotal, yTotal, xOutput, yOutput, unused, unused);
  424. }
  425. static size_t jpg_encode_stream(void *arg, size_t index, const void *data, size_t len)
  426. {
  427. jpg_chunking_t *j = (jpg_chunking_t *)arg;
  428. if (!index)
  429. {
  430. j->len = 0;
  431. }
  432. if (httpd_resp_send_chunk(j->req, (const char *)data, len) != ESP_OK)
  433. {
  434. return 0;
  435. }
  436. j->len += len;
  437. return len;
  438. }
  439. esp_err_t CCamera::CaptureToBasisImage(CImageBasis *_Image, int delay)
  440. {
  441. #ifdef DEBUG_DETAIL_ON
  442. LogFile.WriteHeapInfo("CaptureToBasisImage - Start");
  443. #endif
  444. _Image->EmptyImage(); // Delete previous stored raw image -> black image
  445. LEDOnOff(true); // Status-LED on
  446. if (delay > 0)
  447. {
  448. LightOnOff(true); // Flash-LED on
  449. const TickType_t xDelay = delay / portTICK_PERIOD_MS;
  450. vTaskDelay(xDelay);
  451. }
  452. #ifdef DEBUG_DETAIL_ON
  453. LogFile.WriteHeapInfo("CaptureToBasisImage - After LightOn");
  454. #endif
  455. camera_fb_t *fb = esp_camera_fb_get();
  456. esp_camera_fb_return(fb);
  457. fb = esp_camera_fb_get();
  458. if (!fb)
  459. {
  460. LEDOnOff(false); // Status-LED off
  461. LightOnOff(false); // Flash-LED off
  462. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "is not working anymore (CaptureToBasisImage) - most probably caused "
  463. "by a hardware problem (instablility, ...). System will reboot.");
  464. doReboot();
  465. return ESP_FAIL;
  466. }
  467. if (CCstatus.DemoMode)
  468. {
  469. // Use images stored on SD-Card instead of camera image
  470. /* Replace Framebuffer with image from SD-Card */
  471. loadNextDemoImage(fb);
  472. }
  473. CImageBasis *_zwImage = new CImageBasis("zwImage");
  474. if (_zwImage)
  475. {
  476. _zwImage->LoadFromMemory(fb->buf, fb->len);
  477. }
  478. else
  479. {
  480. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToBasisImage: Can't allocate _zwImage");
  481. }
  482. esp_camera_fb_return(fb);
  483. #ifdef DEBUG_DETAIL_ON
  484. LogFile.WriteHeapInfo("CaptureToBasisImage - After fb_get");
  485. #endif
  486. LEDOnOff(false); // Status-LED off
  487. if (delay > 0)
  488. {
  489. LightOnOff(false); // Flash-LED off
  490. }
  491. // TickType_t xDelay = 1000 / portTICK_PERIOD_MS;
  492. // vTaskDelay( xDelay ); // wait for power to recover
  493. #ifdef DEBUG_DETAIL_ON
  494. LogFile.WriteHeapInfo("CaptureToBasisImage - After LoadFromMemory");
  495. #endif
  496. if (_zwImage == NULL)
  497. {
  498. return ESP_OK;
  499. }
  500. stbi_uc *p_target;
  501. stbi_uc *p_source;
  502. int channels = 3;
  503. int width = CCstatus.ImageWidth;
  504. int height = CCstatus.ImageHeight;
  505. #ifdef DEBUG_DETAIL_ON
  506. std::string _zw = "Targetimage: " + std::to_string((int)_Image->rgb_image) + " Size: " + std::to_string(_Image->width) + ", " + std::to_string(_Image->height);
  507. _zw = _zw + " _zwImage: " + std::to_string((int)_zwImage->rgb_image) + " Size: " + std::to_string(_zwImage->width) + ", " + std::to_string(_zwImage->height);
  508. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, _zw);
  509. #endif
  510. for (int x = 0; x < width; ++x)
  511. {
  512. for (int y = 0; y < height; ++y)
  513. {
  514. p_target = _Image->rgb_image + (channels * (y * width + x));
  515. p_source = _zwImage->rgb_image + (channels * (y * width + x));
  516. for (int c = 0; c < channels; c++)
  517. {
  518. p_target[c] = p_source[c];
  519. }
  520. }
  521. }
  522. delete _zwImage;
  523. #ifdef DEBUG_DETAIL_ON
  524. LogFile.WriteHeapInfo("CaptureToBasisImage - Done");
  525. #endif
  526. return ESP_OK;
  527. }
  528. esp_err_t CCamera::CaptureToFile(std::string nm, int delay)
  529. {
  530. string ftype;
  531. LEDOnOff(true); // Status-LED on
  532. if (delay > 0)
  533. {
  534. LightOnOff(true); // Flash-LED on
  535. const TickType_t xDelay = delay / portTICK_PERIOD_MS;
  536. vTaskDelay(xDelay);
  537. }
  538. camera_fb_t *fb = esp_camera_fb_get();
  539. esp_camera_fb_return(fb);
  540. fb = esp_camera_fb_get();
  541. if (!fb)
  542. {
  543. LEDOnOff(false); // Status-LED off
  544. LightOnOff(false); // Flash-LED off
  545. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToFile: Capture Failed. "
  546. "Check camera module and/or proper electrical connection");
  547. // doReboot();
  548. return ESP_FAIL;
  549. }
  550. LEDOnOff(false); // Status-LED off
  551. #ifdef DEBUG_DETAIL_ON
  552. ESP_LOGD(TAG, "w %d, h %d, size %d", fb->width, fb->height, fb->len);
  553. #endif
  554. nm = FormatFileName(nm);
  555. #ifdef DEBUG_DETAIL_ON
  556. ESP_LOGD(TAG, "Save Camera to: %s", nm.c_str());
  557. #endif
  558. ftype = toUpper(getFileType(nm));
  559. #ifdef DEBUG_DETAIL_ON
  560. ESP_LOGD(TAG, "Filetype: %s", ftype.c_str());
  561. #endif
  562. uint8_t *buf = NULL;
  563. size_t buf_len = 0;
  564. bool converted = false;
  565. if (ftype.compare("BMP") == 0)
  566. {
  567. frame2bmp(fb, &buf, &buf_len);
  568. converted = true;
  569. }
  570. if (ftype.compare("JPG") == 0)
  571. {
  572. if (fb->format != PIXFORMAT_JPEG)
  573. {
  574. bool jpeg_converted = frame2jpg(fb, CCstatus.ImageQuality, &buf, &buf_len);
  575. converted = true;
  576. if (!jpeg_converted)
  577. {
  578. ESP_LOGE(TAG, "JPEG compression failed");
  579. }
  580. }
  581. else
  582. {
  583. buf_len = fb->len;
  584. buf = fb->buf;
  585. }
  586. }
  587. FILE *fp = fopen(nm.c_str(), "wb");
  588. if (fp == NULL)
  589. {
  590. // If an error occurs during the file creation
  591. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToFile: Failed to open file " + nm);
  592. }
  593. else
  594. {
  595. fwrite(buf, sizeof(uint8_t), buf_len, fp);
  596. fclose(fp);
  597. }
  598. if (converted)
  599. {
  600. free(buf);
  601. }
  602. esp_camera_fb_return(fb);
  603. if (delay > 0)
  604. {
  605. LightOnOff(false); // Flash-LED off
  606. }
  607. return ESP_OK;
  608. }
  609. esp_err_t CCamera::CaptureToHTTP(httpd_req_t *req, int delay)
  610. {
  611. esp_err_t res = ESP_OK;
  612. size_t fb_len = 0;
  613. int64_t fr_start = esp_timer_get_time();
  614. LEDOnOff(true); // Status-LED on
  615. if (delay > 0)
  616. {
  617. LightOnOff(true); // Flash-LED on
  618. const TickType_t xDelay = delay / portTICK_PERIOD_MS;
  619. vTaskDelay(xDelay);
  620. }
  621. camera_fb_t *fb = esp_camera_fb_get();
  622. esp_camera_fb_return(fb);
  623. fb = esp_camera_fb_get();
  624. if (!fb)
  625. {
  626. LEDOnOff(false); // Status-LED off
  627. LightOnOff(false); // Flash-LED off
  628. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToFile: Capture Failed. "
  629. "Check camera module and/or proper electrical connection");
  630. httpd_resp_send_500(req);
  631. // doReboot();
  632. return ESP_FAIL;
  633. }
  634. LEDOnOff(false); // Status-LED off
  635. res = httpd_resp_set_type(req, "image/jpeg");
  636. if (res == ESP_OK)
  637. {
  638. res = httpd_resp_set_hdr(req, "Content-Disposition", "inline; filename=raw.jpg");
  639. }
  640. if (res == ESP_OK)
  641. {
  642. if (CCstatus.DemoMode)
  643. {
  644. // Use images stored on SD-Card instead of camera image
  645. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Using Demo image!");
  646. /* Replace Framebuffer with image from SD-Card */
  647. loadNextDemoImage(fb);
  648. res = httpd_resp_send(req, (const char *)fb->buf, fb->len);
  649. }
  650. else
  651. {
  652. if (fb->format == PIXFORMAT_JPEG)
  653. {
  654. fb_len = fb->len;
  655. res = httpd_resp_send(req, (const char *)fb->buf, fb->len);
  656. }
  657. else
  658. {
  659. jpg_chunking_t jchunk = {req, 0};
  660. res = frame2jpg_cb(fb, 80, jpg_encode_stream, &jchunk) ? ESP_OK : ESP_FAIL;
  661. httpd_resp_send_chunk(req, NULL, 0);
  662. fb_len = jchunk.len;
  663. }
  664. }
  665. }
  666. esp_camera_fb_return(fb);
  667. int64_t fr_end = esp_timer_get_time();
  668. ESP_LOGI(TAG, "JPG: %dKB %dms", (int)(fb_len / 1024), (int)((fr_end - fr_start) / 1000));
  669. if (delay > 0)
  670. {
  671. LightOnOff(false); // Flash-LED off
  672. }
  673. return res;
  674. }
  675. esp_err_t CCamera::CaptureToStream(httpd_req_t *req, bool FlashlightOn)
  676. {
  677. esp_err_t res = ESP_OK;
  678. size_t fb_len = 0;
  679. int64_t fr_start;
  680. char *part_buf[64];
  681. // wenn die Kameraeinstellungen durch Erstellen eines neuen Referenzbildes verändert wurden, müssen sie neu gesetzt werden
  682. if (CFstatus.changedCameraSettings)
  683. {
  684. Camera.setSensorDatenFromCCstatus(); // CCstatus >>> Kamera
  685. Camera.SetQualityZoomSize(CCstatus.ImageQuality, CCstatus.ImageFrameSize, CCstatus.ImageZoomEnabled, CCstatus.ImageZoomOffsetX, CCstatus.ImageZoomOffsetY, CCstatus.ImageZoomSize);
  686. CFstatus.changedCameraSettings = false;
  687. }
  688. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Live stream started");
  689. if (FlashlightOn)
  690. {
  691. LEDOnOff(true); // Status-LED on
  692. LightOnOff(true); // Flash-LED on
  693. }
  694. // httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); //stream is blocking web interface, only serving to local
  695. httpd_resp_set_type(req, _STREAM_CONTENT_TYPE);
  696. httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY));
  697. while (1)
  698. {
  699. fr_start = esp_timer_get_time();
  700. camera_fb_t *fb = esp_camera_fb_get();
  701. esp_camera_fb_return(fb);
  702. fb = esp_camera_fb_get();
  703. if (!fb)
  704. {
  705. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CaptureToStream: Camera framebuffer not available");
  706. break;
  707. }
  708. fb_len = fb->len;
  709. if (res == ESP_OK)
  710. {
  711. size_t hlen = snprintf((char *)part_buf, sizeof(part_buf), _STREAM_PART, fb_len);
  712. res = httpd_resp_send_chunk(req, (const char *)part_buf, hlen);
  713. }
  714. if (res == ESP_OK)
  715. {
  716. res = httpd_resp_send_chunk(req, (const char *)fb->buf, fb_len);
  717. }
  718. if (res == ESP_OK)
  719. {
  720. res = httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY));
  721. }
  722. esp_camera_fb_return(fb);
  723. int64_t fr_end = esp_timer_get_time();
  724. ESP_LOGD(TAG, "JPG: %dKB %dms", (int)(fb_len / 1024), (int)((fr_end - fr_start) / 1000));
  725. if (res != ESP_OK)
  726. {
  727. // Exit loop, e.g. also when closing the webpage
  728. break;
  729. }
  730. int64_t fr_delta_ms = (fr_end - fr_start) / 1000;
  731. if (CAM_LIVESTREAM_REFRESHRATE > fr_delta_ms)
  732. {
  733. const TickType_t xDelay = (CAM_LIVESTREAM_REFRESHRATE - fr_delta_ms) / portTICK_PERIOD_MS;
  734. ESP_LOGD(TAG, "Stream: sleep for: %ldms", (long)xDelay * 10);
  735. vTaskDelay(xDelay);
  736. }
  737. }
  738. LEDOnOff(false); // Status-LED off
  739. LightOnOff(false); // Flash-LED off
  740. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Live stream stopped");
  741. return res;
  742. }
  743. void CCamera::LightOnOff(bool status)
  744. {
  745. GpioHandler *gpioHandler = gpio_handler_get();
  746. if ((gpioHandler != NULL) && (gpioHandler->isEnabled()))
  747. {
  748. ESP_LOGD(TAG, "Use gpioHandler to trigger flashlight");
  749. gpioHandler->flashLightEnable(status);
  750. }
  751. else
  752. {
  753. #ifdef USE_PWM_LEDFLASH
  754. if (status)
  755. {
  756. ESP_LOGD(TAG, "Internal Flash-LED turn on with PWM %d", CCstatus.ImageLedIntensity);
  757. ESP_ERROR_CHECK(ledc_set_duty(LEDC_MODE, LEDC_CHANNEL, CCstatus.ImageLedIntensity));
  758. // Update duty to apply the new value
  759. ESP_ERROR_CHECK(ledc_update_duty(LEDC_MODE, LEDC_CHANNEL));
  760. }
  761. else
  762. {
  763. ESP_LOGD(TAG, "Internal Flash-LED turn off PWM");
  764. ESP_ERROR_CHECK(ledc_set_duty(LEDC_MODE, LEDC_CHANNEL, 0));
  765. ESP_ERROR_CHECK(ledc_update_duty(LEDC_MODE, LEDC_CHANNEL));
  766. }
  767. #else
  768. // Init the GPIO
  769. gpio_pad_select_gpio(FLASH_GPIO);
  770. // Set the GPIO as a push/pull output
  771. gpio_set_direction(FLASH_GPIO, GPIO_MODE_OUTPUT);
  772. if (status)
  773. {
  774. gpio_set_level(FLASH_GPIO, 1);
  775. }
  776. else
  777. {
  778. gpio_set_level(FLASH_GPIO, 0);
  779. }
  780. #endif
  781. }
  782. }
  783. void CCamera::LEDOnOff(bool status)
  784. {
  785. if (xHandle_task_StatusLED == NULL)
  786. {
  787. // Init the GPIO
  788. gpio_pad_select_gpio(BLINK_GPIO);
  789. /* Set the GPIO as a push/pull output */
  790. gpio_set_direction(BLINK_GPIO, GPIO_MODE_OUTPUT);
  791. if (!status)
  792. {
  793. gpio_set_level(BLINK_GPIO, 1);
  794. }
  795. else
  796. {
  797. gpio_set_level(BLINK_GPIO, 0);
  798. }
  799. }
  800. }
  801. void CCamera::SetImageWidthHeightFromResolution(framesize_t resol)
  802. {
  803. if (resol == FRAMESIZE_QVGA)
  804. {
  805. CCstatus.ImageHeight = 240;
  806. CCstatus.ImageWidth = 320;
  807. }
  808. else if (resol == FRAMESIZE_VGA)
  809. {
  810. CCstatus.ImageHeight = 480;
  811. CCstatus.ImageWidth = 640;
  812. }
  813. else if (resol == FRAMESIZE_SVGA)
  814. {
  815. CCstatus.ImageHeight = 600;
  816. CCstatus.ImageWidth = 800;
  817. }
  818. else if (resol == FRAMESIZE_XGA)
  819. {
  820. CCstatus.ImageHeight = 768;
  821. CCstatus.ImageWidth = 1024;
  822. }
  823. else if (resol == FRAMESIZE_HD)
  824. {
  825. CCstatus.ImageHeight = 720;
  826. CCstatus.ImageWidth = 1280;
  827. }
  828. else if (resol == FRAMESIZE_SXGA)
  829. {
  830. CCstatus.ImageHeight = 1024;
  831. CCstatus.ImageWidth = 1280;
  832. }
  833. else if (resol == FRAMESIZE_UXGA)
  834. {
  835. CCstatus.ImageHeight = 1200;
  836. CCstatus.ImageWidth = 1600;
  837. }
  838. }
  839. framesize_t CCamera::TextToFramesize(const char *_size)
  840. {
  841. if (strcmp(_size, "QVGA") == 0)
  842. {
  843. return FRAMESIZE_QVGA; // 320x240
  844. }
  845. else if (strcmp(_size, "VGA") == 0)
  846. {
  847. return FRAMESIZE_VGA; // 640x480
  848. }
  849. else if (strcmp(_size, "SVGA") == 0)
  850. {
  851. return FRAMESIZE_SVGA; // 800x600
  852. }
  853. else if (strcmp(_size, "XGA") == 0)
  854. {
  855. return FRAMESIZE_XGA; // 1024x768
  856. }
  857. else if (strcmp(_size, "SXGA") == 0)
  858. {
  859. return FRAMESIZE_SXGA; // 1280x1024
  860. }
  861. else if (strcmp(_size, "UXGA") == 0)
  862. {
  863. return FRAMESIZE_UXGA; // 1600x1200
  864. }
  865. return CCstatus.ImageFrameSize;
  866. }
  867. std::vector<std::string> demoFiles;
  868. void CCamera::useDemoMode(void)
  869. {
  870. char line[50];
  871. FILE *fd = fopen("/sdcard/demo/files.txt", "r");
  872. if (!fd)
  873. {
  874. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can not start Demo mode, the folder '/sdcard/demo/' does not contain the needed files!");
  875. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "See Details on https://jomjol.github.io/AI-on-the-edge-device-docs/Demo-Mode!");
  876. return;
  877. }
  878. demoImage = (uint8_t *)malloc(DEMO_IMAGE_SIZE);
  879. if (demoImage == NULL)
  880. {
  881. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to acquire required memory for demo image!");
  882. return;
  883. }
  884. while (fgets(line, sizeof(line), fd) != NULL)
  885. {
  886. line[strlen(line) - 1] = '\0';
  887. demoFiles.push_back(line);
  888. }
  889. fclose(fd);
  890. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Using Demo mode (" + std::to_string(demoFiles.size()) + " files) instead of real camera image!");
  891. for (auto file : demoFiles)
  892. {
  893. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, file);
  894. }
  895. CCstatus.DemoMode = true;
  896. }
  897. bool CCamera::loadNextDemoImage(camera_fb_t *fb)
  898. {
  899. char filename[50];
  900. int readBytes;
  901. long fileSize;
  902. snprintf(filename, sizeof(filename), "/sdcard/demo/%s", demoFiles[getCountFlowRounds() % demoFiles.size()].c_str());
  903. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Using " + std::string(filename) + " as demo image");
  904. /* Inject saved image */
  905. FILE *fp = fopen(filename, "rb");
  906. if (!fp)
  907. {
  908. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to read file: " + std::string(filename) + "!");
  909. return false;
  910. }
  911. fileSize = GetFileSize(filename);
  912. if (fileSize > DEMO_IMAGE_SIZE)
  913. {
  914. char buf[100];
  915. snprintf(buf, sizeof(buf), "Demo Image (%d bytes) is larger than provided buffer (%d bytes)!", (int)fileSize, DEMO_IMAGE_SIZE);
  916. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, std::string(buf));
  917. return false;
  918. }
  919. readBytes = fread(demoImage, 1, DEMO_IMAGE_SIZE, fp);
  920. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "read " + std::to_string(readBytes) + " bytes");
  921. fclose(fp);
  922. fb->buf = demoImage; // Update pointer
  923. fb->len = readBytes;
  924. // ToDo do we also need to set height, width, format and timestamp?
  925. return true;
  926. }
  927. long CCamera::GetFileSize(std::string filename)
  928. {
  929. struct stat stat_buf;
  930. long rc = stat(filename.c_str(), &stat_buf);
  931. return rc == 0 ? stat_buf.st_size : -1;
  932. }