esp32spi_localtime.py
1 # SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries 2 # SPDX-License-Identifier: MIT 3 4 import time 5 import board 6 import busio 7 from digitalio import DigitalInOut 8 import neopixel 9 from adafruit_esp32spi import adafruit_esp32spi 10 from adafruit_esp32spi import adafruit_esp32spi_wifimanager 11 import rtc 12 13 # Get wifi details and more from a secrets.py file 14 try: 15 from secrets import secrets 16 except ImportError: 17 print("WiFi secrets are kept in secrets.py, please add them there!") 18 raise 19 20 print("ESP32 local time") 21 22 TIME_API = "http://worldtimeapi.org/api/ip" 23 24 esp32_cs = DigitalInOut(board.ESP_CS) 25 esp32_ready = DigitalInOut(board.ESP_BUSY) 26 esp32_reset = DigitalInOut(board.ESP_RESET) 27 spi = busio.SPI(board.SCK, board.MOSI, board.MISO) 28 esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) 29 """Use below for Most Boards""" 30 status_light = neopixel.NeoPixel( 31 board.NEOPIXEL, 1, brightness=0.2 32 ) # Uncomment for Most Boards 33 """Uncomment below for ItsyBitsy M4""" 34 # status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) 35 wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light) 36 37 the_rtc = rtc.RTC() 38 39 response = None 40 while True: 41 try: 42 print("Fetching json from", TIME_API) 43 response = wifi.get(TIME_API) 44 break 45 except (ValueError, RuntimeError) as e: 46 print("Failed to get data, retrying\n", e) 47 continue 48 49 json = response.json() 50 current_time = json["datetime"] 51 the_date, the_time = current_time.split("T") 52 year, month, mday = [int(x) for x in the_date.split("-")] 53 the_time = the_time.split(".")[0] 54 hours, minutes, seconds = [int(x) for x in the_time.split(":")] 55 56 # We can also fill in these extra nice things 57 year_day = json["day_of_year"] 58 week_day = json["day_of_week"] 59 is_dst = json["dst"] 60 61 now = time.struct_time( 62 (year, month, mday, hours, minutes, seconds, week_day, year_day, is_dst) 63 ) 64 print(now) 65 the_rtc.datetime = now 66 67 while True: 68 print(time.localtime()) 69 time.sleep(1)