src/eric7/MicroPython/Devices/MCUScripts/esp32WiFiConnect.py

branch
eric7
changeset 11038
918bc08e1f89
parent 10153
ffe7432f716b
equal deleted inserted replaced
11037:adfda913834a 11038:918bc08e1f89
1 def has_ntp():
2 try:
3 import ntptime
4 return True
5 except ImportError:
6 return False
7
8 def set_ntp_time(server, tz_offset, timeout):
9 import ntptime
10 import machine
11
12 ntptime.host = server
13 ntptime.timeout = timeout
14 ntptime.settime()
15
16 rtc = machine.RTC()
17 t = list(rtc.datetime())
18 t[4] += tz_offset
19 rtc.datetime(t)
20
1 def connect_wifi(): 21 def connect_wifi():
2 import esp32 22 import esp32
3 import network 23 import network
4 from time import sleep 24 from time import sleep
5 25
32 wifi = network.WLAN(network.STA_IF) 52 wifi = network.WLAN(network.STA_IF)
33 wifi.active(False) 53 wifi.active(False)
34 wifi.active(True) 54 wifi.active(True)
35 wifi.connect(ssid, password) 55 wifi.connect(ssid, password)
36 max_wait = 140 56 max_wait = 140
37 while max_wait and wifi.status() == network.STAT_CONNECTING: 57 while max_wait and wifi.status() != network.STAT_GOT_IP:
38 max_wait -= 1 58 max_wait -= 1
39 sleep(0.1) 59 sleep(0.1)
40 print("Connection status:", wifi.isconnected()) 60 if wifi.isconnected():
61 print("WiFi connected:", wifi.ifconfig()[0])
62 if has_ntp():
63 set_ntp_time("pool.ntp.org", 0, 10)
64 print("Time snchronized to network time (UTC).")
65 else:
66 print("WiFi connection failed. Status:", wifi.status())
41 except: 67 except:
42 print("WiFi secrets are kept in NVM. Please store them there!") 68 print("WiFi secrets are kept in NVM. Please store them there!")
43 69
44 connect_wifi() 70 connect_wifi()

eric ide

mercurial