-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
1840 lines (1637 loc) · 85 KB
/
app.py
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import os
import time
from math import cos, pi
import ota
import settings
import vfs
from app_components.notification import Notification
from app_components.tokens import label_font_size, twentyfour_pt, clear_background, button_labels
from app_components import Menu
from events.input import BUTTON_TYPES, Button, Buttons, ButtonUpEvent
from frontboards.twentyfour import BUTTONS
from machine import I2C
from system.eventbus import eventbus
from system.hexpansion.events import (HexpansionInsertionEvent,
HexpansionRemovalEvent)
from system.hexpansion.header import HexpansionHeader
from system.hexpansion.util import get_hexpansion_block_devices
from system.patterndisplay.events import PatternDisable, PatternEnable
from system.scheduler import scheduler
from system.scheduler.events import (RequestForegroundPopEvent,
RequestForegroundPushEvent,
RequestStopAppEvent)
from tildagonos import tildagonos
import app
from .utils import chain, draw_logo_animated, parse_version
# Hard coded to talk to EEPROMs on address 0x50 - because we know that is what is on the HexDrive Hexpansion
# makes it a lot more efficient than scanning the I2C bus for devices and working out what they are
CURRENT_APP_VERSION = 4 # HEXDRIVE.PY Integer Version Number - checked against the EEPROM app.py version to determine if it needs updating
_APP_VERSION = "1.2" # BadgeBot App Version Number
# If you change the URL then you will need to regenerate the QR code
_QR_CODE = [0x1fcf67f,
0x104cc41,
0x174975d,
0x1744e5d,
0x175d45d,
0x104ea41,
0x1fd557f,
0x001af00,
0x04735f7,
0x1070c97,
0x1c23ae9,
0x08ce9bd,
0x1af3160,
0x1270a80,
0x1cc3549,
0x097ef36,
0x03ff5e9,
0x1b18300,
0x1b5a37f,
0x0313b41,
0x03f3d5d,
0x078b65d,
0x111e35d,
0x0b57141,
0x18bbd7f]
# Screen positioning for movement sequence text
H_START = -63
V_START = -58
_BRIGHTNESS = 1.0
# Motor Driver - Defaults
_MAX_POWER = 65535
_POWER_STEP_PER_TICK = 7500 # effectively the acceleration
# Servo Tester - Defaults
_SERVO_DEFAULT_STEP = 10 # us per step
_SERVO_DEFAULT_CENTRE = 1500 # us
_SERVO_DEFAULT_RANGE = 1000 # +/- 500us from centre
_SERVO_DEFAULT_RATE = 25 # *10us per s
_SERVO_DEFAULT_MODE = 0 # Off
_SERVO_DEFAULT_PERIOD = 20 # ms
_SERVO_MAX_RATE = 1000 # *10us per s
_SERVO_MIN_RATE = 1 # *10us per s
_SERVO_MAX_TRIM = 1000 # us
_MAX_SERVO_RANGE = 1400 # 1400us either side of centre (VERY WIDE)
# Timings
_TICK_MS = 10 # Smallest unit of change for power, in ms
_USER_DRIVE_MS = 50 # User specifed drive durations, in ms
_USER_TURN_MS = 20 # User specifed turn durations, in ms
_LONG_PRESS_MS = 750 # Time for long button press to register, in ms
_RUN_COUNTDOWN_MS = 5000 # Time after running program until drive starts, in ms
_AUTO_REPEAT_MS = 200 # Time between auto-repeats, in ms
_AUTO_REPEAT_COUNT_THRES = 10 # Number of auto-repeats before increasing level
_AUTO_REPEAT_SPEED_LEVEL_MAX = 4 # Maximum level of auto-repeat speed increases
_AUTO_REPEAT_LEVEL_MAX = 3 # Maximum level of auto-repeat digit increases
# App states
STATE_INIT = -1
STATE_WARNING = 0
STATE_MENU = 1
STATE_HELP = 2
STATE_RECEIVE_INSTR = 3
STATE_COUNTDOWN = 4
STATE_RUN = 5
STATE_DONE = 6
STATE_CHECK = 7 # Checks for EEPROMs and HexDrives
STATE_DETECTED = 8 # Hexpansion ready for EEPROM initialisation
STATE_UPGRADE = 9 # Hexpansion ready for EEPROM upgrade
STATE_ERASE = 10 # Hexpansion ready for EEPROM erase
STATE_PROGRAMMING = 11 # Hexpansion EEPROM programming
STATE_REMOVED = 12 # Hexpansion removed
STATE_ERROR = 13 # Hexpansion error
STATE_MESSAGE = 14 # Message display
STATE_LOGO = 15 # Logo display
STATE_SERVO = 16 # Servo test
STATE_SETTINGS = 17 # Edit Settings
# App states where user can minimise app
_MINIMISE_VALID_STATES = [0, 1, 7, 12, 13, 14, 15]
_LED_CONTROL_STATES = [0, 3, 4, 5, 6, 12, 13, 14, 15]
# HexDrive Hexpansion constants
_EEPROM_ADDR = 0x50
_EEPROM_NUM_ADDRESS_BYTES = 2
_EEPROM_PAGE_SIZE = 32
_EEPROM_TOTAL_SIZE = 64 * 1024 // 8
#Misceallaneous Settings
_LOGGING = False
_ERASE_SLOT = 0 # Slot for user to set if they want to erase EEPROMs on HexDrives
#
_main_menu_items = ["Motor Moves", "Servo Test", "Settings", "About","Exit"]
class BadgeBotApp(app.App):
def __init__(self):
super().__init__()
# UI Button Controls
self.button_states = Buttons(self)
self.last_press: Button = BUTTON_TYPES["CANCEL"]
self.long_press_delta = 0
self._auto_repeat_intervals = [ _AUTO_REPEAT_MS, _AUTO_REPEAT_MS//2, _AUTO_REPEAT_MS//4, _AUTO_REPEAT_MS//8, _AUTO_REPEAT_MS//16] # at the top end the loop is unlikley to cycle this fast
self._auto_repeat = 0
self._auto_repeat_count = 0
self._auto_repeat_level = 0
# UI Feature Controls
self._refresh = True
self.rpm = 5 # logo rotation speed in RPM
self._animation_counter = 0
self._pattern_status = True # True = Pattern Enabled, False = Pattern Disabled
self.qr_code = _QR_CODE
self.b_msg = f"BadgeBot V{_APP_VERSION}"
self.t_msg = "RobotMad"
self.is_scroll = False
self.scroll_offset = 0
self.notification = None
self.error_message = []
self.current_menu = None
self.menu = None
# BadgeBot Control Sequence Variables
self.run_countdown_elapsed_ms = 0
self.instructions = []
self.current_instruction = None
self.current_power_duration = ((0,0,0,0), 0)
self.power_plan_iter = iter([])
# Settings
self._settings = {}
self._settings['acceleration'] = MySetting(self._settings, _POWER_STEP_PER_TICK, 1, 65535)
self._settings['max_power'] = MySetting(self._settings, _MAX_POWER, 1000, 65535)
self._settings['drive_step_ms'] = MySetting(self._settings, _USER_DRIVE_MS, 5, 200)
self._settings['turn_step_ms'] = MySetting(self._settings, _USER_TURN_MS, 5, 200)
self._settings['servo_step'] = MySetting(self._settings, _SERVO_DEFAULT_STEP, 1, 100)
self._settings['servo_range'] = MySetting(self._settings, _SERVO_DEFAULT_RANGE, 100, _MAX_SERVO_RANGE) # one setting for all servos
self._settings['servo_period'] = MySetting(self._settings, _SERVO_DEFAULT_PERIOD, 5, 50)
self._settings['brightness'] = MySetting(self._settings, _BRIGHTNESS, 0.1, 1.0)
self._settings['logging'] = MySetting(self._settings, _LOGGING, False, True)
self._settings['erase_slot'] = MySetting(self._settings, _ERASE_SLOT, 0, 6)
self._edit_setting = None
self._edit_setting_value = None
self.update_settings()
# Check what version of the Badge s/w we are running on
try:
ver = parse_version(ota.get_version())
if ver is not None:
if self._settings['logging'].v:
print(f"BadgeSW V{ver}")
# Potential to do things differently based on badge s/w version
# e.g. if ver < [1, 9, 0]:
except:
pass
# Hexpansion related
self._HEXDRIVE_TYPES = [HexDriveType(0xCBCB, motors=2, servos=4),
HexDriveType(0xCBCA, motors=2, name="2 Motor"),
HexDriveType(0xCBCC, servos=4, name="4 Servo"),
HexDriveType(0xCBCD, motors=1, servos=2, name = "1 Mot 2 Srvo")]
self.hexpansion_slot_type = [None]*6
self.hexpansion_init_type = 0
self.detected_port = None
self.waiting_app_port = None
self.erase_port = None
self.upgrade_port = None
self.hexdrive_port = None
self.ports_with_blank_eeprom = set()
self.ports_with_hexdrive = set()
self.ports_with_latest_hexdrive = set()
self.hexdrive_app = None
self.hexpansion_update_required = False # flag from async to main loop
eventbus.on_async(HexpansionInsertionEvent, self._handle_hexpansion_insertion, self)
eventbus.on_async(HexpansionRemovalEvent, self._handle_hexpansion_removal, self)
# Motor Driver
self.num_motors = 2 # Default assumed for a single HexDrive
# Servo Tester
self._time_since_last_update = 0
self._keep_alive_period = 500 # ms (half the value used in hexdrive.py)
self.num_servos = 4 # Default assumed for a single HexDrive
self.servo = [None]*4 # Servo Positions
self.servo_centre = [_SERVO_DEFAULT_CENTRE]*4 # Trim Servo Centre
self.servo_range = [_SERVO_DEFAULT_RANGE]*4 # Limit Servo Range
self.servo_rate = [_SERVO_DEFAULT_RATE]*4 # Servo Rate of Change
self.servo_mode = [_SERVO_DEFAULT_MODE]*4 # Servo Mode [0:Position, 1: Scan]
self.servo_selected = 0
self._servo_modes = ['Off','Trim','Position','Scanning']
# Overall app state (controls what is displayed and what user inputs are accepted)
self.current_state = STATE_INIT
self.previous_state = self.current_state
eventbus.on_async(RequestForegroundPushEvent, self._gain_focus, self)
eventbus.on_async(RequestForegroundPopEvent, self._lose_focus, self)
# We start with focus on launch, without an event emmited
self._gain_focus(RequestForegroundPushEvent(self))
### ASYNC EVENT HANDLERS ###
async def _handle_hexpansion_removal(self, event: HexpansionRemovalEvent):
self.hexpansion_slot_type[event.port-1] = None
if event.port in self.ports_with_blank_eeprom:
if self._settinfs['logging'].v:
print(f"H:EEPROM removed from port {event.port}")
self.ports_with_blank_eeprom.remove(event.port)
if event.port in self.ports_with_hexdrive:
if self._settings['logging'].v:
print(f"H:HexDrive removed from port {event.port}")
self.ports_with_hexdrive.remove(event.port)
if event.port in self.ports_with_latest_hexdrive:
if self._settings['logging'].v:
print(f"H:HexDrive V{_APP_VERSION} removed from port {event.port}")
self.ports_with_latest_hexdrive.remove(event.port)
if self.current_state == STATE_DETECTED and event.port == self.detected_port:
self.hexpansion_update_required = True
elif self.current_state == STATE_UPGRADE and event.port == self.upgrade_port:
self.hexpansion_update_required = True
elif self.hexdrive_port is not None and event.port == self.hexdrive_port:
self.hexpansion_update_required = True
elif self.waiting_app_port is not None and event.port == self.waiting_app_port:
self.hexpansion_update_required = True
elif self.erase_port is not None and event.port == self.erase_port:
self.hexpansion_update_required = True
async def _handle_hexpansion_insertion(self, event: HexpansionInsertionEvent):
if self.check_port_for_hexdrive(event.port):
self.hexpansion_update_required = True
async def _gain_focus(self, event: RequestForegroundPushEvent):
if event.app is self:
if self.current_state in _LED_CONTROL_STATES:
eventbus.emit(PatternDisable())
elif self.current_state == STATE_RECEIVE_INSTR:
eventbus.on_async(ButtonUpEvent, self._handle_button_up, self)
async def _lose_focus(self, event: RequestForegroundPopEvent):
if event.app is self:
eventbus.emit(PatternEnable())
self._pattern_status = True
if self.current_state == STATE_RECEIVE_INSTR:
eventbus.remove(ButtonUpEvent, self._handle_button_up, self)
async def _handle_button_up(self, event: ButtonUpEvent):
if self.current_state == STATE_RECEIVE_INSTR and event.button == BUTTONS["C"]:
self.is_scroll = not self.is_scroll
state = "yes" if self.is_scroll else "no"
self.notification = Notification(f"Scroll {state}")
async def background_task(self):
# Modiifed background task loop for shorter sleep time
last_time = time.ticks_ms()
while True:
cur_time = time.ticks_ms()
delta_ticks = time.ticks_diff(cur_time, last_time)
self.background_update(delta_ticks)
s = 10 if self.current_state == STATE_RUN else 50
await asyncio.sleep_ms(s)
last_time = cur_time
### NON-ASYNC FUCNTIONS ###
def background_update(self, delta):
if self.current_state == STATE_RUN:
output = self.get_current_power_level(delta)
if output is None:
self.current_state = STATE_DONE
elif self.hexdrive_app is not None:
self.hexdrive_app.set_motors(output)
def generate_new_qr(self):
from .uQR import QRCode
qr = QRCode(error_correction=1, box_size=10, border=0)
qr.add_data("https://robotmad.odoo.com")
self.qr_code = qr.get_matrix()
# convert QR code made up of True/False into words of 1s and 0s
if 32 < len(self.qr_code):
print("QR code too big")
else:
qr_code_size = len(self.qr_code)
print("_QR_CODE = [")
for row in range(qr_code_size):
bitfield = 0x00000000
for col in range(qr_code_size):
# LSBit is on the left
bitfield = bitfield | (1 << col) if self.qr_code[row][col] else bitfield
print(f"0x{bitfield:08x},")
print("]")
### HEXPANSION FUNCTIONS ###
# Scan the Hexpansion ports for EEPROMs and HexDrives in case they are already plugged in when we start
def scan_ports(self):
for port in range(1, 7):
self.check_port_for_hexdrive(port)
def check_port_for_hexdrive(self, port) -> bool:
# avoiding use of badge read_hexpansion_header as this triggers a full i2c scan each time
# we know the EEPROM address so we can just read the header directly
if port not in range(1, 7):
return False
try:
header_bytes = I2C(port).readfrom_mem(_EEPROM_ADDR, 0, 32, addrsize = (8*_EEPROM_NUM_ADDRESS_BYTES))
except OSError:
# no EEPROM on this port
return False
try:
read_header = HexpansionHeader.from_bytes(header_bytes)
except Exception:
# not a valid header
if self._settings['logging'].v:
print(f"H:Found EEPROM on port {port}")
self.ports_with_blank_eeprom.add(port)
return True
# check is this is a HexDrive header by scanning the _HEXDRIVE_TYPES list
for index, hexpansion_type in enumerate(self._HEXDRIVE_TYPES):
if read_header.vid == hexpansion_type.vid and read_header.pid == hexpansion_type.pid:
if self._settings['logging'].v:
print(f"H:Found '{hexpansion_type.name}' HexDrive on port {port}")
if port not in self.ports_with_latest_hexdrive:
self.ports_with_hexdrive.add(port)
self.hexpansion_slot_type[port-1] = index
return True
# we are not interested in this type of hexpansion
return False
def update_app_in_eeprom(self, port, addr) -> bool:
# Copy hexdrive.mpy to EEPROM as app.mpy
if self._settings['logging'].v:
print(f"H:Updating HexDrive app.mpy on port {port}")
try:
i2c = I2C(port)
except Exception as e:
print(f"H:Error opening I2C port {port}: {e}")
return False
header = self.read_hexpansion_header(i2c=i2c)
if header is None:
if self._settings['logging'].v:
print(f"H:Error reading header on port {port}")
return False
try:
_, partition = get_hexpansion_block_devices(i2c, header, addr)
except RuntimeError as e:
print(f"H:Error getting block devices: {e}")
return False
mountpoint = '/hexpansion_' + str(port)
already_mounted = False
if not already_mounted:
if self._settings['logging'].v:
print(f"H:Mounting {partition} at {mountpoint}")
try:
vfs.mount(partition, mountpoint, readonly=False)
except OSError as e:
if e.args[0] == 1:
already_mounted = True
else:
print(f"H:Error mounting: {e}")
except Exception as e:
print(f"H:Error mounting: {e}")
source_path = "/" + __file__.rsplit("/", 1)[0] + "/hexdrive.mpy"
dest_path = f"{mountpoint}/app.mpy"
try:
# delete the existing app.mpy file
if self._settings['logging'].v:
print(f"H:Deleting {dest_path}")
os.remove(dest_path)
except Exception as e:
if e.args[0] != 2:
# ignore errors which will happen if the file does not exist
print(f"H:Error deleting {dest_path}: {e}")
if self._settings['logging'].v:
print(f"H:Copying {source_path} to {dest_path}")
try:
appfile = open(dest_path, "wb")
except Exception as e:
print(f"H:Error opening {dest_path}: {e}")
return False
try:
template = open(source_path, "rb")
except Exception as e:
print(f"H:Error opening {source_path}: {e}")
return False
try:
appfile.write(template.read())
except Exception as e:
print(f"H:Error updating HexDrive: {e}")
return False
try:
appfile.close()
template.close()
except Exception as e:
print(f"H:Error closing files: {e}")
return False
if not already_mounted:
try:
vfs.umount(mountpoint)
if self._settings['logging'].v:
print(f"H:Unmounted {mountpoint}")
except Exception as e:
print(f"H:Error unmounting {mountpoint}: {e}")
return False
if self._settings['logging'].v:
print(f"H:HexDrive app.mpy updated to version {CURRENT_APP_VERSION}")
return True
def prepare_eeprom(self, port, addr) -> bool:
if self._settings['logging'].v:
print(f"H:Initialising EEPROM on port {port}")
hexdrive_header = HexpansionHeader(
manifest_version="2024",
fs_offset=32,
eeprom_page_size=_EEPROM_PAGE_SIZE,
eeprom_total_size=_EEPROM_TOTAL_SIZE,
vid=self._HEXDRIVE_TYPES[self.hexpansion_init_type].vid,
pid=self._HEXDRIVE_TYPES[self.hexpansion_init_type].pid,
unique_id=0x0,
friendly_name="HexDrive",
)
# Write and read back header efficiently
try:
i2c = I2C(port)
i2c.writeto(addr, bytes([0]*_EEPROM_NUM_ADDRESS_BYTES) + hexdrive_header.to_bytes())
except Exception as e:
print(f"H:Error writing header: {e}")
return False
# Poll ACK
while True:
try:
if i2c.writeto(addr, bytes([0]*_EEPROM_NUM_ADDRESS_BYTES)): # Poll ACK
break
except OSError:
pass
finally:
time.sleep_ms(1)
try:
header_bytes = i2c.readfrom_mem(addr, 0, 32, addrsize = (8*_EEPROM_NUM_ADDRESS_BYTES))
except Exception as e:
print(f"H:Error reading header back: {e}")
return False
try:
read_header = HexpansionHeader.from_bytes(header_bytes)
except Exception as e:
print(f"H:Error parsing header: {e}")
return False
try:
# Get block devices
_, partition = get_hexpansion_block_devices(i2c, read_header, addr)
except RuntimeError as e:
print(f"H:Error getting block devices: {e}")
return False
try:
# Format
vfs.VfsLfs2.mkfs(partition)
if self._settings['logging'].v:
print("H:EEPROM formatted")
except Exception as e:
print(f"H:Error formatting: {e}")
return False
try:
# And mount!
mountpoint = '/hexpansion_' + str(port)
vfs.mount(partition, mountpoint, readonly=False)
if self._settings['logging'].v:
print("H:EEPROM initialised")
except OSError as e:
if e.args[0] == 1:
#already_mounted
if self._settings['logging'].v:
print("H:EEPROM initialised")
else:
print(f"H:Error mounting: {e}")
return False
except Exception as e:
print(f"H:Error mounting: {e}")
return False
return True
def erase_eeprom(self, port, addr) -> bool:
if self._settings['logging'].v:
print(f"H:Erasing EEPROM on port {port}")
try:
i2c = I2C(port)
i2c.writeto(addr, bytes([0]*_EEPROM_NUM_ADDRESS_BYTES))
# loop through all pages and erase them
for page in range(_EEPROM_TOTAL_SIZE // _EEPROM_PAGE_SIZE):
i2c.writeto(addr, bytes([page >> 8, page & 0xFF]) + bytes([0xFF]*_EEPROM_PAGE_SIZE))
# check Ack
while True:
try:
if i2c.writeto(addr, bytes([page >> 8, page & 0xFF])): # Poll ACK
break
except OSError:
pass
finally:
time.sleep_ms(1)
except Exception as e:
print(f"H:Error erasing EEPROM: {e}")
return False
return True
def read_hexpansion_header(self, i2c=None, port=None) -> HexpansionHeader:
try:
if i2c is None:
if port is None:
return None
i2c = I2C(port)
header_bytes = i2c.readfrom_mem(_EEPROM_ADDR, 0, 32, addrsize = (8*_EEPROM_NUM_ADDRESS_BYTES))
return HexpansionHeader.from_bytes(header_bytes)
except OSError:
return None
def find_hexdrive_app(self, port) -> app:
for an_app in scheduler.apps:
if hasattr(an_app, "config") and hasattr(an_app.config, "port") and an_app.config.port == port:
return an_app
return None
def update_settings(self):
for s in self._settings:
self._settings[s].v = settings.get(f"badgebot.{s}", self._settings[s].d)
def _pattern_management(self):
if self.current_state in _LED_CONTROL_STATES:
if self._pattern_status:
eventbus.emit(PatternDisable())
self._pattern_status = False
# delay enough to allow the pattern to stop
time.sleep_ms(500)
elif self.current_state not in _LED_CONTROL_STATES and not self._pattern_status:
eventbus.emit(PatternEnable())
self._pattern_status = True
### MAIN APP CONTROL FUNCTIONS ###
def update(self, delta):
if self.notification:
self.notification.update(delta)
# manage PatternEnable/Disable for all states
self._pattern_management()
self._update_hexpansion_management(delta)
self._update_main_application(delta)
if self.current_state != self.previous_state:
if self._settings['logging'].v:
print(f"State: {self.previous_state} -> {self.current_state}")
self.previous_state = self.current_state
# manage PatternEnable/Disable for all states
self._pattern_management()
# something has changed - so worth redrawing
self._refresh = True
if self.current_state in _LED_CONTROL_STATES:
if self._settings['brightness'].v < 1.0:
# Scale brightness
for i in range(1,13):
tildagonos.leds[i] = tuple(int(j * self._settings['brightness'].v) for j in tildagonos.leds[i])
tildagonos.leds.write()
### START UI FOR HEXPANSION INITIALISATION AND UPGRADE ###
def _update_hexpansion_management(self, delta):
if self.current_state == STATE_INIT:
# One Time initialisation
self.scan_ports()
if (len(self.ports_with_hexdrive) == 0) and (len(self.ports_with_blank_eeprom) == 0):
# There are currently no possible HexDrives plugged in
self._animation_counter = 0
self.current_state = STATE_WARNING
else:
self.current_state = STATE_CHECK
return
if self.hexpansion_update_required:
# something has changed in the hexpansion ports
self.hexpansion_update_required = False
if self.current_state != STATE_CHECK:
print("H:Hexpansion Check")
self.set_menu(None)
self.current_state = STATE_CHECK
if self.current_state == STATE_WARNING or self.current_state == STATE_LOGO:
self._update_state_warning(delta)
elif self.current_state == STATE_ERROR or self.current_state == STATE_MESSAGE or self.current_state == STATE_REMOVED:
self._update_state_error(delta)
elif self.current_state == STATE_PROGRAMMING:
# Programming the Hexpansion
self._update_state_programming(delta)
elif self.current_state == STATE_DETECTED:
# We have detected a Hexpansion with a blank EEPROM - asking the user if they want to initialise it
self._update_state_detected(delta)
elif self.current_state == STATE_ERASE:
self._update_state_erase(delta)
elif self.current_state == STATE_UPGRADE:
# We are currently asking the user if they want hexpansion App upgrading with latest App.mpy
self._update_state_upgrade(delta)
elif self.current_state in _MINIMISE_VALID_STATES:
if self._check_hexpansion_ports(delta):
pass
elif self._check_hexdrive_ports(delta):
pass
elif self.current_state == STATE_CHECK:
self._update_state_check(delta)
def _update_main_application(self, delta):
if self.current_state == STATE_MENU:
if self.current_menu is None:
self.set_menu("main")
self._refresh = True
else:
self.menu.update(delta)
if self.menu.is_animating != "none":
if self._settings['logging'].v:
print("Menu is animating")
self._refresh = True
elif self.button_states.get(BUTTON_TYPES["CANCEL"]) and self.current_state in _MINIMISE_VALID_STATES:
self.button_states.clear()
self.is_scroll = False
self.minimise()
### Motor Moves Application ###
elif self.current_state == STATE_HELP:
self._update_state_help(delta)
elif self.current_state == STATE_RECEIVE_INSTR:
self._update_state_receive_instr(delta)
elif self.current_state == STATE_COUNTDOWN:
self._update_state_countdown(delta)
elif self.current_state == STATE_RUN:
self.clear_leds()
# Run is primarily managed in the background update
elif self.current_state == STATE_DONE:
self._update_state_done(delta)
### Servo Tester Application ###
elif self.current_state == STATE_SERVO:
self._update_state_servo(delta)
### Settings Capability ###
elif self.current_state == STATE_SETTINGS:
self._update_state_settings(delta)
### End of Update ###
def _update_state_warning(self, delta):
if self.button_states.get(BUTTON_TYPES["CONFIRM"]):
self.button_states.clear()
if self.current_state == STATE_WARNING or self.hexdrive_port is not None:
# Warning has been acknowledged by the user
self._animation_counter = 0
self.current_state = STATE_MENU # allow access to settings and About
else:
# Return to Warning screen from Logo when no HexDrive is present
self.current_state = STATE_WARNING
else:
# "CANCEL" button is handled below in common for all MINIMISE_VALID_STATES
# Show the warning screen for 10 seconds
self._animation_counter += delta/1000
self._refresh = True
if self.current_state == STATE_WARNING and self._animation_counter > 10:
# after 10 seconds show the logo
self._animation_counter = 0
self.current_state = STATE_LOGO
elif self.current_state == STATE_LOGO:
# LED management - to match rotating logo:
for i in range(1,13):
colour = (255, 241, 0) # custom Robotmad shade of yellow
# raised cosine cubed wave
wave = self._settings['brightness'].v * pow((1.0 + cos(((i) * pi / 1.5) - (self.rpm * self._animation_counter * pi / 7.5)))/2.0, 3)
# 4 sides each projecting a pattern of 3 LEDs (12 LEDs in total)
tildagonos.leds[i] = tuple(int(wave * j) for j in colour)
else: # STATE_WARNING
for i in range(1,13):
tildagonos.leds[i] = (255,0,0)
def _update_state_error(self, delta):
if self.button_states.get(BUTTON_TYPES["CONFIRM"]):
# Error has been acknowledged by the user
self.button_states.clear()
self.current_state = STATE_CHECK
self.error_message = []
else:
for i in range(1,13):
tildagonos.leds[i] = (0,255,0) if self.current_state == STATE_MESSAGE else (255,0,0)
def _update_state_programming(self, delta):
if self.upgrade_port is not None:
if self.update_app_in_eeprom(self.upgrade_port, _EEPROM_ADDR):
self.notification = Notification("Upgraded", port = self.upgrade_port)
#self.ports_with_latest_hexdrive.add(self.upgrade_port)
# Try to trigger hexpansion managment app to restart the HexDrive
# by emit hexpansion insertion event
eventbus.emit(HexpansionInsertionEvent(self.upgrade_port))
self.error_message = ["Upgraded:","Please","reboop"]
self.current_state = STATE_MESSAGE
if self._settings['logging'].v:
print(f"H:HexDrive on port {self.upgrade_port} upgraded")
else:
self.notification = Notification("Failed", port = self.upgrade_port)
self.error_message = ["HexDrive","programming","failed"]
self.current_state = STATE_ERROR
self.upgrade_port = None
elif self.detected_port is not None:
if self.prepare_eeprom(self.detected_port, _EEPROM_ADDR):
self.notification = Notification("Initialised", port = self.detected_port)
self.upgrade_port = self.detected_port
self.current_state = STATE_UPGRADE
else:
self.notification = Notification("Failed", port = self.detected_port)
self.error_message = ["EEPROM","initialisation","failed"]
self.current_state = STATE_ERROR
self.detected_port = None
elif self._settings['logging'].v:
print("H:Error - no port to program")
def _update_state_detected(self, delta):
# We are currently asking the user if they want hexpansion EEPROM initialising
if self.button_states.get(BUTTON_TYPES["CONFIRM"]):
self.button_states.clear()
self.current_state = STATE_PROGRAMMING
elif self.button_states.get(BUTTON_TYPES["CANCEL"]):
self.button_states.clear()
if self._settings['logging'].v:
print("H:Initialise Cancelled")
self.detected_port = None
self.current_state = STATE_CHECK
elif self.button_states.get(BUTTON_TYPES["UP"]):
self.button_states.clear()
self.hexpansion_init_type = (self.hexpansion_init_type + 1) % len(self._HEXDRIVE_TYPES)
self._refresh = True
elif self.button_states.get(BUTTON_TYPES["DOWN"]):
self.button_states.clear()
self.hexpansion_init_type = (self.hexpansion_init_type - 1) % len(self._HEXDRIVE_TYPES)
self._refresh = True
elif self.button_states.get(BUTTON_TYPES["LEFT"]):
self.button_states.clear()
self.hexpansion_init_type = 1
self._refresh = True
elif self.button_states.get(BUTTON_TYPES["RIGHT"]):
self.button_states.clear()
self.hexpansion_init_type = 2
self._refresh = True
def _update_state_erase(self, delta):
# We are currently asking the user if they want hexpansion EEPROM Erased
if self.button_states.get(BUTTON_TYPES["CONFIRM"]):
# Yes
self.button_states.clear()
if self.erase_eeprom(self.erase_port, _EEPROM_ADDR):
self.error_message = ["Erased:","Please","reboop"]
self.notification = Notification("Erased", port = self.erase_port)
self.erase_port = None
self.current_state = STATE_MESSAGE
else:
self.notification = Notification("Failed", port = self.erase_port)
self.error_message = ["EEPROM","erasure","failed"]
self.current_state = STATE_ERROR
elif self.button_states.get(BUTTON_TYPES["CANCEL"]):
# No
if self._settings['logging'].v:
print("H:Erase Cancelled")
self.button_states.clear()
self.erase_port = None
self.current_state = STATE_CHECK
def _update_state_upgrade(self, delta):
if self.button_states.get(BUTTON_TYPES["CONFIRM"]):
# Yes
self.button_states.clear()
self.notification = Notification("Upgrading", port = self.upgrade_port)
self.current_state = STATE_PROGRAMMING
elif self.button_states.get(BUTTON_TYPES["CANCEL"]):
# No
if self._settings['logging'].v:
print("H:Upgrade Cancelled")
self.button_states.clear()
self.upgrade_port = None
self.current_state = STATE_CHECK
def _update_state_check(self, delta):
#print(f"Check: {self.ports_with_latest_hexdrive}")
if 0 < len(self.ports_with_latest_hexdrive):
# We have at least one HexDrive with the latest App.mpy
if self.hexdrive_port is not None and self.hexdrive_port not in self.ports_with_latest_hexdrive:
print(f"Check: {self.hexdrive_port} lost")
self.hexdrive_port = None
self.hexdrive_app = None
if self.hexdrive_port is None:
valid_port = next(iter(self.ports_with_latest_hexdrive))
# Find our running hexdrive app
hexdrive_app = self.find_hexdrive_app(valid_port)
if hexdrive_app is not None:
self.hexdrive_port = valid_port
self.hexdrive_app = hexdrive_app
if self.hexpansion_slot_type[valid_port-1] is not None:
self.num_motors = self._HEXDRIVE_TYPES[self.hexpansion_slot_type[valid_port-1]].motors
self.num_servos = self._HEXDRIVE_TYPES[self.hexpansion_slot_type[valid_port-1]].servos
# only intended for use with a single active HexDrive at once at present
if self.hexdrive_app.get_status():
if self._settings['logging'].v:
print(f"H:HexDrive [{valid_port}] OK")
self.current_state = STATE_MENU
self._animation_counter = 0
else:
if self._settings['logging'].v:
print(f"H:HexDrive {valid_port}: Failed to initialise PWM resources")
self.error_message = [f"HexDrive {valid_port}","PWM Init","Failed","Please","Reboop"]
self.current_state = STATE_ERROR
else:
if self._settings['logging'].v:
print(f"H:HexDrive {valid_port}: App not found, please reboop")
self.error_message = [f"HexDrive {valid_port}","App not found.","Please","reboop"]
self.current_state = STATE_ERROR
else:
# Still have hexdrive on original port
self.current_state = STATE_MENU
elif self.hexdrive_port is not None:
print(f"Check: {self.hexdrive_port} lost")
self.hexdrive_port = None
self.hexdrive_app = None
self.current_state = STATE_REMOVED
else:
self._animation_counter = 0
self.current_state = STATE_WARNING
def _check_hexpansion_ports(self, delta) -> bool:
if 0 < len(self.ports_with_blank_eeprom):
# if there are any ports with blank eeproms
# Show the UI prompt and wait for button press
self.detected_port = self.ports_with_blank_eeprom.pop()
self.notification = Notification("Initialise?", port = self.detected_port)
self.current_state = STATE_DETECTED
return True
return False
def _check_hexdrive_ports(self, delta) -> bool:
#print(f"Check HexDrive Ports: {self.waiting_app_port} {self.ports_with_hexdrive}")
if self.waiting_app_port is not None or (0 < len(self.ports_with_hexdrive)):
# if there are any ports with HexDrives - check if they need upgrading/erasing
if self.waiting_app_port is None:
self.waiting_app_port = self.ports_with_hexdrive.pop()
self._animation_counter = 0 #timeout
if self._settings['erase_slot'].v == self.waiting_app_port:
# if the user has set a port to erase EEPROMs on
# Show the UI prompt and wait for button press
if self._settings['logging'].v:
print(f"H:HexDrive on port {self.waiting_app_port} Erase?")
self.erase_port = self.waiting_app_port
self.notification = Notification("Erase?", port = self.erase_port)
self.current_state = STATE_ERASE
else:
hexdrive_app = self.find_hexdrive_app(self.waiting_app_port)
# the scheduler is updated asynchronously from hexpansion insertion so we may not find the app immediately
if hexdrive_app is not None:
try:
hexdrive_app_version = hexdrive_app.get_version()
except Exception as e:
hexdrive_app_version = 0
print(f"H:Error getting HexDrive app version - assume old: {e}")
elif 5.0 < self._animation_counter:
if self._settings['logging'].v:
print("H:Timeout waiting for HexDrive app to be started - assume it needs upgrading")
hexdrive_app_version = 0
else:
if 0 == self._animation_counter:
if self._settings['logging'].v:
print(f"H:No app found on port {self.waiting_app_port} - WAITING for app to appear in Scheduler")
self.notification = Notification("Checking...", port = self.waiting_app_port)
self._animation_counter += delta/1000
return True
if hexdrive_app_version == CURRENT_APP_VERSION:
if self._settings['logging'].v:
print(f"H:HexDrive on port {self.waiting_app_port} has latest App")
self.ports_with_latest_hexdrive.add(self.waiting_app_port)
self.current_state = STATE_CHECK
else:
# Show the UI prompt and wait for button press
if self._settings['logging'].v:
print(f"H:HexDrive on port {self.waiting_app_port} needs upgrading from version {hexdrive_app_version}")
self.upgrade_port = self.waiting_app_port
self.notification = Notification("Upgrade?", port = self.upgrade_port)
self.current_state = STATE_UPGRADE
self.waiting_app_port = None
self._animation_counter = 0
return True
return False
def _update_state_help(self, delta):
if self.button_states.get(BUTTON_TYPES["CANCEL"]):
self.button_states.clear()
self.current_state = STATE_MENU
elif self.button_states.get(BUTTON_TYPES["CONFIRM"]):
self.button_states.clear()
self.is_scroll = True # so that release of this button will CLEAR Scroll mode
eventbus.on_async(ButtonUpEvent, self._handle_button_up, self)
self.current_state = STATE_RECEIVE_INSTR
else:
# Show the help for 10 seconds
self._animation_counter += delta/1000
if self._animation_counter > 10:
# after 10 seconds show the logo
self._animation_counter = 0
self.current_state = STATE_LOGO
def _update_state_receive_instr(self, delta):
# Enable/disable scrolling and check for long press
if self.button_states.get(BUTTON_TYPES["CONFIRM"]):
self.long_press_delta += delta
if self.long_press_delta >= _LONG_PRESS_MS:
# if there are no steps saved in the power plan then return to HELP, otherwise go to COUNTDOWN
if self.power_plan_iter is None:
self.current_state = STATE_HELP
else:
self.finalize_instruction()
self.current_state = STATE_COUNTDOWN
self.is_scroll = False
eventbus.remove(ButtonUpEvent, self._handle_button_up, self)
else:
# Confirm is not pressed. Reset long_press state
self.long_press_delta = 0