Skip to content

Commit 4b2568e

Browse files
authored
Merge pull request #918 from cogliano/master
Code for new learning guide - PyPortal Smart Switch
2 parents 693f8f2 + e846a03 commit 4b2568e

File tree

4 files changed

+35808
-0
lines changed

4 files changed

+35808
-0
lines changed

PyPortal_Smart_Switch/code.py

Lines changed: 296 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,296 @@
1+
import time
2+
import gc
3+
import board
4+
import busio
5+
from adafruit_esp32spi import adafruit_esp32spi_socket as socket
6+
from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
7+
import adafruit_requests as requests
8+
import digitalio
9+
import analogio
10+
from adafruit_pyportal import PyPortal
11+
from adafruit_display_shapes.circle import Circle
12+
from adafruit_display_shapes.roundrect import RoundRect
13+
from adafruit_bitmap_font import bitmap_font
14+
from adafruit_display_text import label
15+
import adafruit_touchscreen
16+
17+
from adafruit_minimqtt import MQTT
18+
19+
DISPLAY_COLOR = 0x4444FF
20+
21+
# Switch location
22+
SWITCHX = 260
23+
SWITCHY = 4
24+
25+
FEED_NAME = "pyportal-switch"
26+
27+
months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN",
28+
"JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]
29+
30+
31+
def get_local_timestamp(location=None):
32+
# pylint: disable=line-too-long
33+
"""Fetch and "set" the local time of this microcontroller to the local time at the location, using an internet time API.
34+
:param str location: Your city and country, e.g. ``"New York, US"``.
35+
"""
36+
# pylint: enable=line-too-long
37+
api_url = None
38+
try:
39+
aio_username = secrets['aio_username']
40+
aio_key = secrets['aio_key']
41+
except KeyError:
42+
raise KeyError("\n\nOur time service requires a login/password to rate-limit. Please register for a free adafruit.io account and place the user/key in your secrets file under 'aio_username' and 'aio_key'")# pylint: disable=line-too-long
43+
44+
location = secrets.get('timezone', location)
45+
if location:
46+
print("Getting time for timezone", location)
47+
api_url = (TIME_SERVICE + "&tz=%s") % (aio_username, aio_key, location)
48+
else: # we'll try to figure it out from the IP address
49+
print("Getting time from IP address")
50+
api_url = TIME_SERVICE % (aio_username, aio_key)
51+
api_url += TIME_SERVICE_TIMESTAMP
52+
try:
53+
print("api_url:",api_url)
54+
response = requests.get(api_url)
55+
times = response.text.split(' ')
56+
seconds = int(times[0])
57+
tzoffset = times[1]
58+
tzhours = int(tzoffset[0:3])
59+
tzminutes = int(tzoffset[3:5])
60+
tzseconds = tzhours * 60 * 60
61+
if tzseconds < 0:
62+
tzseconds -= tzminutes * 60
63+
else:
64+
tzseconds += tzminutes * 60
65+
print(seconds + tzseconds, tzoffset, tzhours, tzminutes)
66+
except KeyError:
67+
raise KeyError("Was unable to lookup the time, try setting secrets['timezone'] according to http://worldtimeapi.org/timezones") # pylint: disable=line-too-long
68+
69+
# now clean up
70+
response.close()
71+
response = None
72+
gc.collect()
73+
return int(seconds + tzseconds)
74+
75+
def create_text_areas(configs):
76+
"""Given a list of area specifications, create and return text areas."""
77+
text_areas = []
78+
for cfg in configs:
79+
textarea = label.Label(cfg['font'], text=' '*cfg['size'])
80+
textarea.x = cfg['x']
81+
textarea.y = cfg['y']
82+
textarea.color = cfg['color']
83+
text_areas.append(textarea)
84+
return text_areas
85+
86+
class Switch(object):
87+
def __init__(self, pin, my_pyportal):
88+
self.switch = digitalio.DigitalInOut(pin)
89+
self.switch.direction = digitalio.Direction.OUTPUT
90+
rect = RoundRect(SWITCHX, SWITCHY, 31, 60, 16, fill=0x0, outline=DISPLAY_COLOR, stroke=3)
91+
my_pyportal.splash.append(rect)
92+
self.circle_on = Circle(SWITCHX + 15, SWITCHY + 16, 10, fill=0x0)
93+
my_pyportal.splash.append(self.circle_on)
94+
self.circle_off = Circle(SWITCHX + 15, SWITCHY + 42, 10, fill=DISPLAY_COLOR)
95+
my_pyportal.splash.append(self.circle_off)
96+
97+
# turn switch on or off
98+
def enable(self, enable):
99+
print("turning switch to ", enable)
100+
self.switch.value = enable
101+
if enable:
102+
self.circle_off.fill = 0x0
103+
self.circle_on.fill = DISPLAY_COLOR
104+
else:
105+
self.circle_on.fill = 0x0
106+
self.circle_off.fill = DISPLAY_COLOR
107+
108+
def toggle(self):
109+
if self.switch.value:
110+
self.enable(False)
111+
else:
112+
self.enable(True)
113+
114+
def status(self):
115+
return self.switch.value
116+
117+
# you'll need to pass in an io username and key
118+
TIME_SERVICE = "http://io.adafruit.com/api/v2/%s/integrations/time/strftime?x-aio-key=%s"
119+
# See https://apidock.com/ruby/DateTime/strftime for full options
120+
TIME_SERVICE_TIMESTAMP = '&fmt=%25s+%25z'
121+
122+
class Clock(object):
123+
def __init__(self, my_pyportal):
124+
self.low_light = False
125+
self.update_time = None
126+
self.snapshot_time = None
127+
self.pyportal = my_pyportal
128+
self.current_time = 0
129+
self.light = analogio.AnalogIn(board.LIGHT)
130+
text_area_configs = [dict(x=0, y=110, size=10, color=DISPLAY_COLOR, font=time_font),
131+
dict(x=260, y=165, size=3, color=DISPLAY_COLOR, font=ampm_font),
132+
dict(x=10, y=40, size=20, color=DISPLAY_COLOR, font=date_font)]
133+
self.text_areas = create_text_areas(text_area_configs)
134+
self.text_areas[2].text = "starting ..."
135+
for ta in self.text_areas:
136+
self.pyportal.splash.append(ta)
137+
138+
def adjust_backlight(self, force=False):
139+
"""Check light level. Adjust the backlight and background image if it's dark."""
140+
if force or (self.light.value >= 1500 and self.low_light):
141+
self.pyportal.set_backlight(1.00)
142+
self.low_light = False
143+
elif self.light.value <= 1000 and not self.low_light:
144+
self.pyportal.set_backlight(0.1)
145+
self.low_light = True
146+
147+
def tick(self, now):
148+
self.adjust_backlight()
149+
if (not self.update_time) or ((now - self.update_time) >= 300):
150+
# Update the time
151+
print("update the time")
152+
self.update_time = int(now)
153+
self.snapshot_time = get_local_timestamp(secrets['timezone'])
154+
self.current_time = time.localtime(self.snapshot_time)
155+
else:
156+
self.current_time = time.localtime(int(now) - self.update_time + self.snapshot_time)
157+
hour = self.current_time.tm_hour
158+
if hour > 12:
159+
hour = hour % 12
160+
if hour == 0:
161+
hour = 12
162+
time_string = '%2d:%02d' % (hour,self.current_time.tm_min)
163+
self.text_areas[0].text = time_string
164+
ampm_string = "AM"
165+
if self.current_time.tm_hour >= 12:
166+
ampm_string = "PM"
167+
self.text_areas[1].text = ampm_string
168+
self.text_areas[2].text = (months[int(self.current_time.tm_mon - 1)] +
169+
" " + str(self.current_time.tm_mday))
170+
board.DISPLAY.refresh_soon()
171+
board.DISPLAY.wait_for_frame()
172+
173+
# Define callback methods which are called when events occur
174+
# pylint: disable=unused-argument, redefined-outer-name
175+
def connected(client, userdata, flags, rc):
176+
# This function will be called when the client is connected
177+
# successfully to the broker.
178+
onoff_feed = secrets['aio_username'] + '/feeds/' + FEED_NAME
179+
print('Connected to Adafruit IO! Listening for topic changes on %s' % onoff_feed)
180+
# Subscribe to all changes on the onoff_feed.
181+
client.subscribe(onoff_feed)
182+
183+
def disconnected(client, userdata, rc):
184+
# This method is called when the client is disconnected
185+
print('Disconnected from Adafruit IO!')
186+
187+
def message(client, topic, message):
188+
# This method is called when a topic the client is subscribed to
189+
# has a new message.
190+
print('New message on topic {0}: {1}'.format(topic, message))
191+
if message in ("ON","TRUE","1"):
192+
switch.enable(True)
193+
else:
194+
switch.enable(False)
195+
196+
############################################
197+
198+
try:
199+
from secrets import secrets
200+
except ImportError:
201+
print("""WiFi settings are kept in secrets.py, please add them there!
202+
the secrets dictionary must contain 'ssid' and 'password' at a minimum""")
203+
raise
204+
205+
esp32_cs = digitalio.DigitalInOut(board.ESP_CS)
206+
esp32_ready = digitalio.DigitalInOut(board.ESP_BUSY)
207+
esp32_reset = digitalio.DigitalInOut(board.ESP_RESET)
208+
209+
WIDTH = board.DISPLAY.width
210+
HEIGHT = board.DISPLAY.height
211+
212+
ts = adafruit_touchscreen.Touchscreen(board.TOUCH_XL, board.TOUCH_XR,
213+
board.TOUCH_YD, board.TOUCH_YU,
214+
calibration=(
215+
(5200, 59000),
216+
(5800, 57000)
217+
),
218+
size=(WIDTH, HEIGHT))
219+
220+
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
221+
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset, debug=False)
222+
requests.set_socket(socket, esp)
223+
224+
if esp.status == adafruit_esp32spi.WL_IDLE_STATUS:
225+
print("ESP32 found and in idle mode")
226+
print("Firmware vers.", esp.firmware_version)
227+
print("MAC addr:", [hex(i) for i in esp.MAC_address])
228+
229+
pyportal = PyPortal(esp=esp, external_spi=spi)
230+
231+
ampm_font = bitmap_font.load_font("/fonts/RobotoMono-18.bdf")
232+
ampm_font.load_glyphs(b'ampAMP')
233+
date_font = bitmap_font.load_font("/fonts/RobotoMono-18.bdf")
234+
date_font.load_glyphs(b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789')
235+
time_font = bitmap_font.load_font("/fonts/RobotoMono-72.bdf")
236+
time_font.load_glyphs(b'0123456789:')
237+
238+
clock = Clock(pyportal)
239+
240+
for ap in esp.scan_networks():
241+
print("\t%s\t\tRSSI: %d" % (str(ap['ssid'], 'utf-8'), ap['rssi']))
242+
243+
print("Connecting to AP...")
244+
while not esp.is_connected:
245+
try:
246+
esp.connect_AP(secrets['ssid'], secrets['password'])
247+
except RuntimeError as e:
248+
print("could not connect to AP, retrying: ",e)
249+
continue
250+
print("Connected to", str(esp.ssid, 'utf-8'), "\tRSSI:", esp.rssi)
251+
print("My IP address is", esp.pretty_ip(esp.ip_address))
252+
253+
254+
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(
255+
esp, secrets, debug = True)
256+
257+
258+
# Set up a MiniMQTT Client
259+
mqtt_client = MQTT(socket,
260+
broker='io.adafruit.com',
261+
username=secrets['aio_username'],
262+
password=secrets['aio_key'],
263+
network_manager=wifi)
264+
265+
mqtt_client.on_connect = connected
266+
mqtt_client.on_disconnect = disconnected
267+
mqtt_client.on_message = message
268+
269+
mqtt_client.connect()
270+
271+
switch = Switch(board.D4, pyportal)
272+
273+
second_timer = time.monotonic()
274+
while True:
275+
#time.sleep(1)
276+
p = ts.touch_point
277+
if p:
278+
#if p[0] >= 140 and p[0] <= 170 and p[1] >= 160 and p[1] <= 220:
279+
# touch anywhere on the screen
280+
print("touch!")
281+
clock.adjust_backlight(True)
282+
switch.toggle()
283+
time.sleep(1)
284+
285+
# poll once per second
286+
if time.monotonic() - second_timer >= 1.0:
287+
second_timer = time.monotonic()
288+
# Poll the message queue
289+
try:
290+
mqtt_client.loop()
291+
except RuntimeError:
292+
print("reconnecting wifi")
293+
mqtt_client.reconnect_wifi()
294+
295+
# Update the PyPortal display
296+
clock.tick(time.monotonic())

0 commit comments

Comments
 (0)