@@ -7,10 +7,13 @@ static_assert(ARDUINO_USB_MODE == 0, "must be used when USB is in OTG mode");
77#include < FFat.h>
88#include < USB.h>
99#include < USBMSC.h>
10+ #include < atomic>
11+ #include < condition_variable>
1012#include < cstdint>
1113#include < esp_err.h>
1214#include < esp_partition.h>
1315#include < iostream>
16+ #include < mutex>
1417
1518#if ARDUINO_USB_CDC_ON_BOOT == 1
1619#define HWSerial Serial0
@@ -25,6 +28,30 @@ static constexpr std::uint16_t blockSize = 512; // Should be 512
2528static const esp_partition_t *partition = nullptr ;
2629static const char *const TAG = " STORAGE" ;
2730
31+ static class ReadyCondition
32+ {
33+ public:
34+ void setReady (const bool new_state)
35+ {
36+ ready = new_state;
37+ conditionVariable.notify_all ();
38+ }
39+ bool isReady () const
40+ {
41+ return ready;
42+ }
43+ void wait_unitl_ready () const
44+ {
45+ std::mutex cv_m;
46+ std::unique_lock<std::mutex> lock (cv_m);
47+ conditionVariable.wait (lock, [this ] { return isReady (); });
48+ }
49+
50+ private:
51+ mutable std::condition_variable conditionVariable;
52+ std::atomic<bool > ready;
53+ } fileSystemState;
54+
2855// Callback invoked when received WRITE10 command.
2956// Process data in buffer to disk's storage and
3057// return number of written bytes (must be multiple of block size)
@@ -86,8 +113,9 @@ static void listFiles(const char *const dirname)
86113static void switchToApplicationMode ()
87114{
88115 MSC.mediaPresent (false );
89- FFat.end (); // invalidate cache
90- FFat.begin (); // update data
116+ FFat.end (); // invalidate cache
117+ ESP_ERROR_CHECK (FFat.begin ()); // update data
118+ fileSystemState.setReady (true );
91119}
92120
93121/* *
@@ -96,6 +124,7 @@ static void switchToApplicationMode()
96124static void switchToUSBMode ()
97125{
98126 FFat.end (); // flush and unmount
127+ fileSystemState.setReady (false );
99128 MSC.mediaPresent (true );
100129}
101130
@@ -108,7 +137,6 @@ static void usbStoppedCallback(void *, esp_event_base_t, int32_t, void *)
108137 }
109138 usbIsRunning = false ;
110139 switchToApplicationMode ();
111- listFiles (" /" );
112140}
113141
114142static void usbStartedCallback (void *, esp_event_base_t , int32_t , void *)
@@ -159,3 +187,9 @@ void Storage::begin()
159187 ESP_LOGE (TAG, " starting USB failed" );
160188 }
161189}
190+
191+ void Storage::waitForFileSystem ()
192+ {
193+ fileSystemState.wait_unitl_ready ();
194+ listFiles (" /" );
195+ }
0 commit comments