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
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
# 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:

1. **Do NOT create or modify any files under the test directories** (e.g.
   `tests/`, `test/`, `testing/`, or files named `test_*.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.

2. **Your package MUST be importable by the name the tests use.** The hidden
   tests `import` your package by its documented top-level name (see the
   Project Directory Structure and API Usage Guide below). Provide a valid
   `pyproject.toml` / `setup.py` / `setup.cfg` and lay out your modules so that
   `pip install -e .` succeeds and the package imports cleanly. If your package
   is not installable/importable, every test errors out and the reward is 0.

3. **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/repo` at 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**:
  ```bash
  python3 -I -c 'import base64; from pathlib import Path; Path('"'"'/tmp/programgen-pip-compat-v1.py'"'"').write_bytes(base64.b64decode('"'"'aW1wb3J0IG9zCmZyb20gcGF0aGxpYiBpbXBvcnQgUGF0aAppbXBvcnQgc3VicHJvY2VzcwppbXBvcnQgc3lzCmltcG9ydCB0ZW1wZmlsZQoKZGVmIGNvbnN0cmFpbmVkX2J1aWxkX2luc3RhbGwoY29tbWFuZCwgcnVuKToKICAgIGNvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCgnUFJPR1JBTUdFTl9CVUlMRF9DT05TVFJBSU5UJykKICAgIGlmIG5vdCBjb25zdHJhaW50IG9yICctLW5vLWJ1aWxkLWlzb2xhdGlvbicgaW4gY29tbWFuZDoKICAgICAgICByZXR1cm4gTm9uZQogICAgaWYgc3lzLnZlcnNpb25faW5mb1s6Ml0gPCAoMywgOSk6CiAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSBpc29sYXRlZCBidWlsZCBjb25zdHJhaW50cyByZXF1aXJlIFB5dGhvbiA+PTMuOScsIGZsdXNoPVRydWUpCiAgICAgICAgcmV0dXJuIDEKICAgICMgQSBkZWRpY2F0ZWQgaW5zdGFsbGVyIGNvbnRyb2xzIFBFUCA1MTcgYnVpbGQgZGVwZW5kZW5jaWVzIG9ubHkuIEl0IGRvZXMKICAgICMgbm90IHVwZ3JhZGUgcGlwL3NldHVwdG9vbHMgaW4gdGhlIG1lYXN1cmVkIHByb2plY3QncyBydW50aW1lIGVudmlyb25tZW50LgogICAgd2l0a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GxlZ2FjeSBkaXN0cmlidXRpb24gbWV0YWRhdGE6IHJldHJ5aW5nIHRoZSB1bmNoYW5nZWQgcmVxdWlyZW1lbnRzIHdpdGggcGlwPDI0LjEnLCBmbHVzaD1UcnVlKQogICAgY2hhbmdlZCA9IHJ1bihbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICdwaXA8MjQuMSddKQogICAgaWYgY2hhbmdlZC5yZXR1cm5jb2RlOgogICAgICAgIHJldHVybiBjaGFuZ2VkLnJldHVybmNvZGUKICAgIHJldHVybiBydW4oY29tbWFuZCkucmV0dXJuY29kZQoKaWYgX19uYW1lX18gPT0gJ19fbWFpbl9fJzoKICAgIHJhaXNlIFN5c3RlbUV4aXQoaW5zdGFsbChzeXMuYXJndlsxOl0pKQo='"'"'))'
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**:
  ```bash
  {
    [ -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; default `0` (MIDI channel 1).
- `in_channel` accepts:
  - 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 raises `TypeError` from the comparison (e.g. `in_channel=(1, "x")`), a comparable out-of-range element (e.g. `20`) raises `RuntimeError("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 to `tuple(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 to `RuntimeError("Invalid input channel")`.

Test-sensitive consequences:

- After construction the `in_channel` getter **never returns `None`**; 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. `bool` is an `int` subclass, so `in_channel=True` is 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 raises `ValueError("Incorrect type for channel_spec...")` — unreachable via the property setter but reachable if `from_message_bytes` is called directly with a hand-made filter.

## How the settings are consumed

- `receive()` calls `MIDIMessage.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 expose `channel=None`. Messages on unlistened channels are parsed, discarded, and counted as skipped bytes — never returned. `receive()` returns `None` both 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-`None` result. It preserves the port's blocking character: a UART input blocks inside `read`, `usb_midi.ports[0]` is effectively non-blocking.
- `send(msg)` (or a list/tuple of messages): when `channel` is omitted, `out_channel` is used; an explicit `channel=n` overrides it for that call only. Either way the channel is written into each message object — `msg.channel` is 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=2` sends NoteOn as `0x92 ...`; `send(NoteOn(...), channel=9)` sends `0x99 ...`. A sequence is emitted in a **single** `write(buffer, length)` call. Because the channel is stamped into the object, a later `bytes(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**:

```python
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 provided`
  - `Invalid output channel`
  - `Invalid input channel`
- **Behavior**: MIDI helper class. ``midi_in`` or ``midi_out`` *must* 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 for `ChannelPressure`, 3 for `ControlChange` and `PitchBend`).
- The base `MIDIMessage.__bytes__` returns just `bytes([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 as `bytes([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 & 0x7F` followed by `(pitch_bend >> 7) & 0x7F`. The no-bend midpoint 8192 encodes as `bytes([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:

1. The `channel` property setter raises `ValueError("Channel must be 0-15 or None")` for anything outside 0-15 (`None` is allowed and means "not yet assigned").
2. Data ranges are checked afterwards, raising `ValueError("Out of range")`: `pressure` must be 0-127; both `control` *and* `value` must be 0-127; `pitch_bend` must 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) or `b` (-1); the octave text after the accidental is handed to `int()`, so "C-1" gives 0 while trailing junk like "C4x" surfaces `int()`'s own `ValueError`.
- Fewer than 2 characters raises `ValueError("Bad note format")`; a first letter outside A-G raises `ValueError("Bad note")`.
- Only `str` and `int` are 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

- `LENGTH` counts the status byte; a fixed-length message shorter than `LENGTH` is "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()` render `ClassName(slot=value, ...)` from each class's `_message_slots`, e.g. `ControlChange(control=7, value=100, channel=0)`. `MIDIBadEvent` is the quirk: its `_message_slots` are `["msg_bytes", "exception"]` while its actual attributes are `.data` and `.exception_text`, so the `getattr` fallback yields `None` for both and every `MIDIBadEvent` renders as `MIDIBadEvent(msg_bytes=None, exception=None)` regardless of the stored bytes or exception.
- `bytes()` output is a plain immutable `bytes` object of exactly `LENGTH` bytes 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**:

```python
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**:

```python
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**:

```python
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**:

```python
def note_parser(note: Union[int, str]) -> int
```
- **Raises** (implementation must reproduce these exact messages):
  - `Bad note format`
  - `Bad 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**:

```python
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**:

```python
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:

1. 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.
2. Matches the status byte against the registry and checks completeness. Fixed-length messages (`LENGTH >= 0`, status byte included) are complete when at least `LENGTH` bytes 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's `ENDSTATUS`; encountering any other status byte first is a bad termination.
3. Builds a complete known message by calling its `from_bytes` on the message slice. Channel filtering is conditional: it runs only when the parsed message's `channel` is not `None`, via `channel_filter(msg.channel, channel_in)`. Channel-less messages (the system common/realtime classes, and the two fallback events) skip `channel_filter` entirely and pass regardless of `channel_in`; an invalid `channel_in` spec 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 matching `channel_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 large `SystemExclusive` messages must fit within `MIDI`'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's `skipped`.
- 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

- `skipped` counts 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 returns `endplusone == 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 `None` wait-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**:

```python
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_in` an `int` → matches when `channel == channel_in`.
- `channel_in` a tuple → matches when `channel in channel_in`.
- Any other spec value — including `None` — makes `channel_filter` raise `ValueError`. There is no accept-all spec: only an `int` or 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:

1. A first byte of `0xF0` is SysEx; it is parsed as variable-length SysEx and never channel-filtered.
2. 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()`.
3. The message class's `from_bytes()` runs first and constructs the message; only then is `channel_filter` evaluated on the constructed object's parsed `channel`. A channel-rejected message is therefore constructed but discarded, and parsing continues with the following bytes. Filtering is only decided after successful construction: if `from_bytes()` raises, the span becomes a `MIDIBadEvent` (with no channel) that is returned regardless of `in_channel`.
4. 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.
5. System common/realtime statuses (Timing Clock, Active Sensing, Start, Stop, Continue, MIDI Reset, MTC Quarter Frame, SysEx) bypass the test entirely: their `channel` is `None`, so the predicate is never invoked, and they are returned with `channel is None` regardless of `in_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 until `in_channel` is changed — the most common "receive() returns None" surprise.
- The spec may be an `int` or 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=True` or 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_bytes` reports "nothing found" through its return triple rather than by raising. The triple is `(message, endplusone, skipped)`: `endplusone` is the index just past the returned message — the resync point for the next call — and `skipped` counts 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 returns `None` with 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 a `MIDIBadEvent` that is returned regardless of `in_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_filter` with `channel=None` (e.g. probing a system message) returns `False` for both int and tuple specs — but in the normal parse path system messages never reach the predicate because their `channel` is `None`.

#### 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**:

```python
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 range`
  - `Channel 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)` - `note` accepts an int 0-127 **or** a note-name string, which is converted by `note_parser` at construction time (so `NoteOn("C4")` stores `note=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).
- `channel` is keyword-only in both constructors. `None` means "no channel assigned yet"; a real channel is 0-15. Validating an out-of-range channel raises `ValueError("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__` applies `self.channel & CHANNELMASK` (0x0F), so a message whose channel is still `None` is not encodable: `bytes(obj)` raises `TypeError`. It becomes encodable only once a channel has been set explicitly at construction.
- `from_bytes` and the byte-stream parser always produce a concrete channel 0-15 (masked from the leading byte with `& 0x0F`), never `None`.
- If a message must be routed to a specific channel regardless of the port's configuration, pass an explicit `channel` at 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**:

```python
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**:

```python
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_bytes` splits the frame. If byte 1 is nonzero it is a one-byte ID (`msg_bytes[1:2]`) with data `msg_bytes[2:-1]`; if it is `0x00` a three-byte ID (`msg_bytes[1:4]`) is consumed with data `msg_bytes[4:-1]`. The final byte is assumed to be the terminator and excluded in both branches; `from_bytes` never verifies it is actually `0xF7`. 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, so `from_bytes` takes the one-byte branch and yields `manufacturer_id == b'\xf7'`, `data == b''`. Consequently a SysEx built with an empty `manufacturer_id` encodes to `b'\xf0\xf7'`, re-parses as the one-byte ID `b'\xf7'`, and re-encodes as `b'\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()` returns `None`. `test_SystemExclusive_NoteOn_premalterminatedsysex` pins this: `F0 42 01 02 03 04 F0 90 30 32` yields `(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)`, so `receive()` 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" (default `in_buf_size=30`; a 30-byte frame parses exactly, a 43-byte one is garbled into a stray `0xF7`).
- **Stray `0xF7` with no `0xF0` start**: becomes `MIDIUnknownEvent(status=0xF7)` with `endplusone` just past the terminator and `skipped` counting the preceding data bytes (`test_NoteOn_prepartialsysex` expects `(MIDIUnknownEvent, 5, 4)` for `01 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**:

```python
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; both `None` → `ValueError("No midi_in or midi_out provided")`. One-sided instances are valid, but the unused direction is never null-checked: `receive()` with `midi_in=None` raises `AttributeError` from the `None` port instead of returning `None`, and `send()` with `midi_out=None` raises `AttributeError` only after stamping `msg.channel` and (with `debug=True`) printing `Sending: `.
- Validation order: ports (`ValueError`) → `in_channel` → `out_channel` (both `RuntimeError`). 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) raise `TypeError` at the comparison, comparable out-of-range elements raise `RuntimeError("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 to `RuntimeError("Invalid input channel")`; `None` or `"ALL"` normalizes to `tuple(range(16))`. The getter never returns `None` after construction; `bool` counts as int.
- `out_channel`: int 0-15, default 0; out-of-range → `RuntimeError("Invalid output channel")`; non-numeric values fail with `TypeError` in 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.
- `send` uses `out_channel` unless `channel=` is given; it mutates `msg.channel` as a side effect; wire status byte = base status | channel; a sequence is sent in one `write` call.
- `receive` returns `None` for 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 repeated `None` then `MIDIUnknownEvent(0xF7)` for the EOX byte.
- Debug prints are asymmetric: `Receiving: ` prints only the non-empty byte list returned by `read()` — raw, pre-parse, pre-filter, showing what the peer sent (including unlistened channels); `Sending: ` prints the exact packet handed to `write()`.

## Example

```python
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)`. `LENGTH` includes the status byte: `ChannelPressure` = 2 (`0xD0`), `ControlChange` = 3 (`0xB0`), `PitchBend` = 3 (`0xE0`).
- `PitchBend` emits its 14-bit value as `pitch_bend & 0x7F` then `(pitch_bend >> 7) & 0x7F` (LSB first); valid range 0-16383.
- Validation order: `channel` setter first (`ValueError("Channel must be 0-15 or None")`, `None` allowed), 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 with `channel is None` raises `TypeError`; `MIDI.send()` supplies the port's out-channel when the message channel is `None`. Encoding never mutates the message and is repeatable.
- `from_bytes` reconstructs the channel from `msg_bytes[0] & 0x0F`, making `bytes()` and `from_bytes` an exact round trip.
- `note_parser`: int passes through unchanged; strings parse letter A-G (case-insensitive) via `NOTE_OFFSET = [21, 23, 12, 14, 16, 17, 19]`, optional `#`/`b` accidental, then `int()` 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)`: exact `int` equality or tuple membership; other spec types raise `ValueError` (propagating on a direct call). Inside `from_message_bytes`, however, the `channel_filter` call shares the same `except (ValueError, TypeError)` handler as `from_bytes`, so a bad `channel_spec` type, including `None`, is converted into a `MIDIBadEvent` with `.data`/`.exception_text` set instead of propagating. Used by `from_message_bytes` to accept or skip decoded messages.
- Registry: importing a message module registers its class by `(status, mask)`; `from_message_bytes` matches the first MSB-set byte, requires `LENGTH` bytes for completeness (partials stay buffered), wraps `from_bytes` failures - and any `channel_filter` `ValueError` raised for a bad `channel_spec` type, including `None` - in `MIDIBadEvent` (`.data` = raw bytes, `.exception_text` = `repr(exception)`, channel unset), and maps unmatched statuses to `MIDIUnknownEvent`. `MIDIBadEvent` is never registered.
- `str()`/`repr()` use `_message_slots`, e.g. `ControlChange(control=7, value=100, channel=0)`; `MIDIBadEvent` renders `MIDIBadEvent(msg_bytes=None, exception=None)` because its slot names do not match its `.data`/`.exception_text` attributes.

## Example

```python
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 by `endplusone` (caller slices `midibytes[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) == _STATUS` match wins.
- Fixed `LENGTH` includes the status byte; a message is complete when `len(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 their `ENDSTATUS` inside 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)` with `endplusone = status_index + 1`; leftover data bytes are skipped as preamble on the next call and counted in that call's `skipped`.
- `from_bytes` raising `ValueError`/`TypeError` yields `MIDIBadEvent(message_bytes, exception)` storing `.data` (`bytes`) and `.exception_text` (`repr()` of the exception); `channel` stays `None`, so bad events are returned regardless of `channel_in`, and `str()` shows `MIDIBadEvent(msg_bytes=None, exception=None)`.
- Channel filtering runs only when the parsed message's `channel` is not `None`; channel-less (system) messages are returned regardless of `channel_in` and `channel_filter` is 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_filter` accepts only `int`/tuple specs and raises `ValueError` otherwise - the parser converts that into a `MIDIBadEvent`, 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

```python
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) -> bool` is stateless: an `int` spec matches by equality, a tuple spec by membership. The spec type *is* validated — any other value (including `None`) raises `ValueError` — though channel values themselves are not checked.
- Applied inside `MIDIMessage.from_message_bytes(midibytes, channel_in)` to the parsed `channel` of an already-constructed message, only when that channel is not `None` (i.e. for channel-voice messages). System messages (the `0xF0` family: SysEx, MTC Quarter Frame, Start, Stop, Continue, Timing Clock, Active Sensing, MIDI Reset) have `channel is None`, bypass the predicate, and come back with `channel is None` regardless of `in_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=None` is not an accept-all spec: the `ValueError` raised inside `channel_filter` is caught by `from_message_bytes`'s `except (ValueError, TypeError)` handler and the voice message surfaces as a `MIDIBadEvent` (no channel) — only int/tuple specs filter. Likewise, a message whose `from_bytes` raises for any other reason becomes a `MIDIBadEvent` returned regardless of `channel_in`: filtering is only decided after successful construction.
- Channel `0` matches 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)` where `endplusone` is the index just past the returned message (the resync point) and `skipped` counts 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's `in_channel` (default `0`) on every parse; blocking/timeout behavior is unchanged — only message visibility changes.

## Usage

```python
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

- `NoteOn` and `NoteOff` are fixed-length, 3 bytes **including** the status byte (`LENGTH = 3`); wire form is `status | (channel & 0x0F)` followed by the `note` and `velocity` data 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)` and `NoteOff(note, velocity=0)` parse string notes (`"C4"` -> 60, `"C#4"`/`"Db4"` -> 61) once, at construction.
- Ranges enforced at construction: `note`/`velocity` 0-127 -> `ValueError("Out of range")`; channel must be 0-15 or `None` -> `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=None` is not encodable via `bytes()` (`None & 0x0F` raises `TypeError`) until a channel is assigned; assignment happens only through the constructor. The message classes themselves never store a channel back or reset it to `None` after 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_bytes` performs no status-byte validation or dispatch: it masks `msg_bytes[0]` with `CHANNELMASK` (0x0F) for the channel and uses `msg_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 as `MIDIBadEvent`, not exceptions.
- Class identity is preserved on round-trips (`NoteOn` with `velocity=0` stays `NoteOn`); `str()`/`repr()` render slot values in `_message_slots` order, 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

```python
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 = 0xF7` is appended once by `__bytes__` and must not appear in `data`.
- `manufacturer_id` and `data` are coerced to `bytes` at construction; no 0-127 range check, no `channel` kwarg (`TypeError`), `channel` property is `None`.
- ID width is inferred at parse time: byte after `0xF0` nonzero -> 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 to `manufacturer_id == b'\xf7'`, `data == b''`; `SystemExclusive([], [])` encodes to `b'\xf0\xf7'`, re-parses as ID `b'\xf7'`, and re-encodes as `b'\xf0\xf7\xf7'`, so an empty manufacturer_id does not round-trip.
- `from_bytes` unconditionally excludes the final byte as the terminator without checking it is `0xF7`.
- Parsing ends at the first MSB-set byte after `0xF0`: `0xF7` is 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)`, so `receive()` 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 `0xF7` without a preceding `0xF0` yields `MIDIUnknownEvent(status=0xF7)`; preceding data bytes count toward `skipped`.
- Well-formed 7-bit frames carrying a non-empty manufacturer_id round-trip byte-exactly, including empty `data`; an empty `manufacturer_id` does not round-trip (see the `F0 F7` case), and payloads containing `0xF7` or any >= 0x80 byte truncate at that byte on parse.
- Channel filtering in `receive()` never applies (channel `None` passes every `in_channel`); `send()` stamps `.channel` but encoding ignores it.
- Registration happens at module import; `import adafruit_midi.system_exclusive` is required or `0xF0` decodes as `MIDIUnknownEvent`.
- `str`/`repr` show `SystemExclusive(manufacturer_id=..., data=...)`; class constants `LENGTH == -1` and `ENDSTATUS == 0xF7` are stable contract points.

## Example

```python
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
```