Skip to content

Commit 89f30f3

Browse files
committed
Initial commit
1 parent 5869d46 commit 89f30f3

File tree

4 files changed

+35805
-0
lines changed

4 files changed

+35805
-0
lines changed

PyPortal_Smart_Switch/code.py

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

0 commit comments

Comments
 (0)