esp_atcontrol_cheerlights.py
1 import time 2 import board 3 import busio 4 from digitalio import DigitalInOut 5 from digitalio import Direction 6 7 # ESP32 SPI 8 from adafruit_espatcontrol import ( 9 adafruit_espatcontrol, 10 adafruit_espatcontrol_wifimanager, 11 ) 12 13 14 import neopixel 15 import adafruit_fancyled.adafruit_fancyled as fancy 16 17 18 # Get wifi details and more from a secrets.py file 19 try: 20 from secrets import secrets 21 except ImportError: 22 print("WiFi secrets are kept in secrets.py, please add them there!") 23 raise 24 25 26 # With a Particle Argon 27 RX = board.ESP_TX 28 TX = board.ESP_RX 29 resetpin = DigitalInOut(board.ESP_WIFI_EN) 30 rtspin = DigitalInOut(board.ESP_CTS) 31 uart = busio.UART(TX, RX, timeout=0.1) 32 esp_boot = DigitalInOut(board.ESP_BOOT_MODE) 33 esp_boot.direction = Direction.OUTPUT 34 esp_boot.value = True 35 status_light = None 36 37 print("ESP AT commands") 38 esp = adafruit_espatcontrol.ESP_ATcontrol( 39 uart, 115200, reset_pin=resetpin, rts_pin=rtspin, debug=False 40 ) 41 wifi = adafruit_espatcontrol_wifimanager.ESPAT_WiFiManager(esp, secrets, status_light) 42 43 44 DATA_SOURCE = "https://api.thingspeak.com/channels/1417/feeds.json?results=1" 45 DATA_LOCATION = ["feeds", 0, "field2"] 46 47 48 # neopixels 49 pixels = neopixel.NeoPixel(board.A1, 16, brightness=0.3) 50 pixels.fill(0) 51 52 # we'll save the value in question 53 last_value = value = None 54 55 while True: 56 try: 57 print("Fetching json from", DATA_SOURCE) 58 response = wifi.get(DATA_SOURCE) 59 print(response.json()) 60 value = response.json() 61 for key in DATA_LOCATION: 62 value = value[key] 63 print(value) 64 response.close() 65 except (ValueError, RuntimeError, adafruit_espatcontrol.OKError) as e: 66 print("Failed to get data, retrying\n", e) 67 wifi.reset() 68 continue 69 70 if not value: 71 continue 72 if last_value != value: 73 color = int(value[1:], 16) 74 red = color >> 16 & 0xFF 75 green = color >> 8 & 0xFF 76 blue = color & 0xFF 77 gamma_corrected = fancy.gamma_adjust(fancy.CRGB(red, green, blue)).pack() 78 79 pixels.fill(gamma_corrected) 80 last_value = value 81 response = None 82 time.sleep(60)