1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
//! TODO: Pending to review after intense refactor
use core::pin::Pin;
use futures::task::{Context, Poll};
use embedded_sdmmc::{Directory, DirEntry, File, Mode, TimeSource, Timestamp, Volume, VolumeIdx, VolumeManager};
use futures::Stream;
use heapless;
use printhor_hwa_common::TrackedStaticCell;
use crate::hwa;
use crate::alloc::string::ToString;
use printhor_hwa_common::ControllerMutex;
use futures::Future;
const MAX_DIRS: usize = 3usize;
const MAX_FILES: usize = 1usize;
#[cfg(feature = "sdcard-uses-spi")]
pub type SDCardBlockDevice = hwa::adapters::SPIAdapter<hwa::device::SpiCardCSPin>;
#[cfg(not(feature = "sdcard-uses-spi"))]
pub type SDCardBlockDevice = hwa::device::SDCardBlockDevice;
#[allow(unused)]
#[derive(Debug)]
#[cfg_attr(feature = "with-defmt", derive(defmt::Format))]
pub enum SDCardError {
NoSuchVolume,
InternalError,
NoDirectorySpecified,
#[allow(unused)]
NotYetImplemented,
MaxOpenDirs,
InconsistencyError,
TrailingEntries,
NotFound,
}
pub type SDCardVolumeManager = VolumeManager<SDCardBlockDevice, DummyTimeSource, MAX_DIRS, MAX_FILES>;
/// Helper adaption for embedded_sdmmc::VolumeManager to manage open count and resolve paths
pub struct SDCard {
mgr: SDCardVolumeManager,
vol: Option<Volume>,
pub(crate) opened_dir_slots: heapless::Vec<Option<Directory>, MAX_DIRS>,
pub(crate) opened_dir_refcount: heapless::Vec<u8, MAX_DIRS>,
/// Full paths as of now...
pub(crate) opened_dir_names: heapless::Vec<Option<alloc::string::String>, MAX_DIRS>,
}
pub struct DirectoryRef {
idx: u8,
}
#[allow(unused)]
impl SDCard {
pub(crate) async fn retain(&mut self) {
#[cfg(feature = "sdcard-uses-spi")]
self.mgr.device().retain().await;
}
pub(crate) async fn release(&mut self) {
#[cfg(feature = "sdcard-uses-spi")]
self.mgr.device().release().await;
}
pub(crate) fn open_root_dir(&mut self) -> Result<DirectoryRef, SDCardError> {
match self.vol.as_ref() {
Some(vol) => {
match self.mgr.open_root_dir(vol) {
Ok(directory) => {
let mut idx = 0u8;
for refcount in &self.opened_dir_refcount {
if *refcount == 0 {
break;
}
idx += 1;
}
if idx < (self.opened_dir_refcount.len() as u8 ){
self.opened_dir_refcount[idx as usize] += 1;
self.opened_dir_slots[idx as usize] = Some(directory);
self.opened_dir_names[idx as usize] = None;
Ok(DirectoryRef{idx})
}
else {
self.mgr.close_dir(vol, directory);
Err(SDCardError::MaxOpenDirs)
}
}
Err(reason) => {
match reason {
embedded_sdmmc::Error::DirAlreadyOpen => {
let mut idx = 0u8;
for dirname in &self.opened_dir_names {
if dirname.is_none() {
break;
}
idx += 1;
}
if idx < (self.opened_dir_refcount.len() as u8 ){
self.opened_dir_refcount[idx as usize] += 1;
Ok(DirectoryRef{idx})
}
else {
Err(SDCardError::InconsistencyError)
}
}
_ => {
Err(SDCardError::InternalError)
}
}
}
}
}
None => {
Err(SDCardError::NoSuchVolume)
}
}
}
pub(crate) fn open_dir(&mut self, parent_dir_ref: &DirectoryRef, name: &str) -> Result<DirectoryRef, SDCardError> {
match self.vol.as_ref() {
Some(vol) => {
let parent_idx = parent_dir_ref.idx as usize;
match &self.opened_dir_slots[parent_idx] {
Some(parent_dir) => {
hwa::debug!("Found parent at idx {}", parent_idx);
match self.mgr.open_dir(vol, parent_dir, name) {
Ok(directory) => {
hwa::debug!("Looking for a place...");
let mut idx = 0u8;
for refcount in &self.opened_dir_refcount {
if *refcount == 0 {
break;
}
idx += 1;
}
hwa::debug!("Will get idx {}... Len is {}", idx, MAX_DIRS);
if idx < (self.opened_dir_refcount.len() as u8 ){
self.opened_dir_refcount[idx as usize] += 1;
self.opened_dir_slots[idx as usize] = Some(directory);
self.opened_dir_names[idx as usize] = None;
Ok(DirectoryRef{idx})
}
else {
self.mgr.close_dir(vol, directory);
Err(SDCardError::MaxOpenDirs)
}
}
Err(reason) => {
match reason {
embedded_sdmmc::Error::DirAlreadyOpen => {
let mut idx = 0u8;
for dirname in &self.opened_dir_names {
if dirname.is_none() {
break;
}
idx += 1;
}
if idx < (MAX_DIRS as u8 ){
self.opened_dir_refcount[idx as usize] += 1;
Ok(DirectoryRef{idx})
}
else {
Err(SDCardError::InconsistencyError)
}
}
_ => {
Err(SDCardError::InternalError)
}
}
}
}
}
None => {
Err(SDCardError::InconsistencyError)
}
}
}
None => {
Err(SDCardError::NoSuchVolume)
}
}
}
pub(crate) fn close_dir(&mut self, dir_ref: DirectoryRef) {
match self.vol.as_ref() {
Some(vol) => {
let idx = dir_ref.idx as usize;
if self.opened_dir_refcount[idx] > 0 {
self.opened_dir_refcount[idx] -= 1;
if self.opened_dir_refcount[idx] == 0 {
hwa::debug!("Refcount of {} went to 0", idx);
if let Some(dir) = self.opened_dir_slots[idx].take() {
self.mgr.close_dir(vol, dir);
let _ = self.opened_dir_names[idx].take();
}
}
}
}
None => {
todo!("No volume")
//Err(SDCardError::NoSuchVolume)
}
}
}
pub(crate) fn is_dir(&mut self, parent_dir_ref: &DirectoryRef, entry_name: &str) -> Result<bool, SDCardError>{
match self.vol.as_ref() {
Some(vol) => {
let idx = parent_dir_ref.idx as usize;
if self.opened_dir_refcount[idx] > 0 {
match &self.opened_dir_slots[idx] {
Some(parent_dir) => {
match self.mgr.find_directory_entry(vol, parent_dir, entry_name) {
Ok(dir_entry) => {
Ok(dir_entry.attributes.is_directory())
}
Err(_e) => {
match _e {
embedded_sdmmc::Error::NoSuchVolume => {
Err(SDCardError::NoSuchVolume)
}
embedded_sdmmc::Error::FileNotFound => {
Err(SDCardError::NotFound)
}
_ => {
Err(SDCardError::InternalError)
}
}
}
}
}
None => {
todo!("hodor")
}
}
}
else {
Err(SDCardError::InconsistencyError)
}
}
None => {
todo!("No volume")
//Err(SDCardError::NoSuchVolume)
}
}
}
/***
This is quite slow but safe as we are holding refcounts, so it's not possible to get inconsistencies
*/
pub(crate) fn list_dir<F>(&mut self, dir: &DirectoryRef, func: F) -> Result<(), SDCardError>
where F: FnMut(&DirEntry)
{
match self.vol.as_ref() {
Some(vol) => {
if self.opened_dir_refcount[dir.idx as usize] == 0 {
Err(SDCardError::InternalError)
}
else {
match &self.opened_dir_slots[dir.idx as usize] {
Some(dir) => {
self.mgr.iterate_dir(vol, dir, func).map_err( |e|
match e {
_ => SDCardError::InternalError
}
)
}
None => {
Err(SDCardError::InternalError)
}
}
}
}
None => {
todo!("No volume")
//Err(SDCardError::NoSuchVolume)
}
}
}
pub(crate) async fn open_file(&mut self, parent_dir_ref: &DirectoryRef, file_name: &str) -> Result<File, SDCardError> {
match self.vol.as_mut() {
Some(vol) => {
let idx = parent_dir_ref.idx as usize;
if self.opened_dir_refcount[idx] > 0 {
match &self.opened_dir_slots[idx] {
Some(parent_dir) => {
match self.mgr.open_file_in_dir(vol, parent_dir, file_name, Mode::ReadOnly) {
Ok(file) => {
Ok(file)
}
Err(_e) => {
hwa::error!("Error opening file in directory. CLUE: File releasing is still incompleted :)");
todo!("hodor")
}
}
}
None => {
hwa::error!("TODO Logic error. CLUE: File releasing is still incompleted :)");
todo!("hodor")
}
}
}
else {
Err(SDCardError::InconsistencyError)
}
}
None => {
todo!("No volume")
//Err(SDCardError::NoSuchVolume)
}
}
}
pub(crate) async fn close_file(&mut self, file: File) -> Result<(), SDCardError> {
match self.vol.as_ref() {
Some(vol) => {
match self.mgr.close_file(vol, file) {
Ok(()) => Ok(()),
Err(_e) => {
panic!("hodor")
}
}
}
None => {
todo!("No volume")
//Err(SDCardError::NoSuchVolume)
}
}
}
pub(crate) async fn read(&mut self, file: &mut File, buffer: &mut [u8]) -> Result<usize, SDCardError> {
match self.vol.as_ref() {
Some(vol) => {
Ok(self.mgr.read(vol, file, buffer).map_err(|e| match e {
_ => {
SDCardError::InternalError
}
})?)
}
None => {
todo!("No volume")
//Err(SDCardError::NoSuchVolume)
}
}
}
}
pub struct DummyTimeSource {
}
impl TimeSource for DummyTimeSource {
fn get_timestamp(&self) -> Timestamp {
Timestamp {
year_since_1970: 0,
zero_indexed_month: 0,
zero_indexed_day: 0,
hours: 0,
minutes: 0,
seconds: 0,
}
}
}
pub struct CardController {
instance: &'static ControllerMutex<SDCard>,
}
#[allow(unused)]
impl CardController {
pub(crate) async fn new(device: SDCardBlockDevice) -> Self {
static CARD_CTRL_SHARED_STATE: TrackedStaticCell<ControllerMutex<SDCard>> = TrackedStaticCell::new();
let mut card = SDCardVolumeManager::new_with_limits(device, DummyTimeSource{});
#[cfg(feature = "sdcard-uses-spi")]
card.device().retain().await;
let vol = card.get_volume(VolumeIdx(hwa::SDCARD_PARTITION));
#[cfg(feature = "sdcard-uses-spi")]
card.device().release().await;
let mut opened_dir_slots = heapless::Vec::new();
let mut opened_dir_refcount = heapless::Vec::new();
let mut opened_dir_names = heapless::Vec::new();
for _ in 0 .. MAX_DIRS {
opened_dir_slots.push(None).unwrap();
opened_dir_refcount.push(0).unwrap();
opened_dir_names.push(None).unwrap();
}
Self{
instance: CARD_CTRL_SHARED_STATE.init(
"card_shared_state",
ControllerMutex::new(SDCard {
mgr: card,
vol: vol.ok(),
opened_dir_slots,
opened_dir_refcount,
opened_dir_names,
})
)
}
}
pub (crate) async fn list_dir(&self, full_path: &str) -> Result<CardAsyncDirIterator, SDCardError> {
hwa::debug!("list_dir() called");
let mut path: heapless::Vec<DirectoryRef, MAX_DIRS> = heapless::Vec::new();
hwa::debug!("Locking card");
let mut card = self.instance.lock().await;
hwa::debug!("Locking card_dev");
card.retain().await;
hwa::debug!("opening root dir");
let dir = card.open_root_dir()?; // TODO: Release on errors
path.push(dir).map_err(|dr| {
card.close_dir(dr);
SDCardError::MaxOpenDirs
})?;
hwa::debug!("Opened root dir");
for subdir in full_path.trim_start_matches('/').split('/') {
if !subdir.is_empty() {
if subdir == "." {
continue;
}
else if subdir == ".." {
if let Some(last_dir) = path.pop() {
card.close_dir(last_dir);
continue;
}
else {
return Err(SDCardError::InconsistencyError);
}
}
hwa::debug!("---- Opening {}", subdir);
if let Some(last_dir) = path.last() {
path.push(card.open_dir(last_dir, subdir)?).map_err(|d| {
hwa::error!("Error opening subdir: push failed");
card.close_dir(d);
SDCardError::MaxOpenDirs
})?;
}
}
}
card.release().await;
Ok(CardAsyncDirIterator::new(self.instance, path))
}
pub (crate) async fn new_stream(&self, file_path: &str) -> Result<SDCardStream, SDCardError> {
let mut path: heapless::Vec<DirectoryRef, MAX_DIRS> = heapless::Vec::new();
let mut card = self.instance.lock().await;
card.retain().await;
let dir = card.open_root_dir()?;
path.push(dir).map_err(|dr| {
card.close_dir(dr);
SDCardError::MaxOpenDirs
})?;
hwa::debug!("Opened root dir");
let mut file: Option<File> = None;
for next_entry in file_path.trim_start_matches('/').split('/') {
match file.take() { // If already got a file but willing to deep into tree.. consume the file and fail
Some(file) => {
card.close_file(file).await.map_err(|_d| {
hwa::error!("Unexpected error closing file");
SDCardError::MaxOpenDirs
})?;
return Err(SDCardError::TrailingEntries);
}
None => {}
}
if !next_entry.is_empty() {
if next_entry == "." {
continue;
}
else if next_entry == ".." {
if let Some(last_dir) = path.pop() {
card.close_dir(last_dir);
continue;
}
else {
return Err(SDCardError::InconsistencyError);
}
}
hwa::debug!("---- Opening {}", next_entry);
if let Some(last_dir) = path.last() {
if card.is_dir(last_dir, next_entry)? {
path.push(card.open_dir(last_dir, next_entry)?).map_err(|d| {
hwa::error!("Error opening subdir: push failed");
card.close_dir(d);
SDCardError::MaxOpenDirs
})?;
}
else {
// File found -> Open it
file.replace(
card.open_file(last_dir, next_entry).await
.map_err(|_e| { SDCardError::InternalError })?
);
}
}
}
}
card.release().await;
match file {
Some(f) => {
Ok(SDCardStream::new(self.clone(), path, f))
}
None => {
Err(SDCardError::NotFound)
}
}
}
#[inline]
pub(crate) async fn read(&mut self, file: &mut File, buffer: &mut [u8]) -> Result<usize, SDCardError> {
let mut card = self.instance.lock().await;
card.retain().await;
let result = card.read(file, buffer).await;
card.release().await;
result
}
#[inline]
pub(crate) async fn close_file(&mut self, file: File) -> Result<(), SDCardError> {
let mut card = self.instance.lock().await;
card.retain().await;
let result = card.close_file(file).await;
card.release().await;
result
}
#[inline]
pub(crate) async fn close_dir(&mut self, dir: DirectoryRef) -> () {
let mut card = self.instance.lock().await;
card.retain().await;
card.close_dir(dir);
card.release().await;
}
}
impl Clone for CardController {
fn clone(&self) -> Self {
Self{ instance: self.instance }
}
}
pub enum SDEntryType {
FILE,
DIRECTORY,
}
pub struct SDDirEntry {
pub name: alloc::string::String,
pub entry_type: SDEntryType,
pub size: u32,
}
pub struct CardAsyncDirIterator {
instance: &'static ControllerMutex<SDCard>,
path: heapless::Vec<DirectoryRef, MAX_DIRS>,
current_index: usize,
}
impl CardAsyncDirIterator {
pub fn new(instance: &'static ControllerMutex<SDCard>, path: heapless::Vec<DirectoryRef, MAX_DIRS>) -> Self {
Self {
instance,
path,
current_index: 0,
}
}
pub async fn next(&mut self) -> Result<Option<SDDirEntry>, SDCardError> {
match self.path.last() {
Some(d) => {
let mut card = self.instance.lock().await;
card.retain().await;
let mut idx = 0;
let mut entry = None;
match card.list_dir(d, |de| {
if self.current_index == idx {
let name: alloc::string::String = match de.name.extension().is_empty() {
true => {
alloc::string::String::from_utf8_lossy(de.name.base_name()).to_string()
}
false => {
alloc::format!("{}.{}",
alloc::string::String::from_utf8_lossy(de.name.base_name()).to_string().as_str(),
alloc::string::String::from_utf8_lossy(de.name.extension()).to_string().as_str()
)
}
};
entry = Some(SDDirEntry {
name,
entry_type: match de.attributes.is_directory() {
true => SDEntryType::DIRECTORY,
false => SDEntryType::FILE,
},
size: de.size,
});
}
idx += 1;
}) {
Ok(_) => {
card.release().await;
self.current_index += 1;
Ok(entry)
}
Err(_) => {
card.release().await;
drop(card);
self.cleanup().await;
Ok(None)
}
}
}
None => {
self.cleanup().await;
Err(SDCardError::NoDirectorySpecified)
}
}
}
pub async fn close(&mut self) {
let mut instance = self.instance.lock().await;
while let Some(d) = self.path.pop() {
instance.close_dir(d);
}
}
async fn cleanup(&mut self) {
let mut card = self.instance.lock().await;
while let Some(d) = self.path.pop() {
card.close_dir(d);
}
}
}
const BSIZE: usize = 32;
#[allow(unused)]
pub struct SDCardStream
{
card_controller: CardController,
file: Option<File>,
path: heapless::Vec<DirectoryRef, MAX_DIRS>,
buffer: [u8; BSIZE],
bytes_read: u8,
current_byte_index: u8,
}
impl SDCardStream
{
pub(self) fn new(card_controller: CardController, path: heapless::Vec<DirectoryRef, MAX_DIRS>, file: File) -> Self {
Self {
card_controller,
file: Some(file),
path,
buffer: [0; BSIZE],
bytes_read: 0,
current_byte_index: 0,
}
}
}
impl Stream for SDCardStream {
type Item = Result<u8, async_gcode::Error>;
fn poll_next(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.get_mut();
if this.current_byte_index < this.bytes_read {
let byte = this.buffer[this.current_byte_index as usize];
this.current_byte_index += 1;
Poll::Ready(Some(Ok(byte)))
}
else {
this.current_byte_index = 0;
this.bytes_read = 0;
let result = match this.file.as_mut() {
None => {
Poll::Ready(Err(SDCardError::NotFound))
}
Some(f) => {
core::pin::pin!(
this.card_controller.read(f, &mut this.buffer)
).poll(ctx)
}
};
match result {
Poll::Ready(rst) => {
match rst {
Ok(bytes_read) => {
this.bytes_read = bytes_read as u8;
if bytes_read > 0 {
let byte = this.buffer[this.current_byte_index as usize];
this.current_byte_index = 1;
Poll::Ready(Some(Ok(byte)))
}
else {
this.bytes_read = 0;
this.current_byte_index = 0;
Poll::Ready(None)
}
}
Err(_) => {
// FIXME: Propper error type and logic
Poll::Ready(Some(Err(async_gcode::Error::NumberOverflow)))
}
}
}
Poll::Pending => {
Poll::Pending
}
}
}
}
}
/*
impl async_gcode::AsyncRead for SDCardStream
{
#[inline]
async fn read_byte(&mut self) -> Option<Result<u8, async_gcode::Error>> {
}
#[inline]
fn push_back(&mut self, _b: u8) {
//crate::debug!("async stream push back");
if self.current_byte_index > 0 {
self.current_byte_index -= 1;
}
}
#[inline]
async fn close(&mut self) {
match self.file.take() {
Some(file) => {
let _ = self.card_controller.close_file(file).await;
}
None => {}
}
while let Some(d) = self.path.pop() {
self.card_controller.close_dir(d).await;
}
}
}
*/