# MicroPython

The MicroPython device SDK connects a board to Qualithm in one call. On first boot the board claims
its credential with a claim code and stores it in flash. Every later boot reuses it. The SDK joins
Wi-Fi, checks every server's TLS certificate, renews the credential before it expires and reconnects
when the connection drops.

Your `main.py` holds what the board does. The example on this page sends the board's uptime, free
memory, chip temperature, Wi-Fi signal strength and firmware version every minute, so the readings
appear on a dashboard.

## Before you start

- A scope and a claim code for it. The app's setup creates both: [Set up your
  first device](https://app.qualithm.com/setup). To add a code to an existing scope, open the scope and choose **Claim
  codes**.
- The API URL the device claims its credential at. It's on the [HTTP](https://docs.qualithm.com/http.md#find-your-api-url) page.
- [uv](https://docs.astral.sh/uv/), which runs `mpremote` and `esptool` without installing them.
- A 2.4 GHz Wi-Fi network, for a board.

## Run it on a Pico 2 W

You need a Raspberry Pi Pico 2 W and a USB cable.

1. Flash MicroPython 1.29.0. Hold BOOTSEL while you plug the board in, then copy the Pico 2 W `.uf2`
   from [micropython.org/download/RPI_PICO2_W](https://micropython.org/download/RPI_PICO2_W/) onto
   the `RP2350` drive that appears.
2. Join Wi-Fi and install the SDK:

   ```bash
   uvx mpremote exec "import network; w = network.WLAN(network.STA_IF); w.active(True); w.connect('<your-ssid>', '<your-password>')"
   uvx mpremote exec "import mip; mip.install('github:qualithm/device-sdk-py')"
   ```

3. Write the setup file the board reads on boot, with your network, API URL and claim code filled
   in:

   ```bash
   uvx mpremote exec "import json; open('/qualithm-setup.json', 'w').write(json.dumps({'provisioningUrl': '<your-api-url>', 'wifi': {'ssid': '<your-ssid>', 'passphrase': '<your-password>'}, 'claimCode': '<your-claim-code>'}))"
   ```

4. Save this as `main.py`:

   ```python
   import time

   from qualithm_device import pico

   device = pico.start()
   while True:
       device.publish_reading(pico.system_info())
       device.poll()
       device.renew_if_due()
       time.sleep(60)
   ```

5. Copy it to the board and reset it:

   ```bash
   uvx mpremote cp main.py :main.py + reset
   ```

The board joins the network and claims itself. It then removes the used claim code from the setup
file. A Pico connects with a token credential, since it has no on-board key generation for a
certificate.

The board's LED shows where it is:

| LED                                  | State                                       |
| ------------------------------------ | ------------------------------------------- |
| Slow pulse, one second on, one off   | Joining Wi-Fi and reaching the gateway      |
| Q in Morse (long, long, short, long) | Just claimed                                |
| Steady                               | Connected                                   |
| Fast flash, twice a second           | Needs attention: read the error on the REPL |
| Off                                  | Not running, or unpowered                   |

To read the REPL, run `uvx mpremote` with the board plugged in.

## Run it on an ESP32

You need an ESP32-S3, ESP32-C3 or ESP32-C6 board and a USB cable. The reference boards are the
M5Stack AtomS3 Lite (S3), Stamp C3 (C3) and NanoC6 (C6).

1. Download MicroPython 1.29.0 for your chip:
   [ESP32_GENERIC_S3](https://micropython.org/download/ESP32_GENERIC_S3/) or
   [ESP32_GENERIC_C6](https://micropython.org/download/ESP32_GENERIC_C6/). On an ESP32-C3, download
   the [Qualithm image](https://github.com/qualithm/micropython-firmware/releases/latest) for the C3
   instead. It has the SDK built in, which leaves the C3 enough memory for TLS.
2. Flash it, naming your chip (`esp32s3`, `esp32c3` or `esp32c6`) and the `.bin` you downloaded:

   ```bash
   uvx esptool --chip <your-chip> erase-flash
   uvx esptool --chip <your-chip> write-flash 0 <your-firmware>.bin
   ```

   If esptool can't connect, hold the board's boot button while you plug it in, then run it again.

3. Join Wi-Fi, install the SDK and write the setup file, as steps 2 and 3 for the Pico 2 W do. On
   the C3's Qualithm image, skip installing the SDK.
4. Save this as `main.py`, copy it to the board and reset it:

   ```python
   import time

   from qualithm_device import esp32

   device = esp32.start()
   while True:
       device.publish_reading(esp32.system_info())
       device.poll()
       device.renew_if_due()
       time.sleep(60)
   ```

   ```bash
   uvx mpremote cp main.py :main.py + reset
   ```

An ESP32 sends the same readings as a Pico 2 W. It joins WPA2 and WPA3 Personal networks.

## Run it as a virtual device

A virtual device runs the same code on your computer, with no board. It claims, connects and reports
as a Pico does. Its readings count toward the team's monthly events.

1. Install MicroPython 1.29.0 and the SDK:

   ```bash
   brew install micropython
   micropython -m mip install github:qualithm/device-sdk-py
   ```

2. Write the setup file in your project's folder:

   ```bash
   echo '{"provisioningUrl": "<your-api-url>", "claimCode": "<your-claim-code>"}' > qualithm-setup.json
   ```

3. Save this as `main.py`. The same file runs unchanged on a Pico 2 W or an ESP32:

   ```python
   import time

   from qualithm_device import board

   device = board.start()
   while True:
       device.publish_reading(board.system_info())
       device.poll()
       device.renew_if_due()
       time.sleep(60)
   ```

4. Run it:

   ```bash
   micropython main.py
   ```

The virtual device stores its credential in `qualithm-credential.json`, next to the setup file.
Anyone who can read that folder can read the credential, so keep it out of version control.

## Deploy with the CLI

`qualithm deploy` puts your project folder on a board, with no setup file to write. Sign in once
with `qualithm login`. Then run it from the folder with the board plugged in:

```bash
qualithm deploy
```

If your team has more than one scope, name the new board's scope with `--scope <your-scope-id>`.

The CLI makes three choices for a new board. Its receipt names each one and links to its section
here.

### The MicroPython release

A blank board gets the one MicroPython release the device SDK is tested against. The CLI checks the
image's checksum before it flashes it. A board already running MicroPython keeps its release.
`qualithm board flash` replaces it.

| Board                                     | Image                                               |
| ----------------------------------------- | --------------------------------------------------- |
| Raspberry Pi Pico 2 W, ESP32-S3, ESP32-C6 | MicroPython from micropython.org                    |
| ESP32-C3                                  | Qualithm's MicroPython build, with the SDK built in |

Stock MicroPython can't hold the SDK and a TLS handshake in the ESP32-C3's memory at once.
Qualithm's build from
[micropython-firmware](https://github.com/qualithm/micropython-firmware/releases) leaves it room.

### The device SDK

Each deploy writes the device SDK release the CLI pins to the board's `/lib` folder, next to your
project's files. Only files that changed are written. On the ESP32-C3's Qualithm build, the SDK is
already built in, so the CLI leaves it out. If that build holds another SDK release, the deploy
stops and asks you to run `qualithm board flash`.

### The Wi-Fi network

A new board joins the Wi-Fi network your computer is on. If your computer isn't on one, the board
takes the first network your computer has saved. To choose another, name it:

```bash
qualithm deploy --wifi <your-network>
```

The CLI reads the passphrase from your computer's own store: the Keychain on macOS, NetworkManager
on Linux, the saved Wi-Fi profiles on Windows. Your computer may ask you to allow it. The passphrase
goes from that store straight to the board. It never passes through your AI agent. If the store has
none, run `qualithm deploy` once in a terminal, which asks for it. Later deploys keep the board's
network.

## Next steps

- [Devices](https://docs.qualithm.com/devices.md): how a device reaches production and how to move or delete it.
- [Dashboards](https://docs.qualithm.com/dashboards.md): put the board's readings on a grid of widgets.
- [Declare capabilities](https://docs.qualithm.com/mqtt.md#declare-capabilities): add your own readings and controls.
