import network
import time
from machine import Timer
import socket
wlan = ''
IP = ''
PORT = ''
#========================= WiFi Setup ============================
# This function is used to setup the WiFi connection
# This function returns the 'wlan' object so it can be passed
# to getConfig() and the values printed out
# This can take a while :(
#=================================================================
def setupWiFi():
print("Connecting to WiFi ", end="")
wnic = network.WLAN(network.STA_IF)
wnic.active(True)
wnic.connect("Wokwi-GUEST", "")
# This prints the dots out accross the screen while waiting for
# WiFi to connect
while not wnic.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!\n")
return wnic
#======================== Display Address Info ==================
# This displays address information set by the WiFi Access Point
# Think DHCP
#================================================================
def getConfig(wlan):
config = wlan.ifconfig()
time.sleep(1)
print(f"=======================")
time.sleep(1)
print(f"IP Address: {config[0]}")
time.sleep(1)
print(f"SubnetMask: {config[1]}")
time.sleep(1)
print(f"Gateway : {config[2]}")
time.sleep(1)
print(f"DNS Server: {config[3]}")
time.sleep(1)
print(f"=======================")
#=================================================================
# This function does a DNS lookup for the IP address of google.com
# It then takes that address and attemps to do a TCP handshake on
# port 80. For some reason this micropython version of
# 'socket.connect()' returns 'None' instead of '0' like the normal
# function does. Note: This was tested and confirmed by sending a
# succesfull web request (None) and attempting and failing to
# connect to a closed port (Throws exception:[Errno 103] ECONNABORTED )
#=================================================================
def test_connection(connction_timer):
IP,PORT = socket.getaddrinfo("google.com",80)[0][4]
print(f"Connecting To: {IP}, Port: {PORT}")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
if sock.connect((IP,PORT)) == None:
print("- Conncetion Successful")
else:
print("Connection Failed")
except OSError as e:
print(f"Error: {e}")
sock.close()
#=================================================================
# This function is just used to run all of the other functions
# that are needed to set up the system. This is triggered by the
# ONE_SHOT timer.
#=================================================================
def setup(setup_timer):
print('') # This is just to clear the console buffer [I hate messy output :)]
wlan = setupWiFi()
time.sleep(5)
getConfig(wlan)
setup_timer = Timer(mode=Timer.ONE_SHOT, period=3000, callback=setup)
connction_timer = Timer(mode=Timer.PERIODIC, period=10000, callback=test_connection)