|
| 1 | +import time |
| 2 | +import board |
| 3 | +import busio |
| 4 | +from digitalio import DigitalInOut |
| 5 | +import microcontroller |
| 6 | +from adafruit_esp32spi import adafruit_esp32spi |
| 7 | +from adafruit_esp32spi import adafruit_esp32spi_wifimanager |
| 8 | +import rtc |
| 9 | + |
| 10 | +# Get wifi details and more from a settings.py file |
| 11 | +try: |
| 12 | + from settings import settings |
| 13 | +except ImportError: |
| 14 | + print("WiFi settings are kept in settings.py, please add them there!") |
| 15 | + raise |
| 16 | + |
| 17 | +print("ESP32 local time") |
| 18 | + |
| 19 | +TIME_API = "http://worldtimeapi.org/api/ip" |
| 20 | + |
| 21 | +esp32_cs = DigitalInOut(microcontroller.pin.PB14) # PB14 |
| 22 | +esp32_ready = DigitalInOut(microcontroller.pin.PB16) |
| 23 | +esp32_gpio0 = DigitalInOut(microcontroller.pin.PB15) |
| 24 | +esp32_reset = DigitalInOut(microcontroller.pin.PB17) |
| 25 | +spi = busio.SPI(board.SCK, board.MOSI, board.MISO) |
| 26 | +esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) |
| 27 | +wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, settings, board.NEOPIXEL) |
| 28 | + |
| 29 | +the_rtc = rtc.RTC() |
| 30 | + |
| 31 | +response = None |
| 32 | +while True: |
| 33 | + try: |
| 34 | + print("Fetching json from", TIME_API) |
| 35 | + response = wifi.get(TIME_API) |
| 36 | + break |
| 37 | + except (ValueError, RuntimeError) as e: |
| 38 | + print("Failed to get data, retrying\n", e) |
| 39 | + continue |
| 40 | + |
| 41 | +json = response.json() |
| 42 | +current_time = json['datetime'] |
| 43 | +the_date, the_time = current_time.split('T') |
| 44 | +year, month, mday = [int(x) for x in the_date.split('-')] |
| 45 | +the_time = the_time.split('.')[0] |
| 46 | +hours, minutes, seconds = [int(x) for x in the_time.split(':')] |
| 47 | + |
| 48 | +# We can also fill in these extra nice things |
| 49 | +year_day = json['day_of_year'] |
| 50 | +week_day = json['day_of_week'] |
| 51 | +is_dst = json['dst'] |
| 52 | + |
| 53 | +now = time.struct_time((year, month, mday, hours, minutes, seconds, week_day, year_day, is_dst)) |
| 54 | +print(now) |
| 55 | +the_rtc.datetime = now |
| 56 | + |
| 57 | +while True: |
| 58 | + print(time.localtime()) |
| 59 | + time.sleep(1) |
0 commit comments