-
Notifications
You must be signed in to change notification settings - Fork 0
/
microbit.py
2043 lines (1588 loc) · 64.1 KB
/
microbit.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
### microbit.py v0.35
### A partial emulation of MicroPython micro:bit microbit library
### Tested with an Adafruit CLUE and CircuitPython and 5.3.1
### MIT License
### Copyright (c) 2020 Kevin J. Walters
### Copyright (c) 2016 British Broadcasting Corporation (pendolino3 font and symbols)
### Permission is hereby granted, free of charge, to any person obtaining a copy
### of this software and associated documentation files (the "Software"), to deal
### in the Software without restriction, including without limitation the rights
### to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
### copies of the Software, and to permit persons to whom the Software is
### furnished to do so, subject to the following conditions:
### The above copyright notice and this permission notice shall be included in all
### copies or substantial portions of the Software.
### THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
### IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
### FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
### AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
### LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
### OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
### SOFTWARE.
import array
import time
import math
import collections
### Need to avoid this style of importing as this may be used with "import *"
##from displayio import Bitmap, Group, Palette, TileGrid
import supervisor
import displayio
import terminalio
import analogio
import digitalio
import touchio
import pulseio
import gamepad
import board
import audiopwmio
import audiocore
### For MicroBitDisplayViewText and
### MicroBitDisplayViewEnhanced
try:
import adafruit_display_text.label
except ImportError:
print("No display text library: adafruit_display_text")
### For accelerometer
try:
import adafruit_lsm6ds.lsm6ds33
except ImportError:
print("No accelerometer library: adafruit_lsm6ds")
### For magnetometer / compass
try:
import adafruit_lis3mdl
except ImportError:
print("No magnetometer library: adafruit_lis3mdl")
### For light level
try:
import adafruit_apds9960.apds9960
except ImportError:
print("No light sensor library: adafruit_apds9960")
### For MicroBitDisplayViewEnhanced
try:
import display_pin
except ImportError:
print("No library: display_pin")
STD_IMAGE_WIDTH = 5
STD_IMAGE_HEIGHT = 5
STD_FONT_WIDTH = 5
STD_FONT_HEIGHT = 5
### This is a MicroBitDisplay brightness level, the micro:bit LED display
### actually offers 0-255
MAX_BRIGHTNESS = 9
### Conversion factors
_MICRO_TO_NANO = 1000
_MILLI_TO_MICRO = 1000
def _makeSample(length):
vol = 2 ** 15 - 1
midpoint = 2 ** 15
for s_idx in range(length):
yield round(vol * math.sin(2 * math.pi * (s_idx / length)) + midpoint)
class ClueSpeaker:
"""This allow the CLUE's tiny onboard speaker to be used as the
pin target for music.play(). """
_CLUE_LOW_FREQ = 40.0
def __init__(self):
self._audio = None
self._sample_len = 21
sine_wave = array.array("H", _makeSample(self._sample_len))
self._wave_sample = audiocore.RawSample(sine_wave)
def music_on(self):
if self._audio is None:
self._audio = audiopwmio.PWMAudioOut(board.SPEAKER)
def music_off(self):
if self._audio.playing:
self._audio.stop()
##self._audio.deinit()
##self._audio = None
def music_frequency(self, frequency,
desc=None, ### pylint: disable=unused-argument
):
### stop() needs to be called on a CLUE / PWMAudioOut
if self._audio.playing:
self._audio.stop()
### 0 turns off audio but also don't allow low frequencies
if frequency > self._CLUE_LOW_FREQ:
self._wave_sample.sample_rate = round(self._sample_len * frequency)
self._audio.play(self._wave_sample, loop=True)
def sleep(num_ms):
"""Sleep for num_ms milliseconds."""
time.sleep(num_ms / 1000)
def running_time():
"""In milliseconds since power up."""
return time.monotonic_ns() // 1000000
def panic(error_code):
### TODO - show or scroll??
raise NotImplementedError
def reset():
supervisor.reload()
### Some class to manage the calls to update()
### for MicroBitButton and MicroBitDisplay
class backGroundScheduler:
def __init__(self):
raise NotImplementedError
def run(self):
raise NotImplementedError
def _bytesToWidth(data, offset,
*,
width=5, height=5):
"""TODO. """
char_width = 5 ### default for whitespace
left_col = right_col = None
### Make a width "summary" row by mashing them all together with OR
row_mash = 0x00
for row in data[offset:offset + height]:
row_mash |= row
mask = 1 << (width - 1)
for col_idx in range(width):
if row_mash & mask:
if left_col is None or col_idx < left_col:
left_col = col_idx
if right_col is None or col_idx > right_col:
right_col = col_idx
mask >>= 1
### The Pendolino3 font has 1 pixel wide characters in column 1
### not column 0
if right_col is not None:
char_width = right_col + 1
return char_width
def _bytesToSeq(data, offset, seq_out,
*,
width=5, height=5, bg=0, fg=MAX_BRIGHTNESS):
"""TODO. """
seq_idx = 0
mask = 1 << (width - 1)
for row in data[offset:offset + height]:
row_data = row
for _ in range(width):
seq_out[seq_idx] = fg if row_data & mask else bg
seq_idx += 1
row_data <<= 1
def _bytesToCol(data, offset, column, seq_out,
*,
width=5, height=5, bg=0, fg=MAX_BRIGHTNESS):
"""TODO. """
mask = 0x01 << (width - column - 1)
for seq_idx, row in enumerate(data[offset:offset + height]):
seq_out[seq_idx] = fg if row & mask else bg
class MicroBitFonts:
### This is from https://github.com/lancaster-university/microbit-dal/blob/master/source/core/MicroBitFont.cpp pylint:disable=line-too-long
### 32 to 126, 5 bytes per char, 475 bytes total
PENDOLINO3 = (
b"\x00\x00\x00\x00\x00"
b"\x08\x08\x08\x00\x08"
b"\x0a\x4a\x40\x00\x00"
b"\x0a\x5f\xea\x5f\xea"
b"\x0e\xd9\x2e\xd3\x6e"
b"\x19\x32\x44\x89\x33"
b"\x0c\x92\x4c\x92\x4d"
b"\x08\x08\x00\x00\x00"
b"\x04\x88\x08\x08\x04"
b"\x08\x04\x84\x84\x88"
b"\x00\x0a\x44\x8a\x40"
b"\x00\x04\x8e\xc4\x80"
b"\x00\x00\x00\x04\x88"
b"\x00\x00\x0e\xc0\x00"
b"\x00\x00\x00\x08\x00"
b"\x01\x22\x44\x88\x10"
b"\x0c\x92\x52\x52\x4c"
b"\x04\x8c\x84\x84\x8e"
b"\x1c\x82\x4c\x90\x1e"
b"\x1e\xc2\x44\x92\x4c"
b"\x06\xca\x52\x5f\xe2"
b"\x1f\xf0\x1e\xc1\x3e"
b"\x02\x44\x8e\xd1\x2e"
b"\x1f\xe2\x44\x88\x10"
b"\x0e\xd1\x2e\xd1\x2e"
b"\x0e\xd1\x2e\xc4\x88"
b"\x00\x08\x00\x08\x00"
b"\x00\x04\x80\x04\x88"
b"\x02\x44\x88\x04\x82"
b"\x00\x0e\xc0\x0e\xc0"
b"\x08\x04\x82\x44\x88"
b"\x0e\xd1\x26\xc0\x04"
b"\x0e\xd1\x35\xb3\x6c"
b"\x0c\x92\x5e\xd2\x52"
b"\x1c\x92\x5c\x92\x5c"
b"\x0e\xd0\x10\x10\x0e"
b"\x1c\x92\x52\x52\x5c"
b"\x1e\xd0\x1c\x90\x1e"
b"\x1e\xd0\x1c\x90\x10"
b"\x0e\xd0\x13\x71\x2e"
b"\x12\x52\x5e\xd2\x52"
b"\x1c\x88\x08\x08\x1c"
b"\x1f\xe2\x42\x52\x4c"
b"\x12\x54\x98\x14\x92"
b"\x10\x10\x10\x10\x1e"
b"\x11\x3b\x75\xb1\x31"
b"\x11\x39\x35\xb3\x71"
b"\x0c\x92\x52\x52\x4c"
b"\x1c\x92\x5c\x90\x10"
b"\x0c\x92\x52\x4c\x86"
b"\x1c\x92\x5c\x92\x51"
b"\x0e\xd0\x0c\x82\x5c"
b"\x1f\xe4\x84\x84\x84"
b"\x12\x52\x52\x52\x4c"
b"\x11\x31\x31\x2a\x44"
b"\x11\x31\x35\xbb\x71"
b"\x12\x52\x4c\x92\x52"
b"\x11\x2a\x44\x84\x84"
b"\x1e\xc4\x88\x10\x1e"
b"\x0e\xc8\x08\x08\x0e"
b"\x10\x08\x04\x82\x41"
b"\x0e\xc2\x42\x42\x4e"
b"\x04\x8a\x40\x00\x00"
b"\x00\x00\x00\x00\x1f"
b"\x08\x04\x80\x00\x00"
b"\x00\x0e\xd2\x52\x4f"
b"\x10\x10\x1c\x92\x5c"
b"\x00\x0e\xd0\x10\x0e"
b"\x02\x42\x4e\xd2\x4e"
b"\x0c\x92\x5c\x90\x0e"
b"\x06\xc8\x1c\x88\x08"
b"\x0e\xd2\x4e\xc2\x4c"
b"\x10\x10\x1c\x92\x52"
b"\x08\x00\x08\x08\x08"
b"\x02\x40\x02\x42\x4c"
b"\x10\x14\x98\x14\x92"
b"\x08\x08\x08\x08\x06"
b"\x00\x1b\x75\xb1\x31"
b"\x00\x1c\x92\x52\x52"
b"\x00\x0c\x92\x52\x4c"
b"\x00\x1c\x92\x5c\x90"
b"\x00\x0e\xd2\x4e\xc2"
b"\x00\x0e\xd0\x10\x10"
b"\x00\x06\xc8\x04\x98"
b"\x08\x08\x0e\xc8\x07"
b"\x00\x12\x52\x52\x4f"
b"\x00\x11\x31\x2a\x44"
b"\x00\x11\x31\x35\xbb"
b"\x00\x12\x4c\x8c\x92"
b"\x00\x11\x2a\x44\x98"
b"\x00\x1e\xc4\x88\x1e"
b"\x06\xc4\x8c\x84\x86"
b"\x08\x08\x08\x08\x08"
b"\x18\x08\x0c\x88\x18"
b"\x00\x00\x0c\x83\x60"
)
STANDARD = PENDOLINO3
### PENDOLINO3_WIDTHS and STANDARD_WIDTHS attributes are created and
### added after the class has been created
### Can't do these inside class for some reason
MicroBitFonts.PENDOLINO3_WIDTHS = tuple(_bytesToWidth(MicroBitFonts.PENDOLINO3,
offset, width=5, height=5)
for offset in range(0, len(MicroBitFonts.PENDOLINO3), 5))
MicroBitFonts.STANDARD_WIDTHS = MicroBitFonts.PENDOLINO3_WIDTHS
### https://microbit-micropython.readthedocs.io/en/latest/microbit.html
###
### This is the actual type of microbit.display
class MicroBitDisplay():
def __init__(self, display=None, ### pylint: disable=redefined-outer-name
mode="basic",
*,
led_rows=5,
led_cols=5,
font=MicroBitFonts.STANDARD,
font_widths=MicroBitFonts.STANDARD_WIDTHS,
light_sensor=None,
exception=False,
display_show=True):
"""disp active display
mode "small", "enhanced", "basic"
"""
self.display = display
self._mode = None ### will be set by _initView
self.exception = exception
self._display_show = display_show
self.font = font
self.font_widths = font_widths
self.view = None ### will be set by _initView
self.view_update_count = 0
self._initView(display, mode,
led_rows=led_rows, led_cols=led_cols)
self._light_sensor = light_sensor
if light_sensor:
light_sensor.enable_color = True
self._showing = None
self._scrolling = None
self._led_rows = led_rows
self._led_cols = led_cols
self._leds = led_rows * led_cols * [0]
self._viewUpdate(None, None)
### Place the graphics on screen
if display_show and display:
display.show(self.view.group)
def deinint(self):
display.view.deinint()
if self._display_show and self.display:
display.show(None)
def _initView(self, display, ### pylint: disable=redefined-outer-name
mode,
*,
led_rows=5, led_cols=5):
self._mode = mode
self.view_update_count = 0
self.view = MicroBitDisplayView.makeView(mode,
display=display,
led_rows=led_rows, led_cols=led_cols)
def _viewUpdate(self, x_chg, y_chg, text=None, text_idx=None):
self.view.update(self._leds, x_chg, y_chg)
if text is not None and self.view_update_count == 0:
try:
self.view.updateString(text)
except AttributeError:
pass ### Optional method
if text_idx is not None:
try:
self.view.updateStringPos(text_idx)
except AttributeError:
pass ### Optional method
self.view_update_count += 1
def get_pixel(self, x, y):
return self._leds[x + y * self._led_cols]
def set_pixel(self, x, y, value):
if not 0 <= value <= MAX_BRIGHTNESS:
raise ValueError("value must be 0 to 9 inclusive")
idx = x + y * self._led_cols
old_value = self._leds[idx]
if value != old_value:
self._leds[idx] = value
self._viewUpdate(x, y)
def clear(self):
self._leds = self._led_rows * self._led_cols * [0]
self.view_update_count = 0
self._viewUpdate(None, None, text="")
### wait=False runs in the background - don't think we can do that
### or maybe could have an .update function with programmer
### committing to call that regularly (check adafruit_debouncer)
def show(self, value, delay=400,
*,
wait=True, loop=False, clear=False):
if not wait:
raise NotImplementedError
self.view_update_count = 0
### value can be all sorts of things including an image
if isinstance(value, MicroBitImage):
### TODO clear text
self.showImage(value)
return
show_seq = str(value) if isinstance(value, (int, float)) else value
if len(show_seq) == 1:
### TODO clear text
self.showItem(show_seq[0], seq=show_seq)
return ### Impl. on microbit has no delay for "a" or 5
elem_delay_s = delay / 1000.0
### TODO _showing needs to have loop and delay in too
self._showing = enumerate(show_seq)
while True:
try:
idx, elem = next(self._showing)
self.showItem(elem, seq=show_seq, seq_idx=idx)
time.sleep(elem_delay_s)
except StopIteration:
if loop:
self._showing = enumerate(show_seq)
else:
break
self._showing = None
if clear:
self.clear()
def showItem(self, item, seq=None, seq_idx=None):
"""Show a character or Image."""
if isinstance(item, MicroBitImage):
self.showImage(item)
elif isinstance(item, str) and len(item) == 1:
self.showCharacter(item, full_text=seq, text_idx=seq_idx)
else:
raise ValueError("Must be MicroBitImage or single character string.")
def showCharacter(self, char, *, bg=0, fg=MAX_BRIGHTNESS,
full_text=None, text_idx=None):
"""Show a character."""
### TODO - loads of font specific knowledge is burnt into this code
x = ord(char[0])
if not 32 <= x <= 126:
x = ord('?')
### Calculate offset into font data
f_idx = (x - 32) * 5 ### TODO
_bytesToSeq(self.font, f_idx, self._leds,
width=self._led_cols, height=self._led_rows, fg=fg, bg=bg)
self._viewUpdate(None, None, text=full_text, text_idx=text_idx)
def showImage(self, image):
"""This shows the image as it is but does not update it if image changes.
TODO - check how microbit behaves with a 3x3 - does it blank the border???
"""
src_idx = idx = 0
for _ in range(min(self._led_rows, image.height())):
for col_idx in range(min(self._led_cols, image.width())):
self._leds[idx + col_idx] = image.pixels[src_idx + col_idx]
src_idx += image.width()
idx += self._led_cols
self._viewUpdate(None, None)
### This scrolls the text one pixel (column) at a time
def scroll(self, value, delay=150, *, wait=True, loop=False, monospace=False):
if not wait:
raise NotImplementedError
### Clear screen
self.clear()
self.view_update_count = 0 ### This must be zeroed after clear()
scroll = {"text": value + " ",
"char_col": 0,
"idx" : 0,
"loop": loop,
"delay": delay / 1000.0}
self._scrolling = scroll
text_len = len(scroll["text"])
new_col = [0] * self._led_rows
while True:
text_idx = scroll["idx"]
if text_idx >= text_len:
if scroll["loop"]:
scroll["idx"] = 0
else:
break
text_idx = 0
char = scroll["text"][text_idx]
### TODO - yet another 5x5 font specific value below
width = 5 if monospace else self._getCharWidth(char)
### Add the thin column of whitespace if gone beyond last column
if scroll["char_col"] == width:
new_col = [0] * self._led_rows
else:
self._getCharCol(char,
scroll["char_col"],
new_col)
self._shiftLeftOne(new_column=new_col)
self._viewUpdate(None, None, text=scroll["text"], text_idx=text_idx)
scroll["char_col"] += 1
if scroll["char_col"] > width:
scroll["char_col"] = 0
scroll["idx"] += 1
time.sleep(scroll["delay"])
self._scrolling = None
def _shiftLeftOne(self, new_column=None):
last_row = self._led_rows - 1
col_idx = 0
if new_column is None:
new_column = [0] * self._led_rows
for idx in range(len(self._leds)):
if idx % self._led_cols == last_row:
self._leds[idx] = new_column[col_idx]
col_idx += 1
else:
self._leds[idx] = self._leds[idx + 1]
def _getCharCol(self, char, column, seq_out, *, bg=0, fg=MAX_BRIGHTNESS):
### TODO - loads of font specific knowledge is burnt into this code
### TODO - cut and paste with showCharacter
x = ord(char[0])
if not 32 <= x <= 126:
x = ord('?')
### Calculate offset into font data
f_idx = (x - 32) * 5 ### TODO
_bytesToCol(self.font, f_idx, column, seq_out,
width=self._led_cols, height=self._led_rows, fg=fg, bg=bg)
def _getCharWidth(self, char):
### TODO - loads of font specific knowledge is burnt into this code
### TODO - cut and paste with showCharacter
x = ord(char[0])
if not 32 <= x <= 126:
x = ord('?')
### Calculate offset into font data
f_idx = (x - 32) ### TODO
return self.font_widths[f_idx]
def tickUpdate(self):
"""Returns True if an update took place, False if complete and
None if no update is needed."""
if not self._showing and not self._scrolling:
return None
### Work out where timing goes - here or in caller
### caller may make more sense as simple form of scheduling
### requesting a rate
### do something
### this may need a timer, i.e. if something is due to happen in 50ms then wait for it
### otherwise return
still_updating = True
return still_updating
def on(self):
self._nopOrE()
def off(self):
self._nopOrE()
def _nopOrE(self):
if self.exception:
raise NotImplementedError
### Rather clever implementation on micro:bit although there is a visible flicker
def read_light_level(self):
""" TODO - this is 0-255, reads 30 on a micro:bit at my desk"""
if self._light_sensor:
### r,g,b,clear comes back from the APDS9960
return self._light_sensor.color_data[3] // 256
else:
raise RuntimeError("No light sensor configured - missing library?")
@property
def group(self):
return self.view.group
@property
def mode(self):
return self._mode
@mode.setter
def mode(self, data):
if self._mode != data:
if self.view:
self.view.deinit()
self._initView(self.display, data,
led_rows=self._led_rows,
led_cols=self._led_cols)
self._viewUpdate(None, None)
### Place the graphics on screen
if self._display_show and self.display:
self.display.show(self.view.group)
class MicroBitDisplayView:
### These are set after the sub-classes are defined
_VIEW_NAMES = []
_VIEW_CLASSES = []
def __init__(self, mode, display=None, ### pylint: disable=redefined-outer-name
):
if type(self) == MicroBitDisplayView: ### pylint: disable=unidiomatic-typecheck
raise TypeError("No MicroBitDisplayView for you - this must be subclassed")
self._mode = None ### Must be set for property mode to work
self._display = display
self._display_width = 240 if display is None else display.width
self._display_height = 240 if display is None else display.height
self._levels = 10
self.mode = mode ### property setting
@classmethod
def makeView(cls, view_name,
*, display=None, ### pylint: disable=redefined-outer-name
led_rows=5, led_cols=5):
### TODO - could replace this with a proper class registration scheme
try:
view_class = cls._VIEW_CLASSES[cls._VIEW_NAMES.index(view_name)]
except ValueError:
raise ValueError("Unknown view name")
view = view_class(display=display, led_rows=led_rows, led_cols=led_cols)
return view
def deinit(self):
pass
@property
def mode(self):
return self._mode
@mode.setter
def mode(self, data):
if self._mode is not None and self._mode != data:
self.deinit()
class MicroBitDisplayViewBasic(MicroBitDisplayView):
def __init__(self,
mode="basic", display=None, ### pylint: disable=redefined-outer-name
*, led_rows=5, led_cols=5, scale=None, group_extras=0):
### pylint: disable=too-many-locals
super().__init__(mode=mode,
display=display)
red_shades = self._levels
led_bitmap = displayio.Bitmap(led_cols, led_rows, red_shades)
self._led_bitmap = led_bitmap
self._led_count = led_cols * led_rows
### Make the number of shades of red required for display
palette = displayio.Palette(red_shades)
for idx in range(red_shades):
red_level = round(idx * 255 / (red_shades - 1))
palette[idx] = (red_level, 0, 0)
led_tg = displayio.TileGrid(led_bitmap, pixel_shader=palette)
self._led_tg = led_tg
min_display_dim = min(self._display_width, self._display_height)
if scale is None:
### 48x scale for 5x5
text_scale = min_display_dim // max(led_cols, led_rows)
x_pos = 0
else:
text_scale = scale
x_pos = (min_display_dim - scale * led_cols) // 2
led_group = displayio.Group(max_size=1, scale=text_scale)
led_group.x = x_pos
led_group.append(led_tg)
self._led_group = led_group
if group_extras:
disp_group = displayio.Group(max_size=1 + group_extras)
disp_group.append(led_group)
self.group = disp_group
else:
self.group = led_group ### A public attribute
def update(self, leds, x_chg, y_chg):
### TODO - respect the change hints
## self.led_bitmap[:] = leds ### NotImplementedError: Slices not supported
##af_mode = self._display.auto_refresh if self._display else None
##if af_mode:
## self._display.auto_refresh = False
for idx in range(min(len(leds), self._led_count)):
self._led_bitmap[idx] = leds[idx] ### trusting these are 0-9
##if af_mode:
## self._display.auto_refresh = af_mode
class MicroBitDisplayViewText(MicroBitDisplayView):
PIXEL_TEXT = "II" ### The text used for each pixel
VERY_DARK_GREY = 0x080808
def __init__(self, mode="text", display=None, ### pylint: disable=redefined-outer-name
*, led_rows=5, led_cols=5, scale=3):
### pylint: disable=too-many-locals
super().__init__(mode=mode,
display=display)
self._dio_font = terminalio.FONT
red_shades = self._levels
### initialise with level 0, a dim background colour
self._colours = [self.VERY_DARK_GREY] * self._levels
### then replace 1 onwards with red of varying intensity
for idx in range(1, red_shades):
red_level = round(idx * 255 / (red_shades - 1))
self._colours[idx] = red_level << 16 ### shift past G and B
text_group = displayio.Group(max_size=led_rows * led_cols,
scale=scale)
text_y_pos = 4 ### TODO - calc these
text_y_spacing = 17
text_x_spacing = 17
for _ in range(led_rows):
text_x_pos = 0
for _ in range(led_cols):
text_cell = adafruit_display_text.label.Label(text=self.PIXEL_TEXT,
font=self._dio_font,
color=self._colours[0])
text_cell.x = text_x_pos
text_cell.y = text_y_pos
text_group.append(text_cell)
text_x_pos += text_x_spacing
text_y_pos += text_y_spacing
self._led_text = text_group
self.group = text_group ### A public attribute
def update(self, leds, x_chg, y_chg):
### TODO - respect the change hints
## self.led_bitmap[:] = leds ### NotImplementedError: Slices not supported
##af_mode = self._display.auto_refresh if self._display else None
##if af_mode:
## self._display.auto_refresh = False
for idx in range(min(len(leds), len(self._led_text))):
### trusting these are 0-9
new_intensity = self._colours[leds[idx]]
if self._led_text[idx].color != new_intensity:
self._led_text[idx].color = new_intensity
##if af_mode:
## self._display.auto_refresh = af_mode
class MicroBitDisplayViewStandard(MicroBitDisplayView):
"""TODO - what was I planning here for Standard view????"""
def __init__(self, led_rows=5, led_cols=5):
super().__init__()
raise NotImplementedError("TODO!!!")
def update(self, leds, pos_x, pos_y):
raise NotImplementedError("TODO!!!")
class MicroBitDisplayViewSmall(MicroBitDisplayViewBasic):
def __init__(self, mode="small", display=None, ### pylint: disable=redefined-outer-name
*, led_rows=5, led_cols=5):
super().__init__(mode=mode,
display=display,
led_rows=led_rows, led_cols=led_cols,
scale=24)
def _pin_write_digital_cb(pin_obj, view, value):
view.updatePin(pin_obj.pin_name, "write_digital", value)
def _pin_read_digital_cb(pin_obj, view, value):
view.updatePin(pin_obj.pin_name, "read_digital", value)
def _pin_write_analog_cb(pin_obj, view, value):
view.updatePin(pin_obj.pin_name, "write_analog", value)
def _pin_read_analog_cb(pin_obj, view, value):
view.updatePin(pin_obj.pin_name, "read_analog", value)
def _pin_touch_cb(pin_obj, view, value):
view.updatePin(pin_obj.pin_name, "touch", value)
def _pin_music_frequency_cb(pin_obj, view, value_and_desc):
view.updatePin(pin_obj.pin_name, "music_frequency", value_and_desc)
### Maybe text could overlap in different colour?
### to preserve the pixel writing with wider text on the screen
class MicroBitDisplayViewEnhanced(MicroBitDisplayViewBasic):
### Something unclear going on with staticmethods here so punted them
### outside - .__func__ cannot be used in CP on staticmethods
_HOOKS = (("write_digital", _pin_write_digital_cb),
("read_digital", _pin_read_digital_cb),
("write_analog", _pin_write_analog_cb),
("read_analog", _pin_read_analog_cb),
("touch", _pin_touch_cb),
("music_frequency", _pin_music_frequency_cb),
)
_LARGE_PIN = (230, 62)
_MED_PIN = (230, 36)
_SMALL_PIN = (110, 24)
def __init__(self, mode="enhanced", display=None, ### pylint: disable=redefined-outer-name
*, led_rows=5, led_cols=5):
super().__init__(mode=mode,
display=display,
led_rows=led_rows, led_cols=led_cols,
scale=24,
group_extras=2 + 1)
self._text = None
self._text_idx = None
self._text_pane_font = terminalio.FONT
self._text_pane_char_width = 20 ### TODO - calc this
self._text_pane = adafruit_display_text.label.Label(text="",
max_glyphs=self._text_pane_char_width,
font=self._text_pane_font,
color=0xff0000,
scale=2)
self._text_pane_highlight_char = \
adafruit_display_text.label.Label(text="",
max_glyphs=1,
font=self._text_pane_font,
color=0xc0c0c0,
scale=2)
self._text_pane.y = 138 ### TODO - set properly
self._text_pane_highlight_char.y = self._text_pane.y
self.group.append(self._text_pane)
self.group.append(self._text_pane_highlight_char)
for method_name, func in self._HOOKS:
PinManager.addHookPins(method_name, func, self)
self._max_pins = 6 ### 3 rows of 2 columns = 6
self._pin_data = collections.OrderedDict()
self._pin_group = displayio.Group(max_size=self._max_pins)
self._pin_group.y = 156
self._pinarea_width = self._display_width
self._pinarea_height = self._display_width - 156 ### TODO
self.group.append(self._pin_group)
def deinit(self):
super().deinit()
for method_name, func in self._HOOKS:
_ = PinManager.removeHookPins(method_name, func, self)
def updateString(self, text):
self._text = text
if text == "":
self._text_pane.text = ""
self._text_pane_highlight_char.text = ""
elif len(text) <= self._text_pane_char_width:
self._text_pane.text = text
else:
self._text_pane.text = text[:self._text_pane_char_width]
### TODO jump scroll feature
def updateStringPos(self, text_idx):
if self._text_idx != text_idx and self._text is not None:
self._text_idx = text_idx
self._text_pane_highlight_char.text = self._text[text_idx]
self._text_pane_highlight_char.x = 2 * 6 * text_idx ### TODO
def _pinSize(self, num):
if num == 0:
return (None, None)
elif num == 1:
return self._LARGE_PIN
elif num == 2:
return self._MED_PIN
else:
return self._SMALL_PIN
def _adjustPinPosAndSize(self):
"""A very basic attempt at grid layout with dynamic sizing for up to six pins."""
### pylint: disable=too-many-locals
pins_shown = len(self._pin_data)
if pins_shown == 0:
return
pin_disp_size = self._pinSize(pins_shown)
rows = 2 if pins_shown == 2 else (pins_shown + 1) // 2
cols = 1 if pins_shown <= 2 else 2
pin_spacing = self._pinarea_height / rows ### float not int
new_pin_width, new_pin_height = pin_disp_size