Compare commits
@@ -13,28 +13,21 @@ env:
|
||||
|
||||
jobs:
|
||||
|
||||
# Me no spell so good
|
||||
code-spell:
|
||||
name: Check spelling
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
- name: Run codespell
|
||||
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
|
||||
ignore_words_list: ser,dout
|
||||
|
||||
# Consistent style
|
||||
# Consistent style, spelling
|
||||
astyle:
|
||||
name: Style, Boards, Package
|
||||
name: Spelling, Style, Boards, Package
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: false
|
||||
- name: Run codespell
|
||||
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,shiftIn,acount
|
||||
- name: Get submodules for following tests
|
||||
run: git submodule update --init
|
||||
- name: Check package references
|
||||
run: |
|
||||
./tests/ci/pkgrefs_test.sh
|
||||
@@ -223,3 +216,55 @@ jobs:
|
||||
run: pio ci --board=rpipicow -O "platform_packages=framework-arduinopico@symlink:///home/runner/work/arduino-pico/arduino-pico" libraries/ArduinoOTA/examples/SignedOTA/SignedOTA.ino
|
||||
- name: Build Bluetooth Example
|
||||
run: pio ci --board=rpipicow -O "platform_packages=framework-arduinopico@symlink:///home/runner/work/arduino-pico/arduino-pico" -O "build_flags=-DPIO_FRAMEWORK_ARDUINO_ENABLE_BLUETOOTH" libraries/MouseBLE/examples/BLECircle/BLECircle.ino
|
||||
|
||||
# Build every variant using PIO for simplicity
|
||||
build-variants:
|
||||
name: Build Every Variant ${{ matrix.chunk }}
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
chunk: [0, 1]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: 'true'
|
||||
- name: Initialize needed submodules
|
||||
run: |
|
||||
cd pico-sdk
|
||||
git submodule update --init
|
||||
cd ../libraries/Adafruit_TinyUSB_Arduino
|
||||
git submodule update --init
|
||||
cd ../..
|
||||
- name: Cache pip
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/pip
|
||||
key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-pip-
|
||||
- name: Cache PlatformIO
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.platformio
|
||||
key: ${{ runner.os }}-${{ hashFiles('**/lockfiles') }}
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.x'
|
||||
- name: Install PlatformIO
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install --upgrade platformio
|
||||
pio pkg install --global --platform https://github.com/maxgerhardt/platform-raspberrypi.git
|
||||
pio pkg install --global --tool symlink://.
|
||||
cp -f /home/runner/work/arduino-pico/arduino-pico/tools/json/*.json /home/runner/.platformio/platforms/raspberrypi/boards/.
|
||||
- name: Build Every Variant
|
||||
run: |
|
||||
cnt=0
|
||||
for b in $(cut -f1 -d. /home/runner/work/arduino-pico/arduino-pico/boards.txt | sed 's/#.*//' | sed 's/^menu$//' | sort -u); do
|
||||
cnt=$((cnt + 1))
|
||||
rem=$((cnt % 2))
|
||||
if [ $rem == ${{ matrix.chunk }} ]; then
|
||||
pio ci --board=$b -O "platform_packages=framework-arduinopico@symlink:///home/runner/work/arduino-pico/arduino-pico" libraries/rp2040/examples/Bootsel/Bootsel.ino
|
||||
fi
|
||||
done
|
||||
|
||||
@@ -9,21 +9,21 @@ jobs:
|
||||
name: Update master JSON file
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
- name: Cache pip
|
||||
uses: actions/cache@v3
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/pip
|
||||
key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-pip-
|
||||
- uses: actions/setup-python@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.x'
|
||||
# - name: Cache PlatformIO
|
||||
# uses: actions/cache@v3
|
||||
# uses: actions/cache@v4
|
||||
# with:
|
||||
# path: ~/.platformio
|
||||
# key: ${{ runner.os }}-${{ hashFiles('**/lockfiles') }}
|
||||
|
||||
@@ -15,11 +15,11 @@ jobs:
|
||||
name: Package
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
fetch-depth: 0
|
||||
- uses: actions/setup-python@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.x'
|
||||
- name: Build package JSON
|
||||
|
||||
@@ -37,3 +37,9 @@
|
||||
[submodule "libraries/http_parser/lib/http-parser"]
|
||||
path = libraries/http-parser/lib/http-parser
|
||||
url = https://github.com/nodejs/http-parser.git
|
||||
[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
|
||||
|
||||
@@ -25,9 +25,15 @@ Read the [Contributing Guide](https://github.com/earlephilhower/arduino-pico/blo
|
||||
* Adafruit QTPy RP2040
|
||||
* Adafruit STEMMA Friend RP2040
|
||||
* Adafruit Trinkey RP2040 QT
|
||||
* Amken Bunny
|
||||
* Amken Revelop
|
||||
* Amken Revelop Plus
|
||||
* Amken Revelop eS
|
||||
* Arduino Nano RP2040 Connect
|
||||
* ArtronShop RP2 Nano
|
||||
* Breadstick Raspberry
|
||||
* BridgeTek IDM2040-7A
|
||||
* BridgeTek IDM2040-43A
|
||||
* Cytron Maker Pi RP2040
|
||||
* Cytron Maker Nano RP2040
|
||||
* Cytron Maker Uno RP2040
|
||||
@@ -36,7 +42,9 @@ Read the [Contributing Guide](https://github.com/earlephilhower/arduino-pico/blo
|
||||
* DeRuiLab FlyBoard2040 Core
|
||||
* DFRobot Beetle RP2040
|
||||
* ElectronicCats Hunter Cat NFC
|
||||
* EVN Alpha
|
||||
* ExtremeElectronics RC2040
|
||||
* GroundStudio Marble Pico
|
||||
* Invector Labs Challenger RP2040 WiFi
|
||||
* Invector Labs Challenger RP2040 WiFi/BLE
|
||||
* Invector Labs Challenger RP2040 WiFi6/BLE
|
||||
@@ -49,11 +57,15 @@ 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
|
||||
* Pimoroni Tiny2040
|
||||
* Pintronix PinMax
|
||||
* RAKwireless RAK11300
|
||||
* Redscorp RP2040-Eins
|
||||
* Redscorp RP2040-ProMini
|
||||
@@ -62,6 +74,7 @@ Read the [Contributing Guide](https://github.com/earlephilhower/arduino-pico/blo
|
||||
* Seeed XIAO RP2040
|
||||
* Silicognition RP2040-Shim
|
||||
* Solder Party RP2040 Stamp
|
||||
* SparkFun MicroMod RP2040
|
||||
* SparkFun ProMicro RP2040
|
||||
* SparkFun Thing Plus RP2040
|
||||
* uPesy RP2040 DevKit
|
||||
@@ -72,6 +85,8 @@ Read the [Contributing Guide](https://github.com/earlephilhower/arduino-pico/blo
|
||||
* Waveshare RP2040 Plus
|
||||
* Waveshare RP2040 LCD 0.96
|
||||
* Waveshare RP2040 LCD 1.28
|
||||
* Waveshare RP2040 Matrix
|
||||
* Waveshare RP2040 PiZero
|
||||
* WIZnet W5100S-EVB-Pico
|
||||
* WIZnet W5500-EVB-Pico
|
||||
* WIZnet WizFi360-EVB-Pico
|
||||
@@ -80,8 +95,9 @@ 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)
|
||||
* WiFi (Pico W, ESP32-based ESPHost, Atmel WINC1500)
|
||||
* Ethernet (Wired W5500, W5100, ENC28J60)
|
||||
* HTTP client and server (WebServer)
|
||||
* SSL/TLS/HTTPS
|
||||
@@ -93,7 +109,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
|
||||
|
||||
@@ -202,11 +219,14 @@ Under Windows a local admin user should be able to access the Picoprobe port aut
|
||||
|
||||
To set up user-level access to Picoprobes on Ubuntu (and other OSes which use `udev`):
|
||||
````
|
||||
echo 'SUBSYSTEMS=="usb", ATTRS{idVendor}=="2e8a", ATTRS{idProduct}=="0004", GROUP="users", MODE="0666"' | sudo tee -a /etc/udev/rules.d/98-PicoProbe.rules
|
||||
echo 'SUBSYSTEMS=="usb", ATTRS{idVendor}=="2e8a", ATTRS{idProduct}=="0004", MODE="0666"' | sudo tee -a /etc/udev/rules.d/98-PicoProbe.rules
|
||||
sudo udevadm control --reload
|
||||
sudo udevadm trigger -w -s usb
|
||||
````
|
||||
|
||||
The first line creates a file with the USB vendor and ID of the Picoprobe and tells UDEV to give users full access to it. The second causes `udev` to load this new rule. Note that you will need to unplug and re-plug in your device the first time you create this file, to allow udev to make the device node properly.
|
||||
The first line creates a device file in `/dev` matching the USB vendor and product ID of the Picoprobe, and it enables global read+write permissions. The second line causes `udev` to load this new rule. The third line requests the kernel generate "device change" events that will cause our new `udev` rule to run.
|
||||
|
||||
If for some reason the device file does not appear, manually unplug and re-plug the USB connection and check again. The output from `dmesg` can reveal useful diagnostics if the device file remains absent.
|
||||
|
||||
Once Picoprobe permissions are set up properly, then select the board "Raspberry Pi Pico (Picoprobe)" in the Tools menu and upload as normal.
|
||||
|
||||
@@ -215,13 +235,16 @@ Once Picoprobe permissions are set up properly, then select the board "Raspberry
|
||||
|
||||
Under Windows and macOS, any user should be able to access pico-debug automatically, but under Linux `udev` must be told about the device and to allow normal users access.
|
||||
|
||||
To set up user-level access to all CMSIS-DAP adapters on Ubuntu (and other OSes which use `udev`):
|
||||
To set up group-level access to all CMSIS-DAP adapters on Ubuntu (and other OSes which use `udev`):
|
||||
````
|
||||
echo 'ATTRS{product}=="*CMSIS-DAP*", MODE="664", GROUP="plugdev"' | sudo tee -a /etc/udev/rules.d/98-CMSIS-DAP.rules
|
||||
sudo udevadm control --reload
|
||||
sudo udevadm trigger -w -s usb
|
||||
````
|
||||
|
||||
The first line creates a file that recognizes all CMSIS-DAP adapters and tells UDEV to give users full access to it. The second causes `udev` to load this new rule. Note that you will need to unplug and re-plug in your device the first time you create this file, to allow udev to make the device node properly.
|
||||
The first line creates a device file in `/dev` that matches all CMSIS-DAP adapters, and it enables read+write permissions for members of the `plugdev` group. The second line causes `udev` to load this new rule. The third line requests the kernel generate "device change" events that will cause our new `udev` rule to run.
|
||||
|
||||
If for some reason the device file does not appear, manually unplug and re-plug the USB connection and check again. The output from `dmesg` can reveal useful diagnostics if the device file remains absent.
|
||||
|
||||
Once CMSIS-DAP permissions are set up properly, then select the board "Raspberry Pi Pico (pico-debug)" in the Tools menu.
|
||||
|
||||
@@ -247,6 +270,8 @@ The installed tools include a version of OpenOCD (in the pqt-openocd directory)
|
||||
* [http-parser](https://github.com/nodejs/http-parser) is copyright Joyent, Inc. and other Node contributors.
|
||||
* WebServer code modified from the [ESP32 WebServer](https://github.com/espressif/arduino-esp32/tree/master/libraries/WebServer) and is copyright (c) 2015 Ivan Grokhotkov and others.
|
||||
* [Xoshiro-cpp](https://github.com/Reputeless/Xoshiro-cpp) is copyright (c) 2020 Ryo Suzuki and distributed under the MIT license.
|
||||
* [FatFS low-level filesystem](http://elm-chan.org/fsw/ff/) code is Copyright (C) 2024, ChaN, all rights reserved.
|
||||
|
||||
|
||||
-Earle F. Philhower, III
|
||||
earlephilhower@yahoo.com
|
||||
|
||||
+8051
-623
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,23 @@
|
||||
// Padded and checksummed version of: generated\Winbond\W25Q32JVxQ\boot2.bin
|
||||
|
||||
.cpu cortex-m0plus
|
||||
.thumb
|
||||
|
||||
.section .boot2, "ax"
|
||||
|
||||
.byte 0xf7, 0xb5, 0x73, 0x46, 0x21, 0x22, 0x02, 0x25, 0x01, 0x93, 0x29, 0x4b, 0xc0, 0x24, 0x5a, 0x60
|
||||
.byte 0x9a, 0x68, 0x01, 0x26, 0xaa, 0x43, 0xda, 0x60, 0x9a, 0x60, 0x1a, 0x61, 0x5a, 0x61, 0x00, 0x23
|
||||
.byte 0x64, 0x05, 0xa3, 0x60, 0x04, 0x33, 0x63, 0x61, 0x22, 0x4b, 0x28, 0x00, 0x1e, 0x60, 0xe0, 0x23
|
||||
.byte 0xdb, 0x02, 0x23, 0x60, 0x35, 0x23, 0xa6, 0x60, 0x23, 0x66, 0x23, 0x66, 0x00, 0xf0, 0x4a, 0xf8
|
||||
.byte 0xc0, 0xb2, 0xa8, 0x42, 0x12, 0xd0, 0x06, 0x23, 0x30, 0x00, 0x23, 0x66, 0x00, 0xf0, 0x42, 0xf8
|
||||
.byte 0x31, 0x23, 0x28, 0x00, 0x23, 0x66, 0x25, 0x66, 0x00, 0xf0, 0x3c, 0xf8, 0x03, 0x35, 0x25, 0x66
|
||||
.byte 0x02, 0x20, 0x25, 0x66, 0x00, 0xf0, 0x36, 0xf8, 0x30, 0x42, 0xf8, 0xd1, 0x00, 0x25, 0x12, 0x4b
|
||||
.byte 0xa5, 0x60, 0x12, 0x4f, 0x23, 0x60, 0x12, 0x4b, 0x65, 0x60, 0x01, 0x26, 0x3b, 0x60, 0xeb, 0x23
|
||||
.byte 0xa6, 0x60, 0x23, 0x66, 0x4b, 0x3b, 0x23, 0x66, 0x02, 0x20, 0x00, 0xf0, 0x23, 0xf8, 0x0d, 0x4b
|
||||
.byte 0xa5, 0x60, 0x3b, 0x60, 0xa6, 0x60, 0x01, 0x9b, 0xab, 0x42, 0x08, 0xd1, 0x0a, 0x4b, 0x0b, 0x4a
|
||||
.byte 0x13, 0x60, 0x1b, 0x68, 0x83, 0xf3, 0x08, 0x88, 0x09, 0x4b, 0x1b, 0x68, 0x18, 0x47, 0xf7, 0xbd
|
||||
.byte 0x00, 0x00, 0x02, 0x40, 0xf0, 0x00, 0x00, 0x18, 0x00, 0x03, 0x5f, 0x00, 0xf4, 0x00, 0x00, 0x18
|
||||
.byte 0x21, 0x22, 0x00, 0x00, 0x22, 0x20, 0x00, 0xa0, 0x00, 0x01, 0x00, 0x10, 0x08, 0xed, 0x00, 0xe0
|
||||
.byte 0x04, 0x01, 0x00, 0x10, 0xc0, 0x23, 0x02, 0x00, 0x04, 0x21, 0x5b, 0x05, 0x98, 0x6a, 0x08, 0x42
|
||||
.byte 0xfc, 0xd0, 0x01, 0x21, 0x98, 0x6a, 0x08, 0x42, 0xfc, 0xd1, 0x18, 0x6e, 0x01, 0x2a, 0x00, 0xd0
|
||||
.byte 0x18, 0x6e, 0x70, 0x47, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x2d, 0x68, 0xca
|
||||
@@ -65,9 +65,9 @@ void noInterrupts();
|
||||
#define digitalPinToTimer(pin) (0)
|
||||
#define digitalPinToInterrupt(pin) (pin)
|
||||
#define NOT_AN_INTERRUPT (-1)
|
||||
#define portOutputRegister(port) ((volatile uint32_t*) sio_hw->gpio_out)
|
||||
#define portInputRegister(port) ((volatile uint32_t*) sio_hw->gpio_in)
|
||||
#define portModeRegister(port) ((volatile uint32_t*) sio_hw->gpio_oe)
|
||||
#define portOutputRegister(port) ((volatile uint32_t *)&(sio_hw->gpio_out))
|
||||
#define portInputRegister(port) ((volatile uint32_t *)&(sio_hw->gpio_in))
|
||||
#define portModeRegister(port) ((volatile uint32_t *)&(sio_hw->gpio_oe))
|
||||
#define digitalWriteFast(pin, val) (val ? sio_hw->gpio_set = (1 << pin) : sio_hw->gpio_clr = (1 << pin))
|
||||
#define digitalReadFast(pin) ((1 << pin) & sio_hw->gpio_in)
|
||||
#define sei() interrupts()
|
||||
|
||||
@@ -155,11 +155,52 @@ static uint8_t *GetDescHIDReport(int *len) {
|
||||
return __hid_report;
|
||||
}
|
||||
|
||||
#define TUD_HID_REPORT_DESC_GAMEPAD16(...) \
|
||||
HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\
|
||||
HID_USAGE ( HID_USAGE_DESKTOP_GAMEPAD ) ,\
|
||||
HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\
|
||||
/* Report ID if any */\
|
||||
__VA_ARGS__ \
|
||||
/* 16 bit X, Y, Z, Rz, Rx, Ry (min -32767, max 32767 ) */ \
|
||||
HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\
|
||||
HID_USAGE ( HID_USAGE_DESKTOP_X ) ,\
|
||||
HID_USAGE ( HID_USAGE_DESKTOP_Y ) ,\
|
||||
HID_USAGE ( HID_USAGE_DESKTOP_Z ) ,\
|
||||
HID_USAGE ( HID_USAGE_DESKTOP_RZ ) ,\
|
||||
HID_USAGE ( HID_USAGE_DESKTOP_RX ) ,\
|
||||
HID_USAGE ( HID_USAGE_DESKTOP_RY ) ,\
|
||||
HID_LOGICAL_MIN_N ( -32767, 2 ) ,\
|
||||
HID_LOGICAL_MAX_N ( 32767, 2 ) ,\
|
||||
HID_REPORT_COUNT ( 6 ) ,\
|
||||
HID_REPORT_SIZE ( 16 ) ,\
|
||||
HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\
|
||||
/* 8 bit DPad/Hat Button Map */ \
|
||||
HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\
|
||||
HID_USAGE ( HID_USAGE_DESKTOP_HAT_SWITCH ) ,\
|
||||
HID_LOGICAL_MIN ( 1 ) ,\
|
||||
HID_LOGICAL_MAX ( 8 ) ,\
|
||||
HID_PHYSICAL_MIN ( 0 ) ,\
|
||||
HID_PHYSICAL_MAX_N ( 315, 2 ) ,\
|
||||
HID_REPORT_COUNT ( 1 ) ,\
|
||||
HID_REPORT_SIZE ( 8 ) ,\
|
||||
HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\
|
||||
/* 32 bit Button Map */ \
|
||||
HID_USAGE_PAGE ( HID_USAGE_PAGE_BUTTON ) ,\
|
||||
HID_USAGE_MIN ( 1 ) ,\
|
||||
HID_USAGE_MAX ( 32 ) ,\
|
||||
HID_LOGICAL_MIN ( 0 ) ,\
|
||||
HID_LOGICAL_MAX ( 1 ) ,\
|
||||
HID_REPORT_COUNT ( 32 ) ,\
|
||||
HID_REPORT_SIZE ( 1 ) ,\
|
||||
HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\
|
||||
HID_COLLECTION_END \
|
||||
|
||||
|
||||
void __SetupDescHIDReport() {
|
||||
//allocate memory for the HID report descriptors. We don't use them, but need the size here.
|
||||
uint8_t desc_hid_report_mouse[] = { TUD_HID_REPORT_DESC_MOUSE(HID_REPORT_ID(1)) };
|
||||
uint8_t desc_hid_report_absmouse[] = { TUD_HID_REPORT_DESC_ABSMOUSE(HID_REPORT_ID(1)) };
|
||||
uint8_t desc_hid_report_joystick[] = { TUD_HID_REPORT_DESC_GAMEPAD(HID_REPORT_ID(1)) };
|
||||
uint8_t desc_hid_report_joystick[] = { TUD_HID_REPORT_DESC_GAMEPAD16(HID_REPORT_ID(1)) };
|
||||
uint8_t desc_hid_report_keyboard[] = { TUD_HID_REPORT_DESC_KEYBOARD(HID_REPORT_ID(1)), TUD_HID_REPORT_DESC_CONSUMER(HID_REPORT_ID(2)) };
|
||||
int size = 0;
|
||||
|
||||
@@ -229,7 +270,7 @@ void __SetupDescHIDReport() {
|
||||
reportid++;
|
||||
offset += sizeof(desc_hid_report_absmouse);
|
||||
}
|
||||
uint8_t desc_local[] = { TUD_HID_REPORT_DESC_GAMEPAD(HID_REPORT_ID(reportid)) };
|
||||
uint8_t desc_local[] = { TUD_HID_REPORT_DESC_GAMEPAD16(HID_REPORT_ID(reportid)) };
|
||||
memcpy(__hid_report + offset, desc_local, sizeof(desc_local));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#pragma once
|
||||
#define ARDUINO_PICO_MAJOR 3
|
||||
#define ARDUINO_PICO_MINOR 7
|
||||
#define ARDUINO_PICO_REVISION 0
|
||||
#define ARDUINO_PICO_VERSION_STR "3.7.0"
|
||||
#define ARDUINO_PICO_MINOR 9
|
||||
#define ARDUINO_PICO_REVISION 4
|
||||
#define ARDUINO_PICO_VERSION_STR "3.9.4"
|
||||
|
||||
@@ -53,7 +53,7 @@ public:
|
||||
using Print::write;
|
||||
operator bool() override;
|
||||
|
||||
// Not to be called by users, only from the IRQ handler. In public so that the C-language IQR callback can access it
|
||||
// Not to be called by users, only from the IRQ handler. In public so that the C-language IRQ callback can access it
|
||||
void _handleIRQ();
|
||||
|
||||
protected:
|
||||
|
||||
@@ -201,7 +201,7 @@ void SerialUART::begin(unsigned long baud, uint16_t config) {
|
||||
break;
|
||||
}
|
||||
uart_set_format(_uart, bits, stop, parity);
|
||||
uart_set_hw_flow(_uart, _rts != UART_PIN_NOT_DEFINED, _cts != UART_PIN_NOT_DEFINED);
|
||||
uart_set_hw_flow(_uart, _cts != UART_PIN_NOT_DEFINED, _rts != UART_PIN_NOT_DEFINED);
|
||||
_writer = 0;
|
||||
_reader = 0;
|
||||
|
||||
|
||||
@@ -31,12 +31,10 @@ extern bool __isFreeRTOS;
|
||||
extern volatile bool __freeRTOSinitted;
|
||||
|
||||
extern "C" {
|
||||
#ifndef INC_FREERTOS_H
|
||||
struct QueueDefinition; /* Using old naming convention so as not to break kernel aware debuggers. */
|
||||
typedef struct QueueDefinition * QueueHandle_t;
|
||||
typedef QueueHandle_t SemaphoreHandle_t;
|
||||
typedef int32_t BaseType_t;
|
||||
#endif
|
||||
|
||||
extern bool __freertos_check_if_in_isr() __attribute__((weak));
|
||||
|
||||
|
||||
@@ -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;
|
||||
@@ -33,12 +33,17 @@
|
||||
|
||||
extern void ethernet_arch_lwip_begin() __attribute__((weak));
|
||||
extern void ethernet_arch_lwip_end() __attribute__((weak));
|
||||
extern void ethernet_arch_lwip_gpio_mask() __attribute__((weak));
|
||||
extern void ethernet_arch_lwip_gpio_unmask() __attribute__((weak));
|
||||
|
||||
auto_init_recursive_mutex(__lwipMutex); // Only for case with no Ethernet or PicoW, but still doing LWIP (PPP?)
|
||||
|
||||
class LWIPMutex {
|
||||
public:
|
||||
LWIPMutex() {
|
||||
if (ethernet_arch_lwip_gpio_mask) {
|
||||
ethernet_arch_lwip_gpio_mask();
|
||||
}
|
||||
#if defined(ARDUINO_RASPBERRY_PI_PICO_W)
|
||||
if (rp2040.isPicoW()) {
|
||||
cyw43_arch_lwip_begin();
|
||||
@@ -56,13 +61,18 @@ public:
|
||||
#if defined(ARDUINO_RASPBERRY_PI_PICO_W)
|
||||
if (rp2040.isPicoW()) {
|
||||
cyw43_arch_lwip_end();
|
||||
return;
|
||||
} else {
|
||||
#endif
|
||||
if (ethernet_arch_lwip_end) {
|
||||
ethernet_arch_lwip_end();
|
||||
} else {
|
||||
recursive_mutex_exit(&__lwipMutex);
|
||||
}
|
||||
#if defined(ARDUINO_RASPBERRY_PI_PICO_W)
|
||||
}
|
||||
#endif
|
||||
if (ethernet_arch_lwip_end) {
|
||||
ethernet_arch_lwip_end();
|
||||
} else {
|
||||
recursive_mutex_exit(&__lwipMutex);
|
||||
if (ethernet_arch_lwip_gpio_unmask) {
|
||||
ethernet_arch_lwip_gpio_unmask();
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -79,7 +89,7 @@ extern "C" {
|
||||
extern void __real_lwip_init();
|
||||
void __wrap_lwip_init() {
|
||||
if (!_lwip_rng) {
|
||||
_lwip_rng = new XoshiroCpp::Xoshiro256PlusPlus(get_rand_64());
|
||||
_lwip_rng = new XoshiroCpp::Xoshiro256PlusPlus(micros() * rp2040.getCycleCount());
|
||||
__real_lwip_init();
|
||||
}
|
||||
}
|
||||
@@ -348,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"
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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
@@ -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
@@ -54,9 +54,9 @@ author = u'Earle F. Philhower, III'
|
||||
# built documents.
|
||||
#
|
||||
# The short X.Y version.
|
||||
version = u'3.7.0'
|
||||
version = u'3.9.4'
|
||||
# The full version, including alpha/beta/rc tags.
|
||||
release = u'3.7.0'
|
||||
release = u'3.9.4'
|
||||
|
||||
# The language for content autogenerated by Sphinx. Refer to documentation
|
||||
# for a list of supported languages.
|
||||
|
||||
+15
-2
@@ -86,6 +86,19 @@ Pico may not have enough time to service the Ethernet port before the timer fire
|
||||
leading to a lock up and hang.
|
||||
|
||||
|
||||
Using Interrupt-Driven Handling
|
||||
-------------------------------
|
||||
|
||||
The WizNet and ENC28J60 devices support generating an interrupt when a packet is received,
|
||||
removing the need for polling and decreasing latency. Simply specify the SPI object to use and the
|
||||
interrupt pin when instantiating the Ethernet object:
|
||||
|
||||
.. code:: cpp
|
||||
|
||||
#include <W5100lwIP.h>
|
||||
Wiznet5100lwIP eth(SS /* Chip Select*/, SPI /* SPI interface */, 17 /* Interrupt GPIO */ );
|
||||
|
||||
|
||||
Adjusting SPI Speed
|
||||
-------------------
|
||||
|
||||
@@ -114,12 +127,12 @@ For example, to set the W5500 to use a 30MHZ clock:
|
||||
Using the WIZnet W5100S-EVB-Pico
|
||||
--------------------------------
|
||||
|
||||
You can use the onboard Ethernet chip with these drivers by utilizing the following options:
|
||||
You can use the onboard Ethernet chip with these drivers, in interrupt mode, by utilizing the following options:
|
||||
|
||||
.. code:: cpp
|
||||
|
||||
#include <W5100lwIP.h>
|
||||
Wiznet5100lwIP eth(17); // Note chip select is **17**
|
||||
Wiznet5100lwIP eth(17, SPI, 21); // Note chip select is **17**
|
||||
|
||||
void setup() {
|
||||
// Set SPI to the onboard Wiznet chip
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
FatFSUSB
|
||||
========
|
||||
|
||||
When the onboard flash memory is used as a ``FatFS`` filesystem, the
|
||||
``FatFSUSB`` can be used to allow exporting it to a PC as a standard
|
||||
memory stick. The PC can then access, add, and remove files as if the
|
||||
Pico was a USB memory stick, and upon ejection the Pico can access
|
||||
any new files just as if it made them itself.
|
||||
|
||||
(Note, if you are using LittleFS then you need to use ``SingleFileDrive``
|
||||
to export a single file, not this class, because the PC does not
|
||||
understand the LittleFS disk format.)
|
||||
|
||||
Callbacks, Interrupt Safety, and File Operations
|
||||
------------------------------------------------
|
||||
|
||||
The ``FatFSUSB`` library allows your application to get a callback
|
||||
when a PC attempts to mount or unmount the Pico as a FAT drive.
|
||||
|
||||
When the drive is being used by the Pico (i.e. any ``File`` is open for
|
||||
read or write, the ``FatFS`` is not ``end()`` -ed and still mounted,
|
||||
etc.) the host may not access it. Conversely, while the host PC is
|
||||
connected to the drive no ``FatFS`` access by the Pico is allowed.
|
||||
|
||||
Your ``driveReady`` callback will be called when the PC attempts to mount
|
||||
the drive. If you have any files open, then this callback can report back
|
||||
that the drive is not yet ready. When you complete file processing, the PC
|
||||
can re-attempt to mount the drive and your callback can return ``true`` .
|
||||
|
||||
The ``onPlug`` callback will generally ``FatFS.end()`` and set a
|
||||
global flag letting your application know not to touch the filesystem until
|
||||
the flag is cleared by the ``onUnplug`` callback (which will also do a
|
||||
``FatFS.begin()`` call).
|
||||
|
||||
Failing to close all files **and** ``FatFS.end()`` before granting the
|
||||
PC access to flash memory will result in corruption. FAT does not allow multiple
|
||||
writers to access the same drive. Even mounting and only reading files from
|
||||
the PC may cause hidden writes (things like access time, etc.) which would
|
||||
also cause corruption.
|
||||
|
||||
See the included ``Listfiles-USB`` sketch for an example of working with
|
||||
these limitations.
|
||||
+53
-9
@@ -33,6 +33,7 @@ following include to the sketch:
|
||||
#include "LittleFS.h" // LittleFS is declared
|
||||
// #include <SDFS.h>
|
||||
// #include <SD.h>
|
||||
// #include <FatFS.h>
|
||||
|
||||
|
||||
Compatible Filesystem APIs
|
||||
@@ -48,10 +49,45 @@ SD card reader.
|
||||
SD is the Arduino-supported, somewhat old and limited SD card filesystem.
|
||||
It is recommended to use SDFS for new applications instead of SD.
|
||||
|
||||
All three of these filesystems can open and manipulate ``File`` and ``Dir``
|
||||
FatFS implements a wear-leveled, FTL-backed FAT filesystem in the onboard
|
||||
flash which can be easily accessed over USB as a standard memory stick
|
||||
via FatFSUSB.
|
||||
|
||||
All of these filesystems can open and manipulate ``File`` and ``Dir``
|
||||
objects with the same code because the implement a common end-user
|
||||
filesystem API.
|
||||
|
||||
FatFS File System Caveats and Warnings
|
||||
--------------------------------------
|
||||
|
||||
The FAT filesystem is ubiquitous, but it is also around 50 years old and ill
|
||||
suited to SPI flash memory due to having "hot spots" like the FAT copies that
|
||||
are rewritten many times over. SPI flash allows a high, but limited, number
|
||||
of writes before losing the ability to write safely. Applications like
|
||||
data loggers where many writes occur could end up wearing out the SPI flash
|
||||
sector that holds the FAT **years** before coming close to the write limits of
|
||||
the data sectors.
|
||||
|
||||
To circumvent this issue, the FatFS implementation here uses a flash translation
|
||||
layer (FTL) developed for SPI flash on embedded systems. This allows for the
|
||||
same LBA to be written over and over by the FAT filesystem, but use different
|
||||
flash locations. For more information see
|
||||
[SPIFTL](https://github.com/earlephilhower/SPIFTL). In this mode the Pico
|
||||
flash appears as a normal, 512-byte sector drive to the FAT.
|
||||
|
||||
What this means, practically, is that about 5KB of RAM per megabyte of flash
|
||||
is required for housekeeping. Writes can also become very slow if most of the
|
||||
flash LBA range is used (i.e. if the FAT drive is 99% full) due to the need
|
||||
for garbage collection processes to move data around and preserve the flash
|
||||
lifetime.
|
||||
|
||||
Alternatively, if an FTL is not desired or memory is tight, FatFS can use the
|
||||
raw flash directly. In this mode sectors are 4K in size and flash is mapped
|
||||
1:1 to sectors, so things like the FAT table updates will all use the same
|
||||
physical flash bits. For low-utilization operations this may be fine, but if
|
||||
significant writes are done (from the Pico or the PC host) this may wear out
|
||||
portions of flash very quickly , rendering it unusable.
|
||||
|
||||
LittleFS File System Limitations
|
||||
--------------------------------
|
||||
|
||||
@@ -115,8 +151,8 @@ second SPI port, ``SPI1``. Just use the following call in place of
|
||||
SD.begin(cspin, SPI1);
|
||||
|
||||
|
||||
File system object (LittleFS/SD/SDFS)
|
||||
-------------------------------------
|
||||
File system object (LittleFS/SD/SDFS/FatFS)
|
||||
-------------------------------------------
|
||||
|
||||
setConfig
|
||||
~~~~~~~~~
|
||||
@@ -131,14 +167,22 @@ setConfig
|
||||
c2.setCSPin(12);
|
||||
SDFS.setConfig(c2);
|
||||
|
||||
FatFSConfig c3;
|
||||
c3.setUseFTL(false); // Directly access flash memory
|
||||
c3.setDirEntries(256); // We need 256 root directory entries on a format()
|
||||
c3.setFATCopies(1); // Only 1 FAT to save 4K of space and extra writes
|
||||
FatFS.setConfig(c3);
|
||||
FatFS.format(); // Format using these settings, erasing everything
|
||||
|
||||
This method allows you to configure the parameters of a filesystem
|
||||
before mounting. All filesystems have their own ``*Config`` (i.e.
|
||||
``SDFSConfig`` or ``LittleFSConfig`` with their custom set of options.
|
||||
All filesystems allow explicitly enabling/disabling formatting when
|
||||
mounts fail. If you do not call this ``setConfig`` method before
|
||||
perforing ``begin()``, you will get the filesystem's default
|
||||
behavior and configuration. By default, LittleFS will autoformat the
|
||||
filesystem if it cannot mount it, while SDFS will not.
|
||||
behavior and configuration. By default, LittleFS and FatFS will autoformat the
|
||||
filesystem if it cannot mount it, while SDFS will not. FatFS will also use
|
||||
the built-in FTL to support 512 byte sectors and higher write lifetime.
|
||||
|
||||
begin
|
||||
~~~~~
|
||||
@@ -553,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
|
||||
|
||||
@@ -565,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
|
||||
|
||||
|
||||
@@ -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.
|
||||
+3
-7
@@ -1,15 +1,11 @@
|
||||
IDE Menus
|
||||
=========
|
||||
|
||||
Model
|
||||
Board
|
||||
-----
|
||||
Use the boards menu to select your model of RP2040 board. There will be two
|
||||
options: `Boardname` and `Boardname (Picoprobe)`. If you want to use a
|
||||
Picoprobe to upload your sketches and not the default automatic UF2 upload,
|
||||
use the `(Picoprobe)` option, otherwise use the normal name. No functional
|
||||
or code changes are done because of this.
|
||||
Use the boards menu to select your model of RP2040 board.
|
||||
|
||||
There is also a `Generic` board which allows you to individually select
|
||||
There is also a `Generic RP2040` board which allows you to individually select
|
||||
things such as flash size or boot2 flash type. Use this if your board isn't
|
||||
yet fully supported and isn't working with the normal `Raspberry Pi Pico`
|
||||
option.
|
||||
|
||||
+4
-1
@@ -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>
|
||||
|
||||
|
||||
+12
-2
@@ -37,6 +37,11 @@ Pausing Cores
|
||||
|
||||
Sometimes an application needs to pause the other core on chip (i.e. it is
|
||||
writing to flash or needs to stop processing while some other event occurs).
|
||||
In most cases, however, these calls are **SHOULD NOT BE USED**. To synchronize
|
||||
cross-core operations use normal multiprocessor methods such as circular buffers,
|
||||
global ``volatile`` flags, mutexes, and the like. Stopping a core has massive
|
||||
implications and can kill networking and USB communications if done too long or
|
||||
too frequently.
|
||||
|
||||
void rp2040.idleOtherCore()
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
@@ -69,7 +74,12 @@ Communicating Between Cores
|
||||
The RP2040 provides a hardware FIFO for communicating between cores, but it
|
||||
is used exclusively for the idle/resume calls described above. Instead, please
|
||||
use the following functions to access a software-managed, multicore safe
|
||||
FIFO.
|
||||
FIFO. There are two FIFOs, one written to by core 0 and read by core 1, and
|
||||
the other written to by core 1 and read by core 0.
|
||||
|
||||
You can (and probably should) use shared memory (such as ``volatile`` globals)
|
||||
or other normal multiprocessor communication algorithms to transfer data or
|
||||
work between cores, but for simple tasks these FIFO routines can suffice.
|
||||
|
||||
void rp2040.fifo.push(uint32_t)
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
@@ -96,4 +106,4 @@ Reads a value from this core's FIFO and places it in dest. Will return
|
||||
int rp2040.fifo.available()
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Returns the number of values available in this core's FIFO.
|
||||
Returns the number of values available to read in this core's FIFO.
|
||||
|
||||
+4
-4
@@ -12,7 +12,7 @@ OTA may be done using:
|
||||
- `Arduino IDE <#arduino-ide>`__
|
||||
- `Web Browser <#web-browser>`__
|
||||
- `HTTP Server <#http-server>`__
|
||||
- Any other method (ZModen receive over a UART port, etc.) by using the ``Updater`` object in your sketch
|
||||
- Any other method (ZModem receive over a UART port, etc.) by using the ``Updater`` object in your sketch
|
||||
|
||||
The Arduino IDE option is intended primarily for the software development phase. The other two options would be more useful after deployment, to provide the module with application updates either manually with a web browser, or automatically using an HTTP server.
|
||||
|
||||
@@ -189,7 +189,7 @@ Uploading modules wirelessly from Arduino IDE is intended for the following typi
|
||||
|
||||
To upload wirelessly from the IDE:
|
||||
|
||||
1. Build a sketch starts ``WiFi`` and includes the appropriate calls to ``ArduinoOTA`` (see the examples for reference). These include the ``ArduinoOTA.begin()`` call in ``setup()`` and periodically calling ``ArduinoOTA.handle();`` from the ``loop()``
|
||||
1. Build a sketch that starts ``WiFi`` and includes the appropriate calls to ``ArduinoOTA`` (see the examples for reference). These include the ``ArduinoOTA.begin()`` call in ``setup()`` and periodically calling ``ArduinoOTA.handle();`` from the ``loop()``
|
||||
|
||||
2. Upload using standard USB connection the first time.
|
||||
|
||||
@@ -212,9 +212,9 @@ Before implementing it in your sketch, it is a good idea to check how it works u
|
||||
|
||||
Enter the password and upload should be initiated as usual with the only difference being ``Authenticating...OK`` message visible in the upload log.
|
||||
|
||||
You will not be prompted for a reentering the same password next time. Arduino IDE will remember it for you. You will see a prompt for password only after reopening IDE, or if you change it in your sketch, upload the sketch and then try to upload it again.
|
||||
You will not be prompted for a reentering the same password next time. Arduino IDE will remember it for you. You will see a prompt for password only after reopening the IDE, or if you change it in your sketch, upload the sketch and then try to upload it again.
|
||||
|
||||
Please note, it is possible to reveal password entered previously in Arduino IDE, if IDE has not been closed since last upload. This can be done by enabling *Show verbose output during: upload* in *File > Preferences* and attempting to upload the module.
|
||||
Please note, it is possible to reveal password entered previously in Arduino IDE, if the IDE has not been closed since last upload. This can be done by enabling *Show verbose output during: upload* in *File > Preferences* and attempting to upload the module.
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ To instantiate only a serial transmit or receive unit, pass in
|
||||
``SerialPIO::NOPIN`` as the ``txpin`` or ``rxpin``.
|
||||
|
||||
For example, to make a transmit-only port on GP16
|
||||
|
||||
.. code:: cpp
|
||||
|
||||
SerialPIO transmitter( 16, SerialPIO::NOPIN );
|
||||
|
||||
+37
-5
@@ -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.
|
||||
|
||||
+39
-1
@@ -20,7 +20,45 @@ diagram for your board, or it won't work.
|
||||
Other than that, the API is compatible with the Arduino standard.
|
||||
Both master and slave operation are supported.
|
||||
|
||||
Master transmissions are buffered (up to 128 bytes) and only performed
|
||||
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.
|
||||
|
||||
|
||||
+15
-19
@@ -1,11 +1,9 @@
|
||||
#ifndef _LWIPOPTS_EXAMPLE_COMMONH_H
|
||||
#define _LWIPOPTS_EXAMPLE_COMMONH_H
|
||||
#pragma once
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif // __cplusplus
|
||||
|
||||
|
||||
// Critical section protection
|
||||
extern void noInterrupts();
|
||||
extern void interrupts();
|
||||
@@ -16,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)
|
||||
|
||||
@@ -24,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
|
||||
@@ -40,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
|
||||
@@ -57,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
|
||||
@@ -70,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
|
||||
@@ -108,6 +107,3 @@ extern void __setSystemTime(unsigned long long sec, unsigned long us);
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif // __cplusplus
|
||||
|
||||
|
||||
#endif /* __LWIPOPTS_H__ */
|
||||
|
||||
@@ -3,15 +3,25 @@
|
||||
#######################################
|
||||
|
||||
Arduino KEYWORD3 RESERVED_WORD
|
||||
defined KEYWORD3 RESERVED_WORD
|
||||
|
||||
#######################################
|
||||
# Datatypes (KEYWORD1)
|
||||
#######################################
|
||||
|
||||
Dir KEYWORD1
|
||||
File KEYWORD1
|
||||
timeval KEYWORD1
|
||||
time_t KEYWORD1
|
||||
|
||||
#######################################
|
||||
# Methods and Functions (KEYWORD2)
|
||||
#######################################
|
||||
|
||||
openDir KEYWORD2
|
||||
setConfig KEYWORD2
|
||||
fileCreationTime KEYWORD2
|
||||
|
||||
setup1 KEYWORD2
|
||||
loop1 KEYWORD2
|
||||
|
||||
@@ -61,7 +71,24 @@ digitalReadFast KEYWORD2
|
||||
|
||||
enableDoubleResetBootloader KEYWORD2
|
||||
|
||||
openDir KEYWORD2
|
||||
next KEYWORD2
|
||||
getLastWrite KEYWORD2
|
||||
getCreationTime KEYWORD2
|
||||
fileTime KEYWORD2
|
||||
fileCreationTime KEYWORD2
|
||||
check KEYWORD2
|
||||
setTimeCallback KEYWORD2
|
||||
settimeofday KEYWORD2
|
||||
|
||||
sprintf_P KEYWORD2
|
||||
strcpy_P KEYWORD2
|
||||
snprintf_P KEYWORD2
|
||||
strncpy_P KEYWORD2
|
||||
|
||||
OUTPUT_2MA LITERAL1
|
||||
OUTPUT_4MA LITERAL1
|
||||
OUTPUT_8MA LITERAL1
|
||||
OUTPUT_12MA LITERAL1
|
||||
|
||||
ARDUINO_ARCH_RP2040 LITERAL1
|
||||
|
||||
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.
@@ -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
|
||||
|
||||
Submodule libraries/Adafruit_TinyUSB_Arduino updated: e291865233...c953968c46
@@ -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
+1
Submodule libraries/AsyncUDP added at 9a718fb3dc
@@ -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]);
|
||||
|
||||
@@ -526,6 +526,10 @@ const gatt_client_characteristic_t * BLECharacteristic::getCharacteristic(void)
|
||||
return &characteristic;
|
||||
}
|
||||
|
||||
gatt_client_notification_t *BLECharacteristic::getNotifier() {
|
||||
return ¬ify;
|
||||
}
|
||||
|
||||
|
||||
BLEService::BLEService(void) {
|
||||
}
|
||||
@@ -703,6 +707,7 @@ int BTstackManager::writeCharacteristicWithoutResponse(BLEDevice * device, BLEC
|
||||
}
|
||||
int BTstackManager::subscribeForNotifications(BLEDevice * device, BLECharacteristic * characteristic) {
|
||||
gattAction = gattActionSubscribe;
|
||||
gatt_client_listen_for_characteristic_value_updates(characteristic->getNotifier(), gatt_client_callback, device->getHandle(), (gatt_client_characteristic_t*) characteristic->getCharacteristic());
|
||||
return gatt_client_write_client_characteristic_configuration(gatt_client_callback, device->getHandle(), (gatt_client_characteristic_t*) characteristic->getCharacteristic(),
|
||||
GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION);
|
||||
}
|
||||
@@ -713,6 +718,7 @@ int BTstackManager::subscribeForIndications(BLEDevice * device, BLECharacteristi
|
||||
}
|
||||
int BTstackManager::unsubscribeFromNotifications(BLEDevice * device, BLECharacteristic * characteristic) {
|
||||
gattAction = gattActionUnsubscribe;
|
||||
gatt_client_stop_listening_for_characteristic_value_updates(characteristic->getNotifier());
|
||||
return gatt_client_write_client_characteristic_configuration(gatt_client_callback, device->getHandle(), (gatt_client_characteristic_t*) characteristic->getCharacteristic(),
|
||||
GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NONE);
|
||||
}
|
||||
@@ -808,9 +814,6 @@ void BTstackManager::setup(const char * name) {
|
||||
hci_add_event_handler(&hci_event_callback_registration);
|
||||
l2cap_init();
|
||||
|
||||
// setup central device db
|
||||
le_device_db_init();
|
||||
|
||||
sm_init();
|
||||
|
||||
att_server_init(att_db_util_get_address(), att_read_callback, att_write_callback);
|
||||
@@ -889,6 +892,9 @@ uint16_t BTstackManager::addGATTCharacteristicDynamic(UUID * uuid, uint16_t flag
|
||||
void BTstackManager::setAdvData(uint16_t adv_data_len, const uint8_t * adv_data) {
|
||||
gap_advertisements_set_data(adv_data_len, (uint8_t*) adv_data);
|
||||
}
|
||||
void BTstackManager::setScanData(uint16_t scan_data_len, const uint8_t * scan_data) {
|
||||
gap_scan_response_set_data(scan_data_len, (uint8_t*) scan_data);
|
||||
}
|
||||
void BTstackManager::startAdvertising() {
|
||||
gap_advertisements_enable(1);
|
||||
}
|
||||
|
||||
@@ -84,6 +84,7 @@ extern "C" {
|
||||
|
||||
class BLECharacteristic {
|
||||
private:
|
||||
gatt_client_notification_t notify;
|
||||
gatt_client_characteristic_t characteristic;
|
||||
UUID uuid;
|
||||
public:
|
||||
@@ -93,6 +94,7 @@ extern "C" {
|
||||
bool matches(UUID * uuid);
|
||||
bool isValueHandle(uint16_t value_handle);
|
||||
const gatt_client_characteristic_t * getCharacteristic();
|
||||
gatt_client_notification_t *getNotifier();
|
||||
};
|
||||
|
||||
class BLEService {
|
||||
@@ -143,6 +145,7 @@ extern "C" {
|
||||
void enableDebugLogger();
|
||||
|
||||
void setAdvData(uint16_t size, const uint8_t * data);
|
||||
void setScanData(uint16_t size, const uint8_t * data);
|
||||
void iBeaconConfigure(UUID * uuid, uint16_t major_id, uint16_t minor_id, uint8_t measured_power = 0xc6);
|
||||
void startAdvertising();
|
||||
void stopAdvertising();
|
||||
|
||||
@@ -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
@@ -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
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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];
|
||||
};
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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)
|
||||
#######################################
|
||||
@@ -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];
|
||||
};
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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] = "";
|
||||
|
||||
|
||||
+1
-1
Submodule libraries/ESP8266SdFat updated: 255180be14...c6b7f4a6fb
@@ -0,0 +1,24 @@
|
||||
#######################################
|
||||
# Syntax Coloring Map
|
||||
#######################################
|
||||
|
||||
#######################################
|
||||
# Datatypes (KEYWORD1)
|
||||
#######################################
|
||||
|
||||
FatFS KEYWORD1
|
||||
|
||||
#######################################
|
||||
# Methods and Functions (KEYWORD2)
|
||||
#######################################
|
||||
|
||||
format KEYWORD2
|
||||
FatFSConfig KEYWORD2
|
||||
setUseFTL KEYWORD2
|
||||
setDirEntries KEYWORD2
|
||||
setFATCopies KEYWORD2
|
||||
|
||||
#######################################
|
||||
# Constants (LITERAL1)
|
||||
#######################################
|
||||
|
||||
Submodule
+1
Submodule libraries/FatFS/lib/SPIFTL added at 3016627c3f
@@ -0,0 +1,24 @@
|
||||
FatFs License
|
||||
|
||||
FatFs has being developped as a personal project of the author, ChaN. It is free from the code anyone else wrote at current release. Following code block shows a copy of the FatFs license document that heading the source files.
|
||||
|
||||
/*----------------------------------------------------------------------------/
|
||||
/ FatFs - Generic FAT Filesystem Module Rx.xx /
|
||||
/-----------------------------------------------------------------------------/
|
||||
/
|
||||
/ Copyright (C) 20xx, ChaN, all right reserved.
|
||||
/
|
||||
/ FatFs module is an open source software. Redistribution and use of FatFs in
|
||||
/ source and binary forms, with or without modification, are permitted provided
|
||||
/ that the following condition is met:
|
||||
/
|
||||
/ 1. Redistributions of source code must retain the above copyright notice,
|
||||
/ this condition and the following disclaimer.
|
||||
/
|
||||
/ This software is provided by the copyright holder and contributors "AS IS"
|
||||
/ and any warranties related to this software are DISCLAIMED.
|
||||
/ The copyright owner or contributors be NOT LIABLE for any damages caused
|
||||
/ by use of this software.
|
||||
/----------------------------------------------------------------------------*/
|
||||
|
||||
Therefore FatFs license is one of the BSD-style licenses, but there is a significant feature. FatFs is mainly intended for embedded systems. In order to extend the usability for commercial products, the redistributions of FatFs in binary form, such as embedded code, binary library and any forms without source code, do not need to include about FatFs in the documentations. This is equivalent to the 1-clause BSD license. Of course FatFs is compatible with the most of open source software licenses include GNU GPL. When you redistribute the FatFs source code with changes or create a fork, the license can also be changed to GNU GPL, BSD-style license or any open source software license that not conflict with FatFs license.
|
||||
@@ -0,0 +1 @@
|
||||
FatFS home at http://elm-chan.org/fsw/ff/
|
||||
@@ -0,0 +1,10 @@
|
||||
name=FatFS
|
||||
version=0.15.0
|
||||
author=Earle F. Philhower, III <earlephilhower@yahoo.com>
|
||||
maintainer=Earle F. Philhower, III <earlephilhower@yahoo.com>
|
||||
sentence=FS filesystem for use on flash using ChaN's FatFS code
|
||||
paragraph=FS filesystem for use on flash using ChaN's FatFS code
|
||||
category=Data Storage
|
||||
url=https://github.com/earlephilhower/arduino-pico
|
||||
architectures=rp2040
|
||||
dot_a_linkage=true
|
||||
@@ -0,0 +1,310 @@
|
||||
/*
|
||||
FatFS.cpp - file system wrapper for FatFS
|
||||
Copyright (c) 2024 Earle F. Philhower, III. All rights reserved.
|
||||
|
||||
Based on spiffs_api.cpp which is:
|
||||
| Copyright (c) 2015 Ivan Grokhotkov. All rights reserved.
|
||||
|
||||
This code was influenced by NodeMCU and Sming libraries, and first version of
|
||||
Arduino wrapper written by Hristo Gochkov.
|
||||
|
||||
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 "FatFS.h"
|
||||
#include <FS.h>
|
||||
//#define FTL_DEBUG 1
|
||||
#include "../lib/SPIFTL/FlashInterfaceRP2040.h"
|
||||
#include "../lib/SPIFTL/SPIFTL.h"
|
||||
|
||||
using namespace fs;
|
||||
|
||||
|
||||
#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_FATFS)
|
||||
extern uint8_t _FS_start;
|
||||
extern uint8_t _FS_end;
|
||||
|
||||
FS FatFS = FS(FSImplPtr(new fatfs::FatFSImpl()));
|
||||
static FlashInterfaceRP2040 *_fi = new FlashInterfaceRP2040(&_FS_start, &_FS_end);
|
||||
static SPIFTL *_ftl = nullptr;
|
||||
uint16_t _sectorSize = 512;
|
||||
#endif
|
||||
|
||||
namespace fatfs {
|
||||
|
||||
|
||||
bool FatFSImpl::begin() {
|
||||
if (_mounted) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (_cfg._useFTL) {
|
||||
if (!_ftl) {
|
||||
_ftl = new SPIFTL(_fi);
|
||||
}
|
||||
_sectorSize = 512;
|
||||
} else {
|
||||
_sectorSize = 4096;
|
||||
if (_ftl) {
|
||||
delete _ftl;
|
||||
_ftl = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
_mounted = (FR_OK == f_mount(&_fatfs, "", 1));
|
||||
if (!_mounted && _cfg._autoFormat) {
|
||||
format();
|
||||
_mounted = (FR_OK == f_mount(&_fatfs, "", 1));
|
||||
}
|
||||
//FsDateTime::setCallback(dateTimeCB); TODO = callback
|
||||
return _mounted;
|
||||
}
|
||||
|
||||
void FatFSImpl::end() {
|
||||
if (_mounted) {
|
||||
f_unmount("");
|
||||
}
|
||||
sync();
|
||||
_mounted = false;
|
||||
}
|
||||
|
||||
|
||||
// Required to be global because SDFAT doesn't allow a this pointer in it's own time call
|
||||
time_t (*__fatfs_timeCallback)(void) = nullptr;
|
||||
|
||||
FileImplPtr FatFSImpl::open(const char* path, OpenMode openMode, AccessMode accessMode) {
|
||||
if (!_mounted) {
|
||||
DEBUGV("FatFSImpl::open() called on unmounted FS\n");
|
||||
return FileImplPtr();
|
||||
}
|
||||
if (!path || !path[0]) {
|
||||
DEBUGV("FatFSImpl::open() called with invalid filename\n");
|
||||
return FileImplPtr();
|
||||
}
|
||||
BYTE flags = _getFlags(openMode, accessMode);
|
||||
if ((openMode && OM_CREATE) && strchr(path, '/')) {
|
||||
// For file creation, silently make subdirs as needed. If any fail,
|
||||
// it will be caught by the real file open later on
|
||||
char *pathStr = strdup(path);
|
||||
if (pathStr) {
|
||||
// Make dirs up to the final fnamepart
|
||||
char *ptr = strrchr(pathStr, '/');
|
||||
if (ptr && ptr != pathStr) { // Don't try to make root dir!
|
||||
*ptr = 0;
|
||||
f_mkdir(pathStr);
|
||||
}
|
||||
}
|
||||
free(pathStr);
|
||||
}
|
||||
auto sharedFd = std::make_shared<FIL>();
|
||||
if (FR_OK == f_open(sharedFd.get(), path, flags)) {
|
||||
return std::make_shared<FatFSFileImpl>(this, sharedFd, path, FA_WRITE & flags ? true : false);
|
||||
}
|
||||
sharedFd = nullptr;
|
||||
DEBUGV("FatFSImpl::openFile: path=`%s` openMode=%d accessMode=%d FAILED", path, openMode, accessMode);
|
||||
return FileImplPtr();
|
||||
}
|
||||
|
||||
DirImplPtr FatFSImpl::openDir(const char* path) {
|
||||
if (!_mounted) {
|
||||
return DirImplPtr();
|
||||
}
|
||||
char *pathStr = strdup(path); // Allow edits on our scratch copy
|
||||
if (!pathStr) {
|
||||
// OOM
|
||||
return DirImplPtr();
|
||||
}
|
||||
// Get rid of any trailing slashes
|
||||
while (strlen(pathStr) && (pathStr[strlen(pathStr) - 1] == '/')) {
|
||||
pathStr[strlen(pathStr) - 1] = 0;
|
||||
}
|
||||
// At this point we have a name of "/blah/blah/blah" or "blah" or ""
|
||||
// If that references a directory, just open it and we're done.
|
||||
DIR dirFile;
|
||||
FILINFO fno;
|
||||
const char *filter = "";
|
||||
if (!pathStr[0]) {
|
||||
// openDir("") === openDir("/")
|
||||
f_opendir(&dirFile, "/");
|
||||
filter = "";
|
||||
} else if (FR_OK == f_stat(pathStr, &fno)) {
|
||||
if (fno.fattrib & AM_DIR) {
|
||||
// Easy peasy, path specifies an existing dir!
|
||||
f_opendir(&dirFile, pathStr);
|
||||
filter = "";
|
||||
} else {
|
||||
// This is a file, so open the containing dir
|
||||
char *ptr = strrchr(pathStr, '/');
|
||||
if (!ptr) {
|
||||
// No slashes, open the root dir
|
||||
f_opendir(&dirFile, "/");
|
||||
filter = pathStr;
|
||||
} else {
|
||||
// We've got slashes, open the dir one up
|
||||
*ptr = 0; // Remove slash, truncare string
|
||||
f_opendir(&dirFile, pathStr);
|
||||
filter = ptr + 1;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Name doesn't exist, so use the parent dir of whatever was sent in
|
||||
// This is a file, so open the containing dir
|
||||
char *ptr = strrchr(pathStr, '/');
|
||||
if (!ptr) {
|
||||
// No slashes, open the root dir
|
||||
f_opendir(&dirFile, "/");
|
||||
filter = pathStr;
|
||||
} else {
|
||||
// We've got slashes, open the dir one up
|
||||
*ptr = 0; // Remove slash, truncare string
|
||||
f_opendir(&dirFile, pathStr);
|
||||
filter = ptr + 1;
|
||||
}
|
||||
}
|
||||
// TODO -can this ever happen?
|
||||
// if (!dirFile) {
|
||||
// DEBUGV("FatFSImpl::openDir: path=`%s`\n", path);
|
||||
// return DirImplPtr();
|
||||
// }
|
||||
auto sharedDir = std::make_shared<DIR>(dirFile);
|
||||
auto ret = std::make_shared<FatFSDirImpl>(filter, this, sharedDir, pathStr);
|
||||
free(pathStr);
|
||||
return ret;
|
||||
}
|
||||
|
||||
bool FatFSImpl::format() {
|
||||
if (_mounted) {
|
||||
return false;
|
||||
}
|
||||
BYTE *work = new BYTE[4096]; /* Work area (larger is better for processing time) */
|
||||
MKFS_PARM opt = { FM_FAT | FM_SFD, _cfg._fatCopies, 1, _sectorSize, _cfg._dirEntries};
|
||||
auto ret = f_mkfs("", &opt, work, 4096);
|
||||
delete[] work;
|
||||
|
||||
return ret == FR_OK;
|
||||
}
|
||||
|
||||
DSTATUS disk_status(BYTE p) {
|
||||
(void) p;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static bool started = false;
|
||||
|
||||
void disk_format() {
|
||||
if (!started && _ftl) {
|
||||
_ftl->format();
|
||||
}
|
||||
}
|
||||
|
||||
DSTATUS disk_initialize(BYTE p) {
|
||||
(void) p;
|
||||
if (!started) {
|
||||
if (_ftl) {
|
||||
_ftl->start();
|
||||
}
|
||||
started = true;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
DRESULT disk_read(BYTE p, BYTE *buff, LBA_t sect, UINT count) {
|
||||
(void) p;
|
||||
for (unsigned int i = 0; i < count; i++) {
|
||||
if (_ftl) {
|
||||
_ftl->read(sect + i, buff + i * _sectorSize);
|
||||
} else {
|
||||
_fi->read(sect + i, 0, buff, _sectorSize);
|
||||
}
|
||||
}
|
||||
return RES_OK;
|
||||
}
|
||||
|
||||
DRESULT disk_write(BYTE pdrv, const BYTE* buff, LBA_t sector, UINT count) {
|
||||
(void) pdrv;
|
||||
for (unsigned int i = 0; i < count; i++) {
|
||||
if (_ftl) {
|
||||
_ftl->write(sector + i, buff + i * _sectorSize);
|
||||
} else {
|
||||
_fi->eraseBlock(sector + i);
|
||||
_fi->program(sector + i, 0, buff + i * _sectorSize, _sectorSize);
|
||||
}
|
||||
}
|
||||
return RES_OK;
|
||||
}
|
||||
|
||||
DRESULT disk_ioctl(BYTE pdrv, BYTE cmd, void* buff) {
|
||||
(void) pdrv;
|
||||
switch (cmd) {
|
||||
case CTRL_SYNC:
|
||||
if (_ftl) {
|
||||
_ftl->persist();
|
||||
}
|
||||
return RES_OK;
|
||||
case GET_SECTOR_COUNT: {
|
||||
LBA_t *p = (LBA_t *)buff;
|
||||
if (_ftl) {
|
||||
*p = _ftl->lbaCount();
|
||||
} else {
|
||||
*p = _fi->size() / 4096;
|
||||
}
|
||||
return RES_OK;
|
||||
}
|
||||
case GET_SECTOR_SIZE: {
|
||||
WORD *w = (WORD *)buff;
|
||||
*w = _sectorSize;
|
||||
return RES_OK;
|
||||
}
|
||||
case GET_BLOCK_SIZE: {
|
||||
DWORD *dw = (DWORD *)buff;
|
||||
*dw = _sectorSize;
|
||||
return RES_OK;
|
||||
}
|
||||
case CTRL_TRIM: {
|
||||
LBA_t *lba = (LBA_t *)buff;
|
||||
for (unsigned int i = lba[0]; i < lba[1]; i++) {
|
||||
if (_ftl) {
|
||||
_ftl->trim(i);
|
||||
} else {
|
||||
_fi->eraseBlock(i);
|
||||
}
|
||||
}
|
||||
return RES_OK;
|
||||
}
|
||||
default:
|
||||
return RES_PARERR;
|
||||
}
|
||||
}
|
||||
|
||||
DWORD get_fattime() {
|
||||
time_t now;
|
||||
if (fatfs::__fatfs_timeCallback) {
|
||||
now = fatfs::__fatfs_timeCallback();
|
||||
} else {
|
||||
now = time(nullptr);
|
||||
}
|
||||
struct tm *stm = localtime(&now);
|
||||
if (stm->tm_year < 80) {
|
||||
// FAT can't report years before 1980
|
||||
stm->tm_year = 80;
|
||||
}
|
||||
return (DWORD)(stm->tm_year - 80) << 25 |
|
||||
(DWORD)(stm->tm_mon + 1) << 21 |
|
||||
(DWORD)stm->tm_mday << 16 |
|
||||
(DWORD)stm->tm_hour << 11 |
|
||||
(DWORD)stm->tm_min << 5 |
|
||||
(DWORD)stm->tm_sec >> 1;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,470 @@
|
||||
/*
|
||||
FatFS.h - File system wrapper for FatFS
|
||||
Copyright (c) 2024 Earle F. Philhower, III. All rights reserved.
|
||||
|
||||
Based on spiffs_api.h, which is:
|
||||
| Copyright (c) 2015 Ivan Grokhotkov. All rights reserved.
|
||||
|
||||
This code was influenced by NodeMCU and Sming libraries, and first version of
|
||||
Arduino wrapper written by Hristo Gochkov.
|
||||
|
||||
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 <limits>
|
||||
#include <assert.h>
|
||||
#include "FS.h"
|
||||
#include "FSImpl.h"
|
||||
#include "./ff.h"
|
||||
#include "./diskio.h"
|
||||
#include <FS.h>
|
||||
|
||||
using namespace fs;
|
||||
|
||||
namespace fatfs {
|
||||
|
||||
class FatFSFileImpl;
|
||||
class FatFSDirImpl;
|
||||
class FatFSConfig : public FSConfig {
|
||||
public:
|
||||
static constexpr uint32_t FSId = 0x46617446;
|
||||
|
||||
FatFSConfig(bool autoFormat = true, bool useFTL = true, int dirEntries = 128, int fatCopies = 1) : FSConfig(FSId, autoFormat), _useFTL(useFTL), _dirEntries(dirEntries), _fatCopies(fatCopies) { }
|
||||
|
||||
FatFSConfig setUseFTL(bool val = true) {
|
||||
_useFTL = val;
|
||||
return *this;
|
||||
}
|
||||
|
||||
FatFSConfig setDirEntries(int entries) {
|
||||
_dirEntries = entries;
|
||||
return *this;
|
||||
}
|
||||
|
||||
FatFSConfig setFATCopies(int copies) {
|
||||
_fatCopies = copies;
|
||||
return *this;
|
||||
}
|
||||
|
||||
bool _useFTL;
|
||||
uint16_t _dirEntries;
|
||||
uint8_t _fatCopies;
|
||||
};
|
||||
|
||||
class FatFSImpl : public FSImpl {
|
||||
public:
|
||||
FatFSImpl() : _mounted(false) {
|
||||
}
|
||||
|
||||
FileImplPtr open(const char* path, OpenMode openMode, AccessMode accessMode) override;
|
||||
|
||||
bool exists(const char* path) override {
|
||||
if (_mounted) {
|
||||
FILINFO fi;
|
||||
if (FR_OK == f_stat(path, &fi)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
DirImplPtr openDir(const char* path) override;
|
||||
|
||||
bool rename(const char* pathFrom, const char* pathTo) override {
|
||||
return _mounted ? (FR_OK == f_rename(pathFrom, pathTo)) : false;
|
||||
}
|
||||
|
||||
bool info64(FSInfo64& info) override {
|
||||
if (!_mounted) {
|
||||
DEBUGV("FatFS::info: FS not mounted\n");
|
||||
return false;
|
||||
}
|
||||
FATFS *fs = nullptr;
|
||||
DWORD fre_clust = 0;
|
||||
f_getfree("", &fre_clust, &fs);
|
||||
info.maxOpenFiles = 999; // TODO - not valid
|
||||
info.blockSize = 512 * fs->csize;
|
||||
info.pageSize = 0; // TODO ?
|
||||
info.maxPathLength = 255; // TODO ?
|
||||
info.totalBytes = (uint64_t)(fs->n_fatent - 2) * (uint64_t)fs->csize * 512;
|
||||
info.usedBytes = info.totalBytes - (uint64_t)fre_clust * fs->csize * 512;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool info(FSInfo& info) override {
|
||||
FSInfo64 i;
|
||||
if (!info64(i)) {
|
||||
return false;
|
||||
}
|
||||
info.blockSize = i.blockSize;
|
||||
info.pageSize = i.pageSize;
|
||||
info.maxOpenFiles = i.maxOpenFiles;
|
||||
info.maxPathLength = i.maxPathLength;
|
||||
info.totalBytes = (size_t)i.totalBytes;
|
||||
info.usedBytes = (size_t)i.usedBytes;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool remove(const char* path) override {
|
||||
return _mounted ? (FR_OK == f_unlink(path)) : false;
|
||||
}
|
||||
|
||||
bool mkdir(const char* path) override {
|
||||
return _mounted ? (FR_OK == f_mkdir(path)) : false;
|
||||
}
|
||||
|
||||
bool rmdir(const char* path) override {
|
||||
return _mounted ? (FR_OK == f_unlink(path)) : false;
|
||||
}
|
||||
|
||||
bool setConfig(const FSConfig &cfg) override {
|
||||
if ((cfg._type != FatFSConfig::FSId) || _mounted) {
|
||||
DEBUGV("FatFS::setConfig: invalid config or already mounted\n");
|
||||
return false;
|
||||
}
|
||||
_cfg = *static_cast<const FatFSConfig *>(&cfg);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool begin() override;
|
||||
void end() override;
|
||||
bool format() override;
|
||||
|
||||
// Helper function, takes FAT and makes standard time_t
|
||||
static time_t FatToTimeT(uint16_t d, uint16_t t) {
|
||||
struct tm tiempo;
|
||||
memset(&tiempo, 0, sizeof(tiempo));
|
||||
tiempo.tm_sec = (((int)t) << 1) & 0x3e;
|
||||
tiempo.tm_min = (((int)t) >> 5) & 0x3f;
|
||||
tiempo.tm_hour = (((int)t) >> 11) & 0x1f;
|
||||
tiempo.tm_mday = (int)(d & 0x1f);
|
||||
tiempo.tm_mon = ((int)(d >> 5) & 0x0f) - 1;
|
||||
tiempo.tm_year = ((int)(d >> 9) & 0x7f) + 80;
|
||||
tiempo.tm_isdst = -1;
|
||||
return mktime(&tiempo);
|
||||
}
|
||||
|
||||
virtual void setTimeCallback(time_t (*cb)(void)) override {
|
||||
extern time_t (*__fatfs_timeCallback)(void);
|
||||
__fatfs_timeCallback = cb;
|
||||
}
|
||||
|
||||
void sync() {
|
||||
disk_ioctl(0, CTRL_SYNC, nullptr);
|
||||
}
|
||||
|
||||
protected:
|
||||
friend class FatFileImpl;
|
||||
friend class FatFSDirImpl;
|
||||
|
||||
FATFS* getFs() {
|
||||
return &_fatfs;
|
||||
}
|
||||
|
||||
static int _getFlags(OpenMode openMode, AccessMode accessMode) {
|
||||
int mode = 0;
|
||||
if (openMode & OM_CREATE) {
|
||||
mode |= FA_CREATE_ALWAYS;
|
||||
}
|
||||
if (openMode & OM_APPEND) {
|
||||
mode |= FA_OPEN_APPEND;
|
||||
}
|
||||
if (openMode & OM_TRUNCATE) {
|
||||
mode |= 0; // TODO - no truncate?
|
||||
}
|
||||
if ((accessMode & (AM_READ | AM_WRITE)) == (AM_READ | AM_WRITE)) {
|
||||
mode |= FA_READ | FA_WRITE;
|
||||
} else if (accessMode & AM_READ) {
|
||||
mode |= FA_READ;
|
||||
} else if (accessMode & AM_WRITE) {
|
||||
mode |= FA_WRITE;
|
||||
}
|
||||
return mode;
|
||||
}
|
||||
|
||||
FATFS _fatfs;
|
||||
FatFSConfig _cfg;
|
||||
bool _mounted;
|
||||
};
|
||||
|
||||
|
||||
class FatFSFileImpl : public FileImpl {
|
||||
public:
|
||||
FatFSFileImpl(FatFSImpl *fs, std::shared_ptr<FIL> fd, const char *name, bool writable)
|
||||
: _fs(fs), _fd(fd), _opened(true), _writable(writable) {
|
||||
_name = std::shared_ptr<char>(new char[strlen(name) + 1], std::default_delete<char[]>());
|
||||
strcpy(_name.get(), name);
|
||||
}
|
||||
|
||||
~FatFSFileImpl() override {
|
||||
flush();
|
||||
close();
|
||||
}
|
||||
|
||||
int availableForWrite() override {
|
||||
return 1; // TODO - not implemented? _opened ? _fd->availableSpaceForWrite() : 0;
|
||||
}
|
||||
|
||||
size_t write(const uint8_t *buf, size_t size) override {
|
||||
if (_opened) {
|
||||
UINT bw;
|
||||
if (FR_OK == f_write(_fd.get(), buf, size, &bw)) {
|
||||
return bw;
|
||||
}
|
||||
}
|
||||
return -1; // some kind of error
|
||||
}
|
||||
|
||||
int read(uint8_t* buf, size_t size) override {
|
||||
if (_opened) {
|
||||
UINT bw;
|
||||
if (FR_OK == f_read(_fd.get(), buf, size, &bw)) {
|
||||
return bw;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
void flush() override {
|
||||
if (_opened) {
|
||||
f_sync(_fd.get());
|
||||
if (_writable) {
|
||||
_fs->sync();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool seek(uint32_t pos, SeekMode mode) override {
|
||||
if (!_opened) {
|
||||
return false;
|
||||
}
|
||||
switch (mode) {
|
||||
case SeekSet:
|
||||
return FR_OK == f_lseek(_fd.get(), pos);
|
||||
case SeekEnd:
|
||||
return FR_OK == f_lseek(_fd.get(), f_size(_fd.get()) - pos); // TODO again, odd from POSIX
|
||||
case SeekCur:
|
||||
return FR_OK == f_lseek(_fd.get(), f_tell(_fd.get()) + pos);
|
||||
default:
|
||||
// Should not be hit, we've got an invalid seek mode
|
||||
DEBUGV("FatFSFileImpl::seek: invalid seek mode %d\n", mode);
|
||||
assert((mode == SeekSet) || (mode == SeekEnd) || (mode == SeekCur)); // Will fail and give meaningful assert message
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
size_t position() const override {
|
||||
return _opened ? f_tell(_fd.get()) : 0;
|
||||
}
|
||||
|
||||
size_t size() const override {
|
||||
return _opened ? f_size(_fd.get()) : 0;
|
||||
}
|
||||
|
||||
bool truncate(uint32_t size) override {
|
||||
if (!_opened) {
|
||||
DEBUGV("FatFSFileImpl::truncate: file not opened\n");
|
||||
return false;
|
||||
}
|
||||
if (FR_OK == f_lseek(_fd.get(), size)) {
|
||||
return FR_OK == f_truncate(_fd.get());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void close() override {
|
||||
if (_opened) {
|
||||
f_close(_fd.get());
|
||||
// f_close does a disk_sync
|
||||
_opened = false;
|
||||
}
|
||||
}
|
||||
|
||||
const char* name() const override {
|
||||
if (!_opened) {
|
||||
DEBUGV("FatFSFileImpl::name: file not opened\n");
|
||||
return nullptr;
|
||||
} else {
|
||||
const char *p = _name.get();
|
||||
const char *slash = strrchr(p, '/');
|
||||
// For names w/o any path elements, return directly
|
||||
// If there are slashes, return name after the last slash
|
||||
// (note that strrchr will return the address of the slash,
|
||||
// so need to increment to ckip it)
|
||||
return (slash && slash[1]) ? slash + 1 : p;
|
||||
}
|
||||
}
|
||||
|
||||
const char* fullName() const override {
|
||||
return _opened ? _name.get() : nullptr;
|
||||
}
|
||||
|
||||
bool isFile() const override {
|
||||
if (_opened) {
|
||||
FILINFO fno;
|
||||
if (FR_OK == f_stat(_name.get(), &fno)) {
|
||||
return (fno.fattrib & AM_DIR) ? false : true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool isDirectory() const override {
|
||||
if (_opened) {
|
||||
FILINFO fno;
|
||||
if (FR_OK == f_stat(_name.get(), &fno)) {
|
||||
return (fno.fattrib & AM_DIR) ? true : false;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
time_t getLastWrite() override {
|
||||
return getCreationTime(); // TODO - FatFS doesn't seem to report both filetimes
|
||||
}
|
||||
|
||||
time_t getCreationTime() override {
|
||||
time_t ftime = 0;
|
||||
if (_opened && _fd) {
|
||||
FILINFO fno;
|
||||
if (FR_OK == f_stat(_name.get(), &fno)) {
|
||||
ftime = FatFSImpl::FatToTimeT(fno.fdate, fno.ftime);
|
||||
}
|
||||
}
|
||||
return ftime;
|
||||
}
|
||||
|
||||
protected:
|
||||
FatFSImpl* _fs;
|
||||
std::shared_ptr<FIL> _fd;
|
||||
std::shared_ptr<char> _name;
|
||||
bool _opened;
|
||||
bool _writable;
|
||||
};
|
||||
|
||||
class FatFSDirImpl : public DirImpl {
|
||||
public:
|
||||
FatFSDirImpl(const String& pattern, FatFSImpl* fs, std::shared_ptr<DIR> dir, const char *dirPath = nullptr)
|
||||
: _pattern(pattern), _fs(fs), _dir(dir), _valid(false), _dirPath(nullptr) {
|
||||
if (dirPath) {
|
||||
_dirPath = std::shared_ptr<char>(new char[strlen(dirPath) + 1], std::default_delete<char[]>());
|
||||
strcpy(_dirPath.get(), dirPath);
|
||||
}
|
||||
f_opendir(dir.get(), dirPath);
|
||||
}
|
||||
|
||||
~FatFSDirImpl() override {
|
||||
if (_dir) {
|
||||
f_closedir(_dir.get());
|
||||
}
|
||||
}
|
||||
|
||||
FileImplPtr openFile(OpenMode openMode, AccessMode accessMode) override {
|
||||
if (!_valid) {
|
||||
return FileImplPtr();
|
||||
}
|
||||
// MAX_PATH on FAT32 is potentially 260 bytes per most implementations
|
||||
char tmpName[260];
|
||||
snprintf(tmpName, sizeof(tmpName), "%s%s%s", _dirPath.get() ? _dirPath.get() : "", _dirPath.get() && _dirPath.get()[0] ? "/" : "", _lfn);
|
||||
return _fs->open((const char *)tmpName, openMode, accessMode);
|
||||
}
|
||||
|
||||
const char* fileName() override {
|
||||
if (!_valid) {
|
||||
DEBUGV("FatFSDirImpl::fileName: directory not valid\n");
|
||||
return nullptr;
|
||||
}
|
||||
return (const char*) _lfn; //_dirent.name;
|
||||
}
|
||||
|
||||
size_t fileSize() override {
|
||||
if (!_valid) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return _size;
|
||||
}
|
||||
|
||||
time_t fileTime() override {
|
||||
if (!_valid) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return _time;
|
||||
}
|
||||
|
||||
time_t fileCreationTime() override {
|
||||
if (!_valid) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return _creation;
|
||||
}
|
||||
|
||||
bool isFile() const override {
|
||||
return _valid ? _isFile : false;
|
||||
}
|
||||
|
||||
bool isDirectory() const override {
|
||||
return _valid ? _isDirectory : false;
|
||||
}
|
||||
|
||||
bool next() override {
|
||||
const int n = _pattern.length();
|
||||
do {
|
||||
FILINFO fno;
|
||||
if (FR_OK == f_readdir(_dir.get(), &fno) && fno.fname[0]) {
|
||||
_valid = true;
|
||||
_size = fno.fsize;
|
||||
_isFile = fno.fattrib & AM_DIR ? false : true;
|
||||
_isDirectory = !_isFile;
|
||||
_time = FatFSImpl::FatToTimeT(fno.fdate, fno.ftime);
|
||||
_creation = _time;
|
||||
strncpy(_lfn, fno.fname, sizeof(_lfn));
|
||||
} else {
|
||||
_valid = false;
|
||||
}
|
||||
} while (_valid && strncmp((const char*) _lfn, _pattern.c_str(), n) != 0);
|
||||
return _valid;
|
||||
}
|
||||
|
||||
bool rewind() override {
|
||||
_valid = false;
|
||||
return FR_OK == f_rewinddir(_dir.get());
|
||||
return false;
|
||||
}
|
||||
|
||||
protected:
|
||||
String _pattern;
|
||||
FatFSImpl* _fs;
|
||||
std::shared_ptr<DIR> _dir;
|
||||
bool _valid;
|
||||
char _lfn[64];
|
||||
time_t _time;
|
||||
time_t _creation;
|
||||
std::shared_ptr<char> _dirPath;
|
||||
uint32_t _size;
|
||||
bool _isFile;
|
||||
bool _isDirectory;
|
||||
};
|
||||
|
||||
}; // namespace sdfs
|
||||
|
||||
#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_FATFS)
|
||||
extern FS FatFS;
|
||||
using fatfs::FatFSConfig;
|
||||
#endif
|
||||
@@ -0,0 +1,81 @@
|
||||
/* -----------------------------------------------------------------------/
|
||||
/ Low level disk interface modlue include file (C)ChaN, 2019 /
|
||||
/-----------------------------------------------------------------------*/
|
||||
|
||||
#ifndef _DISKIO_DEFINED
|
||||
#define _DISKIO_DEFINED
|
||||
|
||||
//#ifdef __cplusplus
|
||||
//extern "C" {
|
||||
//#endif
|
||||
|
||||
namespace fatfs {
|
||||
|
||||
/* Status of Disk Functions */
|
||||
typedef BYTE DSTATUS;
|
||||
|
||||
/* Results of Disk Functions */
|
||||
typedef enum {
|
||||
RES_OK = 0, /* 0: Successful */
|
||||
RES_ERROR, /* 1: R/W Error */
|
||||
RES_WRPRT, /* 2: Write Protected */
|
||||
RES_NOTRDY, /* 3: Not Ready */
|
||||
RES_PARERR /* 4: Invalid Parameter */
|
||||
} DRESULT;
|
||||
|
||||
|
||||
/*---------------------------------------*/
|
||||
/* Prototypes for disk control functions */
|
||||
|
||||
|
||||
DSTATUS disk_initialize(BYTE pdrv);
|
||||
DSTATUS disk_status(BYTE pdrv);
|
||||
DRESULT disk_read(BYTE pdrv, BYTE* buff, LBA_t sector, UINT count);
|
||||
DRESULT disk_write(BYTE pdrv, const BYTE* buff, LBA_t sector, UINT count);
|
||||
DRESULT disk_ioctl(BYTE pdrv, BYTE cmd, void* buff);
|
||||
|
||||
|
||||
/* Disk Status Bits (DSTATUS) */
|
||||
|
||||
#define STA_NOINIT 0x01 /* Drive not initialized */
|
||||
#define STA_NODISK 0x02 /* No medium in the drive */
|
||||
#define STA_PROTECT 0x04 /* Write protected */
|
||||
|
||||
|
||||
/* Command code for disk_ioctrl fucntion */
|
||||
|
||||
/* Generic command (Used by FatFs) */
|
||||
#define CTRL_SYNC 0 /* Complete pending write process (needed at FF_FS_READONLY == 0) */
|
||||
#define GET_SECTOR_COUNT 1 /* Get media size (needed at FF_USE_MKFS == 1) */
|
||||
#define GET_SECTOR_SIZE 2 /* Get sector size (needed at FF_MAX_SS != FF_MIN_SS) */
|
||||
#define GET_BLOCK_SIZE 3 /* Get erase block size (needed at FF_USE_MKFS == 1) */
|
||||
#define CTRL_TRIM 4 /* Inform device that the data on the block of sectors is no longer used (needed at FF_USE_TRIM == 1) */
|
||||
|
||||
/* Generic command (Not used by FatFs) */
|
||||
#define CTRL_POWER 5 /* Get/Set power status */
|
||||
#define CTRL_LOCK 6 /* Lock/Unlock media removal */
|
||||
#define CTRL_EJECT 7 /* Eject media */
|
||||
#define CTRL_FORMAT 8 /* Create physical format on the media */
|
||||
|
||||
/* MMC/SDC specific ioctl command */
|
||||
#define MMC_GET_TYPE 10 /* Get card type */
|
||||
#define MMC_GET_CSD 11 /* Get CSD */
|
||||
#define MMC_GET_CID 12 /* Get CID */
|
||||
#define MMC_GET_OCR 13 /* Get OCR */
|
||||
#define MMC_GET_SDSTAT 14 /* Get SD status */
|
||||
#define ISDIO_READ 55 /* Read data form SD iSDIO register */
|
||||
#define ISDIO_WRITE 56 /* Write data to SD iSDIO register */
|
||||
#define ISDIO_MRITE 57 /* Masked write data to SD iSDIO register */
|
||||
|
||||
/* ATA/CF specific ioctl command */
|
||||
#define ATA_GET_REV 20 /* Get F/W revision */
|
||||
#define ATA_GET_MODEL 21 /* Get model name */
|
||||
#define ATA_GET_SN 22 /* Get serial number */
|
||||
|
||||
};
|
||||
|
||||
//#ifdef __cplusplus
|
||||
//}
|
||||
//#endif
|
||||
|
||||
#endif
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,431 @@
|
||||
/* ----------------------------------------------------------------------------/
|
||||
/ FatFs - Generic FAT Filesystem module R0.15 /
|
||||
/-----------------------------------------------------------------------------/
|
||||
/
|
||||
/ Copyright (C) 2022, ChaN, all right reserved.
|
||||
/
|
||||
/ FatFs module is an open source software. Redistribution and use of FatFs in
|
||||
/ source and binary forms, with or without modification, are permitted provided
|
||||
/ that the following condition is met:
|
||||
|
||||
/ 1. Redistributions of source code must retain the above copyright notice,
|
||||
/ this condition and the following disclaimer.
|
||||
/
|
||||
/ This software is provided by the copyright holder and contributors "AS IS"
|
||||
/ and any warranties related to this software are DISCLAIMED.
|
||||
/ The copyright owner or contributors be NOT LIABLE for any damages caused
|
||||
/ by use of this software.
|
||||
/
|
||||
/----------------------------------------------------------------------------*/
|
||||
|
||||
|
||||
#ifndef FF_DEFINED
|
||||
#define FF_DEFINED 80286 /* Revision ID */
|
||||
|
||||
//#ifdef __cplusplus
|
||||
//extern "C" {
|
||||
//#endif
|
||||
|
||||
#include "ffconf.h" /* FatFs configuration options */
|
||||
|
||||
#if FF_DEFINED != FFCONF_DEF
|
||||
#error Wrong configuration file (ffconf.h).
|
||||
#endif
|
||||
|
||||
|
||||
/* Integer types used for FatFs API */
|
||||
|
||||
#if defined(_WIN32) /* Windows VC++ (for development only) */
|
||||
#define FF_INTDEF 2
|
||||
#include <windows.h>
|
||||
typedef unsigned __int64 QWORD;
|
||||
#include <float.h>
|
||||
#define isnan(v) _isnan(v)
|
||||
#define isinf(v) (!_finite(v))
|
||||
|
||||
#elif (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__cplusplus) /* C99 or later */
|
||||
#define FF_INTDEF 2
|
||||
#include <stdint.h>
|
||||
namespace fatfs {
|
||||
typedef unsigned int UINT; /* int must be 16-bit or 32-bit */
|
||||
typedef unsigned char BYTE; /* char must be 8-bit */
|
||||
typedef uint16_t WORD; /* 16-bit unsigned integer */
|
||||
typedef uint32_t DWORD; /* 32-bit unsigned integer */
|
||||
typedef uint64_t QWORD; /* 64-bit unsigned integer */
|
||||
typedef WORD WCHAR; /* UTF-16 character type */
|
||||
};
|
||||
#else /* Earlier than C99 */
|
||||
#define FF_INTDEF 1
|
||||
typedef unsigned int UINT; /* int must be 16-bit or 32-bit */
|
||||
typedef unsigned char BYTE; /* char must be 8-bit */
|
||||
typedef unsigned short WORD; /* 16-bit unsigned integer */
|
||||
typedef unsigned long DWORD; /* 32-bit unsigned integer */
|
||||
typedef WORD WCHAR; /* UTF-16 character type */
|
||||
#endif
|
||||
|
||||
namespace fatfs {
|
||||
/* Type of file size and LBA variables */
|
||||
|
||||
#if FF_FS_EXFAT
|
||||
#if FF_INTDEF != 2
|
||||
#error exFAT feature wants C99 or later
|
||||
#endif
|
||||
typedef QWORD FSIZE_t;
|
||||
#if FF_LBA64
|
||||
typedef QWORD LBA_t;
|
||||
#else
|
||||
typedef DWORD LBA_t;
|
||||
#endif
|
||||
#else
|
||||
#if FF_LBA64
|
||||
#error exFAT needs to be enabled when enable 64-bit LBA
|
||||
#endif
|
||||
typedef DWORD FSIZE_t;
|
||||
typedef DWORD LBA_t;
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
/* Type of path name strings on FatFs API (TCHAR) */
|
||||
|
||||
#if FF_USE_LFN && FF_LFN_UNICODE == 1 /* Unicode in UTF-16 encoding */
|
||||
typedef WCHAR TCHAR;
|
||||
#define _T(x) L ## x
|
||||
#define _TEXT(x) L ## x
|
||||
#elif FF_USE_LFN && FF_LFN_UNICODE == 2 /* Unicode in UTF-8 encoding */
|
||||
typedef char TCHAR;
|
||||
#define _T(x) u8 ## x
|
||||
#define _TEXT(x) u8 ## x
|
||||
#elif FF_USE_LFN && FF_LFN_UNICODE == 3 /* Unicode in UTF-32 encoding */
|
||||
typedef DWORD TCHAR;
|
||||
#define _T(x) U ## x
|
||||
#define _TEXT(x) U ## x
|
||||
#elif FF_USE_LFN && (FF_LFN_UNICODE < 0 || FF_LFN_UNICODE > 3)
|
||||
#error Wrong FF_LFN_UNICODE setting
|
||||
#else /* ANSI/OEM code in SBCS/DBCS */
|
||||
typedef char TCHAR;
|
||||
#define _T(x) x
|
||||
#define _TEXT(x) x
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
/* Definitions of volume management */
|
||||
|
||||
#if FF_MULTI_PARTITION /* Multiple partition configuration */
|
||||
typedef struct {
|
||||
BYTE pd; /* Physical drive number */
|
||||
BYTE pt; /* Partition: 0:Auto detect, 1-4:Forced partition) */
|
||||
} PARTITION;
|
||||
extern PARTITION VolToPart[]; /* Volume - Partition mapping table */
|
||||
#endif
|
||||
|
||||
#if FF_STR_VOLUME_ID
|
||||
#ifndef FF_VOLUME_STRS
|
||||
extern const char* VolumeStr[FF_VOLUMES]; /* User defied volume ID */
|
||||
#endif
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
/* Filesystem object structure (FATFS) */
|
||||
|
||||
typedef struct {
|
||||
BYTE fs_type; /* Filesystem type (0:not mounted) */
|
||||
BYTE pdrv; /* Volume hosting physical drive */
|
||||
BYTE ldrv; /* Logical drive number (used only when FF_FS_REENTRANT) */
|
||||
BYTE n_fats; /* Number of FATs (1 or 2) */
|
||||
BYTE wflag; /* win[] status (b0:dirty) */
|
||||
BYTE fsi_flag; /* FSINFO status (b7:disabled, b0:dirty) */
|
||||
WORD id; /* Volume mount ID */
|
||||
WORD n_rootdir; /* Number of root directory entries (FAT12/16) */
|
||||
WORD csize; /* Cluster size [sectors] */
|
||||
#if FF_MAX_SS != FF_MIN_SS
|
||||
WORD ssize; /* Sector size (512, 1024, 2048 or 4096) */
|
||||
#endif
|
||||
#if FF_USE_LFN
|
||||
WCHAR* lfnbuf; /* LFN working buffer */
|
||||
#endif
|
||||
#if FF_FS_EXFAT
|
||||
BYTE* dirbuf; /* Directory entry block scratchpad buffer for exFAT */
|
||||
#endif
|
||||
#if !FF_FS_READONLY
|
||||
DWORD last_clst; /* Last allocated cluster */
|
||||
DWORD free_clst; /* Number of free clusters */
|
||||
#endif
|
||||
#if FF_FS_RPATH
|
||||
DWORD cdir; /* Current directory start cluster (0:root) */
|
||||
#if FF_FS_EXFAT
|
||||
DWORD cdc_scl; /* Containing directory start cluster (invalid when cdir is 0) */
|
||||
DWORD cdc_size; /* b31-b8:Size of containing directory, b7-b0: Chain status */
|
||||
DWORD cdc_ofs; /* Offset in the containing directory (invalid when cdir is 0) */
|
||||
#endif
|
||||
#endif
|
||||
DWORD n_fatent; /* Number of FAT entries (number of clusters + 2) */
|
||||
DWORD fsize; /* Number of sectors per FAT */
|
||||
LBA_t volbase; /* Volume base sector */
|
||||
LBA_t fatbase; /* FAT base sector */
|
||||
LBA_t dirbase; /* Root directory base sector (FAT12/16) or cluster (FAT32/exFAT) */
|
||||
LBA_t database; /* Data base sector */
|
||||
#if FF_FS_EXFAT
|
||||
LBA_t bitbase; /* Allocation bitmap base sector */
|
||||
#endif
|
||||
LBA_t winsect; /* Current sector appearing in the win[] */
|
||||
BYTE win[FF_MAX_SS]; /* Disk access window for Directory, FAT (and file data at tiny cfg) */
|
||||
} FATFS;
|
||||
|
||||
|
||||
|
||||
/* Object ID and allocation information (FFOBJID) */
|
||||
|
||||
typedef struct {
|
||||
FATFS* fs; /* Pointer to the hosting volume of this object */
|
||||
WORD id; /* Hosting volume's mount ID */
|
||||
BYTE attr; /* Object attribute */
|
||||
BYTE stat; /* Object chain status (b1-0: =0:not contiguous, =2:contiguous, =3:fragmented in this session, b2:sub-directory stretched) */
|
||||
DWORD sclust; /* Object data start cluster (0:no cluster or root directory) */
|
||||
FSIZE_t objsize; /* Object size (valid when sclust != 0) */
|
||||
#if FF_FS_EXFAT
|
||||
DWORD n_cont; /* Size of first fragment - 1 (valid when stat == 3) */
|
||||
DWORD n_frag; /* Size of last fragment needs to be written to FAT (valid when not zero) */
|
||||
DWORD c_scl; /* Containing directory start cluster (valid when sclust != 0) */
|
||||
DWORD c_size; /* b31-b8:Size of containing directory, b7-b0: Chain status (valid when c_scl != 0) */
|
||||
DWORD c_ofs; /* Offset in the containing directory (valid when file object and sclust != 0) */
|
||||
#endif
|
||||
#if FF_FS_LOCK
|
||||
UINT lockid; /* File lock ID origin from 1 (index of file semaphore table Files[]) */
|
||||
#endif
|
||||
} FFOBJID;
|
||||
|
||||
|
||||
|
||||
/* File object structure (FIL) */
|
||||
|
||||
typedef struct {
|
||||
FFOBJID obj; /* Object identifier (must be the 1st member to detect invalid object pointer) */
|
||||
BYTE flag; /* File status flags */
|
||||
BYTE err; /* Abort flag (error code) */
|
||||
FSIZE_t fptr; /* File read/write pointer (Zeroed on file open) */
|
||||
DWORD clust; /* Current cluster of fpter (invalid when fptr is 0) */
|
||||
LBA_t sect; /* Sector number appearing in buf[] (0:invalid) */
|
||||
#if !FF_FS_READONLY
|
||||
LBA_t dir_sect; /* Sector number containing the directory entry (not used at exFAT) */
|
||||
BYTE* dir_ptr; /* Pointer to the directory entry in the win[] (not used at exFAT) */
|
||||
#endif
|
||||
#if FF_USE_FASTSEEK
|
||||
DWORD* cltbl; /* Pointer to the cluster link map table (nulled on open, set by application) */
|
||||
#endif
|
||||
#if !FF_FS_TINY
|
||||
BYTE buf[FF_MAX_SS]; /* File private data read/write window */
|
||||
#endif
|
||||
} FIL;
|
||||
|
||||
|
||||
|
||||
/* Directory object structure (DIR) */
|
||||
|
||||
typedef struct {
|
||||
FFOBJID obj; /* Object identifier */
|
||||
DWORD dptr; /* Current read/write offset */
|
||||
DWORD clust; /* Current cluster */
|
||||
LBA_t sect; /* Current sector (0:Read operation has terminated) */
|
||||
BYTE* dir; /* Pointer to the directory item in the win[] */
|
||||
BYTE fn[12]; /* SFN (in/out) {body[8],ext[3],status[1]} */
|
||||
#if FF_USE_LFN
|
||||
DWORD blk_ofs; /* Offset of current entry block being processed (0xFFFFFFFF:Invalid) */
|
||||
#endif
|
||||
#if FF_USE_FIND
|
||||
const TCHAR* pat; /* Pointer to the name matching pattern */
|
||||
#endif
|
||||
} DIR;
|
||||
|
||||
|
||||
|
||||
/* File information structure (FILINFO) */
|
||||
|
||||
typedef struct {
|
||||
FSIZE_t fsize; /* File size */
|
||||
WORD fdate; /* Modified date */
|
||||
WORD ftime; /* Modified time */
|
||||
BYTE fattrib; /* File attribute */
|
||||
#if FF_USE_LFN
|
||||
TCHAR altname[FF_SFN_BUF + 1];/* Alternative file name */
|
||||
TCHAR fname[FF_LFN_BUF + 1]; /* Primary file name */
|
||||
#else
|
||||
TCHAR fname[12 + 1]; /* File name */
|
||||
#endif
|
||||
} FILINFO;
|
||||
|
||||
|
||||
|
||||
/* Format parameter structure (MKFS_PARM) */
|
||||
|
||||
typedef struct {
|
||||
BYTE fmt; /* Format option (FM_FAT, FM_FAT32, FM_EXFAT and FM_SFD) */
|
||||
BYTE n_fat; /* Number of FATs */
|
||||
UINT align; /* Data area alignment (sector) */
|
||||
UINT n_root; /* Number of root directory entries */
|
||||
DWORD au_size; /* Cluster size (byte) */
|
||||
} MKFS_PARM;
|
||||
|
||||
|
||||
|
||||
/* File function return code (FRESULT) */
|
||||
|
||||
typedef enum {
|
||||
FR_OK = 0, /* (0) Succeeded */
|
||||
FR_DISK_ERR, /* (1) A hard error occurred in the low level disk I/O layer */
|
||||
FR_INT_ERR, /* (2) Assertion failed */
|
||||
FR_NOT_READY, /* (3) The physical drive cannot work */
|
||||
FR_NO_FILE, /* (4) Could not find the file */
|
||||
FR_NO_PATH, /* (5) Could not find the path */
|
||||
FR_INVALID_NAME, /* (6) The path name format is invalid */
|
||||
FR_DENIED, /* (7) Access denied due to prohibited access or directory full */
|
||||
FR_EXIST, /* (8) Access denied due to prohibited access */
|
||||
FR_INVALID_OBJECT, /* (9) The file/directory object is invalid */
|
||||
FR_WRITE_PROTECTED, /* (10) The physical drive is write protected */
|
||||
FR_INVALID_DRIVE, /* (11) The logical drive number is invalid */
|
||||
FR_NOT_ENABLED, /* (12) The volume has no work area */
|
||||
FR_NO_FILESYSTEM, /* (13) There is no valid FAT volume */
|
||||
FR_MKFS_ABORTED, /* (14) The f_mkfs() aborted due to any problem */
|
||||
FR_TIMEOUT, /* (15) Could not get a grant to access the volume within defined period */
|
||||
FR_LOCKED, /* (16) The operation is rejected according to the file sharing policy */
|
||||
FR_NOT_ENOUGH_CORE, /* (17) LFN working buffer could not be allocated */
|
||||
FR_TOO_MANY_OPEN_FILES, /* (18) Number of open files > FF_FS_LOCK */
|
||||
FR_INVALID_PARAMETER /* (19) Given parameter is invalid */
|
||||
} FRESULT;
|
||||
|
||||
|
||||
|
||||
|
||||
/*--------------------------------------------------------------*/
|
||||
/* FatFs Module Application Interface */
|
||||
/*--------------------------------------------------------------*/
|
||||
|
||||
FRESULT f_open(FIL* fp, const TCHAR* path, BYTE mode); /* Open or create a file */
|
||||
FRESULT f_close(FIL* fp); /* Close an open file object */
|
||||
FRESULT f_read(FIL* fp, void* buff, UINT btr, UINT* br); /* Read data from the file */
|
||||
FRESULT f_write(FIL* fp, const void* buff, UINT btw, UINT* bw); /* Write data to the file */
|
||||
FRESULT f_lseek(FIL* fp, FSIZE_t ofs); /* Move file pointer of the file object */
|
||||
FRESULT f_truncate(FIL* fp); /* Truncate the file */
|
||||
FRESULT f_sync(FIL* fp); /* Flush cached data of the writing file */
|
||||
FRESULT f_opendir(DIR* dp, const TCHAR* path); /* Open a directory */
|
||||
FRESULT f_closedir(DIR* dp); /* Close an open directory */
|
||||
FRESULT f_readdir(DIR* dp, FILINFO* fno); /* Read a directory item */
|
||||
FRESULT f_findfirst(DIR* dp, FILINFO* fno, const TCHAR* path, const TCHAR* pattern); /* Find first file */
|
||||
FRESULT f_findnext(DIR* dp, FILINFO* fno); /* Find next file */
|
||||
FRESULT f_mkdir(const TCHAR* path); /* Create a sub directory */
|
||||
FRESULT f_unlink(const TCHAR* path); /* Delete an existing file or directory */
|
||||
FRESULT f_rename(const TCHAR* path_old, const TCHAR* path_new); /* Rename/Move a file or directory */
|
||||
FRESULT f_stat(const TCHAR* path, FILINFO* fno); /* Get file status */
|
||||
FRESULT f_chmod(const TCHAR* path, BYTE attr, BYTE mask); /* Change attribute of a file/dir */
|
||||
FRESULT f_utime(const TCHAR* path, const FILINFO* fno); /* Change timestamp of a file/dir */
|
||||
FRESULT f_chdir(const TCHAR* path); /* Change current directory */
|
||||
FRESULT f_chdrive(const TCHAR* path); /* Change current drive */
|
||||
FRESULT f_getcwd(TCHAR* buff, UINT len); /* Get current directory */
|
||||
FRESULT f_getfree(const TCHAR* path, DWORD* nclst, FATFS** fatfs); /* Get number of free clusters on the drive */
|
||||
FRESULT f_getlabel(const TCHAR* path, TCHAR* label, DWORD* vsn); /* Get volume label */
|
||||
FRESULT f_setlabel(const TCHAR* label); /* Set volume label */
|
||||
FRESULT f_forward(FIL* fp, UINT(*func)(const BYTE*, UINT), UINT btf, UINT* bf); /* Forward data to the stream */
|
||||
FRESULT f_expand(FIL* fp, FSIZE_t fsz, BYTE opt); /* Allocate a contiguous block to the file */
|
||||
FRESULT f_mount(FATFS* fs, const TCHAR* path, BYTE opt); /* Mount/Unmount a logical drive */
|
||||
FRESULT f_mkfs(const TCHAR* path, const MKFS_PARM* opt, void* work, UINT len); /* Create a FAT volume */
|
||||
FRESULT f_fdisk(BYTE pdrv, const LBA_t ptbl[], void* work); /* Divide a physical drive into some partitions */
|
||||
FRESULT f_setcp(WORD cp); /* Set current code page */
|
||||
int f_putc(TCHAR c, FIL* fp); /* Put a character to the file */
|
||||
int f_puts(const TCHAR* str, FIL* cp); /* Put a string to the file */
|
||||
int f_printf(FIL* fp, const TCHAR* str, ...); /* Put a formatted string to the file */
|
||||
TCHAR* f_gets(TCHAR* buff, int len, FIL* fp); /* Get a string from the file */
|
||||
|
||||
/* Some API fucntions are implemented as macro */
|
||||
|
||||
#define f_eof(fp) ((int)((fp)->fptr == (fp)->obj.objsize))
|
||||
#define f_error(fp) ((fp)->err)
|
||||
#define f_tell(fp) ((fp)->fptr)
|
||||
#define f_size(fp) ((fp)->obj.objsize)
|
||||
#define f_rewind(fp) f_lseek((fp), 0)
|
||||
#define f_rewinddir(dp) f_readdir((dp), 0)
|
||||
#define f_rmdir(path) f_unlink(path)
|
||||
#define f_unmount(path) f_mount(0, path, 0)
|
||||
|
||||
|
||||
|
||||
|
||||
/*--------------------------------------------------------------*/
|
||||
/* Additional Functions */
|
||||
/*--------------------------------------------------------------*/
|
||||
|
||||
/* RTC function (provided by user) */
|
||||
#if !FF_FS_READONLY && !FF_FS_NORTC
|
||||
DWORD get_fattime(void); /* Get current time */
|
||||
#endif
|
||||
|
||||
|
||||
/* LFN support functions (defined in ffunicode.c) */
|
||||
|
||||
#if FF_USE_LFN >= 1
|
||||
WCHAR ff_oem2uni(WCHAR oem, WORD cp); /* OEM code to Unicode conversion */
|
||||
WCHAR ff_uni2oem(DWORD uni, WORD cp); /* Unicode to OEM code conversion */
|
||||
DWORD ff_wtoupper(DWORD uni); /* Unicode upper-case conversion */
|
||||
#endif
|
||||
|
||||
|
||||
/* O/S dependent functions (samples available in ffsystem.c) */
|
||||
|
||||
#if FF_USE_LFN == 3 /* Dynamic memory allocation */
|
||||
void* ff_memalloc(UINT msize); /* Allocate memory block */
|
||||
void ff_memfree(void* mblock); /* Free memory block */
|
||||
#endif
|
||||
#if FF_FS_REENTRANT /* Sync functions */
|
||||
int ff_mutex_create(int vol); /* Create a sync object */
|
||||
void ff_mutex_delete(int vol); /* Delete a sync object */
|
||||
int ff_mutex_take(int vol); /* Lock sync object */
|
||||
void ff_mutex_give(int vol); /* Unlock sync object */
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
|
||||
/*--------------------------------------------------------------*/
|
||||
/* Flags and Offset Address */
|
||||
/*--------------------------------------------------------------*/
|
||||
|
||||
/* File access mode and open method flags (3rd argument of f_open) */
|
||||
#define FA_READ 0x01
|
||||
#define FA_WRITE 0x02
|
||||
#define FA_OPEN_EXISTING 0x00
|
||||
#define FA_CREATE_NEW 0x04
|
||||
#define FA_CREATE_ALWAYS 0x08
|
||||
#define FA_OPEN_ALWAYS 0x10
|
||||
#define FA_OPEN_APPEND 0x30
|
||||
|
||||
/* Fast seek controls (2nd argument of f_lseek) */
|
||||
#define CREATE_LINKMAP ((FSIZE_t)0 - 1)
|
||||
|
||||
/* Format options (2nd argument of f_mkfs) */
|
||||
#define FM_FAT 0x01
|
||||
#define FM_FAT32 0x02
|
||||
#define FM_EXFAT 0x04
|
||||
#define FM_ANY 0x07
|
||||
#define FM_SFD 0x08
|
||||
|
||||
/* Filesystem type (FATFS.fs_type) */
|
||||
#define FS_FAT12 1
|
||||
#define FS_FAT16 2
|
||||
#define FS_FAT32 3
|
||||
#define FS_EXFAT 4
|
||||
|
||||
/* File attribute bits for directory entry (FILINFO.fattrib) */
|
||||
#define AM_RDO 0x01 /* Read only */
|
||||
#define AM_HID 0x02 /* Hidden */
|
||||
#define AM_SYS 0x04 /* System */
|
||||
#define AM_DIR 0x10 /* Directory */
|
||||
#define AM_ARC 0x20 /* Archive */
|
||||
|
||||
};
|
||||
|
||||
//#ifdef __cplusplus
|
||||
//}
|
||||
//#endif
|
||||
|
||||
#endif /* FF_DEFINED */
|
||||
@@ -0,0 +1,296 @@
|
||||
/* ---------------------------------------------------------------------------/
|
||||
/ Configurations of FatFs Module
|
||||
/---------------------------------------------------------------------------*/
|
||||
|
||||
#define FFCONF_DEF 80286 /* Revision ID */
|
||||
|
||||
/* ---------------------------------------------------------------------------/
|
||||
/ Function Configurations
|
||||
/---------------------------------------------------------------------------*/
|
||||
|
||||
#define FF_FS_READONLY 0
|
||||
/* This option switches read-only configuration. (0:Read/Write or 1:Read-only)
|
||||
/ Read-only configuration removes writing API functions, f_write(), f_sync(),
|
||||
/ f_unlink(), f_mkdir(), f_chmod(), f_rename(), f_truncate(), f_getfree()
|
||||
/ and optional writing functions as well. */
|
||||
|
||||
|
||||
#define FF_FS_MINIMIZE 0
|
||||
/* This option defines minimization level to remove some basic API functions.
|
||||
/
|
||||
/ 0: Basic functions are fully enabled.
|
||||
/ 1: f_stat(), f_getfree(), f_unlink(), f_mkdir(), f_truncate() and f_rename()
|
||||
/ are removed.
|
||||
/ 2: f_opendir(), f_readdir() and f_closedir() are removed in addition to 1.
|
||||
/ 3: f_lseek() function is removed in addition to 2. */
|
||||
|
||||
|
||||
#define FF_USE_FIND 1
|
||||
/* This option switches filtered directory read functions, f_findfirst() and
|
||||
/ f_findnext(). (0:Disable, 1:Enable 2:Enable with matching altname[] too) */
|
||||
|
||||
|
||||
#define FF_USE_MKFS 1
|
||||
/* This option switches f_mkfs() function. (0:Disable or 1:Enable) */
|
||||
|
||||
|
||||
#define FF_USE_FASTSEEK 1
|
||||
/* This option switches fast seek function. (0:Disable or 1:Enable) */
|
||||
|
||||
|
||||
#define FF_USE_EXPAND 0
|
||||
/* This option switches f_expand function. (0:Disable or 1:Enable) */
|
||||
|
||||
|
||||
#define FF_USE_CHMOD 1
|
||||
/* This option switches attribute manipulation functions, f_chmod() and f_utime().
|
||||
/ (0:Disable or 1:Enable) Also FF_FS_READONLY needs to be 0 to enable this option. */
|
||||
|
||||
|
||||
#define FF_USE_LABEL 1
|
||||
/* This option switches volume label functions, f_getlabel() and f_setlabel().
|
||||
/ (0:Disable or 1:Enable) */
|
||||
|
||||
|
||||
#define FF_USE_FORWARD 0
|
||||
/* This option switches f_forward() function. (0:Disable or 1:Enable) */
|
||||
|
||||
|
||||
#define FF_USE_STRFUNC 0
|
||||
#define FF_PRINT_LLI 1
|
||||
#define FF_PRINT_FLOAT 1
|
||||
#define FF_STRF_ENCODE 3
|
||||
/* FF_USE_STRFUNC switches string functions, f_gets(), f_putc(), f_puts() and
|
||||
/ f_printf().
|
||||
/
|
||||
/ 0: Disable. FF_PRINT_LLI, FF_PRINT_FLOAT and FF_STRF_ENCODE have no effect.
|
||||
/ 1: Enable without LF-CRLF conversion.
|
||||
/ 2: Enable with LF-CRLF conversion.
|
||||
/
|
||||
/ FF_PRINT_LLI = 1 makes f_printf() support long long argument and FF_PRINT_FLOAT = 1/2
|
||||
/ makes f_printf() support floating point argument. These features want C99 or later.
|
||||
/ When FF_LFN_UNICODE >= 1 with LFN enabled, string functions convert the character
|
||||
/ encoding in it. FF_STRF_ENCODE selects assumption of character encoding ON THE FILE
|
||||
/ to be read/written via those functions.
|
||||
/
|
||||
/ 0: ANSI/OEM in current CP
|
||||
/ 1: Unicode in UTF-16LE
|
||||
/ 2: Unicode in UTF-16BE
|
||||
/ 3: Unicode in UTF-8
|
||||
*/
|
||||
|
||||
|
||||
/* ---------------------------------------------------------------------------/
|
||||
/ Locale and Namespace Configurations
|
||||
/---------------------------------------------------------------------------*/
|
||||
|
||||
#define FF_CODE_PAGE 437
|
||||
/* This option specifies the OEM code page to be used on the target system.
|
||||
/ Incorrect code page setting can cause a file open failure.
|
||||
/
|
||||
/ 437 - U.S.
|
||||
/ 720 - Arabic
|
||||
/ 737 - Greek
|
||||
/ 771 - KBL
|
||||
/ 775 - Baltic
|
||||
/ 850 - Latin 1
|
||||
/ 852 - Latin 2
|
||||
/ 855 - Cyrillic
|
||||
/ 857 - Turkish
|
||||
/ 860 - Portuguese
|
||||
/ 861 - Icelandic
|
||||
/ 862 - Hebrew
|
||||
/ 863 - Canadian French
|
||||
/ 864 - Arabic
|
||||
/ 865 - Nordic
|
||||
/ 866 - Russian
|
||||
/ 869 - Greek 2
|
||||
/ 932 - Japanese (DBCS)
|
||||
/ 936 - Simplified Chinese (DBCS)
|
||||
/ 949 - Korean (DBCS)
|
||||
/ 950 - Traditional Chinese (DBCS)
|
||||
/ 0 - Include all code pages above and configured by f_setcp()
|
||||
*/
|
||||
|
||||
|
||||
#define FF_USE_LFN 1
|
||||
#define FF_MAX_LFN 64
|
||||
/* The FF_USE_LFN switches the support for LFN (long file name).
|
||||
/
|
||||
/ 0: Disable LFN. FF_MAX_LFN has no effect.
|
||||
/ 1: Enable LFN with static working buffer on the BSS. Always NOT thread-safe.
|
||||
/ 2: Enable LFN with dynamic working buffer on the STACK.
|
||||
/ 3: Enable LFN with dynamic working buffer on the HEAP.
|
||||
/
|
||||
/ To enable the LFN, ffunicode.c needs to be added to the project. The LFN function
|
||||
/ requiers certain internal working buffer occupies (FF_MAX_LFN + 1) * 2 bytes and
|
||||
/ additional (FF_MAX_LFN + 44) / 15 * 32 bytes when exFAT is enabled.
|
||||
/ The FF_MAX_LFN defines size of the working buffer in UTF-16 code unit and it can
|
||||
/ be in range of 12 to 255. It is recommended to be set it 255 to fully support LFN
|
||||
/ specification.
|
||||
/ When use stack for the working buffer, take care on stack overflow. When use heap
|
||||
/ memory for the working buffer, memory management functions, ff_memalloc() and
|
||||
/ ff_memfree() exemplified in ffsystem.c, need to be added to the project. */
|
||||
|
||||
|
||||
#define FF_LFN_UNICODE 0
|
||||
/* This option switches the character encoding on the API when LFN is enabled.
|
||||
/
|
||||
/ 0: ANSI/OEM in current CP (TCHAR = char)
|
||||
/ 1: Unicode in UTF-16 (TCHAR = WCHAR)
|
||||
/ 2: Unicode in UTF-8 (TCHAR = char)
|
||||
/ 3: Unicode in UTF-32 (TCHAR = DWORD)
|
||||
/
|
||||
/ Also behavior of string I/O functions will be affected by this option.
|
||||
/ When LFN is not enabled, this option has no effect. */
|
||||
|
||||
|
||||
#define FF_LFN_BUF 64
|
||||
#define FF_SFN_BUF 12
|
||||
/* This set of options defines size of file name members in the FILINFO structure
|
||||
/ which is used to read out directory items. These values should be suffcient for
|
||||
/ the file names to read. The maximum possible length of the read file name depends
|
||||
/ on character encoding. When LFN is not enabled, these options have no effect. */
|
||||
|
||||
|
||||
#define FF_FS_RPATH 0
|
||||
/* This option configures support for relative path.
|
||||
/
|
||||
/ 0: Disable relative path and remove related functions.
|
||||
/ 1: Enable relative path. f_chdir() and f_chdrive() are available.
|
||||
/ 2: f_getcwd() function is available in addition to 1.
|
||||
*/
|
||||
|
||||
|
||||
/* ---------------------------------------------------------------------------/
|
||||
/ Drive/Volume Configurations
|
||||
/---------------------------------------------------------------------------*/
|
||||
|
||||
#define FF_VOLUMES 1
|
||||
/* Number of volumes (logical drives) to be used. (1-10) */
|
||||
|
||||
|
||||
#define FF_STR_VOLUME_ID 0
|
||||
#define FF_VOLUME_STRS "FLASH"
|
||||
/* FF_STR_VOLUME_ID switches support for volume ID in arbitrary strings.
|
||||
/ When FF_STR_VOLUME_ID is set to 1 or 2, arbitrary strings can be used as drive
|
||||
/ number in the path name. FF_VOLUME_STRS defines the volume ID strings for each
|
||||
/ logical drives. Number of items must not be less than FF_VOLUMES. Valid
|
||||
/ characters for the volume ID strings are A-Z, a-z and 0-9, however, they are
|
||||
/ compared in case-insensitive. If FF_STR_VOLUME_ID >= 1 and FF_VOLUME_STRS is
|
||||
/ not defined, a user defined volume string table is needed as:
|
||||
/
|
||||
/ const char* VolumeStr[FF_VOLUMES] = {"ram","flash","sd","usb",...
|
||||
*/
|
||||
|
||||
|
||||
#define FF_MULTI_PARTITION 0
|
||||
/* This option switches support for multiple volumes on the physical drive.
|
||||
/ By default (0), each logical drive number is bound to the same physical drive
|
||||
/ number and only an FAT volume found on the physical drive will be mounted.
|
||||
/ When this function is enabled (1), each logical drive number can be bound to
|
||||
/ arbitrary physical drive and partition listed in the VolToPart[]. Also f_fdisk()
|
||||
/ function will be available. */
|
||||
|
||||
|
||||
#define FF_MIN_SS 512
|
||||
#define FF_MAX_SS 4096
|
||||
/* This set of options configures the range of sector size to be supported. (512,
|
||||
/ 1024, 2048 or 4096) Always set both 512 for most systems, generic memory card and
|
||||
/ harddisk, but a larger value may be required for on-board flash memory and some
|
||||
/ type of optical media. When FF_MAX_SS is larger than FF_MIN_SS, FatFs is configured
|
||||
/ for variable sector size mode and disk_ioctl() function needs to implement
|
||||
/ GET_SECTOR_SIZE command. */
|
||||
|
||||
|
||||
#define FF_LBA64 0
|
||||
/* This option switches support for 64-bit LBA. (0:Disable or 1:Enable)
|
||||
/ To enable the 64-bit LBA, also exFAT needs to be enabled. (FF_FS_EXFAT == 1) */
|
||||
|
||||
|
||||
#define FF_MIN_GPT 0x10000000
|
||||
/* Minimum number of sectors to switch GPT as partitioning format in f_mkfs and
|
||||
/ f_fdisk function. 0x100000000 max. This option has no effect when FF_LBA64 == 0. */
|
||||
|
||||
|
||||
#define FF_USE_TRIM 1
|
||||
/* This option switches support for ATA-TRIM. (0:Disable or 1:Enable)
|
||||
/ To enable Trim function, also CTRL_TRIM command should be implemented to the
|
||||
/ disk_ioctl() function. */
|
||||
|
||||
|
||||
|
||||
/* ---------------------------------------------------------------------------/
|
||||
/ System Configurations
|
||||
/---------------------------------------------------------------------------*/
|
||||
|
||||
#define FF_FS_TINY 0
|
||||
/* This option switches tiny buffer configuration. (0:Normal or 1:Tiny)
|
||||
/ At the tiny configuration, size of file object (FIL) is shrinked FF_MAX_SS bytes.
|
||||
/ Instead of private sector buffer eliminated from the file object, common sector
|
||||
/ buffer in the filesystem object (FATFS) is used for the file data transfer. */
|
||||
|
||||
|
||||
#define FF_FS_EXFAT 0
|
||||
/* This option switches support for exFAT filesystem. (0:Disable or 1:Enable)
|
||||
/ To enable exFAT, also LFN needs to be enabled. (FF_USE_LFN >= 1)
|
||||
/ Note that enabling exFAT discards ANSI C (C89) compatibility. */
|
||||
|
||||
|
||||
#define FF_FS_NORTC 0
|
||||
#define FF_NORTC_MON 1
|
||||
#define FF_NORTC_MDAY 1
|
||||
#define FF_NORTC_YEAR 2022
|
||||
/* The option FF_FS_NORTC switches timestamp feature. If the system does not have
|
||||
/ an RTC or valid timestamp is not needed, set FF_FS_NORTC = 1 to disable the
|
||||
/ timestamp feature. Every object modified by FatFs will have a fixed timestamp
|
||||
/ defined by FF_NORTC_MON, FF_NORTC_MDAY and FF_NORTC_YEAR in local time.
|
||||
/ To enable timestamp function (FF_FS_NORTC = 0), get_fattime() function need to be
|
||||
/ added to the project to read current time form real-time clock. FF_NORTC_MON,
|
||||
/ FF_NORTC_MDAY and FF_NORTC_YEAR have no effect.
|
||||
/ These options have no effect in read-only configuration (FF_FS_READONLY = 1). */
|
||||
|
||||
|
||||
#define FF_FS_NOFSINFO 0
|
||||
/* If you need to know correct free space on the FAT32 volume, set bit 0 of this
|
||||
/ option, and f_getfree() function at the first time after volume mount will force
|
||||
/ a full FAT scan. Bit 1 controls the use of last allocated cluster number.
|
||||
/
|
||||
/ bit0=0: Use free cluster count in the FSINFO if available.
|
||||
/ bit0=1: Do not trust free cluster count in the FSINFO.
|
||||
/ bit1=0: Use last allocated cluster number in the FSINFO if available.
|
||||
/ bit1=1: Do not trust last allocated cluster number in the FSINFO.
|
||||
*/
|
||||
|
||||
|
||||
#define FF_FS_LOCK 0
|
||||
/* The option FF_FS_LOCK switches file lock function to control duplicated file open
|
||||
/ and illegal operation to open objects. This option must be 0 when FF_FS_READONLY
|
||||
/ is 1.
|
||||
/
|
||||
/ 0: Disable file lock function. To avoid volume corruption, application program
|
||||
/ should avoid illegal open, remove and rename to the open objects.
|
||||
/ >0: Enable file lock function. The value defines how many files/sub-directories
|
||||
/ can be opened simultaneously under file lock control. Note that the file
|
||||
/ lock control is independent of re-entrancy. */
|
||||
|
||||
|
||||
#define FF_FS_REENTRANT 0
|
||||
#define FF_FS_TIMEOUT 1000
|
||||
/* The option FF_FS_REENTRANT switches the re-entrancy (thread safe) of the FatFs
|
||||
/ module itself. Note that regardless of this option, file access to different
|
||||
/ volume is always re-entrant and volume control functions, f_mount(), f_mkfs()
|
||||
/ and f_fdisk() function, are always not re-entrant. Only file/directory access
|
||||
/ to the same volume is under control of this featuer.
|
||||
/
|
||||
/ 0: Disable re-entrancy. FF_FS_TIMEOUT have no effect.
|
||||
/ 1: Enable re-entrancy. Also user provided synchronization handlers,
|
||||
/ ff_mutex_create(), ff_mutex_delete(), ff_mutex_take() and ff_mutex_give()
|
||||
/ function, must be added to the project. Samples are available in ffsystem.c.
|
||||
/
|
||||
/ The FF_FS_TIMEOUT defines timeout period in unit of O/S time tick.
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/*--- End of configuration options ---*/
|
||||
@@ -0,0 +1,202 @@
|
||||
/*------------------------------------------------------------------------*/
|
||||
/* A Sample Code of User Provided OS Dependent Functions for FatFs */
|
||||
/*------------------------------------------------------------------------*/
|
||||
|
||||
#include "ff.h"
|
||||
|
||||
|
||||
#if FF_USE_LFN == 3 /* Use dynamic memory allocation */
|
||||
|
||||
/*------------------------------------------------------------------------*/
|
||||
/* Allocate/Free a Memory Block */
|
||||
/*------------------------------------------------------------------------*/
|
||||
|
||||
#include <stdlib.h> /* with POSIX API */
|
||||
|
||||
|
||||
void* ff_memalloc( /* Returns pointer to the allocated memory block (null if not enough core) */
|
||||
UINT msize /* Number of bytes to allocate */
|
||||
) {
|
||||
return malloc((size_t)msize); /* Allocate a new memory block */
|
||||
}
|
||||
|
||||
|
||||
void ff_memfree(
|
||||
void* mblock /* Pointer to the memory block to free (no effect if null) */
|
||||
) {
|
||||
free(mblock); /* Free the memory block */
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
|
||||
#if FF_FS_REENTRANT /* Mutal exclusion */
|
||||
/*------------------------------------------------------------------------*/
|
||||
/* Definitions of Mutex */
|
||||
/*------------------------------------------------------------------------*/
|
||||
|
||||
#define OS_TYPE 0 /* 0:Win32, 1:uITRON4.0, 2:uC/OS-II, 3:FreeRTOS, 4:CMSIS-RTOS */
|
||||
|
||||
|
||||
#if OS_TYPE == 0 /* Win32 */
|
||||
#include <windows.h>
|
||||
static HANDLE Mutex[FF_VOLUMES + 1]; /* Table of mutex handle */
|
||||
|
||||
#elif OS_TYPE == 1 /* uITRON */
|
||||
#include "itron.h"
|
||||
#include "kernel.h"
|
||||
static mtxid Mutex[FF_VOLUMES + 1]; /* Table of mutex ID */
|
||||
|
||||
#elif OS_TYPE == 2 /* uc/OS-II */
|
||||
#include "includes.h"
|
||||
static OS_EVENT *Mutex[FF_VOLUMES + 1]; /* Table of mutex pinter */
|
||||
|
||||
#elif OS_TYPE == 3 /* FreeRTOS */
|
||||
#include "FreeRTOS.h"
|
||||
#include "semphr.h"
|
||||
static SemaphoreHandle_t Mutex[FF_VOLUMES + 1]; /* Table of mutex handle */
|
||||
|
||||
#elif OS_TYPE == 4 /* CMSIS-RTOS */
|
||||
#include "cmsis_os.h"
|
||||
static osMutexId Mutex[FF_VOLUMES + 1]; /* Table of mutex ID */
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
/*------------------------------------------------------------------------*/
|
||||
/* Create a Mutex */
|
||||
/*------------------------------------------------------------------------*/
|
||||
/* This function is called in f_mount function to create a new mutex
|
||||
/ or semaphore for the volume. When a 0 is returned, the f_mount function
|
||||
/ fails with FR_INT_ERR.
|
||||
*/
|
||||
|
||||
int ff_mutex_create( /* Returns 1:Function succeeded or 0:Could not create the mutex */
|
||||
int vol /* Mutex ID: Volume mutex (0 to FF_VOLUMES - 1) or system mutex (FF_VOLUMES) */
|
||||
) {
|
||||
#if OS_TYPE == 0 /* Win32 */
|
||||
Mutex[vol] = CreateMutex(NULL, FALSE, NULL);
|
||||
return (int)(Mutex[vol] != INVALID_HANDLE_VALUE);
|
||||
|
||||
#elif OS_TYPE == 1 /* uITRON */
|
||||
T_CMTX cmtx = {TA_TPRI, 1};
|
||||
|
||||
Mutex[vol] = acre_mtx(&cmtx);
|
||||
return (int)(Mutex[vol] > 0);
|
||||
|
||||
#elif OS_TYPE == 2 /* uC/OS-II */
|
||||
OS_ERR err;
|
||||
|
||||
Mutex[vol] = OSMutexCreate(0, &err);
|
||||
return (int)(err == OS_NO_ERR);
|
||||
|
||||
#elif OS_TYPE == 3 /* FreeRTOS */
|
||||
Mutex[vol] = xSemaphoreCreateMutex();
|
||||
return (int)(Mutex[vol] != NULL);
|
||||
|
||||
#elif OS_TYPE == 4 /* CMSIS-RTOS */
|
||||
osMutexDef(cmsis_os_mutex);
|
||||
|
||||
Mutex[vol] = osMutexCreate(osMutex(cmsis_os_mutex));
|
||||
return (int)(Mutex[vol] != NULL);
|
||||
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
/*------------------------------------------------------------------------*/
|
||||
/* Delete a Mutex */
|
||||
/*------------------------------------------------------------------------*/
|
||||
/* This function is called in f_mount function to delete a mutex or
|
||||
/ semaphore of the volume created with ff_mutex_create function.
|
||||
*/
|
||||
|
||||
void ff_mutex_delete( /* Returns 1:Function succeeded or 0:Could not delete due to an error */
|
||||
int vol /* Mutex ID: Volume mutex (0 to FF_VOLUMES - 1) or system mutex (FF_VOLUMES) */
|
||||
) {
|
||||
#if OS_TYPE == 0 /* Win32 */
|
||||
CloseHandle(Mutex[vol]);
|
||||
|
||||
#elif OS_TYPE == 1 /* uITRON */
|
||||
del_mtx(Mutex[vol]);
|
||||
|
||||
#elif OS_TYPE == 2 /* uC/OS-II */
|
||||
OS_ERR err;
|
||||
|
||||
OSMutexDel(Mutex[vol], OS_DEL_ALWAYS, &err);
|
||||
|
||||
#elif OS_TYPE == 3 /* FreeRTOS */
|
||||
vSemaphoreDelete(Mutex[vol]);
|
||||
|
||||
#elif OS_TYPE == 4 /* CMSIS-RTOS */
|
||||
osMutexDelete(Mutex[vol]);
|
||||
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
/*------------------------------------------------------------------------*/
|
||||
/* Request a Grant to Access the Volume */
|
||||
/*------------------------------------------------------------------------*/
|
||||
/* This function is called on enter file functions to lock the volume.
|
||||
/ When a 0 is returned, the file function fails with FR_TIMEOUT.
|
||||
*/
|
||||
|
||||
int ff_mutex_take( /* Returns 1:Succeeded or 0:Timeout */
|
||||
int vol /* Mutex ID: Volume mutex (0 to FF_VOLUMES - 1) or system mutex (FF_VOLUMES) */
|
||||
) {
|
||||
#if OS_TYPE == 0 /* Win32 */
|
||||
return (int)(WaitForSingleObject(Mutex[vol], FF_FS_TIMEOUT) == WAIT_OBJECT_0);
|
||||
|
||||
#elif OS_TYPE == 1 /* uITRON */
|
||||
return (int)(tloc_mtx(Mutex[vol], FF_FS_TIMEOUT) == E_OK);
|
||||
|
||||
#elif OS_TYPE == 2 /* uC/OS-II */
|
||||
OS_ERR err;
|
||||
|
||||
OSMutexPend(Mutex[vol], FF_FS_TIMEOUT, &err));
|
||||
return (int)(err == OS_NO_ERR);
|
||||
|
||||
#elif OS_TYPE == 3 /* FreeRTOS */
|
||||
return (int)(xSemaphoreTake(Mutex[vol], FF_FS_TIMEOUT) == pdTRUE);
|
||||
|
||||
#elif OS_TYPE == 4 /* CMSIS-RTOS */
|
||||
return (int)(osMutexWait(Mutex[vol], FF_FS_TIMEOUT) == osOK);
|
||||
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*------------------------------------------------------------------------*/
|
||||
/* Release a Grant to Access the Volume */
|
||||
/*------------------------------------------------------------------------*/
|
||||
/* This function is called on leave file functions to unlock the volume.
|
||||
*/
|
||||
|
||||
void ff_mutex_give(
|
||||
int vol /* Mutex ID: Volume mutex (0 to FF_VOLUMES - 1) or system mutex (FF_VOLUMES) */
|
||||
) {
|
||||
#if OS_TYPE == 0 /* Win32 */
|
||||
ReleaseMutex(Mutex[vol]);
|
||||
|
||||
#elif OS_TYPE == 1 /* uITRON */
|
||||
unl_mtx(Mutex[vol]);
|
||||
|
||||
#elif OS_TYPE == 2 /* uC/OS-II */
|
||||
OSMutexPost(Mutex[vol]);
|
||||
|
||||
#elif OS_TYPE == 3 /* FreeRTOS */
|
||||
xSemaphoreGive(Mutex[vol]);
|
||||
|
||||
#elif OS_TYPE == 4 /* CMSIS-RTOS */
|
||||
osMutexRelease(Mutex[vol]);
|
||||
|
||||
#endif
|
||||
}
|
||||
|
||||
#endif /* FF_FS_REENTRANT */
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,95 @@
|
||||
// FatFS + FatFSUSB listFiles example
|
||||
|
||||
#include <FatFS.h>
|
||||
#include <FatFSUSB.h>
|
||||
|
||||
volatile bool updated = false;
|
||||
volatile bool driveConnected = false;
|
||||
volatile bool inPrinting = false;
|
||||
|
||||
// Called by FatFSUSB when the drive is released. We note this, restart FatFS, and tell the main loop to rescan.
|
||||
void unplug(uint32_t i) {
|
||||
(void) i;
|
||||
driveConnected = false;
|
||||
updated = true;
|
||||
FatFS.begin();
|
||||
}
|
||||
|
||||
// Called by FatFSUSB when the drive is mounted by the PC. Have to stop FatFS, since the drive data can change, note it, and continue.
|
||||
void plug(uint32_t i) {
|
||||
(void) i;
|
||||
driveConnected = true;
|
||||
FatFS.end();
|
||||
}
|
||||
|
||||
// Called by FatFSUSB to determine if it is safe to let the PC mount the USB drive. If we're accessing the FS in any way, have any Files open, etc. then it's not safe to let the PC mount the drive.
|
||||
bool mountable(uint32_t i) {
|
||||
(void) i;
|
||||
return !inPrinting;
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
while (!Serial) {
|
||||
delay(1);
|
||||
}
|
||||
delay(5000);
|
||||
|
||||
if (!FatFS.begin()) {
|
||||
Serial.println("FatFS initialization failed!");
|
||||
while (1) {
|
||||
delay(1);
|
||||
}
|
||||
}
|
||||
Serial.println("FatFS initialization done.");
|
||||
|
||||
inPrinting = true;
|
||||
printDirectory("/", 0);
|
||||
inPrinting = false;
|
||||
|
||||
// Set up callbacks
|
||||
FatFSUSB.onUnplug(unplug);
|
||||
FatFSUSB.onPlug(plug);
|
||||
FatFSUSB.driveReady(mountable);
|
||||
// Start FatFS USB drive mode
|
||||
FatFSUSB.begin();
|
||||
Serial.println("FatFSUSB started.");
|
||||
Serial.println("Connect drive via USB to upload/erase files and re-display");
|
||||
}
|
||||
|
||||
void loop() {
|
||||
if (updated && !driveConnected) {
|
||||
inPrinting = true;
|
||||
Serial.println("\n\nDisconnected, new file listing:");
|
||||
printDirectory("/", 0);
|
||||
updated = false;
|
||||
inPrinting = false;
|
||||
}
|
||||
}
|
||||
|
||||
void printDirectory(String dirName, int numTabs) {
|
||||
Dir dir = FatFS.openDir(dirName);
|
||||
|
||||
while (true) {
|
||||
|
||||
if (!dir.next()) {
|
||||
// no more files
|
||||
break;
|
||||
}
|
||||
for (uint8_t i = 0; i < numTabs; i++) {
|
||||
Serial.print('\t');
|
||||
}
|
||||
Serial.print(dir.fileName());
|
||||
if (dir.isDirectory()) {
|
||||
Serial.println("/");
|
||||
printDirectory(dirName + "/" + dir.fileName(), numTabs + 1);
|
||||
} else {
|
||||
// files have sizes, directories do not
|
||||
Serial.print("\t\t");
|
||||
Serial.print(dir.fileSize(), DEC);
|
||||
time_t cr = dir.fileCreationTime();
|
||||
struct tm* tmstruct = localtime(&cr);
|
||||
Serial.printf("\t%d-%02d-%02d %02d:%02d:%02d\n", (tmstruct->tm_year) + 1900, (tmstruct->tm_mon) + 1, tmstruct->tm_mday, tmstruct->tm_hour, tmstruct->tm_min, tmstruct->tm_sec);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
#######################################
|
||||
# Syntax Coloring Map
|
||||
#######################################
|
||||
|
||||
#######################################
|
||||
# Datatypes (KEYWORD1)
|
||||
#######################################
|
||||
|
||||
FatFSUSB KEYWORD1
|
||||
|
||||
#######################################
|
||||
# Methods and Functions (KEYWORD2)
|
||||
#######################################
|
||||
|
||||
driveReady KEYWORD1
|
||||
onPlug KEYWORD1
|
||||
onUnplug KEYWORD1
|
||||
|
||||
#######################################
|
||||
# Constants (LITERAL1)
|
||||
#######################################
|
||||
@@ -0,0 +1,11 @@
|
||||
name=FatFSUSB
|
||||
version=1.0.0
|
||||
author=Earle F. Philhower, III <earlephilhower@yahoo.com>
|
||||
maintainer=Earle F. Philhower, III <earlephilhower@yahoo.com>
|
||||
sentence=Allows using USB MSC (USB stick) to transfer an onboard flash file to a PC
|
||||
paragraph=Emulates a USB stick and presents a single file for users to copy over/erase
|
||||
category=Device Control
|
||||
url=https://github.com/earlephilhower/arduino-pico
|
||||
architectures=rp2040
|
||||
dot_a_linkage=true
|
||||
depends=FatFS
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user