-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Description
CircuitPython version
Adafruit CircuitPython 7.2.0 on 2022-02-24; Adafruit MagTag with ESP32S2
Code/REPL
#
# MagTag date and time circuitpython script
# modified by @Paulskpt
# Version of 2022-02-08
#
# MAGTAG flashed with CircuitPython version:
# Using library files from:
# a) https://github.com/adafruit/Adafruit_CircuitPython_Bundle/adafruit-circuitpython-bundle-7.x-mpy-20220208.zip and from
# b) https://github.com/adafruit/Adafruit_CircuitPython_Bundle/adafruit-circuitpython-bundle-py-20220208.zip
# file /lib/adafruit_portalbase/wifi_esp32s2.py modified by @Paulskpt: added 1 import and 5 functions.
# - Added 'import ipaddress'
# - The following functions I created in: /lib/adafruit_portalbase/wifi_esp32s2.py.
# Their contents were originally inside this script (not as functions).
# - WiFi.get()
# - WiFi.ping()
# - WiFi.do_scan()
# - WiFi.get_mac_address()
# - WiFi.get_mac_address_ap()
import time
import secrets
from adafruit_magtag.magtag import MagTag
import ipaddress
import gc, os
from adafruit_portalbase.wifi_esp32s2 import WiFi
import wifi
import ssl
import socketpool
import adafruit_requests
my_debug = False
magtag = MagTag()
response = None # idem
TIME_URL = None
my_wifi = WiFi() # create an instance of WiFi class
# Get wifi details and more from a secrets.py file
start_clk = time.monotonic()
# Copied from UM's ProS3 code.py
#--------------------------------------------
# Show available memory
print("Memory Info - gc.mem_free()")
print("---------------------------")
print("{} Bytes\n".format(gc.mem_free()))
flash = os.statvfs('/')
flash_size = flash[0] * flash[2]
flash_free = flash[0] * flash[3]
# Show flash size
print("Flash - os.statvfs('/')")
print("---------------------------")
print("Size: {} Bytes\nFree: {} Bytes\n".format(flash_size, flash_free))
#--------------------------------------------
def setup():
global requests, TIME_URL, my_wifi
TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html"
JSON_QUOTES_URL = "https://www.adafruit.com/api/quotes.php"
JSON_STARS_URL = "https://api.github.com/repos/adafruit/circuitpython"
# Get wifi details and more from a secrets.py file
try:
from secrets import secrets
except ImportError:
print("WiFi secrets are kept in secrets.py, please add them there!")
raise
# Get our username, key and desired timezone
aio_username = secrets["aio_username"]
aio_key = secrets["aio_key"]
location = secrets.get("timezone", None)
TIME_URL = "https://io.adafruit.com/api/v2/%s/integrations/time/strftime?x-aio-key=%s" % (aio_username, aio_key)
TIME_URL += "&fmt=%25Y-%25m-%25d+%25H%3A%25M%3A%25S.%25L+%25j+%25u+%25z+%25Z"
print("ESP32-S2 Adafruit IO Time test")
#my_mac = my_wifi.get_mac_address()
my_mac = wifi.radio.mac_address
#ap_mac = my_wifi.get_mac_address_ap()
ap_mac = wifi.radio.mac_address_ap
if not my_debug:
print("My MAC address: \'{:x}:{:x}:{:x}:{:x}:{:x}:{:x}\'".format(my_mac[0],my_mac[1],my_mac[2],my_mac[3],my_mac[4],my_mac[5]), end='\n')
print("AP MAC address: \'{:x}:{:x}:{:x}:{:x}:{:x}:{:x}\'".format(ap_mac[0],ap_mac[1],ap_mac[2],ap_mac[3],ap_mac[4],ap_mac[5]), end='\n')
if my_debug:
print("Available WiFi networks:")
my_wifi.do_scan()
print("Connecting to %s"%secrets["ssid"])
my_wifi.connect(secrets["ssid"], secrets["password"])
if my_wifi.is_connected:
print("Connected to %s"%secrets["ssid"])
print("My IP address is \'{}\'".format(my_wifi.ip_address), end='\n')
# my_wifi.ping("8.8.8.8")
if my_debug:
print("Fetching text from", TIME_URL)
pool = socketpool.SocketPool(wifi.radio)
requests = adafruit_requests.Session(pool, ssl.create_default_context())
#response = my_wifi.get(TIME_URL)
response = requests.get(TIME_URL)
if not isinstance(response, type(None)):
print("-" * 40)
print(response.text)
print("-" * 40)# Escreve o teu código aqui :-)
height = magtag.graphics.display.height -1
width = magtag.graphics.display.width -1
h0 = height // 6
hlist = [h0, h0*3, h0*5]
for _ in range (3):
magtag.add_text(
text_position=(
10,
hlist[_],
),
text_scale=3,
)
else:
print("WiFi not connected!")
def get_pr_dt():
global my_wifi, response, TIME_URL, magtag
try:
response = my_wifi.get(TIME_URL)
except Exception as e:
print("get_dt(): error {} occurred.".format(e), end='\n')
return
dt = response.text[0:10]
tm = response.text[11:16] # 23]
tz = response.text[30:40]
#s = "time: {}, timzezone: {}".format(tm, tz)
for _ in range(3):
if _ == 0:
magtag.set_text(dt, _, auto_refresh = False) # Display the date
elif _ == 1:
magtag.set_text(tm, _, auto_refresh = False)
elif _ == 2:
magtag.set_text(tz, _, auto_refresh = False)
magtag.display.refresh() # refresh the display
def elapsed(ltrm):
global start_clk
diff_clk = time.monotonic() - start_clk
d = int(float(diff_clk))
e = "Elapsed: "
if ltrm == 0:
return e+"{:d}".format(d)
if ltrm == 1:
return e+"{:" ">5d}".format(d)
elif ltrm == 2:
return diff_clk
def main():
global start_clk, requests, response, TIME_URL
lStart = True
setup()
while True:
#print("{} Seconds".format(elapsed(1))
if lStart or elapsed(2) > 60:
lStart = False
get_pr_dt() # updatate dt and print
print(response.text)
start_clk = time.monotonic()
if __name__ == '__main__':
main()
Behavior
Auto-reload is on. Simply save files over USB to run them or enter REPL to disable.
code.py output:
Memory Info - gc.mem_free()
---------------------------
1996528 Bytes
Flash - os.statvfs('/')
---------------------------
Size: 963072 Bytes
Free: 819712 Bytes
ESP32-S2 Adafruit IO Time test
My MAC address: '7c:df:a1:15:1f:42'
AP MAC address: '7c:df:a1:15:1f:43'
Connected to [<my_router_ssid>]
My IP address is '[<ip-addres-assigned>]'
Traceback (most recent call last):
File "code.py", line 177, in
File "code.py", line 164, in main
File "code.py", line 104, in setup
File "adafruit_requests.py", line 769, in get
File "adafruit_requests.py", line 710, in request
File "adafruit_requests.py", line 554, in _get_socket
OSError: -2
Description
This error started to happen on September 25, 2021. On February 8, 2022, I added this fact in a comment to issue #4394 from @johncblacker. @tannewt advised me to open a new issue. But then, when I commented-out in code.py, calls to my_wifi.ping(<string>)
, the error vanished. Now, a month later, the script crashed again, this time reporting:
AttributeError: 'WiFi' object has no attribute 'get_mac_address'
get_mac_address
is a function I added to adafruit_portalbase.wifi_esp32s2.py
, containing code that before was in code.py. To get rid of this error I moved the function back to code.py.
Then I was (again) confronted with the OSError -2.
Additional information
No response