i2c-microsd-expansion-circuitpython 1.0.13__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1794 @@
1
+ # SPDX-FileCopyrightText: 2026 I2C microSD Expansion contributors
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """module — async file core + legacy queries (port of the I²C microSD Expansion Arduino host library).
5
+
6
+ Transport mirrors the C++ library verbatim:
7
+
8
+ * repeated-START reads (``writeto_then_readfrom`` — never STOP between
9
+ command and read; module discards the command on STOP),
10
+ * ACK is not committed (``opDone``/``result`` latch),
11
+ * flow-paced writes (``rxFree``-guided, 0 blind retries),
12
+ * ``CLOSE_FLUSH`` barrier on open after any gap > 4 s (abrupt host loss),
13
+ * 6x open retry, first barrier unconditional.
14
+
15
+ Split into :class:`I2CmicroSD` (address/sentinel) and :class:`MicroSDExpFile`.
16
+ Solved for CircuitPython: ``busio.I2C`` + ``I2CDevice`` locking; sketch owns
17
+ pin creation (like ``Wire.begin()`` on Arduino).
18
+ """
19
+
20
+ import time
21
+
22
+ from . import config, protocol
23
+
24
+
25
+ # ---- Non-blocking API types ----------------------------------------------
26
+ ASYNC_IOERR = -2 # STATUS read failed
27
+ ASYNC_BUSY = -1 # operation not finished yet
28
+ ASYNC_OK = 0 # operation completed with no error
29
+
30
+ OP_OPEN_WRITE = 1
31
+ OP_OPEN_READ = 2
32
+ OP_CLOSE = 3
33
+ OP_FORMAT = 4
34
+ OP_QUERY = 5
35
+
36
+
37
+ class AsyncOp:
38
+ """Token returned by a begin_*() call; pass to poll_op()."""
39
+ __slots__ = ("done_before", "kind")
40
+
41
+ def __init__(self):
42
+ self.done_before = 0
43
+ self.kind = 0
44
+
45
+
46
+ class MicroSDExpError:
47
+ """Normalized module errors (mirror of the C++ enum).
48
+
49
+ CircuitPython has no ``enum`` module — class ints keep the same
50
+ member names so ported sketches read identically.
51
+ """
52
+
53
+ OK = 0
54
+ NO_MODULE = 1
55
+ NO_FILE = 2
56
+ OPEN_FAIL = 3
57
+ CARD_ERR = 4
58
+ QUEUE_FULL = 5
59
+ INVALID = 6
60
+ OVERFLOW = 7
61
+ TIMEOUT = 8
62
+ NO_CARD = 9
63
+ UNSUPPORTED = 10 # module does not implement the command (older module)
64
+
65
+
66
+ def _caps_crc16(data):
67
+ """CRC-16/CCITT-FALSE over capability frame bytes 0..29."""
68
+ crc = 0xFFFF
69
+ for byte in data:
70
+ crc ^= byte << 8
71
+ for _ in range(8):
72
+ crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
73
+ return crc
74
+
75
+
76
+ class Capabilities:
77
+ """Parsed capability frame; fields come from bytes 0..29."""
78
+
79
+ def __init__(self, b):
80
+ self.rev = b[0]
81
+ self.fw_major = b[1]
82
+ self.fw_minor = b[2]
83
+ self.fw_patch = b[3]
84
+ self.features_a = b[4] | (b[5] << 8) | (b[6] << 16) | (b[7] << 24)
85
+ self.features_b = b[8] | (b[9] << 8) | (b[10] << 16) | (b[11] << 24)
86
+ self.max_path = b[12] | (b[13] << 8)
87
+ self.rx_block_bytes = b[14] | (b[15] << 8)
88
+ self.tx_block_bytes = b[16] | (b[17] << 8)
89
+ self.expansion_pin_count = b[18]
90
+ self.card_detect_present = b[19]
91
+ self.max_open_files = b[20]
92
+ self.current_storage_mode = b[21]
93
+ self.max_file_name = b[22]
94
+
95
+
96
+ class _ErrorSlot:
97
+ """Error attribute: last result plus first failure since clear_error().
98
+
99
+ Internal library calls may overwrite ``last_error``; a real fault stays
100
+ visible in ``sticky_error`` until the caller explicitly clears it.
101
+ """
102
+
103
+ def __get__(self, obj, objtype=None):
104
+ if obj is None:
105
+ return self
106
+ return obj.__dict__.get("_last_error_value", MicroSDExpError.OK)
107
+
108
+ def __set__(self, obj, value):
109
+ obj.__dict__["_last_error_value"] = value
110
+ if value != MicroSDExpError.OK:
111
+ obj.__dict__["_sticky_error"] = value
112
+
113
+
114
+ class StatusFrame:
115
+ """12-byte STATUS frame: rev, state, opDone, error, rxFree, txAvail, result."""
116
+
117
+ __slots__ = ("rev", "state", "op_done", "error", "rx_free", "tx_avail", "result")
118
+
119
+ def __init__(self):
120
+ self.rev = 0
121
+ self.state = 0
122
+ self.op_done = 0
123
+ self.error = 0
124
+ self.rx_free = 0
125
+ self.tx_avail = 0
126
+ self.result = 0
127
+
128
+
129
+ class CardInfo:
130
+ """24-byte CARD_INFO frame (all LE)."""
131
+
132
+ __slots__ = (
133
+ "mounted",
134
+ "fat_type",
135
+ "card_type",
136
+ "sector_count",
137
+ "free_clusters",
138
+ "err_code",
139
+ "err_data",
140
+ "cluster_count",
141
+ "sck_hz",
142
+ )
143
+
144
+ def __init__(self):
145
+ self.mounted = 0
146
+ self.fat_type = 0
147
+ self.card_type = 0
148
+ self.sector_count = 0
149
+ self.free_clusters = 0
150
+ self.err_code = 0
151
+ self.err_data = 0
152
+ self.cluster_count = 0
153
+ self.sck_hz = 0
154
+
155
+ @property
156
+ def free_bytes(self):
157
+ """Free bytes = free_clusters * sectors-per-cluster * 512 is device
158
+ side; the module only reports free_clusters, so expose the raw
159
+ cluster count and let the sketch multiply (clusters are usually
160
+ 32-64 sectors). Provided for API parity with the docs."""
161
+
162
+ # Note: kept as method docs. Sketch computes free space from
163
+ # sector_count/free_clusters/cluster_count + the card's bps/sectors.
164
+ def __repr__(self):
165
+ return (
166
+ f"CardInfo(mounted={self.mounted}, fat={self.fat_type}, "
167
+ + f"sectors={self.sector_count}, free_clusters={self.free_clusters})"
168
+ )
169
+
170
+
171
+ class DirEntry:
172
+ """One listDir entry."""
173
+
174
+ __slots__ = ("is_dir", "name", "size")
175
+
176
+ def __init__(self, is_dir=False, name="", size=0):
177
+ self.is_dir = is_dir
178
+ self.name = name
179
+ self.size = size
180
+
181
+ def __repr__(self):
182
+ kind = "D" if self.is_dir else "F"
183
+ return f"{kind} {self.name!r} {self.size}"
184
+
185
+
186
+ # Expansion pin -> module command byte (the pair is per pin on the wire).
187
+ _PIN_IDS = (
188
+ protocol.MICROSDEXP_PIN_PA0,
189
+ protocol.MICROSDEXP_PIN_PA1,
190
+ protocol.MICROSDEXP_PIN_PA4,
191
+ protocol.MICROSDEXP_PIN_PA5,
192
+ protocol.MICROSDEXP_PIN_PB2,
193
+ protocol.MICROSDEXP_PIN_PB3,
194
+ )
195
+ _PIN_MODE_CMD = {
196
+ protocol.MICROSDEXP_PIN_PA5: protocol.MICROSDEXP_CMD_PA5_SET_MODE,
197
+ protocol.MICROSDEXP_PIN_PB2: protocol.MICROSDEXP_CMD_PB2_SET_MODE,
198
+ protocol.MICROSDEXP_PIN_PB3: protocol.MICROSDEXP_CMD_PB3_SET_MODE,
199
+ protocol.MICROSDEXP_PIN_PA0: protocol.MICROSDEXP_CMD_PA0_SET_MODE,
200
+ protocol.MICROSDEXP_PIN_PA1: protocol.MICROSDEXP_CMD_PA1_SET_MODE,
201
+ protocol.MICROSDEXP_PIN_PA4: protocol.MICROSDEXP_CMD_PA4_SET_MODE,
202
+ }
203
+ _PIN_CONTROL_CMD = {
204
+ protocol.MICROSDEXP_PIN_PA5: protocol.MICROSDEXP_CMD_PA5_CONTROL,
205
+ protocol.MICROSDEXP_PIN_PB2: protocol.MICROSDEXP_CMD_PB2_CONTROL,
206
+ protocol.MICROSDEXP_PIN_PB3: protocol.MICROSDEXP_CMD_PB3_CONTROL,
207
+ protocol.MICROSDEXP_PIN_PA0: protocol.MICROSDEXP_CMD_PA0_CONTROL,
208
+ protocol.MICROSDEXP_PIN_PA1: protocol.MICROSDEXP_CMD_PA1_CONTROL,
209
+ protocol.MICROSDEXP_PIN_PA4: protocol.MICROSDEXP_CMD_PA4_CONTROL,
210
+ }
211
+ # Wire order of the 6-byte CMD_PIN_MODE_READ (0x1E) answer.
212
+ _PIN_MODE_READ_ORDER = (
213
+ protocol.MICROSDEXP_PIN_PA5,
214
+ protocol.MICROSDEXP_PIN_PB2,
215
+ protocol.MICROSDEXP_PIN_PB3,
216
+ protocol.MICROSDEXP_PIN_PA0,
217
+ protocol.MICROSDEXP_PIN_PA1,
218
+ protocol.MICROSDEXP_PIN_PA4,
219
+ )
220
+ _PIN_MODE_NAMES = ("PA5", "PB2", "PB3", "PA0", "PA1", "PA4")
221
+ _PIN_MODE_LABELS = (
222
+ "DIGITAL_OUTPUT",
223
+ "PWM_OUTPUT",
224
+ "DIGITAL_INPUT",
225
+ "INPUT_PULLUP",
226
+ "ANALOG_INPUT",
227
+ )
228
+ # PWM-capable pins. PA0 is digital-only; PB3 is threshold-only (documented).
229
+ _PWM_PINS = frozenset((
230
+ protocol.MICROSDEXP_PIN_PA5, protocol.MICROSDEXP_PIN_PB2,
231
+ protocol.MICROSDEXP_PIN_PB3, protocol.MICROSDEXP_PIN_PA1,
232
+ protocol.MICROSDEXP_PIN_PA4,
233
+ ))
234
+ _PIN_ABSENT = 0xFF
235
+
236
+
237
+ def _le16(b, off):
238
+ return b[off] | (b[off + 1] << 8)
239
+
240
+
241
+ def _le32(b, off):
242
+ return b[off] | (b[off + 1] << 8) | (b[off + 2] << 16) | (b[off + 3] << 24)
243
+
244
+
245
+ def _diag_bytes(n):
246
+ """Format a byte count for the diagnostics report."""
247
+ return "%.1f MiB / %.2f GiB" % (n / 1048576.0, n / 1073741824.0)
248
+
249
+
250
+ class I2CmicroSD:
251
+ """Host for the I²C microSD Expansion module (one open file at a time)."""
252
+
253
+ # last_error is a descriptor so internal calls cannot erase a real fault.
254
+ _last_error = _ErrorSlot()
255
+
256
+ def __init__(self, i2c_device, scl_hz=None, poll_ms=10, flow_poll_ms=2, address=config.DEFAULT_ADDRESS):
257
+ """
258
+ :param i2c_device: ``busio.I2C`` bus (wrapped automatically) or an
259
+ ``adafruit_bus_device.i2c_device.I2CDevice`` for this module.
260
+ The bus clock belongs to the controller; the library never sets
261
+ it and reads ``bus.frequency`` when it is available.
262
+ :param scl_hz: optional override for timeout scaling. Leave it out to
263
+ follow the bus's current frequency; pass a value only when the
264
+ bus cannot report it or you need to model a different rate.
265
+ :param poll_ms: STATUS poll pause.
266
+ :param flow_poll_ms: rxFree re-check while write-blocked.
267
+ :param address: 7-bit module address (used only when wrapping a bus).
268
+ """
269
+ self._bus = None
270
+ if hasattr(i2c_device, "write_then_readinto"):
271
+ # Already an I2CDevice — use as-is.
272
+ self._device = i2c_device
273
+ # Try to recover the bus handle for later re-addressing.
274
+ for attr in ("i2c", "_i2c"):
275
+ try:
276
+ self._bus = getattr(i2c_device, attr)
277
+ break
278
+ except Exception:
279
+ continue
280
+ else:
281
+ # Raw busio.I2C — wrap it.
282
+ from adafruit_bus_device import i2c_device as _dev_mod
283
+
284
+ self._bus = i2c_device
285
+ self._device = _dev_mod.I2CDevice(i2c_device, address, probe=False)
286
+ self._device_address = address
287
+ self._scl_hz = int(scl_hz) if scl_hz else 0
288
+ self._scl_hz_explicit = bool(scl_hz)
289
+ self._poll_ms = poll_ms
290
+ self._flow_poll_ms = flow_poll_ms
291
+ self._read_chunk = config.READ_CHUNK_BYTES
292
+ self._caps = None
293
+ self._caps_ok = False
294
+ self._last_error = MicroSDExpError.OK
295
+ self._file_open = False
296
+ self._async_pending = False
297
+ self._append_mode = False
298
+ self._read_started = False
299
+ self._base_written = 0
300
+ self._written = 0
301
+ self._last_active = 0.0
302
+ self._append_path = ""
303
+ # Last mode applied per expansion pin (None = "none yet"), so a
304
+ # redundant set_pin_mode(pin, same) is a library-side no-op: no bus
305
+ # transaction, no module EEPROM write.
306
+ self._pin_last_mode = {pid: None for pid in _PIN_IDS}
307
+ # Reusable staging (single-file module: no concurrency).
308
+ self._shared = bytearray(128)
309
+
310
+ # ---- helpers ----
311
+ @classmethod
312
+ def from_bus(cls, i2c, address=config.DEFAULT_ADDRESS, **kw):
313
+ """Convenience: build the I2CDevice for you (bus stays sketch-owned)."""
314
+ from adafruit_bus_device import i2c_device
315
+
316
+ dev = i2c_device.I2CDevice(i2c, address, probe=False)
317
+ return cls(dev, **kw)
318
+
319
+ @property
320
+ def scl_hz(self):
321
+ """Bus clock in Hz, read from the controller unless explicitly set."""
322
+ if self._scl_hz_explicit:
323
+ return self._scl_hz
324
+ if self._bus is not None:
325
+ try:
326
+ freq = getattr(self._bus, "frequency", None)
327
+ if freq is not None:
328
+ return int(freq() if callable(freq) else freq)
329
+ except Exception:
330
+ pass
331
+ return config.DEFAULT_SCL_HZ
332
+
333
+ @property
334
+ def last_error(self):
335
+ return self._last_error
336
+
337
+ @property
338
+ def last_ok(self):
339
+ """True when the most recent call completed without error."""
340
+ return self._last_error == MicroSDExpError.OK
341
+
342
+ @property
343
+ def sticky_error(self):
344
+ """First error since clear_error(); OK if no failure was recorded."""
345
+ return self.__dict__.get("_sticky_error", MicroSDExpError.OK)
346
+
347
+ def clear_error(self):
348
+ """Reset both last_error and sticky_error to OK."""
349
+ self._last_error = MicroSDExpError.OK
350
+ self.__dict__["_sticky_error"] = MicroSDExpError.OK
351
+
352
+ @property
353
+ def file_open(self):
354
+ return self._file_open
355
+
356
+ def set_poll_interval(self, ms):
357
+ self._poll_ms = ms
358
+
359
+ def set_read_chunk_bytes(self, n):
360
+ """Bytes requested per READ drain, clamped to 1..256.
361
+
362
+ Defaults to ``config.READ_CHUNK_BYTES`` (256, matching the module's
363
+ two staged 128 B TX buffers). Lower it for a bus/port that
364
+ cannot carry the full chunk in one transaction.
365
+ """
366
+ if n < 1:
367
+ n = 1
368
+ if n > 256:
369
+ n = 256
370
+ self._read_chunk = n
371
+
372
+ def read_chunk_bytes(self):
373
+ return self._read_chunk
374
+
375
+ def scale_timeout(self, base_ms):
376
+ """base * 100000/scl_hz, >= base, >= 2x below 50 kHz, cap 120 s."""
377
+ scl_hz = self.scl_hz
378
+ if scl_hz == 0:
379
+ return base_ms
380
+ scaled = base_ms * 100000 // scl_hz
381
+ if scaled < base_ms:
382
+ scaled = base_ms
383
+ if scl_hz < 50000:
384
+ dbl = base_ms * 2
385
+ if scaled < dbl:
386
+ scaled = dbl
387
+ if scaled > 120000:
388
+ scaled = 120000
389
+ return scaled
390
+
391
+ # ---- transport ----
392
+ def _write(self, payload):
393
+ """Write payload then STOP. Returns True, or False on NACK."""
394
+ self._last_active = time.monotonic()
395
+ try:
396
+ with self._device:
397
+ self._device.write(payload)
398
+ self._last_error = MicroSDExpError.OK
399
+ return True
400
+ except OSError:
401
+ self._last_error = MicroSDExpError.NO_MODULE
402
+ return False
403
+
404
+ def _write_then_read(self, payload, n, out):
405
+ """Repeated-START: write payload, immediately read n bytes into out[0:n].
406
+ Returns bytes read (0 on bus error)."""
407
+ self._last_active = time.monotonic()
408
+ try:
409
+ with self._device:
410
+ self._device.write_then_readinto(payload, out, in_end=n)
411
+ self._last_error = MicroSDExpError.OK
412
+ return n
413
+ except OSError:
414
+ self._last_error = MicroSDExpError.NO_MODULE
415
+ return 0
416
+
417
+ def raw_write(self, cmd, data=b""):
418
+ """Send a raw command + STOP transaction (advanced users).
419
+
420
+ Returns True on ACK, False on NACK. Matches the reference implementation
421
+ ``moduleSend(cmd, data, stop=true)``."""
422
+ return self._write(bytes([cmd]) + bytes(data))
423
+
424
+ def raw_read(self, cmd, n):
425
+ """Repeated-START read of n bytes. Returns bytes (short on error)."""
426
+ buf = bytearray(n)
427
+ got = self._write_then_read(bytes([cmd]), n, buf)
428
+ return bytes(buf[:got])
429
+
430
+ def set_address(self, addr):
431
+ """Switch to a new address (I2C_SET_ADDR tests).
432
+
433
+ The CircuitPython built-in I2CDevice is immutable (no
434
+ ``device_address`` attribute), so recreate the device object.
435
+ """
436
+ self._device_address = addr
437
+ if self._bus is not None:
438
+ try:
439
+ from adafruit_bus_device import i2c_device as _dev_mod
440
+
441
+ self._device = _dev_mod.I2CDevice(self._bus, addr, probe=False)
442
+ except Exception:
443
+ pass
444
+
445
+ def read_status(self, st=None):
446
+ """Read the 12-byte STATUS frame. Returns StatusFrame or None."""
447
+ if st is None:
448
+ st = StatusFrame()
449
+ n = self._write_then_read(bytes([protocol.MICROSDEXP_CMD_STATUS]), 12, self._shared)
450
+ if n < 12:
451
+ return None
452
+ b = self._shared
453
+ st.rev = b[0]
454
+ st.state = b[1]
455
+ st.op_done = b[2]
456
+ st.error = b[3]
457
+ st.rx_free = _le16(b, 4)
458
+ st.tx_avail = _le16(b, 6)
459
+ st.result = _le32(b, 8)
460
+ return st
461
+
462
+ def wait_for_op_complete(self, done_before, timeout_ms=config.OP_TIMEOUT_MS, scale=True):
463
+ """Poll STATUS until opDone != done_before.
464
+
465
+ Returns ``status.error`` (0 = COMPLETE) or -1 on timeout. Set ``scale``
466
+ to False when the caller already owns the budget (e.g. format())."""
467
+ limit = (self.scale_timeout(timeout_ms) if scale else timeout_ms) / 1000.0
468
+ t0 = time.monotonic()
469
+ while (time.monotonic() - t0) < limit:
470
+ st = self.read_status()
471
+ if st is None:
472
+ time.sleep(self._poll_ms / 1000.0)
473
+ continue
474
+ if st.op_done != done_before:
475
+ self._last_error = MicroSDExpError.OK
476
+ return st.error
477
+ time.sleep(self._poll_ms / 1000.0)
478
+ self._last_error = MicroSDExpError.TIMEOUT
479
+ return -1
480
+
481
+ def wait_for_committed(self, target, timeout_ms=config.COMMIT_TIMEOUT_MS):
482
+ limit = self.scale_timeout(timeout_ms) / 1000.0
483
+ t0 = time.monotonic()
484
+ while (time.monotonic() - t0) < limit:
485
+ st = self.read_status()
486
+ if st is not None:
487
+ if st.state == protocol.MICROSDEXP_ST_ERROR:
488
+ self._last_error = MicroSDExpError.CARD_ERR
489
+ return False
490
+ if st.result >= target:
491
+ return True
492
+ time.sleep(self._poll_ms / 1000.0)
493
+ self._last_error = MicroSDExpError.TIMEOUT
494
+ return False
495
+
496
+ def reset_async_state(self):
497
+ """Clear an abandoned op plus the optimistic file state it set."""
498
+ self._async_pending = False
499
+ self._file_open = False
500
+ self._read_started = False
501
+ self._written = 0
502
+ self._base_written = 0
503
+
504
+ def begin(self):
505
+ """Probe the module. The real address is read from STATUS rev.
506
+
507
+ Address scan: bound device address first, then 0x6A-0x6F (the
508
+ module's I2C_SET_ADDR live range) — keeps sketches honest about
509
+ the 0x6E default, matching the Arduino library. Returns True on
510
+ ACK of any module rev 2 STATUS.
511
+ """
512
+ self.reset_async_state() # a re-begin follows a power cycle / reconnect
513
+ self._caps_ok = False # a power cycle invalidates the cache
514
+ st = self.read_status()
515
+ if st is not None:
516
+ self._last_error = MicroSDExpError.OK
517
+ self._query_capabilities() # NACK on old firmware is non-fatal
518
+ self.clear_error() # the optional probe must not leave a sticky error
519
+ return True
520
+ # Try alternate addresses 0x6A-0x6F (recreate device; CP I2CDevice
521
+ # address is immutable, so mutate is not possible).
522
+ saved = self._device_address
523
+ for addr in range(0x6A, 0x70):
524
+ if addr == saved:
525
+ continue
526
+ self.set_address(addr)
527
+ if self.read_status() is not None:
528
+ self._last_error = MicroSDExpError.OK
529
+ self._query_capabilities() # NACK on old firmware is non-fatal
530
+ self.clear_error() # the optional probe must not leave a sticky error
531
+ return True
532
+ self.set_address(saved)
533
+ self._last_error = MicroSDExpError.NO_MODULE
534
+ return False
535
+
536
+ def _query_capabilities(self):
537
+ """Read and validate the 32-byte capability frame; cache it on success."""
538
+ buf = bytearray(32)
539
+ n = self._write_then_read(
540
+ bytes([protocol.MICROSDEXP_CMD_CAPABILITIES]), 32, buf)
541
+ if n < 32:
542
+ self._last_error = MicroSDExpError.UNSUPPORTED
543
+ return False
544
+ crc = _caps_crc16(buf[:30])
545
+ wire_crc = buf[30] | (buf[31] << 8)
546
+ if buf[0] != 2 or crc != wire_crc or buf[21] > 1 or buf[22] == 0:
547
+ self._last_error = MicroSDExpError.INVALID
548
+ return False
549
+ self._caps = Capabilities(buf)
550
+ self._caps_ok = True
551
+ self._last_error = MicroSDExpError.OK
552
+ return True
553
+
554
+ def capabilities(self):
555
+ """Return the cached ``Capabilities``, querying the module if needed."""
556
+ if not self._caps_ok and not self._query_capabilities():
557
+ return None
558
+ return self._caps
559
+
560
+ def supports(self, bit):
561
+ """True if a capability bit is set (bit < 1<<16: bitmap A, else B)."""
562
+ if not self._caps_ok and not self._query_capabilities():
563
+ return False
564
+ if bit < 0x10000:
565
+ return bool(self._caps.features_a & bit)
566
+ return bool(self._caps.features_b & (bit >> 16))
567
+
568
+ # ---- barriers ----
569
+ def _barrier_close_flush(self):
570
+ st = self.read_status()
571
+ db = st.op_done if st is not None else 0
572
+ if not self._write(bytes([protocol.MICROSDEXP_CMD_CLOSE_FLUSH])):
573
+ return False
574
+ return self.wait_for_op_complete(db) == 0
575
+
576
+ def _barrier_if_gap(self):
577
+ if (time.monotonic() - self._last_active) > 4.0:
578
+ self._barrier_close_flush()
579
+
580
+ # ---- paths ----
581
+ def valid_path(self, path):
582
+ """Length-gate only (module handles LFN semantics).
583
+
584
+ Invalid: None/empty/overlong (no I2C sent)."""
585
+ if not path or len(path) == 0 or len(path) >= config.PATH_MAX:
586
+ self._last_error = MicroSDExpError.INVALID
587
+ return False
588
+ return True
589
+
590
+ def _submit_filename(self, path):
591
+ if not self.valid_path(path):
592
+ return False
593
+ try:
594
+ data = path.encode("ascii") + b"\x00"
595
+ except (UnicodeEncodeError, AttributeError):
596
+ self._last_error = MicroSDExpError.INVALID
597
+ return False
598
+ if len(data) > config.PATH_MAX:
599
+ self._last_error = MicroSDExpError.INVALID
600
+ return False
601
+ return self._write(bytes([protocol.MICROSDEXP_CMD_FILENAME]) + data)
602
+
603
+ def _legacy_op(self, cmd, path, want_result=False):
604
+ """doneBefore -> 0x01 -> cmd -> wait -> STATUS.result latch."""
605
+ st = self.read_status()
606
+ done_before = st.op_done if st is not None else 0
607
+ if not self._submit_filename(path):
608
+ return (100, 0)
609
+ if not self._write(bytes([cmd])):
610
+ return (101, 0)
611
+ err = self.wait_for_op_complete(done_before)
612
+ if err < 0:
613
+ self._last_error = MicroSDExpError.TIMEOUT
614
+ return (err, 0)
615
+ result = 0
616
+ if want_result:
617
+ st2 = self.read_status()
618
+ result = st2.result if st2 is not None else 0
619
+ if err != 0:
620
+ self._last_error = MicroSDExpError.OPEN_FAIL if err == protocol.MICROSDEXP_ERR_OPEN else MicroSDExpError.CARD_ERR
621
+ else:
622
+ self._last_error = MicroSDExpError.OK
623
+ return (err, result)
624
+
625
+ # ---- legacy queries + dirs ----
626
+ def _guard_single_handle(self):
627
+ """Mutating housekeeping commands must not disturb an open file/op."""
628
+ if self._file_open or self._async_pending:
629
+ self._last_error = MicroSDExpError.INVALID
630
+ return False
631
+ return True
632
+
633
+ def mkdir(self, path):
634
+ if not self._guard_single_handle() or not self.valid_path(path):
635
+ return False
636
+ return self._legacy_op(protocol.MICROSDEXP_CMD_MAKE_DIR, path)[0] == 0
637
+
638
+ def rmdir(self, path):
639
+ if not self._guard_single_handle() or not self.valid_path(path):
640
+ return False
641
+ return self._legacy_op(protocol.MICROSDEXP_CMD_REMOVE_DIR, path)[0] == 0
642
+
643
+ def remove(self, path):
644
+ if not self._guard_single_handle() or not self.valid_path(path):
645
+ return False
646
+ return self._legacy_op(protocol.MICROSDEXP_CMD_REMOVE_FILE, path)[0] == 0
647
+
648
+ def exists_checked(self, path):
649
+ """Return (ok, exists). ``ok`` is False on I2C/card/path error."""
650
+ if not self.valid_path(path):
651
+ return (False, False)
652
+ err, res = self._legacy_op(protocol.MICROSDEXP_CMD_FILE_EXISTS, path, want_result=True)
653
+ return (err == 0, err == 0 and res == 1)
654
+
655
+ def exists(self, path):
656
+ """True if the path exists. On error returns False — check last_ok."""
657
+ return self.exists_checked(path)[1]
658
+
659
+ def file_size_checked(self, path):
660
+ """Return (ok, size_bytes). ``ok`` distinguishes 0 bytes from an error."""
661
+ if not self.valid_path(path):
662
+ return (False, 0)
663
+ err, res = self._legacy_op(protocol.MICROSDEXP_CMD_FILE_SIZE, path, want_result=True)
664
+ return (err == 0, res if err == 0 else 0)
665
+
666
+ def file_size(self, path):
667
+ """Size in bytes, 0 if not found or on error — check last_ok."""
668
+ return self.file_size_checked(path)[1]
669
+
670
+ def is_directory_checked(self, path):
671
+ """Return (ok, is_directory). ``ok`` is False on error."""
672
+ if not self.valid_path(path):
673
+ return (False, False)
674
+ err, res = self._legacy_op(protocol.MICROSDEXP_CMD_IS_DIRECTORY, path, want_result=True)
675
+ return (err == 0, err == 0 and res == 1)
676
+
677
+ def is_directory(self, path):
678
+ """True if the path is a directory — check last_ok on error."""
679
+ return self.is_directory_checked(path)[1]
680
+
681
+ def firmware_banner(self):
682
+ """Full identification banner returned by CMD_VERSION (0x0F).
683
+
684
+ The module answers with a NUL-terminated three-line banner::
685
+
686
+ v<version>
687
+ I2C microSD Expansion
688
+ Copyright (C) 2026 syntax1269@gmail.com
689
+
690
+ NUL padding and surrounding whitespace are stripped; the internal
691
+ newlines are preserved.
692
+ """
693
+ buf = bytearray(config.VERSION_BANNER_BYTES)
694
+ n = self._write_then_read(bytes([protocol.MICROSDEXP_CMD_VERSION]),
695
+ config.VERSION_BANNER_BYTES, buf)
696
+ if n == 0:
697
+ return ""
698
+ end = 0
699
+ while end < n and buf[end] != 0:
700
+ end += 1
701
+ self._last_error = MicroSDExpError.OK
702
+ return bytes(buf[:end]).decode("ascii", "replace").strip()
703
+
704
+ def version(self):
705
+ """The whole three-line firmware banner, or "" on error.
706
+
707
+ NUL padding and trailing whitespace are removed but the banner's
708
+ internal newlines are kept, e.g.::
709
+
710
+ v<version>
711
+ I2C microSD Expansion
712
+ Copyright (C) 2026 syntax1269@gmail.com
713
+
714
+ Use :meth:`module_clock_hz` for the measured CPU clock. Sets
715
+ ``INVALID`` when the answer is empty or not a complete banner.
716
+ """
717
+ text = self.firmware_banner()
718
+ lines = text.splitlines()
719
+ if len(lines) < 3 or not lines[0].lower().startswith("v"):
720
+ self._last_error = MicroSDExpError.INVALID
721
+ return ""
722
+ self._last_error = MicroSDExpError.OK
723
+ return text
724
+
725
+ def firmware_clock_hz(self):
726
+ """Deprecated alias of :meth:`module_clock_hz`."""
727
+ return self.module_clock_hz()
728
+
729
+ def module_clock_hz(self):
730
+ """Measured CPU clock in Hz from CMD_MODULE_CLOCK (0x1B), else 0."""
731
+ buf = bytearray(4)
732
+ if self._write_then_read(bytes([protocol.MICROSDEXP_CMD_MODULE_CLOCK]),
733
+ 4, buf) < 4:
734
+ self._last_error = MicroSDExpError.INVALID
735
+ return 0
736
+ self._last_error = MicroSDExpError.OK
737
+ return _le32(buf, 0)
738
+
739
+ def _pin_mode_bytes(self):
740
+ """One CMD_PIN_MODE_READ (0x1E) transaction -> list of 6 ints, or None."""
741
+ buf = bytearray(6)
742
+ if self._write_then_read(bytes([protocol.MICROSDEXP_CMD_PIN_MODE_READ]),
743
+ 6, buf) < 6:
744
+ self._last_error = MicroSDExpError.INVALID
745
+ return None
746
+ self._last_error = MicroSDExpError.OK
747
+ return list(buf)
748
+
749
+ def pin_mode(self, pin_id):
750
+ """Current mode of one expansion pin: 0..4, or 0xFF if absent.
751
+
752
+ ``pin_id`` uses the logical IDs (PA5=5, PB2=2, PB3=3, PA0=0,
753
+ PA1=1, PA4=4). One 0x1E read fetches all six modes; an unknown
754
+ ``pin_id`` or a bad/short frame reports ``INVALID``.
755
+ """
756
+ if pin_id not in _PIN_MODE_READ_ORDER:
757
+ self._last_error = MicroSDExpError.INVALID
758
+ return _PIN_ABSENT
759
+ modes = self._pin_mode_bytes()
760
+ if modes is None:
761
+ return _PIN_ABSENT
762
+ mode = modes[_PIN_MODE_READ_ORDER.index(pin_id)]
763
+ if mode not in (0, 1, 2, 3, 4, _PIN_ABSENT):
764
+ self._last_error = MicroSDExpError.INVALID
765
+ return _PIN_ABSENT
766
+ return mode
767
+
768
+ def pin_modes(self):
769
+ """Map pin names to mode ints (0..4) or None when the pin is absent.
770
+
771
+ Uses a single CMD_PIN_MODE_READ (0x1E) transaction. Keys are
772
+ ``PA5``, ``PB2``, ``PB3``, ``PA0``, ``PA1``, ``PA4`` in wire order.
773
+ A bad/short frame returns an empty dict with ``INVALID`` set.
774
+ """
775
+ modes = self._pin_mode_bytes()
776
+ if modes is None:
777
+ return {}
778
+ out = {}
779
+ for name, mode in zip(_PIN_MODE_NAMES, modes):
780
+ if mode == _PIN_ABSENT:
781
+ out[name] = None
782
+ elif mode in (0, 1, 2, 3, 4):
783
+ out[name] = mode
784
+ else:
785
+ self._last_error = MicroSDExpError.INVALID
786
+ return {}
787
+ return out
788
+
789
+ def volume_name(self):
790
+ """NUL-terminated volume label from CMD_VOLUME_NAME (0x1F), or ""."""
791
+ buf = bytearray(16)
792
+ if self._write_then_read(bytes([protocol.MICROSDEXP_CMD_VOLUME_NAME]),
793
+ 16, buf) < 16:
794
+ self._last_error = MicroSDExpError.INVALID
795
+ return ""
796
+ end = 0
797
+ while end < 16 and buf[end] != 0:
798
+ end += 1
799
+ self._last_error = MicroSDExpError.OK
800
+ return bytes(buf[:end]).decode("ascii", "replace").strip()
801
+
802
+ def temperature_k(self):
803
+ """Die temperature in whole kelvin (2-byte LE); 0xFFFF on error."""
804
+ buf = bytearray(2)
805
+ if self._write_then_read(bytes([protocol.MICROSDEXP_CMD_TEMP_READ]), 2, buf) < 2:
806
+ self._last_error = MicroSDExpError.INVALID
807
+ return 0xFFFF
808
+ self._last_error = MicroSDExpError.OK
809
+ return _le16(buf, 0)
810
+
811
+ def adc_pin(self, pin):
812
+ """Raw 12-bit ADC word by logical pin ID (PA5=5, PA4=4)."""
813
+ commands = {
814
+ protocol.MICROSDEXP_PIN_PA5: protocol.MICROSDEXP_CMD_ADC_READ_PA5,
815
+ protocol.MICROSDEXP_PIN_PA4: protocol.MICROSDEXP_CMD_ADC_READ_PA4,
816
+ }
817
+ if pin not in commands:
818
+ self._last_error = MicroSDExpError.INVALID
819
+ return 0xFFFF
820
+ buf = bytearray(3)
821
+ if self._write_then_read(bytes([commands[pin]]), 3, buf) < 2:
822
+ self._last_error = MicroSDExpError.INVALID
823
+ return 0xFFFF
824
+ if buf[0] == 0xFF and buf[1] == 0xFF:
825
+ self._last_error = MicroSDExpError.INVALID
826
+ return 0xFFFF
827
+ self._last_error = MicroSDExpError.OK
828
+ return _le16(buf, 0)
829
+
830
+ def adc_pa5(self):
831
+ """Raw 12-bit ADC word from PA5."""
832
+ return self.adc_pin(protocol.MICROSDEXP_PIN_PA5)
833
+
834
+ def card_present(self):
835
+ """True while a card is inserted; False on no card or I/O error.
836
+
837
+ Sets ``last_error`` to ``NO_CARD`` when the answer is "no card".
838
+ """
839
+ buf = bytearray(1)
840
+ if self._write_then_read(bytes([protocol.MICROSDEXP_CMD_CARD_PRESENT]), 1, buf) < 1:
841
+ self._last_error = MicroSDExpError.INVALID
842
+ return False
843
+ self._last_error = (MicroSDExpError.OK if buf[0]
844
+ else MicroSDExpError.NO_CARD)
845
+ return buf[0] != 0
846
+
847
+ def card_info(self):
848
+ """24-byte CARD_INFO snapshot as CardInfo, or None."""
849
+ buf = bytearray(24)
850
+ if self._write_then_read(bytes([protocol.MICROSDEXP_CMD_CARD_INFO]), 24, buf) < 24:
851
+ self._last_error = MicroSDExpError.INVALID
852
+ return None
853
+ out = CardInfo()
854
+ out.mounted = buf[0]
855
+ out.fat_type = buf[1]
856
+ out.card_type = buf[2]
857
+ out.sector_count = _le32(buf, 4)
858
+ out.free_clusters = _le32(buf, 8)
859
+ out.err_code = _le16(buf, 12)
860
+ out.err_data = _le16(buf, 14)
861
+ out.cluster_count = _le32(buf, 16)
862
+ out.sck_hz = _le32(buf, 20)
863
+ self._last_error = MicroSDExpError.OK
864
+ return out
865
+
866
+ def diagnostics(self):
867
+ """Return a one-page health report for troubleshooting.
868
+
869
+ Reports module presence, the current software RTC date/time, protocol/firmware
870
+ version (the full banner on its own rows), card/filesystem state,
871
+ volume label, capacity and free space, bound I²C address, configured
872
+ bus clock, measured module clock, expansion-pin modes and a
873
+ communication verdict. Safe to call
874
+ before ``begin()``: unreadable fields show as ``n/a``. The call does
875
+ not change :attr:`last_error`.
876
+
877
+ Free space uses the module's ``free_clusters`` value; a reported 0 means
878
+ unknown (scan pending) or a full card, so the report says ``unknown``.
879
+ """
880
+ preserved = self._last_error
881
+ lines = ["I2C microSD Expansion", "---------------------"]
882
+ st = self.read_status()
883
+ lines.append("Module detected: %s" % ("yes" if st is not None else "no"))
884
+ clk = self.read_clock()
885
+ lines.append("Current Date/Time: %s" % (
886
+ "%04d-%02d-%02d %02d:%02d:%02d" % clk if clk is not None else "n/a"))
887
+ lines.append("Protocol version: %s" % (str(st.rev) if st is not None else "n/a"))
888
+
889
+ fw = self.version()
890
+ lines.append("Firmware version: %s" % (fw if fw else "unknown"))
891
+
892
+ ci = self.card_info()
893
+ lines.append("SD card detected: %s" % ("yes" if ci is not None and ci.mounted else "no"))
894
+ if ci is not None:
895
+ fat_names = {12: "FAT12", 16: "FAT16", 32: "FAT32", 64: "exFAT"}
896
+ lines.append("Filesystem: %s" % fat_names.get(ci.fat_type, "unknown"))
897
+ vol = self.volume_name()
898
+ lines.append("Volume Name: %s" % (vol if vol else "(none)"))
899
+ capacity = ci.sector_count * 512
900
+ lines.append("Capacity: %s" % (
901
+ _diag_bytes(capacity) if capacity else "n/a"))
902
+ if ci.cluster_count > 0 and ci.free_clusters > 0:
903
+ cluster = ((capacity // ci.cluster_count + 256) // 512) * 512
904
+ lines.append("Free space: %s" % _diag_bytes(ci.free_clusters * cluster))
905
+ elif ci.free_clusters == 0:
906
+ lines.append("Free space: unknown")
907
+ else:
908
+ lines.append("Free space: n/a")
909
+ else:
910
+ lines.extend(["Filesystem: n/a",
911
+ "Volume Name: n/a",
912
+ "Capacity: n/a",
913
+ "Free space: n/a"])
914
+
915
+ lines.append("I2C address: 0x%02X" % self._device_address)
916
+ lines.append("I2C speed: %d kHz (bus)" % (self.scl_hz // 1000))
917
+
918
+ hz = self.module_clock_hz()
919
+ lines.append("Module Clock: %s" % ("%d Hz" % hz if hz else "n/a"))
920
+ modes = self.pin_modes()
921
+ for name in _PIN_MODE_NAMES:
922
+ mode = modes.get(name)
923
+ if mode is None:
924
+ label = "absent"
925
+ elif 0 <= mode < len(_PIN_MODE_LABELS):
926
+ label = _PIN_MODE_LABELS[mode]
927
+ else:
928
+ label = "unknown"
929
+ lines.append("PIN %s: %s" % (name, label))
930
+
931
+ lines.append("Communication: %s" % (
932
+ "OK" if st is not None and st.error == 0 else "CHECK"))
933
+
934
+ self._last_error = preserved
935
+ return "\n".join(lines)
936
+
937
+ # ---- Non-blocking API (no sleeps; call from your loop) -----------------
938
+ def _async_submit_open(self, cmd, path, op, kind):
939
+ if self._async_pending or not self.valid_path(path):
940
+ return False
941
+ st = self.read_status()
942
+ if st is None:
943
+ self._last_error = MicroSDExpError.NO_MODULE
944
+ return False
945
+ try:
946
+ raw = path.encode("ascii") + b"\x00"
947
+ except (UnicodeEncodeError, AttributeError):
948
+ self._last_error = MicroSDExpError.INVALID
949
+ return False
950
+ if not self._write(bytes([cmd]) + raw):
951
+ return False
952
+ op.done_before = st.op_done
953
+ op.kind = kind
954
+ self._async_pending = True
955
+ self._append_mode = False
956
+ self._read_started = False
957
+ self._written = 0
958
+ self._file_open = kind in (OP_OPEN_WRITE, OP_OPEN_READ)
959
+ self._last_error = MicroSDExpError.OK
960
+ return True
961
+
962
+ def begin_open_write(self, path, op):
963
+ """Submit OPEN_WRITE without waiting; poll with poll_op()."""
964
+ return self._async_submit_open(protocol.MICROSDEXP_CMD_OPEN_WRITE, path, op, OP_OPEN_WRITE)
965
+
966
+ def begin_open_read(self, path, op):
967
+ """Submit OPEN_READ without waiting; poll with poll_op()."""
968
+ return self._async_submit_open(protocol.MICROSDEXP_CMD_OPEN_READ, path, op, OP_OPEN_READ)
969
+
970
+ def begin_close(self, op):
971
+ """Submit CLOSE_FLUSH without waiting; poll with poll_op()."""
972
+ if self._async_pending or not self._file_open:
973
+ return False
974
+ if self._append_mode: # append chunks are atomic; no module op
975
+ self._file_open = False
976
+ self._append_mode = False
977
+ self._read_started = False
978
+ self._last_error = MicroSDExpError.OK
979
+ return False
980
+ st = self.read_status()
981
+ if st is None:
982
+ self._last_error = MicroSDExpError.NO_MODULE
983
+ return False
984
+ if not self._write(bytes([protocol.MICROSDEXP_CMD_CLOSE_FLUSH])):
985
+ return False
986
+ op.done_before = st.op_done
987
+ op.kind = OP_CLOSE
988
+ self._async_pending = True
989
+ return True
990
+
991
+ def begin_format(self, mode, op):
992
+ """Submit FORMAT without waiting (destructive)."""
993
+ if mode not in (0, 1) or self._async_pending:
994
+ self._last_error = MicroSDExpError.INVALID
995
+ return False
996
+ st = self.read_status()
997
+ if st is None:
998
+ self._last_error = MicroSDExpError.NO_MODULE
999
+ return False
1000
+ if not self._write(bytes([protocol.MICROSDEXP_CMD_FORMAT, mode])):
1001
+ return False
1002
+ op.done_before = st.op_done
1003
+ op.kind = OP_FORMAT
1004
+ self._async_pending = True
1005
+ return True
1006
+
1007
+ def begin_query(self, cmd, path, op):
1008
+ """Submit a queued command (optionally with a path) without waiting."""
1009
+ if self._async_pending:
1010
+ return False
1011
+ st = self.read_status()
1012
+ if st is None:
1013
+ self._last_error = MicroSDExpError.NO_MODULE
1014
+ return False
1015
+ if path and not self._submit_filename(path):
1016
+ return False
1017
+ if not self._write(bytes([cmd])):
1018
+ return False
1019
+ op.done_before = st.op_done
1020
+ op.kind = OP_QUERY
1021
+ self._async_pending = True
1022
+ return True
1023
+
1024
+ def poll_op(self, op):
1025
+ """One STATUS read: ASYNC_BUSY, ASYNC_OK, module error, or ASYNC_IOERR."""
1026
+ st = self.read_status()
1027
+ if st is None:
1028
+ return ASYNC_IOERR
1029
+ if st.op_done == op.done_before:
1030
+ return ASYNC_BUSY
1031
+ if not self._async_pending:
1032
+ return st.error
1033
+ self._async_pending = False
1034
+ if st.error != 0 and op.kind in (OP_OPEN_WRITE, OP_OPEN_READ):
1035
+ # The submit path set _file_open optimistically. Undo it when the
1036
+ # OPEN fails, and never prime a stream on a file that never opened.
1037
+ self._file_open = False
1038
+ self._read_started = False
1039
+ elif op.kind == OP_OPEN_WRITE:
1040
+ self._base_written = st.result
1041
+ elif op.kind == OP_OPEN_READ:
1042
+ self._base_written = st.result
1043
+ self._write(bytes([protocol.MICROSDEXP_CMD_READ])) # prime the stream
1044
+ self._read_started = True
1045
+ elif op.kind == OP_CLOSE:
1046
+ self._file_open = False
1047
+ self._read_started = False
1048
+ if st.error == 0:
1049
+ self._last_error = MicroSDExpError.OK
1050
+ else:
1051
+ self._last_error = (MicroSDExpError.OPEN_FAIL
1052
+ if st.error == protocol.MICROSDEXP_ERR_OPEN
1053
+ else MicroSDExpError.CARD_ERR)
1054
+ return st.error
1055
+
1056
+ def write_now(self, data):
1057
+ """Push at most one chunk if RX has room now. Returns bytes accepted."""
1058
+ if not data or not self._file_open or self._async_pending:
1059
+ if not self._file_open:
1060
+ self._last_error = MicroSDExpError.NO_FILE
1061
+ return 0
1062
+ if self._append_mode:
1063
+ self._last_error = MicroSDExpError.INVALID
1064
+ return 0
1065
+ chunk = bytes(data[:config.CHUNK_BYTES])
1066
+ st = self.read_status()
1067
+ if st is None:
1068
+ self._last_error = MicroSDExpError.NO_MODULE
1069
+ return 0
1070
+ if st.state == protocol.MICROSDEXP_ST_ERROR:
1071
+ self._last_error = MicroSDExpError.CARD_ERR
1072
+ return 0
1073
+ if st.rx_free < len(chunk):
1074
+ return 0 # would block
1075
+ if not self._write(bytes([protocol.MICROSDEXP_CMD_WRITE]) + chunk):
1076
+ return 0
1077
+ self._written += len(chunk)
1078
+ self._last_error = MicroSDExpError.OK
1079
+ return len(chunk)
1080
+
1081
+ def read_now(self, n):
1082
+ """Drain only what is staged right now. Returns bytes (b"" = try later)."""
1083
+ if n <= 0 or not self._file_open or not self._read_started or self._async_pending:
1084
+ return b""
1085
+ st = self.read_status()
1086
+ if st is None:
1087
+ self._last_error = MicroSDExpError.NO_MODULE
1088
+ return b""
1089
+ if st.state == protocol.MICROSDEXP_ST_ERROR:
1090
+ self._last_error = MicroSDExpError.CARD_ERR
1091
+ return b""
1092
+ if st.tx_avail == 0:
1093
+ return b""
1094
+ want = min(st.tx_avail, n, self._read_chunk)
1095
+ try:
1096
+ with self._device:
1097
+ got = bytearray(want)
1098
+ self._device.write_then_readinto(
1099
+ bytes([protocol.MICROSDEXP_CMD_READ]), got
1100
+ )
1101
+ got_bytes = bytes(got)
1102
+ except OSError:
1103
+ self._last_error = MicroSDExpError.CARD_ERR
1104
+ got_bytes = b""
1105
+ self._last_error = MicroSDExpError.OK
1106
+ return got_bytes
1107
+
1108
+ def committed_bytes(self):
1109
+ """Committed byte count from one STATUS read (0 on I/O error)."""
1110
+ st = self.read_status()
1111
+ return st.result if st is not None else 0
1112
+
1113
+ # ---- expansion pins + bit-bang engine ----
1114
+ def set_pin_mode(self, pin, mode):
1115
+ """Put an expansion pin in ``mode`` (0 = digital output).
1116
+
1117
+ Applies immediately in RAM. Modes persist to the module EEPROM only on
1118
+ an explicit :meth:`save_pin_mode` -- the module never writes EEPROM on a
1119
+ mode change, so repeated identical applies are a library-side no-op. An
1120
+ out-of-range mode is rejected with no bus transaction.
1121
+ """
1122
+ cmd = _PIN_MODE_CMD.get(pin)
1123
+ if cmd is None:
1124
+ self._last_error = MicroSDExpError.INVALID
1125
+ return False
1126
+ # Dedup: only RAM applies, only an explicit save persists, so a
1127
+ # redundant apply writes nothing and never churns the EEPROM.
1128
+ if pin in self._pin_last_mode and self._pin_last_mode[pin] == mode:
1129
+ return True
1130
+ self._pin_last_mode[pin] = mode
1131
+ return self._write(bytes([cmd, mode & 0xFF]))
1132
+
1133
+ def save_pin_mode(self):
1134
+ """Persist the configured pin modes + I2C address to module EEPROM.
1135
+
1136
+ Sends CMD_SAVEEEPROM (0x1A): STOP only, no payload. Pin modes already
1137
+ took effect in RAM via :meth:`set_pin_mode`; this writes them to EEPROM
1138
+ so they survive a reset/power loss. This is the only command that
1139
+ persists -- call it once when configuration is final to avoid wearing
1140
+ the EEPROM on dev-loop churn.
1141
+ """
1142
+ return self._write(bytes([protocol.MICROSDEXP_CMD_SAVEEEPROM]))
1143
+
1144
+ def write_pin(self, pin, value):
1145
+ """Drive an output-mode expansion pin.
1146
+
1147
+ In digital mode zero is low and any nonzero value is high. In PWM mode
1148
+ the same byte is the duty; prefer :meth:`pwm_write` for that.
1149
+ """
1150
+ cmd = _PIN_CONTROL_CMD.get(pin)
1151
+ if cmd is None:
1152
+ self._last_error = MicroSDExpError.INVALID
1153
+ return False
1154
+ return self._write(bytes([cmd, value & 0xFF]))
1155
+
1156
+ def pwm_write(self, pin, duty):
1157
+ """Set PWM duty 0..255 on a pin already in PWM mode.
1158
+
1159
+ PA0 has no PWM; PB3 is threshold-only. PA5, PB2, PA1 and PA4 give
1160
+ true timer PWM when present on your board variant.
1161
+ """
1162
+ if pin not in _PWM_PINS or not (0 <= duty <= 255):
1163
+ self._last_error = MicroSDExpError.INVALID
1164
+ return False
1165
+ cmd = _PIN_CONTROL_CMD[pin]
1166
+ return self._write(bytes([cmd, duty]))
1167
+
1168
+ def bitbang_set_mode(self, pin):
1169
+ """Select the bit-bang engine's data pin (PA5 / PB2 / PB3).
1170
+
1171
+ This only selects the pin for the engine; it does not set its
1172
+ direction -- call :meth:`set_pin_mode` first.
1173
+ """
1174
+ if pin not in _PIN_IDS:
1175
+ self._last_error = MicroSDExpError.INVALID
1176
+ return False
1177
+ return self._write(bytes([protocol.MICROSDEXP_CMD_BITBANG_SET_MODE, pin]))
1178
+
1179
+ def bitbang_buffer(self, offset, data, length=None):
1180
+ """Copy bytes into the module's 256 B workspace at ``offset``.
1181
+
1182
+ Long payloads are split into ``config.BITBANG_MAX``-sized writes:
1183
+ the 3-byte header and the payload must travel in one transaction.
1184
+ A request that leaves the 256 B workspace is rejected locally with
1185
+ ``MicroSDExpError.INVALID`` instead of relying on the module to drop
1186
+ the extra bytes.
1187
+ """
1188
+ if not data:
1189
+ self._last_error = MicroSDExpError.INVALID
1190
+ return False
1191
+ buf = bytes(data)
1192
+ count = len(buf) if length is None else min(int(length), len(buf))
1193
+ if (
1194
+ count <= 0
1195
+ or offset < 0
1196
+ or offset >= protocol.BITBANG_WORKSPACE_SIZE
1197
+ or (offset + count) > protocol.BITBANG_WORKSPACE_SIZE
1198
+ ):
1199
+ self._last_error = MicroSDExpError.INVALID
1200
+ return False
1201
+ sent = 0
1202
+ while sent < count:
1203
+ chunk = count - sent
1204
+ if chunk > config.BITBANG_MAX:
1205
+ chunk = config.BITBANG_MAX
1206
+ at = offset + sent
1207
+ payload = bytes(
1208
+ [
1209
+ protocol.MICROSDEXP_CMD_BITBANG_BUFFER,
1210
+ at & 0xFF,
1211
+ (at >> 8) & 0xFF,
1212
+ chunk,
1213
+ ]
1214
+ ) + buf[sent : sent + chunk]
1215
+ if not self._write(payload):
1216
+ return False
1217
+ sent += chunk
1218
+ return True
1219
+
1220
+ def bitbang_execute(self, profile):
1221
+ """Run a bit-bang profile (0x01 NeoPixel, 0x02 script).
1222
+
1223
+ The module plays it from its own loop with interrupts masked, so
1224
+ it serves no I2C until the blit or script finishes.
1225
+ """
1226
+ return self._write(bytes([protocol.MICROSDEXP_CMD_BITBANG_EXECUTE, profile & 0xFF]))
1227
+
1228
+ def bitbang_clear(self):
1229
+ """Zero the workspace and the module's buffered-length mark."""
1230
+ self._write(bytes([protocol.MICROSDEXP_CMD_BITBANG_CLEAR]))
1231
+
1232
+ def show_neopixels(self, pin, grb, pixel_count=None):
1233
+ """Push a WS2812B frame (raw GRB triplets) and latch it.
1234
+
1235
+ ``grb`` holds three bytes per pixel, green first; ``pixel_count``
1236
+ defaults to ``len(grb) // 3``. A frame holds at most 85 pixels
1237
+ (255 of the 256 B workspace).
1238
+
1239
+ The pin must already be a digital output
1240
+ (``set_pin_mode(pin, 0)``), and the sketch must leave a frame time
1241
+ (~30 us/pixel plus the latch reset) before the next I2C command --
1242
+ the module clocks the frame out after it ACKs the execute.
1243
+ """
1244
+ if not grb:
1245
+ self._last_error = MicroSDExpError.INVALID
1246
+ return False
1247
+ buf = bytes(grb)
1248
+ count = len(buf) // 3 if pixel_count is None else int(pixel_count)
1249
+ if count <= 0 or count * 3 > 255:
1250
+ self._last_error = MicroSDExpError.INVALID
1251
+ return False
1252
+ if not self.bitbang_set_mode(pin):
1253
+ return False
1254
+ if not self.bitbang_buffer(0, buf[: count * 3]):
1255
+ return False
1256
+ return self.bitbang_execute(protocol.MICROSDEXP_BITBANG_PROFILE_NEOPIXEL)
1257
+
1258
+ # ---- software RTC for FAT file timestamps ----
1259
+ def set_clock(self, year, month, day, hour, minute, second):
1260
+ """Set the module's software RTC used for FAT file timestamps.
1261
+
1262
+ The module stores one 6-byte value via CMD_CLOCK (0x0E)::
1263
+
1264
+ [year-2000, month, day, hour, minute, second]
1265
+
1266
+ STOP applies the write. This is a software RTC used for FAT file
1267
+ timestamps; it keeps advancing once set. Set a realistic value at
1268
+ startup for correct file creation/modification times. The calendar
1269
+ ``year`` is converted to ``year - 2000`` on the wire (years 2000..2255).
1270
+ Out-of-range fields are rejected locally with ``INVALID`` and no bus
1271
+ transaction.
1272
+
1273
+ Returns True on ACK, False on NACK or invalid input.
1274
+ """
1275
+ values = (year, month, day, hour, minute, second)
1276
+ for value in values:
1277
+ if not isinstance(value, int) or isinstance(value, bool):
1278
+ self._last_error = MicroSDExpError.INVALID
1279
+ return False
1280
+ if not (
1281
+ 2000 <= year <= 2255
1282
+ and 1 <= month <= 12
1283
+ and 1 <= day <= 31
1284
+ and 0 <= hour <= 23
1285
+ and 0 <= minute <= 59
1286
+ and 0 <= second <= 59
1287
+ ):
1288
+ self._last_error = MicroSDExpError.INVALID
1289
+ return False
1290
+ ok = self._write(
1291
+ bytes(
1292
+ [
1293
+ protocol.MICROSDEXP_CMD_CLOCK,
1294
+ year - 2000,
1295
+ month,
1296
+ day,
1297
+ hour,
1298
+ minute,
1299
+ second,
1300
+ ]
1301
+ )
1302
+ )
1303
+ self._last_error = MicroSDExpError.OK if ok else MicroSDExpError.NO_MODULE
1304
+ return ok
1305
+
1306
+ def read_clock(self):
1307
+ """Return ``(year, month, day, hour, minute, second)``, or ``None``.
1308
+
1309
+ Reads the same 6 bytes CMD_CLOCK (0x0E) answers and converts the year
1310
+ back from ``year-2000``. On a short frame (or bus error) returns
1311
+ ``None`` with ``INVALID``. The value is static — it does not advance
1312
+ with real time.
1313
+ """
1314
+ buf = bytearray(6)
1315
+ if self._write_then_read(bytes([protocol.MICROSDEXP_CMD_CLOCK]),
1316
+ 6, buf) < 6:
1317
+ self._last_error = MicroSDExpError.INVALID
1318
+ return None
1319
+ self._last_error = MicroSDExpError.OK
1320
+ return (buf[0] + 2000, buf[1], buf[2], buf[3], buf[4], buf[5])
1321
+
1322
+ def set_clock_time(self, year, month, day, hour, minute, second):
1323
+ """Deprecated alias of :meth:`set_clock`."""
1324
+ return self.set_clock(year, month, day, hour, minute, second)
1325
+
1326
+ def reboot(self):
1327
+ ok = self._write(bytes([protocol.MICROSDEXP_CMD_REBOOT]))
1328
+ # The module drops every in-flight op on reset; an abandoned token
1329
+ # must not leave _async_pending set forever.
1330
+ self.reset_async_state()
1331
+ self._last_error = MicroSDExpError.OK if ok else MicroSDExpError.NO_MODULE
1332
+
1333
+ def format(self, mode=0):
1334
+ """Explicit-only format (no token — guards live in sketch/UI)."""
1335
+ if self._async_pending:
1336
+ self._last_error = MicroSDExpError.INVALID
1337
+ return False
1338
+ if mode > 1:
1339
+ self._last_error = MicroSDExpError.INVALID
1340
+ return False
1341
+ st = self.read_status()
1342
+ done_before = st.op_done if st is not None else 0
1343
+ if not self._write(bytes([protocol.MICROSDEXP_CMD_FORMAT, mode & 0xFF])):
1344
+ return False
1345
+ # A full FAT rebuild takes tens of seconds on a multi-GB card, so it
1346
+ # waits on its own 300 s budget instead of OP_TIMEOUT_MS.
1347
+ err = self.wait_for_op_complete(done_before, config.FORMAT_TIMEOUT_MS,
1348
+ scale=False)
1349
+ if err != 0:
1350
+ self._last_error = MicroSDExpError.TIMEOUT if err == -1 else MicroSDExpError.CARD_ERR
1351
+ return False
1352
+ self._last_error = MicroSDExpError.OK
1353
+ return True
1354
+
1355
+ def list_dir(self, path, max_entries=64):
1356
+ """Enumerate a directory via the 0x08 TX-stream.
1357
+
1358
+ Stream: 'F'/'D' + NUL basename + 4 B size LE; 0xFF terminates.
1359
+ Returns a list of DirEntry (capped at max_entries)."""
1360
+ if not self.valid_path(path) or max_entries == 0:
1361
+ return []
1362
+ st = self.read_status()
1363
+ done_before = st.op_done if st is not None else 0
1364
+ if not self._submit_filename(path):
1365
+ return []
1366
+ if not self._write(bytes([protocol.MICROSDEXP_CMD_LIST_DIR])):
1367
+ return []
1368
+ if self.wait_for_op_complete(done_before) != 0:
1369
+ self._barrier_close_flush()
1370
+ return []
1371
+ stchk = self.read_status()
1372
+ if stchk is not None and stchk.state == protocol.MICROSDEXP_ST_ERROR:
1373
+ self._barrier_close_flush()
1374
+ return []
1375
+
1376
+ entries = []
1377
+ p_type, p_name, p_size = 0, 1, 2
1378
+ pstate = p_type
1379
+ is_dir = False
1380
+ sz_acc = 0
1381
+ sz_idx = 0
1382
+ name = bytearray()
1383
+ finished = False
1384
+ t0 = time.monotonic()
1385
+ limit = self.scale_timeout(config.COMMIT_TIMEOUT_MS) / 1000.0
1386
+
1387
+ while not finished:
1388
+ if (time.monotonic() - t0) >= limit:
1389
+ self._last_error = MicroSDExpError.TIMEOUT
1390
+ break
1391
+ st = self.read_status()
1392
+ if st is None:
1393
+ time.sleep(self._poll_ms / 1000.0)
1394
+ continue
1395
+ if st.state == protocol.MICROSDEXP_ST_ERROR:
1396
+ self._last_error = MicroSDExpError.CARD_ERR
1397
+ entries = []
1398
+ break
1399
+ if st.tx_avail > 0:
1400
+ want = min(st.tx_avail, len(self._shared))
1401
+ n = self._write_then_read(bytes([protocol.MICROSDEXP_CMD_READ]), want, self._shared)
1402
+ for i in range(n):
1403
+ if finished:
1404
+ break
1405
+ b = self._shared[i]
1406
+ if pstate == p_type:
1407
+ if b == protocol.LIST_END:
1408
+ finished = True
1409
+ elif b == 0x46 or b == 0x44: # 'F'/'D'
1410
+ is_dir = b == 0x44
1411
+ name = bytearray()
1412
+ sz_acc = 0
1413
+ sz_idx = 0
1414
+ pstate = p_name
1415
+ else:
1416
+ finished = True # corrupt stream
1417
+ elif pstate == p_name:
1418
+ if b == 0x00:
1419
+ pstate = p_size
1420
+ else:
1421
+ if len(name) < 63:
1422
+ name.append(b)
1423
+ else: # p_size
1424
+ sz_acc |= b << (8 * sz_idx)
1425
+ sz_idx += 1
1426
+ if sz_idx >= 4:
1427
+ if len(entries) < max_entries:
1428
+ entries.append(
1429
+ DirEntry(
1430
+ is_dir=is_dir,
1431
+ name=bytes(name).decode("ascii", "replace"),
1432
+ size=0 if is_dir else sz_acc,
1433
+ )
1434
+ )
1435
+ pstate = p_type
1436
+ continue
1437
+ if st.state == protocol.MICROSDEXP_ST_COMPLETE:
1438
+ break
1439
+ time.sleep(self._poll_ms / 1000.0)
1440
+
1441
+ preserved = self._last_error
1442
+ self._barrier_close_flush()
1443
+ # Preserve a drain error across the barrier (barrier resets lastError).
1444
+ if self._last_error == MicroSDExpError.OK and preserved != MicroSDExpError.OK:
1445
+ self._last_error = preserved
1446
+ return entries
1447
+
1448
+ # ---- async file core ----
1449
+ def open_append(self, path):
1450
+ """Legacy append (0x04). No module OPEN: each 64 B chunk of write()
1451
+ becomes one APPEND transaction (0x01 + 0x04 + payload), committed
1452
+ before the next chunk. A multi-chunk write is not transactional."""
1453
+ if not self.valid_path(path):
1454
+ return False
1455
+ self._append_path = path
1456
+ self._append_mode = True
1457
+ self._file_open = True
1458
+ self._read_started = False
1459
+ self._written = 0
1460
+ self._last_error = MicroSDExpError.OK
1461
+ self._last_active = time.monotonic()
1462
+ return True
1463
+
1464
+ def _append_chunk(self, data):
1465
+ st = self.read_status()
1466
+ done_before = st.op_done if st is not None else 0
1467
+ if not self._submit_filename(self._append_path):
1468
+ return False
1469
+ if not self._write(bytes([protocol.MICROSDEXP_CMD_APPEND_FILE]) + bytes(data)):
1470
+ return False
1471
+ err = self.wait_for_op_complete(done_before)
1472
+ if err != 0:
1473
+ self._last_error = MicroSDExpError.TIMEOUT if err == -1 else MicroSDExpError.CARD_ERR
1474
+ return False
1475
+ self._last_error = MicroSDExpError.OK
1476
+ return True
1477
+
1478
+ def _open_via_cmd(self, cmd, path):
1479
+ if self._async_pending:
1480
+ self._last_error = MicroSDExpError.INVALID
1481
+ return False
1482
+ if not self.valid_path(path):
1483
+ return False
1484
+ self._append_mode = False
1485
+ try:
1486
+ raw = path.encode("ascii") + b"\x00"
1487
+ except (UnicodeEncodeError, AttributeError):
1488
+ self._last_error = MicroSDExpError.INVALID
1489
+ return False
1490
+ for _attempt in range(6):
1491
+ self._barrier_close_flush()
1492
+ st = self.read_status()
1493
+ done_before = st.op_done if st is not None else 0
1494
+ if not self._write(bytes([cmd]) + raw):
1495
+ time.sleep(0.2)
1496
+ continue
1497
+ err = self.wait_for_op_complete(done_before)
1498
+ if err == 0:
1499
+ st2 = self.read_status()
1500
+ self._base_written = st2.result if st2 is not None else 0
1501
+ self._file_open = True
1502
+ self._read_started = False
1503
+ self._written = 0
1504
+ self._last_error = MicroSDExpError.OK
1505
+ return True
1506
+ self._last_error = MicroSDExpError.TIMEOUT if err == -1 else MicroSDExpError.OPEN_FAIL
1507
+ time.sleep(0.2)
1508
+ self._file_open = False
1509
+ return False
1510
+
1511
+ def open_write(self, path):
1512
+ """OPEN_WRITE (truncate). 6 attempts, first barrier unconditional."""
1513
+ return self._open_via_cmd(protocol.MICROSDEXP_CMD_OPEN_WRITE, path)
1514
+
1515
+ def open_read(self, path):
1516
+ """OPEN_READ + prime the TX stream (0x23 with STOP)."""
1517
+ if not self._open_via_cmd(protocol.MICROSDEXP_CMD_OPEN_READ, path):
1518
+ return False
1519
+ # Prime the read stream (C++ openRead does this STOP).
1520
+ if not self._write(bytes([protocol.MICROSDEXP_CMD_READ])):
1521
+ self._last_error = MicroSDExpError.NO_FILE
1522
+ self._read_started = True
1523
+ st = self.read_status()
1524
+ if st is not None:
1525
+ self._base_written = st.result
1526
+ self._last_error = MicroSDExpError.OK
1527
+ return True
1528
+
1529
+ def write(self, data):
1530
+ """Flow-paced push. Returns bytes accepted."""
1531
+ if not data:
1532
+ self._last_error = MicroSDExpError.OK # zero-length is a no-op
1533
+ return 0
1534
+ if self._async_pending:
1535
+ self._last_error = MicroSDExpError.INVALID
1536
+ return 0
1537
+ if not data or not self._file_open:
1538
+ if not self._file_open:
1539
+ self._last_error = MicroSDExpError.NO_FILE
1540
+ return 0
1541
+ if self._append_mode:
1542
+ off = 0
1543
+ buf = bytes(data)
1544
+ while off < len(buf):
1545
+ chunk = buf[off : off + config.CHUNK_BYTES]
1546
+ if not self._append_chunk(chunk):
1547
+ self._written += off
1548
+ return off
1549
+ off += len(chunk)
1550
+ self._written += off
1551
+ self._last_error = MicroSDExpError.OK
1552
+ return off
1553
+ buf = bytes(data)
1554
+ off = 0
1555
+ while off < len(buf):
1556
+ chunk = buf[off : off + config.CHUNK_BYTES]
1557
+ if not self._push_write_block(bytearray(chunk)):
1558
+ self._written += off
1559
+ return off
1560
+ off += len(chunk)
1561
+ self._written += off
1562
+ self._last_error = MicroSDExpError.OK
1563
+ return off
1564
+
1565
+ def _push_write_block(self, chunk):
1566
+ max_attempts = 1200 if 0 < self.scl_hz < 50000 else 400
1567
+ for _attempt in range(max_attempts):
1568
+ st = self.read_status()
1569
+ if st is None:
1570
+ time.sleep(self._flow_poll_ms / 1000.0)
1571
+ continue
1572
+ if st.state == protocol.MICROSDEXP_ST_ERROR:
1573
+ self._last_error = MicroSDExpError.CARD_ERR
1574
+ return False
1575
+ if st.rx_free < len(chunk):
1576
+ time.sleep(self._flow_poll_ms / 1000.0)
1577
+ continue
1578
+ if self._write(bytes([protocol.MICROSDEXP_CMD_WRITE]) + bytes(chunk)):
1579
+ return True
1580
+ time.sleep(0.001)
1581
+ self._last_error = MicroSDExpError.TIMEOUT
1582
+ return False
1583
+
1584
+ def read(self, n):
1585
+ """Read up to n bytes. Returns bytes (short at EOF)."""
1586
+ if n == 0:
1587
+ self._last_error = MicroSDExpError.OK # zero-length is a no-op
1588
+ return b""
1589
+ if self._async_pending:
1590
+ self._last_error = MicroSDExpError.INVALID
1591
+ return b""
1592
+ if n == 0 or not self._file_open:
1593
+ if not self._file_open:
1594
+ self._last_error = MicroSDExpError.NO_FILE
1595
+ return b""
1596
+ if self._append_mode:
1597
+ self._last_error = MicroSDExpError.INVALID
1598
+ return b""
1599
+ out = bytearray()
1600
+ t0 = time.monotonic()
1601
+ limit = self.scale_timeout(config.COMMIT_TIMEOUT_MS) / 1000.0
1602
+ while len(out) < n:
1603
+ if (time.monotonic() - t0) >= limit:
1604
+ self._last_error = MicroSDExpError.TIMEOUT
1605
+ break
1606
+ st = self.read_status()
1607
+ if st is None:
1608
+ time.sleep(self._poll_ms / 1000.0)
1609
+ continue
1610
+ if st.state == protocol.MICROSDEXP_ST_ERROR:
1611
+ self._last_error = MicroSDExpError.CARD_ERR
1612
+ break
1613
+ if st.tx_avail > 0:
1614
+ want = min(st.tx_avail, n - len(out), self._read_chunk)
1615
+ try:
1616
+ with self._device:
1617
+ got = bytearray(want)
1618
+ self._device.write_then_readinto(
1619
+ bytes([protocol.MICROSDEXP_CMD_READ]), got
1620
+ )
1621
+ out.extend(got)
1622
+ self._last_active = time.monotonic()
1623
+ continue
1624
+ except OSError:
1625
+ if want > 128:
1626
+ # This port caps one bus transaction below the
1627
+ # configured chunk (nRF TWIM is 255 B). Drop to the
1628
+ # always-safe 128 B and retry the drain.
1629
+ self._read_chunk = 128
1630
+ continue
1631
+ self._last_error = MicroSDExpError.CARD_ERR
1632
+ break
1633
+ if st.state == protocol.MICROSDEXP_ST_COMPLETE:
1634
+ break
1635
+ time.sleep(self._poll_ms / 1000.0)
1636
+ else:
1637
+ pass
1638
+ self._last_error = MicroSDExpError.OK if len(out) > 0 else self._last_error
1639
+ if len(out) == n:
1640
+ self._last_error = MicroSDExpError.OK
1641
+ self._written = len(out)
1642
+ return bytes(out)
1643
+
1644
+ def sync(self):
1645
+ if self._async_pending:
1646
+ self._last_error = MicroSDExpError.INVALID
1647
+ return False
1648
+ if not self._file_open or self._append_mode or self._read_started:
1649
+ return True
1650
+ target = self._base_written + self._written
1651
+ ok = self.wait_for_committed(target)
1652
+ self._last_error = MicroSDExpError.OK if ok else MicroSDExpError.TIMEOUT
1653
+ return ok
1654
+
1655
+ def close(self):
1656
+ if self._async_pending:
1657
+ self._last_error = MicroSDExpError.INVALID
1658
+ return False
1659
+ if not self._file_open:
1660
+ return True
1661
+ if self._append_mode:
1662
+ self._file_open = False
1663
+ self._append_mode = False
1664
+ self._read_started = False
1665
+ self._last_error = MicroSDExpError.OK
1666
+ return True
1667
+ ok = self.sync()
1668
+ st = self.read_status()
1669
+ db = st.op_done if st is not None else 0
1670
+ if not self._write(bytes([protocol.MICROSDEXP_CMD_CLOSE_FLUSH])):
1671
+ self._last_error = MicroSDExpError.CARD_ERR
1672
+ self._file_open = False
1673
+ self._read_started = False
1674
+ return False
1675
+ cw = self.wait_for_op_complete(db)
1676
+ self._file_open = False
1677
+ self._read_started = False
1678
+ if cw != 0:
1679
+ self._last_error = MicroSDExpError.TIMEOUT if cw == -1 else MicroSDExpError.CARD_ERR
1680
+ return False
1681
+ self._last_error = MicroSDExpError.OK
1682
+ return ok
1683
+
1684
+ # ---- One-shot file helpers -----------------------------------------------
1685
+ def write_file(self, path, data):
1686
+ """Create/truncate, write, commit and close in one call."""
1687
+ if not self.open_write(path):
1688
+ return False
1689
+ data = bytes(bytearray(data)) if data else b""
1690
+ if data and self.write(data) != len(data):
1691
+ self.close()
1692
+ return False
1693
+ return self.close()
1694
+
1695
+ def write_text(self, path, text):
1696
+ """One-shot write of a string (no length argument)."""
1697
+ return self.write_file(path, text.encode("utf-8") if isinstance(text, str) else bytes(text))
1698
+
1699
+ def append_file(self, path, data):
1700
+ """Append bytes in 64 B committed chunks.
1701
+
1702
+ Each chunk is committed and closed independently, so no ``close()``
1703
+ is needed. This is not a transaction for the whole buffer: a failure
1704
+ part-way leaves the earlier chunks in the file and returns ``False``.
1705
+ """
1706
+ if not self.open_append(path):
1707
+ return False
1708
+ data = bytes(bytearray(data)) if data else b""
1709
+ if data and self.write(data) != len(data):
1710
+ self.close()
1711
+ return False
1712
+ return self.close()
1713
+
1714
+ def append_text(self, path, text):
1715
+ """One-shot append of a string (no length argument)."""
1716
+ return self.append_file(path, text.encode("utf-8") if isinstance(text, str) else bytes(text))
1717
+
1718
+ # ---- File-style helpers (mirror C++ openFile) ----
1719
+ def open(self, path, mode="r"):
1720
+ """``open(path, "r"|"w"|"a")`` -> MicroSDExpFile or None.
1721
+
1722
+ Mode is the first char (``r`` read, ``w`` write/truncate, ``a``
1723
+ append via legacy 0x04). Mirrors the C++ ``openFile()``."""
1724
+ m = (mode or "")[:1].lower()
1725
+ if m == "w":
1726
+ ok = self.open_write(path)
1727
+ elif m == "a":
1728
+ ok = self.open_append(path)
1729
+ elif m == "r":
1730
+ ok = self.open_read(path)
1731
+ else:
1732
+ return None
1733
+ if not ok:
1734
+ return None
1735
+ return MicroSDExpFile(self, mode_code={"r": 0, "w": 1, "a": 2}.get(m, 0))
1736
+
1737
+
1738
+ class MicroSDExpFile:
1739
+ """Single-file handle (module is single-file). Context-manager ready."""
1740
+
1741
+ def __init__(self, microSDexp, mode_code=0):
1742
+ self._microSDexp = microSDexp
1743
+ self._open = True
1744
+ self.mode = mode_code # 0=r, 1=w, 2=a
1745
+ self.nil = False
1746
+
1747
+ @property
1748
+ def microSDexp(self):
1749
+ return self._microSDexp
1750
+
1751
+ @property
1752
+ def is_open(self):
1753
+ return self._open
1754
+
1755
+ def write(self, data):
1756
+ if not self._open or self._microSDexp is None:
1757
+ return 0
1758
+ n = self._microSDexp.write(bytes(data))
1759
+ return n
1760
+
1761
+ def read(self, n):
1762
+ if not self._open or self._microSDexp is None:
1763
+ return b""
1764
+ return self._microSDexp.read(n)
1765
+
1766
+ def sync(self):
1767
+ if not self._open or self._microSDexp is None:
1768
+ return False
1769
+ return self._microSDexp.sync()
1770
+
1771
+ def close(self):
1772
+ if not self._open or self._microSDexp is None:
1773
+ return False
1774
+ ok = self._microSDexp.close()
1775
+ self._open = False
1776
+ return ok
1777
+
1778
+ def __enter__(self):
1779
+ return self
1780
+
1781
+ def __exit__(self, *args):
1782
+ if self._open:
1783
+ self.close()
1784
+ return False
1785
+
1786
+
1787
+ def open_file(microSDexp, path, mode="r"):
1788
+ """Module helper mirroring C++ ``openFile(&microSDexp, path, "r"|"w"|"a")``."""
1789
+ return microSDexp.open(path, mode)
1790
+
1791
+
1792
+
1793
+
1794
+