-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
216 lines (170 loc) · 6.47 KB
/
main.py
File metadata and controls
216 lines (170 loc) · 6.47 KB
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
import gc
import machine
import sdcard
import os
import uos
from microdot import Microdot, send_file, Request, redirect
from network import WLAN
from inky_helper import network_connect
from WIFI_CONFIG import SSID, PSK
import jpegdec
from picographics import PicoGraphics, DISPLAY_INKY_FRAME_7 as DISPLAY # 7.3"
app = Microdot()
Request.max_content_length = 1024 * 1024 # 1MB (change as needed)
def display_image(filename):
graphics = PicoGraphics(DISPLAY)
WIDTH, HEIGHT = graphics.get_bounds()
jpeg = jpegdec.JPEG(graphics)
gc.collect()
graphics.set_pen(1)
graphics.clear()
jpeg.open_file(filename)
jpeg.decode()
graphics.update()
@app.route("/")
async def index(request):
path = f"/html/index.html"
return send_file(path)
@app.route("/static/<path:path>")
async def static(request, path):
if ".." in path:
# directory traversal is not allowed
return "Not found", 404
return send_file("/sd/pics/" + path)
@app.post("/upload")
async def upload(request):
print("=== Starting file upload ===")
# Get the Content-Type header to extract boundary
content_type = request.headers.get("Content-Type", "")
if not content_type.startswith("multipart/form-data"):
return "Invalid content type", 400
# Extract boundary from Content-Type header
try:
boundary = content_type.split("boundary=")[1].encode()
except:
return "Could not find form boundary", 400
print(f"Form boundary: {boundary}")
# ensure the pics directory exists
try:
os.mkdir("/sd/pics")
print("Created pics directory")
except OSError:
print("Pics directory already exists")
temp_path = "/sd/pics/temp.jpg"
final_path = "/sd/pics/photo.jpg"
try:
# Write to a temporary file first
print(f"Writing to temporary file: {temp_path}")
total_written = 0
with open(temp_path, "wb") as f:
# Skip until we find the file part boundary
while True:
line = await request.stream.readline()
if not line:
return "Could not find file data", 400
if boundary in line:
break
gc.collect()
# Skip headers until we find blank line
while True:
line = await request.stream.readline()
if not line or line.strip() == b"":
break
gc.collect()
# Now we're at the file content
buffer = b"" # Buffer to handle boundary split across chunks
while True:
chunk = await request.stream.read(1024) # Read 1KB at a time
if not chunk:
break
# Add chunk to our buffer
buffer += chunk
# Look for boundary in combined buffer
boundary_pos = buffer.find(boundary)
if boundary_pos != -1:
# Write only up to the boundary, excluding \r\n--
if (
boundary_pos >= 4
): # Make sure we have enough bytes before boundary
bytes_written = f.write(buffer[: boundary_pos - 4])
total_written += bytes_written
break
else:
# Write everything except the last boundary-length bytes
# (in case the boundary is split across chunks)
safe_length = max(
0, len(buffer) - len(boundary) - 4
) # -4 for potential \r\n--
if safe_length > 0:
bytes_written = f.write(buffer[:safe_length])
total_written += bytes_written
# Keep the remainder in our buffer
buffer = buffer[safe_length:]
if total_written % 10240 == 0: # Log every 10KB
print(f"Progress: {total_written} bytes written")
f.flush()
gc.collect()
print(f"Completed writing {total_written} bytes")
# If we got here without errors, the upload was successful
print("Upload successful, replacing old file")
# Now we can safely remove the old file and rename the new one
try:
os.remove(final_path)
print("Removed old file")
except OSError:
print("No old file to remove")
os.rename(temp_path, final_path)
print("Renamed temporary file to final file")
# Verify the final file
final_size = os.stat(final_path)[6] # Get file size
print(f"Final file size: {final_size} bytes")
gc.collect() # Clean up memory
print("=== Upload completed successfully ===")
display_image(final_path)
return redirect("/")
except Exception as e:
print(f"Error during upload: {str(e)}")
# Clean up the temporary file if something went wrong
try:
os.remove(temp_path)
print("Cleaned up temporary file after error")
except OSError:
print("No temporary file to clean up")
gc.collect()
return "Upload failed: " + str(e), 500
network_connect(SSID, PSK)
print(WLAN().ifconfig())
# prep to save to sdcard
sd_spi = machine.SPI(
0,
sck=machine.Pin(18, machine.Pin.OUT),
mosi=machine.Pin(19, machine.Pin.OUT),
miso=machine.Pin(16, machine.Pin.OUT),
)
sd = sdcard.SDCard(sd_spi, machine.Pin(22))
uos.mount(sd, "/sd")
gc.collect()
# Diagnostic information for SD card
# print("=== SD Card Diagnostic Info ===")
# try:
# stats = os.statvfs("/sd")
# block_size = stats[0]
# total_blocks = stats[2]
# free_blocks = stats[3]
# total_size = block_size * total_blocks
# free_size = block_size * free_blocks
# print(f"Total SD card space: {total_size / 1024 / 1024:.2f} MB")
# print(f"Free SD card space: {free_size / 1024 / 1024:.2f} MB")
# # Check if we can list the root directory
# print("\nSD Card root directory contents:")
# print(os.listdir("/sd"))
# # Check if pics directory exists and is accessible
# try:
# print("\nPics directory contents:")
# print(os.listdir("/sd/pics"))
# except OSError as e:
# print("Pics directory not found or not accessible:", str(e))
# except OSError as e:
# print("Error accessing SD card:", str(e))
# print("============================")
app.run()