Fix crashes, races and SD/WiFi issues; per-day timelapse folders

Bug fixes against v1.1.2, tested on Freenove ESP32-S3-WROOM (OV3660),
arduino-esp32 3.3.11. Details in FIXES_SUMMARY.md.

Crashes and hangs
- Stack overflow in CheckMicroSdCard (#145); stacks sized from measured
  high-water marks, never below master; per-task stack report in telemetry
- NULL deref in /saved-photo.jpg; NULL guards on sensor and EXIF allocations
- OTA version check ran inside the async web handler (boot loop); now
  deferred to the system task
- udp_new_ip_type assert: SNTP stopped after sync, OTA check waits for NTP
- Divide-by-zero on SD card removal
- Busy-wait response loops (PrusaConnect, OTA) starved IDLE0 -> task WDT
- setTimeout() takes seconds: 1000 meant ~16 min

Camera
- Frame buffer returned multiple times per stream teardown
- Reinit frees buffers under the frame-buffer lock
- Capture failure skipped the reinit recovery and left the flash on
- Retry loop leaked a driver buffer per short frame
- Two semaphore leaks in CaptureStream(); stream failure now detectable
- OV3660 lost settings written right after init

Concurrency
- Recursive mutexes for SD card, log rotation, EEPROM and WiFi state
- Task WDT subscribe race: each task subscribes itself
- TWDT already initialised by the core: reconfigure only

Other
- Freenove: XCLK drive strength lowered (harmonics desensed 2.4 GHz WiFi),
  SD at 20 MHz (esp-idf#8521), DHT11 enabled on GPIO47
- Snapshots sent as image/jpeg (image/jpg was not shown in Prusa Connect)
- Second WiFi credential save failed ("sta is connecting")
- isCardCorrupted() misread an empty card as missing
- Log level checked before taking the log lock
- Timelapse: one folder per day, /timelapse/YYYY-MM-DD/YYYY-MM-DD_HH-MM-SS.jpg,
  skipped until NTP sync (FAT directory scans grow with file count)
- Web server started after all subsystems
- README: core and library versions
pull/147/head
Robert Pouliot 2026-10-11 22:01:40 -04:00
parent db0112e9c2
commit bcd9a7279c
19 changed files with 475 additions and 111 deletions

View File

@ -4,16 +4,16 @@
It's neccesary install support for ESP32 board to the arduino IDE. In the board manager we need add next link
https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json
Then we can install "ESP32 by Espressif Systems" board in the board manager.
ESP32 lib version: 3.0.2 (ESP-IDF v5.1.4) by Espressif Systems
ESP32 lib version: 3.3.11 (ESP-IDF v5.5.5) by Espressif Systems
This project uses other libraries. It is necessary to install them in the arduino IDE.
- Library - License - Version - Link
- ESPAsyncWebServer - LGPL 3.0 - 3.4.5 - https://github.com/mathieucarbou/ESPAsyncWebServer
- AsyncTCP - LGPL 3.0 - 3.3.1 - https://github.com/mathieucarbou/AsyncTCP
- ArduinoJson - MIT - 7.3.0 - https://github.com/bblanchon/ArduinoJson
- ESPAsyncWebServer - LGPL 3.0 - 3.12.1 - https://github.com/ESP32Async/ESPAsyncWebServer
- AsyncTCP - LGPL 3.0 - 3.5.0 - https://github.com/ESP32Async/AsyncTCP
- ArduinoJson - MIT - 7.4.3 - https://github.com/bblanchon/ArduinoJson
- ArduinoUniqueID - MIT - 1.3.0 - https://github.com/ricaun/ArduinoUniqueID
- arduino-esp32 - LGPL 2.1 - 3.1.0 - https://github.com/espressif/arduino-esp32
- DHTnew - MIT - 0.5.2 - https://github.com/RobTillaart/DHTNew
- DHTnew - MIT - 0.5.5 - https://github.com/RobTillaart/DHTNew
Arduino IDE configuration for the MCU are stored in the module_XXX.h file.
@ -90,9 +90,6 @@ void setup() {
SystemCamera.CapturePhoto();
SystemCamera.CaptureReturnFrameBuffer();
/* init WEB server */
Server_InitWebServer();
/* init class for communication with PrusaConnect */
Connect.Init();
@ -106,34 +103,30 @@ void setup() {
twdt_config.idle_core_mask = (1 << portNUM_PROCESSORS) - 1, /* Bitmask of all cores */
twdt_config.trigger_panic = true;
esp_task_wdt_init(&twdt_config); /* enable panic so ESP32 restarts */
/* TWDT already initialised by the core: reconfigure only */
esp_task_wdt_reconfigure(&twdt_config);
ESP_ERROR_CHECK(esp_task_wdt_add(NULL)); /* add current thread to WDT watch */
esp_task_wdt_reset(); /* reset wdg */
/* init tasks */
/* init tasks. Each task subscribes itself to the watchdog: adding here raced its first reset */
/* stacks: measured high-water mark + >=512 B, 512 B multiples; overflow corrupts SDMMC state (#145) */
SystemLog.AddEvent(LogLevel_Info, F("Start tasks"));
xTaskCreatePinnedToCore(System_TaskMain, "SystemNtpOtaUpdate", 5200, NULL, 1, &Task_SystemMain, 0); /*function, description, stack size, parameters, priority, task handle, core*/
ESP_ERROR_CHECK(esp_task_wdt_add(Task_SystemMain));
xTaskCreatePinnedToCore(System_TaskCaptureAndSendPhoto, "CaptureAndSendPhoto", 4400, NULL, 2, &Task_CapturePhotoAndSend, 0); /*function, description, stack size, parameters, priority, task handle, core*/
ESP_ERROR_CHECK(esp_task_wdt_add(Task_CapturePhotoAndSend));
xTaskCreatePinnedToCore(System_TaskWifiManagement, "WiFiManagement", 2700, NULL, 3, &Task_WiFiManagement, 0); /*function, description, stack size, parameters, priority, task handle, core*/
ESP_ERROR_CHECK(esp_task_wdt_add(Task_WiFiManagement));
xTaskCreatePinnedToCore(System_TaskMain, "SystemNtpOtaUpdate", 5632, NULL, 1, &Task_SystemMain, 0); /*function, description, stack size, parameters, priority, task handle, core*/
xTaskCreatePinnedToCore(System_TaskCaptureAndSendPhoto, "CaptureAndSendPhoto", 5120, NULL, 2, &Task_CapturePhotoAndSend, 0); /*function, description, stack size, parameters, priority, task handle, core*/
xTaskCreatePinnedToCore(System_TaskWifiManagement, "WiFiManagement", 3072, NULL, 3, &Task_WiFiManagement, 0); /*function, description, stack size, parameters, priority, task handle, core*/
#if (true == ENABLE_SD_CARD)
xTaskCreatePinnedToCore(System_TaskSdCardCheck, "CheckMicroSdCard", 3000, NULL, 4, &Task_SdCardCheck, 0); /*function, description, stack size, parameters, priority, task handle, core*/
ESP_ERROR_CHECK(esp_task_wdt_add(Task_SdCardCheck));
xTaskCreatePinnedToCore(System_TaskSdCardCheck, "CheckMicroSdCard", 5120, NULL, 4, &Task_SdCardCheck, 0); /*function, description, stack size, parameters, priority, task handle, core*/
#endif
xTaskCreatePinnedToCore(System_TaskSerialCfg, "CheckSerialConfiguration", 2300, NULL, 5, &Task_SerialCfg, 0); /*function, description, stack size, parameters, priority, task handle, core*/
ESP_ERROR_CHECK(esp_task_wdt_add(Task_SerialCfg));
xTaskCreatePinnedToCore(System_TaskSystemTelemetry, "PrintSystemTelemetry", 2200, NULL, 6, &Task_SystemTelemetry, 0); /*function, description, stack size, parameters, priority, task handle, core*/
ESP_ERROR_CHECK(esp_task_wdt_add(Task_SystemTelemetry));
xTaskCreatePinnedToCore(System_TaskSysLed, "SystemLed", 2000, NULL, 7, &Task_SysLed, 0); /*function, description, stack size, parameters, priority, task handle, core*/
ESP_ERROR_CHECK(esp_task_wdt_add(Task_SysLed));
xTaskCreatePinnedToCore(System_TaskWiFiWatchdog, "WiFiWatchdog", 2200, NULL, 8, &Task_WiFiWatchdog, 0); /*function, description, stack size, parameters, priority, task handle, core*/
ESP_ERROR_CHECK(esp_task_wdt_add(Task_WiFiWatchdog));
xTaskCreatePinnedToCore(System_TaskSerialCfg, "CheckSerialConfiguration", 3584, NULL, 5, &Task_SerialCfg, 0); /*function, description, stack size, parameters, priority, task handle, core*/
xTaskCreatePinnedToCore(System_TaskSystemTelemetry, "PrintSystemTelemetry", 2560, NULL, 6, &Task_SystemTelemetry, 0); /*function, description, stack size, parameters, priority, task handle, core*/
xTaskCreatePinnedToCore(System_TaskSysLed, "SystemLed", 2560, NULL, 7, &Task_SysLed, 0); /*function, description, stack size, parameters, priority, task handle, core*/
xTaskCreatePinnedToCore(System_TaskWiFiWatchdog, "WiFiWatchdog", 3072, NULL, 8, &Task_WiFiWatchdog, 0); /*function, description, stack size, parameters, priority, task handle, core*/
//xTaskCreatePinnedToCore(System_TaskSdCardRemove, "SdCardRemove", 3000, NULL, 9, &Task_SdCardFileRemove, 0); /*function, description, stack size, parameters, priority, task handle, core*/
//esp_task_wdt_add(Task_SdCardFileRemove);
/* last: requests arrive as soon as the server starts */
Server_InitWebServer();
SystemLog.AddEvent(LogLevel_Info, F("MCU configuration done"));
}

View File

@ -46,21 +46,30 @@ void Server_InitWebServer() {
}
SystemCamera.SetPhotoSending(true);
SystemLog.AddEvent(LogLevel_Verbose, "Photo size: " + String(SystemCamera.GetPhotoFb()->len) + " bytes");
/* validate the buffer itself: the capture-success flag outlives it */
camera_fb_t *fb = SystemCamera.GetPhotoFb();
if ((NULL == fb) || (NULL == fb->buf) || (0 == fb->len)) {
SystemLog.AddEvent(LogLevel_Warning, F("Photo buffer not available!"));
SystemCamera.SetPhotoSending(false);
request->send(404, "text/plain", "Photo not found!");
return;
}
SystemLog.AddEvent(LogLevel_Verbose, "Photo size: " + String(fb->len) + " bytes");
if (SystemCamera.GetPhotoExifData()->header != NULL) {
/* send photo with exif data */
SystemLog.AddEvent(LogLevel_Verbose, F("Send photo with EXIF data"));
size_t total_len = SystemCamera.GetPhotoExifData()->len + SystemCamera.GetPhotoFb()->len - SystemCamera.GetPhotoExifData()->offset;
auto response = request->beginChunkedResponse("image/jpg", [total_len](uint8_t *buffer, size_t maxLen, size_t index) -> size_t {
size_t total_len = SystemCamera.GetPhotoExifData()->len + fb->len - SystemCamera.GetPhotoExifData()->offset;
auto response = request->beginChunkedResponse("image/jpeg", [total_len, fb](uint8_t *buffer, size_t maxLen, size_t index) -> size_t {
size_t len = 0;
if (index < SystemCamera.GetPhotoExifData()->len) {
len = min(maxLen, SystemCamera.GetPhotoExifData()->len - index);
memcpy(buffer, SystemCamera.GetPhotoExifData()->header + index, len);
} else {
size_t offset = index - SystemCamera.GetPhotoExifData()->len + SystemCamera.GetPhotoExifData()->offset;
len = min(maxLen, SystemCamera.GetPhotoFb()->len - offset);
memcpy(buffer, SystemCamera.GetPhotoFb()->buf + offset, len);
len = min(maxLen, fb->len - offset);
memcpy(buffer, fb->buf + offset, len);
}
return len;
});
@ -70,7 +79,7 @@ void Server_InitWebServer() {
} else {
/* send photo without exif data */
SystemLog.AddEvent(LogLevel_Verbose, F("Send photo without EXIF data"));
request->send(200, "image/jpg", SystemCamera.GetPhotoFb()->buf, SystemCamera.GetPhotoFb()->len);
request->send(200, "image/jpeg", fb->buf, fb->len);
}
SystemCamera.SetPhotoSending(false);
@ -867,6 +876,9 @@ void Server_InitWebServer_Sets() {
/* save ssid and password */
SystemWifiMngt.SetStaCredentials(TmpSsid, TmpPassword);
/* disconnect first, else begin() fails: "sta is connecting, cannot set config" */
WiFi.disconnect();
delay(100);
SystemWifiMngt.WiFiStaConnect();
} else {
@ -1093,7 +1105,8 @@ void Server_InitWebServer_Update() {
if (Server_CheckBasicAuth(request) == false)
return;
System_CheckNewVersion();
/* flag only: the check blocks for seconds and must not run on the AsyncTCP task */
FirmwareUpdate.RequestNewVersionCheck = true;
request->send(200, F("text/html"), FirmwareUpdate.CheckNewVersionFwStatus.c_str());
});
}

View File

@ -242,12 +242,16 @@ size_t AsyncJpegStreamResponse::_content(uint8_t *buffer, size_t maxLen, size_t
/* get frame */
_frame.index = 0;
_dframe.buf = NULL;
_dframe.len = 0;
camera->CaptureStream(&_dframe);
_frame.fb = &_dframe;
if (_frame.fb == NULL) {
/* _frame.fb is a member address, never NULL: test the buffer. TRY_AGAIN keeps the stream open */
if ((NULL == _frame.fb->buf) || (0 == _frame.fb->len)) {
log->AddEvent(LogLevel_Error, F("Stream capture frame failed"));
return 0;
_frame.fb = NULL;
return RESPONSE_TRY_AGAIN;
}
/* send boundary */

View File

@ -12,6 +12,7 @@
@bug: no know bug
*/
#include "camera.h"
#include <driver/gpio.h>
Camera SystemCamera(&SystemConfig, &SystemLog, FLASH_GPIO_NUM);
@ -72,8 +73,14 @@ void Camera::Init() {
#endif
InitCameraModule();
/* OV3660 loses settings written right after init: apply, settle, apply again */
delay(100);
ApplyCameraCfg();
GetCameraModel();
delay(250);
ApplyCameraCfg();
}
/**
@ -148,6 +155,13 @@ void Camera::InitCameraModule() {
log->AddEvent(LogLevel_Warning, F("Reset ESP32-cam!"));
ESP.restart();
}
#ifdef CAMERA_XCLK_DRIVE_CAP
/* after init: the driver configures the pin */
if (ESP_OK != gpio_set_drive_capability((gpio_num_t)XCLK_GPIO_NUM, CAMERA_XCLK_DRIVE_CAP)) {
log->AddEvent(LogLevel_Warning, F("Camera XCLK drive strength set failed"));
}
#endif
}
/**
@ -300,6 +314,11 @@ void Camera::ApplyCameraCfg() {
/* sensor configuration */
sensor = esp_camera_sensor_get();
/* NULL when no sensor is initialised; the calls below would fault as LoadProhibited */
if (NULL == sensor) {
log->AddEvent(LogLevel_Error, F("Camera sensor not available. Skip applying CFG"));
return;
}
sensor->set_brightness(sensor, brightness); // -2 to 2
sensor->set_contrast(sensor, contrast); // -2 to 2
sensor->set_saturation(sensor, saturation); // -2 to 2
@ -330,13 +349,29 @@ void Camera::ApplyCameraCfg() {
@return none
*/
void Camera::ReinitCameraModule() {
/* held for the whole teardown: deinit frees buffers another task may be using.
Must not be called with the semaphore already held (not recursive). */
xSemaphoreTake(frameBufferSemaphore, portMAX_DELAY);
esp_err_t err = esp_camera_deinit();
if (err != ESP_OK) {
log->AddEvent(LogLevel_Warning, F("Camera error deinit camera module. Error: "), String(err, HEX));
}
/* deinit freed these */
FrameBuffer = NULL;
PhotoExifData.header = NULL;
delay(100);
InitCameraModule();
/* same OV3660 behaviour as Camera::Init(): settle, then apply twice */
delay(100);
ApplyCameraCfg();
delay(250);
ApplyCameraCfg();
xSemaphoreGive(frameBufferSemaphore);
}
/**
@ -396,21 +431,25 @@ void Camera::CapturePhoto() {
if (FrameBuffer) {
esp_camera_fb_return(FrameBuffer);
/* clear, else returned twice */
FrameBuffer = NULL;
}
/* Capturing a training photo. Without this sequence, the camera will not obtain the current photo but photo from the previous cycle. */
FrameBuffer = esp_camera_fb_get();
if (FrameBuffer) {
esp_camera_fb_return(FrameBuffer);
FrameBuffer = NULL;
log->AddEvent(LogLevel_Verbose, F("Camera capture training photo"));
} else {
esp_camera_fb_return(FrameBuffer);
/* no fb_return() here: FrameBuffer is NULL in this branch */
log->AddEvent(LogLevel_Error, F("Camera capture failed training photo"));
//ReinitCameraModule();
}
int attempts = 0;
const int maxAttempts = 5;
bool PhotoValid = false;
PhotoExifData.header = NULL;
do {
log->AddEvent(LogLevel_Info, F("Taking photo..."));
@ -419,7 +458,19 @@ void Camera::CapturePhoto() {
if (!FrameBuffer) {
CameraCaptureFailedCounter++;
log->AddEvent(LogLevel_Error, F("Camera capture failed! photo. Attempt: "), String(CameraCaptureFailedCounter));
/* flash off on this exit too */
if (true == CameraFlashEnable) {
SetFlashStatus(false);
}
xSemaphoreGive(frameBufferSemaphore); // Release semaphore before returning
/* run the reinit check before returning */
if (CameraCaptureFailedCounter > CAMERA_MAX_FAIL_CAPTURE) {
log->AddEvent(LogLevel_Error, F("Camera capture failed! photo max attempts"));
CameraCaptureFailedCounter = 0;
ReinitCameraModule();
}
return;
}
@ -450,11 +501,20 @@ void Camera::CapturePhoto() {
}
attempts++;
PhotoValid = (FrameBuffer->len > 100);
if (false == PhotoValid) {
/* return the short frame before retrying, else each retry leaks a driver buffer */
esp_camera_fb_return(FrameBuffer);
FrameBuffer = NULL;
PhotoExifData.header = NULL;
if (attempts >= maxAttempts) {
log->AddEvent(LogLevel_Error, F("Failed to capture a valid photo after max attempts"));
break;
}
} while (!(FrameBuffer->len > 100));
}
} while (false == PhotoValid);
/* Disable flash */
if (true == CameraFlashEnable) {
@ -486,11 +546,23 @@ void Camera::CapturePhoto() {
void Camera::CaptureStream(camera_fb_t* i_buf) {
if (xSemaphoreTake(frameBufferSemaphore, portMAX_DELAY)) {
do {
/* return any frame still held from a retry, else it leaks */
if (NULL != FrameBuffer) {
esp_camera_fb_return(FrameBuffer);
FrameBuffer = NULL;
}
/* capture final photo */
FrameBuffer = esp_camera_fb_get();
if (!FrameBuffer) {
log->AddEvent(LogLevel_Error, F("Camera capture failed! stream"));
i_buf = NULL;
/* signal failure via the caller's struct; i_buf = NULL only changes the local copy */
if (NULL != i_buf) {
i_buf->buf = NULL;
i_buf->len = 0;
}
/* must release: returning while holding this leaks it permanently */
xSemaphoreGive(frameBufferSemaphore);
return;
}
@ -521,6 +593,20 @@ void Camera::CaptureStream(camera_fb_t* i_buf) {
/* Allocate memory for the duplicate frame structure */
FrameBufferExif = (camera_fb_t*)heap_caps_malloc(sizeof(camera_fb_t), MALLOC_CAP_SPIRAM);
/* must be checked before ->buf is assigned below: NULL deref on PSRAM exhaustion */
if (NULL == FrameBufferExif) {
log->AddEvent(LogLevel_Error, F("Failed to allocate memory for EXIF frame struct"));
if (NULL != i_buf) {
i_buf->buf = NULL;
i_buf->len = 0;
}
esp_camera_fb_return(FrameBuffer);
FrameBuffer = NULL;
xSemaphoreGive(frameBufferSemaphore);
return;
}
memset(FrameBufferExif, 0, sizeof(camera_fb_t));
/* Calculate the total size of the buffer */
size_t totalSize = PhotoExifData.len + FrameBuffer->len - PhotoExifData.offset;
@ -528,6 +614,14 @@ void Camera::CaptureStream(camera_fb_t* i_buf) {
FrameBufferExif->buf = (uint8_t*)heap_caps_malloc(totalSize, MALLOC_CAP_SPIRAM);
if (FrameBufferExif->buf == NULL) {
log->AddEvent(LogLevel_Error, F("Failed to allocate memory for EXIF buffer"));
/* release the semaphore and the frame, and signal failure via i_buf */
if (NULL != i_buf) {
i_buf->buf = NULL;
i_buf->len = 0;
}
esp_camera_fb_return(FrameBuffer);
FrameBuffer = NULL;
xSemaphoreGive(frameBufferSemaphore);
return;
}
@ -572,6 +666,11 @@ void Camera::CaptureStream(camera_fb_t* i_buf) {
/* Allocate memory for the duplicate frame structure */
FrameBufferDuplicate = (camera_fb_t*)heap_caps_malloc(sizeof(camera_fb_t), MALLOC_CAP_SPIRAM);
/* check before the memcpy below writes through it */
if (NULL == FrameBufferDuplicate) {
Serial.println("Failed to allocate memory for the duplicate frame struct");
} else {
/* Copy the metadata */
if (true == ExifStatus) {
memcpy(FrameBufferDuplicate, FrameBufferExif, sizeof(camera_fb_t));
@ -588,8 +687,9 @@ void Camera::CaptureStream(camera_fb_t* i_buf) {
/* Check if memory allocation was successful */
if (!FrameBufferDuplicate->buf) {
/* Handle error */
/* clear after freeing, else the next pass double-frees */
free(FrameBufferDuplicate);
FrameBufferDuplicate = NULL;
Serial.println("Failed to allocate memory for the duplicate frame buffer");
} else {
/* Copy the image data */
@ -600,6 +700,7 @@ void Camera::CaptureStream(camera_fb_t* i_buf) {
memcpy(FrameBufferDuplicate->buf, FrameBuffer->buf, FrameBuffer->len);
}
}
} /* end NULL == FrameBufferDuplicate guard */
}
xSemaphoreGive(frameBufferSemaphore);
@ -612,7 +713,13 @@ void Camera::CaptureStream(camera_fb_t* i_buf) {
@return none
*/
void Camera::CaptureReturnFrameBuffer() {
/* return at most once: stream teardown called this two or three times */
xSemaphoreTake(frameBufferSemaphore, portMAX_DELAY);
if (NULL != FrameBuffer) {
esp_camera_fb_return(FrameBuffer);
FrameBuffer = NULL;
}
xSemaphoreGive(frameBufferSemaphore);
}
/**
@ -621,10 +728,15 @@ void Camera::CaptureReturnFrameBuffer() {
@return none
*/
void Camera::SetStreamStatus(bool i_status) {
xSemaphoreTake(frameBufferSemaphore, portMAX_DELAY);
StreamOnOff = i_status;
if (FrameBuffer) {
/* same double-release reason as CaptureReturnFrameBuffer() */
if (NULL != FrameBuffer) {
esp_camera_fb_return(FrameBuffer);
FrameBuffer = NULL;
}
xSemaphoreGive(frameBufferSemaphore);
log->AddEvent(LogLevel_Info, F("Camera video stream: "), String(StreamOnOff));
}

View File

@ -73,6 +73,8 @@ private:
String Photo; ///< photo in string format
bool StreamOnOff; ///< stream on/off
bool StreamSendingPhoto; ///< sending photo to Prusa Connect during stream
/* guards FrameBuffer. NOT recursive: never take it twice on one task (see ReinitCameraModule()).
Lock order frameBufferSemaphore -> LogMutex -> sdCardMutex. */
SemaphoreHandle_t frameBufferSemaphore; ///< semaphore for frame buffer
float StreamAverageFps; ///< stream average fps
uint16_t StreamAverageSize; ///< stream average size

View File

@ -21,6 +21,9 @@ Configuration SystemConfig(&SystemLog);
Configuration::Configuration(Logs* i_log) {
Log = i_log;
WiFiMacAddress = WiFi.macAddress();
/* commit() rewrites a whole flash sector: serialise all EEPROM access.
Lock order EepromMutex -> LogMutex -> sdCardMutex. */
EepromMutex = xSemaphoreCreateRecursiveMutex();
}
/**
@ -269,6 +272,7 @@ void Configuration::GetFingerprint() {
@return none
*/
void Configuration::SaveUint8(uint16_t address, uint8_t data) {
xSemaphoreTakeRecursive(EepromMutex, portMAX_DELAY);
EEPROM.write(address, data);
if (EEPROM.commit()) {
@ -277,6 +281,7 @@ void Configuration::SaveUint8(uint16_t address, uint8_t data) {
Log->AddEvent(LogLevel_Error, F("Failed to write uint8_t"));
EEPROM.commit(); // try again
}
xSemaphoreGiveRecursive(EepromMutex);
}
/**
@info Function for save int8_t to EEPROM
@ -285,6 +290,7 @@ void Configuration::SaveUint8(uint16_t address, uint8_t data) {
@return none
*/
void Configuration::SaveInt8(uint16_t address, int8_t data) {
xSemaphoreTakeRecursive(EepromMutex, portMAX_DELAY);
EEPROM.write(address, data);
if (EEPROM.commit()) {
@ -293,6 +299,7 @@ void Configuration::SaveInt8(uint16_t address, int8_t data) {
Log->AddEvent(LogLevel_Error, F("Failed to write int8_t"));
EEPROM.commit(); // try again
}
xSemaphoreGiveRecursive(EepromMutex);
}
/**
@info Function for save bool to EEPROM
@ -301,6 +308,7 @@ void Configuration::SaveInt8(uint16_t address, int8_t data) {
@return none
*/
void Configuration::SaveBool(uint16_t address, bool data) {
xSemaphoreTakeRecursive(EepromMutex, portMAX_DELAY);
EEPROM.write(address, data);
if (EEPROM.commit()) {
@ -309,6 +317,7 @@ void Configuration::SaveBool(uint16_t address, bool data) {
Log->AddEvent(LogLevel_Error, F("Failed to write bool"));
EEPROM.commit(); // try again
}
xSemaphoreGiveRecursive(EepromMutex);
}
/**
@info Function for save uint16_t to EEPROM
@ -320,6 +329,7 @@ void Configuration::SaveUint16(uint16_t address, uint16_t data) {
uint8_t highByte = highByte(data);
uint8_t lowByte = lowByte(data);
xSemaphoreTakeRecursive(EepromMutex, portMAX_DELAY);
EEPROM.write(address, highByte);
EEPROM.write(address + 1, lowByte);
@ -329,6 +339,7 @@ void Configuration::SaveUint16(uint16_t address, uint16_t data) {
Log->AddEvent(LogLevel_Error, F("Failed to write uint16_t"));
EEPROM.commit(); // try again
}
xSemaphoreGiveRecursive(EepromMutex);
}
/**
@ -339,6 +350,7 @@ void Configuration::SaveUint16(uint16_t address, uint16_t data) {
@return none
*/
void Configuration::SaveString(uint16_t address, uint16_t max_length, String data) {
xSemaphoreTakeRecursive(EepromMutex, portMAX_DELAY);
if (data.length() < max_length) {
/* save data length to first byte */
EEPROM.write(address, data.length());
@ -357,6 +369,7 @@ void Configuration::SaveString(uint16_t address, uint16_t max_length, String dat
} else {
Log->AddEvent(LogLevel_Verbose, F("Skip write string"));
}
xSemaphoreGiveRecursive(EepromMutex);
}
/**
@ -368,6 +381,7 @@ void Configuration::SaveString(uint16_t address, uint16_t max_length, String dat
void Configuration::SaveIpAddress(uint16_t address, String data) {
IPAddress ip;
if (ip.fromString(data)) {
xSemaphoreTakeRecursive(EepromMutex, portMAX_DELAY);
EEPROM.write(address, ip[0]);
EEPROM.write(address + 1, ip[1]);
EEPROM.write(address + 2, ip[2]);
@ -378,6 +392,7 @@ void Configuration::SaveIpAddress(uint16_t address, String data) {
} else {
Log->AddEvent(LogLevel_Error, F("Failed to write IP address"));
}
xSemaphoreGiveRecursive(EepromMutex);
}
}
@ -387,7 +402,10 @@ void Configuration::SaveIpAddress(uint16_t address, String data) {
@return uint16_t data
*/
uint16_t Configuration::LoadUint16(uint16_t address) {
/* reads locked too: a concurrent save may be half-applied */
xSemaphoreTakeRecursive(EepromMutex, portMAX_DELAY);
uint16_t tmp = uint16_t(EEPROM.read(address) << 8) | (EEPROM.read(address + 1));
xSemaphoreGiveRecursive(EepromMutex);
return tmp;
}
@ -400,6 +418,7 @@ uint16_t Configuration::LoadUint16(uint16_t address) {
*/
String Configuration::LoadString(uint16_t address, uint16_t max_length, bool show_sensitive_data) {
String tmp = "";
xSemaphoreTakeRecursive(EepromMutex, portMAX_DELAY);
uint8_t len = EEPROM.read(address);
if ((len <= max_length) && (len > 0)) {
@ -407,6 +426,7 @@ String Configuration::LoadString(uint16_t address, uint16_t max_length, bool sho
tmp += (char)EEPROM.read(i);
}
}
xSemaphoreGiveRecursive(EepromMutex);
String LogMsg = "";
if (false == show_sensitive_data) {
@ -423,10 +443,12 @@ String Configuration::LoadString(uint16_t address, uint16_t max_length, bool sho
String Configuration::LoadIpAddress(uint16_t address) {
IPAddress ip;
xSemaphoreTakeRecursive(EepromMutex, portMAX_DELAY);
ip[0] = EEPROM.read(address);
ip[1] = EEPROM.read(address + 1);
ip[2] = EEPROM.read(address + 2);
ip[3] = EEPROM.read(address + 3);
xSemaphoreGiveRecursive(EepromMutex);
return ip.toString();
}

View File

@ -124,6 +124,7 @@ public:
private:
Logs *Log; ///< Pointer to Logs object
String WiFiMacAddress; ///< WiFi MAC address
SemaphoreHandle_t EepromMutex; ///< Mutex serialising all EEPROM access
void ReadCfg();
void DefaultCfg();

View File

@ -86,8 +86,8 @@ bool PrusaConnect::SendDataToBackend(String *i_data, int i_data_length, String i
if ((Fingerprint.length() > 0) && (Token.length() > 0)) {
client.setCACert(root_CAs);
//client.setInsecure();
client.setTimeout(1000);
client.setNoDelay(true);
/* setTimeout() takes seconds (upstream 1000 = 16 min). setNoDelay() after connect(): no socket before */
client.setTimeout(PRUSA_CONNECT_TIMEOUT_S);
log->AddEvent(LogLevel_Verbose, F("Connecting to server..."));
@ -105,6 +105,9 @@ bool PrusaConnect::SendDataToBackend(String *i_data, int i_data_length, String i
return false;
} else {
/* socket exists now */
client.setNoDelay(true);
/* send data to server */
log->AddEvent(LogLevel_Verbose, F("Connected to server!"));
client.println("PUT https://" + PrusaConnectHostname + i_url_path + " HTTP/1.1");
@ -159,6 +162,7 @@ bool PrusaConnect::SendDataToBackend(String *i_data, int i_data_length, String i
sendet_data += client.write(fbBuf, remainder);
}
}
client.println("\r\n");
/* log message */
@ -191,6 +195,9 @@ bool PrusaConnect::SendDataToBackend(String *i_data, int i_data_length, String i
String fullResponse = "";
delay(10); // wait for response
log->AddEvent(LogLevel_Verbose, F("Response:"));
/* connected() stays true while the peer idles: yield and bound the wait */
unsigned long ResponseStart = millis();
while (client.connected()) {
if (client.available()) {
response = client.readStringUntil('\n');
@ -206,6 +213,13 @@ bool PrusaConnect::SendDataToBackend(String *i_data, int i_data_length, String i
ret = true;
}
}
} else if ((millis() - ResponseStart) >= ((unsigned long)PRUSA_CONNECT_TIMEOUT_S * SECOND_TO_MILISECOND)) {
log->AddEvent(LogLevel_Warning, F("Timeout waiting for backend response"));
break;
} else {
delay(1);
}
}
log->AddEvent(LogLevel_Verbose, "Full response: " + fullResponse);
@ -238,18 +252,26 @@ bool PrusaConnect::SendDataToBackend(String *i_data, int i_data_length, String i
*/
void PrusaConnect::SendPhotoToBackend() {
log->AddEvent(LogLevel_Info, F("Start sending photo to prusaconnect"));
/* validate the buffer itself: the capture-success flag outlives it */
camera_fb_t *fb = (camera->GetStreamStatus() == false) ? camera->GetPhotoFb() : camera->GetPhotoFbDuplicate();
if ((NULL == fb) || (NULL == fb->buf) || (0 == fb->len)) {
log->AddEvent(LogLevel_Error, F("No valid photo in buffer. Skip sending to backend!"));
return;
}
camera->SetPhotoSending(true);
String Photo = "";
size_t total_len = 0;
if ((camera->GetPhotoExifData()->header != NULL) && (camera->GetStreamStatus() == false)) {
total_len = camera->GetPhotoExifData()->len + camera->GetPhotoFb()->len - camera->GetPhotoExifData()->offset;
} else if (camera->GetStreamStatus() == false) {
total_len = camera->GetPhotoFb()->len;
total_len = camera->GetPhotoExifData()->len + fb->len - camera->GetPhotoExifData()->offset;
} else {
total_len = camera->GetPhotoFbDuplicate()->len;
total_len = fb->len;
}
SendDataToBackend(&Photo, total_len, F("image/jpg"), F("Photo"), HOST_URL_CAM_PATH, SendPhoto);
/* image/jpg is not a registered MIME type; Connect showed no snapshot */
SendDataToBackend(&Photo, total_len, F("image/jpeg"), F("Photo"), HOST_URL_CAM_PATH, SendPhoto);
camera->SetPhotoSending(false);
}
@ -496,16 +518,28 @@ void PrusaConnect::SavePhotoToSdCard() {
return;
}
/* check if folder for time laps photos exists */
/* /timelapse/YYYY-MM-DD/YYYY-MM-DD_HH-MM-SS.jpg: one directory per day bounds directory size */
if (false == log->CheckDir(SD_MMC, TIMELAPS_PHOTO_FOLDER)) {
log->AddEvent(LogLevel_Info, F("Create folder for TimeLaps photos"));
log->CreateDir(SD_MMC, TIMELAPS_PHOTO_FOLDER);
}
/* create file name */
String FileName = String(TIMELAPS_PHOTO_FOLDER) + "/" + String(TIMELAPS_PHOTO_PREFIX) + "_";
FileName += log->GetSystemTime();
FileName += TIMELAPS_PHOTO_SUFFIX;
/* skip until the clock is set */
String SysTime = log->GetSystemTime();
if ((SysTime.length() < 19) || (SysTime.startsWith("0000-00-00"))) {
log->AddEvent(LogLevel_Warning, F("Time not synced yet. Skip saving TimeLaps photo"));
return;
}
/* "YYYY-MM-DD_HH-MM-SS" -> dir "YYYY-MM-DD" */
String DirName = String(TIMELAPS_PHOTO_FOLDER) + "/" + SysTime.substring(0, 10);
if (false == log->CheckDir(SD_MMC, DirName)) {
log->AddEvent(LogLevel_Info, F("Create TimeLaps day folder: "), DirName);
log->CreateDir(SD_MMC, DirName);
}
String FileName = DirName + "/" + SysTime + TIMELAPS_PHOTO_SUFFIX;
log->AddEvent(LogLevel_Verbose, F("Saving file: "), FileName);
/* save photo to SD card */

View File

@ -38,6 +38,7 @@ private:
bool SendDeviceInformationToBackend; ///< flag for sending device information to backend
uint8_t SendingIntervalCounter; ///< counter for sending interval, represents seconds
bool EnableTimelapsPhotoSave; ///< flag for saving photo to SD card
String LastTimelapsDir; ///< day folder already known to exist, so the check runs once per day instead of once per photo
String Token; ///< token for backend communication
String Fingerprint; ///< fingerprint for backend communication

View File

@ -24,7 +24,7 @@ Logs::Logs() {
FileMaxSize = 1024;
NtpTimeSynced = false;
LogMsg = "";
LogMutex = xSemaphoreCreateMutex();
LogMutex = xSemaphoreCreateRecursiveMutex();
}
/**
@ -40,7 +40,7 @@ Logs::Logs(String i_FilePath, String i_FileName) {
FileMaxSize = 1024;
NtpTimeSynced = false;
LogMsg = "";
LogMutex = xSemaphoreCreateMutex();
LogMutex = xSemaphoreCreateRecursiveMutex();
}
/**
@ -57,7 +57,7 @@ Logs::Logs(LogLevel_enum i_LogLevel, String i_FilePath, String i_FileName) {
FileMaxSize = 1024;
NtpTimeSynced = false;
LogMsg = "";
LogMutex = xSemaphoreCreateMutex();
LogMutex = xSemaphoreCreateRecursiveMutex();
}
/**
@ -74,7 +74,7 @@ Logs::Logs(String i_FilePath, String i_FileName, uint16_t i_FileSize) {
FileMaxSize = i_FileSize;
NtpTimeSynced = false;
LogMsg = "";
LogMutex = xSemaphoreCreateMutex();
LogMutex = xSemaphoreCreateRecursiveMutex();
}
/**
@ -92,7 +92,7 @@ Logs::Logs(LogLevel_enum i_LogLevel, String i_FilePath, String i_FileName, uint1
FileMaxSize = i_FileSize;
NtpTimeSynced = false;
LogMsg = "";
LogMutex = xSemaphoreCreateMutex();
LogMutex = xSemaphoreCreateRecursiveMutex();
}
/**
@ -145,7 +145,10 @@ void Logs::Init() {
*/
void Logs::LogOpenFile() {
#if (true == ENABLE_SD_CARD)
/* guards LogFile / LogFileOpened, which AddEvent() also touches */
xSemaphoreTakeRecursive(LogMutex, portMAX_DELAY);
LogFileOpened = OpenFile(&LogFile, FilePath + FileName);
xSemaphoreGiveRecursive(LogMutex);
#endif
}
@ -155,7 +158,10 @@ void Logs::LogOpenFile() {
*/
void Logs::LogCloseFile() {
#if (true == ENABLE_SD_CARD)
xSemaphoreTakeRecursive(LogMutex, portMAX_DELAY);
CloseFile(&LogFile);
LogFileOpened = false;
xSemaphoreGiveRecursive(LogMutex);
#endif
}
@ -165,7 +171,9 @@ void Logs::LogCloseFile() {
*/
void Logs::LogCheckOpenedFile() {
#if (true == ENABLE_SD_CARD)
xSemaphoreTakeRecursive(LogMutex, portMAX_DELAY);
LogFileOpened = CheckOpenFile(&LogFile);
xSemaphoreGiveRecursive(LogMutex);
#endif
}
@ -187,8 +195,16 @@ void Logs::SetLogLevel(LogLevel_enum level) {
@return none
*/
void Logs::AddEvent(LogLevel_enum level, String msg, bool newLine, bool date) {
/* filter before locking */
if (LogLevel < level) {
#if (true == CONSOLE_VERBOSE_DEBUG)
Serial.println(msg);
#endif
return;
}
/* mutex for log */
xSemaphoreTake(LogMutex, portMAX_DELAY);
xSemaphoreTakeRecursive(LogMutex, portMAX_DELAY);
/* check log level */
if (LogLevel >= level) {
@ -224,7 +240,7 @@ void Logs::AddEvent(LogLevel_enum level, String msg, bool newLine, bool date) {
Serial.println(msg);
}
#endif
xSemaphoreGive(LogMutex);
xSemaphoreGiveRecursive(LogMutex);
}
/**
@ -237,8 +253,15 @@ void Logs::AddEvent(LogLevel_enum level, String msg, bool newLine, bool date) {
@return none
*/
void Logs::AddEvent(LogLevel_enum level, const __FlashStringHelper *msg, String parameters, bool newLine, bool date) {
if (LogLevel < level) {
#if (true == CONSOLE_VERBOSE_DEBUG)
Serial.println(msg);
#endif
return;
}
/* mutex for log */
xSemaphoreTake(LogMutex, portMAX_DELAY);
xSemaphoreTakeRecursive(LogMutex, portMAX_DELAY);
/* check log level */
if (LogLevel >= level) {
@ -279,7 +302,7 @@ void Logs::AddEvent(LogLevel_enum level, const __FlashStringHelper *msg, String
#endif
/* release mutex */
xSemaphoreGive(LogMutex);
xSemaphoreGiveRecursive(LogMutex);
}
/**
@ -362,6 +385,9 @@ bool Logs::GetNtpTimeSynced() {
*/
void Logs::CheckMaxLogFileSize() {
#if (true == ENABLE_SD_CARD)
/* rotation atomic w.r.t. AddEvent(); recursive, AddEvent() below takes it too */
xSemaphoreTakeRecursive(LogMutex, portMAX_DELAY);
uint32_t FileSize = GetFileSize(SD_MMC, FilePath + FileName);
AddEvent(LogLevel_Verbose, F("Log file size: "), String(FileSize) + "/" + String(LOGS_FILE_MAX_SIZE) + " B");
@ -372,6 +398,8 @@ void Logs::CheckMaxLogFileSize() {
RenameFile(SD_MMC, FilePath + FileName, FilePath + FileName + String(file_count));
LogOpenFile();
}
xSemaphoreGiveRecursive(LogMutex);
#endif
}

View File

@ -13,13 +13,13 @@
#define _MCU_CFG_H_
/* ----------------- CAMERA TYPE ---------------*/
#define AI_THINKER_ESP32_CAM true
#define ESP32_WROVER_DEV false
#define CAMERA_MODEL_ESP32_S3_DEV_CAM false
#define CAMERA_MODEL_ESP32_S3_EYE_2_2 false
#define CAMERA_MODEL_XIAO_ESP32_S3_CAM false
#define CAMERA_MODEL_ESP32_S3_CAM false
#define ESP32_S3_WROOM_FREENOVE false
#define AI_THINKER_ESP32_CAM true
#define ESP32_WROVER_DEV false
#define CAMERA_MODEL_ESP32_S3_DEV_CAM false
#define CAMERA_MODEL_ESP32_S3_EYE_2_2 false
#define CAMERA_MODEL_XIAO_ESP32_S3_CAM false
#define CAMERA_MODEL_ESP32_S3_CAM false
#define ESP32_S3_WROOM_FREENOVE false
/* ---------------- BASIC MCU CFG --------------*/
#define SW_VERSION "1.1.2" ///< SW version
@ -54,13 +54,15 @@
/* --------------- WEB SERVER CFG --------------*/
#define WEB_SERVER_PORT 80 ///< WEB server port
#define SERIAL_PORT_SPEED 115200 ///< baud rate
#define WDG_TIMEOUT 40000 ///< wdg timeout [second]
#define WDG_TIMEOUT 40000 ///< wdg timeout [ms]
#define PRUSA_CONNECT_TIMEOUT_S 10 ///< PrusaConnect socket timeout [s]
#define PHOTO_FRAGMENT_SIZE 2048 ///< photo fragmentation size [bytes]
#define LOOP_DELAY 100 ///< loop delay [ms]
#define WIFI_CLIENT_WAIT_CON false ///< wait for connecting to WiFi network
#define WEB_CACHE_INTERVAL 86400 ///< cache interval for browser [s] 86400s = 24h
/* --------------- OTA UPDATE CFG --------------*/
#define OTA_CHECK_RESPONSE_TIMEOUT 10000 ///< max ms spent reading the OTA version response [ms]
#define OTA_UPDATE_API_SERVER "api.github.com" ///< OTA update server URL
#define OTA_UPDATE_API_URL F("/repos/prusa3d/Prusa-Firmware-ESP32-Cam/releases/latest") ///< path to file with OTA update
@ -106,7 +108,6 @@
/* ---------------- TIMELAPS CFG ----------------*/
#define TIMELAPS_PHOTO_FOLDER "/timelapse" ///< folder for timelaps photos
#define TIMELAPS_PHOTO_PREFIX "photo" ///< photo name for timelaps
#define TIMELAPS_PHOTO_SUFFIX ".jpg" ///< photo file type for timelaps
/* ---------------- FACTORY CFG ----------------*/

View File

@ -19,7 +19,8 @@
MicroSd::MicroSd() {
CardDetected = false;
DetectAfterBoot = false;
sdCardMutex = xSemaphoreCreateMutex();
/* recursive: these methods nest (ReinitCard -> InitSdCard -> CheckCardUsedStatus) */
sdCardMutex = xSemaphoreCreateRecursiveMutex();
}
/**
@ -28,12 +29,14 @@ MicroSd::MicroSd() {
@return none
*/
void MicroSd::ReinitCard() {
xSemaphoreTakeRecursive(sdCardMutex, portMAX_DELAY);
Serial.println(F("Reinit micro SD card!"));
Serial.println(F("Deinit micro SD card"));
SD_MMC.end();
delay(50);
Serial.println(F("Init micro SD card"));
InitSdCard();
xSemaphoreGiveRecursive(sdCardMutex);
}
/**
@ -45,6 +48,7 @@ void MicroSd::ReinitCard() {
* @return false
*/
bool MicroSd::OpenFile(File *i_file, String i_path) {
xSemaphoreTakeRecursive(sdCardMutex, portMAX_DELAY);
bool status = false;
if (true == CardDetected) {
@ -71,6 +75,7 @@ bool MicroSd::OpenFile(File *i_file, String i_path) {
}
}
}
xSemaphoreGiveRecursive(sdCardMutex);
return status;
}
@ -80,9 +85,11 @@ bool MicroSd::OpenFile(File *i_file, String i_path) {
* @param i_file - file
*/
void MicroSd::CloseFile(File *i_file) {
xSemaphoreTakeRecursive(sdCardMutex, portMAX_DELAY);
if (*i_file) {
i_file->close();
}
xSemaphoreGiveRecursive(sdCardMutex);
}
/**
@ -93,14 +100,16 @@ void MicroSd::CloseFile(File *i_file) {
* @return false
*/
bool MicroSd::CheckOpenFile(File *i_file) {
xSemaphoreTakeRecursive(sdCardMutex, portMAX_DELAY);
bool status = true;
if (!*i_file) {
#if (true == CONSOLE_VERBOSE_DEBUG)
Serial.println(F("File not opened!"));
#endif
return false;
} else {
return true;
status = false;
}
xSemaphoreGiveRecursive(sdCardMutex);
return status;
}
/**
@ -109,6 +118,7 @@ bool MicroSd::CheckOpenFile(File *i_file) {
@return none
*/
void MicroSd::InitSdCard() {
xSemaphoreTakeRecursive(sdCardMutex, portMAX_DELAY);
/* Start INIT Micro SD card */
Serial.println(F("Start init micro-SD Card"));
@ -117,10 +127,16 @@ void MicroSd::InitSdCard() {
SD_MMC.setPins(SD_PIN_CLK, SD_PIN_CMD, SD_PIN_DATA0);
/* SD_MMC_FREQUENCY: defined only by boards whose default clock fails */
#ifdef SD_MMC_FREQUENCY
if (!SD_MMC.begin("/sdcard", true, false, SD_MMC_FREQUENCY)) {
#else
if (!SD_MMC.begin("/sdcard", true)) {
#endif
Serial.println(F("SD Card Mount Failed"));
CardDetected = false;
CardSizeMB = 0;
xSemaphoreGiveRecursive(sdCardMutex);
return;
}
@ -130,6 +146,7 @@ void MicroSd::InitSdCard() {
Serial.println(F("No SD_MMC card attached"));
CardDetected = false;
CardSizeMB = 0;
xSemaphoreGiveRecursive(sdCardMutex);
return;
}
@ -150,6 +167,7 @@ void MicroSd::InitSdCard() {
/* calculation card size */
CheckCardUsedStatus();
xSemaphoreGiveRecursive(sdCardMutex);
}
/**
@ -160,16 +178,19 @@ void MicroSd::InitSdCard() {
@return none
*/
void MicroSd::ListDir(fs::FS &fs, String DirName, uint8_t levels) {
xSemaphoreTakeRecursive(sdCardMutex, portMAX_DELAY);
if (true == CardDetected) {
Serial.printf("Listing directory: %s\n", DirName.c_str());
File root = fs.open(DirName.c_str());
if (!root) {
Serial.println(F("Failed to open directory"));
xSemaphoreGiveRecursive(sdCardMutex);
return;
}
if (!root.isDirectory()) {
Serial.println(F("Not a directory"));
xSemaphoreGiveRecursive(sdCardMutex);
return;
}
@ -190,6 +211,7 @@ void MicroSd::ListDir(fs::FS &fs, String DirName, uint8_t levels) {
file = root.openNextFile();
}
}
xSemaphoreGiveRecursive(sdCardMutex);
}
/**
@ -199,6 +221,7 @@ void MicroSd::ListDir(fs::FS &fs, String DirName, uint8_t levels) {
@return bool - status
*/
bool MicroSd::CheckDir(fs::FS &fs, String path) {
xSemaphoreTakeRecursive(sdCardMutex, portMAX_DELAY);
bool status = false;
if (true == CardDetected) {
#if (true == CONSOLE_VERBOSE_DEBUG)
@ -210,6 +233,7 @@ bool MicroSd::CheckDir(fs::FS &fs, String path) {
}
}
xSemaphoreGiveRecursive(sdCardMutex);
return status;
}
@ -220,6 +244,7 @@ bool MicroSd::CheckDir(fs::FS &fs, String path) {
@return bool - status
*/
bool MicroSd::CreateDir(fs::FS &fs, String path) {
xSemaphoreTakeRecursive(sdCardMutex, portMAX_DELAY);
bool status = false;
if (true == CardDetected) {
#if (true == CONSOLE_VERBOSE_DEBUG)
@ -234,6 +259,7 @@ bool MicroSd::CreateDir(fs::FS &fs, String path) {
Serial.println((status == true) ? "Created" : "Failed");
#endif
}
xSemaphoreGiveRecursive(sdCardMutex);
return status;
}
@ -244,6 +270,7 @@ bool MicroSd::CreateDir(fs::FS &fs, String path) {
@return bool - status
*/
bool MicroSd::RemoveDir(fs::FS &fs, String path) {
xSemaphoreTakeRecursive(sdCardMutex, portMAX_DELAY);
bool status = false;
if (true == CardDetected) {
#if (true == CONSOLE_VERBOSE_DEBUG)
@ -258,6 +285,7 @@ bool MicroSd::RemoveDir(fs::FS &fs, String path) {
Serial.println((status == true) ? "Removed" : "Failed");
#endif
}
xSemaphoreGiveRecursive(sdCardMutex);
return status;
}
@ -268,12 +296,14 @@ bool MicroSd::RemoveDir(fs::FS &fs, String path) {
@return none
*/
void MicroSd::ReadFileConsole(fs::FS &fs, String path) {
xSemaphoreTakeRecursive(sdCardMutex, portMAX_DELAY);
if (true == CardDetected) {
Serial.printf("Reading file: %s\n", path.c_str());
File file = fs.open(path.c_str());
if (!file) {
Serial.println(F("Failed to open file for reading"));
xSemaphoreGiveRecursive(sdCardMutex);
return;
}
@ -282,6 +312,7 @@ void MicroSd::ReadFileConsole(fs::FS &fs, String path) {
Serial.write(file.read());
}
}
xSemaphoreGiveRecursive(sdCardMutex);
}
/**
@ -292,6 +323,7 @@ void MicroSd::ReadFileConsole(fs::FS &fs, String path) {
@return bool - status
*/
bool MicroSd::WriteFile(fs::FS &fs, String path, String message) {
xSemaphoreTakeRecursive(sdCardMutex, portMAX_DELAY);
bool status = false;
if (true == CardDetected) {
#if (true == CONSOLE_VERBOSE_DEBUG)
@ -313,6 +345,7 @@ bool MicroSd::WriteFile(fs::FS &fs, String path, String message) {
#endif
}
}
xSemaphoreGiveRecursive(sdCardMutex);
return status;
}
@ -324,6 +357,7 @@ bool MicroSd::WriteFile(fs::FS &fs, String path, String message) {
@return bool - status
*/
bool MicroSd::AppendFile(fs::FS &fs, String path, String message) {
xSemaphoreTakeRecursive(sdCardMutex, portMAX_DELAY);
bool status = false;
if (true == CardDetected) {
@ -347,6 +381,7 @@ bool MicroSd::AppendFile(fs::FS &fs, String path, String message) {
#endif
}
}
xSemaphoreGiveRecursive(sdCardMutex);
return status;
}
@ -358,12 +393,12 @@ bool MicroSd::AppendFile(fs::FS &fs, String path, String message) {
*/
bool MicroSd::AppendFile(File *i_file, String *i_msg) {
/* take mutex */
xSemaphoreTake(sdCardMutex, portMAX_DELAY);
xSemaphoreTakeRecursive(sdCardMutex, portMAX_DELAY);
bool status = false;
/* check if card is corrupted */
if (false == isCardCorrupted()) {
xSemaphoreGive(sdCardMutex);
xSemaphoreGiveRecursive(sdCardMutex);
return false;
}
@ -410,7 +445,7 @@ bool MicroSd::AppendFile(File *i_file, String *i_msg) {
}
/* give mutex */
xSemaphoreGive(sdCardMutex);
xSemaphoreGiveRecursive(sdCardMutex);
return status;
}
@ -422,6 +457,7 @@ bool MicroSd::AppendFile(File *i_file, String *i_msg) {
@return bool - status
*/
bool MicroSd::RenameFile(fs::FS &fs, String path1, String path2) {
xSemaphoreTakeRecursive(sdCardMutex, portMAX_DELAY);
bool status = false;
if (true == CardDetected) {
#if (true == CONSOLE_VERBOSE_DEBUG)
@ -436,6 +472,7 @@ bool MicroSd::RenameFile(fs::FS &fs, String path1, String path2) {
#endif
}
xSemaphoreGiveRecursive(sdCardMutex);
return status;
}
@ -446,6 +483,7 @@ bool MicroSd::RenameFile(fs::FS &fs, String path1, String path2) {
@return bool - status
*/
bool MicroSd::DeleteFile(fs::FS &fs, String path) {
xSemaphoreTakeRecursive(sdCardMutex, portMAX_DELAY);
bool status = false;
if (true == CardDetected) {
#if (true == CONSOLE_VERBOSE_DEBUG)
@ -460,6 +498,7 @@ bool MicroSd::DeleteFile(fs::FS &fs, String path) {
#endif
}
xSemaphoreGiveRecursive(sdCardMutex);
return status;
}
@ -470,6 +509,7 @@ bool MicroSd::DeleteFile(fs::FS &fs, String path) {
@return uint32_t - size
*/
uint32_t MicroSd::GetFileSize(fs::FS &fs, String path) {
xSemaphoreTakeRecursive(sdCardMutex, portMAX_DELAY);
uint32_t ret = 0;
if (true == CardDetected) {
#if (true == CONSOLE_VERBOSE_DEBUG)
@ -480,6 +520,7 @@ uint32_t MicroSd::GetFileSize(fs::FS &fs, String path) {
#if (true == CONSOLE_VERBOSE_DEBUG)
Serial.println("Failed to open file for appending");
#endif
xSemaphoreGiveRecursive(sdCardMutex);
return 0;
}
@ -489,6 +530,7 @@ uint32_t MicroSd::GetFileSize(fs::FS &fs, String path) {
#endif
}
xSemaphoreGiveRecursive(sdCardMutex);
return ret; /* kb*/
}
@ -500,6 +542,7 @@ uint32_t MicroSd::GetFileSize(fs::FS &fs, String path) {
@return int16_t - count
*/
uint16_t MicroSd::FileCount(fs::FS &fs, String DirName, String FileName) {
xSemaphoreTakeRecursive(sdCardMutex, portMAX_DELAY);
uint16_t FileCount = 0;
if (true == CardDetected) {
#if (true == CONSOLE_VERBOSE_DEBUG)
@ -509,10 +552,12 @@ uint16_t MicroSd::FileCount(fs::FS &fs, String DirName, String FileName) {
File root = fs.open(DirName.c_str());
if (!root) {
Serial.println(F("Failed to open directory"));
xSemaphoreGiveRecursive(sdCardMutex);
return 0;
}
if (!root.isDirectory()) {
Serial.println(F("Not a directory"));
xSemaphoreGiveRecursive(sdCardMutex);
return 0;
}
@ -539,6 +584,7 @@ uint16_t MicroSd::FileCount(fs::FS &fs, String DirName, String FileName) {
}
}
xSemaphoreGiveRecursive(sdCardMutex);
return FileCount;
}
@ -550,9 +596,11 @@ uint16_t MicroSd::FileCount(fs::FS &fs, String DirName, String FileName) {
@return bool - status
*/
bool MicroSd::RemoveFilesInDir(fs::FS &fs, String path, int maxFiles) {
xSemaphoreTakeRecursive(sdCardMutex, portMAX_DELAY);
bool ret = false;
File dir = fs.open(path.c_str());
if (!dir) {
xSemaphoreGiveRecursive(sdCardMutex);
return ret;
}
@ -570,12 +618,15 @@ bool MicroSd::RemoveFilesInDir(fs::FS &fs, String path, int maxFiles) {
file = dir.openNextFile();
}
xSemaphoreGiveRecursive(sdCardMutex);
return ret;
}
int MicroSd::CountFilesInDir(fs::FS &fs, String path) {
xSemaphoreTakeRecursive(sdCardMutex, portMAX_DELAY);
uint16_t file_count = FileCount(fs, path, "");
xSemaphoreGiveRecursive(sdCardMutex);
return file_count;
}
@ -585,17 +636,28 @@ int MicroSd::CountFilesInDir(fs::FS &fs, String path) {
@return bool - status
*/
void MicroSd::CheckCardUsedStatus() {
xSemaphoreTakeRecursive(sdCardMutex, portMAX_DELAY);
CardSizeMB = SD_MMC.cardSize() / (1024 * 1024);
CardTotalMB = SD_MMC.totalBytes() / (1024 * 1024);
CardUsedMB = SD_MMC.usedBytes() / (1024 * 1024);
CardFreeMB = CardSizeMB - CardUsedMB;
/* guard divide by zero (no card) and unsigned wrap (used > size) */
if (0 == CardSizeMB) {
CardFreeMB = 0;
FreeSpacePercent = 0;
UsedSpacePercent = 0;
} else {
CardFreeMB = (CardUsedMB >= CardSizeMB) ? 0 : (CardSizeMB - CardUsedMB);
FreeSpacePercent = (CardFreeMB * 100) / CardSizeMB;
UsedSpacePercent = 100 - FreeSpacePercent;
}
#if (true == CONSOLE_VERBOSE_DEBUG)
Serial.printf("Card size: %d MB, Total: %d MB, Used: %d MB, Free: %d GB, Free: %d %% \n", CardSizeMB, CardTotalMB, CardUsedMB, CardFreeMB, FreeSpacePercent);
#endif
xSemaphoreGiveRecursive(sdCardMutex);
}
/**
@ -605,33 +667,28 @@ void MicroSd::CheckCardUsedStatus() {
* @return false
*/
bool MicroSd::isCardCorrupted() {
xSemaphoreTakeRecursive(sdCardMutex, portMAX_DELAY);
bool ret = true;
if (true == CardDetected) {
#if (true == CONSOLE_VERBOSE_DEBUG)
//Serial.println(F("Checking card..."));
#endif
/* check card size */
/* use == 0 is valid (empty card); size == 0 means no card */
uint64_t size = SD_MMC.cardSize();
uint64_t use = SD_MMC.usedBytes();
uint64_t size = 0;
if (use != 0) {
size = SD_MMC.cardSize();
}
#if (true == CONSOLE_VERBOSE_DEBUG)
Serial.printf("Card size: %llu, Used: %llu\n", size, use);
#endif
/* check space on the card */
if (size == use) {
Serial.println(F("No space left on device!"));
if (size == 0) {
Serial.println(F("No card detected!"));
CardDetected = false;
ret = false;
}
/* check another error */
if ((size <= 0 ) || (size == 0) || (use <= 0) || (use == 0)) {
Serial.println(F("No card detected!"));
} else if (use >= size) {
Serial.println(F("No space left on device!"));
CardDetected = false;
ret = false;
}
@ -640,6 +697,7 @@ bool MicroSd::isCardCorrupted() {
ret = false;
}
xSemaphoreGiveRecursive(sdCardMutex);
return ret;
}
@ -650,8 +708,9 @@ bool MicroSd::isCardCorrupted() {
@return String - data
*/
bool MicroSd::WritePicture(String i_PhotoName, uint8_t *i_PhotoData, size_t i_PhotoLen) {
xSemaphoreTakeRecursive(sdCardMutex, portMAX_DELAY);
#if (true == CONSOLE_VERBOSE_DEBUG)
Serial.println(f("WritePicture"));
Serial.println(F("WritePicture"));
#endif
bool ret_stat = false;
@ -672,6 +731,7 @@ bool MicroSd::WritePicture(String i_PhotoName, uint8_t *i_PhotoData, size_t i_Ph
Serial.printf("Failed. Could not open file: %s\n", i_PhotoName.c_str());
}
xSemaphoreGiveRecursive(sdCardMutex);
return ret_stat;
}
@ -686,6 +746,7 @@ bool MicroSd::WritePicture(String i_PhotoName, uint8_t *i_PhotoData, size_t i_Ph
@return bool - status
*/
bool MicroSd::WritePicture(String i_PhotoName, uint8_t *i_PhotoData, size_t i_PhotoLen, const uint8_t *i_PtohoExif, size_t i_PhotoExifLen) {
xSemaphoreTakeRecursive(sdCardMutex, portMAX_DELAY);
#if (true == CONSOLE_VERBOSE_DEBUG)
Serial.println(F("WritePicture EXIF"));
@ -718,6 +779,7 @@ bool MicroSd::WritePicture(String i_PhotoName, uint8_t *i_PhotoData, size_t i_Ph
ret_stat = false;
}
xSemaphoreGiveRecursive(sdCardMutex);
return ret_stat;
}

View File

@ -15,6 +15,7 @@
Tools -> Erase all Flash Before Sketch Upload -> Disable (first flash, new board = enable. otherwise = disable)
Tools -> Events Run On -> Core 0
Tools -> Flash Mode -> QIO 80MHz
(use DIO if QIO boot-loops, upstream #117)
Tools -> Flash Size -> 8MB
Tools -> Jtag Adapter -> Disable
Tools -> Arduino Runs On -> Core 0
@ -55,6 +56,8 @@
#define HREF_GPIO_NUM 7 ///< Line sync pin
#define PCLK_GPIO_NUM 13 ///< Pixel clock pin
#define XCLK_GPIO_NUM 15 ///< External clock pin
/* XCLK harmonics at default drive desense the WiFi receiver; CAP_1 is not enough */
#define CAMERA_XCLK_DRIVE_CAP GPIO_DRIVE_CAP_0
/* ------------------ MCU CFG ------------------*/
#define BOARD_NAME F("ESP32-S3 WROOM Freenove") ///< Board name
@ -84,6 +87,8 @@
#define SD_PIN_CLK 39 ///< GPIO pin for SD card clock
#define SD_PIN_CMD 38 ///< GPIO pin for SD card command
#define SD_PIN_DATA0 40 ///< GPIO pin for SD card data 0
/* default 40 MHz fails SD init on ESP32-S3-WROOM-1 (esp-idf#8521) */
#define SD_MMC_FREQUENCY SDMMC_FREQ_DEFAULT ///< SDMMC bus frequency (20MHz)
/* ---------- RESET CFG CONFIGURATION ----------*/
#define CFG_RESET_PIN 21 ///< GPIO 12 is for reset CFG to default
@ -96,8 +101,8 @@
#define STATUS_LED_OFF_PIN_LEVEL LOW ///< GPIO pin level for status LED ON
/* -------------- DHT SENSOR CFG ----------------*/
#define DHT_SENSOR_ENABLE false ///< enable/disable DHT sensor
#define DHT_SENSOR_PIN 47 ///< GPIO pin for DHT sensor
#define DHT_SENSOR_ENABLE true ///< enable/disable DHT sensor
#define DHT_SENSOR_PIN 47 ///< GPIO pin for DHT sensor. Free on this board: not used by the camera, SD, flash LED or reset
#endif // AI_THINKER_ESP32_CAM
/* EOF */

View File

@ -103,11 +103,23 @@ void System_UpdateInit() {
@return none
*/
void System_Main() {
/* check new FW version */
if (false == FirmwareUpdate.CheckNewVersionAfterBoot) {
/* once NTP has synced: TLS needs the clock, and DNS overlapping SNTP asserts (udp_new_ip_type) */
if ((false == FirmwareUpdate.CheckNewVersionAfterBoot) && (true == SystemLog.GetNtpTimeSynced())) {
System_CheckNewVersion();
}
/* re-check requested by /check_web_ota_update */
if (true == FirmwareUpdate.RequestNewVersionCheck) {
FirmwareUpdate.RequestNewVersionCheck = false;
/* needs the clock, as above */
if (true == SystemLog.GetNtpTimeSynced()) {
System_CheckNewVersion();
} else {
FirmwareUpdate.CheckNewVersionFwStatus = F("Time not synced yet, try again later");
SystemLog.AddEvent(LogLevel_Warning, FirmwareUpdate.CheckNewVersionFwStatus);
}
}
/* task for download and flash FW from server */
System_OtaCloudUpdate();
}
@ -145,12 +157,19 @@ void System_CheckNewVersion() {
client.println("Connection: close");
client.println();
/* connected() stays true while the peer idles: bound both reads, yield in the body loop */
unsigned long ResponseStart = millis();
while (client.connected()) {
String line = client.readStringUntil('\n');
if (line == "\r") {
SystemLog.AddEvent(LogLevel_Verbose, "headers received: " + line);
break;
}
if ((millis() - ResponseStart) >= OTA_CHECK_RESPONSE_TIMEOUT) {
SystemLog.AddEvent(LogLevel_Warning, F("Timeout reading OTA response headers"));
break;
}
}
/* wait for data, and read it */
@ -160,6 +179,11 @@ void System_CheckNewVersion() {
while (client.available()) {
Data += (char)client.read();
}
if ((millis() - ResponseStart) >= OTA_CHECK_RESPONSE_TIMEOUT) {
SystemLog.AddEvent(LogLevel_Warning, F("Timeout reading OTA response body"));
break;
}
delay(1);
}
SystemLog.AddEvent(LogLevel_Verbose, Data);
@ -188,6 +212,10 @@ void System_CheckNewVersion() {
for(int i = 0; i < assetsCount; i++) {
JsonObject asset = assets[i];
const char* name = asset["name"];
/* NULL when the asset has no "name"; strcmp_P() would panic on it */
if (NULL == name) {
continue;
}
SystemLog.AddEvent(LogLevel_Info, "Assets[" + String(i) + "]: " + String(name));
/* get FW file and URL */
@ -450,6 +478,7 @@ String System_printMcuResetReasonSimple() {
*/
void System_TaskWifiManagement(void *pvParameters) {
SystemLog.AddEvent(LogLevel_Info, F("Task Wifi Management. core: "), String(xPortGetCoreID()));
ESP_ERROR_CHECK(esp_task_wdt_add(NULL));
TickType_t xLastWakeTime = xTaskGetTickCount();
while (1) {
@ -478,6 +507,7 @@ void System_TaskWifiManagement(void *pvParameters) {
*/
void System_TaskMain(void *pvParameters) {
SystemLog.AddEvent(LogLevel_Info, F("System task. core: "), String(xPortGetCoreID()));
ESP_ERROR_CHECK(esp_task_wdt_add(NULL));
TickType_t xLastWakeTime = xTaskGetTickCount();
while (1) {
@ -502,6 +532,7 @@ void System_TaskMain(void *pvParameters) {
*/
void System_TaskCaptureAndSendPhoto(void *pvParameters) {
SystemLog.AddEvent(LogLevel_Info, F("Task photo processing. core: "), String(xPortGetCoreID()));
ESP_ERROR_CHECK(esp_task_wdt_add(NULL));
TickType_t xLastWakeTime = xTaskGetTickCount();
while (1) {
@ -544,6 +575,7 @@ void System_TaskCaptureAndSendPhoto(void *pvParameters) {
*/
void System_TaskSdCardCheck(void *pvParameters) {
SystemLog.AddEvent(LogLevel_Info, F("MicroSdCard check task. core: "), String(xPortGetCoreID()));
ESP_ERROR_CHECK(esp_task_wdt_add(NULL));
TickType_t xLastWakeTime = xTaskGetTickCount();
while (1) {
@ -596,6 +628,7 @@ void System_TaskSdCardCheck(void *pvParameters) {
*/
void System_TaskSerialCfg(void *pvParameters) {
SystemLog.AddEvent(LogLevel_Info, F("SerialCg task. core: "), String(xPortGetCoreID()));
ESP_ERROR_CHECK(esp_task_wdt_add(NULL));
TickType_t xLastWakeTime = xTaskGetTickCount();
while (1) {
@ -619,6 +652,7 @@ void System_TaskSerialCfg(void *pvParameters) {
*/
void System_TaskSystemTelemetry(void *pvParameters) {
SystemLog.AddEvent(LogLevel_Info, F("SystemTelemetry task. core: "), String(xPortGetCoreID()));
ESP_ERROR_CHECK(esp_task_wdt_add(NULL));
TickType_t xLastWakeTime = xTaskGetTickCount();
while (1) {
@ -635,6 +669,27 @@ void System_TaskSystemTelemetry(void *pvParameters) {
SystemLog.AddEvent(LogLevel_Info, "Free PSRAM: " + String(ESP.getFreePsram()) + " B" + ", Min: " + String(ESP.getMinFreePsram()));
SystemLog.AddEvent(LogLevel_Info, "MCU Temperature: " + String(McuTemperature.TemperatureCelsius) + " *C");
/* min free stack per task [bytes] */
String StackMsg = F("Task stack min free (B): Photo: ");
StackMsg += String(uxTaskGetStackHighWaterMark(Task_CapturePhotoAndSend));
StackMsg += F(", WiFiMngt: ");
StackMsg += String(uxTaskGetStackHighWaterMark(Task_WiFiManagement));
StackMsg += F(", Main: ");
StackMsg += String(uxTaskGetStackHighWaterMark(Task_SystemMain));
#if (true == ENABLE_SD_CARD)
StackMsg += F(", SdCard: ");
StackMsg += String(uxTaskGetStackHighWaterMark(Task_SdCardCheck));
#endif
StackMsg += F(", SerialCfg: ");
StackMsg += String(uxTaskGetStackHighWaterMark(Task_SerialCfg));
StackMsg += F(", Telemetry: ");
StackMsg += String(uxTaskGetStackHighWaterMark(Task_SystemTelemetry));
StackMsg += F(", SysLed: ");
StackMsg += String(uxTaskGetStackHighWaterMark(Task_SysLed));
StackMsg += F(", WiFiWdg: ");
StackMsg += String(uxTaskGetStackHighWaterMark(Task_WiFiWatchdog));
SystemLog.AddEvent(LogLevel_Info, StackMsg);
ExternalTemperatureSensor.ReadSensorData();
/* reset wdg */
@ -653,6 +708,7 @@ void System_TaskSystemTelemetry(void *pvParameters) {
*/
void System_TaskSysLed(void *pvParameters) {
SystemLog.AddEvent(LogLevel_Info, F("SystemLed task. core: "), String(xPortGetCoreID()));
ESP_ERROR_CHECK(esp_task_wdt_add(NULL));
TickType_t xLastWakeTime = xTaskGetTickCount();
while (1) {
@ -674,6 +730,7 @@ void System_TaskSysLed(void *pvParameters) {
*/
void System_TaskWiFiWatchdog(void *pvParameters) {
SystemLog.AddEvent(LogLevel_Info, F("WiFiWatchdog task. core: "), String(xPortGetCoreID()));
ESP_ERROR_CHECK(esp_task_wdt_add(NULL));
TickType_t xLastWakeTime = xTaskGetTickCount();
while (1) {

View File

@ -12,7 +12,7 @@
#include "var.h"
WebBasicAuth_struct WebBasicAuth = { false, "", "" };
struct FirmwareUpdate_struct FirmwareUpdate = { "Ready", false, 0, 0, 0, false, false, "", "", "", false };
struct FirmwareUpdate_struct FirmwareUpdate = { "Ready", false, 0, 0, 0, false, false, false, "", "", "", false };
struct McuTemperature_struct McuTemperature = {0.0};
TaskHandle_t Task_CapturePhotoAndSend;

View File

@ -20,20 +20,22 @@ struct WebBasicAuth_struct {
String Password; ///< password for basic auth
};
/* volatile: shared between tasks (String members are not covered) */
struct FirmwareUpdate_struct {
String UpdatingStatus; ///< Updateing status
bool Processing; ///< status abour processing firmware update
uint8_t PercentProcess; ///< processed firmware update
int TransferedBytes; ///< transfered bytes
volatile bool Processing; ///< status abour processing firmware update
volatile uint8_t PercentProcess; ///< processed firmware update
volatile int TransferedBytes; ///< transfered bytes
int FirmwareSize; ///< uploaded firmware size
volatile int FirmwareSize; ///< uploaded firmware size
bool StartOtaUpdate; ///< Start OTA update process
bool CheckNewVersionAfterBoot; ///< Check new version OTA update after MCU boot
volatile bool StartOtaUpdate; ///< Start OTA update process
volatile bool CheckNewVersionAfterBoot; ///< Check new version OTA update after MCU boot
volatile bool RequestNewVersionCheck; ///< re-check requested by the web UI
String NewVersionFw; ///< New FW version
String CheckNewVersionFwStatus; ///< connection status from checking new OTA update version
String OtaUpdateFwUrl; ///< URL for OTA update
bool OtaUpdateFwAvailable; ///< flag for available new FW version
volatile bool OtaUpdateFwAvailable; ///< flag for available new FW version
};
struct McuTemperature_struct {

View File

@ -10,6 +10,7 @@
*/
#include "wifi_mngt.h"
#include <esp_sntp.h>
WiFiMngt SystemWifiMngt(&SystemConfig, &SystemLog, &SystemCamera);
@ -32,6 +33,7 @@ WiFiMngt::WiFiMngt(Configuration *i_conf, Logs *i_log, Camera *i_cam) {
NtpFirstSync = false;
StartStaWdg = false;
WiFiMutex = xSemaphoreCreateRecursiveMutex();
}
/**
@ -138,6 +140,7 @@ void WiFiMngt::Init() {
@return none
*/
void WiFiMngt::WifiManagement() {
xSemaphoreTakeRecursive(WiFiMutex, portMAX_DELAY);
/* check disable service AP */
unsigned long currentMillis = millis();
if (currentMillis - TaskAp_previousMillis >= STA_AP_MODE_TIMEOUT) {
@ -171,6 +174,7 @@ void WiFiMngt::WifiManagement() {
if ((true == config->CheckActifeWifiCfgFlag()) && (false == NtpFirstSync) && (WL_CONNECTED == WiFi.status())) {
SyncNtpTime();
}
xSemaphoreGiveRecursive(WiFiMutex);
}
/**
@ -179,6 +183,7 @@ void WiFiMngt::WifiManagement() {
@return none
*/
void WiFiMngt::WiFiReconnect() {
xSemaphoreTakeRecursive(WiFiMutex, portMAX_DELAY);
if ((WiFi.status() != WL_CONNECTED) && (FirstConnected == true)) {
log->AddEvent(LogLevel_Warning, F("Reconnecting to WiFi. STA"));
WiFi.disconnect();
@ -197,6 +202,7 @@ void WiFiMngt::WiFiReconnect() {
WiFi.reconnect();
Connect.SetBackendAvailabilitStatus(WaitForFirstConnection);
}
xSemaphoreGiveRecursive(WiFiMutex);
}
/**
@ -227,6 +233,7 @@ void WiFiMngt::SetWifiEvents() {
@note https://espressif-docs.readthedocs-hosted.com/projects/arduino-esp32/en/latest/api/wifi.html#sta-connection
*/
void WiFiMngt::WiFiStaConnect() {
xSemaphoreTakeRecursive(WiFiMutex, portMAX_DELAY);
if (config->CheckActifeWifiCfgFlag() == true) {
system_led.setTimer(STATUS_LED_STA_CONNECTING);
if (false == WiFiStaMultipleNetwork) {
@ -250,6 +257,7 @@ void WiFiMngt::WiFiStaConnect() {
WiFi.setSleep(false);
WiFi.setAutoReconnect(true);
}
xSemaphoreGiveRecursive(WiFiMutex);
}
/**
@ -280,6 +288,9 @@ void WiFiMngt::SyncNtpTime() {
if (true == log->GetNtpTimeSynced()) {
log->AddEvent(LogLevel_Info, F("Sync NTP time done. Set UTC timezone"));
NtpFirstSync = true;
/* stop once synced: a pending SNTP DNS callback in another task asserts (udp_new_ip_type) */
esp_sntp_stop();
} else {
log->AddEvent(LogLevel_Info, F("Sync NTP time fail"));
}
@ -779,6 +790,8 @@ String WiFiMngt::GetNetStaticDns() {
@return none
*/
void WiFiMngt::SetStaCredentials(String i_ssid, String i_pass) {
/* one unit: SSID and password */
xSemaphoreTakeRecursive(WiFiMutex, portMAX_DELAY);
WifiSsid = i_ssid;
config->SaveWifiSsid(WifiSsid);
@ -786,6 +799,7 @@ void WiFiMngt::SetStaCredentials(String i_ssid, String i_pass) {
config->SaveWifiPassword(WifiPassword);
config->SaveWifiCfgFlag(CFG_WIFI_SETTINGS_SAVED);
xSemaphoreGiveRecursive(WiFiMutex);
}
/**
@ -794,8 +808,10 @@ void WiFiMngt::SetStaCredentials(String i_ssid, String i_pass) {
@return none
*/
void WiFiMngt::SetStaSsid(String i_ssid) {
xSemaphoreTakeRecursive(WiFiMutex, portMAX_DELAY);
WifiSsid = i_ssid;
config->SaveWifiSsid(WifiSsid);
xSemaphoreGiveRecursive(WiFiMutex);
}
/**
@ -804,8 +820,10 @@ void WiFiMngt::SetStaSsid(String i_ssid) {
@return none
*/
void WiFiMngt::SetStaPassword(String i_pass) {
xSemaphoreTakeRecursive(WiFiMutex, portMAX_DELAY);
WifiPassword = i_pass;
config->SaveWifiPassword(WifiPassword);
xSemaphoreGiveRecursive(WiFiMutex);
}
/**
@ -824,8 +842,13 @@ void WiFiMngt::SetEnableServiceAp(bool i_data) {
@return none
*/
void WiFiMngt::ConnectToSta() {
xSemaphoreTakeRecursive(WiFiMutex, portMAX_DELAY);
config->SaveWifiCfgFlag(CFG_WIFI_SETTINGS_SAVED);
/* disconnect first, else begin() fails: "sta is connecting" */
WiFi.disconnect();
delay(100);
WiFiStaConnect();
xSemaphoreGiveRecursive(WiFiMutex);
}
/**
@ -862,6 +885,8 @@ void WiFiMngt::SetFirstConnection(bool i_data) {
@return none
*/
void WiFiMngt::SetNetworkConfig(String i_ip, String i_mask, String i_gw, String i_dns) {
/* one unit: a new IP with a stale gateway/mask makes the device unreachable */
xSemaphoreTakeRecursive(WiFiMutex, portMAX_DELAY);
NetStaticIp.fromString(i_ip);
NetStaticMask.fromString(i_mask);
NetStaticGateway.fromString(i_gw);
@ -871,6 +896,7 @@ void WiFiMngt::SetNetworkConfig(String i_ip, String i_mask, String i_gw, String
config->SaveNetworkMask(NetStaticMask.toString());
config->SaveNetworkGateway(NetStaticGateway.toString());
config->SaveNetworkDns(NetStaticDns.toString());
xSemaphoreGiveRecursive(WiFiMutex);
}
/**

View File

@ -86,6 +86,9 @@ private:
Logs *log; ///< pointer to log class
Camera *cam; ///< pointer to camera class
/* serialises WiFi state changes across tasks; recursive (WifiManagement/ConnectToSta -> WiFiStaConnect) */
SemaphoreHandle_t WiFiMutex; ///< mutex for WiFi state changes
public:
WiFiMngt(Configuration*, Logs*, Camera*);
~WiFiMngt() {};

View File

@ -3,15 +3,13 @@
This repository includes source code and firmware releases for the **ESP32-cam** module programmed in the **Arduino IDE**. Currently, several versions of boards built on **ESP32/ESP32S3** processors with a camera chip are supported. You can find a list of supported boards below. Additionally, for each supported board, there is a guide on how to upload the firmware, how to compile code for it, some basic information and a list of known issues for this particular board.
This project uses other libraries. It is necessary to install them in the Arduino IDE:
- App [Arduino IDE 2.3.4](https://www.arduino.cc/en/software)
- MCU support [arduino-ESP32 3.1.0](https://github.com/espressif/arduino-esp32)
- ~~Library [ESPAsyncWebSrv 1.2.7](https://github.com/dvarrel/ESPAsyncWebSrv)~~ To version **1.0.3-rc1**
- ~~Library [AsyncTCP 1.1.4](https://github.com/dvarrel/AsyncTCP)~~ To version **1.0.3-rc1**
- Library [AsyncTCP 3.3.1](https://github.com/mathieucarbou/AsyncTCP)
- Library [ESPAsyncWebServer 3.4.5](https://github.com/mathieucarbou/ESPAsyncWebServer)
- Library [ArduinoJson 7.3.0](https://github.com/bblanchon/ArduinoJson)
- App [Arduino IDE 2.3.10](https://www.arduino.cc/en/software)
- MCU support [arduino-ESP32 3.3.11](https://github.com/espressif/arduino-esp32)
- Library [AsyncTCP 3.5.0](https://github.com/ESP32Async/AsyncTCP)
- Library [ESPAsyncWebServer 3.12.1](https://github.com/ESP32Async/ESPAsyncWebServer)
- Library [ArduinoJson 7.4.3](https://github.com/bblanchon/ArduinoJson)
- Library [UniqueID 1.3.0](https://github.com/ricaun/ArduinoUniqueID)
- Library [DHTnew 0.5.2](https://github.com/RobTillaart/DHTNew)
- Library [DHTnew 0.5.5](https://github.com/RobTillaart/DHTNew)
What we need for functionality:
- Supported versions of boards built on **ESP32/ESP32-S3** processors with a camera [here](#supported_boards)