Compare commits

..
53 Commits
Author SHA1 Message Date
Earle F. Philhower, III 2297d61d92 Update version 2024-06-18 09:44:58 -07:00
Limor "Ladyada" Friedandhathach 6d601250d6 Add Adafruit Adalogger Feather (#2229)
Co-authored-by: hathach <thach@tinyusb.org>
2024-06-17 21:00:45 -07:00
Earle F. Philhower, III c99614c1f5 Add AsyncUDP and simple NetBIOS name lookup server (#2234)
Thanks to @me-no-dev's code.  Lets Windows look up the PicoW by name
using NBNS and needs much less memory and code than mDNS.

AsyncUDP ported from the old ESP8266 version, only minimal changes.  Will
probably only be valid in IPv4 environments and may not match current
ESP32 AsyncUDP interfaces.
2024-06-17 17:46:53 -07:00
Mete K. Atay 352d363463 Add METE HOCA Akana R1 (#2230) 2024-06-17 09:53:02 -07:00
Ayush Sharma 1775fedf44 Webserver: Add support for filters and removable routes (#2225)
This PR implements filters and removable routes in RP2040 arduino core, making it API compatible with recent changes to ESP32 & ESP8266 WebServer API.
2024-06-13 15:32:17 -07:00
Earle F. Philhower, III 4ab0ba6133 Fix crash on SD.end() without initial SD.begin() (#2222)
Fixes #2220
2024-06-11 13:40:27 -07:00
Earle F. Philhower, III eb0badd817 Avoid malloc/free while in HCI callbacks (#2219)
Bluetooth operates at IRQ level, so using std::list (which needs to
new and delete objects) is not legal.  Use a fixed, preallocated
vector instead.
2024-06-10 16:38:50 -07:00
Earle F. Philhower, III f272995536 For consistency, BTHID Joypad->Joystick (#2218)
Matches existing library names and nomenclature
2024-06-10 13:34:59 -07:00
Earle F. Philhower, III db13d3c1f8 Add basic A2DP BluetoothAudio documentation (#2217) 2024-06-09 17:47:13 -07:00
Earle F. Philhower, III f8c1ec100f Add BluetoothHIDMaster documentation (#2216)
Also link in FatFSUSB docs, d'oh!
2024-06-09 16:51:35 -07:00
Earle F. Philhower, III 1fd66bf9c2 Add joypad HID master support (#2214)
Play games on your Pico using Bluetooth gamepads!
2024-06-09 11:47:13 -07:00
Earle F. Philhower, III 151c52c1a0 Remove leftover LWIP debug/redefines (#2213)
Fixes #2211
2024-06-09 10:10:20 -07:00
Earle F. Philhower, III bde21e5ae1 Add BLE support to BluetoothHIDMaster (#2208)
Support Bluetooth BLE keyboard and mice using the same HID master
infrastructure as the BT Classic.
2024-06-07 14:52:52 -07:00
Earle F. Philhower, III c104c6717c Upgrade to Adafruit TinyUSB 3.1.5 (#2206) 2024-06-05 22:36:30 -07:00
Michael Rangen b0ffd89dbb Added Raspberry Breadstick (#2205)
https://shop.breadstick.ca/products/raspberry-breadstick-rp2040
I think I did the pin definitions correctly... other boards used generic pin numbers based on the GPIO pins but I've mapped GPIO to the silkscreen pin labels on our board.
2024-06-05 22:15:05 -07:00
Earle F. Philhower, III 0f05ad1cc2 Use block writes for BT audio consumers (#2204)
Around 2x the performance, and every bit is needed w/BT SBC compression
and decompression.
2024-06-05 16:03:35 -07:00
Zillion 0ec12aa49f Add GroundStudio Marble Pico board (#2203) 2024-06-05 15:18:21 -07:00
Earle F. Philhower, III f997a9c3bd Update README.md 2024-06-05 13:51:03 -07:00
Earle F. Philhower, III 9039089067 Fix PWMAudio::write(buffer, len) (#2202)
PWMAudio was only ever writing one half the buffer passed in because
of an off-by-2 error.  Fixes the sine output in KeyboardPiano.
2024-06-05 13:08:08 -07:00
Earle F. Philhower, III 8bc8c824d3 Update version 2024-06-05 12:03:10 -07:00
Earle F. Philhower, III f08ba6bd42 Rebuild OTA bootloader for newer LittleFS version (#2199)
The LittleFS folks changed the on-flash format in 2.6.0, making
it unmountable with earlier precompiled code.

Rebuild the OTA bootloader using the 2.9.3 LittleFS release,
matching the core version.

Fixes #2198
2024-06-05 11:48:16 -07:00
Earle F. Philhower, III 1ef61d725b Clean up OTA example references to ESP8266 (#2200) 2024-06-05 11:40:37 -07:00
Earle F. Philhower, III b42083f20a Add "Needs Bluetooth" compile warning (#2197) 2024-06-05 11:08:20 -07:00
Earle F. Philhower, III f820dc134a Update version 2024-06-04 14:46:13 -07:00
Earle F. Philhower, III f6d13d2b70 Bluetooth Master HID and musical keyboard example (#2195)
Adds BluetoothHIDMaster and HIDKeyStream which let the PicoW connect to
and use Bluetooth Classic HID devices like keyboards and mice.

An example that lets the PicoW use a BT keyboard as a piano is
included and shows the use of the new classes.
2024-06-04 14:09:28 -07:00
Earle F. Philhower, III f786583986 Split out BluetoothHCI for shared usage (#2194) 2024-06-03 15:09:55 -07:00
Earle F. Philhower, III 5f6fb75505 Move to LittleFS 2.9.3. (#2193)
On-flash format changed after 2.5.1, but this can read prior versions
and will upgrade on-device to the later version.
2024-06-03 09:32:52 -07:00
Christian Halter 962dedad21 Fix folder name for Archi board (#2191)
* fix: Changed folder name to match build.variant property
* Added GPIO definitions for Archi board
Co-authored-by: Christian Halter <christian.halter@newsan.com.ar>
2024-06-03 09:20:59 -07:00
Earle F. Philhower, III ce45c65568 Make LittleFS filenames support full size (#2192)
Support 255 character names, not just 32, in LittleFS filesystems.
2024-06-03 09:11:01 -07:00
Earle F. Philhower, III 6d6433f256 Add track info support for BT audio sink (#2190) 2024-05-31 13:08:41 -07:00
Earle F. Philhower, III bf385490d3 Fix crash on audio end from IRQ, refactor A2DP (#2189)
Fixes #2188

We get a call to stop the audio channel from a timer/IRQ context, so can't
safely remove the IRQ handler for the AudioBufferManager.  The SDK will panic.

Because the IRQ handler will be a noop if it's not uninstalled, we will
instead just leave our shared handler in place and let it do nothing.

Use a common BluetoothLock RAII in BluetoothAudio to clen up the code and
automatically lock BT for the AVRCP button methods.
2024-05-31 12:14:57 -07:00
Earle F. Philhower, III 919a754ef8 Add double-mem LWIP option (#2187)
Add a "-32K" option to all the IP stack options that doubles the PCB and memory
pools from default.  For most use cases this is not necessary, but it could be
helpful in cases where large numbers of TCP clients are connected or high
bandwidth applications.

Fixes #2050
2024-05-30 18:30:50 -07:00
Earle F. Philhower, III 0a2b616c8a Add Cookies to HTTPClient (#2186)
From:
https://github.com/espressif/arduino-esp32/pull/6216
https://github.com/espressif/arduino-esp32/pull/6280
https://github.com/espressif/arduino-esp32/pull/7112
2024-05-30 13:27:43 -07:00
Earle F. Philhower, III 56bd539528 Webserver Ignore extra headers in multipart forms (#2184)
From https://github.com/espressif/arduino-esp32/pull/9253
2024-05-30 13:16:15 -07:00
Earle F. Philhower, III 3839f07afe HTTPClient - Fix case sensitivity for header keys (#2185)
From https://github.com/espressif/arduino-esp32/pull/8713
2024-05-30 13:05:49 -07:00
Earle F. Philhower, III 2043623ce6 Fix POST form parser edge cases (#2182)
From https://github.com/espressif/arduino-esp32/pull/9167
2024-05-30 12:19:44 -07:00
Earle F. Philhower, III a3dba8be5d Fix AdvancedWebServer.ino uptime conversion (#2183)
From https://github.com/espressif/arduino-esp32/pull/9224
2024-05-30 12:07:28 -07:00
Earle F. Philhower, III 1f9350dc2a Allow setting SerialBT advertised name (#2181)
Trivial fix #2179
2024-05-30 11:40:40 -07:00
Earle F. Philhower, III 361b4e0862 Allow uploading huge files to WebServer (#2180)
From https://github.com/espressif/arduino-esp32/pull/9440
2024-05-30 11:24:18 -07:00
Earle F. Philhower, III fa2bfdc2ba Small RAM savings (128b) in WebServer (#2178)
From https://github.com/espressif/arduino-esp32/pull/9594
2024-05-30 10:38:50 -07:00
Earle F. Philhower, III 679be8520f Update version 2024-05-29 14:54:32 -07:00
Earle F. Philhower, III 01e9dc99f2 Add A2DP sink (speaker) support (#2177)
Provide direct connection from BT audio to I2S and PWM audio outputs.
Example included showing play/pause operation.
2024-05-29 14:53:06 -07:00
Earle F. Philhower, III ec5e62e533 Add Bluetooth audio out (A2DP) on the PicoW (#2174)
Adds a library to run classic Bluetooth A2DP source (output) audio from
the PicoW.  Simple example showing operation and callbacks.

Factor out multiple BT lock/unlock and place in the PicoW variant files.
2024-05-26 14:30:40 -07:00
Earle F. Philhower, III 367200a2c8 Use custom LWIP checksum for ~13% faster checksums (#2172)
Use -O2 only on the LWIP checksum routine, resulting in a speedup of
around 13% (checksumming only, not entire LWIP stack) for 72 add'l bytes
of flash.
2024-05-22 10:37:30 -07:00
Earle F. Philhower, III 11814823ed Add asynchronous I2C read and write operations (#2167)
Fixes #1730

Uses DMA operations to avoid the need to bit-bang or busy wait for I2C operations
that might be very slow.  Optional, adds new API calls to enable.  Simple example
included.
2024-05-21 14:32:12 -07:00
Earle F. Philhower, III e6c7ee7813 Add asynchronous SPI transactions (#2168)
Fixes #1192

Uses DMA operations to avoid the need to bit-bang or busy wait for SPI
operations that might be very slow. Optional, adds new API calls to enable.
Simple example included.
2024-05-21 14:08:36 -07:00
Earle F. Philhower, III dc856dbb1c Update README.md 2024-05-21 09:51:27 -07:00
Christian HalterandChristian Halter c4b1ab81c1 Add Newsan Archi board (#2169)
Co-authored-by: Christian Halter <christian.halter@newsan.com.ar>
2024-05-21 09:51:08 -07:00
Earle F. Philhower, III f33df254f1 Add SPI::setMOSI/setMISO, better match pin names (#2166) 2024-05-20 14:43:55 -07:00
Earle F. Philhower, III 83a6aaca1c Update SDFat to use array transfers (#2164)
Fixes #2163
2024-05-17 13:52:47 -07:00
Earle F. Philhower, III 182af71492 Update StaticMulticore-FreeRTOS.ino (#2161) 2024-05-15 07:57:46 -07:00
Earle F. Philhower, III d4cdb3ea69 Fix LWIP crash on unexpected ping packets (#2159)
When a ping is sent from the Pico, a raw_recv callback is added which
sees all raw incoming packets to detect the response from the ping target.
If while waiting for the target response an external ping packet arrives
this incoming ping request packet will be processed by the
LwipIntfDev<>::_pingCB which will return "0" not processed and which
*should* not change the payload unless it handles the actual packet.

Unfortunately, the 20 byte header was unconditionally stripped off of
the packet before checking if this was our response, changing the
payload address and causing an assertion in LWIP.

Fix by using absolute offsets inside the raw packet for the ping
response checks.

Fixes #2156
Fixes #2149
2024-05-14 17:37:54 -07:00
Earle F. Philhower, III 016bf80e3b Protect againt calling LWIP_Ethernet::begin twice (#2158)
As seen in debug of #2149, if the LwipIntfDev is already _started,
return false for a ::begin() call.

Also, protect netif_add/_remove on the very small possibilty of being
called by LwipIntfDev devices while the CYW43 driver is doing work.
2024-05-13 19:08:38 -07:00
132 changed files with 74320 additions and 460 deletions
+1 -1
View File
@@ -25,7 +25,7 @@ jobs:
uses: codespell-project/actions-codespell@master
with:
skip: ./ArduinoCore-API,./libraries/ESP8266SdFat,./libraries/Adafruit_TinyUSB_Arduino,./libraries/LittleFS/lib,./tools/pyserial,./pico-sdk,./.github,./docs/i2s.rst,./cores/rp2040/api,./libraries/FreeRTOS,./tools/libbearssl/bearssl,./include,./libraries/WiFi/examples/BearSSL_Server,./ota/uzlib,./libraries/http-parser/lib,./libraries/WebServer/examples/HelloServerBearSSL/HelloServerBearSSL.ino,./libraries/HTTPUpdateServer/examples/SecureBearSSLUpdater/SecureBearSSLUpdater.ino,./.git,./libraries/FatFS/lib/fatfs,./libraries/FatFS/src/diskio.h,./libraries/FatFS/src/ff.cpp,./libraries/FatFS/src/ffconf.h,./libraries/FatFS/src/ffsystem.cpp,./libraries/FatFS/src/ff.h,./libraries/lwIP_WINC1500/src/driver,./libraries/lwIP_WINC1500/src/common,./libraries/lwIP_WINC1500/src/bus_wrapper,./libraries/lwIP_WINC1500/src/spi_flash
ignore_words_list: ser,dout
ignore_words_list: ser,dout,shiftIn,acount
# Consistent style
astyle:
+3
View File
@@ -40,3 +40,6 @@
[submodule "libraries/FatFS/lib/SPIFTL"]
path = libraries/FatFS/lib/SPIFTL
url = https://github.com/earlephilhower/SPIFTL.git
[submodule "libraries/AsyncUDP"]
path = libraries/AsyncUDP
url = https://github.com/earlephilhower/AsyncUDP.git
+7 -1
View File
@@ -27,6 +27,7 @@ Read the [Contributing Guide](https://github.com/earlephilhower/arduino-pico/blo
* Adafruit Trinkey RP2040 QT
* Arduino Nano RP2040 Connect
* ArtronShop RP2 Nano
* Breadstick Raspberry
* BridgeTek IDM2040-7A
* Cytron Maker Pi RP2040
* Cytron Maker Nano RP2040
@@ -37,6 +38,7 @@ Read the [Contributing Guide](https://github.com/earlephilhower/arduino-pico/blo
* DFRobot Beetle RP2040
* ElectronicCats Hunter Cat NFC
* ExtremeElectronics RC2040
* GroundStudio Marble Pico
* Invector Labs Challenger RP2040 WiFi
* Invector Labs Challenger RP2040 WiFi/BLE
* Invector Labs Challenger RP2040 WiFi6/BLE
@@ -49,8 +51,10 @@ Read the [Contributing Guide](https://github.com/earlephilhower/arduino-pico/blo
* Invector Labs RPICO32
* Melopero Cookie RP2040
* Melopero Shake RP2040
* METE HOCA Akana R1
* Neko Systems BL2040 Mini
* Olimex RP2040-Pico30
* Newsan Archi
* nullbits Bit-C PRO
* Pimoroni PGA2040
* Pimoroni Plasma2040
@@ -84,6 +88,7 @@ Read the [Contributing Guide](https://github.com/earlephilhower/arduino-pico/blo
# Features
* Adafruit TinyUSB Arduino (USB mouse, keyboard, flash drive, generic HID, CDC Serial, MIDI, WebUSB, others)
* Bluetooth on the PicoW (Classic and BLE) with Keyboard, Mouse, Joystick, and Virtual Serial
* Bluetooth Classic and BLE HID master mode (connect to BT keyboard, mouse, or joystick)
* Generic Arduino USB Serial, Keyboard, Joystick, and Mouse emulation
* WiFi (Pico W, ESP32-based ESPHost, Atmel WINC1500)
* Ethernet (Wired W5500, W5100, ENC28J60)
@@ -97,7 +102,8 @@ Read the [Contributing Guide](https://github.com/earlephilhower/arduino-pico/blo
* digitalWrite/Read, shiftIn/Out, tone, analogWrite(PWM)/Read, temperature
* Analog stereo audio in using DMA and the built-in ADC
* Analog stereo audio out using PWM hardware
* USB drive mode for data loggers (SingleFileDrive)
* Bluetooth A2DP audio source (output) and sink (input) on the PicoW
* USB drive mode for data loggers (SingleFileDrive, FatFSUSB)
* Peripherals: SPI master/slave, Wire(I2C) master/slave, dual UART, emulated EEPROM, I2S audio input/output, Servo
* printf (i.e. debug) output over USB serial
+2321
View File
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -1,5 +1,5 @@
#pragma once
#define ARDUINO_PICO_MAJOR 3
#define ARDUINO_PICO_MINOR 8
#define ARDUINO_PICO_REVISION 1
#define ARDUINO_PICO_VERSION_STR "3.8.1"
#define ARDUINO_PICO_MINOR 9
#define ARDUINO_PICO_REVISION 3
#define ARDUINO_PICO_VERSION_STR "3.9.3"
+32
View File
@@ -0,0 +1,32 @@
// Use to create a callback thunk from C to C++
// #define CCALLBACKNAME to a unique per-file name and #include this file
// To make a CB use a define of the form:
/*
#define PACKETHANDLERCB(class, cbFcn) \
(CCALLBACKNAME<void(uint8_t, uint16_t, uint8_t*, uint16_t), __COUNTER__>::func = std::bind(&class::cbFcn, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4), \
static_cast<btstack_packet_handler_t>(<CCALLBACKNAMEvoid(uint8_t, uint16_t, uint8_t*, uint16_t), __COUNTER__ - 1>::callback))
*/
#include <functional>
// Thank you to https://stackoverflow.com/questions/66474621/multiple-non-static-callbacks-of-c-member-functions for the following beautiful hack
#ifndef CCALLBACKNAME
#define CCALLBACKNAME _CCallback
#endif
template <typename T, int tag>
struct CCALLBACKNAME;
template <typename Ret, typename... Params, int tag>
struct CCALLBACKNAME<Ret(Params...), tag> {
template <typename... Args>
static Ret callback(Args... args) {
return func(args...);
}
int _tag = tag;
static std::function<Ret(Params...)> func;
};
template <typename Ret, typename... Params, int tag>
std::function<Ret(Params...)> CCALLBACKNAME<Ret(Params...), tag>::func;
+12
View File
@@ -358,4 +358,16 @@ extern "C" {
__real_raw_remove(pcb);
}
extern struct netif *__real_netif_add(struct netif *netif, const ip4_addr_t *ipaddr, const ip4_addr_t *netmask, const ip4_addr_t *gw, void *state, netif_init_fn init, netif_input_fn input);
struct netif *__wrap_netif_add(struct netif *netif, const ip4_addr_t *ipaddr, const ip4_addr_t *netmask, const ip4_addr_t *gw, void *state, netif_init_fn init, netif_input_fn input) {
LWIPMutex m;
return __real_netif_add(netif, ipaddr, netmask, gw, state, init, input);
}
extern void __real_netif_remove(struct netif *netif);
void __wrap_netif_remove(struct netif *netif) {
LWIPMutex m;
__real_netif_remove(netif);
}
}; // extern "C"
+1 -1
View File
@@ -1212,7 +1212,7 @@ static uint16_t handle_prepare_write_request(att_connection_t * att_connection,
}
/*
@brief transcation queue of prepared writes, e.g., after disconnect
@brief transaction queue of prepared writes, e.g., after disconnect
*/
void att_clear_transaction_queue(att_connection_t * att_connection) {
(*att_write_callback)(att_connection->con_handle, 0, ATT_TRANSACTION_MODE_CANCEL, 0, NULL, 0);
+1 -1
View File
@@ -257,7 +257,7 @@ extern "C" {
uint8_t * response_buffer);
/**
@brief transcation queue of prepared writes, e.g., after disconnect
@brief transaction queue of prepared writes, e.g., after disconnect
@return att_connection
*/
void att_clear_transaction_queue(att_connection_t * att_connection);
+121
View File
@@ -0,0 +1,121 @@
// Taken from LWIP's inet_chksum.c just to set the -O2 flag
/*
Copyright (c) 2001-2004 Swedish Institute of Computer Science.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
This file is part of the lwIP TCP/IP stack.
Author: Adam Dunkels <adam@sics.se>
*/
#include "lwip/opt.h"
#include "lwip/inet_chksum.h"
#include "lwip/def.h"
#include "lwip/ip_addr.h"
#pragma GCC optimize ("O2")
/**
An optimized checksum routine. Basically, it uses loop-unrolling on
the checksum loop, treating the head and tail bytes specially, whereas
the inner loop acts on 8 bytes at a time.
@arg start of buffer to be checksummed. May be an odd byte address.
@len number of bytes in the buffer to be checksummed.
@return host order (!) lwip checksum (non-inverted Internet sum)
by Curt McDowell, Broadcom Corp. December 8th, 2005
*/
extern "C" u16_t lwip_standard_chksum(const void *dataptr, int len) {
const u8_t *pb = (const u8_t *)dataptr;
const u16_t *ps;
u16_t t = 0;
const u32_t *pl;
u32_t sum = 0, tmp;
/* starts at odd byte address? */
int odd = ((mem_ptr_t)pb & 1);
if (odd && len > 0) {
((u8_t *)&t)[1] = *pb++;
len--;
}
ps = (const u16_t *)(const void *)pb;
if (((mem_ptr_t)ps & 3) && len > 1) {
sum += *ps++;
len -= 2;
}
pl = (const u32_t *)(const void *)ps;
while (len > 7) {
tmp = sum + *pl++; /* ping */
if (tmp < sum) {
tmp++; /* add back carry */
}
sum = tmp + *pl++; /* pong */
if (sum < tmp) {
sum++; /* add back carry */
}
len -= 8;
}
/* make room in upper bits */
sum = FOLD_U32T(sum);
ps = (const u16_t *)pl;
/* 16-bit aligned word remaining? */
while (len > 1) {
sum += *ps++;
len -= 2;
}
/* dangling tail byte remaining? */
if (len > 0) { /* include odd byte */
((u8_t *)&t)[0] = *(const u8_t *)ps;
}
sum += t; /* add end bytes */
/* Fold 32-bit sum to 16 bits
calling this twice is probably faster than if statements... */
sum = FOLD_U32T(sum);
sum = FOLD_U32T(sum);
if (odd) {
sum = SWAP_BYTES_IN_WORD(sum);
}
return (u16_t)sum;
}
+39
View File
@@ -0,0 +1,39 @@
Bluetooth Audio (A2DP Source and Sink)
======================================
The PicoW can be used as a Bluetooth Audio sink or source with the ``BluetoothAudio`` class.
Operation is generally handled "automatically" in the background so while the audio is
playing or streaming the main application can perform other operations (like displaying
playback info, polling buttons for controls, etc.)
.. code :: cpp
#include <BluetoothAudio.h>
...
**Note about CPU usage:** Bluetooth SBC audio is a compressed format. That means
that it takes non-trivial amounts of CPU to compress on send, or decompress on receive.
Transmitting precompressed audio from, say, MP3 or AAC, requires first decompressing
the source file into raw PCM and then re-compressing them in the SBC format. You may
want to consider overclocking in this case to avoid underflow.
A2DPSink
--------
This class implements slave sink-mode operation with player control (play, pause, etc.) and
can play the received and decoded SBC audio to ``PWMAudio``, ``I2S``, or a user-created
`BluetoothAudioConsumer`` class.
The ``A2DPSink.ino`` example demonstrates turning a PicoW into a Bluetooth headset with
``PWMAudio``.
A2DPSource
-----------
This class implements a master source-mode SBC Bluetooth A2DP audio connection which
transmits audio using the standard ``Stream`` interface (like ``I2S`` or ``PWMAudio``.
The main application connects to a Bluetooth speaker and then writes samples into a buffer
that's automatically transmitted behind the scenes.
The ``A2DPSource.ino`` example shows how to connect to a Bluetooth speaker, transmit
data, and respond to commands from the speaker.
+7 -5
View File
@@ -2,9 +2,6 @@ Bluetooth on PicoW Support
==========================
As of the Pico-SDK version 1.5.0, the PicoW has **BETA** Bluetooth support.
So, since this core builds off the SDK the best that can be suggested it
that we have **ALPHA** Bluetooth support. As such, bug reports are welcome,
but Pull Requests fixing problems you find are seriously appreciated.
Enabling Bluetooth
------------------
@@ -24,6 +21,11 @@ Bluetooth Low Energy (BLE) HID device using the same API as their USB versions.
The ``SerialBT`` library implements a very simple SPP (Serial Port Profile)
Serial-compatible port.
Connect and use Bluetooth peripherals with the PicoW using the
``BluetoothHIDMaster`` library.
``BluetoothAudio`` (A2DP) is also supported, both sink and source.
Writing Custom Bluetooth Applications
-------------------------------------
You may also write full applications using the ``BTStack`` standard callback
@@ -40,8 +42,8 @@ For many BTStack examples, you simply need call the included
called afterwards to start processing (in the background).
You will also need to acquire the BT ``async_context`` system lock before
calling any BTStack APIs. See the ``libraries/PicoBluetoothHID`` helper
class for an example of how to do this.
calling any BTStack APIs. ``__lockBluetooth`` and ``unlockBluetooth`` are
provided in the PicoW variant code.
Note that if you need to modify the system ``btstack_config.h`` file, do so
in the ``tools/libpico`` directory and rebuild the Pico SDK static library.
+2 -2
View File
@@ -54,9 +54,9 @@ author = u'Earle F. Philhower, III'
# built documents.
#
# The short X.Y version.
version = u'3.8.1'
version = u'3.9.3'
# The full version, including alpha/beta/rc tags.
release = u'3.8.1'
release = u'3.9.3'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
+4 -4
View File
@@ -597,8 +597,8 @@ close
Close the file. No other operations should be performed on *File* object
after ``close`` function was called.
openNextFile (compatibiity method, not recommended for new code)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
openNextFile (compatibility method, not recommended for new code)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. code:: cpp
@@ -609,8 +609,8 @@ openNextFile (compatibiity method, not recommended for new code)
Opens the next file in the directory pointed to by the File. Only valid
when ``File.isDirectory() == true``.
rewindDirectory (compatibiity method, not recommended for new code)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
rewindDirectory (compatibility method, not recommended for new code)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. code:: cpp
+208
View File
@@ -0,0 +1,208 @@
Bluetooth HID Master
====================
The PicoW can connect to a Bluetooth Classic or Bluetooth BLE keyboard,
mouse, or joystick and receive input events from it. As opposed to
the ``Keyboard``, ``Mouse``, and ``Joystick`` libraries, which make
the PicoW into a peripheral others can use, this lets the PicoW use the
same kinds of peripherals in a master rols.
BTDeviceInfo Class
------------------
The ``BluetoothHCI`` class implements a scanning function for classic
and BLE devices and can return a ``std::vector`` of discovered devices to an application.
Iterate over the list using any of the STL iteration methods (i.e. ``for (auto e : list)``).
The elements of this list are ``BTDeviceInfo`` objects which have the following
member functions:
``BTDeviceInfo::deviceClass()`` returns the Bluetooth BLE UUID or the Blustooth device
class for the device. This specifies the general class of the device (keyboard, mouse,
etc.).
``BTDeviceInfo::address()`` and ``BTDeviceInfo::addressString()`` return the
Bluetooth address as a binary array or a string that can be used to ``print``.
``BTDeviceInfo::addressType()`` returns whether the BLE address is random or not, and
is not generally needed by a user application.
``BTDeviceInfo::rssi()`` returns an approximate dB level for the device. Less
negative is stronger signal.
``BTDeviceInfo::name()`` returns the advertised name of the device, if present. Some
devices or scans do not return names for valid devices.
BluetoothHCI Class
------------------
The ``BluetoothHCI`` class is responsible for scanning for devices and the lower-level
housekeeping for a master-mode Bluetooth application. Most applications will not need
to access it directly, but it can be used to discover nearby BT devices. As
part of the application Bluetooth setup, call ``BluetoothHCI::install()`` and then
``BluetoothHCI::begin()`` to start BT processing. Your application is still responsible
for all the non-default HCI initialization and customization. See the ``BluetoothScanner.ino``
example for more info.
BluetoothHIDMaster Operation
----------------------------
Most applications will use the ``BluetoothHIDMaster`` class and, after connecting, receive
callbacks from the Bluetooth stack when input events (key presses, mouse moves, button
mashes) occur.
Application flow will generally be:
1. Install the appropriate callbacks using the ``BluetoothHIDMaster::onXXX`` methods
2. Start the Bluetooth processing with ``BluetoothHIDMaster::begin()`` or ``BluetoothHIDMaster::beginBLE()``
3. Connect to the first device found with ``BluetoothHIDMaster::connectXXX()`` and start receiving callbacks.
4. Callbacks will come at interrupt time and set global state variables, which the main ``loop()`` will process
Callback Event Handlers
-----------------------
The main application is informed of new inputs via a standard callback mechanism. These callbacks run at
interrupt time and should not do significant work, ``delay()``, or allocate or free memory. The most common
way of handling this is setting global ``volatile`` flags and variables that the main ``loop()`` will poll
and process.
Mouse Callbacks
~~~~~~~~~~~~~~~
The ``BluetoothHIDMaster::onMouseMove`` callback gets the delta X, Y, and wheel reported by the device.
The ``BluetoothHIDMaster::onMouseButton`` gets a button number and state (up or down) and will be called
each time an individual button is reported changed by the mouse.
.. code :: cpp
void mouseMoveCB(void *cbdata, int dx, int dy, int dw) {
// Process the deltas, adjust global mouse state
}
void mouseButtonCB(void *cbdata, int butt, bool down) {
// Set the global button array with this new info
}
Meyboard Callbacks
~~~~~~~~~~~~~~~~~~
The `BluetoothHIDMaster::onKeyDown`` callback receives the raw HID key (**NOT ASCII**) sent by the device on a key press
while `BluetoothHIDMaster::onKeyUp`` gets the same when a key is released. Note that up to 6 keys can be pressed at any
one time. For media keys ("consumer keys" in the USB HID documentation) the ``BluetoothHIDMaster::onConsumerKeyDown`` and
``BluetoothHIDMaster::onConsumerKeyUp`` perform the same function (and receive the consumer key IDs defined by the
USB HID spec and not ASCII).
To convert the key press and release (including SHIFT handling), use a ``HIDKeyStream`` object. Simply write the raw
HID key and the up/down state to the stream and read back the ASCII for use in an application.
.. code :: cpp
HIDKeyStream keystream;
void keyDownCB(void *cbdata, int key) {
keystream.write((uint8_t )key);
keystream.write((uint8_t) true); // Keystream now has 1 ASCII character to read out and use
char ascii = keystream.read();
// ....
}
void keyUpCB(void *cbdata, int key) {
// Normally don't do anything on this, the character was read in the keyDownCB
}
void consumerKeyDownCB(void *cbdata, int key) {
// switch(key) and use cases from the USB Consumer Key page
}
void consumerKeyUpCB(void *cbdata, int key) {
// switch(key) and use cases from the USB Consumer Key page
}
Joystick Callbacks
~~~~~~~~~~~~~~~~~~
A single ``BluetoothHIDMaster::onJoystick`` callback gets activated every time a report from a joystick is processed.
It receives (potentially, if supported by the device) 4 analog axes, one 8-way digital hat switch position, and up
to 32 button states at a time.
.. code :: cpp
void joystickCB(void *cbdata, int x, int y, int z, int rz, uint8_t hat, uint32_t buttons) {
// HAT 0 = UP and continues clockwise. If no hat direction it is set to 0x0f.
// Use "buttons & (1 << buttonNumber)" to look at the individual button states
// ...
}
PianoKeyboard Example
~~~~~~~~~~~~~~~~~~~~~
See the ``PianoKeyboard.ino`` and ``PianoKeyboardBLE.ino`` examples for more information on callback operation.
BluetoothHIDMaster::onXXX Callback Installers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. code :: cpp
void BluetoothHIDMaster::onMouseMove(void (*)(void *, int, int, int), void *cbData = nullptr);
void BluetoothHIDMaster::onMouseButton(void (*)(void *, int, bool), void *cbData = nullptr);
void BluetoothHIDMaster::onKeyDown(void (*)(void *, int), void *cbData = nullptr);
void BluetoothHIDMaster::onKeyUp(void (*)(void *, int), void *cbData = nullptr);
void BluetoothHIDMaster::onConsumerKeyDown(void (*)(void *, int), void *cbData = nullptr);
void BluetoothHIDMaster::onConsumerKeyUp(void (*)(void *, int), void *cbData = nullptr);
void BluetoothHIDMaster::onJoystick(void (*)(void *, int, int, int, int, uint8_t, uint32_t), void *cbData = nullptr);
BluetoothHIDMaster Class
------------------------
bool BluetoothHIDMaster::begin()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Installs and configures the Bluetooth Classic stack and starts processing events. No connections are made at this point.
When running in Classic mode, no BLE devices can be detected or used.
bool BluetoothHIDMaster::begin(const char *BLEName)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Installs and configures the Bluetooth BLE stack and starts processing events. No connections are made at this point.
When running in BLE mode, no Classic devices can be detected or used.
bool BluetoothHIDMaster::connected()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Returns if the Bluetooth stack is up and running and a connection to a device is currently active.
void BluetoothHIDMaster::end()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Disables the Bluetooth stack. Note that with the current Bluetooth implementation restarting the stack (i.e. calling ``begin()`` after ``end()``) is not stable and will not work. Consider storing state and rebooting completely if this is necessary.
bool BluetoothHIDMaster::running()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Returns if the Bluetooth stack is running at all. Does not indicate if there is an active connection or not.
bool BluetoothHIDMaster::hciRunning()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Returns if the Bluetooth stack has passed the initial HCI start up phase. Until this returns ``true`` no Bluetooth operations can be performed.
std::vector<BTDeviceInfo> BluetoothHIDMaster::scan(uint32_t mask, int scanTimeSec, bool async)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Passes through the ``BluetoothHCI::scan()`` function to manually scan for a list of nearby devices. If you want to connect to the first found device, this is not needed.
bool BluetoothHIDMaster::connect(const uint8_t *addr)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Start the connection process to the Bluetooth Classic device with the given MAC. Note that this returns immediately, but it may take several seconds until ``connected()`` reports that the connection has been established.
bool BluetoothHIDMaster::connectKeyboard(), connectMouse(), connectJoystick(), connectAny()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Connect to the first found specified Bluetooth Classic device type (or any HID device) in pairing mode. No need to call ``scan()`` or have an address.
bool BluetoothHIDMaster::connectBLE(const uint8_t *addr, int addrType)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Start the connection process to the Bluetooth BLE device with the given MAC. Note that this returns immediately, but it may take several seconds until ``connected()`` reports that the connection has been established.
bool BluetoothHIDMaster::connectBLE()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Connect to the first found BLE device that has a HID service UUID (keyboard, mouse, or joystick)
bool BluetoothHIDMaster::disconnect()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Shuts down the connection to the currently connected device.
void BluetoothHIDMaster::clearPairing()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Erases all Bluetooth keys from memory. This effectively "forgets" all pairing between devices and can help avoid issues with the beta Bluetooth stack in the SDK.
+4 -1
View File
@@ -44,9 +44,12 @@ For the latest version, always check https://github.com/earlephilhower/arduino-p
USB (Arduino and Adafruit_TinyUSB) <usb>
Multicore Processing <multicore>
Bluetooth (Alpha/Beta) <bluetooth>
Bluetooth <bluetooth>
Bluetooth HID Master <hidmaster>
Bluetooth Audio (A2DP) <a2dp>
Single File USB Drive <singlefile>
FatFSUSB - full FS access over USB <fatfsusb>
FreeRTOS SMP (multicore) <freertos>
+37 -5
View File
@@ -8,10 +8,10 @@ SPI pinouts can be set **before SPI.begin()** using the following calls:
.. code:: cpp
bool setRX(pin_size_t pin);
bool setRX(pin_size_t pin); // or setMISO()
bool setCS(pin_size_t pin);
bool setSCK(pin_size_t pin);
bool setTX(pin_size_t pin);
bool setTX(pin_size_t pin); // or setMOSI()
Note that the ``CS`` pin can be hardware or software controlled by the sketch.
When software controlled, the ``setCS()`` call is ignored.
@@ -39,7 +39,39 @@ in order to consunme the received data and provide data to transmit.
* The callbacks operate at IRQ time and may be called very frequently at high SPI frequencies. So, make then small, fast, and with no memory allocations or locking.
Examples
~~~~~~~~
Asynchronous Operation
======================
See the SPItoMyself example for a complete Master and Slave application.
Applications can use asynchronous SPI calls to allow for processing while long-running SPI transfers are
being performed. For example, a game could send a full screen update out over SPI and immediately start
processing the next frame without waiting for the first one to be sent. DMA is used to handle
the transfer to/from the hardware freeing the CPU from bit-banging or busy waiting.
Note that asynchronous operations can not be intersped with normal, synchronous ones. ``transferAsync``
should still occur after a ``beginTransaction()`` and when ``finishedAsync()`` returns ``true`` then
``endTransaction()`` should also be called.
All buffers need to be valid throughout the entire operation. Read data cannot be accessed until
the transaction is completed and can't be "peeked" at while the operation is ongoing.
bool transferAsync(const void \*send, void \*recv, size_t bytes)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Begins an SPI asynchronous transaction. Either ``send`` or ``recv`` can be ``nullptr`` if data only needs
to be transferred in one direction.
Check ``finishedAsync()`` to determine when the operation completes and conclude the transaction.
This operation needs to allocate a buffer from heap equal to ``bytes`` in size if ``LSBMODE`` is used.
bool finishedAsync()
~~~~~~~~~~~~~~~~~~~~
Call to check if the asynchronous operations is completed and the buffer passed in can be either read or
reused. Frees the allocated memory and completes the asynchronous transaction.
void abortAsync()
~~~~~~~~~~~~~~~~~
Cancels the outstanding asynchronous transaction and frees any allocated memory.
Examples
========
See the SPItoMyself and SPItoMyselfAsync examples for a complete Master and Slave application.
+38
View File
@@ -24,3 +24,41 @@ Master transmissions are buffered (up to 256 bytes) and only performed
on ``endTransmission``, as is standard with modern Arduino Wire implementations.
For more detailed information, check the `Arduino Wire documentation <https://www.arduino.cc/en/reference/wire>`_ .
Asynchronous Operation
----------------------
Applications can use asynchronous I2C calls to allow for processing while long-running I2C operations are
being performed. For example, a game could send a full screen update out over I2C and immediately start
processing the next frame without waiting for the first one to be sent over I2C. DMA is used to handle
the transfer to/from the I2C hardware freeing the CPU from bit-banging or busy waiting.
Note that asynchronous operations can not be intersped with normal, synchronous ones. Fully complete an
asynchronous operation before attempting to do a normal ``Wire.beginTransaction()`` or ``Wire.requestFrom``.
Also, all buffers need to be valid throughout the entire operation. Read data cannot be accessed until
the transaction is completed and can't be "peeked" at while the operation is ongoing.
bool writeAsync(uint8_t address, const void \*buffer, size_t bytes, bool sendStop)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Begins an I2C asynchronous write transaction. Writes to ``address`` of ``bytes`` from ``buffer`` and
at the end will send an I2C stop if ``sendStop`` is ``true``.
Check ``finishedAsync()`` to determine when the operation completes and conclude the transaction.
This operation needs to allocate a buffer from heap equal to 2x ``bytes`` in size.
bool readAsync(uint8_t address, void \*buffer, size_t bytes, bool sendStop)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Begins an I2C asynchronous read transaction. Reads from ``address`` for ``bytes`` into ``buffer`` and
at the end will send an I2C stop if ``sendStop`` is ``true``.
Check ``finishedAsync()`` to determine when the operation completes and conclude the transaction.
This operation needs to allocate a buffer from heap equal to 4x ``bytes`` in size.
bool finishedAsync()
~~~~~~~~~~~~~~~~~~~~
Call to check if the asynchronous operations is completed and the buffer passed in can be either read or
reused. Frees the allocated memory and completes the asynchronous transaction.
void abortAsync()
~~~~~~~~~~~~~~~~~
Cancels the outstanding asynchronous transaction and frees any allocated memory.
+14 -13
View File
@@ -14,6 +14,10 @@ extern void interrupts();
extern unsigned long __lwip_rand(void);
#define LWIP_RAND() __lwip_rand()
#ifndef __LWIP_MEMMULT
#define __LWIP_MEMMULT 1
#endif
// Common settings used in most of the pico_w examples
// (see https://www.nongnu.org/lwip/2_1_x/group__lwip__opts.html for details)
@@ -22,10 +26,10 @@ extern unsigned long __lwip_rand(void);
#define MEM_LIBC_MALLOC 0
#define MEM_ALIGNMENT 4
#define MEM_SIZE 16384
#define MEMP_NUM_TCP_SEG 32
#define MEMP_NUM_ARP_QUEUE 10
#define PBUF_POOL_SIZE 24
#define MEM_SIZE (__LWIP_MEMMULT * 16384)
#define MEMP_NUM_TCP_SEG (32)
#define MEMP_NUM_ARP_QUEUE (10)
#define PBUF_POOL_SIZE (__LWIP_MEMMULT > 1 ? 32 : 24)
#define LWIP_ARP 2
#define LWIP_ETHERNET 1
#define LWIP_ICMP 1
@@ -38,12 +42,13 @@ extern unsigned long __lwip_rand(void);
#define LWIP_NETIF_LINK_CALLBACK 1
#define LWIP_NETIF_HOSTNAME 1
#define LWIP_NETCONN 0
#define LWIP_STATS 0
#define LWIP_STATS_DISPLAY 0
#define MEM_STATS 0
#define SYS_STATS 0
#define MEMP_STATS 0
#define LINK_STATS 0
// #define ETH_PAD_SIZE 2
#define LWIP_CHKSUM_ALGORITHM 3
#define LWIP_CHKSUM_ALGORITHM 0
#define LWIP_DHCP 1
#define LWIP_IPV4 1
#define LWIP_TCP 1
@@ -55,7 +60,8 @@ extern unsigned long __lwip_rand(void);
#define LWIP_DHCP_DOES_ACD_CHECK 0
// See #1285
#define MEMP_NUM_UDP_PCB 6
#define MEMP_NUM_UDP_PCB (__LWIP_MEMMULT * 6)
#define MEMP_NUM_TCP_PCB (__LWIP_MEMMULT * 5)
#if LWIP_IPV6
#define LWIP_IPV6_DHCP6 1
@@ -68,12 +74,7 @@ extern void __setSystemTime(unsigned long long sec, unsigned long us);
//#define SNTP_SERVER_ADDRESS "pool.ntp.org"
#define SNTP_SERVER_DNS 1
#ifndef NDEBUG
#define LWIP_DEBUG 1
#define LWIP_STATS 1
#define LWIP_STATS_DISPLAY 1
#endif
#define LWIP_DEBUG 0
#define ETHARP_DEBUG LWIP_DBG_OFF
#define NETIF_DEBUG LWIP_DBG_OFF
#define PBUF_DEBUG LWIP_DBG_OFF
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
+3
View File
@@ -203,6 +203,9 @@
-Wl,--wrap=raw_sendto
-Wl,--wrap=raw_remove
-Wl,--wrap=netif_add
-Wl,--wrap=netif_remove
-Wl,--wrap=cyw43_cb_process_ethernet
-Wl,--wrap=cyw43_cb_tcpip_set_link_up
-Wl,--wrap=cyw43_cb_tcpip_set_link_down
@@ -1,5 +1,5 @@
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFi.h>
#include <LEAmDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
@@ -22,11 +22,11 @@ void setup() {
rp2040.restart();
}
// Port defaults to 8266
// ArduinoOTA.setPort(8266);
// Port defaults to 2040
// ArduinoOTA.setPort(2040);
// Hostname defaults to esp8266-[ChipID]
// ArduinoOTA.setHostname("myesp8266");
// Hostname defaults to pico-[ChipID]
// ArduinoOTA.setHostname("mypico");
// No authentication by default
// ArduinoOTA.setPassword("admin");
@@ -1,5 +1,5 @@
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFi.h>
#include <LEAmDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
Submodule libraries/AsyncUDP added at dd32bfa7d9
@@ -24,8 +24,9 @@
#include <hardware/irq.h>
#include "AudioBufferManager.h"
static int __channelCount = 0; // # of channels left. When we hit 0, then remove our handler
static AudioBufferManager* __channelMap[12]; // Lets the IRQ handler figure out where to dispatch to
static int __channelCount = 0; // # of channels left. When we hit 0, then remove our handler
static AudioBufferManager* __channelMap[12]; // Lets the IRQ handler figure out where to dispatch to
static bool __irqInstalled = false; // Have we put in our IRQ handler yet?
AudioBufferManager::AudioBufferManager(size_t bufferCount, size_t bufferWords, int32_t silenceSample, PinMode direction, enum dma_channel_transfer_size dmaSize) {
_running = false;
@@ -78,11 +79,6 @@ AudioBufferManager::~AudioBufferManager() {
dma_channel_unclaim(_channelDMA[i]);
__channelCount--;
}
if (!__channelCount) {
irq_set_enabled(DMA_IRQ_0, false);
// TODO - how can we know if there are no other parts of the core using DMA0 IRQ??
irq_remove_handler(DMA_IRQ_0, _irq);
}
}
interrupts();
for (int i = 0; i < 2; i++) {
@@ -120,7 +116,7 @@ bool AudioBufferManager::begin(int dreq, volatile void *pioFIFOAddr) {
return false;
}
}
bool needSetIRQ = __channelCount == 0;
// Need to know both channels to set up ping-pong, so do in 2 stages
for (auto i = 0; i < 2; i++) {
dma_channel_config c = dma_channel_get_default_config(_channelDMA[i]);
@@ -146,9 +142,10 @@ bool AudioBufferManager::begin(int dreq, volatile void *pioFIFOAddr) {
__channelMap[_channelDMA[i]] = this;
__channelCount++;
}
if (needSetIRQ) {
if (!__irqInstalled) {
irq_add_shared_handler(DMA_IRQ_0, _irq, PICO_SHARED_IRQ_HANDLER_DEFAULT_ORDER_PRIORITY);
irq_set_enabled(DMA_IRQ_0, true);
__irqInstalled = true;
}
dma_channel_start(_channelDMA[0]);
@@ -0,0 +1,64 @@
// A2DPSink example - Released to the public domain in 2024 by Earle F. Philhower, III
// Hook up a phono plug to GP0 and GP1 (and GND of course...the 1st 3 pins on the PCB)
// Connect wired earbuds up and connect over BT from your phone and play some music.
#include <BluetoothAudio.h>
#include <PWMAudio.h>
PWMAudio pwm;
A2DPSink a2dp;
volatile A2DPSink::PlaybackStatus status = A2DPSink::STOPPED;
void volumeCB(void *param, int pct) {
(void) param;
Serial.printf("Speaker volume changed to %d%%\n", pct);
}
void connectCB(void *param, bool connected) {
(void) param;
if (connected) {
Serial.printf("A2DP connection started to %s\n", bd_addr_to_str(a2dp.getSourceAddress()));
} else {
Serial.printf("A2DP connection stopped\n");
}
}
void playbackCB(void *param, A2DPSink::PlaybackStatus state) {
(void) param;
status = state;
}
void setup() {
Serial.begin(115200);
delay(3000);
Serial.printf("Starting, connect to the PicoW and start playing music\n");
Serial.printf("Use BOOTSEL to pause/resume playback\n");
a2dp.setName("PicoW Boom 00:00:00:00:00:00");
a2dp.setConsumer(new BluetoothAudioConsumerPWM(pwm));
a2dp.onVolume(volumeCB);
a2dp.onConnect(connectCB);
a2dp.onPlaybackStatus(playbackCB);
a2dp.begin();
}
char *nowPlaying = nullptr;
void loop() {
if (BOOTSEL) {
if (status == A2DPSink::PAUSED) {
a2dp.play();
Serial.printf("Resuming\n");
} else if (status == A2DPSink::PLAYING) {
a2dp.pause();
Serial.printf("Pausing\n");
}
while (BOOTSEL);
}
if (!nowPlaying || strcmp(nowPlaying, a2dp.trackTitle())) {
free(nowPlaying);
nowPlaying = strdup(a2dp.trackTitle());
Serial.printf("NOW PLAYING: %s\n", nowPlaying);
}
}
@@ -0,0 +1,100 @@
// Plays tones and Au Claire De La Lune over an A2DP connection
// Released to the public domain by Earle Philhower <earlephilhowwer@yahoo.com>
#include <BluetoothAudio.h>
#include "raw.h"
A2DPSource a2dp;
int16_t pcm[64 * 2];
uint32_t phase = 0;
volatile uint32_t fr = 32;
volatile uint32_t fl = 16;
volatile bool paused = false;
volatile bool playwav = false;
void avrcpCB(void *param, avrcp_operation_id_t op, int pressed) {
(void) param;
if (pressed && op == AVRCP_OPERATION_ID_FORWARD) {
// Change the sound when they hit play
fr = random(8, 64);
fl = random(8, 64);
Serial.printf("Now generating %lu, %lu\n", fr, fl);
} else if (pressed && op == AVRCP_OPERATION_ID_PLAY) {
paused = !paused;
if (paused) {
Serial.printf("Pausing\n");
} else {
Serial.printf("Resuming\n");
}
} else if (pressed && op == AVRCP_OPERATION_ID_BACKWARD) {
playwav = !playwav;
Serial.println(playwav ? "Playing 'Au Claire De La Lune'" : "Playing tones");
}
}
void volumeCB(void *param, int pct) {
(void) param;
Serial.printf("Speaker volume changed to %d%%\n", pct);
}
void connectCB(void *param, bool connected) {
(void) param;
if (connected) {
Serial.printf("A2DP connection started to %s\n", bd_addr_to_str(a2dp.getSinkAddress()));
} else {
Serial.printf("A2DP connection stopped\n");
}
}
void fillPCM() {
if (paused) {
bzero(pcm, sizeof(pcm));
return;
}
if (playwav) {
for (int i = 0; i < 64; i++) {
// Audio in flash is 8-bit signed mono, so shift left to make 16-bit and then play over both channels
pcm[i * 2] = auclairedelalune_raw[(i + phase) % sizeof(auclairedelalune_raw)] << 8;
pcm[i * 2 + 1] = auclairedelalune_raw[(i + phase) % sizeof(auclairedelalune_raw)] << 8;
}
} else {
for (int i = 0; i < 64; i++) {
pcm[i * 2] = ((i + phase) / fr) & 1 ? 3000 : -3000;
pcm[i * 2 + 1] = ((i + phase) / fl) & 1 ? 1000 : -1000;
}
}
phase += 64;
}
void setup() {
delay(2000);
a2dp.onAVRCP(avrcpCB);
a2dp.onVolume(volumeCB);
a2dp.onConnect(connectCB);
a2dp.begin();
Serial.printf("Starting, press BOOTSEL to pair to first found speaker\n");
Serial.printf("Use the forward button on speaker to change tones\n");
Serial.printf("Use the reverse button on speaker to alternate between tones and Au Claire De La Lune\n");
Serial.printf("Use the play button on speaker to pause/unpause the tone\n");
}
void loop() {
while ((size_t)a2dp.availableForWrite() > sizeof(pcm)) {
fillPCM();
a2dp.write((const uint8_t *)pcm, sizeof(pcm));
}
if (BOOTSEL) {
while (BOOTSEL) {
delay(1);
}
a2dp.disconnect();
a2dp.clearPairing();
Serial.printf("Connecting...");
if (a2dp.connect()) {
Serial.printf("Connected!\n");
} else {
Serial.printf("Failed! :(\n");
}
}
}
File diff suppressed because it is too large Load Diff
+59
View File
@@ -0,0 +1,59 @@
#######################################
# Syntax Coloring Map
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
BluetoothAudio KEYWORD1
A2DPSource KEYWORD1
BluetoothAudioConsumer KEYWORD1
BluetoothAudioConsumerI2S KEYWORD1
BluetoothAudioConsumerPWM KEYWORD1
A2DPSink KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
scan KEYWORD2
begin KEYWORD2
end KEYWORD2
setConsumer KEYWORD2
setFrequency KEYWORD2
setName KEYWORD2
setsetBufferSize KEYWORD2
getUnderflow KEYWORD2
getSinkAddress KEYWORD2
scan KEYWORD2
connect KEYWORD2
connected KEYWORD2
disconnect KEYWORD2
clearPairing KEYWORD2
connect KEYWORD2
play KEYWORD2
stop KEYWORD2
pause KEYWORD2
fastForward KEYWORD2
rewind KEYWORD2
forward KEYWORD2
backward KEYWORD2
volumeUp KEYWORD2
volumeDown KEYWORD2
mute KEYWORD2
onTransmit KEYWORD2
onAVRCP KEYWORD2
onBattery KEYWORD2
onVolume KEYWORD2
onConnect KEYWORD2
onPlaybackStatus KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################
STOPPED LITERAL
PLAYING LITERAL
PAUSED LITERAL
@@ -0,0 +1,11 @@
name=BluetoothAudio
version=1.0
author=Earle F. Philhower, III <earlephilhower@yahoo.com>
maintainer=Earle F. Philhower, III <earlephilhower@yahoo.com>
sentence=Plays and receives audio over Bluetooth A2DP
paragraph=Plays and receives audio over Bluetooth A2DP
category=Communication
url=http://github.com/earlephilhower/arduino-pico
architectures=rp2040
dot_a_linkage=true
depends=BluetoothHCI
+818
View File
@@ -0,0 +1,818 @@
/*
A2DP Sink (Bluetooth audio receiver)
Copyright (c) 2024 Earle F. Philhower, III <earlephilhower@yahoo.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "A2DPSink.h"
#include <functional>
#define CCALLBACKNAME _A2DPSINKCB
#include <ctocppcallback.h>
#define PACKETHANDLERCB(class, cbFcn) \
(CCALLBACKNAME<void(uint8_t, uint16_t, uint8_t*, uint16_t), __COUNTER__>::func = std::bind(&class::cbFcn, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4), \
static_cast<btstack_packet_handler_t>(CCALLBACKNAME<void(uint8_t, uint16_t, uint8_t*, uint16_t), __COUNTER__ - 1>::callback))
#define L2CAPPACKETHANDLERCB(class, cbFcn) \
(CCALLBACKNAME<void(uint8_t, uint8_t*, uint16_t), __COUNTER__>::func = std::bind(&class::cbFcn, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3), \
static_cast<void (*)(uint8_t, uint8_t *, uint16_t)>(CCALLBACKNAME<void(uint8_t, uint8_t*, uint16_t), __COUNTER__ - 1>::callback))
#define PCMDECODERCB(class, cbFcn) \
(CCALLBACKNAME<void(int16_t*, int, int, int, void*), __COUNTER__>::func = std::bind(&class::cbFcn, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5), \
static_cast<void (*)(int16_t *, int, int, int, void *)>(CCALLBACKNAME<void(int16_t *, int, int, int, void *), __COUNTER__ - 1>::callback))
// Based off of the BlueKitchen A2DP sink demo
/*
Copyright (C) 2023 BlueKitchen GmbH
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the names of
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
4. Any redistribution, use, or modification is done solely for
personal benefit and not for any commercial purpose or for
monetary gain.
THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN
GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
Please inquire about commercial licensing options at
contact@bluekitchen-gmbh.com
*/
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "btstack.h"
#include "btstack_resample.h"
#include "btstack_ring_buffer.h"
bool A2DPSink::begin() {
if (_running || !_consumer) {
return false;
}
// init protocols
l2cap_init();
sdp_init();
#ifdef ENABLE_BLE
// Initialize LE Security Manager. Needed for cross-transport key derivation
sm_init();
#endif
// Init profiles
a2dp_sink_init();
avrcp_init();
avrcp_controller_init();
avrcp_target_init();
// Configure A2DP Sink
a2dp_sink_register_packet_handler(PACKETHANDLERCB(A2DPSink, a2dp_sink_packet_handler));
a2dp_sink_register_media_handler(L2CAPPACKETHANDLERCB(A2DPSink, handle_l2cap_media_data_packet));
a2dp_sink_stream_endpoint_t * stream_endpoint = &a2dp_sink_stream_endpoint;
avdtp_stream_endpoint_t * local_stream_endpoint = a2dp_sink_create_stream_endpoint(AVDTP_AUDIO,
AVDTP_CODEC_SBC, media_sbc_codec_capabilities, sizeof(media_sbc_codec_capabilities),
stream_endpoint->media_sbc_codec_configuration, sizeof(stream_endpoint->media_sbc_codec_configuration));
if (!local_stream_endpoint) {
DEBUGV("A2DP Source: not enough memory to create local stream endpoint\n");
return false;
}
// - Store stream enpoint's SEP ID, as it is used by A2DP API to identify the stream endpoint
stream_endpoint->a2dp_local_seid = avdtp_local_seid(local_stream_endpoint);
// Configure AVRCP Controller + Target
avrcp_register_packet_handler(PACKETHANDLERCB(A2DPSink, avrcp_packet_handler));
avrcp_controller_register_packet_handler(PACKETHANDLERCB(A2DPSink, avrcp_controller_packet_handler));
avrcp_target_register_packet_handler(PACKETHANDLERCB(A2DPSink, avrcp_target_packet_handler));
// Configure SDP
// - Create and register A2DP Sink service record
memset(sdp_avdtp_sink_service_buffer, 0, sizeof(sdp_avdtp_sink_service_buffer));
a2dp_sink_create_sdp_record(sdp_avdtp_sink_service_buffer, sdp_create_service_record_handle(),
AVDTP_SINK_FEATURE_MASK_HEADPHONE, NULL, NULL);
sdp_register_service(sdp_avdtp_sink_service_buffer);
// - Create AVRCP Controller service record and register it with SDP. We send Category 1 commands to the media player, e.g. play/pause
memset(sdp_avrcp_controller_service_buffer, 0, sizeof(sdp_avrcp_controller_service_buffer));
uint16_t controller_supported_features = 1 << AVRCP_CONTROLLER_SUPPORTED_FEATURE_CATEGORY_PLAYER_OR_RECORDER;
avrcp_controller_create_sdp_record(sdp_avrcp_controller_service_buffer, sdp_create_service_record_handle(),
controller_supported_features, NULL, NULL);
sdp_register_service(sdp_avrcp_controller_service_buffer);
// - Create and register A2DP Sink service record
// - We receive Category 2 commands from the media player, e.g. volume up/down
memset(sdp_avrcp_target_service_buffer, 0, sizeof(sdp_avrcp_target_service_buffer));
uint16_t target_supported_features = 1 << AVRCP_TARGET_SUPPORTED_FEATURE_CATEGORY_MONITOR_OR_AMPLIFIER;
avrcp_target_create_sdp_record(sdp_avrcp_target_service_buffer,
sdp_create_service_record_handle(), target_supported_features, NULL, NULL);
sdp_register_service(sdp_avrcp_target_service_buffer);
// - Create and register Device ID (PnP) service record
memset(device_id_sdp_service_buffer, 0, sizeof(device_id_sdp_service_buffer));
device_id_create_sdp_record(device_id_sdp_service_buffer,
sdp_create_service_record_handle(), DEVICE_ID_VENDOR_ID_SOURCE_BLUETOOTH, BLUETOOTH_COMPANY_ID_BLUEKITCHEN_GMBH, 1, 1);
sdp_register_service(device_id_sdp_service_buffer);
// Configure GAP - discovery / connection
// - Set local name with a template Bluetooth address, that will be automatically
// replaced with an actual address once it is available, i.e. when BTstack boots
// up and starts talking to a Bluetooth module.
if (!_name) {
setName("PicoW A2DP 00:00:00:00:00:00");
}
gap_set_local_name(_name);
// - Allow to show up in Bluetooth inquiry
gap_discoverable_control(1);
// - Set Class of Device - Service Class: Audio, Major Device Class: Audio, Minor: Loudspeaker
gap_set_class_of_device(0x200414);
// - Allow for role switch in general and sniff mode
gap_set_default_link_policy_settings(LM_LINK_POLICY_ENABLE_ROLE_SWITCH | LM_LINK_POLICY_ENABLE_SNIFF_MODE);
// - Allow for role switch on outgoing connections
// - This allows A2DP Source, e.g. smartphone, to become master when we re-connect to it.
gap_set_allow_role_switch(true);
// Register for HCI events
// hci_event_callback_registration.callback = &hci_packet_handler;
// hci_add_event_handler(&hci_event_callback_registration);
_hci.install();
_running = true;
_hci.begin();
return true;
}
bool A2DPSink::disconnect() {
BluetoothLock b;
if (_connected) {
a2dp_sink_disconnect(a2dp_sink_a2dp_connection.a2dp_cid);
}
if (!_running || !_connected) {
return false;
}
_connected = false;
return true;
}
void A2DPSink::clearPairing() {
BluetoothLock b;
if (_connected) {
a2dp_sink_disconnect(a2dp_sink_a2dp_connection.a2dp_cid);
}
gap_delete_all_link_keys();
}
void A2DPSink::playback_handler(int16_t * buffer, uint16_t num_audio_frames) {
// called from lower-layer but guaranteed to be on main thread
if (sbc_frame_size == 0) {
memset(buffer, 0, num_audio_frames * BYTES_PER_FRAME);
return;
}
// first fill from resampled audio
uint32_t bytes_read;
btstack_ring_buffer_read(&decoded_audio_ring_buffer, (uint8_t *) buffer, num_audio_frames * BYTES_PER_FRAME, &bytes_read);
buffer += bytes_read / NUM_CHANNELS;
num_audio_frames -= bytes_read / BYTES_PER_FRAME;
// then start decoding sbc frames using request_* globals
request_buffer = buffer;
request_frames = num_audio_frames;
while (request_frames && btstack_ring_buffer_bytes_available(&sbc_frame_ring_buffer) >= sbc_frame_size) {
// decode frame
uint8_t sbc_frame[MAX_SBC_FRAME_SIZE];
btstack_ring_buffer_read(&sbc_frame_ring_buffer, sbc_frame, sbc_frame_size, &bytes_read);
btstack_sbc_decoder_process_data(&state, 0, sbc_frame, sbc_frame_size);
}
while (request_frames) {
*(request_buffer++) = 0;
*(request_buffer++) = 0;
request_frames--;
}
}
void A2DPSink::handle_pcm_data(int16_t * data, int num_audio_frames, int num_channels, int sample_rate, void * context) {
UNUSED(sample_rate);
UNUSED(context);
UNUSED(num_channels); // must be stereo == 2
// resample into request buffer - add some additional space for resampling
uint32_t resampled_frames = btstack_resample_block(&resample_instance, data, num_audio_frames, output_buffer);
// store data in btstack_audio buffer first
int frames_to_copy = btstack_min(resampled_frames, request_frames);
memcpy(request_buffer, output_buffer, frames_to_copy * BYTES_PER_FRAME);
request_frames -= frames_to_copy;
request_buffer += frames_to_copy * NUM_CHANNELS;
// and rest in ring buffer
int frames_to_store = resampled_frames - frames_to_copy;
if (frames_to_store) {
int status = btstack_ring_buffer_write(&decoded_audio_ring_buffer, (uint8_t *)&output_buffer[frames_to_copy * NUM_CHANNELS], frames_to_store * BYTES_PER_FRAME);
if (status) {
DEBUGV("Error storing samples in PCM ring buffer!!!\n");
}
}
}
int A2DPSink::media_processing_init(BluetoothMediaCodecConfigurationSBC * configuration) {
if (media_initialized) {
return 0;
}
btstack_sbc_decoder_init(&state, mode, PCMDECODERCB(A2DPSink, handle_pcm_data), NULL);
btstack_ring_buffer_init(&sbc_frame_ring_buffer, sbc_frame_storage, sizeof(sbc_frame_storage));
btstack_ring_buffer_init(&decoded_audio_ring_buffer, decoded_audio_storage, sizeof(decoded_audio_storage));
btstack_resample_init(&resample_instance, configuration->num_channels);
// setup audio playback
_consumer->init(NUM_CHANNELS, configuration->sampling_frequency, this);
audio_stream_started = 0;
media_initialized = 1;
return 0;
}
void A2DPSink::media_processing_start(void) {
if (!media_initialized) {
return;
}
// setup audio playback
_consumer->startStream();
audio_stream_started = 1;
}
void A2DPSink::media_processing_pause(void) {
if (!media_initialized) {
return;
}
// stop audio playback
audio_stream_started = 0;
_consumer->stopStream();
// discard pending data
btstack_ring_buffer_reset(&decoded_audio_ring_buffer);
btstack_ring_buffer_reset(&sbc_frame_ring_buffer);
}
void A2DPSink::media_processing_close(void) {
if (!media_initialized) {
return;
}
media_initialized = 0;
audio_stream_started = 0;
sbc_frame_size = 0;
// stop audio playback
_consumer->close();
}
/* @section Handle Media Data Packet
@text Here the audio data, are received through the handle_l2cap_media_data_packet callback.
Currently, only the SBC media codec is supported. Hence, the media data consists of the media packet header and the SBC packet.
The SBC frame will be stored in a ring buffer for later processing (instead of decoding it to PCM right away which would require a much larger buffer).
If the audio stream wasn't started already and there are enough SBC frames in the ring buffer, start playback.
*/
void A2DPSink::handle_l2cap_media_data_packet(uint8_t seid, uint8_t *packet, uint16_t size) {
UNUSED(seid);
int pos = 0;
avdtp_media_packet_header_t media_header;
if (!read_media_data_header(packet, size, &pos, &media_header)) {
return;
}
avdtp_sbc_codec_header_t sbc_header;
if (!read_sbc_header(packet, size, &pos, &sbc_header)) {
return;
}
int packet_length = size - pos;
uint8_t *packet_begin = packet + pos;
// store sbc frame size for buffer management
sbc_frame_size = packet_length / sbc_header.num_frames;
int status = btstack_ring_buffer_write(&sbc_frame_ring_buffer, packet_begin, packet_length);
if (status != ERROR_CODE_SUCCESS) {
DEBUGV("Error storing samples in SBC ring buffer!!!\n");
}
// decide on audio sync drift based on number of sbc frames in queue
int sbc_frames_in_buffer = btstack_ring_buffer_bytes_available(&sbc_frame_ring_buffer) / sbc_frame_size;
uint32_t resampling_factor;
// nominal factor (fixed-point 2^16) and compensation offset
uint32_t nominal_factor = 0x10000;
uint32_t compensation = 0x00100;
if (sbc_frames_in_buffer < OPTIMAL_FRAMES_MIN) {
resampling_factor = nominal_factor - compensation; // stretch samples
} else if (sbc_frames_in_buffer <= OPTIMAL_FRAMES_MAX) {
resampling_factor = nominal_factor; // nothing to do
} else {
resampling_factor = nominal_factor + compensation; // compress samples
}
btstack_resample_set_factor(&resample_instance, resampling_factor);
// start stream if enough frames buffered
if (!audio_stream_started && sbc_frames_in_buffer >= OPTIMAL_FRAMES_MIN) {
media_processing_start();
}
}
int A2DPSink::read_sbc_header(uint8_t * packet, int size, int * offset, avdtp_sbc_codec_header_t * sbc_header) {
int sbc_header_len = 12; // without crc
int pos = *offset;
if (size - pos < sbc_header_len) {
DEBUGV("Not enough data to read SBC header, expected %d, received %d\n", sbc_header_len, size - pos);
return 0;
}
sbc_header->fragmentation = get_bit16(packet[pos], 7);
sbc_header->starting_packet = get_bit16(packet[pos], 6);
sbc_header->last_packet = get_bit16(packet[pos], 5);
sbc_header->num_frames = packet[pos] & 0x0f;
pos++;
*offset = pos;
return 1;
}
int A2DPSink::read_media_data_header(uint8_t *packet, int size, int *offset, avdtp_media_packet_header_t *media_header) {
int media_header_len = 12; // without crc
int pos = *offset;
if (size - pos < media_header_len) {
DEBUGV("Not enough data to read media packet header, expected %d, received %d\n", media_header_len, size - pos);
return 0;
}
media_header->version = packet[pos] & 0x03;
media_header->padding = get_bit16(packet[pos], 2);
media_header->extension = get_bit16(packet[pos], 3);
media_header->csrc_count = (packet[pos] >> 4) & 0x0F;
pos++;
media_header->marker = get_bit16(packet[pos], 0);
media_header->payload_type = (packet[pos] >> 1) & 0x7F;
pos++;
media_header->sequence_number = big_endian_read_16(packet, pos);
pos += 2;
media_header->timestamp = big_endian_read_32(packet, pos);
pos += 4;
media_header->synchronization_source = big_endian_read_32(packet, pos);
pos += 4;
*offset = pos;
return 1;
}
void A2DPSink::avrcp_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
UNUSED(channel);
UNUSED(size);
uint16_t local_cid;
uint8_t status;
bd_addr_t address;
a2dp_sink_avrcp_connection_t * connection = &a2dp_sink_avrcp_connection;
if (packet_type != HCI_EVENT_PACKET) {
return;
}
if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) {
return;
}
switch (packet[2]) {
case AVRCP_SUBEVENT_CONNECTION_ESTABLISHED: {
local_cid = avrcp_subevent_connection_established_get_avrcp_cid(packet);
status = avrcp_subevent_connection_established_get_status(packet);
if (status != ERROR_CODE_SUCCESS) {
DEBUGV("AVRCP: Connection failed, status 0x%02x\n", status);
connection->avrcp_cid = 0;
return;
}
connection->avrcp_cid = local_cid;
avrcp_subevent_connection_established_get_bd_addr(packet, address);
DEBUGV("AVRCP: Connected to %s, cid 0x%02x\n", bd_addr_to_str(address), connection->avrcp_cid);
avrcp_target_support_event(connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_VOLUME_CHANGED);
avrcp_target_support_event(connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_BATT_STATUS_CHANGED);
avrcp_target_battery_status_changed(connection->avrcp_cid, battery_status);
// query supported events:
avrcp_controller_get_supported_events(connection->avrcp_cid);
return;
}
case AVRCP_SUBEVENT_CONNECTION_RELEASED:
DEBUGV("AVRCP: Channel released: cid 0x%02x\n", avrcp_subevent_connection_released_get_avrcp_cid(packet));
connection->avrcp_cid = 0;
connection->notifications_supported_by_target = 0;
return;
default:
break;
}
}
void A2DPSink::avrcp_controller_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
UNUSED(channel);
UNUSED(size);
// helper to print c strings
uint8_t avrcp_subevent_value[256];
uint8_t play_status;
uint8_t event_id;
a2dp_sink_avrcp_connection_t * avrcp_connection = &a2dp_sink_avrcp_connection;
if (packet_type != HCI_EVENT_PACKET) {
return;
}
if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) {
return;
}
if (avrcp_connection->avrcp_cid == 0) {
return;
}
memset(avrcp_subevent_value, 0, sizeof(avrcp_subevent_value));
switch (packet[2]) {
case AVRCP_SUBEVENT_GET_CAPABILITY_EVENT_ID:
avrcp_connection->notifications_supported_by_target |= (1 << avrcp_subevent_get_capability_event_id_get_event_id(packet));
break;
case AVRCP_SUBEVENT_GET_CAPABILITY_EVENT_ID_DONE:
DEBUGV("AVRCP Controller: supported notifications by target:\n");
for (event_id = (uint8_t) AVRCP_NOTIFICATION_EVENT_FIRST_INDEX; event_id < (uint8_t) AVRCP_NOTIFICATION_EVENT_LAST_INDEX; event_id++) {
DEBUGV(" - [%s] %s\n",
(avrcp_connection->notifications_supported_by_target & (1 << event_id)) != 0 ? "X" : " ",
avrcp_notification2str((avrcp_notification_event_id_t)event_id));
}
DEBUGV("\n\n");
// automatically enable notifications
avrcp_controller_enable_notification(avrcp_connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_PLAYBACK_STATUS_CHANGED);
avrcp_controller_enable_notification(avrcp_connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_NOW_PLAYING_CONTENT_CHANGED);
avrcp_controller_enable_notification(avrcp_connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED);
break;
case AVRCP_SUBEVENT_NOTIFICATION_STATE:
event_id = (avrcp_notification_event_id_t)avrcp_subevent_notification_state_get_event_id(packet);
DEBUGV("AVRCP Controller: %s notification registered\n", avrcp_notification2str((avrcp_notification_event_id_t)event_id));
break;
case AVRCP_SUBEVENT_NOTIFICATION_PLAYBACK_POS_CHANGED:
DEBUGV("AVRCP Controller: Playback position changed, position %d ms\n", (unsigned int) avrcp_subevent_notification_playback_pos_changed_get_playback_position_ms(packet));
break;
case AVRCP_SUBEVENT_NOTIFICATION_PLAYBACK_STATUS_CHANGED:
DEBUGV("AVRCP Controller: Playback status changed %s\n", avrcp_play_status2str(avrcp_subevent_notification_playback_status_changed_get_play_status(packet)));
play_status = avrcp_subevent_notification_playback_status_changed_get_play_status(packet);
switch (play_status) {
case AVRCP_PLAYBACK_STATUS_PLAYING:
avrcp_connection->playing = true;
break;
default:
avrcp_connection->playing = false;
break;
}
if (_playbackStatusCB) {
PlaybackStatus status;
switch (play_status) {
case AVRCP_PLAYBACK_STATUS_PLAYING:
status = PLAYING;
break;
case AVRCP_PLAYBACK_STATUS_PAUSED:
status = PAUSED;
break;
default:
status = STOPPED;
break;
}
_playbackStatusCB(_playbackStatusData, status);
}
break;
case AVRCP_SUBEVENT_NOTIFICATION_NOW_PLAYING_CONTENT_CHANGED:
DEBUGV("AVRCP Controller: Playing content changed\n");
break;
case AVRCP_SUBEVENT_NOTIFICATION_TRACK_CHANGED:
_title[0] = 0;
_artist[0] = 0;
_album[0] = 0;
_genre[0] = 0;
avrcp_controller_get_now_playing_info(avrcp_connection->avrcp_cid);
if (_trackChangedCB) {
_trackChangedCB(_trackChangedData);
}
DEBUGV("AVRCP Controller: Track changed\n");
break;
case AVRCP_SUBEVENT_NOTIFICATION_AVAILABLE_PLAYERS_CHANGED:
DEBUGV("AVRCP Controller: Available Players Changed\n");
break;
case AVRCP_SUBEVENT_SHUFFLE_AND_REPEAT_MODE: {
uint8_t shuffle_mode = avrcp_subevent_shuffle_and_repeat_mode_get_shuffle_mode(packet);
uint8_t repeat_mode = avrcp_subevent_shuffle_and_repeat_mode_get_repeat_mode(packet);
(void) shuffle_mode;
(void) repeat_mode;
DEBUGV("AVRCP Controller: %s, %s\n", avrcp_shuffle2str(shuffle_mode), avrcp_repeat2str(repeat_mode));
break;
}
case AVRCP_SUBEVENT_NOW_PLAYING_TRACK_INFO:
DEBUGV("AVRCP Controller: Track %d\n", avrcp_subevent_now_playing_track_info_get_track(packet));
break;
case AVRCP_SUBEVENT_NOW_PLAYING_TOTAL_TRACKS_INFO:
DEBUGV("AVRCP Controller: Total Tracks %d\n", avrcp_subevent_now_playing_total_tracks_info_get_total_tracks(packet));
break;
case AVRCP_SUBEVENT_NOW_PLAYING_TITLE_INFO:
if (avrcp_subevent_now_playing_title_info_get_value_len(packet) > 0) {
memcpy(avrcp_subevent_value, avrcp_subevent_now_playing_title_info_get_value(packet), avrcp_subevent_now_playing_title_info_get_value_len(packet));
strncpy(_title, (char *)avrcp_subevent_value, sizeof(_title));
_title[sizeof(_title) - 1] = 0;
DEBUGV("AVRCP Controller: Title %s\n", avrcp_subevent_value);
}
break;
case AVRCP_SUBEVENT_NOW_PLAYING_ARTIST_INFO:
if (avrcp_subevent_now_playing_artist_info_get_value_len(packet) > 0) {
memcpy(avrcp_subevent_value, avrcp_subevent_now_playing_artist_info_get_value(packet), avrcp_subevent_now_playing_artist_info_get_value_len(packet));
strncpy(_artist, (char *)avrcp_subevent_value, sizeof(_artist));
_artist[sizeof(_artist) - 1] = 0;
DEBUGV("AVRCP Controller: Artist %s\n", avrcp_subevent_value);
}
break;
case AVRCP_SUBEVENT_NOW_PLAYING_ALBUM_INFO:
if (avrcp_subevent_now_playing_album_info_get_value_len(packet) > 0) {
memcpy(avrcp_subevent_value, avrcp_subevent_now_playing_album_info_get_value(packet), avrcp_subevent_now_playing_album_info_get_value_len(packet));
strncpy(_album, (char *)avrcp_subevent_value, sizeof(_album));
_album[sizeof(_album) - 1] = 0;
DEBUGV("AVRCP Controller: Album %s\n", avrcp_subevent_value);
}
break;
case AVRCP_SUBEVENT_NOW_PLAYING_GENRE_INFO:
if (avrcp_subevent_now_playing_genre_info_get_value_len(packet) > 0) {
memcpy(avrcp_subevent_value, avrcp_subevent_now_playing_genre_info_get_value(packet), avrcp_subevent_now_playing_genre_info_get_value_len(packet));
strncpy(_genre, (char *)avrcp_subevent_value, sizeof(_genre));
_genre[sizeof(_genre) - 1] = 0;
DEBUGV("AVRCP Controller: Genre %s\n", avrcp_subevent_value);
}
break;
case AVRCP_SUBEVENT_PLAY_STATUS:
DEBUGV("AVRCP Controller: Song length %" PRIu32 " ms, Song position %" PRIu32 " ms, Play status %s\n",
avrcp_subevent_play_status_get_song_length(packet),
avrcp_subevent_play_status_get_song_position(packet),
avrcp_play_status2str(avrcp_subevent_play_status_get_play_status(packet)));
break;
case AVRCP_SUBEVENT_OPERATION_COMPLETE:
DEBUGV("AVRCP Controller: %s complete\n", avrcp_operation2str(avrcp_subevent_operation_complete_get_operation_id(packet)));
break;
case AVRCP_SUBEVENT_OPERATION_START:
DEBUGV("AVRCP Controller: %s start\n", avrcp_operation2str(avrcp_subevent_operation_start_get_operation_id(packet)));
break;
case AVRCP_SUBEVENT_NOTIFICATION_EVENT_TRACK_REACHED_END:
DEBUGV("AVRCP Controller: Track reached end\n");
break;
case AVRCP_SUBEVENT_PLAYER_APPLICATION_VALUE_RESPONSE:
DEBUGV("AVRCP Controller: Set Player App Value %s\n", avrcp_ctype2str(avrcp_subevent_player_application_value_response_get_command_type(packet)));
break;
default:
break;
}
}
void A2DPSink::avrcp_target_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
UNUSED(channel);
UNUSED(size);
if (packet_type != HCI_EVENT_PACKET) {
return;
}
if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) {
return;
}
uint8_t volume;
char const * button_state;
(void) button_state;
avrcp_operation_id_t operation_id;
switch (packet[2]) {
case AVRCP_SUBEVENT_NOTIFICATION_VOLUME_CHANGED:
volume = avrcp_subevent_notification_volume_changed_get_absolute_volume(packet);
volume_percentage = volume * 100 / 127;
DEBUGV("AVRCP Target : Volume set to %d%% (%d)\n", volume_percentage, volume);
_consumer->setVolume(volume);
break;
case AVRCP_SUBEVENT_OPERATION:
operation_id = (avrcp_operation_id_t)avrcp_subevent_operation_get_operation_id(packet);
button_state = avrcp_subevent_operation_get_button_pressed(packet) > 0 ? "PRESS" : "RELEASE";
DEBUGV("AVRCP Target: operation %s (%s)\n", avrcp_operation2str(operation_id), button_state);
if (_avrcpCB) {
_avrcpCB(_avrcpData, operation_id, avrcp_subevent_operation_get_button_pressed(packet) > 0);
}
switch (operation_id) {
case AVRCP_OPERATION_ID_VOLUME_UP:
DEBUGV("AVRCP Target : VOLUME UP (%s)\n", button_state);
break;
case AVRCP_OPERATION_ID_VOLUME_DOWN:
DEBUGV("AVRCP Target : VOLUME DOWN (%s)\n", button_state);
break;
default:
return;
}
break;
default:
DEBUGV("AVRCP Target : Event 0x%02x is not parsed\n", packet[2]);
break;
}
}
void A2DPSink::a2dp_sink_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
UNUSED(channel);
UNUSED(size);
uint8_t status;
uint8_t allocation_method;
if (packet_type != HCI_EVENT_PACKET) {
return;
}
if (hci_event_packet_get_type(packet) != HCI_EVENT_A2DP_META) {
return;
}
a2dp_sink_a2dp_connection_t * a2dp_conn = &a2dp_sink_a2dp_connection;
switch (packet[2]) {
case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_OTHER_CONFIGURATION:
DEBUGV("A2DP Sink : Received non SBC codec - not implemented\n");
break;
case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_SBC_CONFIGURATION: {
DEBUGV("A2DP Sink : Received SBC codec configuration\n");
a2dp_conn->sbc_configuration.reconfigure = a2dp_subevent_signaling_media_codec_sbc_configuration_get_reconfigure(packet);
a2dp_conn->sbc_configuration.num_channels = a2dp_subevent_signaling_media_codec_sbc_configuration_get_num_channels(packet);
a2dp_conn->sbc_configuration.sampling_frequency = a2dp_subevent_signaling_media_codec_sbc_configuration_get_sampling_frequency(packet);
a2dp_conn->sbc_configuration.block_length = a2dp_subevent_signaling_media_codec_sbc_configuration_get_block_length(packet);
a2dp_conn->sbc_configuration.subbands = a2dp_subevent_signaling_media_codec_sbc_configuration_get_subbands(packet);
a2dp_conn->sbc_configuration.min_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_min_bitpool_value(packet);
a2dp_conn->sbc_configuration.max_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_max_bitpool_value(packet);
allocation_method = a2dp_subevent_signaling_media_codec_sbc_configuration_get_allocation_method(packet);
// Adapt Bluetooth spec definition to SBC Encoder expected input
a2dp_conn->sbc_configuration.allocation_method = (btstack_sbc_allocation_method_t)(allocation_method - 1);
switch (a2dp_subevent_signaling_media_codec_sbc_configuration_get_channel_mode(packet)) {
case AVDTP_CHANNEL_MODE_JOINT_STEREO:
a2dp_conn->sbc_configuration.channel_mode = SBC_CHANNEL_MODE_JOINT_STEREO;
break;
case AVDTP_CHANNEL_MODE_STEREO:
a2dp_conn->sbc_configuration.channel_mode = SBC_CHANNEL_MODE_STEREO;
break;
case AVDTP_CHANNEL_MODE_DUAL_CHANNEL:
a2dp_conn->sbc_configuration.channel_mode = SBC_CHANNEL_MODE_DUAL_CHANNEL;
break;
case AVDTP_CHANNEL_MODE_MONO:
a2dp_conn->sbc_configuration.channel_mode = SBC_CHANNEL_MODE_MONO;
break;
default:
btstack_assert(false);
break;
}
a2dp_conn->sbc_configuration.dump();
break;
}
case A2DP_SUBEVENT_STREAM_ESTABLISHED:
status = a2dp_subevent_stream_established_get_status(packet);
if (status != ERROR_CODE_SUCCESS) {
DEBUGV("A2DP Sink : Streaming connection failed, status 0x%02x\n", status);
break;
}
a2dp_subevent_stream_established_get_bd_addr(packet, a2dp_conn->addr);
a2dp_conn->a2dp_cid = a2dp_subevent_stream_established_get_a2dp_cid(packet);
a2dp_conn->a2dp_local_seid = a2dp_subevent_stream_established_get_local_seid(packet);
a2dp_conn->stream_state = STREAM_STATE_OPEN;
DEBUGV("A2DP Sink : Streaming connection is established, address %s, cid 0x%02x, local seid %d\n",
bd_addr_to_str(a2dp_conn->addr), a2dp_conn->a2dp_cid, a2dp_conn->a2dp_local_seid);
memcpy(_sourceAddress, a2dp_conn->addr, sizeof(_sourceAddress));
break;
case A2DP_SUBEVENT_STREAM_STARTED:
DEBUGV("A2DP Sink : Stream started\n");
a2dp_conn->stream_state = STREAM_STATE_PLAYING;
if (a2dp_conn->sbc_configuration.reconfigure) {
media_processing_close();
}
// prepare media processing
media_processing_init(&a2dp_conn->sbc_configuration);
// audio stream is started when buffer reaches minimal level
_connected = true;
if (_connectCB) {
_connectCB(_connectData, true);
}
break;
case A2DP_SUBEVENT_STREAM_SUSPENDED:
DEBUGV("A2DP Sink : Stream paused\n");
a2dp_conn->stream_state = STREAM_STATE_PAUSED;
media_processing_pause();
break;
case A2DP_SUBEVENT_STREAM_RELEASED:
DEBUGV("A2DP Sink : Stream released\n");
a2dp_conn->stream_state = STREAM_STATE_CLOSED;
media_processing_close();
break;
case A2DP_SUBEVENT_SIGNALING_CONNECTION_RELEASED:
DEBUGV("A2DP Sink : Signaling connection released\n");
a2dp_conn->a2dp_cid = 0;
media_processing_close();
_connected = false;
if (_connectCB) {
_connectCB(_connectData, false);
}
break;
default:
break;
}
}
+337
View File
@@ -0,0 +1,337 @@
/*
A2DP Sink (Bluetooth audio receiver)
Copyright (c) 2024 Earle F. Philhower, III <earlephilhower@yahoo.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#pragma once
#include <Arduino.h>
#include <BluetoothHCI.h>
#include <BluetoothLock.h>
#include "BluetoothAudioConsumer.h"
#include "BluetoothMediaConfigurationSBC.h"
#include "btstack.h"
#include "btstack_resample.h"
#include "btstack_ring_buffer.h"
class A2DPSink : public Stream {
public:
A2DPSink() {
_title[0] = 0;
_artist[0] = 0;
_album[0] = 0;
_genre[0] = 0;
}
virtual int available() override {
return 0; // Unreadable, this is output only
}
virtual int read() override {
return 0;
}
virtual int peek() override {
return 0;
}
virtual void flush() override {
}
virtual size_t write(const uint8_t *buffer, size_t size) override {
(void) buffer;
(void) size;
return 0;
}
virtual int availableForWrite() override {
return 0;
}
virtual size_t write(uint8_t s) override {
(void) s;
return 0;
}
bool setName(const char *name) {
if (_running) {
return false;
}
free(_name);
_name = strdup(name);
return true;
}
void onTransmit(void (*cb)(void *), void *cbData = nullptr) {
_transmitCB = cb;
_transmitData = cbData;
}
void onAVRCP(void (*cb)(void *, avrcp_operation_id_t, int), void *cbData = nullptr) {
_avrcpCB = cb;
_avrcpData = cbData;
}
void onBattery(void (*cb)(void *, avrcp_battery_status_t), void *cbData = nullptr) {
_batteryCB = cb;
_batteryData = cbData;
}
void onVolume(void (*cb)(void *, int), void *cbData = nullptr) {
_volumeCB = cb;
_volumeData = cbData;
}
void onConnect(void (*cb)(void *, bool), void *cbData = nullptr) {
_connectCB = cb;
_connectData = cbData;
}
void onTrackChanged(void (*cb)(void *), void *cbData = nullptr) {
_trackChangedCB = cb;
_trackChangedData = cbData;
}
typedef enum { STOPPED, PLAYING, PAUSED } PlaybackStatus;
void onPlaybackStatus(void (*cb)(void *, PlaybackStatus), void *cbData = nullptr) {
_playbackStatusCB = cb;
_playbackStatusData = cbData;
}
const uint8_t *getSourceAddress() {
if (!_connected) {
return nullptr;
} else {
return _sourceAddress;
}
}
void setConsumer(BluetoothAudioConsumer_ *c) {
_consumer = c;
}
bool begin();
bool disconnect();
void clearPairing();
void playback_handler(int16_t * buffer, uint16_t num_audio_frames);
void play() {
BluetoothLock b;
if (_connected) {
avrcp_controller_play(a2dp_sink_avrcp_connection.avrcp_cid);
}
}
void stop() {
BluetoothLock b;
if (_connected) {
avrcp_controller_stop(a2dp_sink_avrcp_connection.avrcp_cid);
}
}
void pause() {
BluetoothLock b;
if (_connected) {
avrcp_controller_pause(a2dp_sink_avrcp_connection.avrcp_cid);
}
}
void fastForward() {
BluetoothLock b;
if (_connected) {
avrcp_controller_fast_forward(a2dp_sink_avrcp_connection.avrcp_cid);
}
}
void rewind() {
BluetoothLock b;
if (_connected) {
avrcp_controller_rewind(a2dp_sink_avrcp_connection.avrcp_cid);
}
}
void forward() {
BluetoothLock b;
if (_connected) {
avrcp_controller_forward(a2dp_sink_avrcp_connection.avrcp_cid);
}
}
void backward() {
BluetoothLock b;
if (_connected) {
avrcp_controller_backward(a2dp_sink_avrcp_connection.avrcp_cid);
}
}
void volumeUp() {
BluetoothLock b;
if (_connected) {
avrcp_controller_volume_up(a2dp_sink_avrcp_connection.avrcp_cid);
}
}
void volumeDown() {
BluetoothLock b;
if (_connected) {
avrcp_controller_volume_down(a2dp_sink_avrcp_connection.avrcp_cid);
}
}
void mute() {
BluetoothLock b;
if (_connected) {
avrcp_controller_mute(a2dp_sink_avrcp_connection.avrcp_cid);
}
}
const char *trackTitle() {
return _title;
}
const char *trackArtist() {
return _artist;
}
const char *trackAlbum() {
return _album;
}
const char *trackGenre() {
return _genre;
}
private:
void handle_pcm_data(int16_t * data, int num_audio_frames, int num_channels, int sample_rate, void * context);
int media_processing_init(BluetoothMediaCodecConfigurationSBC * configuration);
void media_processing_start();
void media_processing_pause();
void media_processing_close();
void handle_l2cap_media_data_packet(uint8_t seid, uint8_t *packet, uint16_t size);
int read_sbc_header(uint8_t * packet, int size, int * offset, avdtp_sbc_codec_header_t * sbc_header);
int read_media_data_header(uint8_t *packet, int size, int *offset, avdtp_media_packet_header_t *media_header);
void avrcp_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
void avrcp_controller_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
void avrcp_target_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
void a2dp_sink_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
BluetoothHCI _hci;
BluetoothAudioConsumer_ *_consumer = nullptr;
bool _running = false;
bool _connected = false;
// Callbacks
void (*_transmitCB)(void *) = nullptr;
void *_transmitData;
void (*_avrcpCB)(void *, avrcp_operation_id_t, int) = nullptr;
void *_avrcpData;
void (*_batteryCB)(void *, avrcp_battery_status_t) = nullptr;
void *_batteryData;
void (*_volumeCB)(void *, int) = nullptr;
void *_volumeData;
void (*_connectCB)(void *, bool) = nullptr;
void *_connectData;
void (*_playbackStatusCB)(void *, PlaybackStatus) = nullptr;
void *_playbackStatusData;
void (*_trackChangedCB)(void *) = nullptr;
void *_trackChangedData;
char *_name = nullptr;
uint8_t _sourceAddress[6];
enum { NUM_CHANNELS = 2, BYTES_PER_FRAME = (2 * NUM_CHANNELS), MAX_SBC_FRAME_SIZE = 120 };
uint8_t sdp_avdtp_sink_service_buffer[150];
uint8_t sdp_avrcp_target_service_buffer[150];
uint8_t sdp_avrcp_controller_service_buffer[200];
uint8_t device_id_sdp_service_buffer[100];
// we support all configurations with bitpool 2-53
const uint8_t media_sbc_codec_capabilities[4] = {
0xFF,//(AVDTP_SBC_44100 << 4) | AVDTP_SBC_STEREO,
0xFF,//(AVDTP_SBC_BLOCK_LENGTH_16 << 4) | (AVDTP_SBC_SUBBANDS_8 << 2) | AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS,
2, 53
};
// SBC Decoder for WAV file or live playback
btstack_sbc_decoder_state_t state;
btstack_sbc_mode_t mode = SBC_MODE_STANDARD;
// ring buffer for SBC Frames
// below 30: add samples, 30-40: fine, above 40: drop samples
enum { OPTIMAL_FRAMES_MIN = 60, OPTIMAL_FRAMES_MAX = 80, ADDITIONAL_FRAMES = 30 };
uint8_t sbc_frame_storage[(OPTIMAL_FRAMES_MAX + ADDITIONAL_FRAMES) * MAX_SBC_FRAME_SIZE];
btstack_ring_buffer_t sbc_frame_ring_buffer;
unsigned int sbc_frame_size;
// overflow buffer for not fully used sbc frames, with additional frames for resampling
uint8_t decoded_audio_storage[(128 + 16) * BYTES_PER_FRAME];
btstack_ring_buffer_t decoded_audio_ring_buffer;
int media_initialized = 0;
int audio_stream_started;
btstack_resample_t resample_instance;
// temp storage of lower-layer request for audio samples
int16_t * request_buffer;
int request_frames;
// sink state
int volume_percentage = 0;
avrcp_battery_status_t battery_status = AVRCP_BATTERY_STATUS_WARNING;
typedef enum {
STREAM_STATE_CLOSED,
STREAM_STATE_OPEN,
STREAM_STATE_PLAYING,
STREAM_STATE_PAUSED,
} stream_state_t;
typedef struct {
uint8_t a2dp_local_seid;
uint8_t media_sbc_codec_configuration[4];
} a2dp_sink_stream_endpoint_t;
a2dp_sink_stream_endpoint_t a2dp_sink_stream_endpoint;
typedef struct {
bd_addr_t addr;
uint16_t a2dp_cid;
uint8_t a2dp_local_seid;
stream_state_t stream_state;
BluetoothMediaCodecConfigurationSBC sbc_configuration;
} a2dp_sink_a2dp_connection_t;
a2dp_sink_a2dp_connection_t a2dp_sink_a2dp_connection;
typedef struct {
bd_addr_t addr;
uint16_t avrcp_cid;
bool playing;
uint16_t notifications_supported_by_target;
} a2dp_sink_avrcp_connection_t;
a2dp_sink_avrcp_connection_t a2dp_sink_avrcp_connection;
int16_t output_buffer[(128 + 16) * NUM_CHANNELS]; // 16 * 8 * 2
char _title[64];
char _artist[64];
char _album[64];
char _genre[32];
};
+723
View File
@@ -0,0 +1,723 @@
/*
A1DP Source (Bluetooth audio sender)
Copyright (c) 2024 Earle F. Philhower, III <earlephilhower@yahoo.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
// Based heavily off of the a2dp_source example from BlueKitchen BTStack
/*
Copyright (C) 2016 BlueKitchen GmbH
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the names of
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
4. Any redistribution, use, or modification is done solely for
personal benefit and not for any commercial purpose or for
monetary gain.
THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN
GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
Please inquire about commercial licensing options at
contact@bluekitchen-gmbh.com
*/
#include <Arduino.h>
#include "A2DPSource.h"
#define CCALLBACKNAME _A2DPSOURCECB
#include <ctocppcallback.h>
#define PACKETHANDLERCB(class, cbFcn) \
(_A2DPSOURCECB<void(uint8_t, uint16_t, uint8_t*, uint16_t), __COUNTER__>::func = std::bind(&class::cbFcn, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4), \
static_cast<btstack_packet_handler_t>(_A2DPSOURCECB<void(uint8_t, uint16_t, uint8_t*, uint16_t), __COUNTER__ - 1>::callback))
#define TIMEOUTHANDLERCB(class, cbFcn) \
(_A2DPSOURCECB<void(btstack_timer_source_t *), __COUNTER__>::func = std::bind(&class::cbFcn, this, std::placeholders::_1), \
static_cast<void(*)(btstack_timer_source_t*)>(_A2DPSOURCECB<void(btstack_timer_source_t*), __COUNTER__ - 1>::callback))
bool A2DPSource::begin() {
if (_running) {
return false;
}
_pcmBuffer = (int16_t *)malloc(_pcmBufferSize * sizeof(int16_t));
if (!_pcmBuffer) {
DEBUGV("A2DPSource: OOM for pcm buffer\n");
return false;
}
_pcmWriter = 0;
_pcmReader = 0;
// Request role change on reconnecting headset to always use them in slave mode
hci_set_master_slave_policy(0);
// enabled EIR
hci_set_inquiry_mode(INQUIRY_MODE_RSSI_AND_EIR);
l2cap_init();
#ifdef ENABLE_BLE
// Initialize LE Security Manager. Needed for cross-transport key derivation
sm_init();
#endif
// Initialize A2DP Source
a2dp_source_init();
a2dp_source_register_packet_handler(PACKETHANDLERCB(A2DPSource, a2dp_source_packet_handler));
// Create stream endpoint
avdtp_stream_endpoint_t * local_stream_endpoint = a2dp_source_create_stream_endpoint(AVDTP_AUDIO, AVDTP_CODEC_SBC, media_sbc_codec_capabilities, sizeof(media_sbc_codec_capabilities), media_sbc_codec_configuration, sizeof(media_sbc_codec_configuration));
if (!local_stream_endpoint) {
DEBUGV("A2DP Source: not enough memory to create local stream endpoint\n");
return false;
}
// Store stream endpoint's SEP ID, as it is used by A2DP API to identify the stream endpoint
media_tracker.local_seid = avdtp_local_seid(local_stream_endpoint);
avdtp_source_register_delay_reporting_category(media_tracker.local_seid);
// Initialize AVRCP Service
avrcp_init();
avrcp_register_packet_handler(PACKETHANDLERCB(A2DPSource, avrcp_packet_handler));
// Initialize AVRCP Target
avrcp_target_init();
avrcp_target_register_packet_handler(PACKETHANDLERCB(A2DPSource, avrcp_target_packet_handler));
// Initialize AVRCP Controller
avrcp_controller_init();
avrcp_controller_register_packet_handler(PACKETHANDLERCB(A2DPSource, avrcp_controller_packet_handler));
// Initialize SDP,
sdp_init();
// Create A2DP Source service record and register it with SDP
memset(sdp_a2dp_source_service_buffer, 0, sizeof(sdp_a2dp_source_service_buffer));
a2dp_source_create_sdp_record(sdp_a2dp_source_service_buffer, 0x10001, AVDTP_SOURCE_FEATURE_MASK_PLAYER, NULL, NULL);
sdp_register_service(sdp_a2dp_source_service_buffer);
// Create AVRCP Target service record and register it with SDP. We receive Category 1 commands from the headphone, e.g. play/pause
memset(sdp_avrcp_target_service_buffer, 0, sizeof(sdp_avrcp_target_service_buffer));
uint16_t supported_features = AVRCP_FEATURE_MASK_CATEGORY_PLAYER_OR_RECORDER;
#ifdef AVRCP_BROWSING_ENABLED
supported_features |= AVRCP_FEATURE_MASK_BROWSING;
#endif
avrcp_target_create_sdp_record(sdp_avrcp_target_service_buffer, 0x10002, supported_features, NULL, NULL);
sdp_register_service(sdp_avrcp_target_service_buffer);
// Create AVRCP Controller service record and register it with SDP. We send Category 2 commands to the headphone, e.g. volume up/down
memset(sdp_avrcp_controller_service_buffer, 0, sizeof(sdp_avrcp_controller_service_buffer));
uint16_t controller_supported_features = AVRCP_FEATURE_MASK_CATEGORY_MONITOR_OR_AMPLIFIER;
avrcp_controller_create_sdp_record(sdp_avrcp_controller_service_buffer, 0x10003, controller_supported_features, NULL, NULL);
sdp_register_service(sdp_avrcp_controller_service_buffer);
// Register Device ID (PnP) service SDP record
memset(device_id_sdp_service_buffer, 0, sizeof(device_id_sdp_service_buffer));
device_id_create_sdp_record(device_id_sdp_service_buffer, 0x10004, DEVICE_ID_VENDOR_ID_SOURCE_BLUETOOTH, BLUETOOTH_COMPANY_ID_BLUEKITCHEN_GMBH, 1, 1);
sdp_register_service(device_id_sdp_service_buffer);
// Set local name with a template Bluetooth address, that will be automatically
// replaced with a actual address once it is available, i.e. when BTstack boots
// up and starts talking to a Bluetooth module.
if (!_name) {
setName("PicoW A2DP 00:00:00:00:00:00");
}
gap_set_local_name(_name);
gap_discoverable_control(1);
gap_set_class_of_device(0x200408);
// Register for HCI events.
_hci.install();
_running = true;
_hci.begin();
return true;
}
bool A2DPSource::connect(const uint8_t *addr) {
if (!_running) {
return false;
}
while (!_hci.running()) {
delay(10);
}
uint8_t a[6];
if (addr) {
memcpy(a, addr, sizeof(a));
auto ret = !a2dp_source_establish_stream(a, &media_tracker.a2dp_cid);
return ret;
} else {
clearPairing();
auto l = scan();
for (auto e : l) {
DEBUGV("Scan connecting %s at %s ... ", e.name(), e.addressString());
memcpy(a, e.address(), sizeof(a));
if (!a2dp_source_establish_stream(a, &media_tracker.a2dp_cid)) {
DEBUGV("Connection established\n");
return true;
}
DEBUGV("Failed\n");
}
return false;
}
}
bool A2DPSource::disconnect() {
BluetoothLock b;
if (_connected) {
a2dp_source_disconnect(media_tracker.a2dp_cid);
}
if (!_running || !_connected) {
return false;
}
_connected = false;
return true;
}
void A2DPSource::clearPairing() {
BluetoothLock b;
if (_connected) {
a2dp_source_disconnect(media_tracker.a2dp_cid);
}
gap_delete_all_link_keys();
}
// from Print (see notes on write() methods below)
size_t A2DPSource::write(const uint8_t *buffer, size_t size) {
BluetoothLock b;
size_t count = 0;
size /= 2;
// First copy from writer to either end of
uint32_t start = _pcmWriter;
uint32_t end = _pcmReader > _pcmWriter ? _pcmReader : _pcmBufferSize;
if (end - start > size) {
end = start + size;
}
memcpy(_pcmBuffer + start, buffer, (end - start) * sizeof(int16_t));
count += (end - start) * sizeof(int16_t);
size -= end - start;
_pcmWriter += end - start;
_pcmWriter %= _pcmBufferSize;
// Possibly wraparound to 0 if still left
if (size) {
start = 0;
end = _pcmReader;
if (end - start > size) {
end = size;
}
memcpy(_pcmBuffer + start, buffer, (end - start) * sizeof(int16_t));
count += (end - start) * sizeof(int16_t);
size -= end - start;
_pcmWriter += end - start;
_pcmWriter %= _pcmBufferSize;
}
return count;
}
int A2DPSource::availableForWrite() {
BluetoothLock b;
int avail = 0;
if (_pcmWriter == _pcmReader) {
avail = _pcmBufferSize - 1;
} else if (_pcmReader > _pcmWriter) {
avail = _pcmReader - _pcmWriter - 1;
} else {
avail = _pcmBufferSize - _pcmWriter + _pcmReader - 1;
}
return avail;
}
void A2DPSource::a2dp_timer_start(a2dp_media_sending_context_t * context) {
context->max_media_payload_size = btstack_min(a2dp_max_media_payload_size(context->a2dp_cid, context->local_seid), SBC_STORAGE_SIZE);
context->sbc_storage_count = 0;
context->sbc_ready_to_send = 0;
context->streaming = 1;
btstack_run_loop_remove_timer(&context->audio_timer);
btstack_run_loop_set_timer_handler(&context->audio_timer, TIMEOUTHANDLERCB(A2DPSource, a2dp_audio_timeout_handler));
btstack_run_loop_set_timer_context(&context->audio_timer, context);
btstack_run_loop_set_timer(&context->audio_timer, AUDIO_TIMEOUT_MS);
btstack_run_loop_add_timer(&context->audio_timer);
}
void A2DPSource::a2dp_timer_stop(a2dp_media_sending_context_t * context) {
context->time_audio_data_sent = 0;
context->acc_num_missed_samples = 0;
context->samples_ready = 0;
context->streaming = 1;
context->sbc_storage_count = 0;
context->sbc_ready_to_send = 0;
btstack_run_loop_remove_timer(&context->audio_timer);
}
int A2DPSource::a2dp_fill_sbc_audio_buffer(a2dp_media_sending_context_t * context) {
// perform sbc encoding
int total_num_bytes_read = 0;
unsigned int num_audio_samples_per_sbc_buffer = btstack_sbc_encoder_num_audio_frames();
while (context->samples_ready >= num_audio_samples_per_sbc_buffer
&& (context->max_media_payload_size - context->sbc_storage_count) >= btstack_sbc_encoder_sbc_buffer_length()) {
if ((_pcmWriter / 256) != (_pcmReader / 256)) {
btstack_sbc_encoder_process_data(_pcmBuffer + _pcmReader);
asm volatile("" ::: "memory"); // Ensure the data is processed before advancing
auto next_reader = (_pcmReader + 256) % _pcmBufferSize;
asm volatile("" ::: "memory"); // Ensure the reader value is only written once, correctly
_pcmReader = next_reader;
} else {
_underflow = true;
// Just keep sending old data
btstack_sbc_encoder_process_data(_pcmBuffer + _pcmReader);
}
uint16_t sbc_frame_size = btstack_sbc_encoder_sbc_buffer_length();
uint8_t *sbc_frame = btstack_sbc_encoder_sbc_buffer();
total_num_bytes_read += num_audio_samples_per_sbc_buffer;
// first byte in sbc storage contains sbc media header
memcpy(&context->sbc_storage[1 + context->sbc_storage_count], sbc_frame, sbc_frame_size);
context->sbc_storage_count += sbc_frame_size;
context->samples_ready -= num_audio_samples_per_sbc_buffer;
}
return total_num_bytes_read;
}
void A2DPSource::a2dp_audio_timeout_handler(btstack_timer_source_t * timer) {
a2dp_media_sending_context_t * context = (a2dp_media_sending_context_t *) btstack_run_loop_get_timer_context(timer);
btstack_run_loop_set_timer(&context->audio_timer, AUDIO_TIMEOUT_MS);
btstack_run_loop_add_timer(&context->audio_timer);
uint32_t now = btstack_run_loop_get_time_ms();
uint32_t update_period_ms = AUDIO_TIMEOUT_MS;
if (context->time_audio_data_sent > 0) {
update_period_ms = now - context->time_audio_data_sent;
}
uint32_t num_samples = (update_period_ms * _frequency) / 1000;
context->acc_num_missed_samples += (update_period_ms * _frequency) % 1000;
while (context->acc_num_missed_samples >= 1000) {
num_samples++;
context->acc_num_missed_samples -= 1000;
}
context->time_audio_data_sent = now;
context->samples_ready += num_samples;
if (context->sbc_ready_to_send) {
return;
}
a2dp_fill_sbc_audio_buffer(context);
if ((context->sbc_storage_count + btstack_sbc_encoder_sbc_buffer_length()) > context->max_media_payload_size) {
// schedule sending
context->sbc_ready_to_send = 1;
a2dp_source_stream_endpoint_request_can_send_now(context->a2dp_cid, context->local_seid);
}
}
void A2DPSource::a2dp_send_media_packet() {
int num_bytes_in_frame = btstack_sbc_encoder_sbc_buffer_length();
int bytes_in_storage = media_tracker.sbc_storage_count;
uint8_t num_sbc_frames = bytes_in_storage / num_bytes_in_frame;
// Prepend SBC Header
media_tracker.sbc_storage[0] = num_sbc_frames; // (fragmentation << 7) | (starting_packet << 6) | (last_packet << 5) | num_frames;
a2dp_source_stream_send_media_payload_rtp(media_tracker.a2dp_cid, media_tracker.local_seid, 0,
media_tracker.rtp_timestamp,
media_tracker.sbc_storage, bytes_in_storage + 1);
// update rtp_timestamp
unsigned int num_audio_samples_per_sbc_buffer = btstack_sbc_encoder_num_audio_frames();
media_tracker.rtp_timestamp += num_sbc_frames * num_audio_samples_per_sbc_buffer;
media_tracker.sbc_storage_count = 0;
media_tracker.sbc_ready_to_send = 0;
if (_transmitCB) {
_transmitCB(_transmitData);
}
}
void A2DPSource::a2dp_source_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
UNUSED(channel);
UNUSED(size);
uint8_t status;
uint8_t local_seid;
bd_addr_t address;
uint16_t cid;
avdtp_channel_mode_t channel_mode;
uint8_t allocation_method;
if (packet_type != HCI_EVENT_PACKET) {
return;
}
if (hci_event_packet_get_type(packet) != HCI_EVENT_A2DP_META) {
return;
}
switch (hci_event_a2dp_meta_get_subevent_code(packet)) {
case A2DP_SUBEVENT_SIGNALING_CONNECTION_ESTABLISHED:
a2dp_subevent_signaling_connection_established_get_bd_addr(packet, address);
cid = a2dp_subevent_signaling_connection_established_get_a2dp_cid(packet);
status = a2dp_subevent_signaling_connection_established_get_status(packet);
if (status != ERROR_CODE_SUCCESS) {
DEBUGV("A2DP Source: Connection failed, status 0x%02x, cid 0x%02x, a2dp_cid 0x%02x \n", status, cid, media_tracker.a2dp_cid);
media_tracker.a2dp_cid = 0;
break;
}
media_tracker.a2dp_cid = cid;
media_tracker.volume = 32;
memcpy(_sinkAddress, address, sizeof(_sinkAddress));
DEBUGV("A2DP Source: Connected to address %s, a2dp cid 0x%02x, local seid 0x%02x.\n", bd_addr_to_str(address), media_tracker.a2dp_cid, media_tracker.local_seid);
break;
case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_SBC_CONFIGURATION: {
cid = avdtp_subevent_signaling_media_codec_sbc_configuration_get_avdtp_cid(packet);
if (cid != media_tracker.a2dp_cid) {
return;
}
media_tracker.remote_seid = a2dp_subevent_signaling_media_codec_sbc_configuration_get_remote_seid(packet);
sbc_configuration.reconfigure = a2dp_subevent_signaling_media_codec_sbc_configuration_get_reconfigure(packet);
sbc_configuration.num_channels = a2dp_subevent_signaling_media_codec_sbc_configuration_get_num_channels(packet);
sbc_configuration.sampling_frequency = a2dp_subevent_signaling_media_codec_sbc_configuration_get_sampling_frequency(packet);
sbc_configuration.block_length = a2dp_subevent_signaling_media_codec_sbc_configuration_get_block_length(packet);
sbc_configuration.subbands = a2dp_subevent_signaling_media_codec_sbc_configuration_get_subbands(packet);
sbc_configuration.min_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_min_bitpool_value(packet);
sbc_configuration.max_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_max_bitpool_value(packet);
channel_mode = (avdtp_channel_mode_t) a2dp_subevent_signaling_media_codec_sbc_configuration_get_channel_mode(packet);
allocation_method = a2dp_subevent_signaling_media_codec_sbc_configuration_get_allocation_method(packet);
DEBUGV("A2DP Source: Received SBC codec configuration, sampling frequency %u, a2dp_cid 0x%02x, local seid 0x%02x, remote seid 0x%02x.\n",
sbc_configuration.sampling_frequency, cid,
a2dp_subevent_signaling_media_codec_sbc_configuration_get_local_seid(packet),
a2dp_subevent_signaling_media_codec_sbc_configuration_get_remote_seid(packet));
// Adapt Bluetooth spec definition to SBC Encoder expected input
sbc_configuration.allocation_method = (btstack_sbc_allocation_method_t)(allocation_method - 1);
switch (channel_mode) {
case AVDTP_CHANNEL_MODE_JOINT_STEREO:
sbc_configuration.channel_mode = SBC_CHANNEL_MODE_JOINT_STEREO;
break;
case AVDTP_CHANNEL_MODE_STEREO:
sbc_configuration.channel_mode = SBC_CHANNEL_MODE_STEREO;
break;
case AVDTP_CHANNEL_MODE_DUAL_CHANNEL:
sbc_configuration.channel_mode = SBC_CHANNEL_MODE_DUAL_CHANNEL;
break;
case AVDTP_CHANNEL_MODE_MONO:
sbc_configuration.channel_mode = SBC_CHANNEL_MODE_MONO;
break;
default:
btstack_assert(false);
break;
}
sbc_configuration.dump();
btstack_sbc_encoder_init(&sbc_encoder_state, SBC_MODE_STANDARD,
sbc_configuration.block_length, sbc_configuration.subbands,
sbc_configuration.allocation_method, sbc_configuration.sampling_frequency,
sbc_configuration.max_bitpool_value,
sbc_configuration.channel_mode);
break;
}
case A2DP_SUBEVENT_SIGNALING_DELAY_REPORTING_CAPABILITY:
DEBUGV("A2DP Source: remote supports delay report, remote seid %d\n",
avdtp_subevent_signaling_delay_reporting_capability_get_remote_seid(packet));
break;
case A2DP_SUBEVENT_SIGNALING_CAPABILITIES_DONE:
DEBUGV("A2DP Source: All capabilities reported, remote seid %d\n",
avdtp_subevent_signaling_capabilities_done_get_remote_seid(packet));
break;
case A2DP_SUBEVENT_SIGNALING_DELAY_REPORT:
DEBUGV("A2DP Source: Received delay report of %d.%0d ms, local seid %d\n",
avdtp_subevent_signaling_delay_report_get_delay_100us(packet) / 10, avdtp_subevent_signaling_delay_report_get_delay_100us(packet) % 10,
avdtp_subevent_signaling_delay_report_get_local_seid(packet));
break;
case A2DP_SUBEVENT_STREAM_ESTABLISHED:
a2dp_subevent_stream_established_get_bd_addr(packet, address);
status = a2dp_subevent_stream_established_get_status(packet);
if (status != ERROR_CODE_SUCCESS) {
DEBUGV("A2DP Source: Stream failed, status 0x%02x.\n", status);
break;
}
local_seid = a2dp_subevent_stream_established_get_local_seid(packet);
cid = a2dp_subevent_stream_established_get_a2dp_cid(packet);
(void) local_seid;
DEBUGV("A2DP Source: Stream established a2dp_cid 0x%02x, local_seid 0x%02x, remote_seid 0x%02x\n", cid, local_seid, a2dp_subevent_stream_established_get_remote_seid(packet));
media_tracker.stream_opened = 1;
status = a2dp_source_start_stream(media_tracker.a2dp_cid, media_tracker.local_seid);
break;
case A2DP_SUBEVENT_STREAM_RECONFIGURED:
status = a2dp_subevent_stream_reconfigured_get_status(packet);
local_seid = a2dp_subevent_stream_reconfigured_get_local_seid(packet);
cid = a2dp_subevent_stream_reconfigured_get_a2dp_cid(packet);
if (status != ERROR_CODE_SUCCESS) {
DEBUGV("A2DP Source: Stream reconfiguration failed, status 0x%02x\n", status);
break;
}
DEBUGV("A2DP Source: Stream reconfigured a2dp_cid 0x%02x, local_seid 0x%02x\n", cid, local_seid);
status = a2dp_source_start_stream(media_tracker.a2dp_cid, media_tracker.local_seid);
break;
case A2DP_SUBEVENT_STREAM_STARTED:
local_seid = a2dp_subevent_stream_started_get_local_seid(packet);
cid = a2dp_subevent_stream_started_get_a2dp_cid(packet);
play_info.status = AVRCP_PLAYBACK_STATUS_PLAYING;
if (media_tracker.avrcp_cid) {
avrcp_target_set_now_playing_info(media_tracker.avrcp_cid, &_currentTrack, _tracks);
avrcp_target_set_playback_status(media_tracker.avrcp_cid, AVRCP_PLAYBACK_STATUS_PLAYING);
}
a2dp_timer_start(&media_tracker);
DEBUGV("A2DP Source: Stream started, a2dp_cid 0x%02x, local_seid 0x%02x\n", cid, local_seid);
_connected = true;
if (_connectCB) {
_connectCB(_connectData, true);
}
break;
case A2DP_SUBEVENT_STREAMING_CAN_SEND_MEDIA_PACKET_NOW:
local_seid = a2dp_subevent_streaming_can_send_media_packet_now_get_local_seid(packet);
cid = a2dp_subevent_signaling_media_codec_sbc_configuration_get_a2dp_cid(packet);
a2dp_send_media_packet();
break;
case A2DP_SUBEVENT_STREAM_SUSPENDED:
local_seid = a2dp_subevent_stream_suspended_get_local_seid(packet);
cid = a2dp_subevent_stream_suspended_get_a2dp_cid(packet);
play_info.status = AVRCP_PLAYBACK_STATUS_PAUSED;
if (media_tracker.avrcp_cid) {
avrcp_target_set_playback_status(media_tracker.avrcp_cid, AVRCP_PLAYBACK_STATUS_PAUSED);
}
DEBUGV("A2DP Source: Stream paused, a2dp_cid 0x%02x, local_seid 0x%02x\n", cid, local_seid);
a2dp_timer_stop(&media_tracker);
break;
case A2DP_SUBEVENT_STREAM_RELEASED:
play_info.status = AVRCP_PLAYBACK_STATUS_STOPPED;
cid = a2dp_subevent_stream_released_get_a2dp_cid(packet);
local_seid = a2dp_subevent_stream_released_get_local_seid(packet);
DEBUGV("A2DP Source: Stream released, a2dp_cid 0x%02x, local_seid 0x%02x\n", cid, local_seid);
if (cid == media_tracker.a2dp_cid) {
media_tracker.stream_opened = 0;
DEBUGV("A2DP Source: Stream released.\n");
}
if (media_tracker.avrcp_cid) {
avrcp_target_set_now_playing_info(media_tracker.avrcp_cid, NULL, _tracks);
avrcp_target_set_playback_status(media_tracker.avrcp_cid, AVRCP_PLAYBACK_STATUS_STOPPED);
}
a2dp_timer_stop(&media_tracker);
break;
case A2DP_SUBEVENT_SIGNALING_CONNECTION_RELEASED:
cid = a2dp_subevent_signaling_connection_released_get_a2dp_cid(packet);
if (cid == media_tracker.a2dp_cid) {
media_tracker.avrcp_cid = 0;
media_tracker.a2dp_cid = 0;
DEBUGV("A2DP Source: Signaling released.\n\n");
_connected = false;
if (_connectCB) {
_connectCB(_connectData, false);
}
}
break;
default:
break;
}
}
void A2DPSource::avrcp_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
UNUSED(channel);
UNUSED(size);
bd_addr_t event_addr;
uint16_t local_cid;
uint8_t status = ERROR_CODE_SUCCESS;
if (packet_type != HCI_EVENT_PACKET) {
return;
}
if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) {
return;
}
switch (packet[2]) {
case AVRCP_SUBEVENT_CONNECTION_ESTABLISHED:
local_cid = avrcp_subevent_connection_established_get_avrcp_cid(packet);
status = avrcp_subevent_connection_established_get_status(packet);
if (status != ERROR_CODE_SUCCESS) {
DEBUGV("AVRCP: Connection failed, local cid 0x%02x, status 0x%02x\n", local_cid, status);
return;
}
media_tracker.avrcp_cid = local_cid;
avrcp_subevent_connection_established_get_bd_addr(packet, event_addr);
DEBUGV("AVRCP: Channel to %s successfully opened, avrcp_cid 0x%02x\n", bd_addr_to_str(event_addr), media_tracker.avrcp_cid);
avrcp_target_support_event(media_tracker.avrcp_cid, AVRCP_NOTIFICATION_EVENT_PLAYBACK_STATUS_CHANGED);
avrcp_target_support_event(media_tracker.avrcp_cid, AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED);
avrcp_target_support_event(media_tracker.avrcp_cid, AVRCP_NOTIFICATION_EVENT_NOW_PLAYING_CONTENT_CHANGED);
avrcp_target_set_now_playing_info(media_tracker.avrcp_cid, NULL, _tracks);
DEBUGV("Enable Volume Change notification\n");
avrcp_controller_enable_notification(media_tracker.avrcp_cid, AVRCP_NOTIFICATION_EVENT_VOLUME_CHANGED);
DEBUGV("Enable Battery Status Change notification\n");
avrcp_controller_enable_notification(media_tracker.avrcp_cid, AVRCP_NOTIFICATION_EVENT_BATT_STATUS_CHANGED);
return;
case AVRCP_SUBEVENT_CONNECTION_RELEASED:
DEBUGV("AVRCP Target: Disconnected, avrcp_cid 0x%02x\n", avrcp_subevent_connection_released_get_avrcp_cid(packet));
media_tracker.avrcp_cid = 0;
return;
default:
break;
}
if (status != ERROR_CODE_SUCCESS) {
DEBUGV("Responding to event 0x%02x failed, status 0x%02x\n", packet[2], status);
}
}
void A2DPSource::avrcp_target_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
UNUSED(channel);
UNUSED(size);
uint8_t status = ERROR_CODE_SUCCESS;
if (packet_type != HCI_EVENT_PACKET) {
return;
}
if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) {
return;
}
bool button_pressed;
char const * button_state;
avrcp_operation_id_t operation_id;
switch (packet[2]) {
case AVRCP_SUBEVENT_PLAY_STATUS_QUERY:
status = avrcp_target_play_status(media_tracker.avrcp_cid, play_info.song_length_ms, play_info.song_position_ms, play_info.status);
break;
// case AVRCP_SUBEVENT_NOW_PLAYING_INFO_QUERY:
// status = avrcp_target_now_playing_info(avrcp_cid);
// break;
case AVRCP_SUBEVENT_OPERATION:
operation_id = (avrcp_operation_id_t)avrcp_subevent_operation_get_operation_id(packet);
button_pressed = avrcp_subevent_operation_get_button_pressed(packet) > 0;
button_state = button_pressed ? "PRESS" : "RELEASE";
(void) button_state;
DEBUGV("AVRCP Target: operation %s (%s)\n", avrcp_operation2str(operation_id), button_state);
if (_avrcpCB) {
_avrcpCB(_avrcpData, operation_id, button_pressed);
}
if (!button_pressed) {
break;
}
switch (operation_id) {
case AVRCP_OPERATION_ID_PLAY:
status = a2dp_source_start_stream(media_tracker.a2dp_cid, media_tracker.local_seid);
break;
case AVRCP_OPERATION_ID_PAUSE:
status = a2dp_source_pause_stream(media_tracker.a2dp_cid, media_tracker.local_seid);
break;
case AVRCP_OPERATION_ID_STOP:
status = a2dp_source_disconnect(media_tracker.a2dp_cid);
break;
default:
break;
}
break;
default:
break;
}
if (status != ERROR_CODE_SUCCESS) {
DEBUGV("Responding to event 0x%02x failed, status 0x%02x\n", packet[2], status);
}
}
void A2DPSource::avrcp_controller_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
UNUSED(channel);
UNUSED(size);
if (packet_type != HCI_EVENT_PACKET) {
return;
}
if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) {
return;
}
if (!media_tracker.avrcp_cid) {
return;
}
switch (packet[2]) {
case AVRCP_SUBEVENT_NOTIFICATION_VOLUME_CHANGED:
DEBUGV("AVRCP Controller: Notification Absolute Volume %d %%\n", avrcp_subevent_notification_volume_changed_get_absolute_volume(packet) * 100 / 127);
if (_volumeCB) {
_volumeCB(_volumeData, avrcp_subevent_notification_volume_changed_get_absolute_volume(packet) * 100 / 127);
}
break;
case AVRCP_SUBEVENT_NOTIFICATION_EVENT_BATT_STATUS_CHANGED:
// see avrcp_battery_status_t
DEBUGV("AVRCP Controller: Notification Battery Status 0x%02x\n", avrcp_subevent_notification_event_batt_status_changed_get_battery_status(packet));
if (_batteryCB) {
_batteryCB(_batteryData, (avrcp_battery_status_t)avrcp_subevent_notification_event_batt_status_changed_get_battery_status(packet));
}
break;
case AVRCP_SUBEVENT_NOTIFICATION_STATE:
DEBUGV("AVRCP Controller: Notification %s - %s\n",
avrcp_event2str(avrcp_subevent_notification_state_get_event_id(packet)),
avrcp_subevent_notification_state_get_enabled(packet) != 0 ? "enabled" : "disabled");
break;
default:
break;
}
}
+238
View File
@@ -0,0 +1,238 @@
/*
A1DP Source (Bluetooth audio sender)
Copyright (c) 2024 Earle F. Philhower, III <earlephilhower@yahoo.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#pragma once
#include <Arduino.h>
#include <BluetoothHCI.h>
#include <BluetoothLock.h>
#include "BluetoothMediaConfigurationSBC.h"
#include <functional>
#include <list>
#include <memory>
class A2DPSource : public Stream {
public:
A2DPSource() {
}
bool setFrequency(uint32_t rate) {
if (_running || ((rate != 44100) && (rate != 48000))) {
return false;
}
_frequency = rate;
return true;
}
bool setName(const char *name) {
if (_running) {
return false;
}
free(_name);
_name = strdup(name);
return true;
}
void onTransmit(void (*cb)(void *), void *cbData = nullptr) {
_transmitCB = cb;
_transmitData = cbData;
}
void onAVRCP(void (*cb)(void *, avrcp_operation_id_t, int), void *cbData = nullptr) {
_avrcpCB = cb;
_avrcpData = cbData;
}
void onBattery(void (*cb)(void *, avrcp_battery_status_t), void *cbData = nullptr) {
_batteryCB = cb;
_batteryData = cbData;
}
void onVolume(void (*cb)(void *, int), void *cbData = nullptr) {
_volumeCB = cb;
_volumeData = cbData;
}
void onConnect(void (*cb)(void *, bool), void *cbData = nullptr) {
_connectCB = cb;
_connectData = cbData;
}
bool setBufferSize(size_t size) {
if (_running || (size & 127) || (size < 1024)) {
return false;
}
_pcmBufferSize = size;
return true;
}
bool getUnderflow() {
BluetoothLock b;
if (!_running) {
return false;
}
auto ret = _underflow;
_underflow = false;
return ret;
}
const uint8_t *getSinkAddress() {
if (!_connected) {
return nullptr;
} else {
return _sinkAddress;
}
}
bool begin();
std::vector<BTDeviceInfo> scan(uint32_t mask = BluetoothHCI::speaker_cod, int scanTimeSec = 5, bool async = false) {
return _hci.scan(mask, scanTimeSec, async);
}
bool connect(const uint8_t *addr = nullptr);
bool connected() {
return _connected;
}
bool disconnect();
void clearPairing();
// from Stream
virtual int available() override {
return 0; // Unreadable, this is output only
}
virtual int read() override {
return 0;
}
virtual int peek() override {
return 0;
}
virtual void flush() override {
}
// from Print (see notes on write() methods below)
virtual size_t write(const uint8_t *buffer, size_t size) override;
virtual int availableForWrite() override;
virtual size_t write(uint8_t s) override {
(void) s;
return 0; // Never any reason to write 8-bit data, make it always fail.
}
private:
BluetoothHCI _hci;
bool _running = false;
bool _connected = false;
char *_name = nullptr;
int _frequency = 44100;
// Callbacks
void (*_transmitCB)(void *) = nullptr;
void *_transmitData;
void (*_avrcpCB)(void *, avrcp_operation_id_t, int) = nullptr;
void *_avrcpData;
void (*_batteryCB)(void *, avrcp_battery_status_t) = nullptr;
void *_batteryData;
void (*_volumeCB)(void *, int) = nullptr;
void *_volumeData;
void (*_connectCB)(void *, bool) = nullptr;
void *_connectData;
const uint8_t media_sbc_codec_capabilities[4] = {
(AVDTP_SBC_44100 << 4) | AVDTP_SBC_STEREO,
0xFF,//(AVDTP_SBC_BLOCK_LENGTH_16 << 4) | (AVDTP_SBC_SUBBANDS_8 << 2) | AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS,
2, 53
};
uint8_t media_sbc_codec_configuration[4];
enum {SBC_STORAGE_SIZE = 1030, AUDIO_TIMEOUT_MS = 5};
typedef struct {
uint16_t a2dp_cid;
uint8_t local_seid;
uint8_t remote_seid;
uint8_t stream_opened;
uint16_t avrcp_cid;
uint32_t time_audio_data_sent; // ms
uint32_t acc_num_missed_samples;
uint32_t samples_ready;
btstack_timer_source_t audio_timer;
uint8_t streaming;
int max_media_payload_size;
uint32_t rtp_timestamp;
uint8_t sbc_storage[SBC_STORAGE_SIZE];
uint16_t sbc_storage_count;
uint8_t sbc_ready_to_send;
uint8_t volume;
} a2dp_media_sending_context_t;
uint8_t sdp_a2dp_source_service_buffer[150];
uint8_t sdp_avrcp_target_service_buffer[200];
uint8_t sdp_avrcp_controller_service_buffer[200];
uint8_t device_id_sdp_service_buffer[100];
BluetoothMediaCodecConfigurationSBC sbc_configuration;
btstack_sbc_encoder_state_t sbc_encoder_state;
a2dp_media_sending_context_t media_tracker;
typedef struct {
uint8_t track_id[8];
uint32_t song_length_ms;
avrcp_playback_status_t status;
uint32_t song_position_ms; // 0xFFFFFFFF if not supported
} avrcp_play_status_info_t;
avrcp_play_status_info_t play_info;
void a2dp_timer_start(a2dp_media_sending_context_t * context);
void a2dp_timer_stop(a2dp_media_sending_context_t * context);
int16_t *_pcmBuffer = nullptr;
size_t _pcmBufferSize = 4096; // Multiple of 128 required
uint32_t _pcmWriter;
uint32_t _pcmReader;
bool _underflow;
int a2dp_fill_sbc_audio_buffer(a2dp_media_sending_context_t * context);
void a2dp_audio_timeout_handler(btstack_timer_source_t * timer);
void a2dp_send_media_packet();
int _tracks = 1;
avrcp_track_t _currentTrack;
uint8_t _sinkAddress[6];
void a2dp_source_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
void avrcp_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
void avrcp_target_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
void avrcp_controller_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
};
@@ -0,0 +1,10 @@
#include <_needsbt.h>
#include <BluetoothLock.h>
#include <BluetoothDevice.h>
#include <BluetoothHCI.h>
#include "BluetoothMediaConfigurationSBC.h"
#include "A2DPSource.h"
#include "A2DPSink.h"
#include "BluetoothAudioConsumer.h"
#include "BluetoothAudioConsumerPWM.h"
#include "BluetoothAudioConsumerI2S.h"
@@ -0,0 +1,45 @@
/*
Bluetooth A2DP audio stream consumer
Copyright (c) 2024 Earle F. Philhower, III <earlephilhower@yahoo.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#pragma once
class A2DPSink;
class BluetoothAudioConsumer_ {
public:
BluetoothAudioConsumer_() {
_state = STATE_OFF;
}
virtual ~BluetoothAudioConsumer_() {
/* noop */
}
virtual bool init(uint8_t channels, uint32_t samplerate, A2DPSink *a2dpSink) = 0;
virtual void setVolume(uint8_t gain) = 0;
virtual void startStream() = 0;
virtual void stopStream() = 0;
virtual void close() = 0;
protected:
typedef enum { STATE_OFF = 0, STATE_INITIALIZED, STATE_STREAMING } State;
A2DPSink *_a2dpSink;
State _state;
uint8_t _gain;
int _channels;
int _samplerate;
};
@@ -0,0 +1,82 @@
/*
Bluetooth A2DP audio stream consumer - PWMAudio
Copyright (c) 2024 Earle F. Philhower, III <earlephilhower@yahoo.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "BluetoothAudioConsumerI2S.h"
#include "A2DPSink.h"
#include <functional>
#define CCALLBACKNAME _BTA2DPI2S
#include <ctocppcallback.h>
#define NOPARAMCB(class, cbFcn) \
(CCALLBACKNAME<void(void), __COUNTER__>::func = std::bind(&class::cbFcn, this), \
static_cast<void (*)(void)>(CCALLBACKNAME<void(void), __COUNTER__ - 1>::callback))
bool BluetoothAudioConsumerI2S::init(uint8_t channels, uint32_t samplerate, A2DPSink *a2dpSink) {
_channels = channels;
_samplerate = samplerate;
_a2dpSink = a2dpSink;
_i2s->setBuffers(16, 64);
_i2s->onTransmit(NOPARAMCB(BluetoothAudioConsumerI2S, fill));
if (_i2s->begin(samplerate)) {
_state = STATE_INITIALIZED;
_gain = 64;
return true;
}
return false;
}
void BluetoothAudioConsumerI2S::setVolume(uint8_t gain) {
_gain = gain;
}
void BluetoothAudioConsumerI2S::startStream() {
if (_state != STATE_INITIALIZED) {
return;
}
_state = STATE_STREAMING;
}
void BluetoothAudioConsumerI2S::stopStream() {
if (_state != STATE_STREAMING) {
return;
}
_state = STATE_INITIALIZED;
}
void BluetoothAudioConsumerI2S::close() {
if (_state == STATE_STREAMING) {
stopStream();
}
_state = STATE_OFF;
_i2s->end();
}
void BluetoothAudioConsumerI2S::fill() {
int num_samples = _i2s->availableForWrite() / 2;
int16_t buff[32 * 2];
while (num_samples > 63) {
_a2dpSink->playback_handler((int16_t *) buff, 32);
num_samples -= 64;
for (int i = 0; i < 64; i++) {
buff[i] = (((int32_t)buff[i]) * _gain) >> 8;
}
_i2s->write((uint8_t *)buff, 64 * 2);
}
}
@@ -0,0 +1,41 @@
/*
Bluetooth A2DP audio stream consumer - I2S
Copyright (c) 2024 Earle F. Philhower, III <earlephilhower@yahoo.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#pragma once
#include <I2S.h>
#include "BluetoothAudioConsumer.h"
class BluetoothAudioConsumerI2S : public BluetoothAudioConsumer_ {
public:
BluetoothAudioConsumerI2S(I2S &i2s) : BluetoothAudioConsumer_() {
_i2s = &i2s;
}
virtual bool init(uint8_t channels, uint32_t samplerate, A2DPSink *a2dpSink) override;
virtual void setVolume(uint8_t gain) override;
virtual void startStream() override;
virtual void stopStream() override;
virtual void close() override;
private:
I2S *_i2s;
void fill();
};
@@ -0,0 +1,83 @@
/*
Bluetooth A2DP audio stream consumer - PWMAudio
Copyright (c) 2024 Earle F. Philhower, III <earlephilhower@yahoo.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "BluetoothAudioConsumerPWM.h"
#include "A2DPSink.h"
#include <functional>
#define CCALLBACKNAME _BTA2DPPWM
#include <ctocppcallback.h>
#define NOPARAMCB(class, cbFcn) \
(CCALLBACKNAME<void(void), __COUNTER__>::func = std::bind(&class::cbFcn, this), \
static_cast<void (*)(void)>(CCALLBACKNAME<void(void), __COUNTER__ - 1>::callback))
bool BluetoothAudioConsumerPWM::init(uint8_t channels, uint32_t samplerate, A2DPSink *a2dpSink) {
_channels = channels;
_samplerate = samplerate;
_a2dpSink = a2dpSink;
_pwm->setStereo(channels == 2);
_pwm->setBuffers(16, 64);
_pwm->onTransmit(NOPARAMCB(BluetoothAudioConsumerPWM, fill));
if (_pwm->begin(samplerate)) {
_state = STATE_INITIALIZED;
_gain = 64;
return true;
}
return false;
}
void BluetoothAudioConsumerPWM::setVolume(uint8_t gain) {
_gain = gain;
}
void BluetoothAudioConsumerPWM::startStream() {
if (_state != STATE_INITIALIZED) {
return;
}
_state = STATE_STREAMING;
}
void BluetoothAudioConsumerPWM::stopStream() {
if (_state != STATE_STREAMING) {
return;
}
_state = STATE_INITIALIZED;
}
void BluetoothAudioConsumerPWM::close() {
if (_state == STATE_STREAMING) {
stopStream();
}
_state = STATE_OFF;
_pwm->end();
}
void BluetoothAudioConsumerPWM::fill() {
int num_samples = _pwm->availableForWrite() / 2;
int16_t buff[32 * 2];
while (num_samples > 63) {
_a2dpSink->playback_handler((int16_t *) buff, 32);
num_samples -= 64;
for (int i = 0; i < 64; i++) {
buff[i] = (((int32_t)buff[i]) * _gain) >> 8;
}
_pwm->write((uint8_t *)buff, 64 * 2);
}
}
@@ -0,0 +1,41 @@
/*
Bluetooth A2DP audio stream consumer - PWMAudio
Copyright (c) 2024 Earle F. Philhower, III <earlephilhower@yahoo.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#pragma once
#include <PWMAudio.h>
#include "BluetoothAudioConsumer.h"
class BluetoothAudioConsumerPWM : public BluetoothAudioConsumer_ {
public:
BluetoothAudioConsumerPWM(PWMAudio &pwm) : BluetoothAudioConsumer_() {
_pwm = &pwm;
}
virtual bool init(uint8_t channels, uint32_t samplerate, A2DPSink *a2dpSink) override;
virtual void setVolume(uint8_t gain) override;
virtual void startStream() override;
virtual void stopStream() override;
virtual void close() override;
private:
PWMAudio *_pwm;
void fill();
};
@@ -0,0 +1,47 @@
/*
A1DP Source (Bluetooth audio sender)
Copyright (c) 2024 Earle F. Philhower, III <earlephilhower@yahoo.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#pragma once
#include <Arduino.h>
class BluetoothMediaCodecConfigurationSBC {
public:
uint8_t reconfigure;
uint8_t num_channels;
uint16_t sampling_frequency;
uint8_t block_length;
uint8_t subbands;
uint8_t min_bitpool_value;
uint8_t max_bitpool_value;
btstack_sbc_channel_mode_t channel_mode;
btstack_sbc_allocation_method_t allocation_method;
void dump() {
DEBUGV(" - num_channels: %d\n", num_channels);
DEBUGV(" - sampling_frequency: %d\n", sampling_frequency);
DEBUGV(" - channel_mode: %d\n", channel_mode);
DEBUGV(" - block_length: %d\n", block_length);
DEBUGV(" - subbands: %d\n", subbands);
DEBUGV(" - allocation_method: %d\n", allocation_method);
DEBUGV(" - bitpool_value [%d, %d] \n", min_bitpool_value, max_bitpool_value);
DEBUGV("\n");
}
};
@@ -0,0 +1,34 @@
#include <BluetoothHCI.h>
BluetoothHCI hci;
void BTBasicSetup() {
l2cap_init();
gatt_client_init();
sm_init();
sm_set_io_capabilities(IO_CAPABILITY_NO_INPUT_NO_OUTPUT);
gap_set_default_link_policy_settings(LM_LINK_POLICY_ENABLE_SNIFF_MODE | LM_LINK_POLICY_ENABLE_ROLE_SWITCH);
hci_set_master_slave_policy(HCI_ROLE_MASTER);
hci_set_inquiry_mode(INQUIRY_MODE_RSSI_AND_EIR);
hci.setBLEName("Pico BLE Scanner");
hci.install();
hci.begin();
}
void setup() {
delay(5000);
BTBasicSetup();
}
void loop() {
Serial.printf("BEGIN BLE SCAN @%lu ...", millis());
auto l = hci.scanBLE(BluetoothHCI::any_cod);
Serial.printf("END BLE SCAN @%lu\n\n", millis());
Serial.printf("%-8s | %-17s | %-4s | %s\n", "Class", "Address", "RSSI", "Name");
Serial.printf("%-8s | %-17s | %-4s | %s\n", "--------", "-----------------", "----", "----------------");
for (auto e : l) {
Serial.printf("%08lx | %17s | %4d | %s\n", e.deviceClass(), e.addressString(), e.rssi(), e.name());
}
Serial.printf("\n\n\n");
}
@@ -0,0 +1,31 @@
#include <BluetoothHCI.h>
BluetoothHCI hci;
void BTBasicSetup() {
l2cap_init();
sm_init();
gap_set_default_link_policy_settings(LM_LINK_POLICY_ENABLE_SNIFF_MODE | LM_LINK_POLICY_ENABLE_ROLE_SWITCH);
hci_set_master_slave_policy(HCI_ROLE_MASTER);
hci_set_inquiry_mode(INQUIRY_MODE_RSSI_AND_EIR);
hci.install();
hci.begin();
}
void setup() {
delay(5000);
BTBasicSetup();
}
void loop() {
Serial.printf("BEGIN SCAN @%lu ...", millis());
auto l = hci.scan(BluetoothHCI::any_cod);
Serial.printf("END SCAN @%lu\n\n", millis());
Serial.printf("%-8s | %-17s | %-4s | %s\n", "Class", "Address", "RSSI", "Name");
Serial.printf("%-8s | %-17s | %-4s | %s\n", "--------", "-----------------", "----", "----------------");
for (auto e : l) {
Serial.printf("%08lx | %17s | %4d | %s\n", e.deviceClass(), e.addressString(), e.rssi(), e.name());
}
Serial.printf("\n\n\n");
}
+36
View File
@@ -0,0 +1,36 @@
#######################################
# Syntax Coloring Map
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
BluetoothHCI KEYWORD1
BTDeviceInfo KEYWORD1
BluetoothLock KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
begin KEYWORD2
end KEYWORD2
scan KEYWORD2
scanAsyncDone KEYWORD2
scanAsyncResult KEYWORD2
setName KEYWORD2
scanBLE KEYWORD2
# BTDeviceInfo
deviceClass KEYWORD2
address KEYWORD2
addressType KEYWORD2
addressString KEYWORD2
rssi KEYWORD2
name KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################
+10
View File
@@ -0,0 +1,10 @@
name=BluetoothHCI
version=1.0
author=Earle F. Philhower, III <earlephilhower@yahoo.com>
maintainer=Earle F. Philhower, III <earlephilhower@yahoo.com>
sentence=Classic Bluetooth HCI functionality
paragraph=Classic Bluetooth HCI functionality
category=Communication
url=http://github.com/earlephilhower/arduino-pico
architectures=rp2040
dot_a_linkage=true
@@ -0,0 +1,83 @@
/*
Bluetooth device helper class
Copyright (c) 2024 Earle F. Philhower, III <earlephilhower@yahoo.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#pragma once
#include <Arduino.h>
class BTDeviceInfo {
public:
// Classic Bluetooth Device
BTDeviceInfo(uint32_t dc, const uint8_t addr[6], int rssi, const char *name) {
_deviceClass = dc;
memcpy(_address, addr, sizeof(_address));
_addressType = -1;
sprintf(_addressString, "%02x:%02x:%02x:%02x:%02x:%02x", addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
_rssi = rssi;
strncpy(_name, name, sizeof(_name));
_name[sizeof(_name) - 1] = 0;
}
// Bluetooth BLE Device
BTDeviceInfo(uint32_t dc, const uint8_t addr[6], int addressType, int rssi, const char *name, size_t nameLen) {
_deviceClass = dc;
memcpy(_address, addr, sizeof(_address));
sprintf(_addressString, "%02x:%02x:%02x:%02x:%02x:%02x", addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
_addressType = addressType;
_rssi = rssi;
memcpy(_name, name, std::min(nameLen, sizeof(_name)));
_name[std::min(nameLen, sizeof(_name) - 1)] = 0;
}
~BTDeviceInfo() {
}
uint32_t deviceClass() {
return _deviceClass;
}
const uint8_t *address() {
return _address;
}
const char *addressString() {
return _addressString;
}
int rssi() {
return _rssi;
}
const char *name() {
return _name;
}
int addressType() {
return _addressType;
}
private:
uint32_t _deviceClass;
uint8_t _address[6];
int _addressType;
char _addressString[18];
int8_t _rssi;
char _name[241];
};
+443
View File
@@ -0,0 +1,443 @@
/*
Bluetooth HCI packet handler class
Copyright (c) 2024 Earle F. Philhower, III <earlephilhower@yahoo.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <Arduino.h>
#include "btstack.h"
#include <list>
#include <memory>
#include "BluetoothHCI.h"
#include "BluetoothLock.h"
#define CCALLBACKNAME _BTHCICB
#include <ctocppcallback.h>
#define PACKETHANDLERCB(class, cbFcn) \
(_BTHCICB<void(uint8_t, uint16_t, uint8_t*, uint16_t), __COUNTER__>::func = std::bind(&class::cbFcn, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4), \
static_cast<btstack_packet_handler_t>(_BTHCICB<void(uint8_t, uint16_t, uint8_t*, uint16_t), __COUNTER__ - 1>::callback))
void BluetoothHCI::setBLEName(const char *name) {
if (_att) {
free(_att);
_att = nullptr;
}
_att = (uint8_t *)malloc(1 + 0x0a + 0x0d + 0x08 + strlen(name) + 0x02);
uint8_t *ptr = _att;
const uint8_t head[] = {
// ATT DB Version
1,
// 0x0001 PRIMARY_SERVICE-GAP_SERVICE
0x0a, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x28, 0x00, 0x18,
// 0x0002 CHARACTERISTIC-GAP_DEVICE_NAME - READ
0x0d, 0x00, 0x02, 0x00, 0x02, 0x00, 0x03, 0x28, 0x02, 0x03, 0x00, 0x00, 0x2a
};
memcpy(ptr, head, sizeof(head));
ptr += sizeof(head);
*ptr++ = 8 + strlen(name); // len of item
*ptr++ = 0x00;
*ptr++ = 0x02;
*ptr++ = 0x00;
*ptr++ = 0x03;
*ptr++ = 0x00;
*ptr++ = 0x00;
*ptr++ = 0x2a;
memcpy(ptr, name, strlen(name));
ptr += strlen(name);
// End it
*ptr++ = 0x00;
*ptr++ = 0x00;
DEBUGV("ATTDB: ");
for (size_t i = 0; i < 1 + 0x0a + 0x0d + 0x08 + strlen(name) + 0x02; i++) {
DEBUGV("%02X ", _att[i]);
}
DEBUGV("\n");
}
void BluetoothHCI::install() {
hci_set_inquiry_mode(INQUIRY_MODE_RSSI_AND_EIR);
// Register for HCI events.
hci_event_callback_registration.callback = PACKETHANDLERCB(BluetoothHCI, hci_packet_handler);
hci_add_event_handler(&hci_event_callback_registration);
// BLE set our visible name
if (_att) {
att_server_init(_att, nullptr, nullptr);
}
}
void BluetoothHCI::begin() {
_running = true;
hci_power_control(HCI_POWER_ON);
}
void BluetoothHCI::uninstall() {
BluetoothLock b;
hci_remove_event_handler(&hci_event_callback_registration);
_running = false;
free(_att);
_att = nullptr;
}
bool BluetoothHCI::running() {
return _hciRunning;
}
std::vector<BTDeviceInfo> BluetoothHCI::scan(uint32_t mask, int scanTimeSec, bool async) {
_scanMask = mask;
_btdList.reserve(MAX_DEVICES_TO_DISCOVER);
_btdList.clear();
if (!_running) {
return _btdList;
}
_scanning = true;
while (!_hciRunning) {
DEBUGV("HCI::scan(): Waiting for HCI to come up\n");
delay(10);
}
int inquiryTime = (scanTimeSec * 1000) / 1280; // divide by 1.280
if (!inquiryTime) {
inquiryTime = 1;
}
DEBUGV("HCI::scan(): inquiry start\n");
// Only need to lock around the inquiry start command, not the wait
{
BluetoothLock b;
gap_inquiry_start(inquiryTime);
}
if (async) {
return _btdList;
}
while (_scanning) {
delay(10);
}
DEBUGV("HCI::scan(): inquiry end\n");
return _btdList;
}
std::vector<BTDeviceInfo> BluetoothHCI::scanBLE(uint32_t uuid, int scanTimeSec) {
_scanMask = uuid;
_btdList.reserve(MAX_DEVICES_TO_DISCOVER);
_btdList.clear();
if (!_running) {
return _btdList;
}
_scanning = true;
while (!_hciRunning) {
DEBUGV("HCI::scanBLE(): Waiting for HCI to come up\n");
delay(10);
}
uint32_t inquiryTime = scanTimeSec * 1000;
if (!inquiryTime) {
inquiryTime = 1000;
}
DEBUGV("HCI::scan(): BLE advertise inquiry start\n");
// Only need to lock around the inquiry start command, not the wait
{
BluetoothLock b;
gap_set_scan_params(0, 75, 50, 0); // TODO - anything better for these params?
gap_start_scan();
}
uint32_t scanStart = millis();
while (_scanning && ((millis() - scanStart) < inquiryTime)) {
delay(10);
}
DEBUGV("HCI::scanBLE(): inquiry end\n");
gap_stop_scan();
return _btdList;
}
void BluetoothHCI::scanFree() {
_btdList.clear();
_btdList.shrink_to_fit();
}
void BluetoothHCI::parse_advertisement_data(uint8_t *packet) {
bd_addr_t address;
gap_event_advertising_report_get_address(packet, address);
//int event_type = gap_event_advertising_report_get_advertising_event_type(packet);
int address_type = gap_event_advertising_report_get_address_type(packet);
int8_t rssi = gap_event_advertising_report_get_rssi(packet);
uint8_t adv_size = gap_event_advertising_report_get_data_length(packet);
const uint8_t * adv_data = gap_event_advertising_report_get_data(packet);
uint16_t uuid = 0;
const char *nameptr = nullptr;
int namelen = 0;
ad_context_t context;
uint8_t uuid_128[16];
for (ad_iterator_init(&context, adv_size, (uint8_t *)adv_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)) {
uint8_t data_type = ad_iterator_get_data_type(&context);
uint8_t size = ad_iterator_get_data_len(&context);
const uint8_t * data = ad_iterator_get_data(&context);
// if (data_type > 0 && data_type < 0x1B){
// printf(" %s: ", ad_types[data_type]);
// }
int i;
// Assigned Numbers GAP
switch (data_type) {
case BLUETOOTH_DATA_TYPE_FLAGS:
// show only first octet, ignore rest
//for (i=0; i<8;i++){
// if (data[0] & (1<<i)){
// printf("%s; ", flags[i]);
// }
//}
break;
case BLUETOOTH_DATA_TYPE_INCOMPLETE_LIST_OF_16_BIT_SERVICE_CLASS_UUIDS:
case BLUETOOTH_DATA_TYPE_COMPLETE_LIST_OF_16_BIT_SERVICE_CLASS_UUIDS:
case BLUETOOTH_DATA_TYPE_LIST_OF_16_BIT_SERVICE_SOLICITATION_UUIDS:
for (i = 0; i < size; i += 2) {
uint16_t thisuuid = little_endian_read_16(data, i);
if (!_scanMask || (_scanMask == thisuuid)) {
uuid = thisuuid;
}
DEBUGV("uuid %02X ", thisuuid);
}
break;
case BLUETOOTH_DATA_TYPE_INCOMPLETE_LIST_OF_32_BIT_SERVICE_CLASS_UUIDS:
case BLUETOOTH_DATA_TYPE_COMPLETE_LIST_OF_32_BIT_SERVICE_CLASS_UUIDS:
case BLUETOOTH_DATA_TYPE_LIST_OF_32_BIT_SERVICE_SOLICITATION_UUIDS:
for (i = 0; i < size; i += 4) {
uint32_t thisuuid = little_endian_read_32(data, i);
if (!_scanMask || (_scanMask == thisuuid)) {
uuid = thisuuid;
}
DEBUGV("%04" PRIX32, thisuuid);
}
break;
case BLUETOOTH_DATA_TYPE_INCOMPLETE_LIST_OF_128_BIT_SERVICE_CLASS_UUIDS:
case BLUETOOTH_DATA_TYPE_COMPLETE_LIST_OF_128_BIT_SERVICE_CLASS_UUIDS:
case BLUETOOTH_DATA_TYPE_LIST_OF_128_BIT_SERVICE_SOLICITATION_UUIDS:
// Unhandled yet
reverse_128(data, uuid_128);
DEBUGV("%s", uuid128_to_str(uuid_128));
break;
case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
if (!nameptr) {
nameptr = (const char *)data;
namelen = size;
}
for (i = 0; i < size; i++) {
DEBUGV("%c", (char)(data[i]));
}
break;
case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
nameptr = (const char *)data;
namelen = size;
for (i = 0; i < size; i++) {
DEBUGV("%c", (char)(data[i]));
}
break;
case BLUETOOTH_DATA_TYPE_TX_POWER_LEVEL:
DEBUGV("%d dBm", *(int8_t*)data);
break;
case BLUETOOTH_DATA_TYPE_SLAVE_CONNECTION_INTERVAL_RANGE:
DEBUGV("Connection Interval Min = %u ms, Max = %u ms", little_endian_read_16(data, 0) * 5 / 4, little_endian_read_16(data, 2) * 5 / 4);
break;
case BLUETOOTH_DATA_TYPE_SERVICE_DATA:
//printf_hexdump(data, size);
break;
case BLUETOOTH_DATA_TYPE_PUBLIC_TARGET_ADDRESS:
case BLUETOOTH_DATA_TYPE_RANDOM_TARGET_ADDRESS:
reverse_bd_addr(data, address);
DEBUGV("%s", bd_addr_to_str(address));
break;
case BLUETOOTH_DATA_TYPE_APPEARANCE:
// https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.gap.appearance.xml
DEBUGV("%02X", little_endian_read_16(data, 0));
break;
case BLUETOOTH_DATA_TYPE_ADVERTISING_INTERVAL:
DEBUGV("%u ms", little_endian_read_16(data, 0) * 5 / 8);
break;
case BLUETOOTH_DATA_TYPE_3D_INFORMATION_DATA:
//printf_hexdump(data, size);
break;
case BLUETOOTH_DATA_TYPE_MANUFACTURER_SPECIFIC_DATA: // Manufacturer Specific Data
break;
case BLUETOOTH_DATA_TYPE_CLASS_OF_DEVICE:
case BLUETOOTH_DATA_TYPE_SIMPLE_PAIRING_HASH_C:
case BLUETOOTH_DATA_TYPE_SIMPLE_PAIRING_RANDOMIZER_R:
case BLUETOOTH_DATA_TYPE_DEVICE_ID:
case BLUETOOTH_DATA_TYPE_SECURITY_MANAGER_OUT_OF_BAND_FLAGS:
default:
DEBUGV("Advertising Data Type 0x%2x not handled yet", data_type);
break;
}
DEBUGV("\n");
}
DEBUGV("\n");
if (uuid) {
bool seen = false;
for (auto itr = _btdList.begin(); (itr != _btdList.end()) && !seen; itr++) {
if (!memcmp(itr->address(), address, sizeof(address))) {
seen = true;
}
}
if (!seen) {
BTDeviceInfo btd(uuid, address, address_type, rssi, nameptr ? nameptr : "", nameptr ? namelen : 0);
if (_btdList.size() < MAX_DEVICES_TO_DISCOVER) {
_btdList.push_back(btd);
}
}
}
}
static void handle_gatt_client_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
UNUSED(packet_type);
UNUSED(channel);
UNUSED(size);
gatt_client_service_t service;
gatt_client_characteristic_t characteristic;
switch (hci_event_packet_get_type(packet)) {
case GATT_EVENT_SERVICE_QUERY_RESULT:
gatt_event_service_query_result_get_service(packet, &service);
// dump_service(&service);
// services[service_count++] = service;
break;
case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT:
gatt_event_characteristic_query_result_get_characteristic(packet, &characteristic);
// dump_characteristic(&characteristic);
break;
case GATT_EVENT_QUERY_COMPLETE:
// GATT_EVENT_QUERY_COMPLETE of search characteristics
// if (service_index < service_count) {
// service = services[service_index++];
// printf("\nGATT browser - CHARACTERISTIC for SERVICE %s, [0x%04x-0x%04x]\n",
// uuid128_to_str(service.uuid128), service.start_group_handle, service.end_group_handle);
// gatt_client_discover_characteristics_for_service(handle_gatt_client_event, connection_handle, &service);
// break;
// }
// service_index = 0;
break;
default:
break;
}
}
void BluetoothHCI::hci_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
(void)channel;
(void)size;
if (packet_type != HCI_EVENT_PACKET) {
return;
}
bd_addr_t address;
uint32_t cod;
int8_t rssi;
const char *name;
char name_buffer[241];
switch (hci_event_packet_get_type(packet)) {
case BTSTACK_EVENT_STATE:
_hciRunning = (btstack_event_state_get_state(packet) == HCI_STATE_WORKING);
break;
case HCI_EVENT_PIN_CODE_REQUEST:
hci_event_pin_code_request_get_bd_addr(packet, address);
gap_pin_code_response(address, "0000");
break;
case GAP_EVENT_INQUIRY_RESULT:
if (!_scanning) {
return;
}
gap_event_inquiry_result_get_bd_addr(packet, address);
cod = gap_event_inquiry_result_get_class_of_device(packet);
if (gap_event_inquiry_result_get_rssi_available(packet)) {
rssi = gap_event_inquiry_result_get_rssi(packet);
} else {
rssi = -128;
}
if (gap_event_inquiry_result_get_name_available(packet)) {
int name_len = gap_event_inquiry_result_get_name_len(packet);
memcpy(name_buffer, gap_event_inquiry_result_get_name(packet), name_len);
name_buffer[name_len] = 0;
name = name_buffer;
} else {
name = "";
}
DEBUGV("HCI: Scan found '%s', COD 0x%08X, RSSI %d, MAC %02X:%02X:%02X:%02X:%02X:%02X\n", name, (unsigned int)cod, rssi, address[0], address[1], address[2], address[3], address[4], address[5]);
if ((_scanMask & cod) == _scanMask) {
// Sometimes we get multiple reports for the same MAC, so remove any old reports since newer will have newer RSSI
bool updated = false;
for (auto itr = _btdList.begin(); (itr != _btdList.end()) && !updated; itr++) {
if (!memcmp(itr->address(), address, sizeof(address))) {
// Sometimes the name is missing on reports, so if we found it once preserve it
if (!name_buffer[0] && itr->name()[0]) {
strcpy(name_buffer, itr->name());
}
_btdList.erase(itr);
updated = true;
}
}
BTDeviceInfo btd(cod, address, rssi, name);
if (_btdList.size() < MAX_DEVICES_TO_DISCOVER) {
_btdList.push_back(btd);
}
}
break;
case GAP_EVENT_INQUIRY_COMPLETE:
_scanning = false;
break;
case GAP_EVENT_ADVERTISING_REPORT:
if (_scanning) {
parse_advertisement_data(packet);
}
break;
case HCI_EVENT_DISCONNECTION_COMPLETE:
_hciConn = HCI_CON_HANDLE_INVALID;
DEBUGV("HCI Disconnected\n");
break;
case HCI_EVENT_LE_META:
// wait for connection complete
if (hci_event_le_meta_get_subevent_code(packet) != HCI_SUBEVENT_LE_CONNECTION_COMPLETE) {
break;
}
DEBUGV("HCI Connected\n");
_hciConn = hci_subevent_le_connection_complete_get_connection_handle(packet);
if (_smPair) {
sm_request_pairing(_hciConn);
} else {
// query primary services - not used yet
gatt_client_discover_primary_services(handle_gatt_client_event, _hciConn);
}
break;
default:
break;
}
}
+78
View File
@@ -0,0 +1,78 @@
/*
Bluetooth HCI packet handler class
Copyright (c) 2024 Earle F. Philhower, III <earlephilhower@yahoo.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#pragma once
#include <_needsbt.h>
#include <Arduino.h>
#include <list>
#include <memory>
#include "BluetoothDevice.h"
#include <btstack.h>
class BluetoothHCI {
public:
void install();
void setBLEName(const char *bleMasterName);
void begin();
void uninstall();
bool running();
static const uint32_t speaker_cod = 0x200000 | 0x040000 | 0x000400; // Service Class: Rendering | Audio, Major Device Class: Audio
static const uint32_t any_cod = 0;
std::vector<BTDeviceInfo> scan(uint32_t mask, int scanTimeSec = 5, bool async = false);
bool scanAsyncDone();
std::vector<BTDeviceInfo> scanAsyncResult();
std::vector<BTDeviceInfo> scanBLE(uint32_t uuid, int scanTimeSec = 5);
void scanFree(); // Free allocated scan buffers
friend class BluetoothHIDMaster;
protected:
hci_con_handle_t getHCIConn() {
return _hciConn;
}
void setPairOnMeta(bool v) {
_smPair = v;
}
private:
void hci_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
btstack_packet_callback_registration_t hci_event_callback_registration;
volatile bool _hciRunning = false;
uint32_t _scanMask;
// Use a .reserve()'d vector to avoid any memory allocations in the
// HCI callback, since the callback happens at IRQ time. Any more
// elements than MAX_DEVICES_TO_DISCOVER will be thrown out
enum { MAX_DEVICES_TO_DISCOVER = 32 };
std::vector<BTDeviceInfo> _btdList;
volatile bool _scanning = false;
bool _running = false;
// BLE specific
uint8_t *_att = nullptr;
void parse_advertisement_data(uint8_t *packet);
volatile hci_con_handle_t _hciConn = HCI_CON_HANDLE_INVALID;
bool _smPair = false;
};
@@ -0,0 +1,34 @@
/*
Bluetooth lock helper class
Copyright (c) 2024 Earle F. Philhower, III <earlephilhower@yahoo.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#pragma once
#include <_needsbt.h>
#include <Arduino.h>
class BluetoothLock {
public:
BluetoothLock() {
__lockBluetooth();
}
~BluetoothLock() {
__unlockBluetooth();
}
};
@@ -0,0 +1,223 @@
// KeyboardPiano example - Released to the public domain in 2024 by Earle F. Philhower, III
//
// Demonstrates using the BluetoothHIDMaster class to use a Bluetooth keyboard as a
// piano keyboard on the PicoW
//
// Hook up a phono plug to GP0 and GP1 (and GND of course...the 1st 3 pins on the PCB)
// Connect wired earbuds up and connect over BT from your keyboard and play some music.
#include <BluetoothHIDMaster.h>
#include <PWMAudio.h>
// We need the inverse map, borrow from the Keyboard library
#include <HID_Keyboard.h>
extern const uint8_t KeyboardLayout_en_US[128];
BluetoothHIDMaster hid;
PWMAudio pwm;
HIDKeyStream keystream;
int16_t sine[1000]; // One complete precalculated sine wave for oscillator use
void precalculateSine() {
for (int i = 0; i < 1000; i++) {
sine[i] = (int16_t)(2000.0 * sin(i * 2 * 3.14159 / 1000.0)); // Only make amplitude ~1/16 max so we can sum up w/o clipping
}
}
// Simple variable frequency resampling oscillator state
typedef struct {
uint32_t key; // Identifier of which key started this tone
uint32_t pos; // Current sine offset
uint32_t step; // Delta in fixed point 16p16 format
} Oscillator;
Oscillator osc[6]; // Look, ma! 6-note polyphony!
// Quiet down, now!
void silenceOscillators() {
noInterrupts();
for (int i = 0; i < 6; i++) {
osc[i].pos = 0;
osc[i].step = 0;
}
interrupts();
}
// PWM callback, generates sum of online oscillators
void fill() {
int num_samples = pwm.availableForWrite() / 2;
int16_t buff[32 * 2];
while (num_samples > 63) {
// Run in 32 LR sample chunks for speed, less loop overhead
for (int o = 0; o < 32; o++) {
int32_t sum = 0;
for (int i = 0; i < 6; i++) {
if (osc[i].step) {
sum += sine[osc[i].pos >> 16];
osc[i].pos += osc[i].step;
while (osc[i].pos >= 1000 << 16) {
osc[i].pos -= 1000 << 16;
}
}
}
if (sum > 32767) {
sum = 32767;
} else if (sum < -32767) {
sum = -32767;
}
buff[o * 2] = (int16_t) sum;
buff[o * 2 + 1] = (int16_t) sum;
}
pwm.write((const uint8_t *)buff, sizeof(buff));
num_samples -= 64;
}
}
// Mouse callbacks. Could keep track of global mouse position, update a cursor, etc.
void mm(void *cbdata, int dx, int dy, int dw) {
(void) cbdata;
Serial.printf("Mouse: X:%d Y:%d Wheel:%d\n", dx, dy, dw);
}
// Buttons are sent separately from movement
void mb(void *cbdata, int butt, bool down) {
(void) cbdata;
Serial.printf("Mouse: Button %d %s\n", butt, down ? "DOWN" : "UP");
}
// Convert a hertz floating point into a step fixed point 16p16
inline uint32_t stepForHz(float hz) {
const float stepHz = 1000.0 / 44100.0;
const float step = hz * stepHz;
return (uint32_t)(step * 65536.0);
}
uint32_t keyStepMap[128]; // The frequency of any raw HID key
void setupKeyStepMap() {
for (int i = 0; i < 128; i++) {
keyStepMap[i] = 0;
}
// Implements the "standard" PC keyboard to piano setup
// https://ux.stackexchange.com/questions/46669/mapping-piano-keys-to-computer-keyboard
keyStepMap[KeyboardLayout_en_US['a']] = stepForHz(261.6256);
keyStepMap[KeyboardLayout_en_US['w']] = stepForHz(277.1826);
keyStepMap[KeyboardLayout_en_US['s']] = stepForHz(293.6648);
keyStepMap[KeyboardLayout_en_US['e']] = stepForHz(311.1270);
keyStepMap[KeyboardLayout_en_US['d']] = stepForHz(329.6276);
keyStepMap[KeyboardLayout_en_US['f']] = stepForHz(349.2282);
keyStepMap[KeyboardLayout_en_US['t']] = stepForHz(369.9944);
keyStepMap[KeyboardLayout_en_US['g']] = stepForHz(391.9954);
keyStepMap[KeyboardLayout_en_US['y']] = stepForHz(415.3047);
keyStepMap[KeyboardLayout_en_US['h']] = stepForHz(440.0000);
keyStepMap[KeyboardLayout_en_US['u']] = stepForHz(466.1638);
keyStepMap[KeyboardLayout_en_US['j']] = stepForHz(493.8833);
keyStepMap[KeyboardLayout_en_US['k']] = stepForHz(523.2511);
keyStepMap[KeyboardLayout_en_US['o']] = stepForHz(554.3653);
keyStepMap[KeyboardLayout_en_US['l']] = stepForHz(587.3295);
keyStepMap[KeyboardLayout_en_US['p']] = stepForHz(622.2540);
keyStepMap[KeyboardLayout_en_US[';']] = stepForHz(659.2551);
keyStepMap[KeyboardLayout_en_US['\'']] = stepForHz(698.4565);
}
// We get make/break for every key which lets us hold notes while a key is depressed
void kb(void *cbdata, int key) {
bool state = (bool)cbdata;
if (state && key < 128) {
// Starting a new note
for (int i = 0; i < 6; i++) {
if (osc[i].step == 0) {
// This one is free
osc[i].key = key;
osc[i].pos = 0;
osc[i].step = keyStepMap[key];
break;
}
}
} else {
for (int i = 0; i < 6; i++) {
if (osc[i].key == (uint32_t)key) {
osc[i].step = 0;
break;
}
}
}
// The HIDKeyStream object converts a key and state into ASCII. HID key IDs do not map 1:1 to ASCII!
// Write the key and make/break state, then read 1 ASCII char back out.
keystream.write((uint8_t)key);
keystream.write((uint8_t)state);
Serial.printf("Keyboard: %02x %s = '%c'\n", key, state ? "DOWN" : "UP", state ? keystream.read() : '-');
}
// Consumer keys are the special media keys on most modern keyboards (mute/etc.)
void ckb(void *cbdata, int key) {
bool state = (bool)cbdata;
Serial.printf("Consumer: %02x %s\n", key, state ? "DOWN" : "UP");
}
// Joystick can get reports of 4 analog axes, 1 d-pad bitfield, and up to 32 buttons
// Axes and hats that aren't reported by the joystick are read as 0
void joy(void *cbdata, int x, int y, int z, int rz, uint8_t hat, uint32_t buttons) {
(void) cbdata;
const char *hats[16] = { "U", "UR", "R", "DR", "D", "DL", "L", "UL", "", "", "", "", "", "", "", "." };
Serial.printf("Joystick: (%4d, %4d) (%4d, %4d), Hat: %-2s, Buttons:", x, y, z, rz, hats[hat & 15]);
for (int i = 0; i < 32; i++) {
Serial.printf(" %c", (buttons & 1 << i) ? '*' : '.');
}
Serial.println();
}
void setup() {
Serial.begin();
delay(3000);
Serial.printf("Starting HID master, put your device in pairing mode now.\n");
// Init the sound generator
precalculateSine();
silenceOscillators();
setupKeyStepMap();
// Setup the HID key to ASCII conversion
keystream.begin();
// Init the PWM audio output
pwm.setStereo(true);
pwm.setBuffers(16, 64);
pwm.onTransmit(fill);
pwm.begin(44100);
// Mouse buttons and movement reported separately
hid.onMouseMove(mm);
hid.onMouseButton(mb);
// We can use the cbData as a flag to see if we're making or breaking a key
hid.onKeyDown(kb, (void *)true);
hid.onKeyUp(kb, (void *)false);
// Consumer keys are the special function ones like "mute" or "home"
hid.onConsumerKeyDown(ckb, (void *)true);
hid.onConsumerKeyUp(ckb, (void *)false);
hid.onJoystick(joy);
hid.begin();
hid.connectAny();
// or hid.connectMouse();
}
void loop() {
if (BOOTSEL) {
while (BOOTSEL) {
delay(1);
}
hid.disconnect();
hid.clearPairing();
Serial.printf("Restarting HID master, put your device in pairing mode now.\n");
hid.connectAny();
}
}
@@ -0,0 +1,222 @@
// KeyboardPiano example - Released to the public domain in 2024 by Earle F. Philhower, III
//
// Demonstrates using the BluetoothHIDMaster class to use a Bluetooth keyboard as a
// piano keyboard on the PicoW
//
// Hook up a phono plug to GP0 and GP1 (and GND of course...the 1st 3 pins on the PCB)
// Connect wired earbuds up and connect over BT from your keyboard and play some music.
#include <BluetoothHIDMaster.h>
#include <PWMAudio.h>
// We need the inverse map, borrow from the Keyboard library
#include <HID_Keyboard.h>
extern const uint8_t KeyboardLayout_en_US[128];
BluetoothHIDMaster hid;
PWMAudio pwm;
HIDKeyStream keystream;
int16_t sine[1000]; // One complete precalculated sine wave for oscillator use
void precalculateSine() {
for (int i = 0; i < 1000; i++) {
sine[i] = (int16_t)(2000.0 * sin(i * 2 * 3.14159 / 1000.0)); // Only make amplitude ~1/16 max so we can sum up w/o clipping
}
}
// Simple variable frequency resampling oscillator state
typedef struct {
uint32_t key; // Identifier of which key started this tone
uint32_t pos; // Current sine offset
uint32_t step; // Delta in fixed point 16p16 format
} Oscillator;
Oscillator osc[6]; // Look, ma! 6-note polyphony!
// Quiet down, now!
void silenceOscillators() {
noInterrupts();
for (int i = 0; i < 6; i++) {
osc[i].pos = 0;
osc[i].step = 0;
}
interrupts();
}
// PWM callback, generates sum of online oscillators
void fill() {
int num_samples = pwm.availableForWrite() / 2;
int16_t buff[32 * 2];
while (num_samples > 63) {
// Run in 32 LR sample chunks for speed, less loop overhead
for (int o = 0; o < 32; o++) {
int32_t sum = 0;
for (int i = 0; i < 6; i++) {
if (osc[i].step) {
sum += sine[osc[i].pos >> 16];
osc[i].pos += osc[i].step;
while (osc[i].pos >= 1000 << 16) {
osc[i].pos -= 1000 << 16;
}
}
}
if (sum > 32767) {
sum = 32767;
} else if (sum < -32767) {
sum = -32767;
}
buff[o * 2] = (int16_t) sum;
buff[o * 2 + 1] = (int16_t) sum;
}
pwm.write((const uint8_t *)buff, sizeof(buff));
num_samples -= 64;
}
}
// Mouse callbacks. Could keep track of global mouse position, update a cursor, etc.
void mm(void *cbdata, int dx, int dy, int dw) {
(void) cbdata;
Serial.printf("Mouse: X:%d Y:%d Wheel:%d\n", dx, dy, dw);
}
// Buttons are sent separately from movement
void mb(void *cbdata, int butt, bool down) {
(void) cbdata;
Serial.printf("Mouse: Button %d %s\n", butt, down ? "DOWN" : "UP");
}
// Convert a hertz floating point into a step fixed point 16p16
inline uint32_t stepForHz(float hz) {
const float stepHz = 1000.0 / 44100.0;
const float step = hz * stepHz;
return (uint32_t)(step * 65536.0);
}
uint32_t keyStepMap[128]; // The frequency of any raw HID key
void setupKeyStepMap() {
for (int i = 0; i < 128; i++) {
keyStepMap[i] = 0;
}
// Implements the "standard" PC keyboard to piano setup
// https://ux.stackexchange.com/questions/46669/mapping-piano-keys-to-computer-keyboard
keyStepMap[KeyboardLayout_en_US['a']] = stepForHz(261.6256);
keyStepMap[KeyboardLayout_en_US['w']] = stepForHz(277.1826);
keyStepMap[KeyboardLayout_en_US['s']] = stepForHz(293.6648);
keyStepMap[KeyboardLayout_en_US['e']] = stepForHz(311.1270);
keyStepMap[KeyboardLayout_en_US['d']] = stepForHz(329.6276);
keyStepMap[KeyboardLayout_en_US['f']] = stepForHz(349.2282);
keyStepMap[KeyboardLayout_en_US['t']] = stepForHz(369.9944);
keyStepMap[KeyboardLayout_en_US['g']] = stepForHz(391.9954);
keyStepMap[KeyboardLayout_en_US['y']] = stepForHz(415.3047);
keyStepMap[KeyboardLayout_en_US['h']] = stepForHz(440.0000);
keyStepMap[KeyboardLayout_en_US['u']] = stepForHz(466.1638);
keyStepMap[KeyboardLayout_en_US['j']] = stepForHz(493.8833);
keyStepMap[KeyboardLayout_en_US['k']] = stepForHz(523.2511);
keyStepMap[KeyboardLayout_en_US['o']] = stepForHz(554.3653);
keyStepMap[KeyboardLayout_en_US['l']] = stepForHz(587.3295);
keyStepMap[KeyboardLayout_en_US['p']] = stepForHz(622.2540);
keyStepMap[KeyboardLayout_en_US[';']] = stepForHz(659.2551);
keyStepMap[KeyboardLayout_en_US['\'']] = stepForHz(698.4565);
}
// We get make/break for every key which lets us hold notes while a key is depressed
void kb(void *cbdata, int key) {
bool state = (bool)cbdata;
if (state && key < 128) {
// Starting a new note
for (int i = 0; i < 6; i++) {
if (osc[i].step == 0) {
// This one is free
osc[i].key = key;
osc[i].pos = 0;
osc[i].step = keyStepMap[key];
break;
}
}
} else {
for (int i = 0; i < 6; i++) {
if (osc[i].key == (uint32_t)key) {
osc[i].step = 0;
break;
}
}
}
// The HIDKeyStream object converts a key and state into ASCII. HID key IDs do not map 1:1 to ASCII!
// Write the key and make/break state, then read 1 ASCII char back out.
keystream.write((uint8_t)key);
keystream.write((uint8_t)state);
Serial.printf("Keyboard: %02x %s = '%c'\n", key, state ? "DOWN" : "UP", state ? keystream.read() : '-');
}
// Consumer keys are the special media keys on most modern keyboards (mute/etc.)
void ckb(void *cbdata, int key) {
bool state = (bool)cbdata;
Serial.printf("Consumer: %02x %s\n", key, state ? "DOWN" : "UP");
}
// Joystick can get reports of 4 analog axes, 1 d-pad bitfield, and up to 32 buttons
// Axes and hats that aren't reported by the joystick are read as 0
void joy(void *cbdata, int x, int y, int z, int rz, uint8_t hat, uint32_t buttons) {
(void) cbdata;
const char *hats[16] = { "U", "UR", "R", "DR", "D", "DL", "L", "UL", "", "", "", "", "", "", "", "." };
Serial.printf("Joystick: (%4d, %4d) (%4d, %4d), Hat: %-2s, Buttons:", x, y, z, rz, hats[hat & 15]);
for (int i = 0; i < 32; i++) {
Serial.printf(" %c", (buttons & 1 << i) ? '*' : '.');
}
Serial.println();
}
void setup() {
Serial.begin();
delay(3000);
Serial.printf("Starting HID master, put your device in pairing mode now.\n");
// Init the sound generator
precalculateSine();
silenceOscillators();
setupKeyStepMap();
// Setup the HID key to ASCII conversion
keystream.begin();
// Init the PWM audio output
pwm.setStereo(true);
pwm.setBuffers(16, 64);
pwm.onTransmit(fill);
pwm.begin(44100);
// Mouse buttons and movement reported separately
hid.onMouseMove(mm);
hid.onMouseButton(mb);
// We can use the cbData as a flag to see if we're making or breaking a key
hid.onKeyDown(kb, (void *)true);
hid.onKeyUp(kb, (void *)false);
// Consumer keys are the special function ones like "mute" or "home"
hid.onConsumerKeyDown(ckb, (void *)true);
hid.onConsumerKeyUp(ckb, (void *)false);
hid.onJoystick(joy);
hid.begin(true);
hid.connectBLE();
}
void loop() {
if (BOOTSEL) {
while (BOOTSEL) {
delay(1);
}
hid.disconnect();
hid.clearPairing();
Serial.printf("Restarting HID master, put your device in pairing mode now.\n");
hid.connectBLE();
}
}
+45
View File
@@ -0,0 +1,45 @@
#######################################
# Syntax Coloring Map
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
BluetoothHIDMaster KEYWORD1
HIDKeyStream KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
begin KEYWORD2
end KEYWORD2
scan KEYWORD2
scanAsyncDone KEYWORD2
scanAsyncResult KEYWORD2
connectKeyboard KEYWORD2
connectMouse KEYWORD2
connectJoypad KEYWORD2
connectAny KEYWORD2
hidConnected KEYWORD2
onMouseMove KEYWORD2
onMouseButton KEYWORD2
onKeyDown KEYWORD2
onKeyUp KEYWORD2
onConsumerKeyDown KEYWORD2
onConsumerKeyUp KEYWORD2
onJoypad KEYWORD2
# BTDeviceInfo
deviceClass KEYWORD2
address KEYWORD2
addressString KEYWORD2
rssi KEYWORD2
name KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################
@@ -0,0 +1,11 @@
name=BluetoothHIDMaster
version=1.0
author=Earle F. Philhower, III <earlephilhower@yahoo.com>
maintainer=Earle F. Philhower, III <earlephilhower@yahoo.com>
sentence=Bluetooth Classic and BLE HID (Keyboard/Mouse/Joystick) master mode
paragraph=Bluetooth Classic and BLE HID (Keyboard/Mouse/Joystick) master mode
category=Communication
url=http://github.com/earlephilhower/arduino-pico
architectures=rp2040
dot_a_linkage=true
depends=BluetoothHCI
@@ -0,0 +1,825 @@
/*
Bluetooth HCI packet handler class
Copyright (c) 2024 Earle F. Philhower, III <earlephilhower@yahoo.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
// Based off of the BlueKitchen HID master demo
/*
Copyright (C) 2023 BlueKitchen GmbH
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the names of
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
4. Any redistribution, use, or modification is done solely for
personal benefit and not for any commercial purpose or for
monetary gain.
THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN
GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
Please inquire about commercial licensing options at
contact@bluekitchen-gmbh.com
*/
#include <Arduino.h>
#include "btstack.h"
#include <list>
#include <memory>
#include <BluetoothLock.h>
#include "BluetoothHIDMaster.h"
#define CCALLBACKNAME _BTHIDCB
#include <ctocppcallback.h>
#define PACKETHANDLERCB(class, cbFcn) \
(CCALLBACKNAME<void(uint8_t, uint16_t, uint8_t*, uint16_t), __COUNTER__>::func = std::bind(&class::cbFcn, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4), \
static_cast<btstack_packet_handler_t>(CCALLBACKNAME<void(uint8_t, uint16_t, uint8_t*, uint16_t), __COUNTER__ - 1>::callback))
void BluetoothHIDMaster::begin(bool ble, const char *bleName) {
_ble = ble;
if (!ble) {
// Initialize HID Host
hid_host_init(_hid_descriptor_storage, sizeof(_hid_descriptor_storage));
hid_host_register_packet_handler(PACKETHANDLERCB(BluetoothHIDMaster, hid_packet_handler));
} else {
if (bleName) {
_hci.setBLEName(bleName);
}
_hci.setPairOnMeta(true);
}
// Initialize L2CAP
l2cap_init();
// Initialize LE Security Manager. Needed for cross-transport key derivation
if (ble) {
// register for events from Security Manager
_sm_event_callback_registration.callback = PACKETHANDLERCB(BluetoothHIDMaster, sm_packet_handler);
sm_add_event_handler(&_sm_event_callback_registration);
}
sm_init();
if (ble) {
gatt_client_init();
hids_client_init(_hid_descriptor_storage, sizeof(_hid_descriptor_storage));
} else {
// Allow sniff mode requests by HID device and support role switch
gap_set_default_link_policy_settings(LM_LINK_POLICY_ENABLE_SNIFF_MODE | LM_LINK_POLICY_ENABLE_ROLE_SWITCH);
// try to become master on incoming connections
hci_set_master_slave_policy(HCI_ROLE_MASTER);
}
// enabled EIR
hci_set_inquiry_mode(INQUIRY_MODE_RSSI_AND_EIR);
_hci.install();
_running = true;
_hci.begin();
}
void BluetoothHIDMaster::end() {
BluetoothLock b;
_hci.uninstall();
_running = false;
}
bool BluetoothHIDMaster::running() {
return _hci.running() && _hidConnected;
}
bool BluetoothHIDMaster::hciRunning() {
return _hci.running();
}
void BluetoothHIDMaster::onMouseMove(void (*cb)(void *, int, int, int), void *cbData) {
_mouseMoveCB = cb;
_mouseMoveData = cbData;
}
void BluetoothHIDMaster::onMouseButton(void (*cb)(void *, int, bool), void *cbData) {
_mouseButtonCB = cb;
_mouseButtonData = cbData;
}
void BluetoothHIDMaster::onKeyDown(void (*cb)(void *, int), void *cbData) {
_keyDownCB = cb;
_keyDownData = cbData;
}
void BluetoothHIDMaster::onKeyUp(void (*cb)(void *, int), void *cbData) {
_keyUpCB = cb;
_keyUpData = cbData;
}
void BluetoothHIDMaster::onConsumerKeyDown(void (*cb)(void *, int), void *cbData) {
_consumerKeyDownCB = cb;
_consumerKeyDownData = cbData;
}
void BluetoothHIDMaster::onConsumerKeyUp(void (*cb)(void *, int), void *cbData) {
_consumerKeyUpCB = cb;
_consumerKeyUpData = cbData;
}
void BluetoothHIDMaster::onJoystick(void (*cb)(void *, int, int, int, int, uint8_t, uint32_t), void *cbData) {
_joystickCB = cb;
_joystickData = cbData;
}
std::vector<BTDeviceInfo> BluetoothHIDMaster::scan(uint32_t mask, int scanTimeSec, bool async) {
return _hci.scan(mask, scanTimeSec, async);
}
bool BluetoothHIDMaster::scanAsyncDone() {
return _hci.scanAsyncDone();
}
std::vector<BTDeviceInfo> BluetoothHIDMaster::scanAsyncResult() {
return _hci.scanAsyncResult();
}
bool BluetoothHIDMaster::connected() {
return _hidConnected && _hid_host_descriptor_available;
}
bool BluetoothHIDMaster::connect(const uint8_t *addr) {
if (!_running || _ble) {
return false;
}
while (!_hci.running()) {
delay(10);
}
uint8_t a[6];
memcpy(a, addr, sizeof(a));
return ERROR_CODE_SUCCESS == hid_host_connect(a, HID_PROTOCOL_MODE_REPORT, &_hid_host_cid);
}
bool BluetoothHIDMaster::connectCOD(uint32_t cod) {
if (!_running || _ble) {
return false;
}
while (!_hci.running()) {
delay(10);
}
uint8_t a[6];
clearPairing();
auto l = scan(cod);
for (auto e : l) {
DEBUGV("Scan connecting %s at %s ... ", e.name(), e.addressString());
memcpy(a, e.address(), sizeof(a));
if (ERROR_CODE_SUCCESS == hid_host_connect(a, HID_PROTOCOL_MODE_REPORT, &_hid_host_cid)) {
DEBUGV("Connection established\n");
return true;
}
DEBUGV("Failed\n");
}
return false;
}
bool BluetoothHIDMaster::connectBLE(const uint8_t *addr, int addrType) {
if (!_running || !_ble) {
return false;
}
while (!_hci.running()) {
delay(10);
}
uint8_t a[6];
memcpy(a, addr, sizeof(a));
return ERROR_CODE_SUCCESS == gap_connect(a, (bd_addr_type_t)addrType);
}
bool BluetoothHIDMaster::connectBLE() {
if (!_running || !_ble) {
return false;
}
while (!_hci.running()) {
delay(10);
}
clearPairing();
auto l = _hci.scanBLE(0x1812 /* HID */);
for (auto e : l) {
DEBUGV("Scan connecting %s at %s ... ", e.name(), e.addressString());
if (connectBLE(e.address(), e.addressType())) {
DEBUGV("Connection established\n");
return true;
}
DEBUGV("Failed\n");
}
return false;
}
bool BluetoothHIDMaster::connectKeyboard() {
return connectCOD(0x2540);
}
bool BluetoothHIDMaster::connectMouse() {
return connectCOD(0x2580);
}
bool BluetoothHIDMaster::connectJoystick() {
return connectCOD(0x2508);
}
bool BluetoothHIDMaster::connectAny() {
return connectCOD(0x2500);
}
bool BluetoothHIDMaster::disconnect() {
BluetoothLock b;
if (!_running || !connected()) {
return false;
}
if (!_ble && connected()) {
hid_host_disconnect(_hid_host_cid);
} else if (_ble && connected()) {
gap_disconnect(_hci.getHCIConn());
}
_hid_host_descriptor_available = false;
return true;
}
void BluetoothHIDMaster::clearPairing() {
BluetoothLock b;
if (connected()) {
if (_ble) {
gap_disconnect(_hci.getHCIConn());
} else {
hid_host_disconnect(_hid_host_cid);
}
}
gap_delete_all_link_keys();
_hid_host_descriptor_available = false;
}
void BluetoothHIDMaster::hid_host_handle_interrupt_report(btstack_hid_parser_t * parser) {
uint8_t new_keys[NUM_KEYS];
uint8_t tosend[NUM_KEYS];
int tosendcnt = 0;
memset(new_keys, 0, sizeof(new_keys));
int new_keys_count = 0;
uint16_t new_consumer_key = 0;
uint32_t newMB = 0;
bool noMB = false;
bool updCons = false;
bool updKey = false;
bool updMB = false;
bool updJoy = false;
bool updMouse = false;
int dx = 0;
int dy = 0;
int dz = 0;
int rz = 0;
int dwheel = 0;
uint8_t hat = 0;
while (btstack_hid_parser_has_more(parser)) {
uint16_t usage_page;
uint16_t usage;
int32_t value;
btstack_hid_parser_get_field(parser, &usage_page, &usage, &value);
if (usage_page == 0x01) {
updMouse = true;
updJoy = true;
if (usage == 0x30) {
dx = value;
} else if (usage == 0x31) {
dy = value;
} else if (usage == 0x32) {
dz = value;
} else if (usage == 0x35) {
rz = value;
} else if (usage == 0x38) {
dwheel = value;
} else if (usage == 0x39) {
hat = value & 0xff;
}
} else if (usage_page == 0x09) {
updMB = true;
if (usage == 0) {
noMB = true;
}
if (!noMB && value && (usage > 0)) {
newMB |= 1 << (usage - 1);
}
} else if (usage_page == 0x0c) {
updCons = true;
if (value) {
new_consumer_key = usage;
// check if usage was used last time (and ignore in that case)
if (usage == last_consumer_key) {
usage = 0;
}
if (usage == 0) {
continue;
}
if (last_consumer_key) {
if (_consumerKeyUpCB) {
_consumerKeyUpCB(_consumerKeyUpData, last_consumer_key);
}
}
if (_consumerKeyDownCB) {
_consumerKeyDownCB(_consumerKeyDownData, usage);
}
} else if (last_consumer_key == usage) {
if (_consumerKeyUpCB) {
_consumerKeyUpCB(_consumerKeyUpData, last_consumer_key);
}
}
} else if (usage_page == 0x07) {
updKey = true;
if (value) {
new_keys[new_keys_count++] = usage;
// check if usage was used last time (and ignore in that case)
int i;
for (i = 0; i < NUM_KEYS; i++) {
if (usage == last_keys[i]) {
usage = 0;
}
}
if (usage == 0) {
continue;
}
tosend[tosendcnt++] = usage;
}
}
}
if (updKey) {
bool found;
for (int i = 0; i < NUM_KEYS; i++) {
found = false;
for (int j = 0; j < NUM_KEYS; j++) {
if (last_keys[i] == new_keys[j]) {
found = true;
break;
}
}
if (!found && last_keys[i] && _keyUpCB) {
_keyUpCB(_keyUpData, last_keys[i]);
}
}
for (int i = 0; _keyDownCB && i < tosendcnt; i++) {
_keyDownCB(_keyDownData, tosend[i]);
}
memcpy(last_keys, new_keys, NUM_KEYS);
}
if (updCons) {
last_consumer_key = new_consumer_key;
}
if (updMB && _mouseButtonCB) {
if (lastMB != newMB) {
for (int i = 0; i < 8; i++) {
int mask = 1 << i;
if ((lastMB & mask) && !(newMB & mask)) {
_mouseButtonCB(_mouseButtonData, i, false);
} else if (!(lastMB & mask) && (newMB & mask)) {
_mouseButtonCB(_mouseButtonData, i, true);
}
}
lastMB = newMB;
}
}
if (updMouse && _mouseMoveCB) {
_mouseMoveCB(_mouseMoveData, dx, dy, dwheel);
}
if (updJoy && _joystickCB) {
_joystickCB(_joystickData, dx, dy, dz, rz, hat, newMB);
}
}
void BluetoothHIDMaster::hid_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
(void)channel;
(void)size;
if ((packet_type != HCI_EVENT_PACKET) || (hci_event_packet_get_type(packet) != HCI_EVENT_HID_META)) {
return;
}
uint8_t status;
switch (hci_event_hid_meta_get_subevent_code(packet)) {
case HID_SUBEVENT_INCOMING_CONNECTION:
// There is an incoming connection: we can accept it or decline it.
// The hid_host_report_mode in the hid_host_accept_connection function
// allows the application to request a protocol mode.
// For available protocol modes, see hid_protocol_mode_t in btstack_hid.h file.
hid_host_accept_connection(hid_subevent_incoming_connection_get_hid_cid(packet), HID_PROTOCOL_MODE_REPORT);
break;
case HID_SUBEVENT_CONNECTION_OPENED:
// The status field of this event indicates if the control and interrupt
// connections were opened successfully.
status = hid_subevent_connection_opened_get_status(packet);
if (status != ERROR_CODE_SUCCESS) {
DEBUGV("Connection failed, status 0x%02x\n", status);
_hidConnected = false;
_hid_host_cid = 0;
return;
}
_hidConnected = true;
_hid_host_descriptor_available = false;
_hid_host_cid = hid_subevent_connection_opened_get_hid_cid(packet);
DEBUGV("HID Host connected.\n");
break;
case HID_SUBEVENT_DESCRIPTOR_AVAILABLE:
// This event will follows HID_SUBEVENT_CONNECTION_OPENED event.
// For incoming connections, i.e. HID Device initiating the connection,
// the HID_SUBEVENT_DESCRIPTOR_AVAILABLE is delayed, and some HID
// reports may be received via HID_SUBEVENT_REPORT event. It is up to
// the application if these reports should be buffered or ignored until
// the HID descriptor is available.
status = hid_subevent_descriptor_available_get_status(packet);
if (status == ERROR_CODE_SUCCESS) {
_hid_host_descriptor_available = true;
} else {
DEBUGV("Cannot handle input report, HID Descriptor is not available, status 0x%02x\n", status);
}
break;
case HID_SUBEVENT_REPORT:
// Handle input report.
if (_hid_host_descriptor_available) {
uint16_t report_len = hid_subevent_report_get_report_len(packet);
const uint8_t *report = hid_subevent_report_get_report(packet);
// check if HID Input Report
if ((report_len < 1) || (*report != 0xa1)) {
break;
}
report++;
report_len--;;
btstack_hid_parser_t parser;
btstack_hid_parser_init(&parser, hid_descriptor_storage_get_descriptor_data(_hid_host_cid), hid_descriptor_storage_get_descriptor_len(_hid_host_cid), HID_REPORT_TYPE_INPUT, report, report_len);
hid_host_handle_interrupt_report(&parser);
}
break;
case HID_SUBEVENT_SET_PROTOCOL_RESPONSE:
// For incoming connections, the library will set the protocol mode of the
// HID Device as requested in the call to hid_host_accept_connection. The event
// reports the result. For connections initiated by calling hid_host_connect,
// this event will occur only if the established report mode is boot mode.
status = hid_subevent_set_protocol_response_get_handshake_status(packet);
if (status != HID_HANDSHAKE_PARAM_TYPE_SUCCESSFUL) {
DEBUGV("Error set protocol, status 0x%02x\n", status);
break;
}
switch ((hid_protocol_mode_t)hid_subevent_set_protocol_response_get_protocol_mode(packet)) {
case HID_PROTOCOL_MODE_BOOT:
DEBUGV("Protocol mode set: BOOT.\n");
break;
case HID_PROTOCOL_MODE_REPORT:
DEBUGV("Protocol mode set: REPORT.\n");
break;
default:
DEBUGV("Unknown protocol mode.\n");
break;
}
break;
case HID_SUBEVENT_CONNECTION_CLOSED:
// The connection was closed.
_hidConnected = false;
_hid_host_cid = 0;
_hid_host_descriptor_available = false;
DEBUGV("HID Host disconnected.\n");
break;
default:
break;
}
}
void BluetoothHIDMaster::sm_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
UNUSED(channel);
UNUSED(size);
if (packet_type != HCI_EVENT_PACKET) {
return;
}
switch (hci_event_packet_get_type(packet)) {
case SM_EVENT_JUST_WORKS_REQUEST:
DEBUGV("Just works requested\n");
sm_just_works_confirm(sm_event_just_works_request_get_handle(packet));
break;
case SM_EVENT_NUMERIC_COMPARISON_REQUEST:
DEBUGV("Confirming numeric comparison: %" PRIu32 "\n", sm_event_numeric_comparison_request_get_passkey(packet));
sm_numeric_comparison_confirm(sm_event_passkey_display_number_get_handle(packet));
break;
case SM_EVENT_PASSKEY_DISPLAY_NUMBER:
DEBUGV("Display Passkey: %" PRIu32 "\n", sm_event_passkey_display_number_get_passkey(packet));
break;
case SM_EVENT_PAIRING_COMPLETE:
switch (sm_event_pairing_complete_get_status(packet)) {
case ERROR_CODE_SUCCESS:
DEBUGV("Pairing complete, success\n");
// continue - query primary services
DEBUGV("Search for HID service.\n");
//app_state = W4_HID_CLIENT_CONNECTED;
hids_client_connect(_hci.getHCIConn(), PACKETHANDLERCB(BluetoothHIDMaster, handle_gatt_client_event), HID_PROTOCOL_MODE_REPORT, &_hid_host_cid);
break;
case ERROR_CODE_CONNECTION_TIMEOUT:
DEBUGV("Pairing failed, timeout\n");
break;
case ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION:
DEBUGV("Pairing failed, disconnected\n");
break;
case ERROR_CODE_AUTHENTICATION_FAILURE:
DEBUGV("Pairing failed, reason = %u\n", sm_event_pairing_complete_get_reason(packet));
break;
default:
break;
}
break;
default:
break;
}
}
void BluetoothHIDMaster::handle_gatt_client_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
UNUSED(packet_type);
UNUSED(channel);
UNUSED(size);
uint8_t status;
int idx;
if (hci_event_packet_get_type(packet) != HCI_EVENT_GATTSERVICE_META) {
return;
}
switch (hci_event_gattservice_meta_get_subevent_code(packet)) {
case GATTSERVICE_SUBEVENT_HID_SERVICE_CONNECTED:
status = gattservice_subevent_hid_service_connected_get_status(packet);
switch (status) {
case ERROR_CODE_SUCCESS:
DEBUGV("HID service client connected, found %d services\n", gattservice_subevent_hid_service_connected_get_num_instances(packet));
_hidConnected = true;
_hid_host_descriptor_available = true;
break;
default:
DEBUGV("HID service client connection failed, status 0x%02x.\n", status);
gap_disconnect(_hci.getHCIConn());
//handle_outgoing_connection_error();
break;
}
break;
case GATTSERVICE_SUBEVENT_HID_REPORT:
idx = gattservice_subevent_hid_report_get_service_index(packet);
btstack_hid_parser_t parser;
btstack_hid_parser_init(&parser, hids_client_descriptor_storage_get_descriptor_data(_hid_host_cid, idx), hids_client_descriptor_storage_get_descriptor_len(_hid_host_cid, idx), HID_REPORT_TYPE_INPUT, gattservice_subevent_hid_report_get_report(packet), gattservice_subevent_hid_report_get_report_len(packet));
hid_host_handle_interrupt_report(&parser);
//hid_handle_input_report(
// gattservice_subevent_hid_report_get_service_index(packet),
// gattservice_subevent_hid_report_get_report(packet),
// gattservice_subevent_hid_report_get_report_len(packet));
break;
default:
break;
}
}
// Simplified US Keyboard with Shift modifier
#define CHAR_ILLEGAL 0xff
#define CHAR_RETURN '\n'
#define CHAR_ESCAPE 27
#define CHAR_TAB '\t'
#define CHAR_BACKSPACE 0x7f
/**
English (US)
*/
static const uint8_t keytable_us_none [] = {
CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 0-3 */
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', /* 4-13 */
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', /* 14-23 */
'u', 'v', 'w', 'x', 'y', 'z', /* 24-29 */
'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', /* 30-39 */
CHAR_RETURN, CHAR_ESCAPE, CHAR_BACKSPACE, CHAR_TAB, ' ', /* 40-44 */
'-', '=', '[', ']', '\\', CHAR_ILLEGAL, ';', '\'', 0x60, ',', /* 45-54 */
'.', '/', CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 55-60 */
CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 61-64 */
CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 65-68 */
CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 69-72 */
CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 73-76 */
CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 77-80 */
CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 81-84 */
'*', '-', '+', '\n', '1', '2', '3', '4', '5', /* 85-97 */
'6', '7', '8', '9', '0', '.', 0xa7, /* 97-100 */
};
static const uint8_t keytable_us_shift[] = {
CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 0-3 */
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', /* 4-13 */
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', /* 14-23 */
'U', 'V', 'W', 'X', 'Y', 'Z', /* 24-29 */
'!', '@', '#', '$', '%', '^', '&', '*', '(', ')', /* 30-39 */
CHAR_RETURN, CHAR_ESCAPE, CHAR_BACKSPACE, CHAR_TAB, ' ', /* 40-44 */
'_', '+', '{', '}', '|', CHAR_ILLEGAL, ':', '"', 0x7E, '<', /* 45-54 */
'>', '?', CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 55-60 */
CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 61-64 */
CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 65-68 */
CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 69-72 */
CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 73-76 */
CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 77-80 */
CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 81-84 */
'*', '-', '+', '\n', '1', '2', '3', '4', '5', /* 85-97 */
'6', '7', '8', '9', '0', '.', 0xb1, /* 97-100 */
};
bool HIDKeyStream::setFIFOSize(size_t size) {
if (!size || _running) {
return false;
}
_fifoSize = size + 1; // Always 1 unused entry
return true;
}
HIDKeyStream::HIDKeyStream() {
}
HIDKeyStream::~HIDKeyStream() {
end();
}
void HIDKeyStream::begin() {
if (_running) {
end();
}
_queue = new uint8_t[_fifoSize];
_writer = 0;
_reader = 0;
_lshift = false;
_rshift = false;
_holding = false;
_running = true;
}
void HIDKeyStream::end() {
if (!_running) {
return;
}
_running = false;
delete[] _queue;
}
int HIDKeyStream::peek() {
if (!_running) {
return -1;
}
if (_writer != _reader) {
return _queue[_reader];
}
return -1;
}
int HIDKeyStream::read() {
if (!_running) {
return -1;
}
if (_writer != _reader) {
auto ret = _queue[_reader];
asm volatile("" ::: "memory"); // Ensure the value is read before advancing
auto next_reader = (_reader + 1) % _fifoSize;
asm volatile("" ::: "memory"); // Ensure the reader value is only written once, correctly
_reader = next_reader;
return ret;
}
return -1;
}
int HIDKeyStream::available() {
if (!_running) {
return 0;
}
return (_fifoSize + _writer - _reader) % _fifoSize;
}
int HIDKeyStream::availableForWrite() {
return 2 * _fifoSize - available() - 1; // Every 2 write = 1 read buffer insertion
}
void HIDKeyStream::flush() {
// We always send blocking
}
size_t HIDKeyStream::write(uint8_t c) {
if (!availableForWrite()) {
return 0;
}
if (_holding) {
_holding = false;
bool state = (bool)c;
if (_heldKey == 0xe1) {
_lshift = state;
return 1;
} else if (_heldKey == 0xe6) {
_rshift = state;
return 1;
} else if (state) {
auto ascii = (_lshift || _rshift) ? keytable_us_shift[_heldKey] : keytable_us_none[_heldKey];
if (ascii != CHAR_ILLEGAL) {
auto next_writer = _writer + 1;
if (next_writer == _fifoSize) {
next_writer = 0;
}
if (next_writer != _reader) {
_queue[_writer] = ascii;
asm volatile("" ::: "memory"); // Ensure the queue is written before the written count advances
_writer = next_writer;
}
}
return 1;
} else {
return 1;
}
} else {
if ((c < sizeof(keytable_us_shift)) || (c == 0xe1) || (c == 0xe6)) {
_holding = true;
_heldKey = c;
}
return 1;
}
}
size_t HIDKeyStream::write(const uint8_t *p, size_t len) {
if (!_running || !len) {
return 0;
}
size_t cnt = 0;
for (size_t i = 0; i < len; i++) {
if (!write(p[len])) {
return cnt;
}
cnt++;
}
return cnt;
}
HIDKeyStream::operator bool() {
return _running;
}
@@ -0,0 +1,145 @@
/*
Bluetooth HID Master class, can connect to keyboards, mice, and joysticks
Works with Bluetooth Classic and BLE devices
Copyright (c) 2024 Earle F. Philhower, III <earlephilhower@yahoo.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#pragma once
#include <_needsbt.h>
#include <Arduino.h>
#include <list>
#include <memory>
#include <BluetoothHCI.h>
#include <btstack.h>
// Write raw key up/down events, read ASCII chars out
class HIDKeyStream : public Stream {
public:
HIDKeyStream();
~HIDKeyStream();
bool setFIFOSize(size_t size);
void begin();
void end();
virtual int peek() override;
virtual int read() override;
virtual int available() override;
virtual int availableForWrite() override;
virtual void flush() override;
virtual size_t write(uint8_t c) override;
virtual size_t write(const uint8_t *p, size_t len) override;
using Print::write;
operator bool();
private:
bool _lshift = false;
bool _rshift = false;
bool _running = false;
bool _holding = false;
uint8_t _heldKey;
// Lockless, IRQ-handled circular queue
uint32_t _writer;
uint32_t _reader;
size_t _fifoSize = 32;
uint8_t *_queue;
};
class BluetoothHIDMaster {
public:
void begin(const char *bleName) {
begin(true, bleName);
}
void begin(bool ble = false, const char *bleName = nullptr);
bool connected();
void end();
bool hciRunning();
bool running();
static const uint32_t keyboard_cod = 0x2540;
static const uint32_t mouse_cod = 0x2540;
static const uint32_t joystick_cod = 0x2508;
static const uint32_t any_cod = 0;
std::vector<BTDeviceInfo> scan(uint32_t mask, int scanTimeSec = 5, bool async = false);
bool scanAsyncDone();
std::vector<BTDeviceInfo> scanAsyncResult();
bool connect(const uint8_t *addr);
bool connectKeyboard();
bool connectMouse();
bool connectJoystick();
bool connectAny();
bool connectBLE(const uint8_t *addr, int addrType);
bool connectBLE();
bool disconnect();
void clearPairing();
void onMouseMove(void (*)(void *, int, int, int), void *cbData = nullptr);
void onMouseButton(void (*)(void *, int, bool), void *cbData = nullptr);
void onKeyDown(void (*)(void *, int), void *cbData = nullptr);
void onKeyUp(void (*)(void *, int), void *cbData = nullptr);
void onConsumerKeyDown(void (*)(void *, int), void *cbData = nullptr);
void onConsumerKeyUp(void (*)(void *, int), void *cbData = nullptr);
void onJoystick(void (*)(void *, int, int, int, int, uint8_t, uint32_t), void *cbData = nullptr);
private:
bool _ble = false;
bool connectCOD(uint32_t cod);
BluetoothHCI _hci;
void hid_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
uint8_t lastMB = 0;
enum { NUM_KEYS = 6 };
uint8_t last_keys[NUM_KEYS] = { 0 };
uint16_t last_consumer_key = 0;
void hid_host_handle_interrupt_report(btstack_hid_parser_t * parser);
bool _running = false;
volatile bool _hidConnected = false;
uint16_t _hid_host_cid = 0;
bool _hid_host_descriptor_available = false;
uint8_t _hid_descriptor_storage[300];
void (*_mouseMoveCB)(void *, int, int, int) = nullptr;
void *_mouseMoveData;
void (*_mouseButtonCB)(void *, int, bool) = nullptr;
void *_mouseButtonData;
void (*_keyDownCB)(void *, int) = nullptr;
void *_keyDownData;
void (*_keyUpCB)(void *, int) = nullptr;
void *_keyUpData;
void (*_consumerKeyDownCB)(void *, int) = nullptr;
void *_consumerKeyDownData;
void (*_consumerKeyUpCB)(void *, int) = nullptr;
void *_consumerKeyUpData;
void (*_joystickCB)(void *, int, int, int, int, uint8_t, uint32_t) = nullptr;
void *_joystickData;
btstack_packet_callback_registration_t _sm_event_callback_registration;
void sm_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
void handle_gatt_client_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
};
@@ -29,7 +29,7 @@ const char *softAP_password = APPSK;
/* hostname for mDNS. Should work at least on windows. Try http://picow.local */
const char *myHostname = "picow";
/* Don't set this wifi credentials. They are configurated at runtime and stored on EEPROM */
/* Don't set this wifi credentials. They are configured at runtime and stored on EEPROM */
char ssid[33] = "";
char password[65] = "";
@@ -12,7 +12,7 @@
#include <task.h>
#include <semphr.h>
#define SERIAL_PORT Serial1
#define SERIAL_PORT Serial
#define BLINK_ON_TIME 250
#define BLINK_OFF_TIME 500
@@ -58,6 +58,7 @@ void led_ON(void *pvParameters)
digitalWrite(LED_BUILTIN, HIGH);
delay(BLINK_ON_TIME);
xSemaphoreGive( xSemaphore );
delay(1);
}
}
@@ -71,6 +72,7 @@ void led_OFF(void *pvParameters)
digitalWrite(LED_BUILTIN, LOW);
delay(BLINK_OFF_TIME);
xSemaphoreGive( xSemaphore );
delay(1);
}
}
-2
View File
@@ -19,8 +19,6 @@ setCanSendNowCB KEYWORD2
startHID KEYWORD2
connected KEYWORD2
send KEYWORD2
lockBluetooth KEYWORD2
unlockBluetooth KEYWORD2
getCID KEYWORD2
setBattery KEYWORD2
@@ -20,4 +20,80 @@
#include "PicoBluetoothBLEHID.h"
#define CCALLBACKNAME _BLEHIDCB
#include <ctocppcallback.h>
#define PACKETHANDLERCB(class, cbFcn) \
(CCALLBACKNAME<void(uint8_t, uint16_t, uint8_t*, uint16_t), __COUNTER__>::func = std::bind(&class::cbFcn, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4), \
static_cast<btstack_packet_handler_t>(CCALLBACKNAME<void(uint8_t, uint16_t, uint8_t*, uint16_t), __COUNTER__ - 1>::callback))
bool PicoBluetoothBLEHID_::startHID(const char *localName, const char *hidName, uint16_t appearance, const uint8_t *hidDescriptor, uint16_t hidDescriptorSize, int battery) {
if (_running) {
return false;
}
_running = true;
_buildAdvData(localName, appearance);
_buildAttdb(hidName);
_battery = battery;
// Setup L2CAP
l2cap_init();
// Setup SM
sm_init();
sm_set_io_capabilities(IO_CAPABILITY_NO_INPUT_NO_OUTPUT);
sm_set_authentication_requirements(SM_AUTHREQ_SECURE_CONNECTION | SM_AUTHREQ_BONDING);
// Setup ATT server
att_server_init(_attdb, NULL, NULL);
// Setup battery service
battery_service_server_init(battery);
// Setup device information service
device_information_service_server_init();
// Setup HID Device service, depending on activated reports
uint8_t numreports = 1; //start with 1 (feature report)
if (__BLEInstallKeyboard) {
numreports += 2; //add keycodes + consumer keys
}
if (__BLEInstallMouse) {
numreports += 1;
}
if (__BLEInstallJoystick) {
numreports += 1;
}
//allocate memory for hid reports
_reportStorage = (hids_device_report_t *) malloc(sizeof(hids_device_report_t) * numreports);
hids_device_init_with_storage(0, hidDescriptor, hidDescriptorSize, numreports, _reportStorage);
// Setup advertisements
uint16_t adv_int_min = 0x0030;
uint16_t adv_int_max = 0x0030;
uint8_t adv_type = 0;
bd_addr_t null_addr;
memset(null_addr, 0, 6);
gap_advertisements_set_params(adv_int_min, adv_int_max, adv_type, 0, null_addr, 0x07, 0x00);
gap_advertisements_set_data(_advDataLen, _advData);
gap_advertisements_enable(1);
// Register for HCI events
_hci_event_callback_registration.callback = PACKETHANDLERCB(PicoBluetoothBLEHID_, packetHandler);
hci_add_event_handler(&_hci_event_callback_registration);
// Register for SM events
_sm_event_callback_registration.callback = PACKETHANDLERCB(PicoBluetoothBLEHID_, packetHandler);
sm_add_event_handler(&_sm_event_callback_registration);
// Register for HIDS events
hids_device_register_packet_handler(PACKETHANDLERCB(PicoBluetoothBLEHID_, packetHandler));
// GO!
hci_power_control(HCI_POWER_ON);
return true;
}
PicoBluetoothBLEHID_ PicoBluetoothBLEHID;
@@ -79,79 +79,9 @@ public:
_onCanSendNow = cb;
}
bool startHID(const char *localName, const char *hidName, uint16_t appearance, const uint8_t *hidDescriptor, uint16_t hidDescriptorSize, int battery = 100) {
if (_running) {
return false;
}
_running = true;
_buildAdvData(localName, appearance);
_buildAttdb(hidName);
_battery = battery;
// Setup L2CAP
l2cap_init();
// Setup SM
sm_init();
sm_set_io_capabilities(IO_CAPABILITY_NO_INPUT_NO_OUTPUT);
sm_set_authentication_requirements(SM_AUTHREQ_SECURE_CONNECTION | SM_AUTHREQ_BONDING);
// Setup ATT server
att_server_init(_attdb, NULL, NULL);
// Setup battery service
battery_service_server_init(battery);
// Setup device information service
device_information_service_server_init();
// Setup HID Device service, depending on activated reports
uint8_t numreports = 1; //start with 1 (feature report)
if (__BLEInstallKeyboard) {
numreports += 2; //add keycodes + consumer keys
}
if (__BLEInstallMouse) {
numreports += 1;
}
if (__BLEInstallJoystick) {
numreports += 1;
}
//allocate memory for hid reports
_reportStorage = (hids_device_report_t *) malloc(sizeof(hids_device_report_t) * numreports);
hids_device_init_with_storage(0, hidDescriptor, hidDescriptorSize, numreports, _reportStorage);
// Setup advertisements
uint16_t adv_int_min = 0x0030;
uint16_t adv_int_max = 0x0030;
uint8_t adv_type = 0;
bd_addr_t null_addr;
memset(null_addr, 0, 6);
gap_advertisements_set_params(adv_int_min, adv_int_max, adv_type, 0, null_addr, 0x07, 0x00);
gap_advertisements_set_data(_advDataLen, _advData);
gap_advertisements_enable(1);
// Register for HCI events
_hci_event_callback_registration.callback = PacketHandlerWrapper;
hci_add_event_handler(&_hci_event_callback_registration);
// Register for SM events
_sm_event_callback_registration.callback = PacketHandlerWrapper;
sm_add_event_handler(&_sm_event_callback_registration);
// Register for HIDS events
hids_device_register_packet_handler(PacketHandlerWrapper);
// GO!
hci_power_control(HCI_POWER_ON);
return true;
}
static void PacketHandlerWrapper(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t packet_size) {
PicoBluetoothBLEHID.packetHandler(packet_type, channel, packet, packet_size);
}
bool startHID(const char *localName, const char *hidName, uint16_t appearance, const uint8_t *hidDescriptor, uint16_t hidDescriptorSize, int battery = 100);
private:
void packetHandler(uint8_t type, uint16_t channel, uint8_t *packet, uint16_t size) {
uint8_t result;
uint8_t reportID;
@@ -214,14 +144,6 @@ public:
if (result) {
Serial.printf("Error sending %d - report ID: %d\n", result, reportID);
}
//else Serial.printf("Sent report for ID: %d\n",reportID);
#if 0
Serial.printf("Sending report for ID %d, len: %d:\n", reportID, _sendReportLen);
for (uint8_t i = 0; i < _sendReportLen; i++) {
Serial.printf("0x%02X - ", ((const uint8_t *)_sendReport)[i]);
}
Serial.println("");
#endif
break;
default:
break;
@@ -237,7 +159,7 @@ public:
break;
}
}
public:
bool end() {
if (_running) {
hci_power_control(HCI_POWER_OFF);
@@ -259,9 +181,9 @@ public:
_needToSend = true;
_sendReport = rpt;
_sendReportLen = len;
lockBluetooth();
__lockBluetooth();
hids_device_request_can_send_now_event(_con_handle);
unlockBluetooth();
__unlockBluetooth();
while (connected() && _needToSend) {
/* noop busy wait */
}
@@ -276,14 +198,6 @@ public:
return true;
}
static void lockBluetooth() {
async_context_acquire_lock_blocking(cyw43_arch_async_context());
}
static void unlockBluetooth() {
async_context_release_lock(cyw43_arch_async_context());
}
uint8_t *_attdb = nullptr;
int _attdbLen = 0;
@@ -20,4 +20,81 @@
#include "PicoBluetoothHID.h"
#define CCALLBACKNAME _BTHIDCB
#include <ctocppcallback.h>
#define PACKETHANDLERCB(class, cbFcn) \
(CCALLBACKNAME<void(uint8_t, uint16_t, uint8_t*, uint16_t), __COUNTER__>::func = std::bind(&class::cbFcn, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4), \
static_cast<btstack_packet_handler_t>(CCALLBACKNAME<void(uint8_t, uint16_t, uint8_t*, uint16_t), __COUNTER__ - 1>::callback))
bool PicoBluetoothHID_::startHID(const char *localName, const char *hidName, uint16_t hidClass, uint8_t hidSubclass, const uint8_t *hidDescriptor, uint16_t hidDescriptorSize) {
if (_running) {
return false;
}
_running = true;
// Allow finding via inquiry
gap_discoverable_control(1);
// Use Limited Discoverable Mode; Peripheral; Keyboard as CoD
gap_set_class_of_device(hidClass);
// Set local name to be identified - zeroes will be replaced by actual BD ADDR
gap_set_local_name(localName);
// Allow for role switch in general and sniff mode
gap_set_default_link_policy_settings(LM_LINK_POLICY_ENABLE_ROLE_SWITCH | LM_LINK_POLICY_ENABLE_SNIFF_MODE);
// Allow for role switch on outgoing connections - this allow HID Host to become master when we re-connect to it
gap_set_allow_role_switch(true);
// L2CAP
l2cap_init();
#ifdef ENABLE_BLE
// Initialize LE Security Manager. Needed for cross-transport key derivation
sm_init();
#endif
// SDP Server
sdp_init();
bzero(_hid_service_buffer, sizeof(_hid_service_buffer));
const uint8_t hid_boot_device = 0;
const uint8_t hid_virtual_cable = 0;
const uint8_t hid_remote_wake = 1;
const uint8_t hid_reconnect_initiate = 1;
const uint8_t hid_normally_connectable = 1;
// When not set to 0xffff, sniff and sniff subrating are enabled
const uint16_t host_max_latency = 1600;
const uint16_t host_min_timeout = 3200;
hid_sdp_record_t hid_params = {
hidClass, hidSubclass,
hid_virtual_cable, hid_remote_wake,
hid_reconnect_initiate, (bool)hid_normally_connectable,
(bool)hid_boot_device,
host_max_latency, host_min_timeout,
3200,
hidDescriptor,
hidDescriptorSize,
hidName
};
hid_create_sdp_record(_hid_service_buffer, 0x10001, &hid_params);
sdp_register_service(_hid_service_buffer);
// See https://www.bluetooth.com/specifications/assigned-numbers/company-identifiers if you don't have a USB Vendor ID and need a Bluetooth Vendor ID
// device info: BlueKitchen GmbH, product 1, version 1
device_id_create_sdp_record(_device_id_sdp_service_buffer, 0x10003, DEVICE_ID_VENDOR_ID_SOURCE_BLUETOOTH, BLUETOOTH_COMPANY_ID_BLUEKITCHEN_GMBH, 1, 1);
sdp_register_service(_device_id_sdp_service_buffer);
// HID Device
hid_device_init(hid_boot_device, hidDescriptorSize, hidDescriptor);
// register for HCI events
_hci_event_callback_registration.callback = PACKETHANDLERCB(PicoBluetoothHID_, packetHandler);
hci_add_event_handler(&_hci_event_callback_registration);
// register for HID events
hid_device_register_packet_handler(PACKETHANDLERCB(PicoBluetoothHID_, packetHandler));
hci_power_control(HCI_POWER_ON);
return true;
}
PicoBluetoothHID_ PicoBluetoothHID;
+5 -84
View File
@@ -68,80 +68,9 @@ public:
_onCanSendNow = cb;
}
bool startHID(const char *localName, const char *hidName, uint16_t hidClass, uint8_t hidSubclass, const uint8_t *hidDescriptor, uint16_t hidDescriptorSize) {
if (_running) {
return false;
}
_running = true;
// Allow finding via inquiry
gap_discoverable_control(1);
// Use Limited Discoverable Mode; Peripheral; Keyboard as CoD
gap_set_class_of_device(hidClass);
// Set local name to be identified - zeroes will be replaced by actual BD ADDR
gap_set_local_name(localName);
// Allow for role switch in general and sniff mode
gap_set_default_link_policy_settings(LM_LINK_POLICY_ENABLE_ROLE_SWITCH | LM_LINK_POLICY_ENABLE_SNIFF_MODE);
// Allow for role switch on outgoing connections - this allow HID Host to become master when we re-connect to it
gap_set_allow_role_switch(true);
// L2CAP
l2cap_init();
#ifdef ENABLE_BLE
// Initialize LE Security Manager. Needed for cross-transport key derivation
sm_init();
#endif
// SDP Server
sdp_init();
bzero(_hid_service_buffer, sizeof(_hid_service_buffer));
const uint8_t hid_boot_device = 0;
const uint8_t hid_virtual_cable = 0;
const uint8_t hid_remote_wake = 1;
const uint8_t hid_reconnect_initiate = 1;
const uint8_t hid_normally_connectable = 1;
// When not set to 0xffff, sniff and sniff subrating are enabled
const uint16_t host_max_latency = 1600;
const uint16_t host_min_timeout = 3200;
hid_sdp_record_t hid_params = {
hidClass, hidSubclass,
hid_virtual_cable, hid_remote_wake,
hid_reconnect_initiate, (bool)hid_normally_connectable,
(bool)hid_boot_device,
host_max_latency, host_min_timeout,
3200,
hidDescriptor,
hidDescriptorSize,
hidName
};
hid_create_sdp_record(_hid_service_buffer, 0x10001, &hid_params);
sdp_register_service(_hid_service_buffer);
// See https://www.bluetooth.com/specifications/assigned-numbers/company-identifiers if you don't have a USB Vendor ID and need a Bluetooth Vendor ID
// device info: BlueKitchen GmbH, product 1, version 1
device_id_create_sdp_record(_device_id_sdp_service_buffer, 0x10003, DEVICE_ID_VENDOR_ID_SOURCE_BLUETOOTH, BLUETOOTH_COMPANY_ID_BLUEKITCHEN_GMBH, 1, 1);
sdp_register_service(_device_id_sdp_service_buffer);
// HID Device
hid_device_init(hid_boot_device, hidDescriptorSize, hidDescriptor);
// register for HCI events
_hci_event_callback_registration.callback = PacketHandlerWrapper;
hci_add_event_handler(&_hci_event_callback_registration);
// register for HID events
hid_device_register_packet_handler(PacketHandlerWrapper);
hci_power_control(HCI_POWER_ON);
return true;
}
static void PacketHandlerWrapper(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t packet_size) {
PicoBluetoothHID.packetHandler(packet_type, channel, packet, packet_size);
}
bool startHID(const char *localName, const char *hidName, uint16_t hidClass, uint8_t hidSubclass, const uint8_t *hidDescriptor, uint16_t hidDescriptorSize);
private:
void packetHandler(uint8_t type, uint16_t channel, uint8_t *packet, uint16_t size) {
uint8_t status;
if (type != HCI_EVENT_PACKET) {
@@ -198,7 +127,7 @@ public:
}
}
}
public:
bool end() {
if (_running) {
hci_power_control(HCI_POWER_OFF);
@@ -217,23 +146,15 @@ public:
_sendReportID = id;
_sendReport = rpt;
_sendReportLen = len;
lockBluetooth();
__lockBluetooth();
hid_device_request_can_send_now_event(getCID());
unlockBluetooth();
__unlockBluetooth();
while (connected() && _needToSend) {
/* noop busy wait */
}
return connected();
}
static void lockBluetooth() {
async_context_acquire_lock_blocking(cyw43_arch_async_context());
}
static void unlockBluetooth() {
async_context_release_lock(cyw43_arch_async_context());
}
uint16_t getCID() {
return _hid_cid;
}
+209 -10
View File
@@ -24,10 +24,12 @@
*/
#include <Arduino.h>
#include "HTTPClient.h"
#include <WiFi.h>
#include <time.h>
#include "base64.h"
extern "C" char *strptime(const char *__restrict, const char *__restrict, struct tm *__restrict); // Not exposed by headers?
// per https://github.com/esp8266/Arduino/issues/8231
// make sure HTTPClient can be utilized as a movable class member
@@ -205,6 +207,7 @@ bool HTTPClient::begin(WiFiClient &client, const String& url) {
}
_port = (protocol == "https" ? 443 : 80);
_secure = (protocol == "https");
_clientIn = client.clone();
_clientGiven = true;
if (_clientMade) {
@@ -246,6 +249,7 @@ bool HTTPClient::begin(WiFiClient &client, const String& host, uint16_t port, co
_port = port;
_uri = uri;
_protocol = (https ? "https" : "http");
_secure = https;
return true;
}
@@ -590,6 +594,12 @@ int HTTPClient::sendRequest(const char * type, const uint8_t * payload, size_t s
addHeader(F("Content-Length"), String(payload && size > 0 ? size : 0));
// add cookies to header, if present
String cookie_string;
if (generateCookieString(&cookie_string)) {
addHeader("Cookie", cookie_string);
}
// send Header
if (!sendHeader(type)) {
return returnError(HTTPC_ERROR_SEND_HEADER_FAILED);
@@ -691,6 +701,12 @@ int HTTPClient::sendRequest(const char * type, Stream * stream, size_t size) {
addHeader(F("Content-Length"), String(size));
}
// add cookies to header, if present
String cookie_string;
if (generateCookieString(&cookie_string)) {
addHeader("Cookie", cookie_string);
}
// send Header
if (!sendHeader(type)) {
return returnError(HTTPC_ERROR_SEND_HEADER_FAILED);
@@ -955,7 +971,7 @@ void HTTPClient::collectHeaders(const char* headerKeys[], const size_t headerKey
String HTTPClient::header(const char* name) {
for (size_t i = 0; i < _headerKeysCount; ++i) {
if (_currentHeaders[i].key == name) {
if (_currentHeaders[i].key.equalsIgnoreCase(name)) {
return _currentHeaders[i].value;
}
}
@@ -982,7 +998,7 @@ int HTTPClient::headers() {
bool HTTPClient::hasHeader(const char* name) {
for (size_t i = 0; i < _headerKeysCount; ++i) {
if ((_currentHeaders[i].key == name) && (_currentHeaders[i].value.length() > 0)) {
if ((_currentHeaders[i].key.equalsIgnoreCase(name)) && (_currentHeaders[i].value.length() > 0)) {
return true;
}
}
@@ -1100,6 +1116,7 @@ int HTTPClient::handleHeaderResponse() {
_transferEncoding = HTTPC_TE_IDENTITY;
unsigned long lastDataTime = millis();
String date;
while (connected()) {
size_t len = _client()->available();
@@ -1127,6 +1144,10 @@ int HTTPClient::handleHeaderResponse() {
_size = headerValue.toInt();
}
if (headerName.equalsIgnoreCase("Date")) {
date = headerValue;
}
if (_canReuse && headerName.equalsIgnoreCase(F("Connection"))) {
if (headerValue.indexOf(F("close")) >= 0 &&
headerValue.indexOf(F("keep-alive")) < 0) {
@@ -1142,15 +1163,20 @@ int HTTPClient::handleHeaderResponse() {
_location = headerValue;
}
if (headerName.equalsIgnoreCase("Set-Cookie")) {
setCookie(date, headerValue);
}
for (size_t i = 0; i < _headerKeysCount; i++) {
if (_currentHeaders[i].key.equalsIgnoreCase(headerName)) {
if (_currentHeaders[i].value != "") {
// Existing value, append this one with a comma
_currentHeaders[i].value += ',';
_currentHeaders[i].value += headerValue;
} else {
_currentHeaders[i].value = headerValue;
}
// Uncomment the following lines if you need to add support for multiple headers with the same key:
// if (!_currentHeaders[i].value.isEmpty()) {
// // Existing value, append this one with a comma
// _currentHeaders[i].value += ',';
// _currentHeaders[i].value += headerValue;
// } else {
_currentHeaders[i].value = headerValue;
// }
break; // We found a match, stop looking
}
}
@@ -1210,3 +1236,176 @@ int HTTPClient::returnError(int error) {
}
return error;
}
void HTTPClient::setCookieJar(CookieJar* cookieJar) {
_cookieJar = cookieJar;
}
void HTTPClient::resetCookieJar() {
_cookieJar = nullptr;
}
void HTTPClient::clearAllCookies() {
if (_cookieJar) {
_cookieJar->clear();
}
}
void HTTPClient::setCookie(String date, String headerValue) {
if (!_cookieJar) {
return;
}
#define HTTP_TIME_PATTERN "%a, %d %b %Y %H:%M:%S"
Cookie cookie;
String value;
int pos1, pos2;
struct tm tm;
strptime(date.c_str(), HTTP_TIME_PATTERN, &tm);
cookie.date = mktime(&tm);
pos1 = headerValue.indexOf('=');
pos2 = headerValue.indexOf(';');
if (pos1 >= 0 && pos2 > pos1) {
cookie.name = headerValue.substring(0, pos1);
cookie.value = headerValue.substring(pos1 + 1, pos2);
} else {
return; // invalid cookie header
}
// only Cookie Attributes are case insensitive from this point on
headerValue.toLowerCase();
// expires
if (headerValue.indexOf("expires=") >= 0) {
pos1 = headerValue.indexOf("expires=") + strlen("expires=");
pos2 = headerValue.indexOf(';', pos1);
if (pos2 > pos1) {
value = headerValue.substring(pos1, pos2);
} else {
value = headerValue.substring(pos1);
}
strptime(value.c_str(), HTTP_TIME_PATTERN, &tm);
cookie.expires.date = mktime(&tm);
cookie.expires.valid = true;
}
// max-age
if (headerValue.indexOf("max-age=") >= 0) {
pos1 = headerValue.indexOf("max-age=") + strlen("max-age=");
pos2 = headerValue.indexOf(';', pos1);
if (pos2 > pos1) {
value = headerValue.substring(pos1, pos2);
} else {
value = headerValue.substring(pos1);
}
cookie.max_age.duration = value.toInt();
cookie.max_age.valid = true;
}
// domain
if (headerValue.indexOf("domain=") >= 0) {
pos1 = headerValue.indexOf("domain=") + strlen("domain=");
pos2 = headerValue.indexOf(';', pos1);
if (pos2 > pos1) {
value = headerValue.substring(pos1, pos2);
} else {
value = headerValue.substring(pos1);
}
if (value.startsWith(".")) {
value.remove(0, 1);
}
if (_host.indexOf(value) >= 0) {
cookie.domain = value;
} else {
return; // server tries to set a cookie on a different domain; ignore it
}
} else {
pos1 = _host.lastIndexOf('.', _host.lastIndexOf('.') - 1);
if (pos1 >= 0) {
cookie.domain = _host.substring(pos1 + 1);
} else {
cookie.domain = _host;
}
}
// path
if (headerValue.indexOf("path=") >= 0) {
pos1 = headerValue.indexOf("path=") + strlen("path=");
pos2 = headerValue.indexOf(';', pos1);
if (pos2 > pos1) {
cookie.path = headerValue.substring(pos1, pos2);
} else {
cookie.path = headerValue.substring(pos1);
}
}
// HttpOnly
cookie.http_only = (headerValue.indexOf("httponly") >= 0);
// secure
cookie.secure = (headerValue.indexOf("secure") >= 0);
// overwrite or delete cookie in/from cookie jar
time_t now_local = time(NULL);
time_t now_gmt = mktime(gmtime(&now_local));
bool found = false;
for (auto c = _cookieJar->begin(); c != _cookieJar->end(); ++c) {
if (c->domain == cookie.domain && c->name == cookie.name) {
// when evaluating, max-age takes precedence over expires if both are defined
if ((cookie.max_age.valid && ((cookie.date + cookie.max_age.duration) < now_gmt || (cookie.max_age.duration <= 0)))
|| (!cookie.max_age.valid && cookie.expires.valid && (cookie.expires.date < now_gmt))) {
_cookieJar->erase(c);
c--;
} else {
*c = cookie;
}
found = true;
}
}
// add cookie to jar
if (!found && !(cookie.max_age.valid && cookie.max_age.duration <= 0)) {
_cookieJar->push_back(cookie);
}
}
bool HTTPClient::generateCookieString(String *cookieString) {
if (!_cookieJar) {
return false;
}
time_t now_local = time(NULL);
time_t now_gmt = mktime(gmtime(&now_local));
*cookieString = "";
bool found = false;
for (auto c = _cookieJar->begin(); c != _cookieJar->end(); ++c) {
if ((c->max_age.valid && ((c->date + c->max_age.duration) < now_gmt)) || (!c->max_age.valid && c->expires.valid && (c->expires.date < now_gmt))) {
_cookieJar->erase(c);
c--;
} else if (_host.indexOf(c->domain) >= 0 && (!c->secure || _secure)) {
if (*cookieString == "") {
*cookieString = c->name + "=" + c->value;
} else {
*cookieString += " ;" + c->name + "=" + c->value;
}
found = true;
}
}
return found;
}
+35 -2
View File
@@ -33,6 +33,7 @@
#include <WiFiClientSecure.h>
#include <memory>
#include <vector>
#ifdef DEBUG_ESP_HTTP_CLIENT
#ifdef DEBUG_ESP_PORT
@@ -153,6 +154,28 @@ typedef enum {
class TransportTraits;
typedef std::unique_ptr<TransportTraits> TransportTraitsPtr;
// cookie jar support
typedef struct {
String host; // host which tries to set the cookie
time_t date; // timestamp of the response that set the cookie
String name;
String value;
String domain;
String path = "";
struct {
time_t date = 0;
bool valid = false;
} expires;
struct {
time_t duration = 0;
bool valid = false;
} max_age;
bool http_only = false;
bool secure = false;
} Cookie;
typedef std::vector<Cookie> CookieJar;
class HTTPClient {
public:
HTTPClient() = default;
@@ -229,6 +252,11 @@ public:
const String& getString(void);
static String errorToString(int error);
// Cookie jar support
void setCookieJar(CookieJar* cookieJar);
void resetCookieJar();
void clearAllCookies();
// ----------------------------------------------------------------------------------------------
// HTTPS support, mirrors the WiFiClientSecure interface
// Could possibly use a virtual interface class between the two, but for now it is more
@@ -327,6 +355,10 @@ protected:
int handleHeaderResponse();
int writeToStreamDataBlock(Stream * stream, int len);
// Cookie jar support
void setCookie(String date, String headerValue);
bool generateCookieString(String *cookieString);
WiFiClient *_clientMade = nullptr;
bool _clientTLS = false;
@@ -350,6 +382,7 @@ protected:
String _uri;
String _protocol;
bool _secure = false;
String _headers;
String _base64Authorization;
@@ -368,6 +401,6 @@ protected:
String _location;
transferEncoding_t _transferEncoding = HTTPC_TE_IDENTITY;
std::unique_ptr<StreamString> _payload;
// Cookie jar support
CookieJar *_cookieJar = nullptr;
};
+1 -1
View File
@@ -1336,7 +1336,7 @@ bool MDNSResponder::_writeMDNSHostDomain(const char* p_pcHostname, bool p_bPrepe
A very simple form of name compression is applied here: see '_writeMDNSHostDomain'
The cache differentiates of course between service domains which includes
the instance name (p_bIncludeName is set) and thoose who don't.
the instance name (p_bIncludeName is set) and those who don't.
*/
bool
+1 -1
View File
@@ -29,7 +29,7 @@
#include <FS.h>
#include <FSImpl.h>
#define LFS_NAME_MAX 32
#define LFS_NAME_MAX 255
#include "../lib/littlefs/lfs.h"
using namespace fs;
+1 -1
View File
@@ -2,7 +2,7 @@
// Just have a stub here that redirects to the actual source file
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#define LFS_NAME_MAX 32
#define LFS_NAME_MAX 255
#define LFS_NO_DEBUG
#define LFS_NO_WARN
#define LFS_NO_ERROR
+1 -1
View File
@@ -1,4 +1,4 @@
#define LFS_NAME_MAX 32
#define LFS_NAME_MAX 255
#define LFS_NO_DEBUG
#define LFS_NO_WARN
#define LFS_NO_ERROR
@@ -0,0 +1,37 @@
// Modified from the ESP32-NetBIOS example
#include <WiFi.h>
#include <NetBIOS.h>
#ifndef STASSID
#define STASSID "your-ssid"
#define STAPSK "your-password"
#endif
const char* ssid = STASSID;
const char* password = STAPSK;
void setup() {
Serial.begin(115200);
// Connect to WiFi network
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
// Windows (and other OSes using WINS/NetBIOS resolution should now be able to find the device by name)
NBNS.begin("PicoW");
}
void loop() {}
+25
View File
@@ -0,0 +1,25 @@
#######################################
# Syntax Coloring Map For ESPNBNS
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
NetBIOS KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
begin KEYWORD2
#######################################
# Instances (KEYWORD2)
#######################################
NBNS KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################
+9
View File
@@ -0,0 +1,9 @@
name=NetBIOS
version=2.0.0
author=Pablo@xpablo.cz
maintainer=Earle F. Philhower, III <earlephilhower@yahoo.com>
sentence=Enables NBNS (NetBIOS) name resolution.
paragraph=With this library you can connect to your ESP from Windows using a short name
category=Communication
url=http://www.xpablo.cz/?p=751#more-751
architectures=rp2040
+141
View File
@@ -0,0 +1,141 @@
#include "NetBIOS.h"
#include <functional>
#include <lwip/netif.h>
#define NBNS_PORT 137
#define NBNS_MAX_HOSTNAME_LEN 32
typedef struct {
uint16_t id;
uint8_t flags1;
uint8_t flags2;
uint16_t qcount;
uint16_t acount;
uint16_t nscount;
uint16_t adcount;
uint8_t name_len;
char name[NBNS_MAX_HOSTNAME_LEN + 1];
uint16_t type;
uint16_t clas;
} __attribute__((packed)) nbns_question_t;
typedef struct {
uint16_t id;
uint8_t flags1;
uint8_t flags2;
uint16_t qcount;
uint16_t acount;
uint16_t nscount;
uint16_t adcount;
uint8_t name_len;
char name[NBNS_MAX_HOSTNAME_LEN + 1];
uint16_t type;
uint16_t clas;
uint32_t ttl;
uint16_t data_len;
uint16_t flags;
uint32_t addr;
} __attribute__((packed)) nbns_answer_t;
static void _getnbname(const char *nbname, char *name, uint8_t maxlen) {
uint8_t b;
uint8_t c = 0;
while ((*nbname) && (c < maxlen)) {
b = (*nbname++ - 'A') << 4;
c++;
if (*nbname) {
b |= *nbname++ - 'A';
c++;
}
if (!b || b == ' ') {
break;
}
*name++ = b;
}
*name = 0;
}
static void append_16(void *dst, uint16_t value) {
uint8_t *d = (uint8_t *)dst;
*d++ = (value >> 8) & 0xFF;
*d++ = value & 0xFF;
}
static void append_32(void *dst, uint32_t value) {
uint8_t *d = (uint8_t *)dst;
*d++ = (value >> 24) & 0xFF;
*d++ = (value >> 16) & 0xFF;
*d++ = (value >> 8) & 0xFF;
*d++ = value & 0xFF;
}
void NetBIOS::_onPacket(AsyncUDPPacket &packet) {
if (packet.length() >= sizeof(nbns_question_t)) {
nbns_question_t *question = (nbns_question_t *)packet.data();
if (0 == (question->flags1 & 0x80)) {
char name[NBNS_MAX_HOSTNAME_LEN + 1];
_getnbname(&question->name[0], (char *)&name, question->name_len);
if (_name.equals(name)) {
nbns_answer_t nbnsa;
nbnsa.id = question->id;
nbnsa.flags1 = 0x85;
nbnsa.flags2 = 0;
append_16((void *)&nbnsa.qcount, 0);
append_16((void *)&nbnsa.acount, 1);
append_16((void *)&nbnsa.nscount, 0);
append_16((void *)&nbnsa.adcount, 0);
nbnsa.name_len = question->name_len;
memcpy(&nbnsa.name[0], &question->name[0], question->name_len + 1);
append_16((void *)&nbnsa.type, 0x20);
append_16((void *)&nbnsa.clas, 1);
append_32((void *)&nbnsa.ttl, 300000);
append_16((void *)&nbnsa.data_len, 6);
append_16((void *)&nbnsa.flags, 0);
nbnsa.addr = packet.localIP(); // Wrong, but better than nothing
// Iterate over all netifs, see if the incoming address matches one of the netmaskes networks
// TODO - is there an easier way of seeing whicn netif produced a packet?
for (auto netif = netif_list; netif; netif = netif->next) {
auto maskedip = ip4_addr_get_u32(netif_ip4_addr(netif)) & ip4_addr_get_u32(netif_ip4_netmask(netif));
auto maskedin = ((uint32_t)packet.localIP()) & ip4_addr_get_u32(netif_ip4_netmask(netif));
if (maskedip == maskedin) {
nbnsa.addr = ip4_addr_get_u32(netif_ip4_addr(netif));
break;
}
}
_udp.writeTo((uint8_t *)&nbnsa, sizeof(nbnsa), packet.remoteIP(), NBNS_PORT);
}
}
}
}
NetBIOS::NetBIOS() {}
NetBIOS::~NetBIOS() {
end();
}
bool NetBIOS::begin(const char *name) {
_name = name;
_name.toUpperCase();
if (_udp.connected()) {
return true;
}
_udp.onPacket(
[](void *arg, AsyncUDPPacket & packet) {
((NetBIOS *)(arg))->_onPacket(packet);
},
this
);
return _udp.listen(NBNS_PORT);
}
void NetBIOS::end() {
if (_udp.connected()) {
_udp.close();
}
}
NetBIOS NBNS;
+21
View File
@@ -0,0 +1,21 @@
//
#pragma once
#include <Arduino.h>
#include <AsyncUDP.h>
class NetBIOS {
protected:
AsyncUDP _udp;
String _name;
void _onPacket(AsyncUDPPacket &packet);
public:
NetBIOS();
~NetBIOS();
bool begin(const char *name);
void end();
};
extern NetBIOS NBNS;
+3 -3
View File
@@ -242,8 +242,8 @@ size_t PWMAudio::write(const uint8_t *buffer, size_t size) {
return writtenSize;
} else {
p++;
size -= 4;
writtenSize += 4;
size -= 2;
writtenSize += 2;
}
}
return writtenSize;
@@ -288,4 +288,4 @@ void PWMAudio::find_pacer_fraction(int target, uint16_t *numerator, uint16_t *de
last_target = target;
*numerator = bestNum;
*denominator = bestDenom;
}
}
+3 -2
View File
@@ -43,8 +43,9 @@ public:
void end(bool endSPI = true) {
SDFS.end();
if (endSPI) {
if (endSPI && _spi) {
_spi->end();
_spi = nullptr;
}
}
@@ -205,7 +206,7 @@ private:
return time(nullptr);
}
HardwareSPI *_spi;
HardwareSPI *_spi = nullptr;
};
@@ -0,0 +1,93 @@
// Shows how to use SPISlave on a single device in asynchronous mode
// Core0 runs as an SPI master and initiates a transmission to the slave
// Core1 runs the SPI Slave mode and provides a unique reply to messages from the master
//
// Released to the public domain 2024 by Earle F. Philhower, III <earlephilhower@yahoo.com>
#include <SPI.h>
#include <SPISlave.h>
// Wiring:
// Master RX GP0 <-> GP11 Slave TX
// Master CS GP1 <-> GP9 Slave CS
// Master CK GP2 <-> GP10 Slave CK
// Master TX GP3 <-> GP8 Slave RX
SPISettings spisettings(1000000, MSBFIRST, SPI_MODE0);
// Core 0 will be SPI master
void setup() {
SPI.setRX(0);
SPI.setCS(1);
SPI.setSCK(2);
SPI.setTX(3);
SPI.begin(true);
delay(5000);
}
int transmits = 0;
void loop() {
char msg[42];
int loops = 0;
memset(msg, 0, sizeof(msg));
sprintf(msg, "What's up? This is transmission %d", transmits);
Serial.printf("\n\nM-SEND: '%s'\n", msg);
SPI.beginTransaction(spisettings);
SPI.transferAsync(msg, msg, sizeof(msg));
while (!SPI.finishedAsync()) {
loops++;
}
SPI.endTransaction();
Serial.printf("M-RECV: '%s', idle loops %d\n", msg, loops);
transmits++;
delay(5000);
}
// Core 1 will be SPI slave
volatile bool recvBuffReady = false;
char recvBuff[42] = "";
int recvIdx = 0;
void recvCallback(uint8_t *data, size_t len) {
memcpy(recvBuff + recvIdx, data, len);
recvIdx += len;
if (recvIdx == sizeof(recvBuff)) {
recvBuffReady = true;
recvIdx = 0;
}
}
int sendcbs = 0;
// Note that the buffer needs to be long lived, the SPISlave doesn't copy it. So no local stack variables, only globals or heap(malloc/new) allocations.
char sendBuff[42];
void sentCallback() {
memset(sendBuff, 0, sizeof(sendBuff));
sprintf(sendBuff, "Slave to Master Xmission %d", sendcbs++);
SPISlave1.setData((uint8_t*)sendBuff, sizeof(sendBuff));
}
// Note that we use SPISlave1 here **not** because we're running on
// Core 1, but because SPI0 is being used already. You can use
// SPISlave or SPISlave1 on any core.
void setup1() {
SPISlave1.setRX(8);
SPISlave1.setCS(9);
SPISlave1.setSCK(10);
SPISlave1.setTX(11);
// Ensure we start with something to send...
sentCallback();
// Hook our callbacks into the slave
SPISlave1.onDataRecv(recvCallback);
SPISlave1.onDataSent(sentCallback);
SPISlave1.begin(spisettings);
delay(3000);
Serial.println("S-INFO: SPISlave started");
}
void loop1() {
if (recvBuffReady) {
Serial.printf("S-RECV: '%s'\n", recvBuff);
recvBuffReady = false;
}
}
+3
View File
@@ -26,6 +26,9 @@ setRX KEYWORD2
setTX KEYWORD2
setSCK KEYWORD2
setCS KEYWORD2
transferAsync KEYWORD2
finishedAsync KEYWORD2
abortAsync KEYWORD2
#######################################
# Constants (LITERAL1)
+99 -1
View File
@@ -19,6 +19,7 @@
*/
#include "SPI.h"
#include <hardware/dma.h>
#include <hardware/spi.h>
#include <hardware/gpio.h>
#include <hardware/structs/iobank0.h>
@@ -218,7 +219,7 @@ void SPIClassRP2040::beginTransaction(SPISettings settings) {
void SPIClassRP2040::endTransaction(void) {
noInterrupts(); // Avoid race condition so the GPIO IRQs won't come back until all state is restored
DEBUGSPI("SPI::endTransaction()\n");
// Re-enablke IRQs
// Re-enable IRQs
for (auto entry : _usingIRQs) {
int gpio = entry.first;
int mode = entry.second;
@@ -230,6 +231,103 @@ void SPIClassRP2040::endTransaction(void) {
interrupts();
}
bool SPIClassRP2040::transferAsync(const void *send, void *recv, size_t bytes) {
DEBUGSPI("SPI::transferAsync(%p, %p, %d)\n", send, recv, bytes);
const uint8_t *txbuff = reinterpret_cast<const uint8_t *>(send);
uint8_t *rxbuff = reinterpret_cast<uint8_t *>(recv);
_dummy = 0xffffffff;
if (!_initted || (!send && !recv)) {
return false;
}
_channelDMA = dma_claim_unused_channel(false);
if (_channelDMA == -1) {
return false;
}
_channelSendDMA = dma_claim_unused_channel(false);
if (_channelSendDMA == -1) {
dma_channel_unclaim(_channelDMA);
return false;
}
if (send && (_spis.getBitOrder() != MSBFIRST)) {
_dmaBuffer = (uint8_t *)malloc(bytes);
if (!_dmaBuffer) {
dma_channel_unclaim(_channelDMA);
dma_channel_unclaim(_channelSendDMA);
return false;
}
for (size_t i = 0; i < bytes; i++) {
_dmaBuffer[i] = reverseByte(txbuff[i]);
}
}
_dmaBytes = bytes;
_rxFinalBuffer = rxbuff;
hw_write_masked(&spi_get_hw(_spi)->cr0, (8 - 1) << SPI_SSPCR0_DSS_LSB, SPI_SSPCR0_DSS_BITS); // Fast set to 8-bits
dma_channel_config c = dma_channel_get_default_config(_channelSendDMA);
channel_config_set_transfer_data_size(&c, DMA_SIZE_8); // 8b transfers into SPI FIFO
channel_config_set_read_increment(&c, send ? true : false); // Reading incrementing addresses
channel_config_set_write_increment(&c, false); // Writing to the same FIFO address
channel_config_set_dreq(&c, spi_get_dreq(_spi, true)); // Wait for the TX FIFO specified
channel_config_set_chain_to(&c, _channelSendDMA); // No chaining
channel_config_set_irq_quiet(&c, true); // No need for IRQ
dma_channel_configure(_channelSendDMA, &c, &spi_get_hw(_spi)->dr, !send ? (uint8_t *)&_dummy : (_spis.getBitOrder() != MSBFIRST ? _dmaBuffer : txbuff), bytes, false);
c = dma_channel_get_default_config(_channelDMA);
channel_config_set_transfer_data_size(&c, DMA_SIZE_8); // 8b transfers into SPI FIFO
channel_config_set_read_increment(&c, false); // Reading same FIFO address
channel_config_set_write_increment(&c, recv ? true : false); // Writing to the buffer
channel_config_set_dreq(&c, spi_get_dreq(_spi, false)); // Wait for the RX FIFO specified
channel_config_set_chain_to(&c, _channelDMA); // No chaining
channel_config_set_irq_quiet(&c, true); // No need for IRQ
dma_channel_configure(_channelDMA, &c, !recv ? (uint8_t *)&_dummy : rxbuff, &spi_get_hw(_spi)->dr, bytes, false);
spi_get_hw(_spi)->dmacr = 1 | (1 << 1); // TDMAE | RDMAE
dma_channel_start(_channelDMA);
dma_channel_start(_channelSendDMA);
return true;
}
bool SPIClassRP2040::finishedAsync() {
if (!_initted) {
return true;
}
if (dma_channel_is_busy(_channelDMA) || (spi_get_hw(_spi)->sr & SPI_SSPSR_BSY_BITS)) {
return false;
}
dma_channel_cleanup(_channelDMA);
dma_channel_unclaim(_channelDMA);
dma_channel_cleanup(_channelSendDMA);
dma_channel_unclaim(_channelSendDMA);
spi_get_hw(_spi)->dmacr = 0;
if (_spis.getBitOrder() != MSBFIRST) {
for (int i = 0; i < _dmaBytes; i++) {
_rxFinalBuffer[i] = reverseByte(_rxFinalBuffer[i]);
}
free(_dmaBuffer);
_dmaBuffer = nullptr;
}
return true;
}
void SPIClassRP2040::abortAsync() {
if (!_initted) {
return;
}
dma_channel_cleanup(_channelDMA);
dma_channel_unclaim(_channelDMA);
dma_channel_cleanup(_channelSendDMA);
dma_channel_unclaim(_channelSendDMA);
spi_get_hw(_spi)->dmacr = 0;
free(_dmaBuffer);
_dmaBuffer = nullptr;
}
bool SPIClassRP2040::setRX(pin_size_t pin) {
constexpr uint32_t valid[2] = { __bitset({0, 4, 16, 20}) /* SPI0 */,
__bitset({8, 12, 24, 28}) /* SPI1 */
+21
View File
@@ -39,15 +39,28 @@ public:
// Sends one buffer and receives into another, much faster! can set rx or txbuf to nullptr
void transfer(const void *txbuf, void *rxbuf, size_t count) override;
// DMA/asynchronous transfers. Do not combime with synchronous runs or bad stuff will happen
// All buffers must be valid for entire DMA and not touched until `finished()` returns true.
bool transferAsync(const void *send, void *recv, size_t bytes);
bool finishedAsync(); // Call to check if the async operations is completed and the buffer can be reused/read
void abortAsync(); // Cancel an outstanding async operation
// Call before/after every complete transaction
void beginTransaction(SPISettings settings) override;
void endTransaction(void) override;
// Assign pins, call before begin()
bool setRX(pin_size_t pin);
inline bool setMISO(pin_size_t pin) {
return setRX(pin);
}
bool setCS(pin_size_t pin);
bool setSCK(pin_size_t pin);
bool setTX(pin_size_t pin);
inline bool setMOSI(pin_size_t pin) {
return setTX(pin);
}
// Call once to init/deinit SPI class, select pins, etc.
virtual void begin() override {
@@ -86,6 +99,14 @@ private:
bool _initted; // Transaction begun
std::map<int, int> _usingIRQs;
// DMA
int _channelDMA;
int _channelSendDMA;
uint8_t *_dmaBuffer = nullptr;
int _dmaBytes;
uint8_t *_rxFinalBuffer;
uint32_t _dummy;
};
extern SPIClassRP2040 SPI;
@@ -22,6 +22,7 @@
#include <SerialBT.h>
void setup() {
SerialBT.setName("PicoW UPPERCASE 00:00:00:00:00:00");
SerialBT.begin();
}
+1
View File
@@ -11,6 +11,7 @@ SerialBT KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
setName KEYWORD2
#######################################
# Constants (LITERAL1)
+19 -9
View File
@@ -20,6 +20,13 @@
#include "SerialBT.h"
#include <CoreMutex.h>
#define CCALLBACKNAME _SERIALBTCB
#include <ctocppcallback.h>
#define PACKETHANDLERCB(class, cbFcn) \
(CCALLBACKNAME<void(uint8_t, uint16_t, uint8_t*, uint16_t), __COUNTER__>::func = std::bind(&class::cbFcn, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4), \
static_cast<btstack_packet_handler_t>(CCALLBACKNAME<void(uint8_t, uint16_t, uint8_t*, uint16_t), __COUNTER__ - 1>::callback))
bool SerialBT_::setFIFOSize(size_t size) {
if (!size || _running) {
@@ -48,7 +55,7 @@ void SerialBT_::begin(unsigned long baud, uint16_t config) {
_reader = 0;
// register for HCI events
_hci_event_callback_registration.callback = &SerialBT_::PacketHandlerWrapper;
_hci_event_callback_registration.callback = PACKETHANDLERCB(SerialBT_, packetHandler);
hci_add_event_handler(&_hci_event_callback_registration);
l2cap_init();
@@ -59,7 +66,7 @@ void SerialBT_::begin(unsigned long baud, uint16_t config) {
#endif
rfcomm_init();
rfcomm_register_service(SerialBT_::PacketHandlerWrapper, RFCOMM_SERVER_CHANNEL, 0xffff); // reserved channel, mtu limited by l2cap
rfcomm_register_service(PACKETHANDLERCB(SerialBT_, packetHandler), RFCOMM_SERVER_CHANNEL, 0xffff); // reserved channel, mtu limited by l2cap
// init SDP, create record for SPP and register with SDP
sdp_init();
@@ -69,7 +76,10 @@ void SerialBT_::begin(unsigned long baud, uint16_t config) {
gap_discoverable_control(1);
gap_ssp_set_io_capability(SSP_IO_CAPABILITY_DISPLAY_YES_NO);
gap_set_local_name("PicoW Serial 00:00:00:00:00:00");
if (!_name) {
setName("PicoW Serial 00:00:00:00:00:00");
}
gap_set_local_name(_name);
// Turn on!
hci_power_control(HCI_POWER_ON);
@@ -84,9 +94,9 @@ void SerialBT_::end() {
_running = false;
hci_power_control(HCI_POWER_OFF);
lockBluetooth();
__lockBluetooth();
delete[] _queue;
unlockBluetooth();
__unlockBluetooth();
}
int SerialBT_::peek() {
@@ -121,10 +131,10 @@ bool SerialBT_::overflow() {
return false;
}
lockBluetooth();
__lockBluetooth();
bool ovf = _overflow;
_overflow = false;
unlockBluetooth();
__unlockBluetooth();
return ovf;
}
@@ -160,9 +170,9 @@ size_t SerialBT_::write(const uint8_t *p, size_t len) {
}
_writeBuff = p;
_writeLen = len;
lockBluetooth();
__lockBluetooth();
rfcomm_request_can_send_now_event(_channelID);
unlockBluetooth();
__unlockBluetooth();
while (_connected && _writeLen) {
/* noop busy wait */
}
+11 -14
View File
@@ -37,6 +37,14 @@ public:
SerialBT_();
bool setFIFOSize(size_t size);
bool setName(const char *name) {
if (_running) {
return false;
}
free(_name);
_name = strdup(name);
return true;
}
void begin(unsigned long baud = 115200) override {
begin(baud, SERIAL_8N1);
@@ -60,26 +68,13 @@ public:
(void) unused;
}
static void PacketHandlerWrapper(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t packet_size) {
SerialBT.packetHandler(packet_type, channel, packet, packet_size);
}
void packetHandler(uint8_t type, uint16_t channel, uint8_t *packet, uint16_t size);
static void lockBluetooth() {
async_context_acquire_lock_blocking(cyw43_arch_async_context());
}
static void unlockBluetooth() {
async_context_release_lock(cyw43_arch_async_context());
}
private:
bool _running = false;
mutex_t _mutex;
bool _overflow = false;
volatile bool _connected = false;
void packetHandler(uint8_t type, uint16_t channel, uint8_t *packet, uint16_t size);
// Lockless, IRQ-handled circular queue
uint32_t _writer;
@@ -95,4 +90,6 @@ private:
volatile int _writeLen = 0;
const void *_writeBuff;
char *_name = nullptr;
};
@@ -60,8 +60,9 @@ void handleRoot() {
static int cnt = 0;
digitalWrite(led, 1);
int sec = millis() / 1000;
int min = sec / 60;
int hr = min / 60;
int hr = sec / 3600;
int min = (sec / 60) % 60;
sec = sec % 60;
StreamString temp;
temp.reserve(500); // Preallocate a large chunk to avoid memory fragmentation
@@ -80,7 +81,7 @@ void handleRoot() {
<p>Page Count: %d</p>\
<img src=\"/test.svg\" />\
</body>\
</html>", hr, min % 60, sec % 60, rp2040.getFreeHeap(), ++cnt);
</html>", hr, min, sec, rp2040.getFreeHeap(), ++cnt);
server.send(200, "text/html", temp);
digitalWrite(led, 0);
}
@@ -0,0 +1,100 @@
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <LEAmDNS.h>
// Your STA WiFi Credentials
// ( This is the AP your RP2040 will connect to )
const char *ssid = "........";
const char *password = "........";
// Your AP WiFi Credentials
// ( This is the AP your RP2040 will broadcast )
const char *ap_ssid = "RP2040_Demo";
const char *ap_password = "";
WebServer server(80);
const int led = LED_BUILTIN;
// ON_STA_FILTER - Only accept requests coming from STA interface
bool ON_STA_FILTER(HTTPServer &server) {
return WiFi.localIP() == server.client().localIP();
}
// ON_AP_FILTER - Only accept requests coming from AP interface
bool ON_AP_FILTER(HTTPServer &server) {
return WiFi.softAPIP() == server.client().localIP();
}
void handleNotFound() {
digitalWrite(led, 1);
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i = 0; i < server.args(); i++) {
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
digitalWrite(led, 0);
}
void setup(void) {
pinMode(led, OUTPUT);
digitalWrite(led, 0);
Serial.begin(115200);
WiFi.mode(WIFI_AP_STA);
// Connect to STA
WiFi.begin(ssid, password);
// Start AP
WiFi.softAP(ap_ssid, ap_password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
if (MDNS.begin("picow")) {
Serial.println("MDNS responder started");
}
// This route will be accessible by STA clients only
server.on("/", [&]() {
digitalWrite(led, 1);
server.send(200, "text/plain", "Hi!, This route is accessible for STA clients only");
digitalWrite(led, 0);
}).setFilter(ON_STA_FILTER);
// This route will be accessible by AP clients only
server.on("/", [&]() {
digitalWrite(led, 1);
server.send(200, "text/plain", "Hi!, This route is accessible for AP clients only");
digitalWrite(led, 0);
}).setFilter(ON_AP_FILTER);
server.on("/inline", []() {
server.send(200, "text/plain", "this works as well");
});
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}
void loop(void) {
server.handleClient();
MDNS.update();
}
@@ -0,0 +1,13 @@
# Upload Huge File To Filesystem Over HTTP
This project is an example of an HTTP server designed to facilitate the transfer of large files using the PUT method, in accordance with RFC specifications.
### Example cURL Command
```bash
curl -X PUT -T ./my-file.mp3 http://pico-ip/upload/my-file.mp3
```
## Resources
- RFC HTTP/1.0 - Additional Request Methods - PUT : [Link](https://datatracker.ietf.org/doc/html/rfc1945#appendix-D.1.1)
@@ -0,0 +1,92 @@
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <uri/UriRegex.h>
#include <LittleFS.h>
#ifndef STASSID
#define STASSID "your-ssid"
#define STAPSK "your-password"
#endif
const char *ssid = STASSID;
const char *password = STAPSK;
WebServer server(80);
File rawFile;
void handleCreate() {
server.send(200, "text/plain", "");
}
void handleCreateProcess() {
String path = "/" + server.pathArg(0);
HTTPRaw& raw = server.raw();
if (raw.status == RAW_START) {
if (LittleFS.exists((char *)path.c_str())) {
LittleFS.remove((char *)path.c_str());
}
rawFile = LittleFS.open(path.c_str(), "w");
Serial.print("Upload: START, filename: ");
Serial.println(path);
} else if (raw.status == RAW_WRITE) {
if (rawFile) {
rawFile.write(raw.buf, raw.currentSize);
}
Serial.print("Upload: WRITE, Bytes: ");
Serial.println(raw.currentSize);
} else if (raw.status == RAW_END) {
if (rawFile) {
rawFile.close();
}
Serial.print("Upload: END, Size: ");
Serial.println(raw.totalSize);
}
}
void returnFail(String msg) {
server.send(500, "text/plain", msg + "\r\n");
}
void handleNotFound() {
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i = 0; i < server.args(); i++) {
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
void setup(void) {
Serial.begin(115200);
LittleFS.begin();
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
server.on(UriRegex("/upload/(.*)"), HTTP_PUT, handleCreate, handleCreateProcess);
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}
void loop(void) {
server.handleClient();
delay(2);//allow the cpu to switch to other tasks
}
+75 -6
View File
@@ -207,22 +207,65 @@ void HTTPServer::requestAuthentication(HTTPAuthMethod mode, const char* realm, c
send(401, String(FPSTR(mimeTable[html].mimeType)), authFailMsg);
}
void HTTPServer::on(const Uri &uri, HTTPServer::THandlerFunction handler) {
on(uri, HTTP_ANY, handler);
RequestHandler& HTTPServer::on(const Uri &uri, HTTPServer::THandlerFunction handler) {
return on(uri, HTTP_ANY, handler);
}
void HTTPServer::on(const Uri &uri, HTTPMethod method, HTTPServer::THandlerFunction fn) {
on(uri, method, fn, _fileUploadHandler);
RequestHandler& HTTPServer::on(const Uri &uri, HTTPMethod method, HTTPServer::THandlerFunction fn) {
return on(uri, method, fn, _fileUploadHandler);
}
void HTTPServer::on(const Uri &uri, HTTPMethod method, HTTPServer::THandlerFunction fn, HTTPServer::THandlerFunction ufn) {
_addRequestHandler(new FunctionRequestHandler(fn, ufn, uri, method));
RequestHandler& HTTPServer::on(const Uri &uri, HTTPMethod method, HTTPServer::THandlerFunction fn, HTTPServer::THandlerFunction ufn) {
FunctionRequestHandler *handler = new FunctionRequestHandler(fn, ufn, uri, method);
_addRequestHandler(handler);
return *handler;
}
bool HTTPServer::removeRoute(const char *uri) {
return removeRoute(String(uri), HTTP_ANY);
}
bool HTTPServer::removeRoute(const char *uri, HTTPMethod method) {
return removeRoute(String(uri), method);
}
bool HTTPServer::removeRoute(const String &uri) {
return removeRoute(uri, HTTP_ANY);
}
bool HTTPServer::removeRoute(const String &uri, HTTPMethod method) {
bool anyHandlerRemoved = false;
RequestHandler *handler = _firstHandler;
RequestHandler *previousHandler = nullptr;
while (handler) {
if (handler->canHandle(method, uri)) {
if (_removeRequestHandler(handler)) {
anyHandlerRemoved = true;
// Move to the next handler
if (previousHandler) {
handler = previousHandler->next();
} else {
handler = _firstHandler;
}
continue;
}
}
previousHandler = handler;
handler = handler->next();
}
return anyHandlerRemoved;
}
void HTTPServer::addHandler(RequestHandler* handler) {
_addRequestHandler(handler);
}
bool HTTPServer::removeHandler(RequestHandler *handler) {
return _removeRequestHandler(handler);
}
void HTTPServer::_addRequestHandler(RequestHandler* handler) {
if (!_lastHandler) {
_firstHandler = handler;
@@ -233,6 +276,32 @@ void HTTPServer::_addRequestHandler(RequestHandler* handler) {
}
}
bool HTTPServer::_removeRequestHandler(RequestHandler *handler) {
RequestHandler *current = _firstHandler;
RequestHandler *previous = nullptr;
while (current != nullptr) {
if (current == handler) {
if (previous == nullptr) {
_firstHandler = current->next();
} else {
previous->next(current->next());
}
if (current == _lastHandler) {
_lastHandler = previous;
}
// Delete 'matching' handler
delete current;
return true;
}
previous = current;
current = current->next();
}
return false;
}
void HTTPServer::serveStatic(const char* uri, FS& fs, const char* path, const char* cache_header) {
_addRequestHandler(new StaticRequestHandler(fs, path, uri, cache_header));
}

Some files were not shown because too many files have changed in this diff Show More