|
| 1 | +# SPDX-FileCopyrightText: 2024 Liz Clark for Adafruit Industries |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: MIT |
| 4 | + |
| 5 | +import time |
| 6 | +import os |
| 7 | +import ssl |
| 8 | +import wifi |
| 9 | +import socketpool |
| 10 | +import microcontroller |
| 11 | +import board |
| 12 | +import digitalio |
| 13 | +import adafruit_requests |
| 14 | +from adafruit_io.adafruit_io import IO_HTTP, AdafruitIO_RequestError |
| 15 | + |
| 16 | +aio_username = os.getenv("ADAFRUIT_AIO_USERNAME") |
| 17 | +aio_key = os.getenv("ADAFRUIT_AIO_KEY") |
| 18 | + |
| 19 | +# buttons |
| 20 | +button = digitalio.DigitalInOut(board.D5) |
| 21 | +button.direction = digitalio.Direction.INPUT |
| 22 | +button.pull = digitalio.Pull.UP |
| 23 | +button_state = False |
| 24 | + |
| 25 | +lights_on = False |
| 26 | + |
| 27 | +print() |
| 28 | +print("Connecting to WiFi...") |
| 29 | +# connect to your SSID |
| 30 | +wifi.radio.connect(os.getenv('CIRCUITPY_WIFI_SSID'), os.getenv('CIRCUITPY_WIFI_PASSWORD')) |
| 31 | +print("Connected to WiFi!") |
| 32 | + |
| 33 | +pool = socketpool.SocketPool(wifi.radio) |
| 34 | +requests = adafruit_requests.Session(pool, ssl.create_default_context()) |
| 35 | + |
| 36 | +io = IO_HTTP(aio_username, aio_key, requests) |
| 37 | + |
| 38 | +try: |
| 39 | + feed_lights = io.get_feed("lights") |
| 40 | +except AdafruitIO_RequestError: |
| 41 | + feed_lights = io.create_new_feed("lights") |
| 42 | + |
| 43 | +while True: |
| 44 | + try: |
| 45 | + if not button.value and button_state: |
| 46 | + button_state = False |
| 47 | + if button.value and not button_state: |
| 48 | + print("pressed") |
| 49 | + lights_on = not lights_on |
| 50 | + io.send_data(feed_lights["key"], int(lights_on)) |
| 51 | + button_state = True |
| 52 | + except Exception as error: # pylint: disable=broad-except |
| 53 | + print(error) |
| 54 | + time.sleep(5) |
| 55 | + microcontroller.reset() |
0 commit comments