98 lines
3.0 KiB
Python
98 lines
3.0 KiB
Python
import os
|
|
import machine
|
|
from machine import Pin, SDCard
|
|
|
|
class SDCardManager:
|
|
"""Utility class to mount and manage the onboard microSD card slot.
|
|
|
|
Uses SDMMC 1-bit mode on Pins: sck=2, cmd=1, data0=3.
|
|
"""
|
|
|
|
def __init__(self, mount_point='/sd'):
|
|
self.mount_point = mount_point
|
|
self.sd = None
|
|
self.mounted = False
|
|
|
|
def mount(self):
|
|
"""Initializes the SD card and mounts it to the filesystem.
|
|
|
|
Returns:
|
|
bool: True if mounted successfully, False otherwise.
|
|
"""
|
|
if self.mounted:
|
|
print(f"SD card already mounted at {self.mount_point}")
|
|
return True
|
|
|
|
try:
|
|
print("Initializing SDCard (SDMMC 1-bit mode: sck=2, cmd=1, data0=3)...")
|
|
# slot=1 uses the SDMMC peripheral on the ESP32-S3
|
|
self.sd = SDCard(slot=1, width=1, sck=2, cmd=1, data=(3,))
|
|
|
|
print(f"Mounting SD card to {self.mount_point}...")
|
|
os.mount(self.sd, self.mount_point)
|
|
self.mounted = True
|
|
print("SD card mounted successfully!")
|
|
return True
|
|
except Exception as e:
|
|
print(f"Failed to mount SD card: {e}")
|
|
self.sd = None
|
|
self.mounted = False
|
|
return False
|
|
|
|
def unmount(self):
|
|
"""Unmounts the SD card from the filesystem."""
|
|
if not self.mounted:
|
|
return True
|
|
|
|
try:
|
|
print(f"Unmounting SD card from {self.mount_point}...")
|
|
os.umount(self.mount_point)
|
|
self.mounted = False
|
|
self.sd = None
|
|
print("SD card unmounted.")
|
|
return True
|
|
except Exception as e:
|
|
print(f"Failed to unmount SD card: {e}")
|
|
return False
|
|
|
|
def is_mounted(self):
|
|
"""Returns True if the card is currently mounted."""
|
|
return self.mounted
|
|
|
|
def list_files(self):
|
|
"""Lists files on the SD card if mounted.
|
|
|
|
Returns:
|
|
list: List of filenames or None if not mounted.
|
|
"""
|
|
if not self.mounted:
|
|
print("SD card is not mounted.")
|
|
return None
|
|
try:
|
|
return os.listdir(self.mount_point)
|
|
except Exception as e:
|
|
print(f"Error listing SD card files: {e}")
|
|
return None
|
|
|
|
def get_info(self):
|
|
"""Returns storage information of the SD card.
|
|
|
|
Returns:
|
|
dict: {total_bytes, free_bytes} or None on error.
|
|
"""
|
|
if not self.mounted:
|
|
return None
|
|
try:
|
|
stat = os.statvfs(self.mount_point)
|
|
block_size = stat[0]
|
|
total_blocks = stat[2]
|
|
free_blocks = stat[3]
|
|
|
|
return {
|
|
"total_bytes": total_blocks * block_size,
|
|
"free_bytes": free_blocks * block_size
|
|
}
|
|
except Exception as e:
|
|
print(f"Error getting SD card info: {e}")
|
|
return None
|