Summary Files Commits Branches @commit @diff @stats
diff options
context:
space:
mode:
Commit1f2c57338684cb7fb50e322fbe35f63e34130fd7 (patch)
Author
 Syndamia <kamen@syndamia.com>
2024-05-29 08:49:34 +0300
Committer
 Syndamia <kamen@syndamia.com>
2024-05-29 08:49:34 +0300
Files545869830b6e5f6e987dc573fde6e88d04d1f3b9
uni-projects-1f2c57338684cb7fb50e322fbe35f63e34130fd7.tar
uni-projects-1f2c57338684cb7fb50e322fbe35f63e34130fd7.tar.gz
uni-projects-1f2c57338684cb7fb50e322fbe35f63e34130fd7.zip
Parent80afdfae71ef31272f240c9701f7a0e67d42d23a (diff)
[iot/goam] Fixed SPIFFS read/write race condition
1 files changed, 33 insertions, 0 deletions
-rw-r--r--Year 3/Internet of things/goam/main/spiffs.c33
diff --git a/Year 3/Internet of things/goam/main/spiffs.c b/Year 3/Internet of things/goam/main/spiffs.c
index 61e1776..1e37525 100644
--- a/Year 3/Internet of things/goam/main/spiffs.c
+++ b/Year 3/Internet of things/goam/main/spiffs.c
@@ -3,6 +3,7 @@
#include <fcntl.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
+#include "freertos/semphr.h"
#include "esp_log.h"
#include "esp_spiffs.h"
@@ -14,6 +15,8 @@ static const char *TAG = "example";
* Public interface
*/
+static SemaphoreHandle_t rw_mutex = NULL;
+
void spiffs_init() {
esp_vfs_spiffs_conf_t conf = {
.base_path = SPIFFS_PREFIX,
@@ -53,12 +56,22 @@ void spiffs_init() {
ESP_LOGI(TAG, "SPIFFS_check() successful");
}
}
+
+ rw_mutex = xSemaphoreCreateMutex();
+ if (rw_mutex == NULL) {
+ ESP_LOGE(TAG, "Couldn't create Read/Write mutex, SPIFFS operations will crash");
+ }
}
void spiffs_write(const char* filename, const char* data, int data_len) {
+ if (xSemaphoreTake(rw_mutex, 100) == pdFALSE) {
+ return;
+ }
+
int outf = open(filename, O_WRONLY | O_CREAT | O_TRUNC);
if (outf < 0) {
ESP_LOGE(TAG, "Couldn't open file \"%s\" for writing!", filename);
+ xSemaphoreGive(rw_mutex);
return;
}
@@ -76,12 +89,28 @@ void spiffs_write(const char* filename, const char* data, int data_len) {
else {
ESP_LOGD(TAG, "Wrote %d bytes from \"%s\"", length, filename);
}
+ xSemaphoreGive(rw_mutex);
}
+static int readers = 0;
+
int spiffs_read(const char* filename, char** data) {
+ if (readers == 0) {
+ if (xSemaphoreTake(rw_mutex, 100) == pdTRUE) {
+ vTaskDelay(150 / portTICK_PERIOD_MS);
+ }
+ else {
+ *data = NULL;
+ return 0;
+ }
+ }
+ readers++;
+
int inf = open(filename, O_RDONLY);
if (inf < 0) {
ESP_LOGW(TAG, "Couldn't read from file \"%s\"!", filename);
+ readers--;
+ if (readers == 0) xSemaphoreGive(rw_mutex);
return 0;
}
@@ -89,6 +118,8 @@ int spiffs_read(const char* filename, char** data) {
if (fstat(inf, &buf) < 0) {
close(inf);
ESP_LOGE(TAG, "Couldn't read stat of file \"%s\"!", filename);
+ readers--;
+ if (readers == 0) xSemaphoreGive(rw_mutex);
return 0;
}
@@ -98,5 +129,7 @@ int spiffs_read(const char* filename, char** data) {
close(inf);
ESP_LOGD(TAG, "read %d bytes from \"%s\"", length, filename);
+ readers--;
+ if (readers == 0) xSemaphoreGive(rw_mutex);
return length;
}