Skip to content

Commit 873dc9a

Browse files
committed
sd card works now (in simulator)
1 parent 6fc173f commit 873dc9a

File tree

3 files changed

+87
-209
lines changed

3 files changed

+87
-209
lines changed
Lines changed: 71 additions & 118 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,44 @@
11
# SD Card Stress Test Component
22

3-
import time
43
import os
54
import platform
6-
from ..utils import StressTestError, get_timestamp, format_bytes, safe_file_operation
5+
from ..utils import StressTestError, get_timestamp, safe_file_operation
76

87

98
class SDCardTester:
109
"""SD Card testing component"""
1110

1211
def __init__(self, test_path="/sd/stresstest"):
13-
self.test_path = test_path
12+
# Convert path to proper simulator path if needed
13+
self.test_path = platform.fpath(test_path)
1414
self.initial_data = None
1515

1616
async def initialize(self):
1717
"""Initialize SD card testing"""
1818
try:
19-
print("Testing SD card...")
20-
21-
# Check if SD card is available
22-
if not platform.file_exists("/sd"):
23-
raise StressTestError("SD card not mounted")
24-
19+
# Check if SD card is present
20+
if not platform.sdcard.is_present:
21+
raise StressTestError("SD card not present")
22+
23+
# Check if SD card directory exists and is accessible
24+
sd_path = platform.fpath("/sd")
25+
try:
26+
# Try to list the directory to see if it exists and is accessible
27+
list(os.ilistdir(sd_path))
28+
except OSError as e:
29+
try:
30+
platform.maybe_mkdir(sd_path)
31+
except Exception as create_error:
32+
raise StressTestError("SD card directory not accessible and cannot create: " + str(create_error))
33+
2534
# Create test directory
2635
platform.maybe_mkdir(self.test_path)
27-
36+
2837
# Test basic file operations
2938
sdcard_data = await self._test_sdcard_operations()
3039
self.initial_data = sdcard_data
31-
print("SD card test completed:", repr(sdcard_data))
3240
return True
33-
41+
3442
except Exception as e:
3543
print("WARNING: SD card not available:", str(e))
3644
self.initial_data = None
@@ -39,48 +47,30 @@ async def initialize(self):
3947
async def _test_sdcard_operations(self):
4048
"""Test basic SD card operations"""
4149
try:
42-
print("SD card test: Starting...")
43-
4450
# Test file creation
4551
test_file = self.test_path + "/test_" + get_timestamp() + ".txt"
4652
test_data = "SD card test data: " + get_timestamp()
47-
48-
print("SD card test: Writing file...")
53+
54+
# Write test file
4955
result = safe_file_operation(self._write_test_file, test_file, test_data)
5056
if result is None:
5157
raise StressTestError("Failed to write test file")
52-
53-
print("SD card test: Reading file...")
58+
59+
# Read test file
5460
read_data = safe_file_operation(self._read_test_file, test_file)
5561
if read_data is None:
5662
raise StressTestError("Failed to read test file")
57-
63+
64+
# Compare data
5865
if read_data != test_data:
5966
raise StressTestError("Data mismatch: written != read")
60-
61-
print("SD card test: Checking file stats...")
62-
file_size = safe_file_operation(self._get_file_size, test_file)
63-
64-
print("SD card test: Cleaning up...")
67+
68+
# Clean up
6569
safe_file_operation(self._delete_test_file, test_file)
66-
67-
# Get SD card info
68-
sdcard_info = self._get_sdcard_info()
69-
70-
result = {
71-
"test_file": test_file,
72-
"data_length": len(test_data),
73-
"file_size": file_size,
74-
"sdcard_info": sdcard_info,
75-
"timestamp": get_timestamp(),
76-
"status": "success"
77-
}
78-
79-
print("SD card test: Success")
80-
return result
81-
70+
71+
return test_data
72+
8273
except Exception as e:
83-
print("SD card test: Exception occurred:", str(e))
8474
raise StressTestError("SD card test failed: " + str(e))
8575

8676
def _write_test_file(self, filename, data):
@@ -93,14 +83,32 @@ def _read_test_file(self, filename):
9383
"""Read test data from file"""
9484
with open(filename, 'r') as f:
9585
return f.read()
96-
97-
def _get_file_size(self, filename):
98-
"""Get file size"""
86+
87+
async def _read_sdcard(self):
88+
"""Read SD card data for continuous stress testing"""
9989
try:
100-
stat = os.stat(filename)
101-
return stat[6] # Size is at index 6 in MicroPython
102-
except:
103-
return None
90+
# Create a quick test file and read it back
91+
test_file = self.test_path + "/stress_test_" + get_timestamp() + ".txt"
92+
test_data = self.initial_data # Use the initial data for comparison
93+
94+
# Write and read back the data
95+
result = safe_file_operation(self._write_test_file, test_file, test_data)
96+
if result is None:
97+
raise StressTestError("Failed to write stress test file")
98+
99+
read_data = safe_file_operation(self._read_test_file, test_file)
100+
if read_data is None:
101+
raise StressTestError("Failed to read stress test file")
102+
103+
# Clean up
104+
safe_file_operation(self._delete_test_file, test_file)
105+
106+
return read_data
107+
108+
except Exception as e:
109+
raise StressTestError("SD card stress read failed: " + str(e))
110+
111+
104112

105113
def _delete_test_file(self, filename):
106114
"""Delete test file"""
@@ -110,96 +118,42 @@ def _delete_test_file(self, filename):
110118
except:
111119
return False
112120

113-
def _get_sdcard_info(self):
114-
"""Get SD card information"""
115-
try:
116-
# Get filesystem stats
117-
if hasattr(os, 'statvfs'):
118-
stats = os.statvfs('/sd')
119-
block_size = stats[0]
120-
total_blocks = stats[2]
121-
free_blocks = stats[3]
122-
123-
total_space = block_size * total_blocks
124-
free_space = block_size * free_blocks
125-
used_space = total_space - free_space
126-
127-
return {
128-
"total_space": total_space,
129-
"free_space": free_space,
130-
"used_space": used_space,
131-
"total_formatted": format_bytes(total_space),
132-
"free_formatted": format_bytes(free_space),
133-
"used_formatted": format_bytes(used_space)
134-
}
135-
else:
136-
return {"status": "statvfs not available"}
137-
except Exception as e:
138-
return {"error": str(e)}
121+
139122

140123
async def test_sdcard_performance(self, iterations=5, data_size=1024):
141124
"""Test SD card performance with multiple operations"""
142125
if not self.is_available():
143126
return {"status": "skipped", "reason": "SD card not available"}
144-
145-
results = []
127+
146128
successful_operations = 0
147-
129+
148130
for i in range(iterations):
149131
try:
150-
print("SD card test iteration", i + 1, "of", iterations)
151-
start_time = time.time()
152-
153132
# Create test data
154133
test_data = "x" * data_size
155134
test_file = self.test_path + "/perf_test_" + str(i) + "_" + get_timestamp() + ".txt"
156-
135+
157136
# Write test
158-
write_start = time.time()
159137
safe_file_operation(self._write_test_file, test_file, test_data)
160-
write_time = time.time() - write_start
161-
138+
162139
# Read test
163-
read_start = time.time()
164140
read_data = safe_file_operation(self._read_test_file, test_file)
165-
read_time = time.time() - read_start
166-
141+
167142
# Cleanup
168143
safe_file_operation(self._delete_test_file, test_file)
169-
170-
end_time = time.time()
171-
total_duration = end_time - start_time
172-
144+
173145
# Verify data integrity
174-
data_ok = (read_data == test_data) if read_data else False
175-
176-
results.append({
177-
"iteration": i + 1,
178-
"status": "success" if data_ok else "data_error",
179-
"data_size": data_size,
180-
"write_time": write_time,
181-
"read_time": read_time,
182-
"total_duration": total_duration,
183-
"data_integrity": data_ok
184-
})
185-
186-
if data_ok:
146+
if read_data == test_data:
187147
successful_operations += 1
188-
189-
except Exception as e:
190-
results.append({
191-
"iteration": i + 1,
192-
"status": "failed",
193-
"error": str(e)
194-
})
195-
148+
149+
except Exception:
150+
pass # Count as failed iteration
151+
196152
return {
197153
"status": "completed",
198154
"total_iterations": iterations,
199155
"successful_operations": successful_operations,
200-
"success_rate": (successful_operations / iterations) * 100,
201-
"data_size": data_size,
202-
"results": results
156+
"success_rate": (successful_operations / iterations) * 100
203157
}
204158

205159
def is_available(self):
@@ -216,6 +170,5 @@ def cleanup(self):
216170
"""Clean up test files and directories"""
217171
try:
218172
platform.delete_recursively(self.test_path)
219-
print("SD card test cleanup completed")
220-
except Exception as e:
221-
print("SD card cleanup failed:", str(e))
173+
except Exception:
174+
pass

src/stresstest/core.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -250,16 +250,28 @@ async def _test_component_continuously(self, component_name, tester):
250250
print("Storage read error:", str(e))
251251

252252
elif component_name == 'sdcard':
253-
if self.initial_values.get('sdcard') is None:
253+
print("DEBUG: Testing SD card component")
254+
# Check if SD card was successfully initialized
255+
if not self.initial_values.get('sd_card'):
256+
print("DEBUG: SD card not initialized, skipping")
254257
return
255258

259+
# Use the actual initial data from the tester
260+
initial_value = tester.initial_data
261+
if initial_value is None:
262+
print("DEBUG: SD card initial data is None, skipping")
263+
return
264+
265+
print("DEBUG: SD card initial data:", repr(initial_value))
256266
try:
257267
current_data = await tester._read_sdcard()
258268
self.statistics['sdcard_reads'] += 1
269+
print("DEBUG: SD card read successful, count now:", self.statistics['sdcard_reads'])
259270

260271
# Compare with initial value (like original stress test)
261-
if current_data != self.initial_values.get('sdcard'):
272+
if current_data != initial_value:
262273
self.statistics['mismatches'] += 1
274+
print("DEBUG: SD card data mismatch - expected:", repr(initial_value), "got:", repr(current_data))
263275

264276
except Exception as e:
265277
self.statistics['sdcard_errors'] += 1

0 commit comments

Comments
 (0)