-
Notifications
You must be signed in to change notification settings - Fork 0
/
code.py
825 lines (641 loc) · 25.3 KB
/
code.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
#TODO
'''
Functionality changed. Inverted will show tomorrow's schedule.
Rightside up now show's today's schedule and automatically changes to Live Game
when a game is on.
- Favorite team details when turned vertically.
- IN PROGRESS. Fine-tune refresh times so MagTag only updates at midnight, just before a match, and then at regular intervals during a match.
- NOT POSSIBLE YET. In-game stats when available.
- DONE. remove need for Adafruit credentials
- DONE. (displaying current day schedule instead) Display next game info on Live Match page when no game is being played.
'''
# built-in modules
import gc
import time as atime
import alarm
import random
import rtc
import json
import supervisor
import board
import busio
from digitalio import DigitalInOut, Direction, Pull, DriveMode
from analogio import AnalogIn
import displayio
import terminalio
import ssl
import wifi
import socketpool
import ipaddress
# External Modules
# Time
from adafruit_bitmap_font import bitmap_font
from adafruit_display_text import bitmap_label as label
from adafruit_display_shapes.rect import Rect
# import adafruit_ntp
from adafruit_datetime import datetime, date, time, timedelta
# Network
import adafruit_requests as aio_requests
from adafruit_io.adafruit_io import IO_HTTP
# import adafruit_minimqtt.adafruit_minimqtt as MQTT
# from adafruit_io.adafruit_io import IO_MQTT
# Hardware
import adafruit_lis3dh
import neopixel
# See sample secrets.py file for details.
from secrets import secrets
# User Settings -----------
# WiFi Credentials
SSID = secrets["ssid"]
PASSWORD = secrets["password"]
# Change these to meet your location
TIME_ZONE_NAME = 'PST'
TIME_ZONE_OFFSET = -8
# Refresh times
GAME_ON_REFRESH = 12 # in seconds (10 sec minimum. API rate limit is 10.
GAME_OFF_REFRESH = (10 * 60) # in seconds
# For future, change to timezone of cup host
HOST_TIME = 3
# Configurations ------
# I2C Devices
i2c = busio.I2C(board.SCL, board.SDA, frequency=100000)
# Turn things off
NP_POWER = DigitalInOut(board.NEOPIXEL_POWER)
NP_POWER.switch_to_output(True) # OFF = True, ON = False
# set up hardware
lis = adafruit_lis3dh.LIS3DH_I2C(i2c, address=0x19)
voltage_pin = AnalogIn(board.VOLTAGE_MONITOR)
pixels = neopixel.NeoPixel(board.NEOPIXEL, 4, brightness=1, auto_write=True)
# Useful functions ---------
# a function to facilitate audio signals
def sound_signal(duration=0, frequency=0, time_off=0):
#TODO Add beep to signal a goal.
#
# board.SPEAKER
# board.SPEAKER_ENABLE
# SPEAKER_POWER.switch_to_output(False) # Flase = ON, True = OFF
return
# flashing LEDs routine
def np_signal(color=0x220000, flashes=3, interval=.15, time_off=1):
# NP_POWER.switch_to_output(False) # Flase = ON, True = OFF
for i in range(flashes):
atime.sleep(interval * time_off)
pixels.fill(color)
atime.sleep(interval)
pixels.fill(0)
def update_alert():
#TODO trigger an audo alert on goal change.
# sound_signal()
# Blink LEDs to signal a change in goals.
colors = [0x110900, 0x001111, 0x110011]
flashes = 1
interval = 0.5
time_off = 0.1
for i in range(len(colors)):
np_signal(color=colors[i], flashes=flashes,
interval=interval, time_off=time_off)
def goal_simulator(): # A simple function to simulate a new goal when testing.
add_goal = 0
rand_sequence = (1,3,9,7,2,8,0,6,5,4,)
rn = random.randint(0,9)
rand_num = rand_sequence[rn]
if rand_num < 3:
add_goal = 1
print(rand_num, add_goal)
return(add_goal)
# Data Update -------------------
# These lines activate board components.
# Be sure to load modules/drivers first.
def update_data():
# Turn things off
NP_POWER.switch_to_output(False)
# Light Sensor
# light = light_sensor.value
# light = (((light_sensor.value - 0) / 65535.0) * 3.3 * 2) * 10000
# Battery Voltage
# battery = voltage_pin.value
battery = ((voltage_pin.value / 65535.0) * 3.3 * 2) * 1
# On-board accelerometer
x, y, z = lis.acceleration
return(x, y, z, battery)
# Time Functions ------------------
# Adafruit delivers time based on user's IP.
# This function helps move time between time zones.
def local_time(hours = 0, minutes = 0, seconds = 0):
dt_current_time = datetime.fromtimestamp(atime.time()) # update the datetime object
show_date = dt_current_time + timedelta(hours = hours, minutes = minutes, seconds = seconds)
times = {
'ts' : atime.time(),
'iso' : show_date.isoformat(),
'ctime' : show_date.ctime(),
'date' : show_date.date(),
'time' : show_date.time()
}
return(times)
# POSIX / Unix Timestamp, always GMT.
# Uses TIME_ZONE_OFFSET to get GMT/UTC/Zulu time.
def ts():
now_time = local_time(hours = (-1 * TIME_ZONE_OFFSET), minutes = 0, seconds = 0)
return(now_time['ts'])
# Network Functions ------------------
def NETWORK_FUNCTIONS():
return
def wifi_connect(choice=0):
# Connect to local network
print("\nAvailable WiFi networks:")
for network in wifi.radio.start_scanning_networks():
print(" {:>18} RSSI: {:<4} Channel: {:<2}".format(
str(network.ssid, "utf-8"), network.rssi, network.channel ))
wifi.radio.stop_scanning_networks()
while not wifi.radio.ipv4_address:
try:
print("\nConnecting to {}".format(SSID))
wifi.radio.connect(SSID)
# wifi.radio.connect(SSID, PASSWORD)
except ConnectionError as e:
print("Connection Error: {}".format(e))
print("Retrying in 10 seconds")
print("Connected!\n")
np_signal(color=0x000100, flashes=3, interval=0.15, time_off=0.3)
atime.sleep(10)
gc.collect()
# MQTT Functions -----------
# Define callback functions which will be called when certain events happen.
# pylint: disable=unused-argument
def connected(client):
print("Connected to AIO, listening for feed updates ...")
# https://io.adafruit.com/api/docs/mqtt.html#time-seconds
# io.subscribe_to_time("hours")
io.subscribe_to_time("seconds")
# io.subscribe_to_time("iso")
def subscribe(client, userdata, topic, granted_qos):
# This method is called when the client subscribes to a new feed.
print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos))
def unsubscribe(client, userdata, topic, pid):
# This method is called when the client unsubscribes from a feed.
print("Unsubscribed from {0} with PID {1}".format(topic, pid))
# pylint: disable=unused-argument
def disconnected(client):
# Disconnected function will be called when the client disconnects.
print("Disconnected from Adafruit IO!")
# pylint: disable=unused-argument
def message(client, feed_id, payload):
# Message function will be called when a subscribed feed has a new value.
# The feed_id parameter identifies the feed, and the payload parameter has
# the new value.
ts = payload
print("Feed {0} received new value: {1}".format(feed_id, payload))
return(ts)
# World Cup Schedule functions --------------------
def TEXT_FORMAT():
return
# This function GETs today's schedule (GMT times).
def world_cup(hours = 0):
if wifi.radio.ipv4_gateway is None:
try:
import os
with open("wc_test_data.json", "r") as fp:
x = fp.read()
match_schedule = json.loads(x)
except OSError as e:
raise Exception("Could not read text file.")
page_title, the_schedule = wc_schedule(match_schedule)
else:
GET_DATE = ((local_time(hours=hours))['date'])
WORLD_CUP = 'https://worldcupjson.net/'
API_PARAMETERS = 'start_date={0}&end_date={0}'.format(GET_DATE)
# Fetching World Cup Today
json_header = {"Accept": "application/json"}
print("GETting schedule from:\n{}matches?{}".format(WORLD_CUP, API_PARAMETERS))
match_schedule = requests.get("{}matches?{}".format(WORLD_CUP, API_PARAMETERS), headers = json_header)
# matches_today.close()
match_schedule = match_schedule.json()
page_title, the_schedule = wc_schedule(match_schedule, hours)
game_info = True
return(game_info, the_schedule, page_title)
# Function to build schedule text for MagTag display
def wc_schedule(match_schedule, adjust_hours = 0):
# JSON times are Zulu/UTC/GMT
# Device is set to local time
title_date = ((local_time(hours = adjust_hours))['ctime'])[4:10]
if adjust_hours < 24:
tod_morrow = 'Today'
else:
tod_morrow = 'Tomorrow'
the_schedule = ''
page_title = ('{}: {}\n'.format(tod_morrow, title_date))
for i in match_schedule:
game_time = (i['datetime'])
game_time = (game_time[0:19])
game_time = (datetime.fromisoformat(game_time) + # Game time as local time.
timedelta(hours = TIME_ZONE_OFFSET))
schedule_items = [
i['away_team']['name'],
i['away_team']['goals'],
i['home_team']['name'],
i['home_team']['goals']
]
# I gotta learn List Comprehension.
# https://docs.python.org/3/tutorial/datastructures.html?highlight=list%20comprehension#list-comprehensions
schedule_items = ['' if v is None else v for v in schedule_items]
# home_team_goals = str(i['home_team']['goals'])
the_schedule = the_schedule + ('{:<5} {:>11} ({}) v ({}) {:<0}\n'.format(
str(game_time.time())[0:5],
schedule_items[0],
schedule_items[1],
schedule_items[3],
schedule_items[2],
))
return(page_title, the_schedule)
# Function GETs current game stats.
def wc_current(old_score):
if wifi.radio.ipv4_gateway is None:
import os
try:
with open("wc_current_match.json", "r") as fp:
x = fp.read()
# parse x:
current_match = json.loads(x)
except OSError as e:
raise Exception("Could not read text file.")
game_stats = match_stats(current_match, old_score)
print('Using test data.\n')
else:
WORLD_CUP = 'https://worldcupjson.net/'
# Fetch World Cup Today
json_header = {"Accept": "application/json"}
print("{}matches/current\n".format(WORLD_CUP))
current_match = requests.get("{}matches/current".format(WORLD_CUP), headers = json_header)
game_stats = match_stats(current_match.json(), old_score)
return(game_stats)
# This function parses information on the current match.
def match_stats(current_match, old_score):
try:
# Parse current_match
match_details = {
# Match Title
"away_team" : current_match[0]['home_team']['name'],
"home_team" : current_match[0]['away_team']['name'],
"away_team_goals" : current_match[0]['home_team']['goals'],
"home_team_goals" : current_match[0]['away_team']['goals'],
# General Info
"match_time" : current_match[0]['time'],
"location" : current_match[0]['location'],
"stage_name" : current_match[0]['stage_name'],
# Team Info
"away_tactics" : current_match[0]['home_team_lineup']['tactics'],
"away_penalties" : current_match[0]['home_team']['penalties'],
"home_tactics" : current_match[0]['away_team_lineup']['tactics'],
"home_penalties" : current_match[0]['away_team']['penalties']
}
if wifi.radio.ipv4_gateway is None:
add_goal = goal_simulator()
match_details['away_team_goals'] = (match_details['away_team_goals'] + add_goal)
new_score = (match_details['away_team_goals'], match_details['home_team_goals'])
if new_score == old_score:
new_goal = False
else:
new_goal = True
# Host Time
local_time_offset = (-1 * TIME_ZONE_OFFSET + HOST_TIME)
host_hours = (local_time(hours = local_time_offset))
host_hours = str(host_hours['time'])[0:5]
location = ('{!s}'.format(
match_details['location'], host_hours))
# Create texts
game_info = ('{:>7}{:^29}{:<12}'.format(
match_details['match_time'], match_details['stage_name'], location))
match_title = ('{1:>12}{0:^6}{2:<12}'.format(
'', match_details['away_team'], match_details['home_team']))
if new_goal:
game_score = ('{1:^7d}{0:^15}{2:^7d}'.format(
'Gol', match_details['away_team_goals'], match_details['home_team_goals']))
if not new_goal:
game_score = ('{1:^7d}{0:^15}{2:^7d}'.format(
'---', match_details['away_team_goals'], match_details['home_team_goals']))
game_tactics = ('{:>2}{:^21}{:<2}'.format(
match_details['away_tactics'], 'Tac', match_details['home_tactics']))
game_penalties = ('{:^7d}{:^21}{:^7d}'.format(
match_details['away_penalties'], 'Pen', match_details['home_penalties']))
old_score = new_score
except:
#TODO Determine next match and display basic stats.
# - GET list of upcoming matches
# - Convert times to timestamp for easy comparisons
# - Compare each game-time to local-time
# - Eliminate times before local-time
# - Select game with lowest of remaining time
# - Parse match data to display: Home & Away teams, time of match and time till match.
game_info = False
match_title = ''
game_score = ''
game_tactics = ''
game_penalties = ''
print('match_stats Old Goals: {}'.format(old_score))
game_stats = (game_info, match_title, game_score, game_tactics, game_penalties, old_score)
return(game_stats)
# Display Setup
def DISPLAY_SETUP():
return
# Display object
WIDTH = 296
HEIGHT = 128
display = board.DISPLAY
main_group = displayio.Group()
display.show(main_group)
# Font definitions
SPARTAN_LIGHT = bitmap_font.load_font("fonts/LeagueSpartan-Light.bdf")
SPARTAN_BOLD_16 = bitmap_font.load_font("fonts/LeagueSpartan-Bold-16.bdf")
HELVETICA_BOLD_16 = bitmap_font.load_font("fonts/Helvetica-Bold-16.bdf")
JUNCTION_24 = bitmap_font.load_font("fonts/Junction-regular-24.bdf")
TERMINAL_FONT = terminalio.FONT
def try_refresh():
try:
board.DISPLAY.refresh()
except RuntimeError as too_soon_error:
# catch refresh too soon
print(too_soon_error)
print("waiting before retry refresh()")
time.sleep(10)
board.DISPLAY.refresh()
# Create labels
# https://docs.circuitpython.org/projects/display_text/en/latest/api.html#adafruit-display-text
# https://github.com/adafruit/Adafruit_CircuitPython_Bitmap_Font/tree/main/examples/fonts
# if the screen is inverted:
def set_page_footer():
next_update_ts = ts() + refresh_time
next_update = str((datetime.fromtimestamp(next_update_ts)).time())[0:5]
page_footer = 'Bat: {:0.1f}v - Next: {}'.format(
battery, next_update)
return(page_footer)
# ------ Main Program ------
def MAIN_PROGRAM():
return
# Comment out for test mode and use cached JSON files.
# choice= option to choose what SSID to connect with.
wifi_connect(choice=0)
x, y, z, battery = update_data()
print("My gateway is {}".format(wifi.radio.ipv4_gateway))
print("My IP address is {}\n".format(wifi.radio.ipv4_address))
print('Battery: {}'.format(battery))
print('x: {} y: {} z: {}\n'.format(x, y, z))
# WiFi Setup ------------------
if wifi.radio.ipv4_gateway is None: # Use test data
now_time = str((local_time())['time'])[0:5]
print('The current time is: {}, ({})'.format(now_time, ts()))
else: # use live data
pool = socketpool.SocketPool(wifi.radio)
requests = aio_requests.Session(pool, ssl.create_default_context())
# For using NTP instead of AdafruitIO
'''
# set RTC clock
ntp = adafruit_ntp.NTP(pool, tz_offset=TIME_ZONE_OFFSET)
rtc.RTC().datetime = ntp.datetime
r = rtc.RTC()
now_time = local_time()
print('The current datetime is: {}, ({})'.format(now_time['iso'], ts()))
'''
# For storing data on AdafruitIO via MQTT
'''
# Initialize a new MQTT Client object
mqtt_client = MQTT.MQTT(
broker = "io.adafruit.com",
port = 1883,
username = secrets["aio_username"],
password = secrets["aio_key"],
socket_pool = pool,
ssl_context = ssl.create_default_context(),
)
# Initialize an Adafruit IO MQTT Client
io = IO_MQTT(mqtt_client)
# Connect the callback methods defined above to Adafruit IO
io.on_connect = connected
io.on_disconnect = disconnected
io.on_subscribe = subscribe
io.on_unsubscribe = unsubscribe
io.on_message = message
# Connect to Adafruit IO
io.connect()
print('\nConnected to Adafruit IO via MQTT')
the_schedule = world_cup()
io.loop()
ts = message()
ts = datetime.fromtimestamp(ts)
rtc.RTC().datetime = ts.datetime
r = rtc.RTC()
now_time = local_time()
print('The current datetime is: {}, ({})'.format(now_time['iso'], ts()))
'''
# AIO Time
# Get time from Adafruit public time server. Time can fetched as a regular GET
# request. This eliminates need for dedicated NTP library.
AIO_TIME = 'https://io.adafruit.com/api/v2/time/seconds' # POSIX/Unix timestamp
text_header = {"Accept": "application/text"}
print("Fetching time from Adafruit IO...\n")
# Set time using io.adafruit.com time feed
time_from_aio = requests.get('{}'.format(AIO_TIME), headers = text_header)
time_from_aio = (datetime.fromtimestamp(int(time_from_aio.text)))
time_from_aio = time_from_aio + timedelta(hours = TIME_ZONE_OFFSET)
rtc.RTC().datetime = time_from_aio.timetuple()
# Get local time
now_time = (local_time())['time']
print('The current time is: {}, ({})'.format(now_time, ts()))
# Screen Decision Routine
# Rotation determines what screen to display and refresh_time.
# Logic to display game stats when a game is live.
#TODO a vertical orientation to display favorite team details.
if y > 0:
def game_is_running():
return
inverted = False # Display live score
DISPLAY_ROTATION = 270
display.rotation = DISPLAY_ROTATION
refresh_time = GAME_ON_REFRESH # seconds
# refresh_time = 20 # seconds
old_game_stats = ('FIRST RUN', '','')
old_score = (0, 0)
while True:
game_stats = wc_current(old_score)
# game_stats = (game_info, match_title, game_score, game_tactics, game_penalties, old_goals)
print('{}\n\n{}\n\n{}\n\n'.format(game_stats[0], game_stats, old_game_stats))
if game_stats[2] == old_game_stats[2]:
gol = False
print('no new gol\n')
else:
print('NEW gol!\n')
gol = True
if game_stats[0] == False:
game_info = game_stats[0]
break
if game_stats == old_game_stats:
pass
else:
game_info = game_stats[0]
match_title = game_stats[1]
game_score = game_stats[2]
game_tactics = game_stats[3]
game_penalties = game_stats[4]
old_game_stats = game_stats
print(game_info)
print(match_title)
print(game_score)
print(game_tactics)
print(game_penalties)
page_footer = '{:0.1f}v'.format(battery)
print(page_footer)
# Label Setup
# Make the background white
rect = Rect(0, 0, WIDTH, HEIGHT, fill=0xFFFFFF, outline=0xFFFFFF)
game_page_title = label.Label(
SPARTAN_BOLD_16,
text=match_title,
color=0x000000,
anchored_position = (WIDTH * 0.5 + 0, HEIGHT * 0.5 - 46),
anchor_point = (0.5, 0.5),
base_alignment=True,
)
game_page_body1 = label.Label(
HELVETICA_BOLD_16,
scale = 1,
text=game_score,
color=0x000000,
anchored_position = (WIDTH * 0.5 + 0, HEIGHT * 0.5 - 26),
anchor_point = (0.5, 0.5),
base_alignment=True,
)
game_page_body2 = label.Label(
SPARTAN_LIGHT,
scale = 1,
text=game_tactics,
color=0x000000,
anchored_position = (WIDTH * 0.5 + 0, HEIGHT * 0.5 - 8),
anchor_point = (0.5, 0.5),
base_alignment=True,
)
game_page_body3 = label.Label(
SPARTAN_LIGHT,
scale = 1,
text=game_penalties,
color=0x000000,
anchored_position = (WIDTH * 0.5 + 0, HEIGHT * 0.5 + 10),
anchor_point = (0.5, 0.5),
base_alignment=True,
)
'''
WIDTH = 296
HEIGHT = 128
'''
game_page_body0 = label.Label(
TERMINAL_FONT,
scale = 1,
text=game_info,
color=0x000000,
anchor_point = (0.5, 1),
anchored_position = (WIDTH * 0.5 - 0, HEIGHT - 2),
base_alignment=True,
)
game_page_footer = label.Label(
TERMINAL_FONT,
text=page_footer,
bg_color=0xFFFFFF,
color=0x000000,
anchor_point = (1, 0),
anchored_position = (WIDTH - 3, 2),
base_alignment=True,
)
main_group.append(rect)
main_group.append(game_page_body0)
main_group.append(game_page_title)
main_group.append(game_page_body1)
main_group.append(game_page_body2)
main_group.append(game_page_body3)
main_group.append(game_page_footer)
# show the group
display.show(main_group)
# refresh display
if gol:
update_alert()
try_refresh()
print('\nnext update in {}s\n'.format(refresh_time))
atime.sleep(refresh_time)
print('Exiting game on loop.\n')
else:
def show_me_the_schedule():
return
inverted = True # Display schedule
DISPLAY_ROTATION = 90
refresh_time = GAME_OFF_REFRESH # seconds
print('Game is on: {}'.format(inverted))
print('Refresh: {}s\n'.format(refresh_time))
# game_info, match_title, game_score, game_tactics, game_penalties = wc_current()
game_info, the_schedule, page_title = world_cup(hours = 24)
print('\ninverted: {}\ngame_info: {}\n'.format(inverted, game_info))
# inverted = False & game_info = False then get tomorrow's schedule
if not game_info: # when the game ends or no game is running
inverted = True # This triggers the schedule routine.
DISPLAY_ROTATION = 270
refresh_time = GAME_OFF_REFRESH # seconds
print('Game is: {} / Info is: {}'.format(inverted, game_info))
print('Refresh: {}s\n'.format(refresh_time))
game_info, the_schedule, page_title = world_cup(hours = 0)
else:
print('Game is: {} / Info is: {}'.format(inverted, game_info))
print('Refresh: {}s\n'.format(refresh_time))
page_footer = set_page_footer()
print(str(game_info) + '\n')
print(page_title)
print(the_schedule)
print(page_footer)
# Make the background white
rect = Rect(0, 0, WIDTH, HEIGHT, fill=0xFFFFFF, outline=0xFFFFFF)
schedule_page_title = label.Label(
SPARTAN_BOLD_16,
text=page_title,
color=0x000000,
anchored_position = (10, 10),
anchor_point = (0, 0),
base_alignment=True,
)
schedule_page_body = label.Label(
TERMINAL_FONT,
scale = 1,
text=the_schedule,
color=0x000000,
anchored_position = (WIDTH * 0.5 - 0, HEIGHT * 0.5 + 0),
anchor_point = (0.5, 0.5),
base_alignment=True,
)
schedule_page_footer = label.Label(
TERMINAL_FONT,
text=page_footer,
bg_color=0xFFFFFF,
color=0x000000,
anchored_position = (WIDTH * 0.5 + 0, HEIGHT * 0.5 + 56),
anchor_point = (0.5, 0.5),
base_alignment=True,
)
display = board.DISPLAY
main_group = displayio.Group()
display.show(main_group)
display.rotation = DISPLAY_ROTATION
main_group.append(rect)
main_group.append(schedule_page_title)
main_group.append(schedule_page_body)
main_group.append(schedule_page_footer)
# show the group
display.show(main_group)
# refresh display
# update_alert()
try_refresh()
print('\nscreen refreshed\ngoing to sleep for {:0.0f} minutes.'.format(refresh_time/60))
# Turn things off:
wifi.radio.enabled = False
NP_POWER.switch_to_output(False) # Flase = ON, True = OFF
# SPEAKER_POWER.switch_to_output(False) # Flase = ON, True = OFF
def go_to_sleep():
return
# Create a an alarm
time_alarm = alarm.time.TimeAlarm(monotonic_time=atime.monotonic() + refresh_time)
# Exit the program, and then deep sleep until the alarm wakes us.
alarm.exit_and_deep_sleep_until_alarms(time_alarm)
# Does not return, so we never get here.