Download tasks/data/forward/adafruit__adafruit_circuitpython_midi.6f5d681/instruction.md from Lego-X/ProgramGen: direct link, hf CLI and curl.
- Browser
- Download file 83.9 kB
-
https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/adafruit__adafruit_circuitpython_midi.6f5d681/instruction.md
- Command line
-
hf download hf://datasets/Lego-X/ProgramGen/tasks/data/forward/adafruit__adafruit_circuitpython_midi.6f5d681/instruction.md
-
curl -L -o instruction.md https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/adafruit__adafruit_circuitpython_midi.6f5d681/instruction.md
adafruit/adafruit_circuitpython_midi
Project Overview
Adafruit_CircuitPython_MIDI is a CircuitPython helper library for encoding and decoding MIDI messages, letting a microcontroller board running CircuitPython (or a host such as a Raspberry Pi) exchange MIDI packets over a MIDI wire connection or UART, and over transports like USB MIDI and BLE MIDI that expose a byte-stream port. Its scope is the MIDI 1.0 message protocol: it models individual MIDI messages as Python objects and takes care of serializing them into status and data bytes on output and parsing incoming byte streams back into typed message objects.
The package is organized around two core pieces. adafruit_midi/midi_message.py defines the abstract MIDIMessage base class, which establishes the status-byte, fixed/variable-length, and channel-mask conventions shared by every message type, plus a registry that each message module populates at import time so the parser (from_message_bytes) can recognize a status byte and construct the matching class. Shared utilities include note-name parsing ('C#4' to a MIDI key number) and channel-specification matching. adafruit_midi/init.py provides the top-level MIDI object, which wraps an input and output port (for example usb_midi.ports or a busio.UART), tracks the in and out channels, sends message objects either individually or as lists, and reads incoming bytes into message objects with configurable blocking behavior.
Channel voice messages are implemented one per module - note_on, note_off, control_change, program_change, pitch_bend, channel_pressure, and polyphonic_key_pressure - while system common and realtime messages cover system_exclusive, mtc_quarter_frame, start, stop, midi_continue, timing_clock, active_sensing, and midi_reset; control_change_values enumerates standard controller numbers. Supporting material includes usage examples, unit tests, and Sphinx documentation published on Read the Docs, following the standard Adafruit CircuitPython library structure.
Re-implement this repository from scratch so that the original test suite passes. The sections below document the language/environment, the project structure, the public API the tests exercise, and per-capability implementation guidance.
Submission Constraints (read carefully — the evaluation depends on these)
This is a closed-book task. The graded test suite is hidden and will be injected into the workspace at evaluation time. To be scored correctly you MUST follow these rules:
Do NOT create or modify any files under the test directories (e.g.
tests/,test/,testing/, or files namedtest_*.py/conftest.py). The grader injects its own test files at those paths; any file you place there will collide with the injected suite and cause the whole evaluation to score 0. Implement only the library/source code — never the tests.Your package MUST be importable by the name the tests use. The hidden tests
importyour package by its documented top-level name (see the Project Directory Structure and API Usage Guide below). Provide a validpyproject.toml/setup.py/setup.cfgand lay out your modules so thatpip install -e .succeeds and the package imports cleanly. If your package is not installable/importable, every test errors out and the reward is 0.Match the documented module paths and public API exactly (names, signatures, and any literal error/exception strings). Internal helpers not listed in the API guide may be implemented however you like.
Install / Reconstruction Contract
Follow this contract before implementing the documented APIs:
- Project root:
/workspace/repoat runtime; the submitted repository root is.. - Package/distribution name:
adafruit-circuitpython-midi - Package roots:
. - Install strategy:
editable-install - Import/entry: use the package and public entry points listed in the API Usage Guide; do not invent a different top-level package.
- Provision commands:
python3 -I -c 'import base64; from pathlib import Path; Path('"'"'/tmp/programgen-pip-compat-v1.py'"'"').write_bytes(base64.b64decode('"'"'aW1wb3J0IG9zCmZyb20gcGF0aGxpYiBpbXBvcnQgUGF0aAppbXBvcnQgc3VicHJvY2VzcwppbXBvcnQgc3lzCmltcG9ydCB0ZW1wZmlsZQoKZGVmIGNvbnN0cmFpbmVkX2J1aWxkX2luc3RhbGwoY29tbWFuZCwgcnVuKToKICAgIGNvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCgnUFJPR1JBTUdFTl9CVUlMRF9DT05TVFJBSU5UJykKICAgIGlmIG5vdCBjb25zdHJhaW50IG9yICctLW5vLWJ1aWxkLWlzb2xhdGlvbicgaW4gY29tbWFuZDoKICAgICAgICByZXR1cm4gTm9uZQogICAgaWYgc3lzLnZlcnNpb25faW5mb1s6Ml0gPCAoMywgOSk6CiAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSBpc29sYXRlZCBidWlsZCBjb25zdHJhaW50cyByZXF1aXJlIFB5dGhvbiA+PTMuOScsIGZsdXNoPVRydWUpCiAgICAgICAgcmV0dXJuIDEKICAgICMgQSBkZWRpY2F0ZWQgaW5zdGFsbGVyIGNvbnRyb2xzIFBFUCA1MTcgYnVpbGQgZGVwZW5kZW5jaWVzIG9ubHkuIEl0IGRvZXMKICAgICMgbm90IHVwZ3JhZGUgcGlwL3NldHVwdG9vbHMgaW4gdGhlIG1lYXN1cmVkIHByb2plY3QncyBydW50aW1lIGVudmlyb25tZW50LgogICAgd2l0aCB0ZW1wZmlsZS5UZW1wb3JhcnlEaXJlY3RvcnkocHJlZml4PSdwcm9ncmFtZ2VuLWJ1aWxkLWluc3RhbGxlci0nKSBhcyBkaXJlY3Rvcnk6CiAgICAgICAgcnVubmVyID0gc3RyKFBhdGgoZGlyZWN0b3J5KSAvICdiaW4nIC8gJ3B5dGhvbicpCiAgICAgICAgZm9yIHNldHVwIGluIChbc3lzLmV4ZWN1dGFibGUsICctbScsICd2ZW52JywgZGlyZWN0b3J5XSwKICAgICAgICAgICAgICAgICAgICAgIFtydW5uZXIsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICctLW5vLWNhY2hlLWRpcicsICdwaXA9PTI1LjMnXSk6CiAgICAgICAgICAgIHJlc3VsdCA9IHJ1bihzZXR1cCkKICAgICAgICAgICAgaWYgcmVzdWx0LnJldHVybmNvZGU6CiAgICAgICAgICAgICAgICByZXR1cm4gcmVzdWx0LnJldHVybmNvZGUKICAgICAgICBpZiBjb21tYW5kWzo0XSAhPSBbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCddIGFuZCBjb21tYW5kWzo0XSAhPSBbJ3B5dGhvbjMnLCAnLW0nLCAncGlwJywgJ2luc3RhbGwnXToKICAgICAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSB1bnN1cHBvcnRlZCBjb25zdHJhaW5lZCBpbnN0YWxsZXIgY29tbWFuZCcsIGZsdXNoPVRydWUpCiAgICAgICAgICAgIHJldHVybiAxCiAgICAgICAgdGFyZ2V0ID0gW3J1bm5lciwgJy1tJywgJ3BpcCcsICctLXB5dGhvbicsIHN5cy5leGVjdXRhYmxlLCAnaW5zdGFsbCcsCiAgICAgICAgICAgICAgICAgICctLWJ1aWxkLWNvbnN0cmFpbnQnLCBjb25zdHJhaW50XSArIGNvbW1hbmRbNDpdCiAgICAgICAgcmV0dXJuIHJ1bih0YXJnZXQpLnJldHVybmNvZGUKCmRlZiBpbnN0YWxsKGNvbW1hbmQsIHJ1bj1zdWJwcm9jZXNzLnJ1bik6CiAgICBmb3IgdmFyaWFibGUgaW4gKCdQUk9HUkFNR0VOX1JVTlRJTUVfQ09OU1RSQUlOVCcsICdQUk9HUkFNR0VOX1JVTlRJTUVfUkVQQUlSX0NPTlNUUkFJTlQnKToKICAgICAgICBydW50aW1lX2NvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCh2YXJpYWJsZSkKICAgICAgICBpZiBydW50aW1lX2NvbnN0cmFpbnQ6CiAgICAgICAgICAgIGNvbW1hbmQgPSBsaXN0KGNvbW1hbmQpICsgWyctYycsIHJ1bnRpbWVfY29uc3RyYWludF0KICAgIGNvbnN0cmFpbmVkID0gY29uc3RyYWluZWRfYnVpbGRfaW5zdGFsbChjb21tYW5kLCBydW4pCiAgICBpZiBjb25zdHJhaW5lZCBpcyBub3QgTm9uZToKICAgICAgICByZXR1cm4gY29uc3RyYWluZWQKICAgIHJlc3VsdCA9IHJ1bihjb21tYW5kLCBzdGRvdXQ9c3VicHJvY2Vzcy5QSVBFLCBzdGRlcnI9c3VicHJvY2Vzcy5TVERPVVQsIHRleHQ9VHJ1ZSkKICAgIG91dHB1dCA9IHJlc3VsdC5zdGRvdXQgb3IgJycKICAgIHN5cy5zdGRvdXQud3JpdGUob3V0cHV0KQogICAgc3lzLnN0ZG91dC5mbHVzaCgpCiAgICBpZiByZXN1bHQucmV0dXJuY29kZSA9PSAwOgogICAgICAgIHJldHVybiAwCiAgICBsZWdhY3kgPSAnaW52YWxpZCBtZXRhZGF0YScgaW4gb3V0cHV0Lmxvd2VyKCkgYW5kICdwbGVhc2UgdXNlIHBpcDwyNC4xJyBpbiBvdXRwdXQubG93ZXIoKQogICAgaWYgbm90IGxlZ2FjeSBvciBub3QgKDMsIDgpIDw9IHN5cy52ZXJzaW9uX2luZm9bOjJdIDw9ICgzLCAxMik6CiAgICAgICAgcmV0dXJuIHJlc3VsdC5yZXR1cm5jb2RlCiAgICBwcmludCgnW3Byb2dyYW1nZW5dIGxlZ2FjeSBkaXN0cmlidXRpb24gbWV0YWRhdGE6IHJldHJ5aW5nIHRoZSB1bmNoYW5nZWQgcmVxdWlyZW1lbnRzIHdpdGggcGlwPDI0LjEnLCBmbHVzaD1UcnVlKQogICAgY2hhbmdlZCA9IHJ1bihbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICdwaXA8MjQuMSddKQogICAgaWYgY2hhbmdlZC5yZXR1cm5jb2RlOgogICAgICAgIHJldHVybiBjaGFuZ2VkLnJldHVybmNvZGUKICAgIHJldHVybiBydW4oY29tbWFuZCkucmV0dXJuY29kZQoKaWYgX19uYW1lX18gPT0gJ19fbWFpbl9fJzoKICAgIHJhaXNlIFN5c3RlbUV4aXQoaW5zdGFsbChzeXMuYXJndlsxOl0pKQo='"'"'))' programgen_pip_install() { python3 -I /tmp/programgen-pip-compat-v1.py "$@"; } export -f programgen_pip_install programgen_pip_install python3 -m pip install -U pip 'setuptools<82' wheel programgen_pip_install python3 -m pip install setuptools wheel setuptools-scm ( programgen_install_report="$(mktemp)" trap 'rm -f "$programgen_install_report"' EXIT SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 programgen_pip_install python3 -m pip install -e . --no-build-isolation --no-deps --report "$programgen_install_report" python3 -c 'exec("import json,subprocess,sys\nfrom pip._vendor.packaging.requirements import Requirement\nfrom pip._vendor.packaging.utils import canonicalize_name\nreport=json.load(open(sys.argv[1], encoding='"'"'utf-8'"'"'))\n\nrequested={canonicalize_name(name) for name in ()}\nrequirements=[]\nfor item in report.get('"'"'install'"'"', []):\n metadata=item.get('"'"'metadata'"'"', {})\n name=canonicalize_name(metadata.get('"'"'name'"'"', '"'"''"'"'))\n provided={canonicalize_name(value) for value in metadata.get('"'"'provides_extra'"'"', [])}\n selected={'"'"''"'"'} | (provided & requested)\n parsed=[Requirement(value) for value in metadata.get('"'"'requires_dist'"'"', [])]\n while True:\n added=set()\n for requirement in parsed:\n if requirement.marker is not None and not any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n continue\n if canonicalize_name(requirement.name)==name:\n if requirement.url or (requirement.specifier and not requirement.specifier.contains(metadata.get('"'"'version'"'"', '"'"''"'"'), prereleases=True)):\n raise ValueError('"'"'local extra requires a different target distribution'"'"')\n extras={canonicalize_name(value) for value in requirement.extras}\n if not extras <= provided:\n raise ValueError('"'"'local extra refers to an undeclared extra'"'"')\n added.update(extras - selected)\n if not added:\n break\n selected.update(added)\n for requirement in parsed:\n if canonicalize_name(requirement.name)==name:\n continue\n if requirement.marker is None or any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n requirement.marker=None\n requirements.append(str(requirement))\nrequirements=list(dict.fromkeys(requirements))\nsubprocess.run([sys.executable, '"'"'-I'"'"', '"'"'/tmp/programgen-pip-compat-v1.py'"'"', sys.executable, '"'"'-m'"'"', '"'"'pip'"'"', '"'"'install'"'"', *requirements], check=True) if requirements else None\n")' "$programgen_install_report" ) - Runtime setup:
{ [ -e "$PWD"/README.rst ] || { mkdir -p "$(dirname "$PWD"/README.rst)"; : > "$PWD"/README.rst; }; SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 SETUPTOOLS_SCM_WRITE_TO_SOURCE=1 python3 -m pip install -e "$PWD" --no-build-isolation --no-deps; } - Project root for installation:
. - Build-version environment:
SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0,PDM_BUILD_SCM_VERSION=0.0.0,POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0,UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 - Test directory:
tests - Test command:
bash -lc 'export PYTHONPATH=.:${PYTHONPATH:-} set -uo pipefail run=(python3 -m pytest -vv --continue-on-collection-errors -o addopts= tests/test_MIDIMessage_unittests.py tests/test_MIDI_unittests.py tests/test_note_parser.py) if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv --continue-on-collection-errors -o addopts= tests/test_MIDIMessage_unittests.py tests/test_MIDI_unittests.py tests/test_note_parser.py); fi collect=(python3 -m pytest -q -o addopts= tests/test_MIDIMessage_unittests.py tests/test_MIDI_unittests.py tests/test_note_parser.py) collected_output=$("${collect[@]}" --collect-only) collect_rc=$? if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then printf "%s\n" "$collected_output" >&2 printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 exit "$collect_rc" fi mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '"'"'/::/p'"'"' | sed '"'"'s/[[:space:]]*$//'"'"') if [ "${#collected[@]}" -gt 500 ]; then while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'"'"'::'"'"' -v limit=500 '"'"'{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}'"'"') fi "${run[@]}"; exit $?' - Test startup: run the exact test command above from the project root after installation; hidden tests are injected separately.
Environment & Project Structure
- Language: python
- Build system: python
- Test command:
bash -lc export PYTHONPATH=.:${PYTHONPATH:-} set -uo pipefail run=(python3 -m pytest -vv --continue-on-collection-errors -o addopts= tests/test_MIDIMessage_unittests.py tests/test_MIDI_unittests.py tests/test_note_parser.py) if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv --continue-on-collection-errors -o addopts= tests/test_MIDIMessage_unittests.py tests/test_MIDI_unittests.py tests/test_note_parser.py); fi collect=(python3 -m pytest -q -o addopts= tests/test_MIDIMessage_unittests.py tests/test_MIDI_unittests.py tests/test_note_parser.py) collected_output=$("${collect[@]}" --collect-only) collect_rc=$? if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then printf "%s\n" "$collected_output" >&2 printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 exit "$collect_rc" fi mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '/::/p' | sed 's/[[:space:]]*$//') if [ "${#collected[@]}" -gt 500 ]; then while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'::' -v limit=500 '{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}') fi "${run[@]}"; exit $?
Project Directory Structure
.gitattributes
.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md
.github/workflows/build.yml
.github/workflows/failure-help-text.yml
.github/workflows/release_gh.yml
.github/workflows/release_pypi.yml
.gitignore
.pre-commit-config.yaml
.readthedocs.yaml
CODE_OF_CONDUCT.md
LICENSE
LICENSES/CC-BY-4.0.txt
LICENSES/MIT.txt
LICENSES/Unlicense.txt
README.rst
README.rst.license
adafruit_midi/__init__.py
adafruit_midi/active_sensing.py
adafruit_midi/channel_pressure.py
adafruit_midi/control_change.py
adafruit_midi/control_change_values.py
adafruit_midi/midi_continue.py
adafruit_midi/midi_message.py
adafruit_midi/midi_reset.py
adafruit_midi/mtc_quarter_frame.py
adafruit_midi/note_off.py
adafruit_midi/note_on.py
adafruit_midi/pitch_bend.py
adafruit_midi/polyphonic_key_pressure.py
adafruit_midi/program_change.py
adafruit_midi/start.py
adafruit_midi/stop.py
adafruit_midi/system_exclusive.py
adafruit_midi/timing_clock.py
docs/_static/custom.css
docs/_static/favicon.ico
docs/_static/favicon.ico.license
docs/api.rst
docs/api.rst.license
docs/conf.py
docs/examples.rst
docs/examples.rst.license
docs/index.rst
docs/index.rst.license
docs/requirements.txt
examples/midi_inoutdemo.py
examples/midi_intest1.py
examples/midi_memorycheck.py
examples/midi_simpletest.py
optional_requirements.txt
pyproject.toml
requirements.txt
ruff.toml
API Usage Guide
Each capability below lists the components the tests exercise with their exact signatures and behavior. Re-create these so the tests pass; internal helpers not listed here may be implemented freely.
Capability: MIDI port and channel configuration
MIDI port and channel configuration
Purpose and object model
A single MIDI instance is the configuration point for a whole MIDI link. It wraps at most one input port (any object implementing read(length), e.g. usb_midi.ports[0] or a busio.UART) and one output port (any object implementing write(buffer, length), e.g. usb_midi.ports[1] or a UART); other duck-typed streams work equally well. Two channel settings hang off the object: in_channel, the filter receive() applies to parsed messages, and out_channel, the default send() uses when no channel is passed. All channels are wire protocol numbers 0-15, where MIDI channel N is wire number N-1 (wire 3 = MIDI channel 4).
Construction and validation order
At least one port is mandatory: MIDI() raises ValueError("No midi_in or midi_out provided"). Output-only and input-only instances are both legal (the tests construct MIDI(midi_out=...) and MIDI(midi_in=..., midi_out=None)); the unused direction simply never transfers data, and it is also never null-checked. Calling receive() when midi_in is None raises AttributeError ('NoneType' object has no attribute 'read') because receive() dereferences the port to top up its buffer — there is no graceful None return. Calling send() when midi_out is None raises AttributeError ('NoneType' object has no attribute 'write'), but only after send() stamps msg.channel and, with debug=True, prints the Sending: line — so a send() on an input-only instance mutates the message before it fails.
Validation runs in a strict order: ports first (ValueError), then in_channel, then out_channel (both RuntimeError). So MIDI(midi_out=p, in_channel=99, out_channel=16) fails with "Invalid input channel" before the output value is ever examined. The constructor assigns both channels through their property setters, which has two consequences: in_channel="ALL" is accepted in the constructor even though the __init__ type hint lists only Optional[Union[int, Tuple[int, ...]]], and constructing with an invalid channel can still mutate the private attribute before the exception propagates (the object never becomes usable). Note that a non-numeric out_channel (e.g. a string) fails inside the range comparison with TypeError, not RuntimeError.
Channel normalization
Both properties re-validate identically on every later assignment, so a bad value fails at the configuration site rather than corrupting a status byte at send time.
out_channel: any int 0-15; default0(MIDI channel 1).in_channelaccepts:- an int 0-15, stored as that int;
- a tuple whose elements are only range-checked (
0 <= c <= 15) at the comparison itself, with no per-element type check: a non-comparable element such as a string raisesTypeErrorfrom the comparison (e.g.in_channel=(1, "x")), a comparable out-of-range element (e.g.20) raisesRuntimeError("Invalid input channel"), and any comparable in-range value — floats and bools included — is accepted and stored verbatim, so "a tuple of ints" understates the validation. The tuple itself is stored verbatim — not sorted, not de-duplicated; None(the default) or the string"ALL", both normalized totuple(range(16))(listen on all channels);- only specs that are none of int, tuple,
None, or"ALL"(e.g. a bare float or a list) fall through toRuntimeError("Invalid input channel").
Test-sensitive consequences:
- After construction the
in_channelgetter never returnsNone; the default has become the 16-element tuple. The getter's type reveals the mode:int= single channel,tuple= multi-channel. - An empty tuple passes validation (
all()over nothing is true) and matches no channel —receive()then consumes every channel voice message as skipped bytes.boolis anintsubclass, soin_channel=Trueis silently channel 1. - Parse-time matching uses
channel_filter: an int spec matches by equality, a tuple spec by membership, and any other spec type raisesValueError("Incorrect type for channel_spec...")— unreachable via the property setter but reachable iffrom_message_bytesis called directly with a hand-made filter.
How the settings are consumed
receive()callsMIDIMessage.from_message_bytes(self._in_buf, self._in_channel). The filter applies only to messages that carry a channel; system messages (channel is None, e.g. SysEx, timing clock, unknown statuses) always pass through and exposechannel=None. Messages on unlistened channels are parsed, discarded, and counted as skipped bytes — never returned.receive()returnsNoneboth when the port is empty and when the buffer holds only partial or non-matching data, so callers (and the tests) loop until a non-Noneresult. It preserves the port's blocking character: a UART input blocks insideread,usb_midi.ports[0]is effectively non-blocking.send(msg)(or a list/tuple of messages): whenchannelis omitted,out_channelis used; an explicitchannel=noverrides it for that call only. Either way the channel is written into each message object —msg.channelis mutated as a side effect — and the wire status byte is the message's base status with the channel in the low nibble:out_channel=2sends NoteOn as0x92 ...;send(NoteOn(...), channel=9)sends0x99 .... A sequence is emitted in a singlewrite(buffer, length)call. Because the channel is stamped into the object, a laterbytes(msg)reflects the last-sent channel.
Buffer interaction
in_buf_size (default 30) caps the internal receive buffer. Each receive() tops the buffer up from the port only while it is shorter than in_buf_size, parses from the front, trims consumed bytes, and retains any partial message for the next call. The buffer must therefore exceed the longest expected message: a SysEx larger than in_buf_size can never complete — every receive() returns None while data keeps arriving, and once parsing reaches the end-of-exclusive byte the implementation reports MIDIUnknownEvent with status=0xF7 and channel=None, after which subsequent messages parse normally. Malformed messages can surface as MIDIBadEvent (also channel=None). These exact behaviors are asserted by the test suite, so a re-implementation must reproduce them.
Debug aid
With debug=True, transfers print hex byte lists, but the two directions are not symmetric. Receiving: prints only the non-empty byte list returned by the port's read() (guarded by if bytes_in:) — empty and partial reads print nothing — and it dumps those raw bytes before any parsing or channel filtering, so the channels in its low nibbles are what the peer sent (including unlistened channels), not the configured in_channel. Sending: prints the exact packet handed to write(), so it is the one direction whose low nibble reflects the configured channel. A re-implementation must not print Receiving: on empty reads and must not treat its output as reflecting the configured channels.
Exact API Reference
adafruit_midi.MIDI
- Import Path:
from adafruit_midi import MIDI - Required Test Import Paths:
- adafruit_midi.MIDI
- Exact Test Import Statements:
- import adafruit_midi
- Kind: class
- Signature:
class MIDI:
def __init__(self, midi_in: Optional[BinaryIO]=None, midi_out: Optional[BinaryIO]=None, *, in_channel: Optional[Union[int, Tuple[int, ...]]]=None, out_channel: int=0, in_buf_size: int=30, debug: bool=False)
@property
def in_channel(self) -> Optional[Union[int, Tuple[int, ...]]]
@in_channel.setter
def in_channel(self, channel: Optional[Union[str, int, Tuple[int, ...]]]) -> None
@property
def out_channel(self) -> int
@out_channel.setter
def out_channel(self, channel: int) -> None
def receive(self) -> Optional[MIDIMessage]
def send(self, msg: MIDIMessage, channel: Optional[int]=None) -> None
_in_buf_size: Any
- Raises (implementation must reproduce these exact messages):
No midi_in or midi_out providedInvalid output channelInvalid input channel
- Behavior: MIDI helper class.
midi_inormidi_outmust be set or both together.
adafruit_midi
- Import Path:
adafruit_midi - Required Test Import Paths:
- adafruit_midi
- Exact Test Import Statements:
- import adafruit_midi
- Kind: module
- Behavior: Module required during hidden-test collection.
Capability: MIDI message encoding to wire bytes
Encoding MIDI messages to wire bytes
Purpose
Each channel-voice message class models one MIDI 1.0 event as a plain Python object. Converting an object with bytes(...) (the __bytes__ wire protocol) produces the exact status-plus-data byte sequence for a MIDI/UART or USB-MIDI/BLE-MIDI byte-stream port, with the message's channel number merged into the low nibble of the status byte. The test suite compares these bytes values literally, so the encodings below are the contract a re-implementation must satisfy.
Shared conventions
All message classes derive from MIDIMessage, which fixes the layout:
_STATUS— the status byte with channel bits cleared (MSB always set).CHANNELMASK = 0x0F— the mask used to OR the channel into_STATUS.LENGTH— total wire length including the status byte (2 forChannelPressure, 3 forControlChangeandPitchBend).- The base
MIDIMessage.__bytes__returns justbytes([self._STATUS]); every concrete channel message overrides it to append its data bytes.
Encoding is stateless and deterministic: bytes(msg) reads the stored attributes and channel, never mutates the object, and repeated calls yield identical results. Data bytes always follow the status byte in a fixed order, and their 7-bit (0-127, MSB clear) property comes from constructor validation rather than masking - pitch bend is the exception, since it masks and splits explicitly.
Concrete encodings
ControlChange(control, value, *, channel=None)- 3 bytes:0xB0 | channel,control,value.ControlChange(7, 100, channel=0)encodes asbytes([0xB0, 7, 100]).ChannelPressure(pressure, *, channel=None)- 2 bytes:0xD0 | channel,pressure.PitchBend(pitch_bend, *, channel=None)- 3 bytes:0xE0 | channel, then the 14-bit value split LSB-first:pitch_bend & 0x7Ffollowed by(pitch_bend >> 7) & 0x7F. The no-bend midpoint 8192 encodes asbytes([0xE0 | channel, 0x00, 0x40]). The LSB-before-MSB ordering is the easiest detail to get backwards.
Channel handling and validation order
Constructors take keyword-only channel=None; validation happens in a strict order that tests exercise:
- The
channelproperty setter raisesValueError("Channel must be 0-15 or None")for anything outside 0-15 (Noneis allowed and means "not yet assigned"). - Data ranges are checked afterwards, raising
ValueError("Out of range"):pressuremust be 0-127; bothcontrolandvaluemust be 0-127;pitch_bendmust be 0-16383.
Because the overrides compute _STATUS | (self.channel & CHANNELMASK), calling bytes() on a message whose channel is still None raises TypeError. In normal workflows the top-level MIDI object fills in the out-channel during send() when a message's channel is None (the channel property is documented as "updated by MIDI.send()"), so direct bytes() encoding is only valid once a channel has been set explicitly or via send(). Decoding mirrors encoding: each class's from_bytes recovers the channel with msg_bytes[0] & CHANNELMASK, so a bytes() to from_bytes round trip preserves channel and data values.
MIDIBadEvent is created only by the parse path, when a matched class's from_bytes raises ValueError or TypeError (typically a status byte appearing where a data byte is expected), or when the subsequent channel_filter call raises ValueError because channel_in is neither an int nor a tuple. It stores the raw bytes in .data and repr(exception) in .exception_text; its channel stays None. It is deliberately not registered as a message type, so it never matches a status byte itself.
Note numbers via note_parser
note_parser returns an int unchanged and parses str input:
- The first character is uppercased and must be A-G, indexing
NOTE_OFFSET = [21, 23, 12, 14, 16, 17, 19](semitones for A, B, C, D, E, F, G). "C4" gives 60, "C#4" gives 61, "A4" gives 69. - The second character may be
#(+1 semitone) orb(-1); the octave text after the accidental is handed toint(), so "C-1" gives 0 while trailing junk like "C4x" surfacesint()'s ownValueError. - Fewer than 2 characters raises
ValueError("Bad note format"); a first letter outside A-G raisesValueError("Bad note"). - Only
strandintare handled; any other type leaves the result variable unassigned and fails, so the docstring phrase "not a string ... will simply be returned" must not be read to cover floats. - There is no 0-127 range check here; an out-of-range result (e.g. "A9" gives 129) fails later at message construction with
ValueError("Out of range").
How encoding connects to the parse registry
Importing a message module calls register_message_type(), inserting the class into a registry keyed by (status, mask), ordered most-specific mask first. from_message_bytes(midibytes, channel_in) then: skips non-status preamble bytes (counted in skipped), matches the first MSB-set byte against registered statuses, and treats a message as complete only when at least LENGTH bytes exist (variable-length messages instead scan for their ENDSTATUS; a partial known message leaves bytes buffered for the next read). On a complete match it calls from_bytes, then applies channel_filter(msg.channel, channel_in) - true for exact int equality or membership in a tuple. The channel_filter call sits inside the same except (ValueError, TypeError) handler that wraps from_bytes, so a bad channel_spec type (including None) does not propagate: its ValueError is caught, and from_message_bytes returns a MIDIBadEvent carrying the matched bytes in .data and the repr text in .exception_text rather than raising. A propagating ValueError for a non-int/non-tuple spec is observable only from a direct channel_filter call. Messages on other channels are skipped and parsing continues. An unmatched status yields MIDIUnknownEvent; a complete message whose data is invalid - or whose channel_in spec has an unsupported type - yields MIDIBadEvent.
Test-sensitive specifics
LENGTHcounts the status byte; a fixed-length message shorter thanLENGTHis "partial", not an error.- Pitch bend is two 7-bit chunks, LSB first; 16383 encodes as
bytes([0xE0 | ch, 0x7F, 0x7F]). - Error strings are exact: "Out of range", "Channel must be 0-15 or None", "Bad note format", "Bad note".
str()/repr()renderClassName(slot=value, ...)from each class's_message_slots, e.g.ControlChange(control=7, value=100, channel=0).MIDIBadEventis the quirk: its_message_slotsare["msg_bytes", "exception"]while its actual attributes are.dataand.exception_text, so thegetattrfallback yieldsNonefor both and everyMIDIBadEventrenders asMIDIBadEvent(msg_bytes=None, exception=None)regardless of the stored bytes or exception.bytes()output is a plain immutablebytesobject of exactlyLENGTHbytes for these fixed-length messages.
Exact API Reference
adafruit_midi.channel_pressure.ChannelPressure
- Import Path:
from adafruit_midi.channel_pressure import ChannelPressure - Required Test Import Paths:
- adafruit_midi.channel_pressure.ChannelPressure
- Exact Test Import Statements:
- from adafruit_midi.channel_pressure import ChannelPressure
- Kind: class
- Signature:
class ChannelPressure(MIDIMessage):
LENGTH: int
def __init__(self, pressure, *, channel=None)
@classmethod
def from_bytes(cls, msg_bytes)
pressure: Any
CHANNELMASK: int
ENDSTATUS: Any
@property
def channel(self) -> Optional[int]
@classmethod
def register_message_type(cls) -> None
@classmethod
def from_message_bytes(cls, midibytes: bytearray, channel_in: Optional[Union[int, Tuple[int, ...]]]) -> Tuple[Optional['MIDIMessage'], int, int]
def __str__(self) -> str
__repr__: Any
- Behavior: Channel Pressure MIDI message.
adafruit_midi.control_change.ControlChange
- Import Path:
from adafruit_midi.control_change import ControlChange - Required Test Import Paths:
- adafruit_midi.control_change.ControlChange
- Exact Test Import Statements:
- from adafruit_midi.control_change import ControlChange
- Kind: class
- Signature:
class ControlChange(MIDIMessage):
LENGTH: int
def __init__(self, control, value, *, channel=None)
@classmethod
def from_bytes(cls, msg_bytes)
control: Any
value: Any
CHANNELMASK: int
ENDSTATUS: Any
@property
def channel(self) -> Optional[int]
@classmethod
def register_message_type(cls) -> None
@classmethod
def from_message_bytes(cls, midibytes: bytearray, channel_in: Optional[Union[int, Tuple[int, ...]]]) -> Tuple[Optional['MIDIMessage'], int, int]
def __str__(self) -> str
__repr__: Any
- Behavior: Control Change MIDI message.
adafruit_midi.midi_message.channel_filter
- Import Path:
from adafruit_midi.midi_message import channel_filter - Signature:
def channel_filter(channel: int, channel_spec: Optional[Union[int, Tuple[int, ...]]]) -> bool
- Behavior: Utility function to return True iff the given channel matches channel_spec.
adafruit_midi.midi_message.note_parser
- Import Path:
from adafruit_midi.midi_message import note_parser - Required Test Import Paths:
- adafruit_midi.midi_message.note_parser
- Exact Test Import Statements:
- from adafruit_midi.midi_message import note_parser
- Kind: function
- Signature:
def note_parser(note: Union[int, str]) -> int
- Raises (implementation must reproduce these exact messages):
Bad note formatBad note
- Behavior: If note is a string then it will be parsed and converted to a MIDI note (key) number, e.g.
adafruit_midi.midi_message.MIDIBadEvent
- Import Path:
from adafruit_midi.midi_message import MIDIBadEvent - Required Test Import Paths:
- adafruit_midi.midi_message.MIDIBadEvent
- Exact Test Import Statements:
- import adafruit_midi
- Kind: class
- Signature:
class MIDIBadEvent(MIDIMessage):
LENGTH: Any
def __init__(self, msg_bytes: bytearray, exception: Exception)
data: Any
exception_text: Any
CHANNELMASK: int
ENDSTATUS: Any
@property
def channel(self) -> Optional[int]
@classmethod
def register_message_type(cls) -> None
@classmethod
def from_message_bytes(cls, midibytes: bytearray, channel_in: Optional[Union[int, Tuple[int, ...]]]) -> Tuple[Optional['MIDIMessage'], int, int]
@classmethod
def from_bytes(cls, msg_bytes: bytes) -> 'MIDIMessage'
def __str__(self) -> str
__repr__: Any
- Behavior: A bad MIDI message, one that could not be parsed/constructed.
adafruit_midi.pitch_bend.PitchBend
- Import Path:
from adafruit_midi.pitch_bend import PitchBend - Required Test Import Paths:
- adafruit_midi.pitch_bend.PitchBend
- Exact Test Import Statements:
- from adafruit_midi.pitch_bend import PitchBend
- Kind: class
- Signature:
class PitchBend(MIDIMessage):
LENGTH: int
def __init__(self, pitch_bend, *, channel=None)
@classmethod
def from_bytes(cls, msg_bytes)
pitch_bend: Any
CHANNELMASK: int
ENDSTATUS: Any
@property
def channel(self) -> Optional[int]
@classmethod
def register_message_type(cls) -> None
@classmethod
def from_message_bytes(cls, midibytes: bytearray, channel_in: Optional[Union[int, Tuple[int, ...]]]) -> Tuple[Optional['MIDIMessage'], int, int]
def __str__(self) -> str
__repr__: Any
- Behavior: Pitch Bend Change MIDI message.
Capability: MIDI byte stream parsing and decoding
MIDIMessage.from_message_bytes is the decode half of the library: it turns a raw MIDI byte stream - bytes from a UART, usb_midi.ports endpoint, or BLE MIDI byte-stream characteristic - into typed message objects, and MIDI.read() uses it internally on its accumulated input buffer. Two sentinel classes express recoverable decode failures: MIDIUnknownEvent for status bytes no registered message class claims, and MIDIBadEvent for messages that were recognized but could not be constructed.
Recognition depends on imports
Matching is driven by one shared class-level table, MIDIMessage._statusandmask_to_class, whose entries are ((status, mask), class) pairs. Each concrete message module calls register_message_type() at import time; entries are inserted so more specific masks (larger _STATUSMASK, e.g. 0xFF for system common/realtime messages) precede looser ones (0xF0 for channel voice messages). Lookup masks the incoming status byte with each entry's mask and takes the first class whose _STATUS equals the result, so registration order across modules does not matter - but a status byte is decodable only if the module implementing it has actually been imported. Undefined or unimported statuses fall through the whole table into the unknown-event path. The table is shared by all subclasses, so the classmethod can be invoked on MIDIMessage itself.
Walking the buffer
from_message_bytes(midibytes, channel_in) returns (msg, endplusone, skipped) and never mutates the input; the caller trims with midibytes[endplusone:]. Each call:
- Steps over leading data bytes (MSB clear). Data bytes skipped before the first status byte - the preamble - are counted in
skipped; preamble state resets on every call. - Matches the status byte against the registry and checks completeness. Fixed-length messages (
LENGTH >= 0, status byte included) are complete when at leastLENGTHbytes remain from their status byte to the end of the buffer (len(buf) - start >= LENGTH); bytes before the status byte - preamble or bytes left from previously consumed messages - do not count toward completeness, while trailing extra bytes past the message do not block parsing. Variable-length messages (LENGTH == -1) scan forward for the class'sENDSTATUS; encountering any other status byte first is a bad termination. - Builds a complete known message by calling its
from_byteson the message slice. Channel filtering is conditional: it runs only when the parsed message'schannelis notNone, viachannel_filter(msg.channel, channel_in). Channel-less messages (the system common/realtime classes, and the two fallback events) skipchannel_filterentirely and pass regardless ofchannel_in; an invalidchannel_inspec is never evaluated for them.
Return cases:
- Complete message that passes channel filtering:
(msg, index past its last byte, skipped). Filtering applies only to messages with a channel; complete messages addressed elsewhere are consumed silently and the scan continues within the same call, so a multi-message buffer yields the first message matchingchannel_in(or the first channel-less message, which always passes). When every complete message is addressed elsewhere, the scan consumes the whole buffer and returns(None, len(midibytes), skipped)- the same tuple shape as the empty/preamble-only case, but reached after consuming messages. - Known fixed-length message still incomplete:
(None, 0, skipped)- nothing is consumed; wait for more bytes. - Variable-length message with no terminator in the buffer:
(None, len(midibytes), skipped)- the partial message is discarded. This is why the module docstring warns that largeSystemExclusivemessages must fit withinMIDI's input buffer. - Variable-length message ended by a foreign status byte: also incomplete; the bytes through the foreign status are consumed and dropped, returning
None. - Unknown status:
(MIDIUnknownEvent(status), status_index + 1, skipped)- exactly one byte is consumed. Its data bytes remain, and on the next call they are skipped as preamble and counted in that call'sskipped. - Empty or preamble-only buffer:
(None, len(midibytes), skipped).
channel_in follows the channel_filter convention: an int or a tuple of ints. channel_filter raises ValueError for any other spec value (including None); because the channel check sits inside the parser's try block, that failure is converted into a MIDIBadEvent rather than propagating - but only for messages with a channel, since channel_filter is never called for channel-less messages.
The two fallback events
MIDIUnknownEvent(status) keeps the raw status byte exactly as received, channel bits included; it does no channel extraction, so its channel property is None and it is returned regardless of channel_in. It is deliberately not registered (it carries LENGTH = -1 but never enters the table) and exists only as the parser's fallback. str()/repr() render MIDIUnknownEvent(status=245).
MIDIBadEvent(msg_bytes, exception) is created when from_bytes raises ValueError or TypeError - most often because a status byte appears where a data byte is expected and the message constructor rejects it with ValueError('Out of range'). It stores data (the complete failed message as bytes) and exception_text (the repr() of the exception). Its channel is None, so it bypasses channel filtering and is always returned. Non-obvious quirk: its _message_slots list names msg_bytes and exception, but the stored attributes are data and exception_text, so str()/repr() print MIDIBadEvent(msg_bytes=None, exception=None) - tests must inspect the attributes, not the string form.
Test-sensitive details
skippedcounts only pre-first-status bytes per call; leftovers after an unknown event are re-counted on the next call, and because an incomplete fixed-length message returnsendplusone == 0, the same preamble is re-counted on every retry.- Only the first registry match wins; there is no fallback to later entries.
- The parser never raises on malformed stream content; every failure surfaces as one of the two event objects (or a
Nonewait-for-more result).
Exact API Reference
adafruit_midi.midi_message.MIDIUnknownEvent
- Import Path:
from adafruit_midi.midi_message import MIDIUnknownEvent - Required Test Import Paths:
- adafruit_midi.midi_message.MIDIUnknownEvent
- Exact Test Import Statements:
- import adafruit_midi
- Kind: class
- Signature:
class MIDIUnknownEvent(MIDIMessage):
LENGTH: Any
def __init__(self, status: int)
status: Any
CHANNELMASK: int
ENDSTATUS: Any
@property
def channel(self) -> Optional[int]
@classmethod
def register_message_type(cls) -> None
@classmethod
def from_message_bytes(cls, midibytes: bytearray, channel_in: Optional[Union[int, Tuple[int, ...]]]) -> Tuple[Optional['MIDIMessage'], int, int]
@classmethod
def from_bytes(cls, msg_bytes: bytes) -> 'MIDIMessage'
def __str__(self) -> str
__repr__: Any
- Behavior: An unknown MIDI message.
Capability: Incoming message channel filtering
Purpose
A shared MIDI input carries every voice message on the wire, including notes meant for other channels when several sound sources share one bus. Incoming channel filtering is the receive-side gate: every complete channel voice message decoded from the input stream is matched against the configured input-channel specification (in_channel), and messages whose channel is outside the spec are constructed and then discarded, never returned to the caller. System-level messages carry no channel and are exempt. The mechanism is not invoked directly in normal use — MIDI.receive() hands self._in_channel to MIDIMessage.from_message_bytes(), which constructs each candidate message and then applies the channel_filter() predicate to its parsed channel during parsing.
The predicate
channel_filter(channel, channel_in) is deterministic and side-effect free, and it is defined only for the two documented spec shapes:
channel_inanint→ matches whenchannel == channel_in.channel_ina tuple → matches whenchannel in channel_in.- Any other spec value — including
None— makeschannel_filterraiseValueError. There is no accept-all spec: only anintor a tuple filters as described.
channel here is the 0–15 value implied by the incoming status byte's low nibble (status & CHANNEL_MASK, i.e. status & 0x0F). Matching is plain equality/membership, so channel 0 is a real, matchable value and is never treated as falsy. Conversely, a spec value outside 0–15 (say 16) can never equal a status nibble: such a spec filters out all voice traffic while system messages still pass.
What happens when the spec is invalid: inside from_message_bytes the channel_filter call sits in the same try block as message construction, and its ValueError is caught by the same except (ValueError, TypeError) handler. A channel-voice message parsed under such a spec therefore does not come back as its real class — it is returned as a MIDIBadEvent. System messages, whose channel is None, still pass because the predicate is never called for them.
Where and when it is applied
from_message_bytes(midibytes, channel_in) walks the buffer from its start:
- A first byte of
0xF0is SysEx; it is parsed as variable-length SysEx and never channel-filtered. - Otherwise the byte must have its high bit set to be a status byte; it is looked up in the registry that each message module populated at import time via
register_message_type(). - The message class's
from_bytes()runs first and constructs the message; only then ischannel_filterevaluated on the constructed object's parsedchannel. A channel-rejected message is therefore constructed but discarded, and parsing continues with the following bytes. Filtering is only decided after successful construction: iffrom_bytes()raises, the span becomes aMIDIBadEvent(with no channel) that is returned regardless ofin_channel. - The "Channel must be 0-15 or None" setter validation is never triggered by incoming wire data, because a status nibble is always 0–15; that error belongs to constructing/sending messages, not to receiving them.
- System common/realtime statuses (Timing Clock, Active Sensing, Start, Stop, Continue, MIDI Reset, MTC Quarter Frame, SysEx) bypass the test entirely: their
channelisNone, so the predicate is never invoked, and they are returned withchannel is Noneregardless ofin_channel.
A rejected message is skipped as a whole status+data span: its data bytes are consumed together, so they cannot be mistaken for the start of the next message. Each call returns at most one message — the first complete, channel-matching one — with its channel property set from the status nibble, so callers can still tell which of the allowed channels produced it. Further matches, in wire order, require repeated calls, each resuming after the previously returned end index.
Integration with MIDI.receive
MIDI(..., in_channel=0, ...)defaults to channel 0 only. A keyboard transmitting on channel 1 looks completely silent untilin_channelis changed — the most common "receive() returns None" surprise.- The spec may be an
intor a tuple of ints to listen on several channels at once; tuple semantics are membership only (no ordering, duplicates harmless). No other spec value filters (see above). - Filtering is orthogonal to blocking: with
blocking=Trueor a timeout,receive()keeps reading until a matching message arrives or the wait expires. Bytes of filtered messages are consumed while waiting; they do not queue up for later. from_message_bytesreports "nothing found" through its return triple rather than by raising. The triple is(message, endplusone, skipped):endplusoneis the index just past the returned message — the resync point for the next call — andskippedcounts only the leading data bytes before the buffer's first status byte. An empty buffer gives(None, 0, 0); a buffer holding no matching message returnsNonewith the index to resume from, letting a caller driving its own buffer resynchronize exactly.
Test-sensitive edge cases
- Filtered ≠ unknown: a voice message on a disallowed channel is constructed, rejected, and consumed as one well-formed span; stray leading data bytes show up in
skipped, and bytes that are not recognized statuses are handled separately by the parse loop. Tests distinguish these via the returned message object and the(endplusone, skipped)pair. - Filtering is decided only after successful construction, not from the status byte alone: malformed data bytes that make
from_bytes()raise produce aMIDIBadEventthat is returned regardless ofin_channel— the channel test never runs for it. - Note On with velocity 0 is still Note On on its channel; no NoteOff conversion happens at the filter layer.
channel_filterwithchannel=None(e.g. probing a system message) returnsFalsefor both int and tuple specs — but in the normal parse path system messages never reach the predicate because theirchannelisNone.
Exact API Reference
adafruit_midi.midi_message.MIDIMessage
- Import Path:
from adafruit_midi.midi_message import MIDIMessage - Required Test Import Paths:
- adafruit_midi.MIDIMessage
- Exact Test Import Statements:
- import adafruit_midi
- Kind: class
- Signature:
class MIDIMessage:
LENGTH: Optional[int]
CHANNELMASK: int
ENDSTATUS: Any
def __init__(self, *, channel: Optional[int]=None) -> None
@property
def channel(self) -> Optional[int]
@channel.setter
def channel(self, channel: int) -> None
@classmethod
def register_message_type(cls) -> None
@classmethod
def from_message_bytes(cls, midibytes: bytearray, channel_in: Optional[Union[int, Tuple[int, ...]]]) -> Tuple[Optional['MIDIMessage'], int, int]
@classmethod
def from_bytes(cls, msg_bytes: bytes) -> 'MIDIMessage'
def __str__(self) -> str
__repr__: Any
- Raises (implementation must reproduce these exact messages):
Out of rangeChannel must be 0-15 or None
- Behavior: The parent class for MIDI messages.
Capability: Channel voice message construction
Channel voice message construction
Within this capability's verified scope — NoteOn and NoteOff — a channel voice message is one small class whose instances are mutable value objects: a status number (_STATUS), a fixed LENGTH of 3 bytes including the status byte, and three attributes held in _message_slots (note, velocity, channel) — two data values plus the channel. Constructing a message validates its fields immediately and stores parsed integers; encoding happens later via bytes(obj). The classes exist so the same message can be created by hand (NoteOn(60)) or reconstructed from a byte stream (NoteOn.from_bytes(...) via the parser) and then behave identically when re-encoded or printed.
The 3-byte length, the two data slots, and the constructor defaults below are verified only for NoteOn and NoteOff. Other channel voice families in the library (control change, pitch bend, channel pressure) are outside this capability's evidence: do not assume they share this length, slot layout, argument defaults, or value ranges, and do not generalize "the same shape" to them.
Construction and defaults
NoteOn(note, velocity=127, *, channel=None)-noteaccepts an int 0-127 or a note-name string, which is converted bynote_parserat construction time (soNoteOn("C4")storesnote=60). Velocity defaults to 127 (a full strike).NoteOff(note, velocity=0, *, channel=None)- same note handling, but velocity defaults to 0 (release velocity is usually ignored).channelis keyword-only in both constructors.Nonemeans "no channel assigned yet"; a real channel is 0-15. Validating an out-of-range channel raisesValueError("Channel must be 0-15 or None").
Validation order inside both constructors is test-relevant: (1) note_parser runs first, so a malformed note string raises before anything else; (2) the base-class constructor validates the channel; (3) only then are note/velocity range-checked, raising ValueError("Out of range") if either is outside 0-127. A message with both a bad channel and a bad velocity reports the channel error.
Note-name parsing
note_parser converts strings like "C4" (60), "C#4" (61), "Db4" (61), "A4" (69). The letter must be A-G (case-insensitive), optionally followed by # or b, then an octave number (negative octaves work, so "C-1" is 0). Failure modes: fewer than two characters raises ValueError("Bad note format"); a letter outside A-G raises ValueError("Bad note"); a non-numeric octave raises the int() conversion error. Ints pass through unchanged - including out-of-range ints, which are caught afterwards by the constructor's range check, not by the parser.
Channel handling and encodability
Within these two classes, channel is written exactly once - by the constructor. Nothing in NoteOn/NoteOff (neither __bytes__ nor from_bytes) assigns, stores back, or resets it afterwards, and these classes define no send-time channel behavior: whether MIDI.send() fills in, persists, or clears a channel belongs to the transport layer, not to the message classes, and this capability makes no claim about it. What the message classes themselves guarantee:
__bytes__appliesself.channel & CHANNELMASK(0x0F), so a message whose channel is stillNoneis not encodable:bytes(obj)raisesTypeError. It becomes encodable only once a channel has been set explicitly at construction.from_bytesand the byte-stream parser always produce a concrete channel 0-15 (masked from the leading byte with& 0x0F), neverNone.- If a message must be routed to a specific channel regardless of the port's configuration, pass an explicit
channelat construction; the class stores it unchanged and encoding uses it as given.
Encoding
__bytes__ emits [status | channel, data...]: 0x90 for NoteOn and 0x80 for NoteOff, plus the low nibble of the channel, then note and velocity. LENGTH = 3 includes the status byte, which is what the parser uses to decide whether enough bytes remain. The objects keep whatever integers were stored at construction; assigning msg.note = "C4" afterwards bypasses note_parser, and a later bytes() call then fails on the stray string - note and velocity are plain slot attributes, not properties with setters.
Interaction with parsing and round-trips
Each voice-message module registers itself at import time, so from_message_bytes only recognizes message types whose modules were imported. For a matched status byte (byte & 0xF0 == 0x90 etc.) with fewer than LENGTH bytes available, the parser leaves the bytes in the buffer and waits for more; a complete message is handed to from_bytes, which calls the constructor with the wire values - so a data byte with the high bit set (e.g. 0xFF in the velocity slot) triggers the constructor's ValueError("Out of range"), which the parser converts into a MIDIBadEvent rather than propagating. Channel filtering happens on the reconstructed object: NoteOn on a channel not in channel_in is skipped (returns None with the byte offset advanced past it).
Round-tripping is stable: bytes(NoteOn.from_bytes(bytes(msg))) == bytes(msg) for valid messages. Note that NoteOn with velocity=0 stays a NoteOn - the library does not normalize it to NoteOff - so encode/parse cycles preserve the class you chose, which matters when code uses isinstance checks or matching by class.
from_bytes preconditions
from_bytes neither checks nor dispatches on the status byte. It masks msg_bytes[0] with CHANNELMASK for the channel and takes msg_bytes[1] and msg_bytes[2] as the data values. Status matching is the parser's job; a caller who hands from_bytes a buffer whose leading byte has the wrong status nibble gets a silently mis-decoded message (wrong channel and/or wrong data), not an exception. Only call from_bytes when you already hold exactly one complete message of this class starting at its correct status byte; for incoming traffic of unknown type, use the parser.
String forms
str()/repr() use the class name plus the slot values in _message_slots order, e.g. NoteOn(note=60, velocity=127, channel=None). channel=None appears verbatim for channel-less messages. These exact strings are asserted in tests.
Exact API Reference
adafruit_midi.note_off.NoteOff
- Import Path:
from adafruit_midi.note_off import NoteOff - Required Test Import Paths:
- adafruit_midi.note_off.NoteOff
- Exact Test Import Statements:
- from adafruit_midi.note_off import NoteOff
- Kind: class
- Signature:
class NoteOff(MIDIMessage):
LENGTH: int
def __init__(self, note, velocity=0, *, channel=None)
@classmethod
def from_bytes(cls, msg_bytes)
note: Any
velocity: Any
CHANNELMASK: int
ENDSTATUS: Any
@property
def channel(self) -> Optional[int]
@classmethod
def register_message_type(cls) -> None
@classmethod
def from_message_bytes(cls, midibytes: bytearray, channel_in: Optional[Union[int, Tuple[int, ...]]]) -> Tuple[Optional['MIDIMessage'], int, int]
def __str__(self) -> str
__repr__: Any
- Behavior: Note Off Change MIDI message.
adafruit_midi.note_on.NoteOn
- Import Path:
from adafruit_midi.note_on import NoteOn - Required Test Import Paths:
- adafruit_midi.note_on.NoteOn
- Exact Test Import Statements:
- from adafruit_midi.note_on import NoteOn
- Kind: class
- Signature:
class NoteOn(MIDIMessage):
LENGTH: int
def __init__(self, note, velocity=127, *, channel=None)
@classmethod
def from_bytes(cls, msg_bytes)
note: Any
velocity: Any
CHANNELMASK: int
ENDSTATUS: Any
@property
def channel(self) -> Optional[int]
@classmethod
def register_message_type(cls) -> None
@classmethod
def from_message_bytes(cls, midibytes: bytearray, channel_in: Optional[Union[int, Tuple[int, ...]]]) -> Tuple[Optional['MIDIMessage'], int, int]
def __str__(self) -> str
__repr__: Any
- Behavior: Note On Change MIDI message.
Capability: System Exclusive message handling
Purpose and frame shape
SystemExclusive is the library's only variable-length message: a 0xF0 status, a manufacturer ID of one byte (or three when the first is 0x00), any amount of 7-bit data, and an 0xF7 end-of-exclusive terminator. Wire layout is exactly 0xF0 + manufacturer_id + data + 0xF7; attribute order defines byte order, and the encoder appends ENDSTATUS = 0xF7 itself, so never place 0xF7 in data. LENGTH stays -1, the framework sentinel that routes SysEx through the variable-length parsing path instead of a fixed-size slice.
Construction
Both manufacturer_id and data are required with no defaults; each may be a list, bytearray, or bytes and is converted to bytes immediately, so the attributes are always immutable. There is no 0-127 validation - out-of-range values encode verbatim and only bite during parsing (see below). Beware bytes(int): SystemExclusive(3, []) yields manufacturer_id == b'\x00\x00\x00', i.e. an accidental three-byte ID, not the single byte 3. An empty manufacturer_id is accepted and encodes as a zero-length ID (see the degenerate F0 F7 case under Parsing semantics). There is no channel keyword; passing one raises TypeError, and the inherited channel property is None on constructed and parsed instances alike, because the 0xFF status mask leaves no room for a channel nibble.
Registration and import requirements
The module calls register_message_type() at import, inserting (0xF0, 0xFF) - the most specific mask - at the front of the parser registry. The top-level adafruit_midi package imports only midi_message, so you must import adafruit_midi.system_exclusive (as the tests do) or incoming 0xF0 frames fall through to MIDIUnknownEvent. With the import in place, MIDI.send() writes msg.__bytes__() to the output port and stamps msg.channel (from out_channel or the per-call argument) as a side effect, though the stamped value never appears in the encoded bytes; MIDI.receive() returns a SystemExclusive regardless of in_channel, since msg.channel being None bypasses channel filtering.
Parsing semantics
from_message_bytes matches the 0xF0 status, then scans forward for the next byte with the MSB set - any status byte ends the frame, not just 0xF7:
- Good termination (
0xF7):from_bytessplits the frame. If byte 1 is nonzero it is a one-byte ID (msg_bytes[1:2]) with datamsg_bytes[2:-1]; if it is0x00a three-byte ID (msg_bytes[1:4]) is consumed with datamsg_bytes[4:-1]. The final byte is assumed to be the terminator and excluded in both branches;from_bytesnever verifies it is actually0xF7. Returns(msg, endidx_through_F7, 0), and the round trip is byte-exact for well-formed frames carrying a non-empty manufacturer_id, including empty data. - Degenerate frame
F0 F7(no ID byte): byte 1 is the terminator itself, which is nonzero, sofrom_bytestakes the one-byte branch and yieldsmanufacturer_id == b'\xf7',data == b''. Consequently a SysEx built with an emptymanufacturer_idencodes tob'\xf0\xf7', re-parses as the one-byte IDb'\xf7', and re-encodes asb'\xf0\xf7\xf7'- an empty manufacturer_id never round-trips. - Bad termination (any other status byte): the message is discarded, the buffer is consumed through the offending status, and
receive()returnsNone.test_SystemExclusive_NoteOn_premalterminatedsysexpins this:F0 42 01 02 03 04 F0 90 30 32yields(None, 7, 0), and the trailing NoteOn parses on the next call from the remaining bytes. - No status byte found (unterminated): returns
(None, len(buf), 0), soreceive()empties the buffer. Unlike fixed-length messages, which are retained while incomplete, a partially received SysEx is dropped - matching the documented limitation that SysEx "can only be parsed if it fits within the input buffer" (defaultin_buf_size=30; a 30-byte frame parses exactly, a 43-byte one is garbled into a stray0xF7). - Stray
0xF7with no0xF0start: becomesMIDIUnknownEvent(status=0xF7)withendplusonejust past the terminator andskippedcounting the preceding data bytes (test_NoteOn_prepartialsysexexpects(MIDIUnknownEvent, 5, 4)for01 02 03 04 F7 90 30 32).
Consequences: a data byte >= 0x80 acts as a (bad) terminator, so non-7-bit payloads encode but never survive parsing; a 0xF7 inside data splits the message at that point (F0 7D 01 F7 02 F7 parses as data b'\x01', leaving 02 F7 behind); a frame with no ID byte mis-parses as F0 F7 above. A truncated three-byte ID is misread: F0 00 F7 parses to manufacturer_id == b'\x00\xf7', data == b''.
Text forms
__str__/__repr__ render the declared slots as wire values, e.g. SystemExclusive(manufacturer_id=b'}', data=b'@\x00') - not a channel or note-style summary.
Exact API Reference
adafruit_midi.system_exclusive.SystemExclusive
- Import Path:
from adafruit_midi.system_exclusive import SystemExclusive - Required Test Import Paths:
- adafruit_midi.system_exclusive.SystemExclusive
- Exact Test Import Statements:
- from adafruit_midi.system_exclusive import SystemExclusive
- Kind: class
- Signature:
class SystemExclusive(MIDIMessage):
LENGTH: Any
ENDSTATUS: int
def __init__(self, manufacturer_id, data)
@classmethod
def from_bytes(cls, msg_bytes)
manufacturer_id: Any
data: Any
CHANNELMASK: int
@property
def channel(self) -> Optional[int]
@classmethod
def register_message_type(cls) -> None
@classmethod
def from_message_bytes(cls, midibytes: bytearray, channel_in: Optional[Union[int, Tuple[int, ...]]]) -> Tuple[Optional['MIDIMessage'], int, int]
def __str__(self) -> str
__repr__: Any
- Behavior: System Exclusive MIDI message.
Detailed Implementation Nodes
Node: MIDI port and channel configuration
Functional constraints
- One input port (
read(length)) and/or one output port (write(buffer, length)) required; bothNone→ValueError("No midi_in or midi_out provided"). One-sided instances are valid, but the unused direction is never null-checked:receive()withmidi_in=NoneraisesAttributeErrorfrom theNoneport instead of returningNone, andsend()withmidi_out=NoneraisesAttributeErroronly after stampingmsg.channeland (withdebug=True) printingSending:. - Validation order: ports (
ValueError) →in_channel→out_channel(bothRuntimeError). The constructor routes both channels through the property setters, which re-validate identically on every later assignment. in_channel: int 0-15 kept as an int. Tuple specs are only range-checked per element, with no element type check: non-comparable elements (e.g. a string) raiseTypeErrorat the comparison, comparable out-of-range elements raiseRuntimeError("Invalid input channel"), and comparable in-range elements (floats, bools) are accepted and stored verbatim; the tuple itself is kept verbatim (empty tuple is accepted and matches nothing). Only specs that are none of int/tuple/None/"ALL"(e.g. a bare float or list) fall through toRuntimeError("Invalid input channel");Noneor"ALL"normalizes totuple(range(16)). The getter never returnsNoneafter construction;boolcounts as int.out_channel: int 0-15, default 0; out-of-range →RuntimeError("Invalid output channel"); non-numeric values fail withTypeErrorin the comparison.- Parse-time filter (
channel_filter): int spec = equality, tuple spec = membership, other types →ValueError("Incorrect type for channel_spec..."). Only channel-carrying messages are filtered; system messages (channel is None) always pass. sendusesout_channelunlesschannel=is given; it mutatesmsg.channelas a side effect; wire status byte = base status | channel; a sequence is sent in onewritecall.receivereturnsNonefor empty ports, partial data, or fully filtered-out data; unlistened-channel messages are consumed as skipped bytes. It blocks only as the underlying port blocks.in_buf_size(default 30) must exceed the longest expected message; an oversize SysEx yields repeatedNonethenMIDIUnknownEvent(0xF7)for the EOX byte.- Debug prints are asymmetric:
Receiving:prints only the non-empty byte list returned byread()— raw, pre-parse, pre-filter, showing what the peer sent (including unlistened channels);Sending:prints the exact packet handed towrite().
Example
import usb_midi
import adafruit_midi
from adafruit_midi.note_on import NoteOn
midi = adafruit_midi.MIDI(midi_in=usb_midi.ports[0],
midi_out=usb_midi.ports[1],
in_channel=(0, 1), # listen on MIDI channels 1-2
out_channel=0) # MIDI channel 1
assert midi.in_channel == (0, 1) # getter returns what was set
midi.in_channel = "ALL" # -> tuple(range(16))
midi.out_channel = 15 # wire 15 = MIDI channel 16
note = NoteOn(60, 100)
midi.send(note) # note.channel becomes 15 (0x9F ...)
msg = midi.receive() # None or a filtered message
Node: MIDI message encoding to wire bytes
Functional constraints
bytes(msg)is the wire encoding: status byte first, then data bytes; status =_STATUS | (channel & 0x0F).LENGTHincludes the status byte:ChannelPressure= 2 (0xD0),ControlChange= 3 (0xB0),PitchBend= 3 (0xE0).PitchBendemits its 14-bit value aspitch_bend & 0x7Fthen(pitch_bend >> 7) & 0x7F(LSB first); valid range 0-16383.- Validation order:
channelsetter first (ValueError("Channel must be 0-15 or None"),Noneallowed), then data ranges (ValueError("Out of range")for pressure/control/value outside 0-127, pitch_bend outside 0-16383). Both checks run in__init__, so an invalid message is never constructed. bytes()on a message withchannel is NoneraisesTypeError;MIDI.send()supplies the port's out-channel when the message channel isNone. Encoding never mutates the message and is repeatable.from_bytesreconstructs the channel frommsg_bytes[0] & 0x0F, makingbytes()andfrom_bytesan exact round trip.note_parser: int passes through unchanged; strings parse letter A-G (case-insensitive) viaNOTE_OFFSET = [21, 23, 12, 14, 16, 17, 19], optional#/baccidental, thenint()on the octave text ("C-1" gives 0). Exact errors: "Bad note format" (len < 2), "Bad note" (letter not A-G); no 0-127 range check.channel_filter(channel, spec): exactintequality or tuple membership; other spec types raiseValueError(propagating on a direct call). Insidefrom_message_bytes, however, thechannel_filtercall shares the sameexcept (ValueError, TypeError)handler asfrom_bytes, so a badchannel_spectype, includingNone, is converted into aMIDIBadEventwith.data/.exception_textset instead of propagating. Used byfrom_message_bytesto accept or skip decoded messages.- Registry: importing a message module registers its class by
(status, mask);from_message_bytesmatches the first MSB-set byte, requiresLENGTHbytes for completeness (partials stay buffered), wrapsfrom_bytesfailures - and anychannel_filterValueErrorraised for a badchannel_spectype, includingNone- inMIDIBadEvent(.data= raw bytes,.exception_text=repr(exception), channel unset), and maps unmatched statuses toMIDIUnknownEvent.MIDIBadEventis never registered. str()/repr()use_message_slots, e.g.ControlChange(control=7, value=100, channel=0);MIDIBadEventrendersMIDIBadEvent(msg_bytes=None, exception=None)because its slot names do not match its.data/.exception_textattributes.
Example
from adafruit_midi.control_change import ControlChange
from adafruit_midi.pitch_bend import PitchBend
from adafruit_midi.midi_message import note_parser
cc = ControlChange(7, 100, channel=0)
assert bytes(cc) == bytes([0xB0, 7, 100]) # status, control, value
assert bytes(PitchBend(8192, channel=1)) == bytes([0xE1, 0x00, 0x40]) # LSB first
assert note_parser('C#4') == 61 # 'C4' -> 60
rt = ControlChange.from_bytes(bytes(cc))
assert (rt.control, rt.value, rt.channel) == (7, 100, 0)
try:
PitchBend(16384, channel=0) # 14-bit max is 16383
except ValueError as ex:
assert str(ex) == 'Out of range'
Node: MIDI byte stream parsing and decoding
Functional constraints
MIDIMessage.from_message_bytes(midibytes, channel_in)returns(msg, endplusone, skipped); the input is not mutated, and consumption is expressed byendplusone(caller slicesmidibytes[endplusone:]).- The recognition table is populated only by imported message modules via
register_message_type(); entries are kept most-specific-mask first and the first(status & mask) == _STATUSmatch wins. - Fixed
LENGTHincludes the status byte; a message is complete whenlen(buf) - start >= LENGTH, counting only from its status byte to the end of the buffer (bytes before the status byte do not count). Variable-length (LENGTH == -1) messages need theirENDSTATUSinside the buffer; a different status byte is a bad termination, treated as incomplete with the bytes through it dropped. - Unknown status yields
MIDIUnknownEvent(raw_status)withendplusone = status_index + 1; leftover data bytes are skipped as preamble on the next call and counted in that call'sskipped. from_bytesraisingValueError/TypeErroryieldsMIDIBadEvent(message_bytes, exception)storing.data(bytes) and.exception_text(repr()of the exception);channelstaysNone, so bad events are returned regardless ofchannel_in, andstr()showsMIDIBadEvent(msg_bytes=None, exception=None).- Channel filtering runs only when the parsed message's
channelis notNone; channel-less (system) messages are returned regardless ofchannel_inandchannel_filteris never called for them. Mismatched messages are consumed and the scan continues in the same call; if every complete message mismatches, the whole buffer is consumed and the result is(None, len(buf), skipped).channel_filteraccepts onlyint/tuple specs and raisesValueErrorotherwise - the parser converts that into aMIDIBadEvent, but only for messages with a channel. - Returns
(None, len(buf), skipped)for empty/preamble-only buffers and unterminated variable-length messages;(None, 0, skipped)for incomplete fixed-length messages (wait for more bytes).
Example
import adafruit_midi
import adafruit_midi.note_on # importing registers NoteOn with the parser
from adafruit_midi.midi_message import MIDIMessage, MIDIUnknownEvent
buf = bytearray(b"\x90\x3c\x40\xf5\x01\x90\x3e\x7f")
msg, end, skipped = MIDIMessage.from_message_bytes(buf, (0,))
# NoteOn(note=60, velocity=64, channel=0); end == 3, skipped == 0
rest = buf[end:]
evt, end2, _ = MIDIMessage.from_message_bytes(rest, (0,))
# 0xF5 is unregistered: MIDIUnknownEvent, evt.status == 0xF5, end2 == 1
msg3, end3, skipped3 = MIDIMessage.from_message_bytes(rest[end2:], (0,))
# 0x01 skipped (skipped3 == 1), then NoteOn(note=62, velocity=127), end3 == 4
Node: Incoming message channel filtering
Functional constraints
channel_filter(channel, channel_in) -> boolis stateless: anintspec matches by equality, a tuple spec by membership. The spec type is validated — any other value (includingNone) raisesValueError— though channel values themselves are not checked.- Applied inside
MIDIMessage.from_message_bytes(midibytes, channel_in)to the parsedchannelof an already-constructed message, only when that channel is notNone(i.e. for channel-voice messages). System messages (the0xF0family: SysEx, MTC Quarter Frame, Start, Stop, Continue, Timing Clock, Active Sensing, MIDI Reset) havechannel is None, bypass the predicate, and come back withchannel is Noneregardless ofin_channel. - Ordering: the message class's
from_bytes()runs first; the filter is then applied to the constructed object. A well-formed voice message on a disallowed channel is constructed, discarded, and the parse loop advances past its whole status+data span. The "Channel must be 0-15 or None" setter validation is never triggered by incoming wire data (the status nibble is always 0–15). channel_in=Noneis not an accept-all spec: theValueErrorraised insidechannel_filteris caught byfrom_message_bytes'sexcept (ValueError, TypeError)handler and the voice message surfaces as aMIDIBadEvent(no channel) — only int/tuple specs filter. Likewise, a message whosefrom_bytesraises for any other reason becomes aMIDIBadEventreturned regardless ofchannel_in: filtering is only decided after successful construction.- Channel
0matches normally (equality, not truthiness). Spec values outside 0–15 match nothing: all voice traffic is dropped while system messages still pass. - Result is
(message, endplusone, skipped)whereendplusoneis the index just past the returned message (the resync point) andskippedcounts only the leading data bytes before the buffer's first status byte (filtered-out messages do not increment it). Empty/no input →(None, 0, 0). At most one message is returned per call; parsing continues past filtered messages within the same buffer. MIDI.receive()supplies the constructor'sin_channel(default0) on every parse; blocking/timeout behavior is unchanged — only message visibility changes.
Usage
import adafruit_midi
from adafruit_midi.midi_message import MIDIMessage
from adafruit_midi.note_on import NoteOn
# Buffer holds NoteOn on channel 0, then NoteOn on channel 1.
buf = bytearray([0x90, 60, 64, 0x91, 62, 64])
# in_channel=1: the channel-0 message is constructed, rejected, and
# discarded; the first match returned is the channel-1 NoteOn, with
# endplusone just past it and no skipped leading data bytes.
msg, endplusone, skipped = MIDIMessage.from_message_bytes(buf, 1)
assert isinstance(msg, NoteOn) and msg.channel == 1
assert (endplusone, skipped) == (6, 0)
# A tuple spec listens on several channels at once; the first message
# matches immediately.
msg, endplusone, skipped = MIDIMessage.from_message_bytes(buf, (0, 1))
assert msg.channel == 0 and (endplusone, skipped) == (3, 0)
# One message per call: resuming after the returned endplusone (3)
# finds the channel-1 NoteOn next.
msg, endplusone, skipped = MIDIMessage.from_message_bytes(buf[3:], 1)
assert isinstance(msg, NoteOn) and (endplusone, skipped) == (3, 0)
Node: Channel voice message construction
Functional constraints
NoteOnandNoteOffare fixed-length, 3 bytes including the status byte (LENGTH = 3); wire form isstatus | (channel & 0x0F)followed by thenoteandvelocitydata bytes. The 3-byte figure is verified only for these two classes; other voice-message families in the library are outside this capability's evidence and must not be assumed to share it.NoteOn(note, velocity=127)andNoteOff(note, velocity=0)parse string notes ("C4"-> 60,"C#4"/"Db4"-> 61) once, at construction.- Ranges enforced at construction:
note/velocity0-127 ->ValueError("Out of range"); channel must be 0-15 orNone->ValueError("Channel must be 0-15 or None"). Note parsing and channel validation both happen before the value-range check, so a bad note string or bad channel raises before the range check runs. - A message with
channel=Noneis not encodable viabytes()(None & 0x0FraisesTypeError) until a channel is assigned; assignment happens only through the constructor. The message classes themselves never store a channel back or reset it toNoneafter construction, and they define no send-time channel behavior - any fill-in, persistence, or clearing of the channel at send time is transport-layer behavior and is not claimed here. from_bytesperforms no status-byte validation or dispatch: it masksmsg_bytes[0]withCHANNELMASK(0x0F) for the channel and usesmsg_bytes[1]/msg_bytes[2]as data. It therefore always yields a concrete channel 0-15, but a leading byte with the wrong status nibble is silently decoded instead of raising; guaranteeing the leading byte matches the class's status is the caller's (or the parser's) responsibility. Constructor failures during parsing surface asMIDIBadEvent, not exceptions.- Class identity is preserved on round-trips (
NoteOnwithvelocity=0staysNoteOn);str()/repr()render slot values in_message_slotsorder, e.g.NoteOn(note=60, velocity=127, channel=None). - Parsing only recognizes message classes whose modules have been imported (each module calls
register_message_type()at import time).
Example
import adafruit_midi.note_on # import registers the parser entry
import adafruit_midi.note_off
from adafruit_midi.note_on import NoteOn
from adafruit_midi.note_off import NoteOff
msg = NoteOn("C4", channel=0) # note parsed to 60, velocity 127
bytes(msg) # b'\x90<\x7f'
off = NoteOff("C4", velocity=64, channel=0)
bytes(off) # b'\x80<\x40'
same = NoteOn.from_bytes(bytes(msg)) # channel masked from the leading byte's low nibble
str(same) # 'NoteOn(note=60, velocity=127, channel=0)'
NoteOn(128) # ValueError: Out of range
NoteOn(60, channel=16) # ValueError: Channel must be 0-15 or None
NoteOn("H4") # ValueError: Bad note
Node: System Exclusive message handling
Functional constraints
- Frame:
0xF0+manufacturer_id+data+0xF7;ENDSTATUS = 0xF7is appended once by__bytes__and must not appear indata. manufacturer_idanddataare coerced tobytesat construction; no 0-127 range check, nochannelkwarg (TypeError),channelproperty isNone.- ID width is inferred at parse time: byte after
0xF0nonzero -> one-byte ID;0x00-> three-byte ID (0x00+ two following bytes). - A frame with no ID byte (
F0 F7) falls into the nonzero branch (byte 1 is the terminator) and parses tomanufacturer_id == b'\xf7',data == b'';SystemExclusive([], [])encodes tob'\xf0\xf7', re-parses as IDb'\xf7', and re-encodes asb'\xf0\xf7\xf7', so an empty manufacturer_id does not round-trip. from_bytesunconditionally excludes the final byte as the terminator without checking it is0xF7.- Parsing ends at the first MSB-set byte after
0xF0:0xF7is a good termination; any other status byte is a bad termination that discards the message and consumes the buffer through that byte ((None, endidx+1, 0)). - An unterminated
0xF0 ...tail returns(None, len(buf), 0), soreceive()drops it; fixed-length partial messages are kept, variable-length ones are not. The whole frame must fit the input buffer (default 30 bytes). - A stray
0xF7without a preceding0xF0yieldsMIDIUnknownEvent(status=0xF7); preceding data bytes count towardskipped. - Well-formed 7-bit frames carrying a non-empty manufacturer_id round-trip byte-exactly, including empty
data; an emptymanufacturer_iddoes not round-trip (see theF0 F7case), and payloads containing0xF7or any >= 0x80 byte truncate at that byte on parse. - Channel filtering in
receive()never applies (channelNonepasses everyin_channel);send()stamps.channelbut encoding ignores it. - Registration happens at module import;
import adafruit_midi.system_exclusiveis required or0xF0decodes asMIDIUnknownEvent. str/reprshowSystemExclusive(manufacturer_id=..., data=...); class constantsLENGTH == -1andENDSTATUS == 0xF7are stable contract points.
Example
from adafruit_midi.system_exclusive import SystemExclusive
sysex = SystemExclusive([0x7D], [0x40, 0x00]) # single-byte manufacturer id
bytes(sysex) # b'\xf0\x7d\x40\x00\xf7' - 0xF7 appended automatically
wide = SystemExclusive([0x00, 0x20, 0x29], [0x01]) # three-byte id (starts 0x00)
bytes(wide) # b'\xf0\x00\x29\x01\xf7'
msg, end, skipped = SystemExclusive.from_message_bytes(
bytearray(b"\xf0\x42\x01\x02\x03\x04\xf7\x90"), None)
msg.manufacturer_id # b'\x42' - nonzero first id byte
msg.data # b'\x01\x02\x03\x04'
end # 7 - consumed through the 0xF7 terminator