1
7
15
16
17
18
19
20
21
22
23
24
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
48
49
50
51
52
53
54
55
56
57
58
59
60
61
65
66
67
68
69
70
71
74
75
76
77
78
79
80
81
82
83
84
85
91
92
93
94
95
96
106
107
108
109
114
115
118
119
120
121
122
123
124
125
126
127
128
/* ... */
#include <stdio.h>
#include <string.h>
#include <sys/unistd.h>
#include <sys/stat.h>
#include "esp_err.h"
#include "esp_log.h"
#include "esp_spiffs.h"
#include "mbedtls/md5.h"8 includes
static const char *TAG = "example";
static void read_hello_txt(void)
{
ESP_LOGI(TAG, "Reading hello.txt");
FILE* f = fopen("/spiffs/hello.txt", "r");
if (f == NULL) {
ESP_LOGE(TAG, "Failed to open hello.txt");
return;
}{...}
char buf[64];
memset(buf, 0, sizeof(buf));
fread(buf, 1, sizeof(buf), f);
fclose(f);
ESP_LOGI(TAG, "Read from hello.txt: %s", buf);
}{ ... }
static void compute_alice_txt_md5(void)
{
ESP_LOGI(TAG, "Computing alice.txt MD5 hash");
FILE* f = fopen("/spiffs/sub/alice.txt", "r");
if (f == NULL) {
ESP_LOGE(TAG, "Failed to open alice.txt");
return;
}{...}
#define MD5_MAX_LEN 16
char buf[64];
mbedtls_md5_context ctx;
unsigned char digest[MD5_MAX_LEN];
mbedtls_md5_init(&ctx);
mbedtls_md5_starts(&ctx);
size_t read;
do {
read = fread((void*) buf, 1, sizeof(buf), f);
mbedtls_md5_update(&ctx, (unsigned const char*) buf, read);
}{...} while(read == sizeof(buf));
mbedtls_md5_finish(&ctx, digest);
char digest_str[MD5_MAX_LEN * 2];
for (int i = 0; i < MD5_MAX_LEN; i++) {
sprintf(&digest_str[i * 2], "%02x", (unsigned int)digest[i]);
}{...}
ESP_LOGI(TAG, "Computed MD5 hash of alice.txt: %s", digest_str);
fclose(f);
}{ ... }
void app_main(void)
{
ESP_LOGI(TAG, "Initializing SPIFFS");
esp_vfs_spiffs_conf_t conf = {
.base_path = "/spiffs",
.partition_label = NULL,
.max_files = 5,
.format_if_mount_failed = false
}{...};
esp_err_t ret = esp_vfs_spiffs_register(&conf);
if (ret != ESP_OK) {
if (ret == ESP_FAIL) {
ESP_LOGE(TAG, "Failed to mount or format filesystem");
}{...} else if (ret == ESP_ERR_NOT_FOUND) {
ESP_LOGE(TAG, "Failed to find SPIFFS partition");
}{...} else {
ESP_LOGE(TAG, "Failed to initialize SPIFFS (%s)", esp_err_to_name(ret));
}{...}
return;
}{...}
size_t total = 0, used = 0;
ret = esp_spiffs_info(NULL, &total, &used);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to get SPIFFS partition information (%s)", esp_err_to_name(ret));
}{...} else {
ESP_LOGI(TAG, "Partition size: total: %d, used: %d", total, used);
}{...}
/* ... */
read_hello_txt();
compute_alice_txt_md5();
esp_vfs_spiffs_unregister(NULL);
ESP_LOGI(TAG, "SPIFFS unmounted");
}{ ... }