93 lines
2.3 KiB
Python
93 lines
2.3 KiB
Python
import ubinascii
|
|
import time
|
|
import socket
|
|
import struct
|
|
import machine
|
|
|
|
def with_fallback(value, fallback):
|
|
if value is None:
|
|
return fallback
|
|
else:
|
|
return value
|
|
|
|
def with_fallback_to_str(value, fallback: str) -> str:
|
|
if value is None:
|
|
return fallback
|
|
else:
|
|
return str(value)
|
|
|
|
def set_time():
|
|
NTP_DELTA = 2208988800
|
|
HU_CORRECTION = 3600
|
|
host = "pool.ntp.org"
|
|
|
|
NTP_QUERY = bytearray(48)
|
|
NTP_QUERY[0] = 0x1B
|
|
addr = socket.getaddrinfo(host, 123)[0][-1]
|
|
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
try:
|
|
s.settimeout(10)
|
|
res = s.sendto(NTP_QUERY, addr)
|
|
msg = s.recv(48)
|
|
finally:
|
|
s.close()
|
|
val = struct.unpack("!I", msg[40:44])[0]
|
|
t = val - NTP_DELTA + HU_CORRECTION
|
|
tm = time.gmtime(t)
|
|
machine.RTC().datetime((tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0))
|
|
|
|
def connect_wifi(wlan, ssid, pw, blink_onboard_led):
|
|
print('Connecting to WiFi ' + ssid + '...')
|
|
wlan.active(True)
|
|
# If you need to disable powersaving mode
|
|
# wlan.config(pm = 0xa11140)
|
|
|
|
# See the MAC address in the wireless chip OTP
|
|
mac = ubinascii.hexlify(wlan.config('mac'),':').decode()
|
|
print('mac = ' + mac)
|
|
|
|
# Other things to query
|
|
# print(wlan.config('channel'))
|
|
# print(wlan.config('essid'))
|
|
# print(wlan.config('txpower'))
|
|
|
|
wlan.connect(ssid, pw)
|
|
|
|
# Wait for connection with 10 second timeout
|
|
timeout = 10
|
|
while timeout > 0:
|
|
if wlan.status() < 0 or wlan.status() >= 3:
|
|
break
|
|
timeout -= 1
|
|
print('Waiting for connection... Status is ' + str(wlan.status()))
|
|
blink_onboard_led(2)
|
|
time.sleep(1)
|
|
# Handle connection error
|
|
# Error meanings
|
|
# 0 Link Down
|
|
# 1 Link Join
|
|
# 2 Link NoIp
|
|
# 3 Link Up
|
|
# -1 Link Fail
|
|
# -2 Link NoNet
|
|
# -3 Link BadAuth
|
|
|
|
wlan_status = wlan.status()
|
|
blink_onboard_led(wlan_status)
|
|
|
|
if wlan_status != 3:
|
|
blink_onboard_led(5)
|
|
print('Wi-Fi connection failed')
|
|
return False
|
|
else:
|
|
blink_onboard_led(1)
|
|
print('Connected')
|
|
status = wlan.ifconfig()
|
|
print('ip = ' + status[0])
|
|
return True
|
|
|
|
def disconnect_wifi(wlan):
|
|
wlan.disconnect()
|
|
wlan.active(False)
|
|
wlan.deinit()
|
|
print('Disconnected') |