October is open-source month. What better way to celebrate it than by using open-source hardware and software to celebrate all of the amazing open-source hardware that's been certified by OSHWA over the last few years!

In this project, you'll program an Adafruit MagTag to display one project from OSHWA every hour. You'll display the title of the project, the description, and a QR code you can easily scan to look at the full project.

Parts

This kit contains all the necessary parts except for a USB cable

The Adafruit MagTag combines the new ESP32-S2 wireless module and a 2.9" grayscale E-Ink display to make a low-power IoT display that can show data on its screen...
$44.95
In Stock

Or get the pieces separately:

The Adafruit MagTag combines the new ESP32-S2 wireless module and a 2.9" grayscale E-Ink display to make a low-power IoT display that can show data on its screen even when power...
$34.95
In Stock
Got a glorious RGB Matrix project you want to mount and display in your workspace or home? If you have one of the matrix panels listed below, you'll need a pack of these...
$2.50
In Stock
Lithium-ion polymer (also known as 'lipo' or 'lipoly') batteries are thin, light, and powerful. The output ranges from 4.2V when completely charged to 3.7V. This...
$6.95
In Stock

This is optional, but useful if you want to secure the battery to the MagTag.

UGlu Dashes are perfect for a variety of small projects. These adhesive squares provide a stronger bond to most surfaces and are cleaner and easier to...
$0.50
In Stock

Last but not least, make sure to pick up a USB-C cable, if you don't already have one.

As technology changes and adapts, so does Adafruit. This  USB Type A to Type C cable will help you with the transition to USB C, even if you're still...
$3.95
In Stock

CircuitPython is a derivative of MicroPython designed to simplify experimentation and education on low-cost microcontrollers. It makes it easier than ever to get prototyping by requiring no upfront desktop software downloads. Simply copy and edit files on the CIRCUITPY drive to iterate.

Set Up CircuitPython

Follow the steps to get CircuitPython installed on your MagTag.

Click the link above and download the latest .BIN and .UF2 file

(depending on how you program the ESP32S2 board you may need one or the other, might as well get both)

Download and save it to your desktop (or wherever is handy).

Plug your MagTag into your computer using a known-good USB cable.

A lot of people end up using charge-only USB cables and it is very frustrating! So make sure you have a USB cable you know is good for data sync.

Option 1 - Load with UF2 Bootloader

This is by far the easiest way to load CircuitPython. However it requires your board has the UF2 bootloader installed. Some early boards do not (we hadn't written UF2 yet!) - in which case you can load using the built in ROM bootloader.

Still, try this first!

Try Launching UF2 Bootloader

Loading CircuitPython by drag-n-drop UF2 bootloader is the easier way and we recommend it. If you have a MagTag where the front of the board is black, your MagTag came with UF2 already on it.

Launch UF2 by double-clicking the Reset button (the one next to the USB C port). You may have to try a few times to get the timing right.

If the UF2 bootloader is installed, you will see a new disk drive appear called MAGTAGBOOT

Copy the UF2 file you downloaded at the first step of this tutorial onto the MAGTAGBOOT drive

If you're using Windows and you get an error at the end of the file copy that says Error from the file copy, Error 0x800701B1: A device which does not exist was specified. You can ignore this error, the bootloader sometimes disconnects without telling Windows, the install completed just fine and you can continue. If its really annoying, you can also upgrade the bootloader (the latest version of the UF2 bootloader fixes this warning)

Your board should auto-reset into CircuitPython, or you may need to press reset. A CIRCUITPY drive will appear. You're done! Go to the next pages.

Option 2 - Use esptool to load BIN file

If you have an original MagTag with while soldermask on the front, we didn't have UF2 written for the ESP32S2 yet so it will not come with the UF2 bootloader.

You can upload with esptool to the ROM (hardware) bootloader instead!

Follow the initial steps found in the Run esptool and check connection section of the ROM Bootloader page to verify your environment is set up, your board is successfully connected, and which port it's using.

In the final command to write a binary file to the board, replace the port with your port, and replace "firmware.bin" with the the file you downloaded above.

The output should look something like the output in the image.

Press reset to exit the bootloader.

Your CIRCUITPY drive should appear!

You're all set! Go to the next pages.

Option 3 - Use Chrome Browser To Upload BIN file

If for some reason you cannot get esptool to run, you can always try using the Chrome-browser version of esptool we have written. This is handy if you don't have Python on your computer, or something is really weird with your setup that makes esptool not run (which happens sometimes and isn't worth debugging!) You can follow along on the Web Serial ESPTool page and either load the UF2 bootloader and then come back to Option 1 on this page, or you can download the CircuitPython BIN file directly using the tool in the same manner as the bootloader.

To use the internet-connectivity built into your ESP32-S2 with CircuitPython, you must first install a number of libraries. This page covers that process.

Adafruit CircuitPython Library Bundle

Download the Adafruit CircuitPython Bundle. You can find the latest release here:

Download the adafruit-circuitpython-bundle-version-mpy-*.zip bundle zip file, and unzip a folder of the same name. Inside you'll find a lib folder. The entire collection of libraries is too large to fit on the CIRCUITPY drive. Instead, add each library as you need it, this will reduce the space usage but you'll need to put in a little more effort.

At a minimum we recommend the following libraries, in fact we more than recommend. They're basically required. So grab them and install them into CIRCUITPY/lib now!

  • adafruit_requests.mpy - A requests-like library for HTTP commands.
  • neopixel.mpy - Helper library to use NeoPixel LEDs, often built into the boards so they're great for quick feedback

Once you have added those files, please continue to the next page to set up and test Internet connectivity

Once you have CircuitPython installed and the minimum libraries installed we can get your board connected to the Internet. 

To get connected, you will need to start by creating a secrets.py file.

Secrets File

We expect people to share tons of projects as they build CircuitPython WiFi widgets. What we want to avoid is people accidentally sharing their passwords or secret tokens and API keys. So, we designed all our examples to use a secrets.py file, that is in your CIRCUITPY drive, to hold secret/private/custom data. That way you can share your main project without worrying about accidentally sharing private stuff.

Your secrets.py file should look like this:

# This file is where you keep secret settings, passwords, and tokens!
# If you put them in the code you risk committing that info or sharing it

secrets = {
    'ssid' : 'home_wifi_network',
    'password' : 'wifi_password',
    'aio_username' : 'my_adafruit_io_username',
    'aio_key' : 'my_adafruit_io_key',
    'timezone' : "America/New_York", # http://worldtimeapi.org/timezones
    }

Copy and paste that text/code into a file called secrets.py and save it to your CIRCUITPY folder like so:

Inside is a python dictionary named secrets with a line for each entry. Each entry has an entry name (say 'ssid') and then a colon to separate it from the entry key 'home ssid' and finally a comma ,

At a minimum you'll need to adjust the ssid and password for your local WiFi setup so do that now!

As you make projects you may need more tokens and keys, just add them one line at a time. See for example other tokens such as one for accessing github or the hackaday API. Other non-secret data like your timezone can also go here, just cause its called secrets doesn't mean you can't have general customization data in there!

For the correct time zone string, look at http://worldtimeapi.org/timezones and remember that if your city is not listed, look for a city in the same time zone, for example Boston, New York, Philadelphia, Washington DC, and Miami are all on the same time as New York.

Of course, don't share your secrets.py - keep that out of GitHub, Discord or other project-sharing sites.

Don't share your secrets.py file, it has your passwords and API keys in it!

Connect to WiFi

OK now you have your secrets setup - you can connect to the Internet using the Requests module.

First make sure you are running the latest version of Adafruit CircuitPython for your board.

Next you'll need to install the necessary libraries to use the hardware--carefully follow the steps to find and install these libraries from Adafruit's CircuitPython library bundle. Our introduction guide has a great page on how to install the library bundle.

  • adafruit_requests
  • neopixel

Before continuing make sure your board's CIRCUITPY/lib folder or root filesystem has the above files copied over.

Once that's done, load up the following example using Mu or your favorite editor:

import ipaddress
import ssl
import wifi
import socketpool
import adafruit_requests

# URLs to fetch from
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

print("ESP32-S2 WebClient Test")

print("My MAC addr:", [hex(i) for i in wifi.radio.mac_address])

print("Available WiFi networks:")
for network in wifi.radio.start_scanning_networks():
    print("\t%s\t\tRSSI: %d\tChannel: %d" % (str(network.ssid, "utf-8"),
            network.rssi, network.channel))
wifi.radio.stop_scanning_networks()

print("Connecting to %s"%secrets["ssid"])
wifi.radio.connect(secrets["ssid"], secrets["password"])
print("Connected to %s!"%secrets["ssid"])
print("My IP address is", wifi.radio.ipv4_address)

ipv4 = ipaddress.ip_address("8.8.4.4")
print("Ping google.com: %f ms" % (wifi.radio.ping(ipv4)*1000))

pool = socketpool.SocketPool(wifi.radio)
requests = adafruit_requests.Session(pool, ssl.create_default_context())

print("Fetching text from", TEXT_URL)
response = requests.get(TEXT_URL)
print("-" * 40)
print(response.text)
print("-" * 40)

print("Fetching json from", JSON_QUOTES_URL)
response = requests.get(JSON_QUOTES_URL)
print("-" * 40)
print(response.json())
print("-" * 40)

print()

print("Fetching and parsing json from", JSON_STARS_URL)
response = requests.get(JSON_STARS_URL)
print("-" * 40)
print("CircuitPython GitHub Stars", response.json()["stargazers_count"])
print("-" * 40)

print("done")

And save it to your board. Make sure the file is named code.py.

Open up your REPL, you should see something like the following:

In order, the example code...

Checks the ESP32-S2's MAC address.

print("My MAC addr:", [hex(i) for i in wifi.radio.mac_address])

Performs a scan of all access points and prints out the access point's name (SSID), signal strength (RSSI), and channel.

print("Avaliable WiFi networks:")
for network in wifi.radio.start_scanning_networks():
    print("\t%s\t\tRSSI: %d\tChannel: %d" % (str(network.ssid, "utf-8"),
            network.rssi, network.channel))
wifi.radio.stop_scanning_networks()

Connects to the access point you defined in the secrets.py file, prints out its local IP address, and attempts to ping google.com to check its network connectivity. 

print("Connecting to %s"%secrets["ssid"])
wifi.radio.connect(secrets["ssid"], secrets["password"])
print(print("Connected to %s!"%secrets["ssid"]))
print("My IP address is", wifi.radio.ipv4_address)

ipv4 = ipaddress.ip_address("8.8.4.4")
print("Ping google.com: %f ms" % wifi.radio.ping(ipv4))

The code creates a socketpool using the wifi radio's available sockets. This is performed so we don't need to re-use sockets. Then, it initializes a a new instance of the requests interface - which makes getting data from the internet really really easy.

pool = socketpool.SocketPool(wifi.radio)
requests = adafruit_requests.Session(pool, ssl.create_default_context())

To read in plain-text from a web URL, call requests.get - you may pass in either a http, or a https url for SSL connectivity. 

print("Fetching text from", TEXT_URL)
response = requests.get(TEXT_URL)
print("-" * 40)
print(response.text)
print("-" * 40)

Requests can also display a JSON-formatted response from a web URL using a call to requests.get

print("Fetching json from", JSON_QUOTES_URL)
response = requests.get(JSON_QUOTES_URL)
print("-" * 40)
print(response.json())
print("-" * 40)

Finally, you can fetch and parse a JSON URL using requests.get. This code snippet obtains the stargazers_count field from a call to the GitHub API.

print("Fetching and parsing json from", JSON_STARS_URL)
response = requests.get(JSON_STARS_URL)
print("-" * 40)
print("CircuitPython GitHub Stars", response.json()["stargazers_count"])
print("-" * 40)

OK you now have your ESP32-S2 board set up with a proper secrets.py file and can connect over the Internet. If not, check that your secrets.py file has the right ssid and password and retrace your steps until you get the Internet connectivity working!

A very common need for projects is to know the current date and time. Especially when you want to deep sleep until an event, or you want to change your display based on what day, time, date, etc. it is

Determining the correct local time is really really hard. There are various time zones, Daylight Savings dates, leap seconds, etc. Trying to get NTP time and then back-calculating what the local time is, is extraordinarily hard on a microcontroller just isn't worth the effort and it will get out of sync as laws change anyways.

For that reason, we have the free adafruit.io time service. Free for anyone, with a free adafruit.io account. You do need an account because we have to keep accidentally mis-programmed-board from overwhelming adafruit.io and lock them out temporarily. Again, it's free!

There are other services like WorldTimeAPI, but we don't use those for our guides because they are nice people and we don't want to accidentally overload their site. Also, there's a chance it may eventually go down or also require an account.

Step 1) Make an Adafruit account

It's free! Visit https://accounts.adafruit.com/ to register and make an account if you do not already have one

Step 2) Sign into Adafruit IO

Head over to io.adafruit.com and click Sign In to log into IO using your Adafruit account. It's free and fast to join.

Step 3) Get your Adafruit IO Key

Click on My Key in the top bar

You will get a popup with your Username and Key (In this screenshot, we've covered it with red blocks)

Go to your secrets.py file on your CIRCUITPY drive and add three lines for aio_username, aio_key and timezone so you get something like the following:

# This file is where you keep secret settings, passwords, and tokens!
# If you put them in the code you risk committing that info or sharing it

secrets = {
    'ssid' : 'home_wifi_network',
    'password' : 'wifi_password',
    'aio_username' : 'my_adafruit_io_username',
    'aio_key' : 'my_adafruit_io_key',
    'timezone' : "America/New_York", # http://worldtimeapi.org/timezones
    }

The timezone is optional, if you don't have that entry, adafruit.io will guess your timezone based on geographic IP address lookup. You can visit http://worldtimeapi.org/timezones to see all the time zones available (even though we do not use worldtimeapi for time-keeping we do use the same time zone table)

Step 4) Upload Test Python Code

This code is like the Internet Test code from before, but this time it will connect to adafruit.io and get the local time

import ipaddress
import ssl
import wifi
import socketpool
import adafruit_requests
import secrets


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")

print("My MAC addr:", [hex(i) for i in wifi.radio.mac_address])

print("Available WiFi networks:")
for network in wifi.radio.start_scanning_networks():
    print("\t%s\t\tRSSI: %d\tChannel: %d" % (str(network.ssid, "utf-8"),
            network.rssi, network.channel))
wifi.radio.stop_scanning_networks()

print("Connecting to %s"%secrets["ssid"])
wifi.radio.connect(secrets["ssid"], secrets["password"])
print("Connected to %s!"%secrets["ssid"])
print("My IP address is", wifi.radio.ipv4_address)

ipv4 = ipaddress.ip_address("8.8.4.4")
print("Ping google.com: %f ms" % wifi.radio.ping(ipv4))

pool = socketpool.SocketPool(wifi.radio)
requests = adafruit_requests.Session(pool, ssl.create_default_context())

print("Fetching text from", TIME_URL)
response = requests.get(TIME_URL)
print("-" * 40)
print(response.text)
print("-" * 40)

After running this, you will see something like the below text. We have blocked out the part with the secret username and key data!

Note at the end you will get the date, time, and your timezone! If so, you have correctly configured your secrets.py and can continue to the next steps!

To use all the amazing features of your MagTag with CircuitPython, you must first install a number of libraries. This page covers that process.

Get Latest Adafruit CircuitPython Bundle

Download the Adafruit CircuitPython Library Bundle. You can find the latest release here:

Download the adafruit-circuitpython-bundle-version-mpy-*.zip bundle zip file, and unzip a folder of the same name. Inside you'll find a lib folder. The entire collection of libraries is too large to fit on the CIRCUITPY drive. Therefore, you'll need to copy the necessary libraries to your board individually.

At a minimum, the following libraries are required. Copy the following folders or .mpy files to the lib folder on your CIRCUITPY drive. If the library is a folder, copy the entire folder to the lib folder on your board.

Library folders (copy the whole folder over to lib):

  • adafruit_magtag - This is a helper library designed for using all of the features of the MagTag, including networking, buttons, NeoPixels, etc.
  • adafruit_portalbase - This library is the base library that adafruit_magtag is built on top of.
  • adafruit_bitmap_font - There is fancy font support, and it's easy to make new fonts. This library reads and parses font files.
  • adafruit_display_text - This library displays text on the screen.
  • adafruit_io - This library helps connect the MagTag to our free data logging and viewing service

Library files:

  • adafruit_requests.mpy - This library allows us to perform HTTP requests and get responses back from servers. GET/POST/PUT/PATCH - they're all in here!
  • adafruit_fakerequests.mpy  - This library allows you to create fake HTTP requests by using local files.
  • adafruit_miniqr.mpy  - QR creation library lets us add easy-to-scan 2D barcodes to the E-Ink display
  • neopixel.mpy - This library is used to control the onboard NeoPixels.
  • simpleio.mpy - This library is used for tone generation.

Secrets

Even if you aren't planning to go online with your MagTag, you'll need to have a secrets.py file in the root directory (top level) of your CIRCUITPY drive. If you do not intend to connect to wireless, it does not need to have valid data in it. Here's more info on the secrets.py file.

Before anything else, plug the battery into the MagTag. The jack is right next to the Adafruit logo on the back of the board. If you would like to use a double-sided adhesive, put it where you want the battery to go, press down firmly, then remove the piece of paper covering the exposed side and stick the battery to it.

Installing the Project Code

Download a zip of the project code by clicking 'Download: Project Zip' in the preview of code.py below.

After unzipping the file, copy its contents to the CIRCUITPY drive which appears when the MagTag is connected to your computer via a USB cable and turned on via a small on/off switch onboard.

You don't need to install any other libraries than the ones you installed in the MagTag-Specific CircuitPython Libraries page.

After you've copied everything over, your CIRCUITPY drive, it should look something like this:

CIRCUITPY

You'll need to get an OSHWA API key and paste it in on line 34 of code.py.

# SPDX-FileCopyrightText: 2021 Dylan Herrada for Adafruit Industries
#
# SPDX-License-Identifier: MIT

import random
import ssl
import gc
import wifi
import socketpool
import adafruit_requests as requests
from adafruit_magtag.magtag import MagTag

# 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

# Initialize magtag object
magtag = MagTag()

magtag.set_background("bmps/oshwa_full.bmp")

# Set up WiFi
wifi.radio.connect(secrets["ssid"], secrets["password"])
print(f"Connected to {secrets['ssid']}!")
print("My IP address is", wifi.radio.ipv4_address)

socket = socketpool.SocketPool(wifi.radio)
https = requests.Session(socket, ssl.create_default_context())

# Paste your API token below
TOKEN = "YOUR_API_TOKEN"


def font_width_to_dict(font):
    # Reads the font file to determine how wide each character is
    # Used to avoid bad wrapping breaking the QR code
    chars = {}
    with open(font, "r") as file:
        for line in file:
            if "FONTBOUNDINGBOX" in line:
                size = int(line.split(" ")[1])
            if "ENCODING" in line and "_ENCODING" not in line:
                character = chr(int(line.split(" ")[1][:-1]))
                chars[character] = None
            if "SWIDTH" in line:
                swidth = (int(line.split(" ")[1]) / 1000) * size
            if "DWIDTH" in line:
                chars[character] = int(int(line.split(" ")[1]) + swidth)
    return chars


def wrap(text, max_width, max_lines, font):
    # Used to wrap the title and description to avoid breaking the QR code
    lines = []
    ellipsis = 3 * font["."]
    line = ""
    line_width = 0
    for word in text.split(" "):
        for character in word:
            line_width += font[character]
            if (
                len(lines) + 1 != max_lines
                or sum(font[i] for i in word) + line_width <= max_width
            ):
                if line_width > max_width:
                    print(str(line_width) + line)
                    line_width = sum(font[i] for i in word)
                    lines.append(line.strip())
                    line = word + " "
                    break
            else:
                for char_1 in word:
                    if line_width + ellipsis + font[char_1] > max_width:
                        line = line + "..."
                        print(str(line_width) + line)
                        lines.append(line)
                        return "\n".join(lines[:max_lines])
                    line = line + char_1
                    line_width += font[char_1]

        else:
            line = line + word + " "

    lines.append(line.strip())
    return "\n".join(lines[:max_lines])


# Get first 300 items, saving only the OSHWA UIDs. The first 300 are also used to find the
# number of requests that will need to be made.
# This was done this way since if the items themselves were all asked for and stored, the MagTag
# would run out of memory. If we just got the number of total projects and chose a random number,
# that also wouldn't work as you can only get individual projects with an OSHWA UID and these UIDs
# are prefixed by the country they were registered in, thus making getting it with a simple number
# in-between 1 and the total number of registered projects impossible.
URL = "https://certificationapi.oshwa.org/api/projects?limit=300"

print(URL)

payload = {}
headers = {"Content-Type": "application/json", "Authorization": f"Bearer {TOKEN}"}

oshwaID = []

print("Getting number of projects and first set of 300 projects")
with https.get(URL, headers=headers, data=payload) as response:
    R_JSON = response.json()
    total = int(R_JSON["total"])
    print(f"{total} Projects")
    for i in R_JSON["items"]:
        oshwaID.append(i["oshwaUid"])
    R_JSON.clear()
    R_JSON = None
    gc.collect()

# Gets the rest of the OSHWA UIDs
print(len(oshwaID))
for i in range(int(total / 300)):
    print(f"Getting request {i+2}")
    url = (
        f"https://certificationapi.oshwa.org/api/projects?limit=300&offset={3*(i+1)}00"
    )
    with https.get(url, headers=headers, data=payload) as response:
        R_JSON = response.json()
        for item in R_JSON["items"]:
            oshwaID.append(item["oshwaUid"])
        R_JSON.clear()
        R_JSON = None
        gc.collect()
    print(f"{len(oshwaID)} IDs gathered")

# Select the UID that will be displayed
selected = random.choice(oshwaID)

# Get the project that will be displayed
url = f"https://certificationapi.oshwa.org/api/projects/{selected}"
response = https.get(url, headers=headers, data=payload)

selected = response.json()[0]

# Filters out characters that the API or the MagTag itself isn't handling correctly
for char in range(1, 32):
    selected["projectDescription"].replace(chr(char), "")

selected["projectDescription"] = (
    selected["projectDescription"]
    .replace("&#x27;", "'")
    .replace("&amp;#x27;", "'")
    .replace("&#x2F;", "/")
    .replace("&quot;", '"')
    .replace("’", "'")
)

# Add the two text fields
magtag.add_text(
    text_font="fonts/Arial-Bold-12.bdf",
    text_position=(5, 0),
    text_scale=1,
    line_spacing=0.7,
    text_anchor_point=(0, 0),
)

magtag.add_text(
    text_font="fonts/ArialMT-9.bdf",
    text_position=(5, 38),
    text_scale=1,
    line_spacing=0.6,
    text_anchor_point=(0, 0),
)

# Create the QR code
url = f"https://certification.oshwa.org/{selected['oshwaUid'].lower()}.html"
magtag.graphics.qrcode(url, qr_size=4, x=173, y=3)

# Prepare to wrap the text correctly by getting the width of each character for every font
arial_12 = font_width_to_dict("fonts/Arial-Bold-12.bdf")
arial_9 = font_width_to_dict("fonts/ArialMT-9.bdf")

# Set the text. On some characters, this fails. If so, run the whole file again in 5 seconds
try:
    magtag.set_text(wrap(selected["projectName"], 545, 2, arial_12), 0, False)
    magtag.set_text(wrap(selected["projectDescription"], 530, 19, arial_9), 1)
    magtag.exit_and_deep_sleep(3600)
except Exception:  # pylint: disable=broad-except
    print("Could not set title or description: unsupported glyphs.")
    print("Trying again in 10 seconds.")
    magtag.exit_and_deep_sleep(10)

Code Run Through

First, the code imports all the required libraries.

import random
import ssl
import gc
import wifi
import socketpool
import adafruit_requests as requests
from adafruit_magtag.magtag import MagTag

Next, the code gets the WiFi details and Adafruit IO API token from the secrets.py file.

try:
    from secrets import secrets
except ImportError:
    print("WiFi secrets are kept in secrets.py, please add them there!")
    raise

Now, the MagTag object is initialized.

magtag = MagTag()

magtag.set_background("bmps/oshwa_full.bmp")

After that, the WiFi is set up and connected to.

# Set up WiFi
wifi.radio.connect(secrets["ssid"], secrets["password"])
print(f"Connected to {secrets['ssid']}!")
print("My IP address is", wifi.radio.ipv4_address)

socket = socketpool.SocketPool(wifi.radio)
https = requests.Session(socket, ssl.create_default_context())

This is the part where you'll paste your API token. If you haven't already done so, you can get it here.

# Paste your API token below
TOKEN = "YOUR_API_TOKEN"

The next two functions are used to wrap the description text by pixels instead of characters. This is because when it was being done by characters, the number of lines would vary greatly and the lines would sometimes go into the QR code, making it unreadable. This first function opens the font file and gets the width of every character.

def font_width_to_dict(font):
    # Reads the font file to determine how wide each character is
    # Used to avoid bad wrapping breaking the QR code
    chars = {}
    with open(font, "r") as file:
        for line in file:
            if "FONTBOUNDINGBOX" in line:
                size = int(line.split(" ")[1])
            if "ENCODING" in line and "_ENCODING" not in line:
                character = chr(int(line.split(" ")[1][:-1]))
                chars[character] = None
            if "SWIDTH" in line:
                swidth = (int(line.split(" ")[1]) / 1000) * size
            if "DWIDTH" in line:
                chars[character] = int(int(line.split(" ")[1]) + swidth)
    return chars

The second function does the actual wrapping of the text. It takes the text to format, the max width of the line, the max number of lines, as well as the dictionary that the previous function returns.

def wrap(text, max_width, max_lines, font):
    # Used to wrap the title and description to avoid breaking the QR code
    lines = []
    ellipsis = 3 * font["."]
    line = ""
    line_width = 0
    for word in text.split(" "):
        for character in word:
            line_width += font[character]
            if (
                len(lines) + 1 != max_lines
                or sum(font[i] for i in word) + line_width <= max_width
            ):
                if line_width > max_width:
                    print(str(line_width) + line)
                    line_width = sum(font[i] for i in word)
                    lines.append(line.strip())
                    line = word + " "
                    break
            else:
                for char_1 in word:
                    if line_width + ellipsis + font[char_1] > max_width:
                        line = line + "..."
                        print(str(line_width) + line)
                        lines.append(line)
                        return "\n".join(lines[:max_lines])
                    line = line + char_1
                    line_width += font[char_1]

        else:
            line = line + word + " "

    lines.append(line.strip())
    return "\n".join(lines[:max_lines])

This next bit of code gets first 300 items, saving only the OSHWA UIDs. The first 300 are also used to find the number of requests that will need to be made. This was done since if the items themselves were all stored at once, the MagTag would run out of memory. If we just got the number of total projects and chose a random number, that also wouldn't work as you can only get individual projects with an OSHWA UID and these UIDs are prefixed by the country they were registered in, thus making getting it with a simple number in-between 1 and the total number of registered projects impossible unless you only wanted to get projects registered in one country.

URL = "https://certificationapi.oshwa.org/api/projects?limit=300"

print(URL)

payload = {}
headers = {"Content-Type": "application/json", "Authorization": f"Bearer {TOKEN}"}

oshwaID = []

print("Getting number of projects and first set of 300 projects")
with https.get(URL, headers=headers, data=payload) as response:
    R_JSON = response.json()
    total = int(R_JSON["total"])
    print(f"{total} Projects")
    for i in R_JSON["items"]:
        oshwaID.append(i["oshwaUid"])
    R_JSON.clear()
    R_JSON = None
    gc.collect()

This loop gets the rest of the OSHWA UIDs in a way that won't fill up all the memory of the MagTag.

print(len(oshwaID))
for i in range(int(total / 300)):
    print(f"Getting request {i+2}")
    url = (
        f"https://certificationapi.oshwa.org/api/projects?limit=300&offset={3*(i+1)}00"
    )
    with https.get(url, headers=headers, data=payload) as response:
        R_JSON = response.json()
        for item in R_JSON["items"]:
            oshwaID.append(item["oshwaUid"])
        R_JSON.clear()
        R_JSON = None
        gc.collect()
    print(f"{len(oshwaID)} IDs gathered")

Next, a random UID from the list of OSHWA UIDs is chosen, and a request is sent over the API for that specific project.

selected = random.choice(oshwaID)

url = f"https://certificationapi.oshwa.org/api/projects/{selected}"
response = https.get(url, headers=headers, data=payload)

selected = response.json()[0]

The combination of the OSHWA API not handling all non-alphanumeric characters correctly and the fonts used on the MagTag only having a subset of all characters that could have been used results in the need to remove all the special characters and replace all the punctuation marks that aren't being handled correctly.

# Filters out characters that the API or the MagTag itself isn't handling correctly
for char in range(1, 32):
    selected["projectDescription"].replace(chr(char), "")

selected["projectDescription"] = (
    selected["projectDescription"]
    .replace("&#x27;", "'")
    .replace("&amp;#x27;", "'")
    .replace("&#x2F;", "/")
    .replace("&quot;", '"')
    .replace("’", "'")
)

Now, the code creates the two text fields. The first one is for the title, and the second one is for the description.

# Add the two text fields
magtag.add_text(
    text_font="fonts/Arial-12.bdf",
    text_position=(5, -2),
    text_scale=1,
    line_spacing=0.6,
    text_anchor_point=(0, 0),
)

magtag.add_text(
    text_font="fonts/ArialMT-9.bdf",
    text_position=(5, 30),
    text_scale=1,
    line_spacing=0.6,
    text_anchor_point=(0, 0),
)

After that, the QR code is created and added to the display.

# Create the QR code
url = f"https://certification.oshwa.org/{selected['oshwaUid'].lower()}.html"
magtag.graphics.qrcode(url, qr_size=4, x=173, y=3)

Before adding the text, the code prepares to wrap it correctly by getting the width of each character for the two fonts that will be used.

arial_12 = font_width_to_dict("fonts/Arial-12.bdf")
arial_9 = font_width_to_dict("fonts/ArialMT-9.bdf")

Finally, the code sets the text. On some characters which aren't included in the fonts for memory reasons, this fails. If this occurs, the code runs again in 5 seconds.

try:
    magtag.set_text(wrap(selected["projectName"], 530, 2, arial_12), 0, False)
    magtag.set_text(wrap(selected["projectDescription"], 530, 10, arial_9), 1)
    magtag.exit_and_deep_sleep(3600)
except Exception: # pylint: disable=broad-except
    print("Could not set title or description: unsupported glyphs.")
    print("Trying again in 10 seconds.")
    magtag.exit_and_deep_sleep(10)

This guide was first published on Oct 13, 2021. It was last updated on 2021-10-13 12:02:36 -0400.