/ examples / esp_atcontrol_localtime.py
esp_atcontrol_localtime.py
 1  import time
 2  import board
 3  import busio
 4  from digitalio import DigitalInOut
 5  from digitalio import Direction
 6  import rtc
 7  
 8  from adafruit_espatcontrol import (
 9      adafruit_espatcontrol,
10      adafruit_espatcontrol_wifimanager,
11  )
12  
13  
14  # Get wifi details and more from a secrets.py file
15  try:
16      from secrets import secrets
17  except ImportError:
18      print("WiFi secrets are kept in secrets.py, please add them there!")
19      raise
20  
21  
22  # With a Particle Argon
23  RX = board.ESP_TX
24  TX = board.ESP_RX
25  resetpin = DigitalInOut(board.ESP_WIFI_EN)
26  rtspin = DigitalInOut(board.ESP_CTS)
27  uart = busio.UART(TX, RX, timeout=0.1)
28  esp_boot = DigitalInOut(board.ESP_BOOT_MODE)
29  esp_boot.direction = Direction.OUTPUT
30  esp_boot.value = True
31  status_light = None
32  
33  
34  print("ESP AT commands")
35  esp = adafruit_espatcontrol.ESP_ATcontrol(
36      uart, 115200, reset_pin=resetpin, rts_pin=rtspin, debug=False
37  )
38  wifi = adafruit_espatcontrol_wifimanager.ESPAT_WiFiManager(esp, secrets, status_light)
39  
40  
41  print("ESP32 local time")
42  
43  TIME_API = "http://worldtimeapi.org/api/ip"
44  
45  
46  the_rtc = rtc.RTC()
47  
48  response = None
49  while True:
50      try:
51          print("Fetching json from", TIME_API)
52          response = wifi.get(TIME_API)
53          break
54      except (ValueError, RuntimeError, adafruit_espatcontrol.OKError) as e:
55          print("Failed to get data, retrying\n", e)
56          continue
57  
58  json = response.json()
59  current_time = json["datetime"]
60  the_date, the_time = current_time.split("T")
61  year, month, mday = [int(x) for x in the_date.split("-")]
62  the_time = the_time.split(".")[0]
63  hours, minutes, seconds = [int(x) for x in the_time.split(":")]
64  
65  # We can also fill in these extra nice things
66  year_day = json["day_of_year"]
67  week_day = json["day_of_week"]
68  is_dst = json["dst"]
69  
70  now = time.struct_time(
71      (year, month, mday, hours, minutes, seconds, week_day, year_day, is_dst)
72  )
73  print(now)
74  the_rtc.datetime = now
75  
76  while True:
77      print(time.localtime())
78      time.sleep(1)