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