Skip to content

Commit c691fe9

Browse files
authored
Merge pull request #2108 from makermelissa/main
Updated Google Calendar example to make better use of MagTag library
2 parents d9e1188 + 700f7f4 commit c691fe9

File tree

2 files changed

+63
-89
lines changed

2 files changed

+63
-89
lines changed

MagTag_Google_Calendar/authenticator.py

Lines changed: 10 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,10 @@
11
# SPDX-FileCopyrightText: 2021 Brent Rubell, written for Adafruit Industries
22
#
33
# SPDX-License-Identifier: Unlicense
4-
import ssl
5-
import board
6-
import wifi
7-
import socketpool
8-
import adafruit_requests as requests
94
from adafruit_oauth2 import OAuth2
105
from adafruit_display_text.label import Label
116
from adafruit_bitmap_font import bitmap_font
12-
from adafruit_magtag.magtag import Graphics
7+
from adafruit_magtag.magtag import Graphics, Network
138
from adafruit_display_shapes.rect import Rect
149

1510
# Add a secrets.py to your filesystem that has a dictionary called secrets with "ssid" and
@@ -22,12 +17,8 @@
2217
print("Credentials and tokens are kept in secrets.py, please add them there!")
2318
raise
2419

25-
print("Connecting to %s" % secrets["ssid"])
26-
wifi.radio.connect(secrets["ssid"], secrets["password"])
27-
print("Connected to %s!" % secrets["ssid"])
28-
29-
pool = socketpool.SocketPool(wifi.radio)
30-
requests = requests.Session(pool, ssl.create_default_context())
20+
network = Network()
21+
network.connect()
3122

3223
# DisplayIO setup
3324
font_small = bitmap_font.load_font("/fonts/Arial-12.pcf")
@@ -49,14 +40,10 @@
4940
)
5041
graphics.splash.append(label_overview_text)
5142

52-
label_verification_url = Label(
53-
font_small, x=0, y=40, line_spacing=0.75, color=0x000000
54-
)
43+
label_verification_url = Label(font_small, x=0, y=40, line_spacing=0.75, color=0x000000)
5544
graphics.splash.append(label_verification_url)
5645

57-
label_user_code = Label(
58-
font_small, x=0, y=80, color=0x000000, line_spacing=0.75
59-
)
46+
label_user_code = Label(font_small, x=0, y=80, color=0x000000, line_spacing=0.75)
6047
graphics.splash.append(label_user_code)
6148

6249
label_qr_code = Label(
@@ -69,7 +56,10 @@
6956

7057
# Initialize an OAuth2 object
7158
google_auth = OAuth2(
72-
requests, secrets["google_client_id"], secrets["google_client_secret"], scopes
59+
network.requests,
60+
secrets["google_client_id"],
61+
secrets["google_client_secret"],
62+
scopes,
7363
)
7464

7565
# Request device and user codes
@@ -91,7 +81,7 @@
9181
label_user_code.text = "2. Enter code: %s" % google_auth.user_code
9282

9383
graphics.qrcode(google_auth.verification_url.encode(), qr_size=2, x=240, y=70)
94-
board.DISPLAY.show(graphics.splash)
84+
graphics.display.show(graphics.splash)
9585
display.refresh()
9686

9787
# Poll Google's authorization server

MagTag_Google_Calendar/code.py

Lines changed: 53 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,9 @@
22
#
33
# SPDX-License-Identifier: Unlicense
44
import time
5-
import ssl
6-
import board
75
import rtc
8-
import wifi
9-
import socketpool
10-
import adafruit_requests as requests
116
from adafruit_oauth2 import OAuth2
127
from adafruit_display_shapes.line import Line
13-
from adafruit_bitmap_font import bitmap_font
14-
from adafruit_display_text import label
158
from adafruit_magtag.magtag import MagTag
169

1710
# Calendar ID
@@ -59,17 +52,16 @@
5952
print("Credentials and tokens are kept in secrets.py, please add them there!")
6053
raise
6154

62-
print("Connecting to %s" % secrets["ssid"])
63-
wifi.radio.connect(secrets["ssid"], secrets["password"])
64-
print("Connected to %s!" % secrets["ssid"])
55+
# Create a new MagTag object
56+
magtag = MagTag()
57+
r = rtc.RTC()
6558

66-
pool = socketpool.SocketPool(wifi.radio)
67-
requests = requests.Session(pool, ssl.create_default_context())
59+
magtag.network.connect()
6860

6961
# Initialize an OAuth2 object with GCal API scope
7062
scopes = ["https://www.googleapis.com/auth/calendar.readonly"]
7163
google_auth = OAuth2(
72-
requests,
64+
magtag.network.requests,
7365
secrets["google_client_id"],
7466
secrets["google_client_secret"],
7567
scopes,
@@ -86,15 +78,17 @@ def get_current_time(time_max=False):
8678
cur_time = r.datetime
8779
if time_max: # maximum time to fetch events is midnight (4:59:59UTC)
8880
cur_time_max = time.struct_time(
89-
cur_time[0],
90-
cur_time[1],
91-
cur_time[2] + 1,
92-
4,
93-
59,
94-
59,
95-
cur_time[6],
96-
cur_time[7],
97-
cur_time[8],
81+
(
82+
cur_time[0],
83+
cur_time[1],
84+
cur_time[2] + 1,
85+
4,
86+
59,
87+
59,
88+
cur_time[6],
89+
cur_time[7],
90+
cur_time[8],
91+
)
9892
)
9993
cur_time = cur_time_max
10094
cur_time = "{:04d}-{:02d}-{:02d}T{:02d}:{:02d}:{:02d}{:s}".format(
@@ -126,7 +120,7 @@ def get_calendar_events(calendar_id, max_events, time_min):
126120
"/events?maxResults={1}&timeMin={2}&timeMax={3}&orderBy=startTime"
127121
"&singleEvents=true".format(calendar_id, max_events, time_min, time_max)
128122
)
129-
resp = requests.get(url, headers=headers)
123+
resp = magtag.network.requests.get(url, headers=headers)
130124
resp_json = resp.json()
131125
if "error" in resp_json:
132126
raise RuntimeError("Error:", resp_json)
@@ -186,76 +180,66 @@ def display_calendar_events(resp_events):
186180
print("Event Time:", format_datetime(event_start))
187181
print("-" * 40)
188182
# Generate labels holding event info
189-
label_event_time = label.Label(
190-
font_event,
191-
x=7,
192-
y=40 + (event_idx * 35),
193-
color=0x000000,
183+
magtag.add_text(
184+
text_font=font_event,
185+
text_position=(7, 40 + (event_idx * 35)),
186+
text_color=0x000000,
194187
text=format_datetime(event_start),
195188
)
196-
magtag.splash.append(label_event_time)
197-
198-
label_event_desc = label.Label(
199-
font_event,
200-
x=88,
201-
y=40 + (event_idx * 35),
202-
color=0x000000,
189+
magtag.add_text(
190+
text_font=font_event,
191+
text_position=(88, 40 + (event_idx * 35)),
192+
text_color=0x000000,
203193
text=event_name,
204194
line_spacing=0.65,
205195
)
206-
magtag.splash.append(label_event_desc)
207196

208197

209-
# Create a new MagTag object
210-
magtag = MagTag()
211-
r = rtc.RTC()
212-
213198
# DisplayIO Setup
214199
magtag.set_background(0xFFFFFF)
215200

216201
# Add the header
217202
line_header = Line(0, 30, 320, 30, color=0x000000)
218203
magtag.splash.append(line_header)
219204

220-
font_h1 = bitmap_font.load_font("fonts/Arial-18.pcf")
221-
label_header = label.Label(font_h1, x=5, y=15, color=0x000000)
222-
magtag.splash.append(label_header)
205+
label_header = magtag.add_text(
206+
text_font="fonts/Arial-18.pcf",
207+
text_position=(5, 15),
208+
text_color=0x000000,
209+
)
223210

224211
# Set up calendar event fonts
225-
font_event = bitmap_font.load_font("fonts/Arial-12.pcf")
212+
font_event = "fonts/Arial-12.pcf"
226213

227214
if not google_auth.refresh_access_token():
228215
raise RuntimeError("Unable to refresh access token - has the token been revoked?")
229216
access_token_obtained = int(time.monotonic())
230217

231-
while True:
232-
# check if we need to refresh token
233-
if (
234-
int(time.monotonic()) - access_token_obtained
235-
>= google_auth.access_token_expiration
236-
):
237-
print("Access token expired, refreshing...")
238-
if not google_auth.refresh_access_token():
239-
raise RuntimeError(
240-
"Unable to refresh access token - has the token been revoked?"
241-
)
242-
access_token_obtained = int(time.monotonic())
218+
# check if we need to refresh token
219+
if int(time.monotonic()) - access_token_obtained >= google_auth.access_token_expiration:
220+
print("Access token expired, refreshing...")
221+
if not google_auth.refresh_access_token():
222+
raise RuntimeError(
223+
"Unable to refresh access token - has the token been revoked?"
224+
)
225+
access_token_obtained = int(time.monotonic())
243226

244-
# fetch calendar events!
245-
print("fetching local time...")
246-
now = get_current_time()
227+
# fetch calendar events!
228+
print("fetching local time...")
229+
now = get_current_time()
247230

248-
# setup header label
249-
label_header.text = format_datetime(now, pretty_date=True)
231+
# setup header label
232+
magtag.set_text(
233+
format_datetime(now, pretty_date=True), label_header, auto_refresh=False
234+
)
250235

251-
print("fetching calendar events...")
252-
events = get_calendar_events(CALENDAR_ID, MAX_EVENTS, now)
236+
print("fetching calendar events...")
237+
events = get_calendar_events(CALENDAR_ID, MAX_EVENTS, now)
253238

254-
print("displaying events")
255-
display_calendar_events(events)
239+
print("displaying events")
240+
display_calendar_events(events)
256241

257-
board.DISPLAY.show(magtag.splash)
258-
board.DISPLAY.refresh()
242+
magtag.graphics.display.refresh()
259243

260-
print("Sleeping for %d minutes" % REFRESH_TIME)
261-
magtag.exit_and_deep_sleep(REFRESH_TIME * 60)
244+
print("Sleeping for %d minutes" % REFRESH_TIME)
245+
magtag.exit_and_deep_sleep(REFRESH_TIME * 60)

0 commit comments

Comments
 (0)