1
0
mirror of https://github.com/trezor/trezor-firmware.git synced 2024-11-12 10:39:00 +00:00
trezor-firmware/core/src/trezor/sdcard.py

62 lines
1.7 KiB
Python
Raw Normal View History

2020-02-26 18:25:22 +00:00
from trezorio import fatfs, sdcard
2020-02-17 14:44:58 +00:00
if False:
2020-02-26 18:25:22 +00:00
from typing import Any, Callable, Optional, TypeVar
T = TypeVar("T", bound=Callable)
2020-02-17 14:44:58 +00:00
class FilesystemWrapper:
_INSTANCE = None # type: Optional[FilesystemWrapper]
def __init__(self, mounted: bool) -> None:
2020-02-17 14:44:58 +00:00
self.mounted = mounted
self.counter = 0
@classmethod
def get_instance(cls, mounted: bool = True) -> "FilesystemWrapper":
if cls._INSTANCE is None:
cls._INSTANCE = cls(mounted=mounted)
if cls._INSTANCE.mounted is not mounted:
raise RuntimeError # cannot request mounted and non-mounted instance at the same time
return cls._INSTANCE
def _deinit_instance(self) -> None:
2020-02-26 18:25:22 +00:00
fatfs.unmount()
sdcard.power_off()
FilesystemWrapper._INSTANCE = None
2020-02-26 18:25:22 +00:00
def __enter__(self) -> None:
try:
if self.counter <= 0:
self.counter = 0
sdcard.power_on()
if self.mounted:
2020-02-26 18:25:22 +00:00
fatfs.mount()
self.counter += 1
except Exception:
self._deinit_instance()
raise
2020-02-17 14:44:58 +00:00
def __exit__(self, exc_type: Any, exc_val: Any, tb: Any) -> None:
self.counter -= 1
if self.counter <= 0:
self.counter = 0
self._deinit_instance()
2020-02-17 14:44:58 +00:00
2020-02-26 18:25:22 +00:00
def filesystem(mounted: bool = True) -> FilesystemWrapper:
2020-02-17 14:44:58 +00:00
return FilesystemWrapper.get_instance(mounted=mounted)
2020-02-26 18:25:22 +00:00
def with_filesystem(func: T) -> T:
def wrapped_func(*args, **kwargs) -> Any: # type: ignore
with filesystem():
return func(*args, **kwargs)
return wrapped_func # type: ignore
2020-02-17 14:44:58 +00:00
is_present = sdcard.is_present
2020-02-26 18:25:22 +00:00
capacity = sdcard.capacity