Devesh36/usb-c-aqi-meter

A PETG-enclosed air-quality monitor assembly combining an AQI circuit board, Sensirion SPS30 particulate sensor, OLED display with bezel and glass, power slider, branding, and internal wiring harness.

Version
1.2.0
License
unset
Stars
0

Use with the tscircuit CLI

tsci is the tscircuit CLI. Install it with npm install -g tscircuit.

tsci clone Devesh36/usb-c-aqi-meter  # download the package files into ./usb-c-aqi-meter
tsci add Devesh36/usb-c-aqi-meter    # add it to your project as @tsci/Devesh36.usb-c-aqi-meter

In a cloned or new (tsci init) project: tsci dev starts a local preview, tsci build outputs Circuit JSON, and tsci push publishes to tscircuit.com.

firmware/protocol.py

"""Pure-Python SPS30 SHDLC, SHT4x CRC, and indicative PM2.5 index helpers."""
import math
import struct


def crc8(data):
    crc = 0xFF
    for value in data:
        crc ^= value
        for _ in range(8):
            crc = ((crc << 1) ^ (0x31 if crc & 0x80 else 0)) & 0xFF
    return crc


def shdlc_request(command, data=b""):
    body = bytes((0, command, len(data))) + data
    body += bytes(((~sum(body)) & 0xFF,))
    escaped = bytearray((0x7E,))
    for value in body:
        if value in (0x7E, 0x7D, 0x11, 0x13):
            escaped.extend((0x7D, value ^ 0x20))
        else:
            escaped.append(value)
    escaped.append(0x7E)
    return bytes(escaped)


def shdlc_response(frame, command):
    if len(frame) < 2 or frame[0] != 0x7E or frame[-1] != 0x7E:
        raise ValueError("Incomplete SPS30 frame")
    body, escape = bytearray(), False
    for value in frame[1:-1]:
        if escape:
            if value not in (0x5E, 0x5D, 0x31, 0x33):
                raise ValueError("Bad SPS30 escape")
            body.append(value ^ 0x20)
            escape = False
        elif value == 0x7D:
            escape = True
        elif value in (0x7E, 0x11, 0x13):
            raise ValueError("Unescaped SPS30 byte")
        else:
            body.append(value)
    if escape or len(body) < 5 or sum(body) & 0xFF != 0xFF:
        raise ValueError("SPS30 checksum/frame error")
    if body[0] != 0 or body[1] != command or len(body) != body[3] + 5:
        raise ValueError("Unexpected SPS30 response")
    # Reject both execution errors and the device-status error flag.
    if body[2]:
        raise ValueError("SPS30 state 0x%02X" % body[2])
    return bytes(body[4:-1])


def particle_values(payload):
    if not payload:
        return None  # No fresh measurement yet; do not display a fabricated zero.
    if len(payload) != 40:
        raise ValueError("Expected ten SPS30 floats")
    values = struct.unpack(">10f", payload)
    if any(not math.isfinite(v) or v < 0 for v in values):
        raise ValueError("Invalid SPS30 measurement")
    return values


# US EPA 2024 PM2.5 breakpoints. Using short-term concentration gives an
# INDICATIVE index only, not a 24-hour regulatory AQI or AirNow NowCast.
BREAKPOINTS = (
    (0.0, 9.0, 0, 50), (9.1, 35.4, 51, 100),
    (35.5, 55.4, 101, 150), (55.5, 125.4, 151, 200),
    (125.5, 225.4, 201, 300), (225.5, 325.4, 301, 500),
)


def indicative_aqi(pm25):
    if not math.isfinite(pm25) or pm25 < 0:
        raise ValueError("Invalid PM2.5")
    # EPA truncation of concentration to one decimal, then round-half-up index.
    c = math.floor(pm25 * 10) / 10
    if c > 325.4:
        return 501  # UI explicitly shows >500; do not silently clamp to 500.
    for lo, hi, ilo, ihi in BREAKPOINTS:
        if c <= hi:
            return int((ihi - ilo) * (c - lo) / (hi - lo) + ilo + 0.5)
    raise ValueError("PM2.5 outside supported range")