# ping_test.py
# to try this, copy it to the CIRCUITPY drive as code.py

import time
import wifi
import ipaddress
import socketpool

# name of the host to ping
ping_host = "www.cmu.edu"

# fetch the device address from the WiFi module
mac = ':'.join([("%02x" % b) for b in wifi.radio.mac_address])
print("device WiFi MAC:", mac)

print("Attempting to connect to the campus CMU-DEVICE WiFi.")
wifi.radio.connect(ssid="CMU-DEVICE")

print("device IP addr:", wifi.radio.ipv4_address)

# use DNS to find the host address
pool = socketpool.SocketPool(wifi.radio)
addr = pool.getaddrinfo(ping_host, port=80)

# extract the host address field from the resulting list of tuples
host_ip = addr[0][4][0]

print("pinging", ping_host, "at", host_ip)
ip = ipaddress.ip_address(host_ip)

while True:
    print("ping time:", wifi.radio.ping(ip))
    time.sleep(5)
