Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
336 lines (305 loc) · 13 KB
/
Copy pathmain.py
File metadata and controls
336 lines (305 loc) · 13 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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
import sys, wifi, socketpool, time, os, json, microcontroller, ampule, gc
import load_settings
import digitalio, board
import adafruit_connection_manager, adafruit_requests
settings = load_settings.settings()
import load_screen
from load_screen import *
from check_button import *
import patches
import storage
if "apps" in os.listdir():
for file in os.listdir("apps"):
try: os.rename("apps/" + file, file)
except: pass
try: os.rmdir("apps")
except: pass
# Logo: rows 1-2 of the panel (y 1..12), left-aligned on every screen.
# "Matrix" (font_small, bright white) and "BOX" (font_large, orange; red while
# the filesystem is read-only). Words are placed by their ink, so the blank
# rows in the glyph cells don't push the logo out of its band.
_LOGO_BAND_TOP = 1
_LOGO_BAND_H = 12
_LOGO_DROP = (-9, -5, -2, 0, 1, 0) # BOX letter y-offsets while falling; the 1 px overshoot settles
_LOGO_STAGGER = 4 # frames between one BOX letter starting its drop and the next
_LOGO_SLIDE = 8 # frames for "Matrix" to slide in from the left
_LOGO_FRAME_S = 0.05
_LOGO_MATRIX_COLOR = 2 # brightwhite
_LOGO_BOX_COLOR = 11 # orange (palette index, matches the website)
_LOGO_RO_COLOR = 4 # red
_LOGO_UP = 1 # pixels the logo sits above the centre of its band (leaves the row below clearer)
def _logo_ink(font, text):
"""(top, bottom) pixel rows that have ink in text, relative to the glyph origin."""
top, bottom = font["fontheight"], -1
for ch in text:
if ch not in font:
continue
g = font[ch]
for h in range(font["fontheight"]):
bits = g[h + 1]
if isinstance(bits, int) and bits:
if h < top: top = h
if h > bottom: bottom = h
return top, bottom
def _logo_layout():
"""Origins for 'Matrix' and 'BOX': both left-aligned at x=0 (BOX after Matrix),
their ink bottom-aligned, and the pair centred vertically in the band."""
fs, fl = load_screen.font_small, load_screen.font_large
gap = 2
mat_w = load_screen.strlen("Matrix", fs)
mat_top, mat_bot = _logo_ink(fs, "Matrix")
box_top, box_bot = _logo_ink(fl, "BOX")
ink_h = box_bot - box_top + 1
box_y = _LOGO_BAND_TOP + (_LOGO_BAND_H - ink_h) // 2 - box_top - _LOGO_UP
mat_y = box_y + box_bot - mat_bot
return (0, mat_y), (mat_w + gap, box_y)
def _logo_box_color():
try:
return _LOGO_RO_COLOR if storage.getmount("/").readonly else _LOGO_BOX_COLOR
except Exception:
return _LOGO_BOX_COLOR
def _logo_glyph(ch, x, y, font, color):
# Same bit convention as load_screen.pprint(); returns the glyph advance.
win = load_screen.window
if ch not in font:
return 3
g = font[ch]
gw = g[0]
for w in range(gw):
px = x + w
if not 0 <= px < win.width:
continue
for h in range(font["fontheight"]):
py = y + h
bits = g[h + 1]
if isinstance(bits, int) and 0 <= py < win.height and (bits >> (gw - w)) & 1:
win[px, py] = color
return gw
def _logo_text(text, x, y, font, color):
for ch in text:
x += _logo_glyph(ch, x, y, font, color)
def _logo_clear():
# Starts at row 0: the drop frames draw letters up into row 0, and nothing else would clear it.
win = load_screen.window
for y in range(0, _LOGO_BAND_TOP + _LOGO_BAND_H):
for x in range(win.width):
win[x, y] = 0
def logo_static():
"""The logo as it sits on rows 1-2 once the intro is over."""
_logo_clear()
(mx, my), (bx, by) = _logo_layout()
_logo_text("Matrix", mx, my, load_screen.font_small, _LOGO_MATRIX_COLOR)
_logo_text("BOX", bx, by, load_screen.font_large, _logo_box_color())
show_logo = logo_static # web_interface redraws the logo through this name
def logo_intro():
"""Startup intro: 'Matrix' slides in from the left first, then the letters of
BOX drop into place one after another. A button press skips to the final logo."""
load_screen.window.fill(0) # also clears the boot text
fs, fl = load_screen.font_small, load_screen.font_large
(mx, my), (bx, by) = _logo_layout()
color = _logo_box_color()
mat_w = load_screen.strlen("Matrix", fs)
letters = []
x = bx
for ch in "BOX":
letters.append((ch, x))
x += fl[ch][0]
drop_start = _LOGO_SLIDE # BOX starts dropping once "Matrix" has landed
total = drop_start + (len(letters) - 1) * _LOGO_STAGGER + len(_LOGO_DROP)
for f in range(total):
_logo_clear()
if f < _LOGO_SLIDE:
k = f + 1
sx = mx + (-mat_w - mx) * (_LOGO_SLIDE - k) // _LOGO_SLIDE
else:
sx = mx
_logo_text("Matrix", sx, my, fs, _LOGO_MATRIX_COLOR)
for i, (ch, lx) in enumerate(letters):
step = f - drop_start - i * _LOGO_STAGGER
if step < 0:
continue
dy = _LOGO_DROP[step] if step < len(_LOGO_DROP) else 0
_logo_glyph(ch, lx, by + dy, fl, color)
load_screen.display.refresh()
if check_if_button_pressed():
break
time.sleep(_LOGO_FRAME_S)
logo_static()
# Always push the final state to the panel: a skipped intro would otherwise
# stay on its last mid-drop frame until the home screen next refreshes.
load_screen.display.refresh()
logo_intro()
wifi.radio.tx_power = 9.0
pool = socketpool.SocketPool(wifi.radio)
socket = pool.socket()
socket.setblocking(False)
socket.setsockopt(pool.SOL_SOCKET, pool.SO_REUSEADDR, 1)
socket.bind(('', 80))
socket.listen(5)
socket_timeout = 5
macid = "matrixbox-" + "".join([hex(i) for i in wifi.radio.mac_address]).replace("0x","")[:3] # mac-id för hotspot
ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio)
requests = adafruit_requests.Session(pool, ssl_context)
screensaver = time.monotonic()
@ampule.route("/exit", method="GET")
def webinterface(request):
load_settings.app_running = False
#return (200, {}, """<meta http-equiv="refresh" content="0; url=../" />""")
return (302, {"Location": "/"}, "")
@ampule.route("/", method="GET")
def webinterface(request):
if load_settings.app_running:
return (200, {}, str(exitbutton) + f"""<br> running app {load_settings.app_running}""")
if request.params:
if "run" in request.params: load_settings.app_running = request.params["run"]
return (200, {}, select_app())
def initialize_app():
global autostart
ampule_routes_backup = ampule.routes.copy()
palette_backup = [load_screen.palette[i] for i in range(12)] # restored on exit
try:
clearscreen(lines=True)
pprint(f">> {load_settings.app_running}...")
os.chdir(load_settings.app_running)
time.sleep(0.5)
# apps start with a clean route table except for system routes
# (settings, filemanager, terminal etc.)
ampule.routes.clear()
import __init__
except Exception as e:
print(f"{e}")
pprint(f"{e}")
time.sleep(1)
settings["autostart"] = 0
finally:
# Apps that change the matrix's color bit depth (e.g. flights needs
# 6) are expected to restore it themselves, but this is the safety
# net for every app regardless -- a no-op if it's already 4 (and
# nothing else needs rebuilding either).
init_display(bit_depth=4)
# Bare `palette`/`display`/`rf_group` below were only ever a
# one-time copy from `from load_screen import *` at this file's own
# import -- if the app that just ran rebuilt the matrix (bit depth,
# or even just the safety-net call above), those names are stale,
# orphaned objects that are no longer what's actually on screen.
# Fetching them from load_screen directly guarantees these lines
# operate on the real, current display (same bug/fix as
# flights/code.py's window/display/palette references).
for i, backup in enumerate(palette_backup):
load_screen.palette[i] = backup
try: microcontroller.cpu.frequency = 160000000
except: pass
autostart = False
ampule.routes = ampule_routes_backup.copy()
try:
for codefile in os.listdir():
try: del sys.modules[codefile.rsplit(".", 1)[0]]
except: pass
except: pass
gc.collect() # reclaim the exited app's bitmaps so the next launch is clean
load_screen.display.root_group = load_screen.rf_group
os.chdir("/")
render_home_screen()
return False
def savesettings(settings):
print("Saving...")
clearscreen(True)
saved = True
try:
with open("settings.txt","w") as f:
f.write(json.dumps(settings))
except Exception as e:
# USB-connected boards are often read-only to their own code (see boot.py)
print("Read only!", e)
saved = False
clearscreen(False)
return saved
def installed_apps():
installed_apps = []
for app in os.listdir("/"):
if app == "LICENSE": continue
if not "." in app:
try:
if not "__init__.py" in os.listdir("/" + app): continue
except: continue
installed_apps.append(app)
return installed_apps if len(installed_apps) else ["No apps found"]
def show_first_app():
try: load_settings.installed_apps_list[1]
except: load_settings.installed_apps_list = installed_apps()
pprint(load_settings.installed_apps_list[0], line=-1, color="orange", clear=True, _refresh=True)
def render_home_screen():
# Single place that draws the persistent LED screen -- other functions
# call this instead of drawing their own version. Rows 1-2 are the logo,
# rows 3-5 the home screen (row 5 is the app name, see show_first_app).
clearscreen(lines=True)
logo_static() # clearscreen(lines=True) above also wiped the logo -- redraw it
if wifi.radio.connected:
_wifi_address = f"IP: {wifi.radio.ipv4_address}" if wifi.radio.ipv4_address else "OFFLINE"
pprint(_wifi_address, line=2)
if wlan.STATUS:
# Full message is in the Settings error box; screen is too narrow for it.
pprint("READ-ONLY", line=5, color="red")
else:
pprint("Select app:", line=3)
show_first_app()
elif wifi.radio.ap_active:
load_screen.window.fill(0)
wlan.show_setup_on_led()
wlan.show_status_on_led()
def next_program_in_list(run=False):
try: load_settings.installed_apps_list[1]
except: load_settings.installed_apps_list = installed_apps()
if run:
load_settings.app_running = load_settings.installed_apps_list[0]
return
print(load_settings.installed_apps_list)
load_settings.installed_apps_list.append(load_settings.installed_apps_list[0])
load_settings.installed_apps_list.pop(0)
scroll_line(load_settings.installed_apps_list[0], color="orange")
def check_for_button_next_program():
global screensaver
b = check_if_button_pressed()
if b == 0: pass
if b == 1: next_program_in_list()
elif b == 2: next_program_in_list(run=True)
if load_settings.app_running:
load_settings.app_running = initialize_app()
screensaver = time.monotonic()
autostart = settings["autostart"]
screensaver_app = settings.get("screensaver", "starcloud")
wifi.radio.tx_power = float(settings["wifi_power"])
from web_interface import *
import wlan
wlan.connect_to_network()
while 1:
print("Entered main loop")
while not wifi.radio.connected and not wifi.radio.ap_active:
check_network_again_timer = time.monotonic()
wlan.start_hotspot()
while wifi.radio.ap_active and not wifi.radio.connected:
ampule.listen(socket)
if autostart:
print(ampule.listen(socket))
load_settings.app_running = autostart
check_for_button_next_program()
if time.monotonic() > check_network_again_timer + 10:
print("Attempting... " + str(wifi.radio.tx_power))
wifi.radio.tx_power += 1
if wifi.radio.tx_power == 21: wifi.radio.tx_power = 18
check_network_again_timer = wlan.connect_to_network(timeout=3, silent=True)
wlan.show_status_on_led() # show this attempt's error (or clear it) on line 5
if wifi.radio.connected: wifi.radio.stop_ap()
while wifi.radio.connected or wifi.radio.ap_active:
settings["wifi_power"] = wifi.radio.tx_power
render_home_screen()
while wifi.radio.connected:# or wifi.radio.ap_active:
if autostart:
print(ampule.listen(socket))
load_settings.app_running = autostart
elif not load_settings.app_running: ampule.listen(socket)
check_for_button_next_program()
if screensaver_app and time.monotonic() > screensaver + 60:
try: load_settings.app_running = screensaver_app
except Exception as e: pprint(e)
screensaver = time.monotonic()