Initial import: Rust BLE-MIDI keypad for Pico W
Port of the C/BTstack BLE-MIDI keypad firmware to Rust (embassy + cyw43 + trouble). 16-pad RGB keypad (APA102 SPI + I2C button expander), BLE-MIDI 1.0 GATT server (full codec: sysex, running-status, real-time), octave display on BOOTSEL, onboard LED heartbeat, USB serial logging. - src/keypad.rs Pimoroni RGB Keypad driver - src/midi_keypad.rs pad->Note On/Off + LED response state machine - src/codec.rs BLE-MIDI 1.0 codec (port of rppicomidi, MIT) - src/main.rs cyw43 BT bring-up + trouble GATT + MIDI pump - src/octave.rs octave digit display on BOOTSEL GPL-3.0-or-later; codec.rs retains its MIT (rppicomidi) attribution.
This commit is contained in:
@@ -0,0 +1,5 @@
|
|||||||
|
[build]
|
||||||
|
target = "thumbv6m-none-eabi" # Cortex-M0+ (RP2040)
|
||||||
|
|
||||||
|
[env]
|
||||||
|
DEFMT_LOG = "info"
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
/target
|
||||||
Generated
+2074
File diff suppressed because it is too large
Load Diff
+54
@@ -0,0 +1,54 @@
|
|||||||
|
[package]
|
||||||
|
name = "rgb-keypad"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
resolver = "2"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
embassy-executor = { version = "0.10", default-features = false, features = ["platform-cortex-m", "executor-thread", "defmt", "executor-interrupt"] }
|
||||||
|
embassy-time = { version = "0.5", default-features = false, features = ["defmt", "defmt-timestamp-uptime"] }
|
||||||
|
embassy-rp = { version = "0.10", features = ["defmt", "unstable-pac", "time-driver", "critical-section-impl", "rp2040"] }
|
||||||
|
embassy-sync = { version = "0.8", features = ["defmt"] }
|
||||||
|
embassy-futures = "0.1.2"
|
||||||
|
embassy-usb = { version = "0.6", default-features = false, features = ["defmt"] }
|
||||||
|
embassy-usb-logger = { version = "0.6", default-features = false }
|
||||||
|
log = "0.4"
|
||||||
|
|
||||||
|
# BLE: cyw43 (CYW43439 BT controller on Pico W) + trouble (BLE host / GATT).
|
||||||
|
# trouble-host 0.8.0 is unreleased on crates.io, so we pull it from git; it must
|
||||||
|
# match the bt-hci version used by cyw43, hence the embassy/cyw43 git patch
|
||||||
|
# below pins everything to a known-compatible revision (the same one the
|
||||||
|
# upstream rp-pico-w example uses).
|
||||||
|
trouble-host = { git = "https://github.com/embassy-rs/trouble", rev = "4eea72088fdbb91326a3ac95160b3154fdff802a", features = ["derive", "gatt", "defmt", "default-packet-pool-mtu-128"] }
|
||||||
|
cyw43 = { version = "0.7", features = ["defmt", "firmware-logs", "bluetooth"] }
|
||||||
|
cyw43-pio = { version = "0.10", features = ["defmt"] }
|
||||||
|
|
||||||
|
defmt = "1.0"
|
||||||
|
defmt-rtt = "1.0"
|
||||||
|
panic-probe = { version = "1.0", features = ["print-defmt"] }
|
||||||
|
|
||||||
|
cortex-m = { version = "0.7.6" }
|
||||||
|
cortex-m-rt = "0.7.0"
|
||||||
|
static_cell = "2"
|
||||||
|
portable-atomic = { version = "1.5", features = ["critical-section"] }
|
||||||
|
heapless = "0.8"
|
||||||
|
|
||||||
|
embedded-hal-async = "1.0"
|
||||||
|
|
||||||
|
[profile.release]
|
||||||
|
debug = 2
|
||||||
|
opt-level = "s"
|
||||||
|
|
||||||
|
# Pin the embassy + cyw43 crates to the same git revision the upstream
|
||||||
|
# rp-pico-w Bluetooth example validates, so cyw43's bt-hci and trouble's
|
||||||
|
# bt-hci unify on one version (released crates pull incompatible bt-hci majors).
|
||||||
|
[patch.crates-io]
|
||||||
|
cyw43 = { git = "https://github.com/embassy-rs/embassy.git", rev = "3cd51e6d8eb6aff8b0d64d9e56a75a538bcfc65a" }
|
||||||
|
cyw43-pio = { git = "https://github.com/embassy-rs/embassy.git", rev = "3cd51e6d8eb6aff8b0d64d9e56a75a538bcfc65a" }
|
||||||
|
embassy-rp = { git = "https://github.com/embassy-rs/embassy.git", rev = "3cd51e6d8eb6aff8b0d64d9e56a75a538bcfc65a" }
|
||||||
|
embassy-sync = { git = "https://github.com/embassy-rs/embassy.git", rev = "3cd51e6d8eb6aff8b0d64d9e56a75a538bcfc65a" }
|
||||||
|
embassy-executor = { git = "https://github.com/embassy-rs/embassy.git", rev = "3cd51e6d8eb6aff8b0d64d9e56a75a538bcfc65a" }
|
||||||
|
embassy-time = { git = "https://github.com/embassy-rs/embassy.git", rev = "3cd51e6d8eb6aff8b0d64d9e56a75a538bcfc65a" }
|
||||||
|
embassy-usb = { git = "https://github.com/embassy-rs/embassy.git", rev = "3cd51e6d8eb6aff8b0d64d9e56a75a538bcfc65a" }
|
||||||
|
embassy-usb-driver = { git = "https://github.com/embassy-rs/embassy.git", rev = "3cd51e6d8eb6aff8b0d64d9e56a75a538bcfc65a" }
|
||||||
|
embassy-usb-logger = { git = "https://github.com/embassy-rs/embassy.git", rev = "3cd51e6d8eb6aff8b0d64d9e56a75a538bcfc65a" }
|
||||||
@@ -0,0 +1,652 @@
|
|||||||
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users. We, the Free Software Foundation, use the
|
||||||
|
GNU General Public License for most of our software; it applies also to
|
||||||
|
any other work released this way by its authors. You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you
|
||||||
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether
|
||||||
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
|
or can get the source code. And you must show them these terms so they
|
||||||
|
know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
|
that there is no warranty for this free software. For both users' and
|
||||||
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
|
changed, so that their problems will not be attributed erroneously to
|
||||||
|
authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run
|
||||||
|
modified versions of the software inside them, although the manufacturer
|
||||||
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
|
protecting users' freedom to change the software. The systematic
|
||||||
|
pattern of such abuse occurs in the area of products for individuals to
|
||||||
|
use, which is precisely where it is most unacceptable. Therefore, we
|
||||||
|
have designed this version of the GPL to prohibit the practice for those
|
||||||
|
products. If such problems arise substantially in other domains, we
|
||||||
|
stand ready to extend this provision to those domains in future versions
|
||||||
|
of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents.
|
||||||
|
States should not allow patents to restrict development and use of
|
||||||
|
software on general-purpose computers, but in those that do, we wish to
|
||||||
|
avoid the special danger that patents applied to a free program could
|
||||||
|
make it effectively proprietary. To prevent this, the GPL assures that
|
||||||
|
patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based on
|
||||||
|
the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that the work is licensed under this License and how to
|
||||||
|
view a copy of this License. If the interface presents a list of user
|
||||||
|
commands or options, such as a menu, a prominent item in the list meets
|
||||||
|
this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes this unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to the
|
||||||
|
covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of the source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall be
|
||||||
|
treated as though they were included in this License, to the extent that
|
||||||
|
they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not
|
||||||
|
to sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for or in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey the
|
||||||
|
Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the special requirements of the GNU Affero General Public License,
|
||||||
|
section 13, concerning interaction through a network will apply to the
|
||||||
|
combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFICULT, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short
|
||||||
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
<program> Copyright (C) <year> <name of author>
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w` and `show c` should show the appropriate
|
||||||
|
parts of the General Public License. Of course, your program's commands
|
||||||
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program
|
||||||
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License. But first, please read
|
||||||
|
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
# pico-pi-midi (Rust)
|
||||||
|
|
||||||
|
BLE-MIDI keypad firmware for the Raspberry Pi Pico W (RP2040 + CYW43439), written in Rust using [embassy](https://embassy.dev), the [cyw43](https://crates.io/crates/cyw43) driver (Bluetooth), and the [TrouBLE](https://github.com/embassy-rs/trouble) BLE host.
|
||||||
|
|
||||||
|
This is the Rust port of the original C/BTstack firmware (now kept separately as `pico-pi-midi-c`). It talks BLE-MIDI 1.0 to iOS / macOS Core MIDI, turning the Pimoroni Pico RGB Keypad into a 16-pad wireless MIDI controller.
|
||||||
|
|
||||||
|
## What it does
|
||||||
|
|
||||||
|
- **16-pad keypad** (Pimoroni RGB Keypad Base): reads buttons over I²C (GPIO expander @ 0x20) and drives APA102 RGB LEDs over SPI (CS=17, SCK=18, MOSI=19).
|
||||||
|
- **BLE-MIDI 1.0** GATT server (MIDI Service `03B80E5A-…`), advertised so Core MIDI discovers it as a MIDI device. Pad presses → Note On/Off over Bluetooth; incoming Note On lights the pad.
|
||||||
|
- **Octave display**: the BOOTSEL button cycles the keypad's note offset by +12 and flashes the active octave as a digit on the 4×4 grid for 500 ms.
|
||||||
|
- **Onboard LED** heartbeat (driven via the CYW43 chip — the Pico W's LED is on the wireless chip, not an RP2040 pin).
|
||||||
|
- **USB serial logging** via `embassy-usb-logger` — connect and read with `screen /dev/cu.usbmodem* 115200` to see boot/advertising logs.
|
||||||
|
|
||||||
|
## Roadmap
|
||||||
|
|
||||||
|
This is v1: a BLE-MIDI keypad. The goal is a **flexible MIDI router** — MIDI over USB, BLE, keypad, TRS, and 4 stereo CV outputs, with channels configurable at runtime via an LCD. See the architecture notes (kept in the session memory) for the plan.
|
||||||
|
|
||||||
|
## Building
|
||||||
|
|
||||||
|
Requires Rust stable (≥1.93) and the `thumbv6m-none-eabi` target:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
rustup target add thumbv6m-none-eabi
|
||||||
|
cargo build --release
|
||||||
|
```
|
||||||
|
|
||||||
|
The CYW43 firmware blobs (`cyw43-firmware/*.bin`) are committed here so no network access is needed at build time. They are redistributable under the permissive binary license in the upstream [`embassy cyw43-firmware`](https://github.com/embassy-rs/embassy/tree/main/cyw43-firmware) directory.
|
||||||
|
|
||||||
|
## Flashing
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo build --release
|
||||||
|
elf2uf2-rs convert target/thumbv6m-none-eabi/release/rgb-keypad target/uf2/rgb-keypad.uf2
|
||||||
|
# hold BOOTSEL + plug in the Pico W, then:
|
||||||
|
picotool load target/uf2/rgb-keypad.uf2 -x
|
||||||
|
```
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
GPL-3.0-or-later (see [`LICENSE`](LICENSE)).
|
||||||
|
|
||||||
|
`src/codec.rs` is a Rust port of the BLE-MIDI 1.0 packet codec from
|
||||||
|
[rppicomidi/pico-w-ble-midi-lib](https://github.com/rppicomidi/pico-w-ble-midi-lib),
|
||||||
|
which is MIT-licensed; that attribution is retained in the file header. MIT is
|
||||||
|
GPL-3.0-compatible, so the repository as a whole is GPL-3.0-or-later while that
|
||||||
|
file preserves its MIT provenance.
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
//! Build script: place memory.x on the linker search path and set up the
|
||||||
|
//! RP2040 + defmt linker scripts. The CYW43 firmware blobs are committed
|
||||||
|
//! under `cyw43-firmware/` (no network access needed at build time).
|
||||||
|
|
||||||
|
use std::env;
|
||||||
|
use std::fs::File;
|
||||||
|
use std::io::Write;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap());
|
||||||
|
File::create(out.join("memory.x"))
|
||||||
|
.unwrap()
|
||||||
|
.write_all(include_bytes!("memory.x"))
|
||||||
|
.unwrap();
|
||||||
|
println!("cargo::rustc-link-search={}", out.display());
|
||||||
|
|
||||||
|
println!("cargo::rerun-if-changed=memory.x");
|
||||||
|
|
||||||
|
println!("cargo::rustc-link-arg-bins=--nmagic");
|
||||||
|
println!("cargo::rustc-link-arg-bins=-Tlink.x");
|
||||||
|
println!("cargo::rustc-link-arg-bins=-Tlink-rp.x");
|
||||||
|
println!("cargo::rustc-link-arg-bins=-Tdefmt.x");
|
||||||
|
}
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,7 @@
|
|||||||
|
MEMORY {
|
||||||
|
BOOT2 : ORIGIN = 0x10000000, LENGTH = 0x100
|
||||||
|
FLASH : ORIGIN = 0x10000100, LENGTH = 2048K - 0x100
|
||||||
|
|
||||||
|
/* RP2040: 264K RAM (6K stripe + 256K main, used as one block) */
|
||||||
|
RAM : ORIGIN = 0x20000000, LENGTH = 264K
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
[toolchain]
|
||||||
|
channel = "stable"
|
||||||
|
targets = ["thumbv6m-none-eabi"]
|
||||||
+719
@@ -0,0 +1,719 @@
|
|||||||
|
//! BLE-MIDI 1.0 packet codec — faithful Rust port of `ble_midi_pkt_codec.c`
|
||||||
|
//! (rppicomidi, MIT). Encodes a MIDI 1.0 byte stream into BLE-MIDI packets and
|
||||||
|
//! decodes BLE-MIDI packets back into timestamped MIDI messages, with full
|
||||||
|
//! support for system-exclusive, running-status, and system real-time.
|
||||||
|
//!
|
||||||
|
//! Pure `no_std` logic (no allocator, no HAL/BLE deps) so it is independent of
|
||||||
|
//! the rest of the firmware and could be unit-tested on host.
|
||||||
|
//!
|
||||||
|
//! Spec: https://midi.org/specifications/midi-transports-specifications/midi-over-bluetooth-low-energy-ble-midi
|
||||||
|
//!
|
||||||
|
//! ---
|
||||||
|
//!
|
||||||
|
//! This file is a Rust port of MIT-licensed code by rppicomidi
|
||||||
|
//! (https://github.com/rppicomidi/pico-w-ble-midi-lib). The original MIT
|
||||||
|
//! notice and permission are retained below per its terms. The port is
|
||||||
|
//! contributed to this project under GPL-3.0-or-later (see the repository
|
||||||
|
//! LICENSE); MIT is GPL-3.0-compatible so both apply here.
|
||||||
|
//!
|
||||||
|
//! Original MIT license — Copyright (c) 2023 rppicomidi
|
||||||
|
//!
|
||||||
|
//! Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
//! of this software and associated documentation files (the "Software"), to deal
|
||||||
|
//! in the Software without restriction, including without limitation the rights
|
||||||
|
//! to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
//! copies of the Software, and to permit persons to whom the Software is
|
||||||
|
//! furnished to do so, subject to the following conditions:
|
||||||
|
//!
|
||||||
|
//! The above copyright notice and this permission notice shall be included in
|
||||||
|
//! all copies or substantial portions of the Software.
|
||||||
|
//!
|
||||||
|
//! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
//! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
//! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
//! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
//! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
//! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
//! THE SOFTWARE.
|
||||||
|
//!
|
||||||
|
//! SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
|
#![allow(clippy::needless_range_loop)]
|
||||||
|
|
||||||
|
/// Max BLE-MIDI packet payload. Without LE Data Length Extension the ATT default
|
||||||
|
/// MTU is 23, giving a 20-byte MIDI payload (MTU - 3 ATT header).
|
||||||
|
pub const MAX_BLE_MIDI_PACKET: usize = 20;
|
||||||
|
|
||||||
|
// Flag bits stored in the upper bits of `BleMidiMessage::nbytes`.
|
||||||
|
const IS_START_SYSEX: u8 = 0x80;
|
||||||
|
const IS_SYSEX: u8 = 0x20;
|
||||||
|
const IS_REAL_TIME: u8 = 0x10;
|
||||||
|
const IS_CHANNEL: u8 = 0x08;
|
||||||
|
const NBYTES_MASK: u8 = 0x03;
|
||||||
|
|
||||||
|
const fn header(ts: u16) -> u8 {
|
||||||
|
0x80 | ((ts >> 7) & 0x3F) as u8
|
||||||
|
}
|
||||||
|
const fn timestamp_low(ts: u16) -> u8 {
|
||||||
|
0x80 | (ts & 0x7F) as u8
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A timestamped fragment of a MIDI message (the decode output unit).
|
||||||
|
///
|
||||||
|
/// The upper bits of `nbytes` encode what kind of message is in `msg_bytes`;
|
||||||
|
/// the low 2 bits hold the number of valid bytes.
|
||||||
|
#[derive(Clone, Copy, Default)]
|
||||||
|
pub struct BleMidiMessage {
|
||||||
|
pub nbytes: u8,
|
||||||
|
pub msg_bytes: [u8; 3],
|
||||||
|
pub timestamp_ms: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BleMidiMessage {
|
||||||
|
/// Number of valid bytes in `msg_bytes`.
|
||||||
|
pub fn byte_count(&self) -> u8 {
|
||||||
|
self.nbytes & NBYTES_MASK
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A BLE-MIDI 1.0 data packet (the encode output / notify payload).
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
pub struct BleMidiPacket {
|
||||||
|
/// Number of valid bytes in `pkt`.
|
||||||
|
pub nbytes: usize,
|
||||||
|
pub pkt: [u8; MAX_BLE_MIDI_PACKET],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for BleMidiPacket {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
nbytes: 0,
|
||||||
|
pkt: [0; MAX_BLE_MIDI_PACKET],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Single-producer/single-consumer ring of fixed-size `Copy` elements.
|
||||||
|
struct Ring<T: Copy + Default, const N: usize> {
|
||||||
|
buf: [T; N],
|
||||||
|
head: usize,
|
||||||
|
tail: usize,
|
||||||
|
len: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Copy + Default, const N: usize> Ring<T, N> {
|
||||||
|
fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
buf: core::array::from_fn(|_| T::default()),
|
||||||
|
head: 0,
|
||||||
|
tail: 0,
|
||||||
|
len: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn push(&mut self, v: T) -> bool {
|
||||||
|
if self.len < N {
|
||||||
|
self.buf[self.tail] = v;
|
||||||
|
self.tail = (self.tail + 1) % N;
|
||||||
|
self.len += 1;
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn pop(&mut self) -> Option<T> {
|
||||||
|
if self.len > 0 {
|
||||||
|
let v = self.buf[self.head];
|
||||||
|
self.head = (self.head + 1) % N;
|
||||||
|
self.len -= 1;
|
||||||
|
Some(v)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn len(&self) -> usize {
|
||||||
|
self.len
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encoder state for one connection (mirrors `to_ble_midi_stream_t`).
|
||||||
|
#[derive(Clone, Copy, Default)]
|
||||||
|
struct ToBleStream {
|
||||||
|
mes: BleMidiMessage,
|
||||||
|
next_msg_byte_idx: u16,
|
||||||
|
previous_timestamp: u16,
|
||||||
|
running_status: u8,
|
||||||
|
npending_rt: u8,
|
||||||
|
pending_rt_status: [u8; 4],
|
||||||
|
pending_rt_timestamp: [u16; 4],
|
||||||
|
pending_ble_pkt: BleMidiPacket,
|
||||||
|
pending_ble_midi_pkt_running_status: u8,
|
||||||
|
pending_ble_midi_pkt_prev_status: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Per-connection BLE-MIDI codec context.
|
||||||
|
pub struct Codec {
|
||||||
|
to_ble: Ring<BleMidiPacket, 10>,
|
||||||
|
from_ble: Ring<BleMidiMessage, 100>,
|
||||||
|
stream: ToBleStream,
|
||||||
|
ble_mtu: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Codec {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
let mut c = Self {
|
||||||
|
to_ble: Ring::new(),
|
||||||
|
from_ble: Ring::new(),
|
||||||
|
stream: ToBleStream::default(),
|
||||||
|
ble_mtu: MAX_BLE_MIDI_PACKET,
|
||||||
|
};
|
||||||
|
c.reset_stream();
|
||||||
|
c
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_mtu(&mut self, ble_mtu: usize) {
|
||||||
|
self.ble_mtu = ble_mtu;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update MTU, capped at the packet buffer size (matches the C `update_mtu`
|
||||||
|
/// which does `MIN(ble_mtu, sizeof(pending_ble_pkt.pkt))`).
|
||||||
|
pub fn update_mtu(&mut self, ble_mtu: usize) {
|
||||||
|
self.ble_mtu = core::cmp::min(ble_mtu, MAX_BLE_MIDI_PACKET);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_mtu(&self) -> usize {
|
||||||
|
self.ble_mtu
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reset_stream(&mut self) {
|
||||||
|
let s = &mut self.stream;
|
||||||
|
s.next_msg_byte_idx = 0;
|
||||||
|
s.previous_timestamp = 0xffff; // illegal sentinel
|
||||||
|
s.running_status = 0;
|
||||||
|
s.mes.nbytes = 0;
|
||||||
|
s.mes.timestamp_ms = 0xffff;
|
||||||
|
s.npending_rt = 0;
|
||||||
|
s.pending_ble_pkt.nbytes = 0;
|
||||||
|
s.pending_ble_midi_pkt_running_status = 0;
|
||||||
|
s.pending_ble_midi_pkt_prev_status = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- encode (MIDI stream -> BLE-MIDI packets) --------------------------
|
||||||
|
|
||||||
|
/// Push a MIDI 1.0 byte stream to be encoded. Returns `(bytes_pushed,
|
||||||
|
/// ready_to_send)` where `ready_to_send` is true if at least one complete
|
||||||
|
/// BLE-MIDI packet is available to pop and notify.
|
||||||
|
pub fn push_midi(&mut self, midi_stream: &[u8], now_ms: u16) -> (u16, bool) {
|
||||||
|
let timestamp = now_ms & 0x1FFF;
|
||||||
|
let mut bytes_pushed: u16 = 0;
|
||||||
|
let mut ready_to_send = false;
|
||||||
|
|
||||||
|
let s = &mut self.stream;
|
||||||
|
let to_ble = &mut self.to_ble;
|
||||||
|
let ble_mtu = self.ble_mtu;
|
||||||
|
|
||||||
|
while (bytes_pushed as usize) < midi_stream.len() && s.pending_ble_pkt.nbytes < ble_mtu {
|
||||||
|
let ms_byte = midi_stream[bytes_pushed as usize];
|
||||||
|
|
||||||
|
if ms_byte & 0x80 != 0 {
|
||||||
|
// ---- status byte ----
|
||||||
|
if ms_byte == 0xF0 {
|
||||||
|
s.previous_timestamp = timestamp;
|
||||||
|
s.mes.nbytes = IS_START_SYSEX | IS_SYSEX | 1;
|
||||||
|
bytes_pushed += 1;
|
||||||
|
s.running_status = 0;
|
||||||
|
s.mes.msg_bytes[0] = ms_byte;
|
||||||
|
s.next_msg_byte_idx = 1;
|
||||||
|
} else if ms_byte == 0xF7 {
|
||||||
|
if s.mes.nbytes & IS_SYSEX == 0 {
|
||||||
|
// EOX without being in a sysex — stream error
|
||||||
|
discard_stream(s);
|
||||||
|
return (bytes_pushed, ready_to_send);
|
||||||
|
}
|
||||||
|
if s.next_msg_byte_idx != 0 {
|
||||||
|
encode_bt_pkt(s, to_ble, ble_mtu);
|
||||||
|
}
|
||||||
|
s.mes.timestamp_ms = s.previous_timestamp;
|
||||||
|
s.mes.msg_bytes[0] = ms_byte;
|
||||||
|
s.mes.nbytes = 1;
|
||||||
|
bytes_pushed += 1;
|
||||||
|
encode_full_bt_pkt(s, to_ble, ble_mtu);
|
||||||
|
s.running_status = 0;
|
||||||
|
} else if ms_byte >= 0xF8 {
|
||||||
|
// system real-time (may occur inside sysex)
|
||||||
|
if s.mes.nbytes & IS_SYSEX != 0 && (s.mes.nbytes & NBYTES_MASK) > 0 {
|
||||||
|
encode_bt_pkt(s, to_ble, ble_mtu);
|
||||||
|
s.next_msg_byte_idx = 0;
|
||||||
|
s.mes.nbytes = IS_SYSEX;
|
||||||
|
}
|
||||||
|
if s.npending_rt < s.pending_rt_status.len() as u8 {
|
||||||
|
let i = s.npending_rt as usize;
|
||||||
|
s.pending_rt_status[i] = ms_byte;
|
||||||
|
s.pending_rt_timestamp[i] = timestamp;
|
||||||
|
s.npending_rt += 1;
|
||||||
|
}
|
||||||
|
bytes_pushed += 1;
|
||||||
|
if s.npending_rt >= s.pending_rt_status.len() as u8 {
|
||||||
|
discard_stream(s);
|
||||||
|
return (bytes_pushed, ready_to_send);
|
||||||
|
}
|
||||||
|
flush_rt_midi_to_pkt(s, to_ble, ble_mtu);
|
||||||
|
} else if ms_byte > 0xF0 {
|
||||||
|
// system common
|
||||||
|
s.mes.msg_bytes[0] = ms_byte;
|
||||||
|
s.previous_timestamp = timestamp;
|
||||||
|
s.mes.timestamp_ms = timestamp;
|
||||||
|
bytes_pushed += 1;
|
||||||
|
s.running_status = 0;
|
||||||
|
if ms_byte == 0xF1 || ms_byte == 0xF3 {
|
||||||
|
s.mes.nbytes = 2;
|
||||||
|
s.next_msg_byte_idx = 1;
|
||||||
|
} else if ms_byte == 0xF2 {
|
||||||
|
s.mes.nbytes = 3;
|
||||||
|
s.next_msg_byte_idx = 1;
|
||||||
|
} else {
|
||||||
|
s.mes.nbytes = 1;
|
||||||
|
encode_full_bt_pkt(s, to_ble, ble_mtu);
|
||||||
|
s.mes.nbytes = 0;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// channel message
|
||||||
|
s.running_status = ms_byte;
|
||||||
|
s.mes.msg_bytes[0] = ms_byte;
|
||||||
|
s.previous_timestamp = timestamp;
|
||||||
|
s.mes.timestamp_ms = timestamp;
|
||||||
|
bytes_pushed += 1;
|
||||||
|
s.next_msg_byte_idx = 1;
|
||||||
|
s.mes.nbytes = IS_CHANNEL | 3;
|
||||||
|
let chan_msg_base = (ms_byte >> 4) & 0xF;
|
||||||
|
if chan_msg_base == 0xC || chan_msg_base == 0xD {
|
||||||
|
s.mes.nbytes = IS_CHANNEL | 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// ---- data byte ----
|
||||||
|
if s.mes.nbytes & IS_SYSEX != 0 {
|
||||||
|
s.mes.msg_bytes[s.next_msg_byte_idx as usize] = ms_byte;
|
||||||
|
s.next_msg_byte_idx += 1;
|
||||||
|
s.mes.nbytes += 1;
|
||||||
|
bytes_pushed += 1;
|
||||||
|
if s.next_msg_byte_idx >= 3 {
|
||||||
|
encode_full_bt_pkt(s, to_ble, ble_mtu);
|
||||||
|
s.mes.timestamp_ms = s.previous_timestamp;
|
||||||
|
s.mes.nbytes = IS_SYSEX; // length 0, still in sysex
|
||||||
|
}
|
||||||
|
} else if s.mes.nbytes & IS_CHANNEL != 0 && s.next_msg_byte_idx == 0 {
|
||||||
|
if s.running_status == 0 || s.running_status != s.mes.msg_bytes[0] {
|
||||||
|
discard_stream(s);
|
||||||
|
return (bytes_pushed, ready_to_send);
|
||||||
|
} else {
|
||||||
|
s.mes.msg_bytes[1] = ms_byte;
|
||||||
|
s.mes.timestamp_ms = timestamp;
|
||||||
|
bytes_pushed += 1;
|
||||||
|
s.next_msg_byte_idx = 2;
|
||||||
|
if (s.mes.nbytes & NBYTES_MASK) as u16 == s.next_msg_byte_idx {
|
||||||
|
encode_full_bt_pkt(s, to_ble, ble_mtu);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let len = s.mes.nbytes & NBYTES_MASK;
|
||||||
|
if (s.next_msg_byte_idx as u8) < len {
|
||||||
|
s.mes.msg_bytes[s.next_msg_byte_idx as usize] = ms_byte;
|
||||||
|
s.next_msg_byte_idx += 1;
|
||||||
|
bytes_pushed += 1;
|
||||||
|
if len == s.next_msg_byte_idx as u8 {
|
||||||
|
encode_full_bt_pkt(s, to_ble, ble_mtu);
|
||||||
|
if s.mes.nbytes & IS_CHANNEL == 0 {
|
||||||
|
s.mes.nbytes = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
discard_stream(s);
|
||||||
|
return (bytes_pushed, ready_to_send);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if bytes_pushed > 0 && self.stream.pending_ble_pkt.nbytes > 0 {
|
||||||
|
self.to_ble.push(self.stream.pending_ble_pkt);
|
||||||
|
self.stream.pending_ble_pkt.nbytes = 0;
|
||||||
|
self.stream.pending_ble_midi_pkt_running_status = 0;
|
||||||
|
self.stream.pending_ble_midi_pkt_prev_status = 0;
|
||||||
|
ready_to_send = true;
|
||||||
|
}
|
||||||
|
(bytes_pushed, ready_to_send)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pop the next encoded BLE-MIDI packet to send (notify).
|
||||||
|
pub fn ble_pkt_pop(&mut self) -> Option<BleMidiPacket> {
|
||||||
|
self.to_ble.pop()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True if at least one encoded packet is available to send.
|
||||||
|
pub fn ble_pkt_available(&self) -> bool {
|
||||||
|
self.to_ble.len() > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- decode (BLE-MIDI packet -> timestamped MIDI messages) ------------
|
||||||
|
|
||||||
|
/// Decode a BLE-MIDI packet, pushing each resulting timestamped message to
|
||||||
|
/// the from-BLE ring. Returns the number of packet bytes consumed.
|
||||||
|
pub fn decode_push(&mut self, pkt: &[u8]) -> usize {
|
||||||
|
let nbytes = pkt.len();
|
||||||
|
if nbytes < 2 {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
// header byte must be present
|
||||||
|
if (pkt[0] & 0xc0) != 0x80 {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
let mut timestamp: u16 = ((pkt[0] & 0x3f) as u16) << 7;
|
||||||
|
let mut prev_lsb: u8 = 0;
|
||||||
|
let mut ndecoded: usize = 1;
|
||||||
|
let mut running_status: u8 = 0;
|
||||||
|
let mut running_status_nbytes: u8 = 0;
|
||||||
|
let mut mes: BleMidiMessage = BleMidiMessage::default();
|
||||||
|
|
||||||
|
// sysex continuation data at the start of the packet?
|
||||||
|
if (pkt[ndecoded] & 0x80) == 0 {
|
||||||
|
mes.nbytes = IS_SYSEX;
|
||||||
|
if !decode_sysex_data(pkt, &mut mes, &mut self.from_ble, &mut ndecoded, 0) {
|
||||||
|
return ndecoded;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
while ndecoded < nbytes {
|
||||||
|
if ndecoded + 1 < nbytes {
|
||||||
|
if pkt[ndecoded] & 0x80 != 0 && pkt[ndecoded + 1] & 0x80 != 0 {
|
||||||
|
// timestamp + status byte (or rt inside sysex, or EOX)
|
||||||
|
if mes.nbytes & IS_SYSEX == 0 {
|
||||||
|
// not in sysex: timestamp + status
|
||||||
|
mes.timestamp_ms = timestamp_decode(&mut timestamp, pkt[ndecoded], &mut prev_lsb);
|
||||||
|
ndecoded += 1;
|
||||||
|
mes.msg_bytes[0] = pkt[ndecoded];
|
||||||
|
ndecoded += 1;
|
||||||
|
if mes.msg_bytes[0] >= 0xF8 {
|
||||||
|
// real-time
|
||||||
|
mes.nbytes = IS_REAL_TIME + 1;
|
||||||
|
if !from_ble_push(&mut self.from_ble, &mes) {
|
||||||
|
return ndecoded;
|
||||||
|
}
|
||||||
|
} else if mes.msg_bytes[0] > 0xF0 && mes.msg_bytes[0] <= 0xF7 {
|
||||||
|
// system common
|
||||||
|
if mes.msg_bytes[0] == 0xF1 || mes.msg_bytes[0] == 0xF3 {
|
||||||
|
mes.nbytes = 2;
|
||||||
|
} else if mes.msg_bytes[0] == 0xF2 {
|
||||||
|
mes.nbytes = 3;
|
||||||
|
} else {
|
||||||
|
mes.nbytes = 1;
|
||||||
|
}
|
||||||
|
if ndecoded + (mes.nbytes as usize) - 1 <= nbytes {
|
||||||
|
for idx in 1..mes.nbytes as usize {
|
||||||
|
mes.msg_bytes[idx] = pkt[ndecoded];
|
||||||
|
ndecoded += 1;
|
||||||
|
}
|
||||||
|
if !from_ble_push(&mut self.from_ble, &mes) {
|
||||||
|
ndecoded -= 1;
|
||||||
|
return ndecoded;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return ndecoded;
|
||||||
|
}
|
||||||
|
} else if mes.msg_bytes[0] < 0xF0 {
|
||||||
|
// channel message
|
||||||
|
running_status = mes.msg_bytes[0];
|
||||||
|
let stat = (mes.msg_bytes[0] >> 4) & 0xF;
|
||||||
|
if stat == 0xC || stat == 0xD {
|
||||||
|
mes.nbytes = 2;
|
||||||
|
running_status_nbytes = 2;
|
||||||
|
} else {
|
||||||
|
running_status_nbytes = 3;
|
||||||
|
}
|
||||||
|
if (running_status_nbytes as usize) + ndecoded - 1 <= nbytes {
|
||||||
|
for idx in 1..running_status_nbytes as usize {
|
||||||
|
mes.msg_bytes[idx] = pkt[ndecoded];
|
||||||
|
ndecoded += 1;
|
||||||
|
}
|
||||||
|
mes.nbytes = running_status_nbytes | IS_CHANNEL;
|
||||||
|
if !from_ble_push(&mut self.from_ble, &mes) {
|
||||||
|
ndecoded -= 1;
|
||||||
|
return ndecoded;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// not enough data; leave for next? C returns.
|
||||||
|
return ndecoded;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 0xF0: start of sysex
|
||||||
|
mes.nbytes = IS_SYSEX + 1;
|
||||||
|
if !decode_sysex_data(pkt, &mut mes, &mut self.from_ble, &mut ndecoded, 1) {
|
||||||
|
return ndecoded;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if pkt[ndecoded + 1] >= 0xF8 {
|
||||||
|
// real-time timestamp+status within a sysex
|
||||||
|
let bytecount = mes.nbytes & NBYTES_MASK;
|
||||||
|
if bytecount > 0 {
|
||||||
|
if !from_ble_push(&mut self.from_ble, &mes) {
|
||||||
|
ndecoded -= bytecount as usize;
|
||||||
|
return ndecoded;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut mes_rt = BleMidiMessage::default();
|
||||||
|
mes_rt.nbytes = IS_REAL_TIME + 1;
|
||||||
|
mes_rt.timestamp_ms = timestamp_decode(&mut timestamp, pkt[ndecoded], &mut prev_lsb);
|
||||||
|
ndecoded += 1;
|
||||||
|
mes_rt.msg_bytes[0] = pkt[ndecoded];
|
||||||
|
ndecoded += 1;
|
||||||
|
if !from_ble_push(&mut self.from_ble, &mes_rt) {
|
||||||
|
ndecoded -= 2;
|
||||||
|
return ndecoded;
|
||||||
|
}
|
||||||
|
// continue parsing sysex data after the rt interleave
|
||||||
|
mes.nbytes = IS_SYSEX;
|
||||||
|
let mut idx: u8 = 0;
|
||||||
|
while ndecoded < nbytes && (pkt[ndecoded] & 0x80) == 0 {
|
||||||
|
mes.msg_bytes[idx as usize] = pkt[ndecoded];
|
||||||
|
ndecoded += 1;
|
||||||
|
mes.nbytes += 1;
|
||||||
|
idx += 1;
|
||||||
|
if idx == 3 {
|
||||||
|
if !from_ble_push(&mut self.from_ble, &mes) {
|
||||||
|
ndecoded -= 3;
|
||||||
|
return ndecoded;
|
||||||
|
}
|
||||||
|
idx = 0;
|
||||||
|
mes.nbytes = IS_SYSEX;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let bytecount = mes.nbytes & NBYTES_MASK;
|
||||||
|
if bytecount > 0 {
|
||||||
|
if !from_ble_push(&mut self.from_ble, &mes) {
|
||||||
|
ndecoded -= bytecount as usize;
|
||||||
|
return ndecoded;
|
||||||
|
}
|
||||||
|
mes.nbytes = IS_SYSEX;
|
||||||
|
}
|
||||||
|
} else if pkt[ndecoded + 1] == 0xF7 {
|
||||||
|
// sysex ending: flush pending data; EOX handled next iter
|
||||||
|
let bytecount = mes.nbytes & NBYTES_MASK;
|
||||||
|
if bytecount > 0 {
|
||||||
|
if !from_ble_push(&mut self.from_ble, &mes) {
|
||||||
|
ndecoded -= bytecount as usize;
|
||||||
|
return ndecoded;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
mes.nbytes = 0; // clear is_sysex flag
|
||||||
|
}
|
||||||
|
// else: timestamp+status where status is not handled — fall through
|
||||||
|
} else if pkt[ndecoded] & 0x80 != 0 && pkt[ndecoded + 1] & 0x80 == 0 {
|
||||||
|
// running-status channel message: timestamp + data byte(s)
|
||||||
|
if running_status != 0 && ndecoded + running_status_nbytes as usize <= nbytes {
|
||||||
|
mes.timestamp_ms = timestamp_decode(&mut timestamp, pkt[ndecoded], &mut prev_lsb);
|
||||||
|
ndecoded += 1;
|
||||||
|
mes.msg_bytes[0] = running_status;
|
||||||
|
mes.nbytes = running_status_nbytes | IS_CHANNEL;
|
||||||
|
for idx in 1..running_status_nbytes as usize {
|
||||||
|
mes.msg_bytes[idx] = pkt[ndecoded];
|
||||||
|
ndecoded += 1;
|
||||||
|
}
|
||||||
|
if !from_ble_push(&mut self.from_ble, &mes) {
|
||||||
|
ndecoded -= running_status_nbytes as usize;
|
||||||
|
return ndecoded;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return ndecoded;
|
||||||
|
}
|
||||||
|
} else if pkt[ndecoded] & 0x80 == 0 && pkt[ndecoded + 1] & 0x80 == 0 {
|
||||||
|
// running status same as previous, same timestamp, new data
|
||||||
|
if running_status == mes.msg_bytes[0]
|
||||||
|
&& mes.nbytes & IS_CHANNEL != 0
|
||||||
|
&& ndecoded + running_status_nbytes as usize - 1 <= nbytes
|
||||||
|
{
|
||||||
|
for idx in 1..running_status_nbytes as usize {
|
||||||
|
mes.msg_bytes[idx] = pkt[ndecoded];
|
||||||
|
ndecoded += 1;
|
||||||
|
}
|
||||||
|
if !from_ble_push(&mut self.from_ble, &mes) {
|
||||||
|
ndecoded -= (running_status_nbytes as usize) - 1;
|
||||||
|
return ndecoded;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return ndecoded;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// only one byte left and not a timestamp+status pair — stop
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ndecoded
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pop the next decoded timestamped MIDI message.
|
||||||
|
pub fn pop_midi(&mut self) -> Option<BleMidiMessage> {
|
||||||
|
self.from_ble.pop()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Codec {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- free encode helpers (take stream + ring + mtu to avoid overlapping
|
||||||
|
// borrows of `self`) ----------------------------------------------------
|
||||||
|
|
||||||
|
fn discard_stream(s: &mut ToBleStream) {
|
||||||
|
s.next_msg_byte_idx = 0;
|
||||||
|
s.pending_ble_pkt.nbytes = 0;
|
||||||
|
s.previous_timestamp = 0xffff;
|
||||||
|
s.running_status = 0;
|
||||||
|
s.mes.nbytes = 0;
|
||||||
|
s.mes.timestamp_ms = 0xffff;
|
||||||
|
s.npending_rt = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add_header_if_needed(pkt: &mut BleMidiPacket, timestamp: u16) {
|
||||||
|
if pkt.nbytes == 0 {
|
||||||
|
pkt.pkt[pkt.nbytes] = header(timestamp);
|
||||||
|
pkt.nbytes += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn flush_rt_midi_to_pkt(s: &mut ToBleStream, to_ble: &mut Ring<BleMidiPacket, 10>, ble_mtu: usize) {
|
||||||
|
for idx in 0..s.npending_rt as usize {
|
||||||
|
// make room for a 2-byte (timestamp + status) real-time entry
|
||||||
|
if s.pending_ble_pkt.nbytes + 2 >= ble_mtu {
|
||||||
|
to_ble.push(s.pending_ble_pkt);
|
||||||
|
s.pending_ble_pkt.nbytes = 0;
|
||||||
|
s.pending_ble_midi_pkt_running_status = 0;
|
||||||
|
s.pending_ble_midi_pkt_prev_status = 0;
|
||||||
|
}
|
||||||
|
if s.pending_ble_pkt.nbytes == 0 {
|
||||||
|
s.pending_ble_pkt.pkt[s.pending_ble_pkt.nbytes] = header(s.pending_rt_timestamp[0]);
|
||||||
|
s.pending_ble_pkt.nbytes += 1;
|
||||||
|
}
|
||||||
|
s.pending_ble_pkt.pkt[s.pending_ble_pkt.nbytes] = timestamp_low(s.pending_rt_timestamp[idx]);
|
||||||
|
s.pending_ble_pkt.nbytes += 1;
|
||||||
|
s.pending_ble_pkt.pkt[s.pending_ble_pkt.nbytes] = s.pending_rt_status[idx];
|
||||||
|
s.pending_ble_pkt.nbytes += 1;
|
||||||
|
s.pending_ble_midi_pkt_prev_status = s.pending_rt_status[idx];
|
||||||
|
}
|
||||||
|
s.npending_rt = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn encode_bt_pkt(s: &mut ToBleStream, to_ble: &mut Ring<BleMidiPacket, 10>, ble_mtu: usize) {
|
||||||
|
let nbytes = s.mes.nbytes & NBYTES_MASK;
|
||||||
|
if nbytes == 0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if s.mes.nbytes & IS_REAL_TIME != IS_REAL_TIME {
|
||||||
|
flush_rt_midi_to_pkt(s, to_ble, ble_mtu);
|
||||||
|
}
|
||||||
|
|
||||||
|
// channel messages may omit the status byte if running status matches
|
||||||
|
let requires_byte0 = (s.mes.nbytes & IS_CHANNEL != IS_CHANNEL)
|
||||||
|
|| (s.pending_ble_midi_pkt_running_status != s.mes.msg_bytes[0]);
|
||||||
|
|
||||||
|
// most messages need a timestamp prefix
|
||||||
|
let mut needs_timestamp = (s.mes.nbytes & (IS_SYSEX | IS_START_SYSEX) != IS_SYSEX)
|
||||||
|
&& (requires_byte0 || s.previous_timestamp != s.mes.timestamp_ms);
|
||||||
|
if !needs_timestamp
|
||||||
|
&& s.mes.nbytes & IS_CHANNEL == IS_CHANNEL
|
||||||
|
&& s.pending_ble_midi_pkt_prev_status != s.pending_ble_midi_pkt_running_status
|
||||||
|
{
|
||||||
|
needs_timestamp = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
let first_byte_idx: u8 = if requires_byte0 { 0 } else { 1 };
|
||||||
|
let total_bytes = nbytes as usize + (if needs_timestamp { 1 } else { 0 }) - first_byte_idx as usize;
|
||||||
|
|
||||||
|
if s.pending_ble_pkt.nbytes + total_bytes >= ble_mtu {
|
||||||
|
to_ble.push(s.pending_ble_pkt);
|
||||||
|
s.pending_ble_pkt.nbytes = 0;
|
||||||
|
s.pending_ble_midi_pkt_running_status = 0;
|
||||||
|
s.pending_ble_midi_pkt_prev_status = 0;
|
||||||
|
needs_timestamp = true;
|
||||||
|
// requires_byte0 is set true in the C here but only used above; keep
|
||||||
|
// first_byte_idx consistent by re-evaluating would change total_bytes.
|
||||||
|
// The C sets requires_byte0=true after the flush but does not recompute
|
||||||
|
// first_byte_idx/total_bytes, so neither do we.
|
||||||
|
}
|
||||||
|
|
||||||
|
if s.mes.nbytes & IS_CHANNEL != 0 {
|
||||||
|
s.pending_ble_midi_pkt_running_status = s.mes.msg_bytes[0];
|
||||||
|
}
|
||||||
|
if s.mes.msg_bytes[0] & 0x80 != 0 {
|
||||||
|
s.pending_ble_midi_pkt_prev_status = s.mes.msg_bytes[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
add_header_if_needed(&mut s.pending_ble_pkt, s.mes.timestamp_ms);
|
||||||
|
if needs_timestamp {
|
||||||
|
s.pending_ble_pkt.pkt[s.pending_ble_pkt.nbytes] = timestamp_low(s.mes.timestamp_ms);
|
||||||
|
s.pending_ble_pkt.nbytes += 1;
|
||||||
|
}
|
||||||
|
for idx in first_byte_idx as usize..nbytes as usize {
|
||||||
|
s.pending_ble_pkt.pkt[s.pending_ble_pkt.nbytes] = s.mes.msg_bytes[idx];
|
||||||
|
s.pending_ble_pkt.nbytes += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn encode_full_bt_pkt(s: &mut ToBleStream, to_ble: &mut Ring<BleMidiPacket, 10>, ble_mtu: usize) {
|
||||||
|
encode_bt_pkt(s, to_ble, ble_mtu);
|
||||||
|
s.next_msg_byte_idx = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- free decode helpers --------------------------------------------------
|
||||||
|
|
||||||
|
fn from_ble_push(ring: &mut Ring<BleMidiMessage, 100>, mes: &BleMidiMessage) -> bool {
|
||||||
|
ring.push(*mes)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reconstruct a 14-bit timestamp from the accumulated 13-bit MSB and a 7-bit
|
||||||
|
/// LSB, incrementing the MSB when the LSB wraps backward.
|
||||||
|
fn timestamp_decode(msb: &mut u16, lsb_byte: u8, prev_lsb: &mut u8) -> u16 {
|
||||||
|
let lsb = lsb_byte;
|
||||||
|
if *prev_lsb > lsb {
|
||||||
|
*msb += 1;
|
||||||
|
}
|
||||||
|
*prev_lsb = lsb;
|
||||||
|
(*msb << 7) | (lsb as u16 & 0x7F)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decode sysex data bytes (MSB clear) starting at `start_idx` into `mes`,
|
||||||
|
/// flushing 3-byte chunks to the ring. Returns false if the ring is full.
|
||||||
|
fn decode_sysex_data(
|
||||||
|
pkt: &[u8],
|
||||||
|
mes: &mut BleMidiMessage,
|
||||||
|
ring: &mut Ring<BleMidiMessage, 100>,
|
||||||
|
ndecoded: &mut usize,
|
||||||
|
start_idx: u8,
|
||||||
|
) -> bool {
|
||||||
|
let mut idx = start_idx;
|
||||||
|
while *ndecoded < pkt.len() && (pkt[*ndecoded] & 0x80) == 0 {
|
||||||
|
mes.msg_bytes[idx as usize] = pkt[*ndecoded];
|
||||||
|
*ndecoded += 1;
|
||||||
|
mes.nbytes += 1;
|
||||||
|
idx += 1;
|
||||||
|
if idx == 3 {
|
||||||
|
if !ring.push(*mes) {
|
||||||
|
*ndecoded -= 3;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
idx = 0;
|
||||||
|
mes.nbytes = IS_SYSEX;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let bytecount = mes.nbytes & NBYTES_MASK;
|
||||||
|
if bytecount > 0 {
|
||||||
|
if !ring.push(*mes) {
|
||||||
|
*ndecoded -= bytecount as usize;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// keep tracking an unterminated sysex message
|
||||||
|
mes.nbytes = IS_SYSEX;
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
//! Pimoroni Pico RGB Keypad driver — Rust port of `pico_rgb_keypad.cpp`.
|
||||||
|
//!
|
||||||
|
//! Copyright (C) 2026 Nils — SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
//! This file is part of pico-pi-midi. See LICENSE for the full notice.
|
||||||
|
//!
|
||||||
|
//! Hardware: 16 APA102-style RGB LEDs driven over SPI (CS=17, SCK=18, MOSI=19)
|
||||||
|
//! and a 16-bit button state read over I2C from a GPIO expander at address
|
||||||
|
//! 0x20 (SDA=4, SCL=5). Reading register 0 returns two bytes (little-endian
|
||||||
|
//! button bitmap); the C driver inverts them so a pressed pad reads as 1.
|
||||||
|
//!
|
||||||
|
//! APA102 frame: 4 start bytes (0x00), then per-LED 4 bytes
|
||||||
|
//! (0xE0|brightness, B, G, R), then a 4-byte end frame (0xFF). Total 72 bytes,
|
||||||
|
//! matching the C buffer layout `[start(4)][led0(4)]..[led15(4)][end(4)]`.
|
||||||
|
|
||||||
|
use embassy_rp::gpio::Output;
|
||||||
|
use embassy_rp::i2c::{self, Blocking as I2cBlocking};
|
||||||
|
use embassy_rp::spi::{self, Blocking as SpiBlocking};
|
||||||
|
|
||||||
|
pub const NUM_PADS: usize = 16;
|
||||||
|
const KEYPAD_ADDRESS: u8 = 0x20;
|
||||||
|
|
||||||
|
/// 5-bit global brightness (0..=31), stored in each LED's frame header.
|
||||||
|
/// `set_brightness(1.0)` in the C driver -> 0b11111.
|
||||||
|
const BRIGHTNESS: u8 = 0b11111;
|
||||||
|
|
||||||
|
pub struct RgbKeypad {
|
||||||
|
cs: Output<'static>,
|
||||||
|
spi: spi::Spi<'static, SpiBlocking>,
|
||||||
|
i2c: i2c::I2c<'static, I2cBlocking>,
|
||||||
|
/// APA102 frame buffer: 4 start + 16*4 LED + 4 end = 72 bytes.
|
||||||
|
buffer: [u8; 4 + NUM_PADS * 4 + 4],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RgbKeypad {
|
||||||
|
/// Build the driver from already-constructed SPI (tx-only), I2C and CS
|
||||||
|
/// output. The peripherals are consumed in `main` and the resulting driver
|
||||||
|
/// is `'static`, so it can be moved into an embassy task.
|
||||||
|
pub fn new(
|
||||||
|
cs: Output<'static>,
|
||||||
|
spi: spi::Spi<'static, SpiBlocking>,
|
||||||
|
i2c: i2c::I2c<'static, I2cBlocking>,
|
||||||
|
) -> Self {
|
||||||
|
let mut s = Self {
|
||||||
|
cs,
|
||||||
|
spi,
|
||||||
|
i2c,
|
||||||
|
buffer: [0; 4 + NUM_PADS * 4 + 4],
|
||||||
|
};
|
||||||
|
|
||||||
|
// APA102 start frame: 0x00 0x00 0x00 0x00.
|
||||||
|
s.buffer[0..4].copy_from_slice(&[0x00, 0x00, 0x00, 0x00]);
|
||||||
|
// Per-LED brightness header (0xE0 | 5-bit brightness); RGB stays 0 (off).
|
||||||
|
for i in 0..NUM_PADS {
|
||||||
|
s.buffer[4 + i * 4] = 0xE0 | BRIGHTNESS;
|
||||||
|
}
|
||||||
|
// End frame: 0xFF 0xFF 0xFF 0xFF (>= 1 bit per 2 LEDs).
|
||||||
|
let end = 4 + NUM_PADS * 4;
|
||||||
|
s.buffer[end..end + 4].copy_from_slice(&[0xFF, 0xFF, 0xFF, 0xFF]);
|
||||||
|
|
||||||
|
s.update();
|
||||||
|
s
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Push the frame buffer to the LEDs over SPI.
|
||||||
|
pub fn update(&mut self) {
|
||||||
|
self.cs.set_low();
|
||||||
|
let _ = self.spi.blocking_write(&self.buffer);
|
||||||
|
self.cs.set_high();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set an LED by linear index `i` (0..16) to `(r, g, b)`. Mirrors the C
|
||||||
|
/// `illuminate(i, r, g, b)`: frame byte order is brightness,B,G,R.
|
||||||
|
pub fn illuminate(&mut self, i: usize, r: u8, g: u8, b: u8) {
|
||||||
|
if i >= NUM_PADS {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let off = 4 + i * 4;
|
||||||
|
// [0]=brightness (already set), [1]=B, [2]=G, [3]=R
|
||||||
|
self.buffer[off + 1] = b;
|
||||||
|
self.buffer[off + 2] = g;
|
||||||
|
self.buffer[off + 3] = r;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read the 16-bit button state bitmap. Bit `i` is 1 when pad `i` is
|
||||||
|
/// pressed (the raw expander value is inverted, matching the C driver).
|
||||||
|
pub fn get_button_states(&mut self) -> u16 {
|
||||||
|
let mut buf = [0u8; 2];
|
||||||
|
// Write register 0, then read 2 bytes (repeated-start, like the C code).
|
||||||
|
let _ = self
|
||||||
|
.i2c
|
||||||
|
.blocking_write_read(KEYPAD_ADDRESS, &[0x00], &mut buf);
|
||||||
|
// C returns ~((buf[0]) | (buf[1] << 8))
|
||||||
|
!(u16::from(buf[0]) | (u16::from(buf[1]) << 8))
|
||||||
|
}
|
||||||
|
}
|
||||||
+394
@@ -0,0 +1,394 @@
|
|||||||
|
//! RGB MIDI Keypad — Rust port for Raspberry Pi Pico W (RP2040 + CYW43439).
|
||||||
|
//!
|
||||||
|
//! Copyright (C) 2026 Nils
|
||||||
|
//!
|
||||||
|
//! This program is free software: you can redistribute it and/or modify
|
||||||
|
//! it under the terms of the GNU General Public License as published by
|
||||||
|
//! the Free Software Foundation, either version 3 of the License, or
|
||||||
|
//! (at your option) any later version.
|
||||||
|
//!
|
||||||
|
//! This program is distributed in the hope that it will be useful,
|
||||||
|
//! but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
//! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
//! GNU General Public License for more details.
|
||||||
|
//!
|
||||||
|
//! You should have received a copy of the GNU General Public License
|
||||||
|
//! along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
//!
|
||||||
|
//! SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
//!
|
||||||
|
//! Wires the Pimoroni RGB Keypad (16 pads + APA102 LEDs) to a BLE-MIDI 1.0
|
||||||
|
//! GATT service so pad presses send Note On/Off over Bluetooth MIDI and
|
||||||
|
//! incoming Note messages light the pads.
|
||||||
|
//!
|
||||||
|
//! Concurrency:
|
||||||
|
//! - `cyw43_task` : drives the CYW43 controller (WiFi+BT firmware).
|
||||||
|
//! - `led_task` : blinks the onboard LED as a heartbeat.
|
||||||
|
//! - `keypad_task` : polls pads, sends Note On/Off on `OUTBOUND`, lights pads
|
||||||
|
//! from `INBOUND`.
|
||||||
|
//! - main (BLE) : runs the trouble host; advertises, accepts a connection,
|
||||||
|
//! and pumps MIDI in both directions through the codec.
|
||||||
|
|
||||||
|
#![no_std]
|
||||||
|
#![no_main]
|
||||||
|
|
||||||
|
use cyw43::Cyw43439;
|
||||||
|
use cyw43_pio::PioSpi;
|
||||||
|
use defmt::*;
|
||||||
|
use embassy_executor::Spawner;
|
||||||
|
use embassy_futures::join::join;
|
||||||
|
use embassy_futures::select::{select, Either};
|
||||||
|
use embassy_rp::gpio::{Level, Output};
|
||||||
|
use embassy_rp::peripherals::{DMA_CH0, DMA_CH1, PIO0, USB};
|
||||||
|
use embassy_rp::pio::{InterruptHandler, Pio};
|
||||||
|
use embassy_rp::usb::{Driver, InterruptHandler as UsbInterruptHandler};
|
||||||
|
use embassy_rp::{bind_interrupts, dma};
|
||||||
|
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||||
|
use embassy_sync::channel::{Channel, Receiver, Sender};
|
||||||
|
use embassy_time::{Instant, Timer};
|
||||||
|
use heapless::Vec;
|
||||||
|
use static_cell::StaticCell;
|
||||||
|
use trouble_host::prelude::*;
|
||||||
|
use {defmt_rtt as _, panic_probe as _};
|
||||||
|
|
||||||
|
mod codec;
|
||||||
|
mod keypad;
|
||||||
|
mod midi_keypad;
|
||||||
|
mod octave;
|
||||||
|
|
||||||
|
use keypad::RgbKeypad;
|
||||||
|
use midi_keypad::{MidiKeypad, MidiOut};
|
||||||
|
|
||||||
|
bind_interrupts!(struct Irqs {
|
||||||
|
PIO0_IRQ_0 => InterruptHandler<PIO0>;
|
||||||
|
DMA_IRQ_0 => dma::InterruptHandler<DMA_CH0>, dma::InterruptHandler<DMA_CH1>;
|
||||||
|
USBCTRL_IRQ => UsbInterruptHandler<USB>;
|
||||||
|
});
|
||||||
|
|
||||||
|
#[embassy_executor::task]
|
||||||
|
async fn logger_task(driver: Driver<'static, USB>) {
|
||||||
|
embassy_usb_logger::run!(1024, log::LevelFilter::Info, driver);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Max number of simultaneous BLE connections.
|
||||||
|
const CONNECTIONS_MAX: usize = 1;
|
||||||
|
/// Max L2CAP channels ( signalling + ATT ).
|
||||||
|
const L2CAP_CHANNELS_MAX: usize = 2;
|
||||||
|
|
||||||
|
/// Keypad -> BLE: each entry is a 3-byte Note On/Off message.
|
||||||
|
static OUTBOUND: Channel<CriticalSectionRawMutex, [u8; 3], 16> = Channel::new();
|
||||||
|
/// BLE -> keypad: each entry is a 3-byte channel message to light a pad.
|
||||||
|
static INBOUND: Channel<CriticalSectionRawMutex, [u8; 3], 16> = Channel::new();
|
||||||
|
|
||||||
|
// ---- BLE-MIDI 1.0 GATT service definition --------------------------------
|
||||||
|
//
|
||||||
|
// Service: 03B80E5A-EDE8-4B33-A751-6CE34EC4C700 (MIDI Service)
|
||||||
|
// Char: 7772E5DB-3868-4112-A1A9-F2669D106BF3 (MIDI I/O)
|
||||||
|
// Props: read | write-without-response | notify
|
||||||
|
#[gatt_server]
|
||||||
|
struct Server {
|
||||||
|
midi_service: MidiService,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[gatt_service(uuid = "03b80e5a-ede8-4b33-a751-6ce34ec4c700")]
|
||||||
|
struct MidiService {
|
||||||
|
#[characteristic(uuid = "7772e5db-3868-4112-a1a9-f2669d106bf3", read, write_without_response, notify)]
|
||||||
|
midi_io: (),
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- CYW43 runner + heartbeat tasks --------------------------------------
|
||||||
|
|
||||||
|
#[embassy_executor::task]
|
||||||
|
async fn cyw43_task(
|
||||||
|
runner: cyw43::Runner<
|
||||||
|
'static,
|
||||||
|
cyw43::SpiBus<Output<'static>, PioSpi<'static, PIO0, 0>>,
|
||||||
|
Cyw43439,
|
||||||
|
>,
|
||||||
|
) {
|
||||||
|
runner.run().await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[embassy_executor::task]
|
||||||
|
async fn led_task(mut control: cyw43::Control<'static>) {
|
||||||
|
loop {
|
||||||
|
control.gpio_set(0, true).await;
|
||||||
|
Timer::after_millis(80).await;
|
||||||
|
control.gpio_set(0, false).await;
|
||||||
|
Timer::after_millis(920).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Poll the keypad: send Note On/Off for changed pads, light pads from inbound
|
||||||
|
/// MIDI, repeat every 10ms (matching the C main loop cadence).
|
||||||
|
#[embassy_executor::task]
|
||||||
|
async fn keypad_task(mut keypad: RgbKeypad, mut bootsel: embassy_rp::Peri<'static, embassy_rp::peripherals::BOOTSEL>) {
|
||||||
|
// Startup blink: all LEDs white, then off — a visible "main is alive and
|
||||||
|
// the keypad/SPI driver works" signal that does not depend on the radio.
|
||||||
|
for i in 0..keypad::NUM_PADS {
|
||||||
|
keypad.illuminate(i, 64, 64, 64);
|
||||||
|
}
|
||||||
|
keypad.update();
|
||||||
|
Timer::after_millis(400).await;
|
||||||
|
|
||||||
|
let mut midi = MidiKeypad::new(&mut keypad, 48); // note offset C3; paints underlay
|
||||||
|
let mut out_buf: Vec<MidiOut, 16> = Vec::new();
|
||||||
|
let outbound = OUTBOUND.sender();
|
||||||
|
let inbound = INBOUND.receiver();
|
||||||
|
let mut note_offset: u8 = 48;
|
||||||
|
let mut bootsel_held = false;
|
||||||
|
|
||||||
|
loop {
|
||||||
|
// 1. read pads -> Note On/Off. Each message is routed two ways, matching
|
||||||
|
// the C firmware's connect_ports("MidiKeypad","MidiKeypad") local
|
||||||
|
// feedback + connect_ports("MidiKeypad","BluetoothMidi"):
|
||||||
|
// (a) local: light the pressed pad immediately,
|
||||||
|
// (b) outbound: send to the BLE side to notify the host.
|
||||||
|
out_buf.clear();
|
||||||
|
midi.update(&mut keypad, &mut out_buf);
|
||||||
|
for m in out_buf.iter() {
|
||||||
|
midi.receive_midi_message(&mut keypad, &m.bytes);
|
||||||
|
let _ = outbound.try_send(m.bytes);
|
||||||
|
}
|
||||||
|
out_buf.clear();
|
||||||
|
|
||||||
|
// 2. light pads from inbound MIDI (host -> keypad)
|
||||||
|
while let Ok(msg) = inbound.try_receive() {
|
||||||
|
midi.receive_midi_message(&mut keypad, &msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. BOOTSEL: cycle octave +12 (wrap at 120) and flash the octave digit.
|
||||||
|
// Edge-triggered so one press = one step (C firmware re-checked every
|
||||||
|
// loop while held, which multi-triggered; we debounce to a press edge).
|
||||||
|
let pressed = embassy_rp::bootsel::is_bootsel_pressed(bootsel.reborrow());
|
||||||
|
if pressed && !bootsel_held {
|
||||||
|
note_offset = (note_offset + 12) % 120;
|
||||||
|
midi.set_note_offset(&mut keypad, note_offset);
|
||||||
|
crate::octave::display_active_octave(&mut midi, &mut keypad, note_offset).await;
|
||||||
|
}
|
||||||
|
bootsel_held = pressed;
|
||||||
|
|
||||||
|
Timer::after_millis(10).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- TrouBLE host runner --------------------------------------------------
|
||||||
|
|
||||||
|
async fn ble_task<C: Controller, P: PacketPool>(mut runner: Runner<'_, C, P>) {
|
||||||
|
loop {
|
||||||
|
if let Err(e) = runner.run().await {
|
||||||
|
log::error!("[ble_task] runner error: {:?}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Advertising ----------------------------------------------------------
|
||||||
|
|
||||||
|
async fn advertise<'a, 'b, C: Controller>(
|
||||||
|
peripheral: &mut Peripheral<'a, C, DefaultPacketPool>,
|
||||||
|
server: &'b Server<'a>,
|
||||||
|
) -> Result<GattConnection<'a, 'b, DefaultPacketPool>, BleHostError<C::Error>> {
|
||||||
|
// adv_data: Flags + MIDI service UUID (so MIDI hosts auto-discover).
|
||||||
|
// scan_data: device name (won't fit in adv_data alongside the 128-bit UUID).
|
||||||
|
let mut advertiser_data = [0u8; 31];
|
||||||
|
let mut scan_response = [0u8; 31];
|
||||||
|
// MIDI Service UUID 03B80E5A-EDE8-4B33-A751-6CE34EC4C700, little-endian.
|
||||||
|
let midi_service_uuid: [u8; 16] = [
|
||||||
|
0x00, 0xc7, 0xc4, 0x4e, 0xe3, 0x6c, 0x51, 0xa7, 0x33, 0x4b, 0xe8, 0xed, 0x5a, 0x0e, 0xb8,
|
||||||
|
0x03,
|
||||||
|
];
|
||||||
|
let adv_len = AdStructure::encode_slice(
|
||||||
|
&[
|
||||||
|
AdStructure::Flags(LE_GENERAL_DISCOVERABLE | BR_EDR_NOT_SUPPORTED),
|
||||||
|
AdStructure::CompleteServiceUuids128(&[midi_service_uuid]),
|
||||||
|
],
|
||||||
|
&mut advertiser_data[..],
|
||||||
|
)?;
|
||||||
|
let scan_len = AdStructure::encode_slice(
|
||||||
|
&[AdStructure::CompleteLocalName("BLE-RGB Keypad".as_bytes())],
|
||||||
|
&mut scan_response[..],
|
||||||
|
)?;
|
||||||
|
log::info!("[adv] starting advertise...");
|
||||||
|
let advertiser = peripheral
|
||||||
|
.advertise(
|
||||||
|
&Default::default(),
|
||||||
|
Advertisement::ConnectableScannableUndirected {
|
||||||
|
adv_data: &advertiser_data[..adv_len],
|
||||||
|
scan_data: &scan_response[..scan_len],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
log::info!("[adv] advertising as 'BLE-RGB Keypad'");
|
||||||
|
let conn = advertiser.accept().await?.with_attribute_server(server)?;
|
||||||
|
log::info!("[adv] connection established");
|
||||||
|
Ok(conn)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Connection: pump MIDI both ways -------------------------------------
|
||||||
|
|
||||||
|
async fn run_connection<'a, 'b, P: PacketPool>(
|
||||||
|
conn: &GattConnection<'a, 'b, P>,
|
||||||
|
server: &'b Server<'a>,
|
||||||
|
codec: &mut codec::Codec,
|
||||||
|
outbound: &Receiver<'static, CriticalSectionRawMutex, [u8; 3], 16>,
|
||||||
|
inbound: &Sender<'static, CriticalSectionRawMutex, [u8; 3], 16>,
|
||||||
|
) {
|
||||||
|
let midi_handle = server.midi_service.midi_io.handle;
|
||||||
|
let midi_io = &server.midi_service.midi_io;
|
||||||
|
|
||||||
|
loop {
|
||||||
|
match select(conn.next(), outbound.receive()).await {
|
||||||
|
Either::First(ev) => match ev {
|
||||||
|
GattConnectionEvent::Disconnected { reason } => {
|
||||||
|
info!("[gatt] disconnected: {:?}", reason);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
GattConnectionEvent::Gatt { event } => {
|
||||||
|
let reply = match event {
|
||||||
|
GattEvent::Write(e) => {
|
||||||
|
if e.handle() == midi_handle {
|
||||||
|
// Copy the written bytes out, then decode.
|
||||||
|
let mut buf = [0u8; codec::MAX_BLE_MIDI_PACKET];
|
||||||
|
let mut len = 0usize;
|
||||||
|
e.with_data(|_offset, data| {
|
||||||
|
len = data.len().min(buf.len());
|
||||||
|
buf[..len].copy_from_slice(&data[..len]);
|
||||||
|
});
|
||||||
|
codec.decode_push(&buf[..len]);
|
||||||
|
while let Some(m) = codec.pop_midi() {
|
||||||
|
let bc = m.byte_count() as usize;
|
||||||
|
if bc == 3 {
|
||||||
|
let _ = inbound.try_send(m.msg_bytes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
e.accept()
|
||||||
|
}
|
||||||
|
other => other.accept(),
|
||||||
|
};
|
||||||
|
if let Ok(reply) = reply {
|
||||||
|
let _ = reply.send().await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
},
|
||||||
|
Either::Second(msg) => {
|
||||||
|
// Outbound Note On/Off: stamp + encode + notify.
|
||||||
|
let now = Instant::now().as_millis() as u16;
|
||||||
|
let (_, ready) = codec.push_midi(&msg, now);
|
||||||
|
if ready {
|
||||||
|
while let Some(pkt) = codec.ble_pkt_pop() {
|
||||||
|
let _ = midi_io.notify_raw(conn, &pkt.pkt[..pkt.nbytes], false).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- main -----------------------------------------------------------------
|
||||||
|
|
||||||
|
#[embassy_executor::main]
|
||||||
|
async fn main(spawner: Spawner) {
|
||||||
|
let p = embassy_rp::init(Default::default());
|
||||||
|
info!("[boot] embassy_rp initialised");
|
||||||
|
|
||||||
|
// ---- USB serial logger (routes log::info!/error! to the serial port) -
|
||||||
|
let driver = Driver::new(p.USB, Irqs);
|
||||||
|
let _ = spawner.spawn(unwrap!(logger_task(driver)));
|
||||||
|
info!("[boot] usb logger task spawned");
|
||||||
|
|
||||||
|
// ---- Keypad task FIRST (I2C0 + SPI0; independent of the radio) ------
|
||||||
|
let mut kp_spi_cfg = embassy_rp::spi::Config::default();
|
||||||
|
kp_spi_cfg.frequency = 4_000_000;
|
||||||
|
let kp_spi = embassy_rp::spi::Spi::new_blocking_txonly(p.SPI0, p.PIN_18, p.PIN_19, kp_spi_cfg);
|
||||||
|
let mut kp_i2c_cfg = embassy_rp::i2c::Config::default();
|
||||||
|
kp_i2c_cfg.frequency = 400_000;
|
||||||
|
kp_i2c_cfg.sda_pullup = true;
|
||||||
|
kp_i2c_cfg.scl_pullup = true;
|
||||||
|
let kp_i2c = embassy_rp::i2c::I2c::new_blocking(p.I2C0, p.PIN_5, p.PIN_4, kp_i2c_cfg);
|
||||||
|
let kp_cs = Output::new(p.PIN_17, Level::High);
|
||||||
|
let keypad = RgbKeypad::new(kp_cs, kp_spi, kp_i2c);
|
||||||
|
let _ = spawner.spawn(unwrap!(keypad_task(keypad, p.BOOTSEL)));
|
||||||
|
info!("[boot] keypad task spawned");
|
||||||
|
|
||||||
|
// ---- CYW43 firmware blobs (committed under cyw43-firmware/) -----------
|
||||||
|
let fw = cyw43::aligned_bytes!("../cyw43-firmware/43439A0.bin");
|
||||||
|
let clm = cyw43::aligned_bytes!("../cyw43-firmware/43439A0_clm.bin");
|
||||||
|
let btfw = cyw43::aligned_bytes!("../cyw43-firmware/43439A0_btfw.bin");
|
||||||
|
let nvram = cyw43::aligned_bytes!("../cyw43-firmware/nvram_rp2040.bin");
|
||||||
|
|
||||||
|
// ---- CYW43 PIO-SPI bus (Pico W wiring) -------------------------------
|
||||||
|
let pwr = Output::new(p.PIN_23, Level::Low);
|
||||||
|
let cs = Output::new(p.PIN_25, Level::High);
|
||||||
|
let mut pio = Pio::new(p.PIO0, Irqs);
|
||||||
|
let spi = PioSpi::new(
|
||||||
|
&mut pio.common,
|
||||||
|
pio.sm0,
|
||||||
|
cyw43_pio::DEFAULT_CLOCK_DIVIDER,
|
||||||
|
pio.irq0,
|
||||||
|
cs,
|
||||||
|
p.PIN_24,
|
||||||
|
p.PIN_29,
|
||||||
|
dma::Channel::new(p.DMA_CH0, Irqs),
|
||||||
|
dma::Channel::new(p.DMA_CH1, Irqs),
|
||||||
|
);
|
||||||
|
|
||||||
|
static STATE: StaticCell<cyw43::State> = StaticCell::new();
|
||||||
|
let state = STATE.init(cyw43::State::new());
|
||||||
|
|
||||||
|
let (_net_device, bt_device, mut control, runner) =
|
||||||
|
cyw43::new_with_bluetooth(state, pwr, spi, fw, btfw, nvram).await;
|
||||||
|
let _ = spawner.spawn(unwrap!(cyw43_task(runner)));
|
||||||
|
control.init(clm).await;
|
||||||
|
log::info!("[cyw43] initialised");
|
||||||
|
|
||||||
|
let _ = spawner.spawn(unwrap!(led_task(control)));
|
||||||
|
|
||||||
|
// ---- TrouBLE BLE host -------------------------------------------------
|
||||||
|
let controller: ExternalController<_, 10> = ExternalController::new(bt_device);
|
||||||
|
let address: Address = Address::random([0xff, 0x8f, 0x1a, 0x05, 0xe4, 0xff]);
|
||||||
|
log::info!("[ble] controller wrapped, address set");
|
||||||
|
|
||||||
|
static RES: StaticCell<HostResources<DefaultPacketPool, CONNECTIONS_MAX, L2CAP_CHANNELS_MAX>> =
|
||||||
|
StaticCell::new();
|
||||||
|
let resources = RES.init(HostResources::new());
|
||||||
|
log::info!("[ble] building stack...");
|
||||||
|
let stack = trouble_host::new(controller, resources)
|
||||||
|
.set_random_address(address)
|
||||||
|
.build();
|
||||||
|
log::info!("[ble] stack built");
|
||||||
|
let runner = stack.runner();
|
||||||
|
let mut peripheral = stack.peripheral();
|
||||||
|
log::info!("[ble] peripheral acquired");
|
||||||
|
|
||||||
|
let server = Server::new_with_config(GapConfig::Peripheral(PeripheralConfig {
|
||||||
|
name: "BLE-RGB Keypad",
|
||||||
|
appearance: &appearance::power_device::GENERIC_POWER_DEVICE,
|
||||||
|
}))
|
||||||
|
.unwrap();
|
||||||
|
log::info!("[ble] gatt server built");
|
||||||
|
|
||||||
|
let outbound = OUTBOUND.receiver();
|
||||||
|
let inbound = INBOUND.sender();
|
||||||
|
log::info!("[ble] entering advertise loop");
|
||||||
|
|
||||||
|
join(ble_task(runner), async {
|
||||||
|
let mut codec = codec::Codec::new();
|
||||||
|
loop {
|
||||||
|
match advertise(&mut peripheral, &server).await {
|
||||||
|
Ok(conn) => {
|
||||||
|
log::info!("[ble] connected");
|
||||||
|
// Fresh codec state per connection.
|
||||||
|
codec = codec::Codec::new();
|
||||||
|
run_connection(&conn, &server, &mut codec, &outbound, &inbound).await;
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("[adv] error: {:?}", e);
|
||||||
|
Timer::after_millis(500).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
}
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
//! MIDI keypad state machine — Rust port of `MidiKeypad.cpp`.
|
||||||
|
//!
|
||||||
|
//! Copyright (C) 2026 Nils — SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
//! This file is part of pico-pi-midi. See LICENSE for the full notice.
|
||||||
|
//!
|
||||||
|
//! Reads the 16-pad button matrix from [`RgbKeypad`], turns presses/releases
|
||||||
|
//! into Note On/Off MIDI messages, and lights pads in response to incoming
|
||||||
|
//! Note messages. The underlay colours distinguish root / white / black keys
|
||||||
|
//! within the current octave, and an overlay can temporarily take over the
|
||||||
|
//! LEDs (used by the octave display).
|
||||||
|
|
||||||
|
use crate::keypad::{RgbKeypad, NUM_PADS};
|
||||||
|
|
||||||
|
/// Root note (MIDI note number where the keypad's pad 0 starts).
|
||||||
|
pub type NoteOffset = u8;
|
||||||
|
|
||||||
|
/// A MIDI message to send (Note On / Note Off here, 3 bytes each).
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
pub struct MidiOut {
|
||||||
|
pub bytes: [u8; 3],
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Flip a 4x4 grid index so that physical pad 0 (top-left) maps to the
|
||||||
|
/// bottom-left note, matching the C `transform_index`.
|
||||||
|
fn transform_index(i: usize) -> usize {
|
||||||
|
let row = i / 4;
|
||||||
|
let column = i % 4;
|
||||||
|
(3 - row) * 4 + column
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct MidiKeypad {
|
||||||
|
pub note_offset: NoteOffset,
|
||||||
|
previous_button_states: u16,
|
||||||
|
/// RGB underlay colour per physical pad index.
|
||||||
|
underlay_colors: [[u8; 3]; NUM_PADS],
|
||||||
|
overlay_active: bool,
|
||||||
|
underlay_active: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MidiKeypad {
|
||||||
|
pub fn new(keypad: &mut RgbKeypad, note_offset: NoteOffset) -> Self {
|
||||||
|
let mut s = Self {
|
||||||
|
note_offset,
|
||||||
|
previous_button_states: 0,
|
||||||
|
underlay_colors: [[0; 3]; NUM_PADS],
|
||||||
|
overlay_active: false,
|
||||||
|
underlay_active: true,
|
||||||
|
};
|
||||||
|
s.set_base_colors(keypad);
|
||||||
|
s
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_note_offset(&mut self, keypad: &mut RgbKeypad, offset: NoteOffset) {
|
||||||
|
self.note_offset = offset;
|
||||||
|
self.set_base_colors(keypad);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Poll the button matrix; append a Note On/Off `[status, note, velocity]`
|
||||||
|
/// to `out` for every pad whose state changed since the last call.
|
||||||
|
pub fn update(&mut self, keypad: &mut RgbKeypad, out: &mut heapless::Vec<MidiOut, 16>) {
|
||||||
|
if self.overlay_active {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let current = keypad.get_button_states();
|
||||||
|
let changed = current ^ self.previous_button_states;
|
||||||
|
if changed != 0 {
|
||||||
|
for i in 0..NUM_PADS {
|
||||||
|
let mask = 1u16 << i;
|
||||||
|
if changed & mask != 0 {
|
||||||
|
let pressed = current & mask != 0;
|
||||||
|
let note = (transform_index(i) as u8).wrapping_add(self.note_offset);
|
||||||
|
let bytes = if pressed {
|
||||||
|
[0x90, note, 127] // Note On, full velocity
|
||||||
|
} else {
|
||||||
|
[0x80, note, 0] // Note Off
|
||||||
|
};
|
||||||
|
let _ = out.push(MidiOut { bytes });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.previous_button_states = current;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Light a single pad for the overlay (takes over the LEDs until cleared).
|
||||||
|
pub fn set_overlay_led(&mut self, keypad: &mut RgbKeypad, pad_index: usize, r: u8, g: u8, b: u8) {
|
||||||
|
let reversed = transform_index(pad_index);
|
||||||
|
keypad.illuminate(reversed, r, g, b);
|
||||||
|
keypad.update();
|
||||||
|
self.overlay_active = true;
|
||||||
|
self.underlay_active = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mark the overlay active after painting LEDs directly (e.g. a bitmap via
|
||||||
|
/// `RgbKeypad` rather than `set_overlay_led`), so the keypad update loop
|
||||||
|
/// suspends button reads and `clear_overlay` knows to repaint the underlay.
|
||||||
|
pub fn set_overlay_active(&mut self) {
|
||||||
|
self.overlay_active = true;
|
||||||
|
self.underlay_active = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Release the overlay and repaint the underlay.
|
||||||
|
pub fn clear_overlay(&mut self, keypad: &mut RgbKeypad) {
|
||||||
|
self.overlay_active = false;
|
||||||
|
self.underlay_active = true;
|
||||||
|
self.update_underlay(keypad);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handle an incoming 3-byte MIDI channel message, lighting the matching
|
||||||
|
/// pad if it falls in the keypad's note range. Mirrors the C
|
||||||
|
/// `receive_midi_message` (with the duplicated Note-On block de-duplicated).
|
||||||
|
pub fn receive_midi_message(&mut self, keypad: &mut RgbKeypad, message: &[u8]) {
|
||||||
|
if message.len() < 3 || self.overlay_active {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let status = message[0];
|
||||||
|
let note = message[1];
|
||||||
|
let velocity = message[2];
|
||||||
|
|
||||||
|
let original = note as i32 - self.note_offset as i32;
|
||||||
|
if !(0..NUM_PADS as i32).contains(&original) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let original = original as usize;
|
||||||
|
let reversed = transform_index(original);
|
||||||
|
|
||||||
|
let mut r = self.underlay_colors[original][0];
|
||||||
|
let mut g = self.underlay_colors[original][1];
|
||||||
|
let mut b = self.underlay_colors[original][2];
|
||||||
|
|
||||||
|
// Default to white if the underlay is off.
|
||||||
|
if r == 0 && g == 0 && b == 0 {
|
||||||
|
r = 255;
|
||||||
|
g = 255;
|
||||||
|
b = 255;
|
||||||
|
} else {
|
||||||
|
// Normalise the underlay colour to full brightness.
|
||||||
|
let max = r.max(g).max(b);
|
||||||
|
r = (r as u16 * 255 / max as u16) as u8;
|
||||||
|
g = (g as u16 * 255 / max as u16) as u8;
|
||||||
|
b = (b as u16 * 255 / max as u16) as u8;
|
||||||
|
}
|
||||||
|
|
||||||
|
if status == 0x90 && velocity > 0 {
|
||||||
|
// Note On: scale the normalised colour by velocity.
|
||||||
|
r = (r as u16 * velocity as u16 / 127) as u8;
|
||||||
|
g = (g as u16 * velocity as u16 / 127) as u8;
|
||||||
|
b = (b as u16 * velocity as u16 / 127) as u8;
|
||||||
|
keypad.illuminate(reversed, r, g, b);
|
||||||
|
} else if status == 0x80 || (status == 0x90 && velocity == 0) {
|
||||||
|
// Note Off: revert to the original underlay colour.
|
||||||
|
keypad.illuminate(
|
||||||
|
reversed,
|
||||||
|
self.underlay_colors[original][0],
|
||||||
|
self.underlay_colors[original][1],
|
||||||
|
self.underlay_colors[original][2],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
keypad.update();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Paint the underlay colours across all pads.
|
||||||
|
fn update_underlay(&self, keypad: &mut RgbKeypad) {
|
||||||
|
if !self.overlay_active && self.underlay_active {
|
||||||
|
for i in 0..NUM_PADS {
|
||||||
|
let j = transform_index(i);
|
||||||
|
keypad.illuminate(
|
||||||
|
j,
|
||||||
|
self.underlay_colors[i][0],
|
||||||
|
self.underlay_colors[i][1],
|
||||||
|
self.underlay_colors[i][2],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
keypad.update();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set the base underlay colours: root note purple, black keys dim, white
|
||||||
|
/// keys blue — keyed by `(note_offset + i) % 12`.
|
||||||
|
fn set_base_colors(&mut self, keypad: &mut RgbKeypad) {
|
||||||
|
for i in 0..NUM_PADS {
|
||||||
|
let note = (self.note_offset.wrapping_add(i as u8)) % 12;
|
||||||
|
self.underlay_colors[i] = match note {
|
||||||
|
0 => [5, 1, 5], // root (purple)
|
||||||
|
1 | 3 | 6 | 8 | 10 => [0, 0, 0], // black keys (dim)
|
||||||
|
_ => [1, 1, 10], // white keys (blue)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
self.update_underlay(keypad);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
//! Octave display — Rust port of the octave bitmaps + `display_active_octave`
|
||||||
|
//! from `main.cpp`. On a BOOTSEL press, the active octave is shown as a digit
|
||||||
|
//! on the 4x4 keypad grid for 500ms via the keypad overlay, then cleared.
|
||||||
|
//!
|
||||||
|
//! Copyright (C) 2026 Nils — SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
//! This file is part of pico-pi-midi. See LICENSE for the full notice.
|
||||||
|
|
||||||
|
use crate::keypad::{RgbKeypad, NUM_PADS};
|
||||||
|
use crate::midi_keypad::MidiKeypad;
|
||||||
|
|
||||||
|
/// 4x4 bitmaps for octaves -1..=9. Each row is 4 bits (MSB = leftmost column),
|
||||||
|
/// rows ordered top-to-bottom. Index 0 = octave -1, index k = octave k-1.
|
||||||
|
/// (Direct copy of the C `digit_bitmaps[11][4]`.)
|
||||||
|
const DIGIT_BITMAPS: [[u8; 4]; 11] = [
|
||||||
|
[0b0001, 0b0001, 0b1101, 0b0001], // -1
|
||||||
|
[0b0010, 0b0101, 0b0101, 0b0010], // 0
|
||||||
|
[0b0001, 0b0001, 0b0001, 0b0001], // 1
|
||||||
|
[0b0111, 0b0011, 0b0110, 0b0111], // 2
|
||||||
|
[0b0111, 0b0001, 0b0011, 0b0111], // 3
|
||||||
|
[0b0101, 0b0111, 0b0001, 0b0001], // 4
|
||||||
|
[0b0111, 0b0110, 0b0011, 0b0111], // 5
|
||||||
|
[0b0100, 0b0111, 0b0101, 0b0111], // 6
|
||||||
|
[0b0111, 0b0001, 0b0010, 0b0100], // 7
|
||||||
|
[0b0111, 0b0111, 0b0111, 0b0111], // 8
|
||||||
|
[0b0111, 0b0101, 0b0111, 0b0001], // 9
|
||||||
|
];
|
||||||
|
|
||||||
|
/// Paint a 4x4 bitmap onto the keypad overlay (white where the bit is set).
|
||||||
|
/// Mirrors the C `display_bitmap`: row 0 is top, and the grid is written so
|
||||||
|
/// that physical row (3-row) is at the top — matching `transform_index`.
|
||||||
|
fn display_bitmap(keypad: &mut RgbKeypad, bitmap: &[u8; 4]) {
|
||||||
|
for row in 0..4 {
|
||||||
|
let row_data = bitmap[row];
|
||||||
|
for col in 0..4 {
|
||||||
|
let on = row_data & (1 << (3 - col)) != 0;
|
||||||
|
let c = if on { 255 } else { 0 };
|
||||||
|
// C: set_overlay_led((3 - row) * 4 + col, ...)
|
||||||
|
let pad_index = (3 - row) * 4 + col;
|
||||||
|
keypad.illuminate(pad_index, c, c, c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
keypad.update();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Show the active octave for `note_offset` on the grid for 500ms, then clear.
|
||||||
|
/// `octave = note_offset/12 - 1` (MIDI convention: note 0 = C-1). Out of range
|
||||||
|
/// flashes all pads red.
|
||||||
|
pub async fn display_active_octave(midi: &mut MidiKeypad, keypad: &mut RgbKeypad, note_offset: u8) {
|
||||||
|
let octave = (note_offset / 12) as i32 - 1;
|
||||||
|
|
||||||
|
midi.clear_overlay(keypad);
|
||||||
|
|
||||||
|
if (-1..=9).contains(&octave) {
|
||||||
|
display_bitmap(keypad, &DIGIT_BITMAPS[(octave + 1) as usize]);
|
||||||
|
midi.set_overlay_active();
|
||||||
|
} else {
|
||||||
|
// Out of range: flash all LEDs red.
|
||||||
|
for i in 0..NUM_PADS {
|
||||||
|
midi.set_overlay_led(keypad, i, 255, 0, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
embassy_time::Timer::after_millis(500).await;
|
||||||
|
midi.clear_overlay(keypad);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user