Compare commits
@@ -25,7 +25,7 @@ jobs:
|
||||
uses: codespell-project/actions-codespell@master
|
||||
with:
|
||||
skip: ./ArduinoCore-API,./libraries/ESP8266SdFat,./libraries/Adafruit_TinyUSB_Arduino,./libraries/LittleFS/lib,./tools/pyserial,./pico-sdk,./.github,./docs/i2s.rst,./cores/rp2040/api,./libraries/FreeRTOS,./tools/libbearssl/bearssl,./include,./libraries/WiFi/examples/BearSSL_Server,./ota/uzlib,./libraries/http-parser/lib,./libraries/WebServer/examples/HelloServerBearSSL/HelloServerBearSSL.ino,./libraries/HTTPUpdateServer/examples/SecureBearSSLUpdater/SecureBearSSLUpdater.ino,./.git,./libraries/FatFS/lib/fatfs,./libraries/FatFS/src/diskio.h,./libraries/FatFS/src/ff.cpp,./libraries/FatFS/src/ffconf.h,./libraries/FatFS/src/ffsystem.cpp,./libraries/FatFS/src/ff.h,./libraries/lwIP_WINC1500/src/driver,./libraries/lwIP_WINC1500/src/common,./libraries/lwIP_WINC1500/src/bus_wrapper,./libraries/lwIP_WINC1500/src/spi_flash
|
||||
ignore_words_list: ser,dout,shiftIn
|
||||
ignore_words_list: ser,dout,shiftIn,acount
|
||||
|
||||
# Consistent style
|
||||
astyle:
|
||||
|
||||
@@ -40,3 +40,6 @@
|
||||
[submodule "libraries/FatFS/lib/SPIFTL"]
|
||||
path = libraries/FatFS/lib/SPIFTL
|
||||
url = https://github.com/earlephilhower/SPIFTL.git
|
||||
[submodule "libraries/AsyncUDP"]
|
||||
path = libraries/AsyncUDP
|
||||
url = https://github.com/earlephilhower/AsyncUDP.git
|
||||
|
||||
@@ -27,6 +27,7 @@ Read the [Contributing Guide](https://github.com/earlephilhower/arduino-pico/blo
|
||||
* Adafruit Trinkey RP2040 QT
|
||||
* Arduino Nano RP2040 Connect
|
||||
* ArtronShop RP2 Nano
|
||||
* Breadstick Raspberry
|
||||
* BridgeTek IDM2040-7A
|
||||
* Cytron Maker Pi RP2040
|
||||
* Cytron Maker Nano RP2040
|
||||
@@ -37,6 +38,7 @@ Read the [Contributing Guide](https://github.com/earlephilhower/arduino-pico/blo
|
||||
* DFRobot Beetle RP2040
|
||||
* ElectronicCats Hunter Cat NFC
|
||||
* ExtremeElectronics RC2040
|
||||
* GroundStudio Marble Pico
|
||||
* Invector Labs Challenger RP2040 WiFi
|
||||
* Invector Labs Challenger RP2040 WiFi/BLE
|
||||
* Invector Labs Challenger RP2040 WiFi6/BLE
|
||||
@@ -49,6 +51,7 @@ 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
|
||||
@@ -85,6 +88,7 @@ Read the [Contributing Guide](https://github.com/earlephilhower/arduino-pico/blo
|
||||
# Features
|
||||
* Adafruit TinyUSB Arduino (USB mouse, keyboard, flash drive, generic HID, CDC Serial, MIDI, WebUSB, others)
|
||||
* Bluetooth on the PicoW (Classic and BLE) with Keyboard, Mouse, Joystick, and Virtual Serial
|
||||
* Bluetooth Classic and BLE HID master mode (connect to BT keyboard, mouse, or joystick)
|
||||
* Generic Arduino USB Serial, Keyboard, Joystick, and Mouse emulation
|
||||
* WiFi (Pico W, ESP32-based ESPHost, Atmel WINC1500)
|
||||
* Ethernet (Wired W5500, W5100, ENC28J60)
|
||||
@@ -98,7 +102,7 @@ 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
|
||||
* Bluetooth A2DP audio source (output) on the PicoW
|
||||
* 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
|
||||
|
||||
+2087
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,5 @@
|
||||
#pragma once
|
||||
#define ARDUINO_PICO_MAJOR 3
|
||||
#define ARDUINO_PICO_MINOR 9
|
||||
#define ARDUINO_PICO_REVISION 0
|
||||
#define ARDUINO_PICO_VERSION_STR "3.9.0"
|
||||
#define ARDUINO_PICO_REVISION 3
|
||||
#define ARDUINO_PICO_VERSION_STR "3.9.3"
|
||||
|
||||
@@ -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.
|
||||
+5
-3
@@ -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
|
||||
|
||||
+2
-2
@@ -54,9 +54,9 @@ author = u'Earle F. Philhower, III'
|
||||
# built documents.
|
||||
#
|
||||
# The short X.Y version.
|
||||
version = u'3.9.0'
|
||||
version = u'3.9.3'
|
||||
# The full version, including alpha/beta/rc tags.
|
||||
release = u'3.9.0'
|
||||
release = u'3.9.3'
|
||||
|
||||
# The language for content autogenerated by Sphinx. Refer to documentation
|
||||
# for a list of supported languages.
|
||||
|
||||
+2
-2
@@ -598,7 +598,7 @@ Close the file. No other operations should be performed on *File* object
|
||||
after ``close`` function was called.
|
||||
|
||||
openNextFile (compatibility method, not recommended for new code)
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. code:: cpp
|
||||
|
||||
@@ -610,7 +610,7 @@ Opens the next file in the directory pointed to by the File. Only valid
|
||||
when ``File.isDirectory() == true``.
|
||||
|
||||
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.
|
||||
+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>
|
||||
|
||||
|
||||
+16
-17
@@ -14,6 +14,10 @@ extern void interrupts();
|
||||
extern unsigned long __lwip_rand(void);
|
||||
#define LWIP_RAND() __lwip_rand()
|
||||
|
||||
#ifndef __LWIP_MEMMULT
|
||||
#define __LWIP_MEMMULT 1
|
||||
#endif
|
||||
|
||||
// Common settings used in most of the pico_w examples
|
||||
// (see https://www.nongnu.org/lwip/2_1_x/group__lwip__opts.html for details)
|
||||
|
||||
@@ -22,10 +26,10 @@ extern unsigned long __lwip_rand(void);
|
||||
#define MEM_LIBC_MALLOC 0
|
||||
|
||||
#define MEM_ALIGNMENT 4
|
||||
#define MEM_SIZE 16384
|
||||
#define MEMP_NUM_TCP_SEG 32
|
||||
#define MEMP_NUM_ARP_QUEUE 10
|
||||
#define PBUF_POOL_SIZE 24
|
||||
#define MEM_SIZE (__LWIP_MEMMULT * 16384)
|
||||
#define MEMP_NUM_TCP_SEG (32)
|
||||
#define MEMP_NUM_ARP_QUEUE (10)
|
||||
#define PBUF_POOL_SIZE (__LWIP_MEMMULT > 1 ? 32 : 24)
|
||||
#define LWIP_ARP 2
|
||||
#define LWIP_ETHERNET 1
|
||||
#define LWIP_ICMP 1
|
||||
@@ -38,11 +42,12 @@ extern unsigned long __lwip_rand(void);
|
||||
#define LWIP_NETIF_LINK_CALLBACK 1
|
||||
#define LWIP_NETIF_HOSTNAME 1
|
||||
#define LWIP_NETCONN 0
|
||||
#define MEM_STATS 1
|
||||
#define SYS_STATS 1
|
||||
#define MEMP_STATS 1
|
||||
#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 0
|
||||
#define LWIP_DHCP 1
|
||||
#define LWIP_IPV4 1
|
||||
@@ -55,7 +60,8 @@ extern unsigned long __lwip_rand(void);
|
||||
#define LWIP_DHCP_DOES_ACD_CHECK 0
|
||||
|
||||
// See #1285
|
||||
#define MEMP_NUM_UDP_PCB 6
|
||||
#define MEMP_NUM_UDP_PCB (__LWIP_MEMMULT * 6)
|
||||
#define MEMP_NUM_TCP_PCB (__LWIP_MEMMULT * 5)
|
||||
|
||||
#if LWIP_IPV6
|
||||
#define LWIP_IPV6_DHCP6 1
|
||||
@@ -68,14 +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
|
||||
#define MEMP_STATS 1
|
||||
#define MEM_STATS 1
|
||||
#endif
|
||||
|
||||
#define LWIP_DEBUG 0
|
||||
#define ETHARP_DEBUG LWIP_DBG_OFF
|
||||
#define NETIF_DEBUG LWIP_DBG_OFF
|
||||
#define PBUF_DEBUG LWIP_DBG_OFF
|
||||
|
||||
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.
Submodule libraries/Adafruit_TinyUSB_Arduino updated: d629476752...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 dd32bfa7d9
@@ -24,8 +24,9 @@
|
||||
#include <hardware/irq.h>
|
||||
#include "AudioBufferManager.h"
|
||||
|
||||
static int __channelCount = 0; // # of channels left. When we hit 0, then remove our handler
|
||||
static AudioBufferManager* __channelMap[12]; // Lets the IRQ handler figure out where to dispatch to
|
||||
static int __channelCount = 0; // # of channels left. When we hit 0, then remove our handler
|
||||
static AudioBufferManager* __channelMap[12]; // Lets the IRQ handler figure out where to dispatch to
|
||||
static bool __irqInstalled = false; // Have we put in our IRQ handler yet?
|
||||
|
||||
AudioBufferManager::AudioBufferManager(size_t bufferCount, size_t bufferWords, int32_t silenceSample, PinMode direction, enum dma_channel_transfer_size dmaSize) {
|
||||
_running = false;
|
||||
@@ -78,11 +79,6 @@ AudioBufferManager::~AudioBufferManager() {
|
||||
dma_channel_unclaim(_channelDMA[i]);
|
||||
__channelCount--;
|
||||
}
|
||||
if (!__channelCount) {
|
||||
irq_set_enabled(DMA_IRQ_0, false);
|
||||
// TODO - how can we know if there are no other parts of the core using DMA0 IRQ??
|
||||
irq_remove_handler(DMA_IRQ_0, _irq);
|
||||
}
|
||||
}
|
||||
interrupts();
|
||||
for (int i = 0; i < 2; i++) {
|
||||
@@ -120,7 +116,7 @@ bool AudioBufferManager::begin(int dreq, volatile void *pioFIFOAddr) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
bool needSetIRQ = __channelCount == 0;
|
||||
|
||||
// Need to know both channels to set up ping-pong, so do in 2 stages
|
||||
for (auto i = 0; i < 2; i++) {
|
||||
dma_channel_config c = dma_channel_get_default_config(_channelDMA[i]);
|
||||
@@ -146,9 +142,10 @@ bool AudioBufferManager::begin(int dreq, volatile void *pioFIFOAddr) {
|
||||
__channelMap[_channelDMA[i]] = this;
|
||||
__channelCount++;
|
||||
}
|
||||
if (needSetIRQ) {
|
||||
if (!__irqInstalled) {
|
||||
irq_add_shared_handler(DMA_IRQ_0, _irq, PICO_SHARED_IRQ_HANDLER_DEFAULT_ORDER_PRIORITY);
|
||||
irq_set_enabled(DMA_IRQ_0, true);
|
||||
__irqInstalled = true;
|
||||
}
|
||||
|
||||
dma_channel_start(_channelDMA[0]);
|
||||
|
||||
@@ -43,9 +43,10 @@ void setup() {
|
||||
a2dp.begin();
|
||||
}
|
||||
|
||||
char *nowPlaying = nullptr;
|
||||
|
||||
void loop() {
|
||||
if (BOOTSEL) {
|
||||
__lockBluetooth();
|
||||
if (status == A2DPSink::PAUSED) {
|
||||
a2dp.play();
|
||||
Serial.printf("Resuming\n");
|
||||
@@ -53,7 +54,11 @@ void loop() {
|
||||
a2dp.pause();
|
||||
Serial.printf("Pausing\n");
|
||||
}
|
||||
__unlockBluetooth();
|
||||
while (BOOTSEL);
|
||||
}
|
||||
if (!nowPlaying || strcmp(nowPlaying, a2dp.trackTitle())) {
|
||||
free(nowPlaying);
|
||||
nowPlaying = strdup(a2dp.trackTitle());
|
||||
Serial.printf("NOW PLAYING: %s\n", nowPlaying);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,9 +7,7 @@
|
||||
#######################################
|
||||
|
||||
BluetoothAudio KEYWORD1
|
||||
BluetoothHCI KEYWORD1
|
||||
A2DPSource KEYWORD1
|
||||
BTDeviceInfo KEYWORD1
|
||||
BluetoothAudioConsumer KEYWORD1
|
||||
BluetoothAudioConsumerI2S KEYWORD1
|
||||
BluetoothAudioConsumerPWM KEYWORD1
|
||||
@@ -18,6 +16,7 @@ A2DPSink KEYWORD1
|
||||
#######################################
|
||||
# Methods and Functions (KEYWORD2)
|
||||
#######################################
|
||||
scan KEYWORD2
|
||||
begin KEYWORD2
|
||||
end KEYWORD2
|
||||
|
||||
@@ -52,13 +51,6 @@ onVolume KEYWORD2
|
||||
onConnect KEYWORD2
|
||||
onPlaybackStatus KEYWORD2
|
||||
|
||||
# BTDeviceInfo
|
||||
deviceClass KEYWORD2
|
||||
address KEYWORD2
|
||||
addressString KEYWORD2
|
||||
rssi KEYWORD2
|
||||
name KEYWORD2
|
||||
|
||||
#######################################
|
||||
# Constants (LITERAL1)
|
||||
#######################################
|
||||
|
||||
@@ -8,3 +8,4 @@ category=Communication
|
||||
url=http://github.com/earlephilhower/arduino-pico
|
||||
architectures=rp2040
|
||||
dot_a_linkage=true
|
||||
depends=BluetoothHCI
|
||||
|
||||
@@ -191,9 +191,10 @@ bool A2DPSink::begin() {
|
||||
}
|
||||
|
||||
bool A2DPSink::disconnect() {
|
||||
__lockBluetooth();
|
||||
a2dp_sink_disconnect(a2dp_sink_a2dp_connection.a2dp_cid);
|
||||
__unlockBluetooth();
|
||||
BluetoothLock b;
|
||||
if (_connected) {
|
||||
a2dp_sink_disconnect(a2dp_sink_a2dp_connection.a2dp_cid);
|
||||
}
|
||||
if (!_running || !_connected) {
|
||||
return false;
|
||||
}
|
||||
@@ -202,10 +203,11 @@ bool A2DPSink::disconnect() {
|
||||
}
|
||||
|
||||
void A2DPSink::clearPairing() {
|
||||
disconnect();
|
||||
__lockBluetooth();
|
||||
BluetoothLock b;
|
||||
if (_connected) {
|
||||
a2dp_sink_disconnect(a2dp_sink_a2dp_connection.a2dp_cid);
|
||||
}
|
||||
gap_delete_all_link_keys();
|
||||
__unlockBluetooth();
|
||||
}
|
||||
|
||||
|
||||
@@ -557,6 +559,14 @@ void A2DPSink::avrcp_controller_packet_handler(uint8_t packet_type, uint16_t cha
|
||||
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;
|
||||
|
||||
@@ -583,6 +593,8 @@ void A2DPSink::avrcp_controller_packet_handler(uint8_t packet_type, uint16_t cha
|
||||
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;
|
||||
@@ -590,6 +602,8 @@ void A2DPSink::avrcp_controller_packet_handler(uint8_t packet_type, uint16_t cha
|
||||
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;
|
||||
@@ -597,6 +611,8 @@ void A2DPSink::avrcp_controller_packet_handler(uint8_t packet_type, uint16_t cha
|
||||
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;
|
||||
@@ -604,6 +620,8 @@ void A2DPSink::avrcp_controller_packet_handler(uint8_t packet_type, uint16_t cha
|
||||
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;
|
||||
|
||||
@@ -21,7 +21,8 @@
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include "BluetoothHCI.h"
|
||||
#include <BluetoothHCI.h>
|
||||
#include <BluetoothLock.h>
|
||||
#include "BluetoothAudioConsumer.h"
|
||||
#include "BluetoothMediaConfigurationSBC.h"
|
||||
|
||||
@@ -32,6 +33,10 @@
|
||||
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
|
||||
@@ -95,6 +100,11 @@ public:
|
||||
_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;
|
||||
@@ -120,65 +130,91 @@ public:
|
||||
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);
|
||||
|
||||
@@ -195,7 +231,7 @@ private:
|
||||
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;
|
||||
BluetoothHCI _hci;
|
||||
BluetoothAudioConsumer_ *_consumer = nullptr;
|
||||
bool _running = false;
|
||||
bool _connected = false;
|
||||
@@ -213,6 +249,9 @@ private:
|
||||
void *_connectData;
|
||||
void (*_playbackStatusCB)(void *, PlaybackStatus) = nullptr;
|
||||
void *_playbackStatusData;
|
||||
void (*_trackChangedCB)(void *) = nullptr;
|
||||
void *_trackChangedData;
|
||||
|
||||
char *_name = nullptr;
|
||||
uint8_t _sourceAddress[6];
|
||||
|
||||
@@ -290,4 +329,9 @@ private:
|
||||
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];
|
||||
};
|
||||
|
||||
@@ -196,11 +196,11 @@ bool A2DPSource::connect(const uint8_t *addr) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool A2DPSource::disconnect() {
|
||||
__lockBluetooth();
|
||||
a2dp_source_disconnect(media_tracker.a2dp_cid);
|
||||
__unlockBluetooth();
|
||||
BluetoothLock b;
|
||||
if (_connected) {
|
||||
a2dp_source_disconnect(media_tracker.a2dp_cid);
|
||||
}
|
||||
if (!_running || !_connected) {
|
||||
return false;
|
||||
}
|
||||
@@ -209,17 +209,20 @@ bool A2DPSource::disconnect() {
|
||||
}
|
||||
|
||||
void A2DPSource::clearPairing() {
|
||||
disconnect();
|
||||
__lockBluetooth();
|
||||
BluetoothLock b;
|
||||
if (_connected) {
|
||||
a2dp_source_disconnect(media_tracker.a2dp_cid);
|
||||
}
|
||||
gap_delete_all_link_keys();
|
||||
__unlockBluetooth();
|
||||
}
|
||||
|
||||
// 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;
|
||||
__lockBluetooth();
|
||||
|
||||
// First copy from writer to either end of
|
||||
uint32_t start = _pcmWriter;
|
||||
uint32_t end = _pcmReader > _pcmWriter ? _pcmReader : _pcmBufferSize;
|
||||
@@ -244,13 +247,12 @@ size_t A2DPSource::write(const uint8_t *buffer, size_t size) {
|
||||
_pcmWriter += end - start;
|
||||
_pcmWriter %= _pcmBufferSize;
|
||||
}
|
||||
__unlockBluetooth();
|
||||
return count;
|
||||
}
|
||||
|
||||
int A2DPSource::availableForWrite() {
|
||||
BluetoothLock b;
|
||||
int avail = 0;
|
||||
__lockBluetooth();
|
||||
if (_pcmWriter == _pcmReader) {
|
||||
avail = _pcmBufferSize - 1;
|
||||
} else if (_pcmReader > _pcmWriter) {
|
||||
@@ -258,7 +260,6 @@ int A2DPSource::availableForWrite() {
|
||||
} else {
|
||||
avail = _pcmBufferSize - _pcmWriter + _pcmReader - 1;
|
||||
}
|
||||
__unlockBluetooth();
|
||||
return avail;
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,8 @@
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include "BluetoothHCI.h"
|
||||
#include <BluetoothHCI.h>
|
||||
#include <BluetoothLock.h>
|
||||
#include "BluetoothMediaConfigurationSBC.h"
|
||||
#include <functional>
|
||||
#include <list>
|
||||
@@ -84,13 +85,12 @@ public:
|
||||
}
|
||||
|
||||
bool getUnderflow() {
|
||||
BluetoothLock b;
|
||||
if (!_running) {
|
||||
return false;
|
||||
}
|
||||
__lockBluetooth();
|
||||
auto ret = _underflow;
|
||||
_underflow = false;
|
||||
__unlockBluetooth();
|
||||
return ret;
|
||||
}
|
||||
|
||||
@@ -104,7 +104,7 @@ public:
|
||||
|
||||
bool begin();
|
||||
|
||||
std::list<BTDeviceInfo> scan(uint32_t mask = BluetoothHCI_::speaker_cod, int scanTimeSec = 5, bool async = false) {
|
||||
std::vector<BTDeviceInfo> scan(uint32_t mask = BluetoothHCI::speaker_cod, int scanTimeSec = 5, bool async = false) {
|
||||
return _hci.scan(mask, scanTimeSec, async);
|
||||
}
|
||||
|
||||
@@ -144,7 +144,7 @@ public:
|
||||
|
||||
|
||||
private:
|
||||
BluetoothHCI_ _hci;
|
||||
BluetoothHCI _hci;
|
||||
bool _running = false;
|
||||
bool _connected = false;
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#include "BluetoothDevice.h"
|
||||
#include "BluetoothHCI.h"
|
||||
#include <_needsbt.h>
|
||||
#include <BluetoothLock.h>
|
||||
#include <BluetoothDevice.h>
|
||||
#include <BluetoothHCI.h>
|
||||
#include "BluetoothMediaConfigurationSBC.h"
|
||||
#include "A2DPSource.h"
|
||||
#include "A2DPSink.h"
|
||||
|
||||
@@ -75,10 +75,8 @@ void BluetoothAudioConsumerI2S::fill() {
|
||||
_a2dpSink->playback_handler((int16_t *) buff, 32);
|
||||
num_samples -= 64;
|
||||
for (int i = 0; i < 64; i++) {
|
||||
int32_t tmp = buff[i];
|
||||
tmp *= _gain;
|
||||
tmp >>= 8;
|
||||
_i2s->write((int16_t)tmp);
|
||||
buff[i] = (((int32_t)buff[i]) * _gain) >> 8;
|
||||
}
|
||||
_i2s->write((uint8_t *)buff, 64 * 2);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,10 +76,8 @@ void BluetoothAudioConsumerPWM::fill() {
|
||||
_a2dpSink->playback_handler((int16_t *) buff, 32);
|
||||
num_samples -= 64;
|
||||
for (int i = 0; i < 64; i++) {
|
||||
int32_t tmp = buff[i];
|
||||
tmp *= _gain;
|
||||
tmp >>= 8;
|
||||
_pwm->write((int16_t)tmp);
|
||||
buff[i] = (((int32_t)buff[i]) * _gain) >> 8;
|
||||
}
|
||||
_pwm->write((uint8_t *)buff, 64 * 2);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,162 +0,0 @@
|
||||
/*
|
||||
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"
|
||||
|
||||
#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_::install() {
|
||||
// Register for HCI events.
|
||||
hci_event_callback_registration.callback = PACKETHANDLERCB(BluetoothHCI_, hci_packet_handler);
|
||||
hci_add_event_handler(&hci_event_callback_registration);
|
||||
}
|
||||
|
||||
void BluetoothHCI_::begin() {
|
||||
_running = true;
|
||||
hci_power_control(HCI_POWER_ON);
|
||||
}
|
||||
|
||||
void BluetoothHCI_::uninstall() {
|
||||
__lockBluetooth();
|
||||
hci_remove_event_handler(&hci_event_callback_registration);
|
||||
_running = false;
|
||||
__unlockBluetooth();
|
||||
}
|
||||
|
||||
bool BluetoothHCI_::running() {
|
||||
return _hciRunning;
|
||||
}
|
||||
|
||||
std::list<BTDeviceInfo> BluetoothHCI_::scan(uint32_t mask, int scanTimeSec, bool async) {
|
||||
_scanMask = mask;
|
||||
_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");
|
||||
__lockBluetooth();
|
||||
gap_inquiry_start(inquiryTime);
|
||||
__unlockBluetooth();
|
||||
if (async) {
|
||||
return _btdList;
|
||||
}
|
||||
|
||||
while (_scanning) {
|
||||
delay(10);
|
||||
}
|
||||
DEBUGV("HCI::scan(): inquiry end\n");
|
||||
return _btdList;
|
||||
}
|
||||
|
||||
bool BluetoothHCI_::scanAsyncDone() {
|
||||
return _scanning;
|
||||
}
|
||||
std::list<BTDeviceInfo> BluetoothHCI_::scanAsyncResult() {
|
||||
return _btdList;
|
||||
}
|
||||
|
||||
|
||||
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);
|
||||
_btdList.push_back(btd);
|
||||
}
|
||||
break;
|
||||
case GAP_EVENT_INQUIRY_COMPLETE:
|
||||
_scanning = false;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
+27
-10
@@ -24,43 +24,60 @@
|
||||
|
||||
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;
|
||||
_name = strdup(name);
|
||||
strncpy(_name, name, sizeof(_name));
|
||||
_name[sizeof(_name) - 1] = 0;
|
||||
}
|
||||
// Copy constructor to ensure we deep-copy the string
|
||||
BTDeviceInfo(const BTDeviceInfo &b) {
|
||||
_deviceClass = b._deviceClass;
|
||||
memcpy(_address, b._address, sizeof(_address));
|
||||
memcpy(_addressString, b._addressString, sizeof(_addressString));
|
||||
_rssi = b._rssi;
|
||||
_name = strdup(b._name);
|
||||
|
||||
// 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() {
|
||||
free(_name);
|
||||
}
|
||||
|
||||
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;
|
||||
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;
|
||||
}
|
||||
}
|
||||
+30
-4
@@ -20,6 +20,7 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <_needsbt.h>
|
||||
#include <Arduino.h>
|
||||
#include <list>
|
||||
#include <memory>
|
||||
@@ -28,25 +29,50 @@
|
||||
#include <btstack.h>
|
||||
|
||||
|
||||
class BluetoothHCI_ {
|
||||
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::list<BTDeviceInfo> scan(uint32_t mask, int scanTimeSec = 5, bool async = false);
|
||||
std::vector<BTDeviceInfo> scan(uint32_t mask, int scanTimeSec = 5, bool async = false);
|
||||
bool scanAsyncDone();
|
||||
std::list<BTDeviceInfo> scanAsyncResult();
|
||||
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;
|
||||
std::list<BTDeviceInfo> _btdList;
|
||||
// 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);
|
||||
};
|
||||
@@ -24,10 +24,12 @@
|
||||
|
||||
*/
|
||||
#include <Arduino.h>
|
||||
|
||||
#include "HTTPClient.h"
|
||||
#include <WiFi.h>
|
||||
#include <time.h>
|
||||
#include "base64.h"
|
||||
extern "C" char *strptime(const char *__restrict, const char *__restrict, struct tm *__restrict); // Not exposed by headers?
|
||||
|
||||
|
||||
// per https://github.com/esp8266/Arduino/issues/8231
|
||||
// make sure HTTPClient can be utilized as a movable class member
|
||||
@@ -205,6 +207,7 @@ bool HTTPClient::begin(WiFiClient &client, const String& url) {
|
||||
}
|
||||
|
||||
_port = (protocol == "https" ? 443 : 80);
|
||||
_secure = (protocol == "https");
|
||||
_clientIn = client.clone();
|
||||
_clientGiven = true;
|
||||
if (_clientMade) {
|
||||
@@ -246,6 +249,7 @@ bool HTTPClient::begin(WiFiClient &client, const String& host, uint16_t port, co
|
||||
_port = port;
|
||||
_uri = uri;
|
||||
_protocol = (https ? "https" : "http");
|
||||
_secure = https;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -590,6 +594,12 @@ int HTTPClient::sendRequest(const char * type, const uint8_t * payload, size_t s
|
||||
|
||||
addHeader(F("Content-Length"), String(payload && size > 0 ? size : 0));
|
||||
|
||||
// add cookies to header, if present
|
||||
String cookie_string;
|
||||
if (generateCookieString(&cookie_string)) {
|
||||
addHeader("Cookie", cookie_string);
|
||||
}
|
||||
|
||||
// send Header
|
||||
if (!sendHeader(type)) {
|
||||
return returnError(HTTPC_ERROR_SEND_HEADER_FAILED);
|
||||
@@ -691,6 +701,12 @@ int HTTPClient::sendRequest(const char * type, Stream * stream, size_t size) {
|
||||
addHeader(F("Content-Length"), String(size));
|
||||
}
|
||||
|
||||
// add cookies to header, if present
|
||||
String cookie_string;
|
||||
if (generateCookieString(&cookie_string)) {
|
||||
addHeader("Cookie", cookie_string);
|
||||
}
|
||||
|
||||
// send Header
|
||||
if (!sendHeader(type)) {
|
||||
return returnError(HTTPC_ERROR_SEND_HEADER_FAILED);
|
||||
@@ -955,7 +971,7 @@ void HTTPClient::collectHeaders(const char* headerKeys[], const size_t headerKey
|
||||
|
||||
String HTTPClient::header(const char* name) {
|
||||
for (size_t i = 0; i < _headerKeysCount; ++i) {
|
||||
if (_currentHeaders[i].key == name) {
|
||||
if (_currentHeaders[i].key.equalsIgnoreCase(name)) {
|
||||
return _currentHeaders[i].value;
|
||||
}
|
||||
}
|
||||
@@ -982,7 +998,7 @@ int HTTPClient::headers() {
|
||||
|
||||
bool HTTPClient::hasHeader(const char* name) {
|
||||
for (size_t i = 0; i < _headerKeysCount; ++i) {
|
||||
if ((_currentHeaders[i].key == name) && (_currentHeaders[i].value.length() > 0)) {
|
||||
if ((_currentHeaders[i].key.equalsIgnoreCase(name)) && (_currentHeaders[i].value.length() > 0)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1100,6 +1116,7 @@ int HTTPClient::handleHeaderResponse() {
|
||||
|
||||
_transferEncoding = HTTPC_TE_IDENTITY;
|
||||
unsigned long lastDataTime = millis();
|
||||
String date;
|
||||
|
||||
while (connected()) {
|
||||
size_t len = _client()->available();
|
||||
@@ -1127,6 +1144,10 @@ int HTTPClient::handleHeaderResponse() {
|
||||
_size = headerValue.toInt();
|
||||
}
|
||||
|
||||
if (headerName.equalsIgnoreCase("Date")) {
|
||||
date = headerValue;
|
||||
}
|
||||
|
||||
if (_canReuse && headerName.equalsIgnoreCase(F("Connection"))) {
|
||||
if (headerValue.indexOf(F("close")) >= 0 &&
|
||||
headerValue.indexOf(F("keep-alive")) < 0) {
|
||||
@@ -1142,15 +1163,20 @@ int HTTPClient::handleHeaderResponse() {
|
||||
_location = headerValue;
|
||||
}
|
||||
|
||||
if (headerName.equalsIgnoreCase("Set-Cookie")) {
|
||||
setCookie(date, headerValue);
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < _headerKeysCount; i++) {
|
||||
if (_currentHeaders[i].key.equalsIgnoreCase(headerName)) {
|
||||
if (_currentHeaders[i].value != "") {
|
||||
// Existing value, append this one with a comma
|
||||
_currentHeaders[i].value += ',';
|
||||
_currentHeaders[i].value += headerValue;
|
||||
} else {
|
||||
_currentHeaders[i].value = headerValue;
|
||||
}
|
||||
// Uncomment the following lines if you need to add support for multiple headers with the same key:
|
||||
// if (!_currentHeaders[i].value.isEmpty()) {
|
||||
// // Existing value, append this one with a comma
|
||||
// _currentHeaders[i].value += ',';
|
||||
// _currentHeaders[i].value += headerValue;
|
||||
// } else {
|
||||
_currentHeaders[i].value = headerValue;
|
||||
// }
|
||||
break; // We found a match, stop looking
|
||||
}
|
||||
}
|
||||
@@ -1210,3 +1236,176 @@ int HTTPClient::returnError(int error) {
|
||||
}
|
||||
return error;
|
||||
}
|
||||
|
||||
void HTTPClient::setCookieJar(CookieJar* cookieJar) {
|
||||
_cookieJar = cookieJar;
|
||||
}
|
||||
|
||||
void HTTPClient::resetCookieJar() {
|
||||
_cookieJar = nullptr;
|
||||
}
|
||||
|
||||
void HTTPClient::clearAllCookies() {
|
||||
if (_cookieJar) {
|
||||
_cookieJar->clear();
|
||||
}
|
||||
}
|
||||
|
||||
void HTTPClient::setCookie(String date, String headerValue) {
|
||||
if (!_cookieJar) {
|
||||
return;
|
||||
}
|
||||
|
||||
#define HTTP_TIME_PATTERN "%a, %d %b %Y %H:%M:%S"
|
||||
|
||||
Cookie cookie;
|
||||
String value;
|
||||
int pos1, pos2;
|
||||
|
||||
struct tm tm;
|
||||
strptime(date.c_str(), HTTP_TIME_PATTERN, &tm);
|
||||
cookie.date = mktime(&tm);
|
||||
|
||||
pos1 = headerValue.indexOf('=');
|
||||
pos2 = headerValue.indexOf(';');
|
||||
|
||||
if (pos1 >= 0 && pos2 > pos1) {
|
||||
cookie.name = headerValue.substring(0, pos1);
|
||||
cookie.value = headerValue.substring(pos1 + 1, pos2);
|
||||
} else {
|
||||
return; // invalid cookie header
|
||||
}
|
||||
|
||||
// only Cookie Attributes are case insensitive from this point on
|
||||
headerValue.toLowerCase();
|
||||
|
||||
// expires
|
||||
if (headerValue.indexOf("expires=") >= 0) {
|
||||
pos1 = headerValue.indexOf("expires=") + strlen("expires=");
|
||||
pos2 = headerValue.indexOf(';', pos1);
|
||||
|
||||
if (pos2 > pos1) {
|
||||
value = headerValue.substring(pos1, pos2);
|
||||
} else {
|
||||
value = headerValue.substring(pos1);
|
||||
}
|
||||
|
||||
strptime(value.c_str(), HTTP_TIME_PATTERN, &tm);
|
||||
cookie.expires.date = mktime(&tm);
|
||||
cookie.expires.valid = true;
|
||||
}
|
||||
|
||||
// max-age
|
||||
if (headerValue.indexOf("max-age=") >= 0) {
|
||||
pos1 = headerValue.indexOf("max-age=") + strlen("max-age=");
|
||||
pos2 = headerValue.indexOf(';', pos1);
|
||||
|
||||
if (pos2 > pos1) {
|
||||
value = headerValue.substring(pos1, pos2);
|
||||
} else {
|
||||
value = headerValue.substring(pos1);
|
||||
}
|
||||
|
||||
cookie.max_age.duration = value.toInt();
|
||||
cookie.max_age.valid = true;
|
||||
}
|
||||
|
||||
// domain
|
||||
if (headerValue.indexOf("domain=") >= 0) {
|
||||
pos1 = headerValue.indexOf("domain=") + strlen("domain=");
|
||||
pos2 = headerValue.indexOf(';', pos1);
|
||||
|
||||
if (pos2 > pos1) {
|
||||
value = headerValue.substring(pos1, pos2);
|
||||
} else {
|
||||
value = headerValue.substring(pos1);
|
||||
}
|
||||
|
||||
if (value.startsWith(".")) {
|
||||
value.remove(0, 1);
|
||||
}
|
||||
|
||||
if (_host.indexOf(value) >= 0) {
|
||||
cookie.domain = value;
|
||||
} else {
|
||||
return; // server tries to set a cookie on a different domain; ignore it
|
||||
}
|
||||
} else {
|
||||
pos1 = _host.lastIndexOf('.', _host.lastIndexOf('.') - 1);
|
||||
if (pos1 >= 0) {
|
||||
cookie.domain = _host.substring(pos1 + 1);
|
||||
} else {
|
||||
cookie.domain = _host;
|
||||
}
|
||||
}
|
||||
|
||||
// path
|
||||
if (headerValue.indexOf("path=") >= 0) {
|
||||
pos1 = headerValue.indexOf("path=") + strlen("path=");
|
||||
pos2 = headerValue.indexOf(';', pos1);
|
||||
|
||||
if (pos2 > pos1) {
|
||||
cookie.path = headerValue.substring(pos1, pos2);
|
||||
} else {
|
||||
cookie.path = headerValue.substring(pos1);
|
||||
}
|
||||
}
|
||||
|
||||
// HttpOnly
|
||||
cookie.http_only = (headerValue.indexOf("httponly") >= 0);
|
||||
|
||||
// secure
|
||||
cookie.secure = (headerValue.indexOf("secure") >= 0);
|
||||
|
||||
// overwrite or delete cookie in/from cookie jar
|
||||
time_t now_local = time(NULL);
|
||||
time_t now_gmt = mktime(gmtime(&now_local));
|
||||
|
||||
bool found = false;
|
||||
|
||||
for (auto c = _cookieJar->begin(); c != _cookieJar->end(); ++c) {
|
||||
if (c->domain == cookie.domain && c->name == cookie.name) {
|
||||
// when evaluating, max-age takes precedence over expires if both are defined
|
||||
if ((cookie.max_age.valid && ((cookie.date + cookie.max_age.duration) < now_gmt || (cookie.max_age.duration <= 0)))
|
||||
|| (!cookie.max_age.valid && cookie.expires.valid && (cookie.expires.date < now_gmt))) {
|
||||
_cookieJar->erase(c);
|
||||
c--;
|
||||
} else {
|
||||
*c = cookie;
|
||||
}
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
|
||||
// add cookie to jar
|
||||
if (!found && !(cookie.max_age.valid && cookie.max_age.duration <= 0)) {
|
||||
_cookieJar->push_back(cookie);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
bool HTTPClient::generateCookieString(String *cookieString) {
|
||||
if (!_cookieJar) {
|
||||
return false;
|
||||
}
|
||||
time_t now_local = time(NULL);
|
||||
time_t now_gmt = mktime(gmtime(&now_local));
|
||||
|
||||
*cookieString = "";
|
||||
bool found = false;
|
||||
|
||||
for (auto c = _cookieJar->begin(); c != _cookieJar->end(); ++c) {
|
||||
if ((c->max_age.valid && ((c->date + c->max_age.duration) < now_gmt)) || (!c->max_age.valid && c->expires.valid && (c->expires.date < now_gmt))) {
|
||||
_cookieJar->erase(c);
|
||||
c--;
|
||||
} else if (_host.indexOf(c->domain) >= 0 && (!c->secure || _secure)) {
|
||||
if (*cookieString == "") {
|
||||
*cookieString = c->name + "=" + c->value;
|
||||
} else {
|
||||
*cookieString += " ;" + c->name + "=" + c->value;
|
||||
}
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@
|
||||
#include <WiFiClientSecure.h>
|
||||
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
#ifdef DEBUG_ESP_HTTP_CLIENT
|
||||
#ifdef DEBUG_ESP_PORT
|
||||
@@ -153,6 +154,28 @@ typedef enum {
|
||||
class TransportTraits;
|
||||
typedef std::unique_ptr<TransportTraits> TransportTraitsPtr;
|
||||
|
||||
|
||||
// cookie jar support
|
||||
typedef struct {
|
||||
String host; // host which tries to set the cookie
|
||||
time_t date; // timestamp of the response that set the cookie
|
||||
String name;
|
||||
String value;
|
||||
String domain;
|
||||
String path = "";
|
||||
struct {
|
||||
time_t date = 0;
|
||||
bool valid = false;
|
||||
} expires;
|
||||
struct {
|
||||
time_t duration = 0;
|
||||
bool valid = false;
|
||||
} max_age;
|
||||
bool http_only = false;
|
||||
bool secure = false;
|
||||
} Cookie;
|
||||
typedef std::vector<Cookie> CookieJar;
|
||||
|
||||
class HTTPClient {
|
||||
public:
|
||||
HTTPClient() = default;
|
||||
@@ -229,6 +252,11 @@ public:
|
||||
const String& getString(void);
|
||||
static String errorToString(int error);
|
||||
|
||||
// Cookie jar support
|
||||
void setCookieJar(CookieJar* cookieJar);
|
||||
void resetCookieJar();
|
||||
void clearAllCookies();
|
||||
|
||||
// ----------------------------------------------------------------------------------------------
|
||||
// HTTPS support, mirrors the WiFiClientSecure interface
|
||||
// Could possibly use a virtual interface class between the two, but for now it is more
|
||||
@@ -327,6 +355,10 @@ protected:
|
||||
int handleHeaderResponse();
|
||||
int writeToStreamDataBlock(Stream * stream, int len);
|
||||
|
||||
// Cookie jar support
|
||||
void setCookie(String date, String headerValue);
|
||||
bool generateCookieString(String *cookieString);
|
||||
|
||||
WiFiClient *_clientMade = nullptr;
|
||||
bool _clientTLS = false;
|
||||
|
||||
@@ -350,6 +382,7 @@ protected:
|
||||
|
||||
String _uri;
|
||||
String _protocol;
|
||||
bool _secure = false;
|
||||
String _headers;
|
||||
String _base64Authorization;
|
||||
|
||||
@@ -368,6 +401,6 @@ protected:
|
||||
String _location;
|
||||
transferEncoding_t _transferEncoding = HTTPC_TE_IDENTITY;
|
||||
std::unique_ptr<StreamString> _payload;
|
||||
|
||||
|
||||
// Cookie jar support
|
||||
CookieJar *_cookieJar = nullptr;
|
||||
};
|
||||
|
||||
Submodule libraries/LittleFS/lib/littlefs updated: 6a53d76e90...d01280e649
@@ -29,7 +29,7 @@
|
||||
#include <FS.h>
|
||||
#include <FSImpl.h>
|
||||
|
||||
#define LFS_NAME_MAX 32
|
||||
#define LFS_NAME_MAX 255
|
||||
#include "../lib/littlefs/lfs.h"
|
||||
|
||||
using namespace fs;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// Just have a stub here that redirects to the actual source file
|
||||
|
||||
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
|
||||
#define LFS_NAME_MAX 32
|
||||
#define LFS_NAME_MAX 255
|
||||
#define LFS_NO_DEBUG
|
||||
#define LFS_NO_WARN
|
||||
#define LFS_NO_ERROR
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#define LFS_NAME_MAX 32
|
||||
#define LFS_NAME_MAX 255
|
||||
#define LFS_NO_DEBUG
|
||||
#define LFS_NO_WARN
|
||||
#define LFS_NO_ERROR
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
// Modified from the ESP32-NetBIOS example
|
||||
|
||||
#include <WiFi.h>
|
||||
#include <NetBIOS.h>
|
||||
|
||||
#ifndef STASSID
|
||||
#define STASSID "your-ssid"
|
||||
#define STAPSK "your-password"
|
||||
#endif
|
||||
|
||||
const char* ssid = STASSID;
|
||||
const char* password = STAPSK;
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
|
||||
// Connect to WiFi network
|
||||
WiFi.mode(WIFI_STA);
|
||||
WiFi.begin(ssid, password);
|
||||
Serial.println("");
|
||||
|
||||
// Wait for connection
|
||||
while (WiFi.status() != WL_CONNECTED) {
|
||||
delay(500);
|
||||
Serial.print(".");
|
||||
}
|
||||
Serial.println("");
|
||||
Serial.print("Connected to ");
|
||||
Serial.println(ssid);
|
||||
Serial.print("IP address: ");
|
||||
Serial.println(WiFi.localIP());
|
||||
|
||||
// Windows (and other OSes using WINS/NetBIOS resolution should now be able to find the device by name)
|
||||
NBNS.begin("PicoW");
|
||||
}
|
||||
|
||||
void loop() {}
|
||||
Executable
+25
@@ -0,0 +1,25 @@
|
||||
#######################################
|
||||
# Syntax Coloring Map For ESPNBNS
|
||||
#######################################
|
||||
|
||||
#######################################
|
||||
# Datatypes (KEYWORD1)
|
||||
#######################################
|
||||
|
||||
NetBIOS KEYWORD1
|
||||
|
||||
#######################################
|
||||
# Methods and Functions (KEYWORD2)
|
||||
#######################################
|
||||
|
||||
begin KEYWORD2
|
||||
|
||||
#######################################
|
||||
# Instances (KEYWORD2)
|
||||
#######################################
|
||||
|
||||
NBNS KEYWORD2
|
||||
|
||||
#######################################
|
||||
# Constants (LITERAL1)
|
||||
#######################################
|
||||
@@ -0,0 +1,9 @@
|
||||
name=NetBIOS
|
||||
version=2.0.0
|
||||
author=Pablo@xpablo.cz
|
||||
maintainer=Earle F. Philhower, III <earlephilhower@yahoo.com>
|
||||
sentence=Enables NBNS (NetBIOS) name resolution.
|
||||
paragraph=With this library you can connect to your ESP from Windows using a short name
|
||||
category=Communication
|
||||
url=http://www.xpablo.cz/?p=751#more-751
|
||||
architectures=rp2040
|
||||
@@ -0,0 +1,141 @@
|
||||
#include "NetBIOS.h"
|
||||
#include <functional>
|
||||
#include <lwip/netif.h>
|
||||
|
||||
#define NBNS_PORT 137
|
||||
#define NBNS_MAX_HOSTNAME_LEN 32
|
||||
|
||||
typedef struct {
|
||||
uint16_t id;
|
||||
uint8_t flags1;
|
||||
uint8_t flags2;
|
||||
uint16_t qcount;
|
||||
uint16_t acount;
|
||||
uint16_t nscount;
|
||||
uint16_t adcount;
|
||||
uint8_t name_len;
|
||||
char name[NBNS_MAX_HOSTNAME_LEN + 1];
|
||||
uint16_t type;
|
||||
uint16_t clas;
|
||||
} __attribute__((packed)) nbns_question_t;
|
||||
|
||||
typedef struct {
|
||||
uint16_t id;
|
||||
uint8_t flags1;
|
||||
uint8_t flags2;
|
||||
uint16_t qcount;
|
||||
uint16_t acount;
|
||||
uint16_t nscount;
|
||||
uint16_t adcount;
|
||||
uint8_t name_len;
|
||||
char name[NBNS_MAX_HOSTNAME_LEN + 1];
|
||||
uint16_t type;
|
||||
uint16_t clas;
|
||||
uint32_t ttl;
|
||||
uint16_t data_len;
|
||||
uint16_t flags;
|
||||
uint32_t addr;
|
||||
} __attribute__((packed)) nbns_answer_t;
|
||||
|
||||
static void _getnbname(const char *nbname, char *name, uint8_t maxlen) {
|
||||
uint8_t b;
|
||||
uint8_t c = 0;
|
||||
|
||||
while ((*nbname) && (c < maxlen)) {
|
||||
b = (*nbname++ - 'A') << 4;
|
||||
c++;
|
||||
if (*nbname) {
|
||||
b |= *nbname++ - 'A';
|
||||
c++;
|
||||
}
|
||||
if (!b || b == ' ') {
|
||||
break;
|
||||
}
|
||||
*name++ = b;
|
||||
}
|
||||
*name = 0;
|
||||
}
|
||||
|
||||
static void append_16(void *dst, uint16_t value) {
|
||||
uint8_t *d = (uint8_t *)dst;
|
||||
*d++ = (value >> 8) & 0xFF;
|
||||
*d++ = value & 0xFF;
|
||||
}
|
||||
|
||||
static void append_32(void *dst, uint32_t value) {
|
||||
uint8_t *d = (uint8_t *)dst;
|
||||
*d++ = (value >> 24) & 0xFF;
|
||||
*d++ = (value >> 16) & 0xFF;
|
||||
*d++ = (value >> 8) & 0xFF;
|
||||
*d++ = value & 0xFF;
|
||||
}
|
||||
|
||||
void NetBIOS::_onPacket(AsyncUDPPacket &packet) {
|
||||
if (packet.length() >= sizeof(nbns_question_t)) {
|
||||
nbns_question_t *question = (nbns_question_t *)packet.data();
|
||||
if (0 == (question->flags1 & 0x80)) {
|
||||
char name[NBNS_MAX_HOSTNAME_LEN + 1];
|
||||
_getnbname(&question->name[0], (char *)&name, question->name_len);
|
||||
if (_name.equals(name)) {
|
||||
nbns_answer_t nbnsa;
|
||||
nbnsa.id = question->id;
|
||||
nbnsa.flags1 = 0x85;
|
||||
nbnsa.flags2 = 0;
|
||||
append_16((void *)&nbnsa.qcount, 0);
|
||||
append_16((void *)&nbnsa.acount, 1);
|
||||
append_16((void *)&nbnsa.nscount, 0);
|
||||
append_16((void *)&nbnsa.adcount, 0);
|
||||
nbnsa.name_len = question->name_len;
|
||||
memcpy(&nbnsa.name[0], &question->name[0], question->name_len + 1);
|
||||
append_16((void *)&nbnsa.type, 0x20);
|
||||
append_16((void *)&nbnsa.clas, 1);
|
||||
append_32((void *)&nbnsa.ttl, 300000);
|
||||
append_16((void *)&nbnsa.data_len, 6);
|
||||
append_16((void *)&nbnsa.flags, 0);
|
||||
nbnsa.addr = packet.localIP(); // Wrong, but better than nothing
|
||||
// Iterate over all netifs, see if the incoming address matches one of the netmaskes networks
|
||||
// TODO - is there an easier way of seeing whicn netif produced a packet?
|
||||
for (auto netif = netif_list; netif; netif = netif->next) {
|
||||
auto maskedip = ip4_addr_get_u32(netif_ip4_addr(netif)) & ip4_addr_get_u32(netif_ip4_netmask(netif));
|
||||
auto maskedin = ((uint32_t)packet.localIP()) & ip4_addr_get_u32(netif_ip4_netmask(netif));
|
||||
if (maskedip == maskedin) {
|
||||
nbnsa.addr = ip4_addr_get_u32(netif_ip4_addr(netif));
|
||||
break;
|
||||
}
|
||||
}
|
||||
_udp.writeTo((uint8_t *)&nbnsa, sizeof(nbnsa), packet.remoteIP(), NBNS_PORT);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
NetBIOS::NetBIOS() {}
|
||||
|
||||
NetBIOS::~NetBIOS() {
|
||||
end();
|
||||
}
|
||||
|
||||
bool NetBIOS::begin(const char *name) {
|
||||
_name = name;
|
||||
_name.toUpperCase();
|
||||
|
||||
if (_udp.connected()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
_udp.onPacket(
|
||||
[](void *arg, AsyncUDPPacket & packet) {
|
||||
((NetBIOS *)(arg))->_onPacket(packet);
|
||||
},
|
||||
this
|
||||
);
|
||||
return _udp.listen(NBNS_PORT);
|
||||
}
|
||||
|
||||
void NetBIOS::end() {
|
||||
if (_udp.connected()) {
|
||||
_udp.close();
|
||||
}
|
||||
}
|
||||
|
||||
NetBIOS NBNS;
|
||||
@@ -0,0 +1,21 @@
|
||||
//
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <AsyncUDP.h>
|
||||
|
||||
class NetBIOS {
|
||||
protected:
|
||||
AsyncUDP _udp;
|
||||
String _name;
|
||||
void _onPacket(AsyncUDPPacket &packet);
|
||||
|
||||
public:
|
||||
NetBIOS();
|
||||
~NetBIOS();
|
||||
bool begin(const char *name);
|
||||
void end();
|
||||
};
|
||||
|
||||
extern NetBIOS NBNS;
|
||||
@@ -242,8 +242,8 @@ size_t PWMAudio::write(const uint8_t *buffer, size_t size) {
|
||||
return writtenSize;
|
||||
} else {
|
||||
p++;
|
||||
size -= 4;
|
||||
writtenSize += 4;
|
||||
size -= 2;
|
||||
writtenSize += 2;
|
||||
}
|
||||
}
|
||||
return writtenSize;
|
||||
@@ -288,4 +288,4 @@ void PWMAudio::find_pacer_fraction(int target, uint16_t *numerator, uint16_t *de
|
||||
last_target = target;
|
||||
*numerator = bestNum;
|
||||
*denominator = bestDenom;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,8 +43,9 @@ public:
|
||||
|
||||
void end(bool endSPI = true) {
|
||||
SDFS.end();
|
||||
if (endSPI) {
|
||||
if (endSPI && _spi) {
|
||||
_spi->end();
|
||||
_spi = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,7 +206,7 @@ private:
|
||||
return time(nullptr);
|
||||
}
|
||||
|
||||
HardwareSPI *_spi;
|
||||
HardwareSPI *_spi = nullptr;
|
||||
};
|
||||
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
#include <SerialBT.h>
|
||||
|
||||
void setup() {
|
||||
SerialBT.setName("PicoW UPPERCASE 00:00:00:00:00:00");
|
||||
SerialBT.begin();
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ SerialBT KEYWORD1
|
||||
#######################################
|
||||
# Methods and Functions (KEYWORD2)
|
||||
#######################################
|
||||
setName KEYWORD2
|
||||
|
||||
#######################################
|
||||
# Constants (LITERAL1)
|
||||
|
||||
@@ -76,7 +76,10 @@ void SerialBT_::begin(unsigned long baud, uint16_t config) {
|
||||
|
||||
gap_discoverable_control(1);
|
||||
gap_ssp_set_io_capability(SSP_IO_CAPABILITY_DISPLAY_YES_NO);
|
||||
gap_set_local_name("PicoW Serial 00:00:00:00:00:00");
|
||||
if (!_name) {
|
||||
setName("PicoW Serial 00:00:00:00:00:00");
|
||||
}
|
||||
gap_set_local_name(_name);
|
||||
|
||||
// Turn on!
|
||||
hci_power_control(HCI_POWER_ON);
|
||||
|
||||
@@ -37,6 +37,14 @@ public:
|
||||
SerialBT_();
|
||||
|
||||
bool setFIFOSize(size_t size);
|
||||
bool setName(const char *name) {
|
||||
if (_running) {
|
||||
return false;
|
||||
}
|
||||
free(_name);
|
||||
_name = strdup(name);
|
||||
return true;
|
||||
}
|
||||
|
||||
void begin(unsigned long baud = 115200) override {
|
||||
begin(baud, SERIAL_8N1);
|
||||
@@ -82,4 +90,6 @@ private:
|
||||
|
||||
volatile int _writeLen = 0;
|
||||
const void *_writeBuff;
|
||||
|
||||
char *_name = nullptr;
|
||||
};
|
||||
|
||||
@@ -60,8 +60,9 @@ void handleRoot() {
|
||||
static int cnt = 0;
|
||||
digitalWrite(led, 1);
|
||||
int sec = millis() / 1000;
|
||||
int min = sec / 60;
|
||||
int hr = min / 60;
|
||||
int hr = sec / 3600;
|
||||
int min = (sec / 60) % 60;
|
||||
sec = sec % 60;
|
||||
|
||||
StreamString temp;
|
||||
temp.reserve(500); // Preallocate a large chunk to avoid memory fragmentation
|
||||
@@ -80,7 +81,7 @@ void handleRoot() {
|
||||
<p>Page Count: %d</p>\
|
||||
<img src=\"/test.svg\" />\
|
||||
</body>\
|
||||
</html>", hr, min % 60, sec % 60, rp2040.getFreeHeap(), ++cnt);
|
||||
</html>", hr, min, sec, rp2040.getFreeHeap(), ++cnt);
|
||||
server.send(200, "text/html", temp);
|
||||
digitalWrite(led, 0);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
#include <WiFi.h>
|
||||
#include <WiFiClient.h>
|
||||
#include <WebServer.h>
|
||||
#include <LEAmDNS.h>
|
||||
|
||||
// Your STA WiFi Credentials
|
||||
// ( This is the AP your RP2040 will connect to )
|
||||
const char *ssid = "........";
|
||||
const char *password = "........";
|
||||
|
||||
// Your AP WiFi Credentials
|
||||
// ( This is the AP your RP2040 will broadcast )
|
||||
const char *ap_ssid = "RP2040_Demo";
|
||||
const char *ap_password = "";
|
||||
|
||||
WebServer server(80);
|
||||
|
||||
const int led = LED_BUILTIN;
|
||||
|
||||
// ON_STA_FILTER - Only accept requests coming from STA interface
|
||||
bool ON_STA_FILTER(HTTPServer &server) {
|
||||
return WiFi.localIP() == server.client().localIP();
|
||||
}
|
||||
|
||||
// ON_AP_FILTER - Only accept requests coming from AP interface
|
||||
bool ON_AP_FILTER(HTTPServer &server) {
|
||||
return WiFi.softAPIP() == server.client().localIP();
|
||||
}
|
||||
|
||||
void handleNotFound() {
|
||||
digitalWrite(led, 1);
|
||||
String message = "File Not Found\n\n";
|
||||
message += "URI: ";
|
||||
message += server.uri();
|
||||
message += "\nMethod: ";
|
||||
message += (server.method() == HTTP_GET) ? "GET" : "POST";
|
||||
message += "\nArguments: ";
|
||||
message += server.args();
|
||||
message += "\n";
|
||||
for (uint8_t i = 0; i < server.args(); i++) {
|
||||
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
|
||||
}
|
||||
server.send(404, "text/plain", message);
|
||||
digitalWrite(led, 0);
|
||||
}
|
||||
|
||||
void setup(void) {
|
||||
pinMode(led, OUTPUT);
|
||||
digitalWrite(led, 0);
|
||||
Serial.begin(115200);
|
||||
WiFi.mode(WIFI_AP_STA);
|
||||
// Connect to STA
|
||||
WiFi.begin(ssid, password);
|
||||
// Start AP
|
||||
WiFi.softAP(ap_ssid, ap_password);
|
||||
Serial.println("");
|
||||
|
||||
// Wait for connection
|
||||
while (WiFi.status() != WL_CONNECTED) {
|
||||
delay(500);
|
||||
Serial.print(".");
|
||||
}
|
||||
Serial.println("");
|
||||
Serial.print("Connected to ");
|
||||
Serial.println(ssid);
|
||||
Serial.print("IP address: ");
|
||||
Serial.println(WiFi.localIP());
|
||||
|
||||
if (MDNS.begin("picow")) {
|
||||
Serial.println("MDNS responder started");
|
||||
}
|
||||
|
||||
// This route will be accessible by STA clients only
|
||||
server.on("/", [&]() {
|
||||
digitalWrite(led, 1);
|
||||
server.send(200, "text/plain", "Hi!, This route is accessible for STA clients only");
|
||||
digitalWrite(led, 0);
|
||||
}).setFilter(ON_STA_FILTER);
|
||||
|
||||
// This route will be accessible by AP clients only
|
||||
server.on("/", [&]() {
|
||||
digitalWrite(led, 1);
|
||||
server.send(200, "text/plain", "Hi!, This route is accessible for AP clients only");
|
||||
digitalWrite(led, 0);
|
||||
}).setFilter(ON_AP_FILTER);
|
||||
|
||||
server.on("/inline", []() {
|
||||
server.send(200, "text/plain", "this works as well");
|
||||
});
|
||||
|
||||
server.onNotFound(handleNotFound);
|
||||
|
||||
server.begin();
|
||||
Serial.println("HTTP server started");
|
||||
}
|
||||
|
||||
void loop(void) {
|
||||
server.handleClient();
|
||||
MDNS.update();
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
# Upload Huge File To Filesystem Over HTTP
|
||||
|
||||
This project is an example of an HTTP server designed to facilitate the transfer of large files using the PUT method, in accordance with RFC specifications.
|
||||
|
||||
### Example cURL Command
|
||||
|
||||
```bash
|
||||
curl -X PUT -T ./my-file.mp3 http://pico-ip/upload/my-file.mp3
|
||||
```
|
||||
|
||||
## Resources
|
||||
|
||||
- RFC HTTP/1.0 - Additional Request Methods - PUT : [Link](https://datatracker.ietf.org/doc/html/rfc1945#appendix-D.1.1)
|
||||
@@ -0,0 +1,92 @@
|
||||
#include <WiFi.h>
|
||||
#include <WiFiClient.h>
|
||||
#include <WebServer.h>
|
||||
#include <uri/UriRegex.h>
|
||||
#include <LittleFS.h>
|
||||
|
||||
#ifndef STASSID
|
||||
#define STASSID "your-ssid"
|
||||
#define STAPSK "your-password"
|
||||
#endif
|
||||
|
||||
const char *ssid = STASSID;
|
||||
const char *password = STAPSK;
|
||||
|
||||
WebServer server(80);
|
||||
|
||||
File rawFile;
|
||||
void handleCreate() {
|
||||
server.send(200, "text/plain", "");
|
||||
}
|
||||
void handleCreateProcess() {
|
||||
String path = "/" + server.pathArg(0);
|
||||
HTTPRaw& raw = server.raw();
|
||||
if (raw.status == RAW_START) {
|
||||
if (LittleFS.exists((char *)path.c_str())) {
|
||||
LittleFS.remove((char *)path.c_str());
|
||||
}
|
||||
rawFile = LittleFS.open(path.c_str(), "w");
|
||||
Serial.print("Upload: START, filename: ");
|
||||
Serial.println(path);
|
||||
} else if (raw.status == RAW_WRITE) {
|
||||
if (rawFile) {
|
||||
rawFile.write(raw.buf, raw.currentSize);
|
||||
}
|
||||
Serial.print("Upload: WRITE, Bytes: ");
|
||||
Serial.println(raw.currentSize);
|
||||
} else if (raw.status == RAW_END) {
|
||||
if (rawFile) {
|
||||
rawFile.close();
|
||||
}
|
||||
Serial.print("Upload: END, Size: ");
|
||||
Serial.println(raw.totalSize);
|
||||
}
|
||||
}
|
||||
|
||||
void returnFail(String msg) {
|
||||
server.send(500, "text/plain", msg + "\r\n");
|
||||
}
|
||||
|
||||
void handleNotFound() {
|
||||
String message = "File Not Found\n\n";
|
||||
message += "URI: ";
|
||||
message += server.uri();
|
||||
message += "\nMethod: ";
|
||||
message += (server.method() == HTTP_GET) ? "GET" : "POST";
|
||||
message += "\nArguments: ";
|
||||
message += server.args();
|
||||
message += "\n";
|
||||
for (uint8_t i = 0; i < server.args(); i++) {
|
||||
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
|
||||
}
|
||||
server.send(404, "text/plain", message);
|
||||
}
|
||||
|
||||
void setup(void) {
|
||||
Serial.begin(115200);
|
||||
|
||||
LittleFS.begin();
|
||||
|
||||
WiFi.mode(WIFI_STA);
|
||||
WiFi.begin(ssid, password);
|
||||
|
||||
while (WiFi.status() != WL_CONNECTED) {
|
||||
delay(500);
|
||||
Serial.print(".");
|
||||
}
|
||||
Serial.print("Connected to ");
|
||||
Serial.println(ssid);
|
||||
Serial.print("IP address: ");
|
||||
Serial.println(WiFi.localIP());
|
||||
|
||||
server.on(UriRegex("/upload/(.*)"), HTTP_PUT, handleCreate, handleCreateProcess);
|
||||
server.onNotFound(handleNotFound);
|
||||
server.begin();
|
||||
Serial.println("HTTP server started");
|
||||
|
||||
}
|
||||
|
||||
void loop(void) {
|
||||
server.handleClient();
|
||||
delay(2);//allow the cpu to switch to other tasks
|
||||
}
|
||||
@@ -207,22 +207,65 @@ void HTTPServer::requestAuthentication(HTTPAuthMethod mode, const char* realm, c
|
||||
send(401, String(FPSTR(mimeTable[html].mimeType)), authFailMsg);
|
||||
}
|
||||
|
||||
void HTTPServer::on(const Uri &uri, HTTPServer::THandlerFunction handler) {
|
||||
on(uri, HTTP_ANY, handler);
|
||||
RequestHandler& HTTPServer::on(const Uri &uri, HTTPServer::THandlerFunction handler) {
|
||||
return on(uri, HTTP_ANY, handler);
|
||||
}
|
||||
|
||||
void HTTPServer::on(const Uri &uri, HTTPMethod method, HTTPServer::THandlerFunction fn) {
|
||||
on(uri, method, fn, _fileUploadHandler);
|
||||
RequestHandler& HTTPServer::on(const Uri &uri, HTTPMethod method, HTTPServer::THandlerFunction fn) {
|
||||
return on(uri, method, fn, _fileUploadHandler);
|
||||
}
|
||||
|
||||
void HTTPServer::on(const Uri &uri, HTTPMethod method, HTTPServer::THandlerFunction fn, HTTPServer::THandlerFunction ufn) {
|
||||
_addRequestHandler(new FunctionRequestHandler(fn, ufn, uri, method));
|
||||
RequestHandler& HTTPServer::on(const Uri &uri, HTTPMethod method, HTTPServer::THandlerFunction fn, HTTPServer::THandlerFunction ufn) {
|
||||
FunctionRequestHandler *handler = new FunctionRequestHandler(fn, ufn, uri, method);
|
||||
_addRequestHandler(handler);
|
||||
return *handler;
|
||||
}
|
||||
|
||||
bool HTTPServer::removeRoute(const char *uri) {
|
||||
return removeRoute(String(uri), HTTP_ANY);
|
||||
}
|
||||
|
||||
bool HTTPServer::removeRoute(const char *uri, HTTPMethod method) {
|
||||
return removeRoute(String(uri), method);
|
||||
}
|
||||
|
||||
bool HTTPServer::removeRoute(const String &uri) {
|
||||
return removeRoute(uri, HTTP_ANY);
|
||||
}
|
||||
|
||||
bool HTTPServer::removeRoute(const String &uri, HTTPMethod method) {
|
||||
bool anyHandlerRemoved = false;
|
||||
RequestHandler *handler = _firstHandler;
|
||||
RequestHandler *previousHandler = nullptr;
|
||||
|
||||
while (handler) {
|
||||
if (handler->canHandle(method, uri)) {
|
||||
if (_removeRequestHandler(handler)) {
|
||||
anyHandlerRemoved = true;
|
||||
// Move to the next handler
|
||||
if (previousHandler) {
|
||||
handler = previousHandler->next();
|
||||
} else {
|
||||
handler = _firstHandler;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
previousHandler = handler;
|
||||
handler = handler->next();
|
||||
}
|
||||
|
||||
return anyHandlerRemoved;
|
||||
}
|
||||
|
||||
void HTTPServer::addHandler(RequestHandler* handler) {
|
||||
_addRequestHandler(handler);
|
||||
}
|
||||
|
||||
bool HTTPServer::removeHandler(RequestHandler *handler) {
|
||||
return _removeRequestHandler(handler);
|
||||
}
|
||||
|
||||
void HTTPServer::_addRequestHandler(RequestHandler* handler) {
|
||||
if (!_lastHandler) {
|
||||
_firstHandler = handler;
|
||||
@@ -233,6 +276,32 @@ void HTTPServer::_addRequestHandler(RequestHandler* handler) {
|
||||
}
|
||||
}
|
||||
|
||||
bool HTTPServer::_removeRequestHandler(RequestHandler *handler) {
|
||||
RequestHandler *current = _firstHandler;
|
||||
RequestHandler *previous = nullptr;
|
||||
|
||||
while (current != nullptr) {
|
||||
if (current == handler) {
|
||||
if (previous == nullptr) {
|
||||
_firstHandler = current->next();
|
||||
} else {
|
||||
previous->next(current->next());
|
||||
}
|
||||
|
||||
if (current == _lastHandler) {
|
||||
_lastHandler = previous;
|
||||
}
|
||||
|
||||
// Delete 'matching' handler
|
||||
delete current;
|
||||
return true;
|
||||
}
|
||||
previous = current;
|
||||
current = current->next();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void HTTPServer::serveStatic(const char* uri, FS& fs, const char* path, const char* cache_header) {
|
||||
_addRequestHandler(new StaticRequestHandler(fs, path, uri, cache_header));
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
enum HTTPUploadStatus { UPLOAD_FILE_START, UPLOAD_FILE_WRITE, UPLOAD_FILE_END,
|
||||
UPLOAD_FILE_ABORTED
|
||||
};
|
||||
enum HTTPRawStatus { RAW_START, RAW_WRITE, RAW_END, RAW_ABORTED };
|
||||
enum HTTPClientStatus { HC_NONE, HC_WAIT_READ, HC_WAIT_CLOSE };
|
||||
enum HTTPAuthMethod { BASIC_AUTH, DIGEST_AUTH };
|
||||
|
||||
@@ -40,6 +41,10 @@ enum HTTPAuthMethod { BASIC_AUTH, DIGEST_AUTH };
|
||||
#define HTTP_UPLOAD_BUFLEN 1436
|
||||
#endif
|
||||
|
||||
#ifndef HTTP_RAW_BUFLEN
|
||||
#define HTTP_RAW_BUFLEN 1436
|
||||
#endif
|
||||
|
||||
#define HTTP_MAX_DATA_WAIT 5000 //ms to wait for the client to send the request
|
||||
#define HTTP_MAX_DATA_AVAILABLE_WAIT 30 //ms to wait for the client to send the request when there is another client with data available
|
||||
#define HTTP_MAX_POST_WAIT 5000 //ms to wait for POST data to arrive
|
||||
@@ -63,6 +68,16 @@ typedef struct {
|
||||
uint8_t buf[HTTP_UPLOAD_BUFLEN];
|
||||
} HTTPUpload;
|
||||
|
||||
|
||||
typedef struct {
|
||||
HTTPRawStatus status;
|
||||
size_t totalSize; // content size
|
||||
size_t currentSize; // size of data currently in buf
|
||||
uint8_t buf[HTTP_UPLOAD_BUFLEN];
|
||||
void *data; // additional data
|
||||
} HTTPRaw;
|
||||
|
||||
|
||||
#include "detail/RequestHandler.h"
|
||||
|
||||
namespace fs {
|
||||
@@ -80,10 +95,16 @@ public:
|
||||
void requestAuthentication(HTTPAuthMethod mode = BASIC_AUTH, const char* realm = nullptr, const String& authFailMsg = String(""));
|
||||
|
||||
typedef std::function<void(void)> THandlerFunction;
|
||||
void on(const Uri &uri, THandlerFunction fn);
|
||||
void on(const Uri &uri, HTTPMethod method, THandlerFunction fn);
|
||||
void on(const Uri &uri, HTTPMethod method, THandlerFunction fn, THandlerFunction ufn); //ufn handles file uploads
|
||||
typedef std::function<bool(HTTPServer &server)> FilterFunction;
|
||||
RequestHandler& on(const Uri &uri, THandlerFunction fn);
|
||||
RequestHandler& on(const Uri &uri, HTTPMethod method, THandlerFunction fn);
|
||||
RequestHandler& on(const Uri &uri, HTTPMethod method, THandlerFunction fn, THandlerFunction ufn); //ufn handles file uploads
|
||||
bool removeRoute(const char *uri);
|
||||
bool removeRoute(const char *uri, HTTPMethod method);
|
||||
bool removeRoute(const String &uri);
|
||||
bool removeRoute(const String &uri, HTTPMethod method);
|
||||
void addHandler(RequestHandler* handler);
|
||||
bool removeHandler(RequestHandler *handler);
|
||||
void serveStatic(const char* uri, fs::FS& fs, const char* path, const char* cache_header = nullptr);
|
||||
void onNotFound(THandlerFunction fn); //called when handler is not assigned
|
||||
void onFileUpload(THandlerFunction ufn); //handle file uploads
|
||||
@@ -94,9 +115,15 @@ public:
|
||||
HTTPMethod method() {
|
||||
return _currentMethod;
|
||||
}
|
||||
WiFiClient& client() {
|
||||
return *_currentClient;
|
||||
}
|
||||
HTTPUpload& upload() {
|
||||
return *_currentUpload;
|
||||
}
|
||||
HTTPRaw& raw() {
|
||||
return *_currentRaw;
|
||||
}
|
||||
|
||||
String pathArg(unsigned int i); // get request path argument by number
|
||||
String arg(String name); // get request argument value by name
|
||||
@@ -212,6 +239,7 @@ protected:
|
||||
return _currentClient->write(b, l);
|
||||
}
|
||||
void _addRequestHandler(RequestHandler* handler);
|
||||
bool _removeRequestHandler(RequestHandler *handler);
|
||||
void _handleRequest();
|
||||
void _finalizeResponse();
|
||||
ClientFuture _parseRequest(WiFiClient* client);
|
||||
@@ -257,6 +285,7 @@ protected:
|
||||
RequestArgument* _postArgs;
|
||||
|
||||
std::unique_ptr<HTTPUpload> _currentUpload;
|
||||
std::unique_ptr<HTTPRaw> _currentRaw;
|
||||
|
||||
int _headerKeysCount;
|
||||
RequestArgument* _currentHeaders;
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
|
||||
#define __STR(a) #a
|
||||
#define _STR(a) __STR(a)
|
||||
const char * _http_method_str[] = {
|
||||
static const char * _http_method_str[] = {
|
||||
#define XX(num, name, string) _STR(name),
|
||||
HTTP_METHOD_MAP(XX)
|
||||
#undef XX
|
||||
@@ -136,7 +136,7 @@ HTTPServer::ClientFuture HTTPServer::_parseRequest(WiFiClient* client) {
|
||||
//attach handler
|
||||
RequestHandler* handler;
|
||||
for (handler = _firstHandler; handler; handler = handler->next()) {
|
||||
if (handler->canHandle(_currentMethod, _currentUri)) {
|
||||
if (handler->canHandle(*this, _currentMethod, _currentUri)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -188,7 +188,30 @@ HTTPServer::ClientFuture HTTPServer::_parseRequest(WiFiClient* client) {
|
||||
}
|
||||
}
|
||||
|
||||
if (!isForm) {
|
||||
if (!isForm && _currentHandler && _currentHandler->canRaw(*this, _currentUri)) {
|
||||
log_v("Parse raw");
|
||||
_currentRaw.reset(new HTTPRaw());
|
||||
_currentRaw->status = RAW_START;
|
||||
_currentRaw->totalSize = 0;
|
||||
_currentRaw->currentSize = 0;
|
||||
log_v("Start Raw");
|
||||
_currentHandler->raw(*this, _currentUri, *_currentRaw);
|
||||
_currentRaw->status = RAW_WRITE;
|
||||
|
||||
while (_currentRaw->totalSize < (size_t)_clientContentLength) {
|
||||
_currentRaw->currentSize = client->readBytes(_currentRaw->buf, HTTP_RAW_BUFLEN);
|
||||
_currentRaw->totalSize += _currentRaw->currentSize;
|
||||
if (_currentRaw->currentSize == 0) {
|
||||
_currentRaw->status = RAW_ABORTED;
|
||||
_currentHandler->raw(*this, _currentUri, *_currentRaw);
|
||||
return CLIENT_MUST_STOP;
|
||||
}
|
||||
_currentHandler->raw(*this, _currentUri, *_currentRaw);
|
||||
}
|
||||
_currentRaw->status = RAW_END;
|
||||
_currentHandler->raw(*this, _currentUri, *_currentRaw);
|
||||
log_v("Finish Raw");
|
||||
} else if (!isForm) {
|
||||
size_t plainLength;
|
||||
char* plainBuf = readBytesWithTimeout(client, _clientContentLength, plainLength, HTTP_MAX_POST_WAIT);
|
||||
if ((int)plainLength < (int)_clientContentLength) {
|
||||
@@ -324,7 +347,7 @@ void HTTPServer::_parseArguments(String data) {
|
||||
|
||||
void HTTPServer::_uploadWriteByte(uint8_t b) {
|
||||
if (_currentUpload->currentSize == HTTP_UPLOAD_BUFLEN) {
|
||||
if (_currentHandler && _currentHandler->canUpload(_currentUri)) {
|
||||
if (_currentHandler && _currentHandler->canUpload(*this, _currentUri)) {
|
||||
_currentHandler->upload(*this, _currentUri, *_currentUpload);
|
||||
}
|
||||
_currentUpload->totalSize += _currentUpload->currentSize;
|
||||
@@ -333,51 +356,22 @@ void HTTPServer::_uploadWriteByte(uint8_t b) {
|
||||
_currentUpload->buf[_currentUpload->currentSize++] = b;
|
||||
}
|
||||
|
||||
int HTTPServer::_uploadReadByte(WiFiClient* client) {
|
||||
int HTTPServer::_uploadReadByte(WiFiClient * client) {
|
||||
int res = client->read();
|
||||
|
||||
if (res < 0) {
|
||||
// keep trying until you either read a valid byte or timeout
|
||||
unsigned long startMillis = millis();
|
||||
unsigned long timeoutIntervalMillis = client->getTimeout();
|
||||
bool timedOut = false;
|
||||
for (;;) {
|
||||
if (!client->connected()) {
|
||||
return -1;
|
||||
}
|
||||
// loosely modeled after blinkWithoutDelay pattern
|
||||
while (!timedOut && !client->available() && client->connected()) {
|
||||
delay(2);
|
||||
timedOut = millis() - startMillis >= timeoutIntervalMillis;
|
||||
}
|
||||
|
||||
res = client->read();
|
||||
if (res >= 0) {
|
||||
return res; // exit on a valid read
|
||||
}
|
||||
// NOTE: it is possible to get here and have all of the following
|
||||
// assertions hold true
|
||||
//
|
||||
// -- client->available() > 0
|
||||
// -- client->connected == true
|
||||
// -- res == -1
|
||||
//
|
||||
// a simple retry strategy overcomes this which is to say the
|
||||
// assertion is not permanent, but the reason that this works
|
||||
// is elusive, and possibly indicative of a more subtle underlying
|
||||
// issue
|
||||
|
||||
timedOut = millis() - startMillis >= timeoutIntervalMillis;
|
||||
if (timedOut) {
|
||||
return res; // exit on a timeout
|
||||
}
|
||||
while (!client->available() && client->connected()) {
|
||||
delay(2);
|
||||
}
|
||||
|
||||
res = client->read();
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
bool HTTPServer::_parseForm(WiFiClient* client, String boundary, uint32_t len) {
|
||||
(void) len;
|
||||
bool HTTPServer::_parseForm(WiFiClient * client, String boundary, uint32_t len) {
|
||||
(void)len;
|
||||
log_v("Parse Form: Boundary: %s Length: %d", boundary.c_str(), len);
|
||||
String line;
|
||||
int retry = 0;
|
||||
@@ -425,10 +419,12 @@ bool HTTPServer::_parseForm(WiFiClient* client, String boundary, uint32_t len) {
|
||||
argType = FPSTR(mimeTable[txt].mimeType);
|
||||
line = client->readStringUntil('\r');
|
||||
client->readStringUntil('\n');
|
||||
if (line.length() > 12 && line.substring(0, 12).equalsIgnoreCase(FPSTR(Content_Type))) {
|
||||
argType = line.substring(line.indexOf(':') + 2);
|
||||
//skip next line
|
||||
client->readStringUntil('\r');
|
||||
while (line.length() > 0) {
|
||||
if (line.length() > 12 && line.substring(0, 12).equalsIgnoreCase(FPSTR(Content_Type))) {
|
||||
argType = line.substring(line.indexOf(':') + 2);
|
||||
}
|
||||
//skip over any other headers
|
||||
line = client->readStringUntil('\r');
|
||||
client->readStringUntil('\n');
|
||||
}
|
||||
log_v("PostArg Type: %s", argType.c_str());
|
||||
@@ -446,7 +442,7 @@ bool HTTPServer::_parseForm(WiFiClient* client, String boundary, uint32_t len) {
|
||||
}
|
||||
log_v("PostArg Value: %s", argValue.c_str());
|
||||
|
||||
RequestArgument& arg = _postArgs[_postArgsLen++];
|
||||
RequestArgument &arg = _postArgs[_postArgsLen++];
|
||||
arg.key = argName;
|
||||
arg.value = argValue;
|
||||
|
||||
@@ -466,102 +462,64 @@ bool HTTPServer::_parseForm(WiFiClient* client, String boundary, uint32_t len) {
|
||||
_currentUpload->totalSize = 0;
|
||||
_currentUpload->currentSize = 0;
|
||||
log_v("Start File: %s Type: %s", _currentUpload->filename.c_str(), _currentUpload->type.c_str());
|
||||
if (_currentHandler && _currentHandler->canUpload(_currentUri)) {
|
||||
if (_currentHandler && _currentHandler->canUpload(*this, _currentUri)) {
|
||||
_currentHandler->upload(*this, _currentUri, *_currentUpload);
|
||||
}
|
||||
_currentUpload->status = UPLOAD_FILE_WRITE;
|
||||
int argByte = _uploadReadByte(client);
|
||||
readfile:
|
||||
|
||||
while (argByte != 0x0D) {
|
||||
if (argByte < 0) {
|
||||
int fastBoundaryLen = 4 /* \r\n-- */ + boundary.length() + 1 /* \0 */;
|
||||
char fastBoundary[fastBoundaryLen];
|
||||
snprintf(fastBoundary, fastBoundaryLen, "\r\n--%s", boundary.c_str());
|
||||
int boundaryPtr = 0;
|
||||
while (true) {
|
||||
int ret = _uploadReadByte(client);
|
||||
if (ret < 0) {
|
||||
// Unexpected, we should have had data available per above
|
||||
return _parseFormUploadAborted();
|
||||
}
|
||||
_uploadWriteByte(argByte);
|
||||
argByte = _uploadReadByte(client);
|
||||
}
|
||||
|
||||
argByte = _uploadReadByte(client);
|
||||
if (argByte < 0) {
|
||||
return _parseFormUploadAborted();
|
||||
}
|
||||
if (argByte == 0x0A) {
|
||||
argByte = _uploadReadByte(client);
|
||||
if (argByte < 0) {
|
||||
return _parseFormUploadAborted();
|
||||
}
|
||||
if ((char)argByte != '-') {
|
||||
//continue reading the file
|
||||
_uploadWriteByte(0x0D);
|
||||
_uploadWriteByte(0x0A);
|
||||
goto readfile;
|
||||
} else {
|
||||
argByte = _uploadReadByte(client);
|
||||
if (argByte < 0) {
|
||||
return _parseFormUploadAborted();
|
||||
}
|
||||
if ((char)argByte != '-') {
|
||||
//continue reading the file
|
||||
_uploadWriteByte(0x0D);
|
||||
_uploadWriteByte(0x0A);
|
||||
_uploadWriteByte((uint8_t)('-'));
|
||||
goto readfile;
|
||||
}
|
||||
}
|
||||
|
||||
uint8_t endBuf[boundary.length()];
|
||||
uint32_t i = 0;
|
||||
while (i < boundary.length()) {
|
||||
argByte = _uploadReadByte(client);
|
||||
if (argByte < 0) {
|
||||
return _parseFormUploadAborted();
|
||||
}
|
||||
if ((char)argByte == 0x0D) {
|
||||
_uploadWriteByte(0x0D);
|
||||
_uploadWriteByte(0x0A);
|
||||
_uploadWriteByte((uint8_t)('-'));
|
||||
_uploadWriteByte((uint8_t)('-'));
|
||||
for (uint32_t j = 0; j < i; j++) {
|
||||
_uploadWriteByte(endBuf[j]);
|
||||
}
|
||||
goto readfile;
|
||||
}
|
||||
endBuf[i++] = (uint8_t)argByte;
|
||||
}
|
||||
|
||||
if (strstr((const char*)endBuf, boundary.c_str()) != nullptr) {
|
||||
if (_currentHandler && _currentHandler->canUpload(_currentUri)) {
|
||||
_currentHandler->upload(*this, _currentUri, *_currentUpload);
|
||||
}
|
||||
_currentUpload->totalSize += _currentUpload->currentSize;
|
||||
_currentUpload->status = UPLOAD_FILE_END;
|
||||
if (_currentHandler && _currentHandler->canUpload(_currentUri)) {
|
||||
_currentHandler->upload(*this, _currentUri, *_currentUpload);
|
||||
}
|
||||
log_v("End File: %s Type: %s Size: %d", _currentUpload->filename.c_str(), _currentUpload->type.c_str(), _currentUpload->totalSize);
|
||||
line = client->readStringUntil(0x0D);
|
||||
client->readStringUntil(0x0A);
|
||||
if (line == "--") {
|
||||
log_v("Done Parsing POST");
|
||||
char in = (char)ret;
|
||||
if (in == fastBoundary[boundaryPtr]) {
|
||||
// The input matched the current expected character, advance and possibly exit this file
|
||||
boundaryPtr++;
|
||||
if (boundaryPtr == fastBoundaryLen - 1) {
|
||||
// We read the whole boundary line, we're done here!
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
} else {
|
||||
_uploadWriteByte(0x0D);
|
||||
_uploadWriteByte(0x0A);
|
||||
_uploadWriteByte((uint8_t)('-'));
|
||||
_uploadWriteByte((uint8_t)('-'));
|
||||
for (uint32_t j = 0; j < boundary.length(); j++) {
|
||||
_uploadWriteByte(endBuf[j]);
|
||||
// The char doesn't match what we want, so dump whatever matches we had, the read in char, and reset ptr to start
|
||||
for (int i = 0; i < boundaryPtr; i++) {
|
||||
_uploadWriteByte(fastBoundary[i]);
|
||||
}
|
||||
if (in == fastBoundary[0]) {
|
||||
// This could be the start of the real end, mark it so and don't emit/skip it
|
||||
boundaryPtr = 1;
|
||||
} else {
|
||||
// Not the 1st char of our pattern, so emit and ignore
|
||||
_uploadWriteByte(in);
|
||||
boundaryPtr = 0;
|
||||
}
|
||||
argByte = _uploadReadByte(client);
|
||||
goto readfile;
|
||||
}
|
||||
} else {
|
||||
_uploadWriteByte(0x0D);
|
||||
goto readfile;
|
||||
}
|
||||
break;
|
||||
// Found the boundary string, finish processing this file upload
|
||||
if (_currentHandler && _currentHandler->canUpload(*this, _currentUri)) {
|
||||
_currentHandler->upload(*this, _currentUri, *_currentUpload);
|
||||
}
|
||||
_currentUpload->totalSize += _currentUpload->currentSize;
|
||||
_currentUpload->status = UPLOAD_FILE_END;
|
||||
if (_currentHandler && _currentHandler->canUpload(*this, _currentUri)) {
|
||||
_currentHandler->upload(*this, _currentUri, *_currentUpload);
|
||||
}
|
||||
log_v("End File: %s Type: %s Size: %d", _currentUpload->filename.c_str(), _currentUpload->type.c_str(), (int)_currentUpload->totalSize);
|
||||
if (!client->connected()) {
|
||||
return _parseFormUploadAborted();
|
||||
}
|
||||
line = client->readStringUntil('\r');
|
||||
client->readStringUntil('\n');
|
||||
if (line == "--") { // extra two dashes mean we reached the end of all form fields
|
||||
log_v("Done Parsing POST");
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -570,7 +528,7 @@ readfile:
|
||||
int iarg;
|
||||
int totalArgs = ((WEBSERVER_MAX_POST_ARGS - _postArgsLen) < _currentArgCount) ? (WEBSERVER_MAX_POST_ARGS - _postArgsLen) : _currentArgCount;
|
||||
for (iarg = 0; iarg < totalArgs; iarg++) {
|
||||
RequestArgument& arg = _postArgs[_postArgsLen++];
|
||||
RequestArgument &arg = _postArgs[_postArgsLen++];
|
||||
arg.key = _currentArgs[iarg].key;
|
||||
arg.value = _currentArgs[iarg].value;
|
||||
}
|
||||
@@ -579,7 +537,7 @@ readfile:
|
||||
}
|
||||
_currentArgs = new RequestArgument[_postArgsLen];
|
||||
for (iarg = 0; iarg < _postArgsLen; iarg++) {
|
||||
RequestArgument& arg = _currentArgs[iarg];
|
||||
RequestArgument &arg = _currentArgs[iarg];
|
||||
arg.key = _postArgs[iarg].key;
|
||||
arg.value = _postArgs[iarg].value;
|
||||
}
|
||||
@@ -595,7 +553,7 @@ readfile:
|
||||
return false;
|
||||
}
|
||||
|
||||
String HTTPServer::urlDecode(const String& text) {
|
||||
String HTTPServer::urlDecode(const String & text) {
|
||||
String decoded = "";
|
||||
char temp[] = "0x00";
|
||||
unsigned int len = text.length();
|
||||
@@ -622,7 +580,7 @@ String HTTPServer::urlDecode(const String& text) {
|
||||
|
||||
bool HTTPServer::_parseFormUploadAborted() {
|
||||
_currentUpload->status = UPLOAD_FILE_ABORTED;
|
||||
if (_currentHandler && _currentHandler->canUpload(_currentUri)) {
|
||||
if (_currentHandler && _currentHandler->canUpload(*this, _currentUri)) {
|
||||
_currentHandler->upload(*this, _currentUri, *_currentUpload);
|
||||
}
|
||||
return false;
|
||||
|
||||
@@ -171,6 +171,7 @@ void WebServerTemplate<ServerType, DefaultPort>::handleClient() {
|
||||
}
|
||||
_currentStatus = HC_NONE;
|
||||
_currentUpload.reset();
|
||||
_currentRaw.reset();
|
||||
}
|
||||
|
||||
if (callYield) {
|
||||
|
||||
@@ -6,13 +6,43 @@
|
||||
class RequestHandler {
|
||||
public:
|
||||
virtual ~RequestHandler() { }
|
||||
|
||||
/*
|
||||
note: old handler API for backward compatibility
|
||||
*/
|
||||
|
||||
virtual bool canHandle(HTTPMethod method, String uri) {
|
||||
(void) method;
|
||||
(void) uri;
|
||||
(void)method;
|
||||
(void)uri;
|
||||
return false;
|
||||
}
|
||||
virtual bool canUpload(String uri) {
|
||||
(void) uri;
|
||||
(void)uri;
|
||||
return false;
|
||||
}
|
||||
virtual bool canRaw(String uri) {
|
||||
(void)uri;
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
note: new handler API with support for filters etc.
|
||||
*/
|
||||
|
||||
virtual bool canHandle(HTTPServer &server, HTTPMethod method, String uri) {
|
||||
(void)server;
|
||||
(void)method;
|
||||
(void)uri;
|
||||
return false;
|
||||
}
|
||||
virtual bool canUpload(HTTPServer &server, String uri) {
|
||||
(void)server;
|
||||
(void)uri;
|
||||
return false;
|
||||
}
|
||||
virtual bool canRaw(HTTPServer &server, String uri) {
|
||||
(void)server;
|
||||
(void)uri;
|
||||
return false;
|
||||
}
|
||||
virtual bool handle(HTTPServer& server, HTTPMethod requestMethod, String requestUri) {
|
||||
@@ -26,6 +56,11 @@ public:
|
||||
(void) requestUri;
|
||||
(void) upload;
|
||||
}
|
||||
virtual void raw(HTTPServer& server, String requestUri, HTTPRaw& raw) {
|
||||
(void) server;
|
||||
(void) requestUri;
|
||||
(void) raw;
|
||||
}
|
||||
|
||||
RequestHandler* next() {
|
||||
return _next;
|
||||
@@ -34,6 +69,11 @@ public:
|
||||
_next = r;
|
||||
}
|
||||
|
||||
virtual RequestHandler& setFilter(std::function<bool(HTTPServer&)> filter) {
|
||||
(void)filter;
|
||||
return *this;
|
||||
}
|
||||
|
||||
private:
|
||||
RequestHandler* _next = nullptr;
|
||||
|
||||
|
||||
@@ -42,10 +42,40 @@ public:
|
||||
|
||||
return true;
|
||||
}
|
||||
bool canRaw(String requestUri) override {
|
||||
(void) requestUri;
|
||||
if (!_ufn || _method == HTTP_GET) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool canHandle(HTTPServer &server, HTTPMethod requestMethod, String requestUri) override {
|
||||
if (_method != HTTP_ANY && _method != requestMethod) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return _uri->canHandle(requestUri, pathArgs) && (_filter != NULL ? _filter(server) : true);
|
||||
}
|
||||
bool canUpload(HTTPServer &server, String requestUri) override {
|
||||
if (!_ufn || !canHandle(server, HTTP_POST, requestUri)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
bool canRaw(HTTPServer &server, String requestUri) override {
|
||||
(void) requestUri;
|
||||
if (!_ufn || _method == HTTP_GET || (_filter != NULL ? _filter(server) == false : false)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool handle(HTTPServer& server, HTTPMethod requestMethod, String requestUri) override {
|
||||
(void) server;
|
||||
if (!canHandle(requestMethod, requestUri)) {
|
||||
if (!canHandle(server, requestMethod, requestUri)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -54,16 +84,31 @@ public:
|
||||
}
|
||||
|
||||
void upload(HTTPServer& server, String requestUri, HTTPUpload& upload) override {
|
||||
(void) server;
|
||||
(void) upload;
|
||||
if (canUpload(requestUri)) {
|
||||
if (canUpload(server, requestUri)) {
|
||||
_ufn();
|
||||
}
|
||||
}
|
||||
|
||||
void raw(HTTPServer& server, String requestUri, HTTPRaw& raw) override {
|
||||
(void)server;
|
||||
(void)raw;
|
||||
if (canRaw(server, requestUri)) {
|
||||
_ufn();
|
||||
}
|
||||
}
|
||||
|
||||
FunctionRequestHandler& setFilter(HTTPServer::FilterFunction filter) {
|
||||
_filter = filter;
|
||||
return *this;
|
||||
}
|
||||
|
||||
protected:
|
||||
HTTPServer::THandlerFunction _fn;
|
||||
HTTPServer::THandlerFunction _ufn;
|
||||
// _filter should return 'true' when the request should be handled
|
||||
// and 'false' when the request should be ignored
|
||||
HTTPServer::FilterFunction _filter;
|
||||
Uri *_uri;
|
||||
HTTPMethod _method;
|
||||
};
|
||||
@@ -93,8 +138,24 @@ public:
|
||||
return true;
|
||||
}
|
||||
|
||||
bool canHandle(HTTPServer &server, HTTPMethod requestMethod, String requestUri) override {
|
||||
if (requestMethod != HTTP_GET) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ((_isFile && requestUri != _uri) || !requestUri.startsWith(_uri)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (_filter != NULL ? _filter(server) == false : false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool handle(HTTPServer& server, HTTPMethod requestMethod, String requestUri) override {
|
||||
if (!canHandle(requestMethod, requestUri)) {
|
||||
if (!canHandle(server, requestMethod, requestUri)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -153,7 +214,15 @@ public:
|
||||
return String(buff);
|
||||
}
|
||||
|
||||
StaticRequestHandler& setFilter(HTTPServer::FilterFunction filter) {
|
||||
_filter = filter;
|
||||
return *this;
|
||||
}
|
||||
|
||||
protected:
|
||||
// _filter should return 'true' when the request should be handled
|
||||
// and 'false' when the request should be ignored
|
||||
HTTPServer::FilterFunction _filter;
|
||||
FS _fs;
|
||||
String _uri;
|
||||
String _path;
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "framework-arduinopico",
|
||||
"version": "1.30900.0",
|
||||
"version": "1.30903.0",
|
||||
"description": "Arduino Wiring-based Framework (RPi Pico RP2040)",
|
||||
"keywords": [
|
||||
"framework",
|
||||
|
||||
@@ -35,6 +35,9 @@
|
||||
{
|
||||
"name": "Adafruit Feather RP2040 DVI"
|
||||
},
|
||||
{
|
||||
"name": "Adafruit Feather RP2040 Adalogger"
|
||||
},
|
||||
{
|
||||
"name": "Adafruit Feather RP2040 RFM"
|
||||
},
|
||||
@@ -77,6 +80,9 @@
|
||||
{
|
||||
"name": "ArtronShop RP2 Nano"
|
||||
},
|
||||
{
|
||||
"name": "Breadstick Raspberry"
|
||||
},
|
||||
{
|
||||
"name": "BridgeTek IDM2040-7A"
|
||||
},
|
||||
@@ -110,6 +116,9 @@
|
||||
{
|
||||
"name": "ExtremeElectronics RC2040"
|
||||
},
|
||||
{
|
||||
"name": "GroundStudio Marble Pico"
|
||||
},
|
||||
{
|
||||
"name": "iLabs Challenger 2040 LTE"
|
||||
},
|
||||
@@ -152,6 +161,9 @@
|
||||
{
|
||||
"name": "Melopero Shake RP2040"
|
||||
},
|
||||
{
|
||||
"name": "METE HOCA Akana R1"
|
||||
},
|
||||
{
|
||||
"name": "Neko Systems BL2040 Mini"
|
||||
},
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@
|
||||
# https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5---3rd-party-Hardware-specification
|
||||
|
||||
name=Raspberry Pi RP2040 Boards
|
||||
version=3.9.0
|
||||
version=3.9.3
|
||||
|
||||
# Required discoveries and monitors
|
||||
# ---------------------------------
|
||||
|
||||
+2
-1
@@ -15,7 +15,8 @@ for dir in ./cores/rp2040 ./libraries/EEPROM ./libraries/I2S ./libraries/SingleF
|
||||
./libraries/JoystickBLE ./libraries/KeyboardBLE ./libraries/MouseBLE \
|
||||
./libraries/lwIP_w5500 ./libraries/lwIP_w5100 ./libraries/lwIP_enc28j60 \
|
||||
./libraries/SPISlave ./libraries/lwIP_ESPHost ./libraries/FatFS\
|
||||
./libraries/FatFSUSB ./libraries/BluetoothAudio; do
|
||||
./libraries/FatFSUSB ./libraries/BluetoothAudio ./libraries/BluetoothHCI \
|
||||
./libraries/BluetoothHIDMaster ./libraries/NetBIOS; do
|
||||
find $dir -type f \( -name "*.c" -o -name "*.h" -o -name "*.cpp" \) -a \! -path '*api*' -exec astyle --suffix=none --options=./tests/astyle_core.conf \{\} \;
|
||||
find $dir -type f -name "*.ino" -exec astyle --suffix=none --options=./tests/astyle_examples.conf \{\} \;
|
||||
done
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
{
|
||||
"build": {
|
||||
"arduino": {
|
||||
"earlephilhower": {
|
||||
"boot2_source": "boot2_w25q080_2_padded_checksum.S",
|
||||
"usb_vid": "0x239A",
|
||||
"usb_pid": "0x815D"
|
||||
}
|
||||
},
|
||||
"core": "earlephilhower",
|
||||
"cpu": "cortex-m0plus",
|
||||
"extra_flags": "-D ARDUINO_ADAFRUIT_FEATHER_RP2040_ADALOGGER -DARDUINO_ARCH_RP2040 -DUSBD_MAX_POWER_MA=250",
|
||||
"f_cpu": "133000000L",
|
||||
"hwids": [
|
||||
[
|
||||
"0x2E8A",
|
||||
"0x00C0"
|
||||
],
|
||||
[
|
||||
"0x239A",
|
||||
"0x815D"
|
||||
]
|
||||
],
|
||||
"mcu": "rp2040",
|
||||
"variant": "adafruit_feather_adalogger"
|
||||
},
|
||||
"debug": {
|
||||
"jlink_device": "RP2040_M0_0",
|
||||
"openocd_target": "rp2040.cfg",
|
||||
"svd_path": "rp2040.svd"
|
||||
},
|
||||
"frameworks": [
|
||||
"arduino"
|
||||
],
|
||||
"name": "Feather RP2040 Adalogger",
|
||||
"upload": {
|
||||
"maximum_ram_size": 270336,
|
||||
"maximum_size": 8388608,
|
||||
"require_upload_port": true,
|
||||
"native_usb": true,
|
||||
"use_1200bps_touch": true,
|
||||
"wait_for_upload_port": false,
|
||||
"protocol": "picotool",
|
||||
"protocols": [
|
||||
"blackmagic",
|
||||
"cmsis-dap",
|
||||
"jlink",
|
||||
"raspberrypi-swd",
|
||||
"picotool",
|
||||
"picoprobe",
|
||||
"pico-debug"
|
||||
]
|
||||
},
|
||||
"url": "https://www.raspberrypi.org/products/raspberry-pi-pico/",
|
||||
"vendor": "Adafruit"
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
{
|
||||
"build": {
|
||||
"arduino": {
|
||||
"earlephilhower": {
|
||||
"boot2_source": "boot2_generic_03h_4_padded_checksum.S",
|
||||
"usb_vid": "0x2E8A",
|
||||
"usb_pid": "0x3001"
|
||||
}
|
||||
},
|
||||
"core": "earlephilhower",
|
||||
"cpu": "cortex-m0plus",
|
||||
"extra_flags": "-D ARDUINO_METEHOCA_AKANA_R1 -DARDUINO_ARCH_RP2040 -DUSBD_MAX_POWER_MA=500",
|
||||
"f_cpu": "133000000L",
|
||||
"hwids": [
|
||||
[
|
||||
"0x2E8A",
|
||||
"0x00C0"
|
||||
],
|
||||
[
|
||||
"0x2E8A",
|
||||
"0x3001"
|
||||
]
|
||||
],
|
||||
"mcu": "rp2040",
|
||||
"variant": "akana_r1"
|
||||
},
|
||||
"debug": {
|
||||
"jlink_device": "RP2040_M0_0",
|
||||
"openocd_target": "rp2040.cfg",
|
||||
"svd_path": "rp2040.svd"
|
||||
},
|
||||
"frameworks": [
|
||||
"arduino"
|
||||
],
|
||||
"name": "Akana R1",
|
||||
"upload": {
|
||||
"maximum_ram_size": 270336,
|
||||
"maximum_size": 16777216,
|
||||
"require_upload_port": true,
|
||||
"native_usb": true,
|
||||
"use_1200bps_touch": true,
|
||||
"wait_for_upload_port": false,
|
||||
"protocol": "picotool",
|
||||
"protocols": [
|
||||
"blackmagic",
|
||||
"cmsis-dap",
|
||||
"jlink",
|
||||
"raspberrypi-swd",
|
||||
"picotool",
|
||||
"picoprobe",
|
||||
"pico-debug"
|
||||
]
|
||||
},
|
||||
"url": "https://www.metehoca.com/",
|
||||
"vendor": "METE HOCA"
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
{
|
||||
"build": {
|
||||
"arduino": {
|
||||
"earlephilhower": {
|
||||
"boot2_source": "boot2_w25q080_2_padded_checksum.S",
|
||||
"usb_vid": "0x2E8A",
|
||||
"usb_pid": "0x105E"
|
||||
}
|
||||
},
|
||||
"core": "earlephilhower",
|
||||
"cpu": "cortex-m0plus",
|
||||
"extra_flags": "-D ARDUINO_Breadstick_Raspberry -DARDUINO_ARCH_RP2040 -DUSBD_MAX_POWER_MA=500",
|
||||
"f_cpu": "133000000L",
|
||||
"hwids": [
|
||||
[
|
||||
"0x2E8A",
|
||||
"0x00C0"
|
||||
],
|
||||
[
|
||||
"0x2E8A",
|
||||
"0x105E"
|
||||
]
|
||||
],
|
||||
"mcu": "rp2040",
|
||||
"variant": "breadstick_raspberry"
|
||||
},
|
||||
"debug": {
|
||||
"jlink_device": "RP2040_M0_0",
|
||||
"openocd_target": "rp2040.cfg",
|
||||
"svd_path": "rp2040.svd"
|
||||
},
|
||||
"frameworks": [
|
||||
"arduino"
|
||||
],
|
||||
"name": "Raspberry",
|
||||
"upload": {
|
||||
"maximum_ram_size": 270336,
|
||||
"maximum_size": 16777216,
|
||||
"require_upload_port": true,
|
||||
"native_usb": true,
|
||||
"use_1200bps_touch": true,
|
||||
"wait_for_upload_port": false,
|
||||
"protocol": "picotool",
|
||||
"protocols": [
|
||||
"blackmagic",
|
||||
"cmsis-dap",
|
||||
"jlink",
|
||||
"raspberrypi-swd",
|
||||
"picotool",
|
||||
"picoprobe",
|
||||
"pico-debug"
|
||||
]
|
||||
},
|
||||
"url": "https://shop.breadstick.ca/products/raspberry-breadstick-rp2040",
|
||||
"vendor": "Breadstick"
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
{
|
||||
"build": {
|
||||
"arduino": {
|
||||
"earlephilhower": {
|
||||
"boot2_source": "boot2_w25q16jvxq_4_padded_checksum.S",
|
||||
"usb_vid": "0x2E8A",
|
||||
"usb_pid": "0x0003"
|
||||
}
|
||||
},
|
||||
"core": "earlephilhower",
|
||||
"cpu": "cortex-m0plus",
|
||||
"extra_flags": "-D ARDUINO_MARBLE_PICO -DARDUINO_ARCH_RP2040 -DUSBD_MAX_POWER_MA=500",
|
||||
"f_cpu": "133000000L",
|
||||
"hwids": [
|
||||
[
|
||||
"0x2E8A",
|
||||
"0x00C0"
|
||||
],
|
||||
[
|
||||
"0x2E8A",
|
||||
"0x0003"
|
||||
]
|
||||
],
|
||||
"mcu": "rp2040",
|
||||
"variant": "groundstudio_marble_pico"
|
||||
},
|
||||
"debug": {
|
||||
"jlink_device": "RP2040_M0_0",
|
||||
"openocd_target": "rp2040.cfg",
|
||||
"svd_path": "rp2040.svd"
|
||||
},
|
||||
"frameworks": [
|
||||
"arduino"
|
||||
],
|
||||
"name": "Marble Pico",
|
||||
"upload": {
|
||||
"maximum_ram_size": 270336,
|
||||
"maximum_size": 8388608,
|
||||
"require_upload_port": true,
|
||||
"native_usb": true,
|
||||
"use_1200bps_touch": true,
|
||||
"wait_for_upload_port": false,
|
||||
"protocol": "picotool",
|
||||
"protocols": [
|
||||
"blackmagic",
|
||||
"cmsis-dap",
|
||||
"jlink",
|
||||
"raspberrypi-swd",
|
||||
"picotool",
|
||||
"picoprobe",
|
||||
"pico-debug"
|
||||
]
|
||||
},
|
||||
"url": "https://ardushop.ro/2652-marble-pico.html",
|
||||
"vendor": "GroundStudio"
|
||||
}
|
||||
@@ -103,6 +103,12 @@ target_compile_definitions(picow-noipv6-nobtc-noble PUBLIC
|
||||
LWIP_IPV6=0
|
||||
)
|
||||
|
||||
add_library(picow-noipv6-nobtc-noble-big STATIC)
|
||||
target_compile_definitions(picow-noipv6-nobtc-noble-big PUBLIC
|
||||
__LWIP_MEMMULT=2
|
||||
LWIP_IPV6=0
|
||||
)
|
||||
|
||||
set(picow_link_libraries
|
||||
common
|
||||
cyw43_driver
|
||||
@@ -121,20 +127,40 @@ target_link_libraries(picow-noipv6-nobtc-noble
|
||||
${picow_link_libraries}
|
||||
)
|
||||
|
||||
target_link_libraries(picow-noipv6-nobtc-noble-big
|
||||
${picow_link_libraries}
|
||||
)
|
||||
|
||||
add_library(picow-ipv6-nobtc-noble STATIC)
|
||||
target_compile_definitions(picow-ipv6-nobtc-noble PUBLIC
|
||||
LWIP_IPV6=1
|
||||
)
|
||||
|
||||
add_library(picow-ipv6-nobtc-noble-big STATIC)
|
||||
target_compile_definitions(picow-ipv6-nobtc-noble-big PUBLIC
|
||||
__LWIP_MEMMULT=2
|
||||
LWIP_IPV6=1
|
||||
)
|
||||
|
||||
target_link_libraries(picow-ipv6-nobtc-noble
|
||||
${picow_link_libraries}
|
||||
)
|
||||
|
||||
target_link_libraries(picow-ipv6-nobtc-noble-big
|
||||
${picow_link_libraries}
|
||||
)
|
||||
|
||||
add_library(picow-noipv6-btc-ble STATIC)
|
||||
target_compile_definitions(picow-noipv6-btc-ble PUBLIC
|
||||
LWIP_IPV6=0
|
||||
)
|
||||
|
||||
add_library(picow-noipv6-btc-ble-big STATIC)
|
||||
target_compile_definitions(picow-noipv6-btc-ble-big PUBLIC
|
||||
__LWIP_MEMMULT=2
|
||||
LWIP_IPV6=0
|
||||
)
|
||||
|
||||
set(picow_bt_link_libraries
|
||||
pico_btstack_cyw43
|
||||
pico_btstack_ble
|
||||
@@ -148,17 +174,34 @@ target_link_libraries(picow-noipv6-btc-ble
|
||||
${picow_bt_link_libraries}
|
||||
)
|
||||
|
||||
target_link_libraries(picow-noipv6-btc-ble-big
|
||||
${picow_link_libraries}
|
||||
${picow_bt_link_libraries}
|
||||
)
|
||||
|
||||
add_library(picow-ipv6-btc-ble STATIC)
|
||||
target_compile_definitions(picow-ipv6-btc-ble PUBLIC
|
||||
LWIP_IPV6=1
|
||||
)
|
||||
|
||||
add_library(picow-ipv6-btc-ble-big STATIC)
|
||||
target_compile_definitions(picow-ipv6-btc-ble-big PUBLIC
|
||||
__LWIP_MEMMULT=2
|
||||
LWIP_IPV6=1
|
||||
)
|
||||
|
||||
target_link_libraries(picow-ipv6-btc-ble
|
||||
${picow_link_libraries}
|
||||
${picow_bt_link_libraries}
|
||||
)
|
||||
|
||||
foreach(tgt pico picow-noipv6-nobtc-noble picow-ipv6-nobtc-noble picow-noipv6-btc-ble picow-ipv6-btc-ble)
|
||||
target_link_libraries(picow-ipv6-btc-ble-big
|
||||
${picow_link_libraries}
|
||||
${picow_bt_link_libraries}
|
||||
)
|
||||
|
||||
|
||||
foreach(tgt pico picow-noipv6-nobtc-noble picow-ipv6-nobtc-noble picow-noipv6-btc-ble picow-ipv6-btc-ble picow-noipv6-nobtc-noble-big picow-ipv6-nobtc-noble-big picow-noipv6-btc-ble-big picow-ipv6-btc-ble-big)
|
||||
add_custom_command(TARGET ${tgt} POST_BUILD
|
||||
COMMAND ar d lib${tgt}.a stdio.c.obj stdio_uart.c.obj stdio_usb.c.obj stdio_usb_descriptors.c.obj pico_malloc.c.obj
|
||||
COMMAND ar d lib${tgt}.a btstack_flash_bank.c.obj # Need to override with our own implementation
|
||||
|
||||
+16
-17
@@ -14,6 +14,10 @@ extern void interrupts();
|
||||
extern unsigned long __lwip_rand(void);
|
||||
#define LWIP_RAND() __lwip_rand()
|
||||
|
||||
#ifndef __LWIP_MEMMULT
|
||||
#define __LWIP_MEMMULT 1
|
||||
#endif
|
||||
|
||||
// Common settings used in most of the pico_w examples
|
||||
// (see https://www.nongnu.org/lwip/2_1_x/group__lwip__opts.html for details)
|
||||
|
||||
@@ -22,10 +26,10 @@ extern unsigned long __lwip_rand(void);
|
||||
#define MEM_LIBC_MALLOC 0
|
||||
|
||||
#define MEM_ALIGNMENT 4
|
||||
#define MEM_SIZE 16384
|
||||
#define MEMP_NUM_TCP_SEG 32
|
||||
#define MEMP_NUM_ARP_QUEUE 10
|
||||
#define PBUF_POOL_SIZE 24
|
||||
#define MEM_SIZE (__LWIP_MEMMULT * 16384)
|
||||
#define MEMP_NUM_TCP_SEG (32)
|
||||
#define MEMP_NUM_ARP_QUEUE (10)
|
||||
#define PBUF_POOL_SIZE (__LWIP_MEMMULT > 1 ? 32 : 24)
|
||||
#define LWIP_ARP 2
|
||||
#define LWIP_ETHERNET 1
|
||||
#define LWIP_ICMP 1
|
||||
@@ -38,11 +42,12 @@ extern unsigned long __lwip_rand(void);
|
||||
#define LWIP_NETIF_LINK_CALLBACK 1
|
||||
#define LWIP_NETIF_HOSTNAME 1
|
||||
#define LWIP_NETCONN 0
|
||||
#define MEM_STATS 1
|
||||
#define SYS_STATS 1
|
||||
#define MEMP_STATS 1
|
||||
#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 0
|
||||
#define LWIP_DHCP 1
|
||||
#define LWIP_IPV4 1
|
||||
@@ -55,7 +60,8 @@ extern unsigned long __lwip_rand(void);
|
||||
#define LWIP_DHCP_DOES_ACD_CHECK 0
|
||||
|
||||
// See #1285
|
||||
#define MEMP_NUM_UDP_PCB 6
|
||||
#define MEMP_NUM_UDP_PCB (__LWIP_MEMMULT * 6)
|
||||
#define MEMP_NUM_TCP_PCB (__LWIP_MEMMULT * 5)
|
||||
|
||||
#if LWIP_IPV6
|
||||
#define LWIP_IPV6_DHCP6 1
|
||||
@@ -68,14 +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
|
||||
#define MEMP_STATS 1
|
||||
#define MEM_STATS 1
|
||||
#endif
|
||||
|
||||
#define LWIP_DEBUG 0
|
||||
#define ETHARP_DEBUG LWIP_DBG_OFF
|
||||
#define NETIF_DEBUG LWIP_DBG_OFF
|
||||
#define PBUF_DEBUG LWIP_DBG_OFF
|
||||
|
||||
+27
-1
@@ -117,6 +117,19 @@ def BuildIPBTStack(name):
|
||||
print("%s.menu.ipbtstack.ipv4ipv6btcble=IPv4 + IPv6 + Bluetooth" % (name))
|
||||
print('%s.menu.ipbtstack.ipv4ipv6btcble.build.libpicow=libpicow-ipv6-btc-ble.a' % (name))
|
||||
print('%s.menu.ipbtstack.ipv4ipv6btcble.build.libpicowdefs=-DLWIP_IPV6=1 -DLWIP_IPV4=1 -DENABLE_CLASSIC=1 -DENABLE_BLE=1' % (name))
|
||||
print("%s.menu.ipbtstack.ipv4onlybig=IPv4 Only - 32K" % (name))
|
||||
print('%s.menu.ipbtstack.ipv4onlybig.build.libpicow=libpicow-noipv6-nobtc-noble-big.a' % (name))
|
||||
print('%s.menu.ipbtstack.ipv4onlybig.build.libpicowdefs=-DLWIP_IPV6=0 -DLWIP_IPV4=1 -D__LWIP_MEMMULT=2' % (name))
|
||||
print("%s.menu.ipbtstack.ipv4ipv6big=IPv4 + IPv6 - 32K" % (name))
|
||||
print('%s.menu.ipbtstack.ipv4ipv6big.build.libpicow=libpicow-ipv6-nobtc-noble-big.a' % (name))
|
||||
print('%s.menu.ipbtstack.ipv4ipv6big.build.libpicowdefs=-DLWIP_IPV6=1 -DLWIP_IPV4=1 -D__LWIP_MEMMULT=2' % (name))
|
||||
print("%s.menu.ipbtstack.ipv4btcblebig=IPv4 + Bluetooth - 32K" % (name))
|
||||
print('%s.menu.ipbtstack.ipv4btcblebig.build.libpicow=libpicow-noipv6-btc-ble-big.a' % (name))
|
||||
print('%s.menu.ipbtstack.ipv4btcblebig.build.libpicowdefs=-DLWIP_IPV6=0 -DLWIP_IPV4=1 -DENABLE_CLASSIC=1 -DENABLE_BLE=1 -D__LWIP_MEMMULT=2' % (name))
|
||||
print("%s.menu.ipbtstack.ipv4ipv6btcblebig=IPv4 + IPv6 + Bluetooth - 32K" % (name))
|
||||
print('%s.menu.ipbtstack.ipv4ipv6btcblebig.build.libpicow=libpicow-ipv6-btc-ble-big.a' % (name))
|
||||
print('%s.menu.ipbtstack.ipv4ipv6btcblebig.build.libpicowdefs=-DLWIP_IPV6=1 -DLWIP_IPV4=1 -DENABLE_CLASSIC=1 -DENABLE_BLE=1 -D__LWIP_MEMMULT=2' % (name))
|
||||
|
||||
|
||||
def BuildUploadMethodMenu(name):
|
||||
for a, b, c, d, e, f in [ ["default", "Default (UF2)", 256, "picoprobe_cmsis_dap.tcl", "uf2conv", "uf2conv-network"],
|
||||
@@ -237,6 +250,10 @@ def MakeBoard(name, vendor_name, product_name, vid, pid, pwr, boarddefine, flash
|
||||
elif name == "pimoroni_tiny2040":
|
||||
BuildFlashMenu(name, 2*1024*1024, fssizelist)
|
||||
BuildFlashMenu(name, 8*1024*1024, [0, 7*1024*1024, 4*1024*1024, 2*1024*1024])
|
||||
elif name == "akana_r1":
|
||||
BuildFlashMenu(name, 2*1024*1024, [0, 1*1024*1024])
|
||||
BuildFlashMenu(name, 8*1024*1024, [0, 7*1024*1024, 4*1024*1024, 2*1024*1024])
|
||||
BuildFlashMenu(name, 16*1024*1024, [0, 15*1024*1024, 14*1024*1024, 12*1024*1024, 8*1024*1024, 4*1024*1024, 2*1024*1024])
|
||||
else:
|
||||
BuildFlashMenu(name, flashsizemb * 1024 * 1024, fssizelist)
|
||||
BuildFreq(name)
|
||||
@@ -365,6 +382,7 @@ MakeBoard("0xcb_helios", "0xCB", "Helios", "0x1209", "0xCB74", 500, "0XCB_HELIOS
|
||||
MakeBoard("adafruit_feather", "Adafruit", "Feather RP2040", "0x239a", "0x80f1", 250, "ADAFRUIT_FEATHER_RP2040", 8, "boot2_w25x10cl_4_padded_checksum")
|
||||
MakeBoard("adafruit_feather_scorpio", "Adafruit", "Feather RP2040 SCORPIO", "0x239a", "0x8121", 250, "ADAFRUIT_FEATHER_RP2040_SCORPIO", 8, "boot2_w25q080_2_padded_checksum")
|
||||
MakeBoard("adafruit_feather_dvi", "Adafruit", "Feather RP2040 DVI", "0x239a", "0x8127", 250, "ADAFRUIT_FEATHER_RP2040_DVI", 8, "boot2_w25q080_2_padded_checksum")
|
||||
MakeBoard("adafruit_feather_adalogger", "Adafruit", "Feather RP2040 Adalogger", "0x239a", "0x815d", 250, "ADAFRUIT_FEATHER_RP2040_ADALOGGER", 8, "boot2_w25q080_2_padded_checksum")
|
||||
MakeBoard("adafruit_feather_rfm", "Adafruit", "Feather RP2040 RFM", "0x239a", "0x812D", 250, "ADAFRUIT_FEATHER_RP2040_RFM", 8, "boot2_w25q080_2_padded_checksum")
|
||||
MakeBoard("adafruit_feather_thinkink", "Adafruit", "Feather RP2040 ThinkINK", "0x239a", "0x812B", 250, "ADAFRUIT_FEATHER_RP2040_THINKINK", 8, "boot2_w25q080_2_padded_checksum")
|
||||
MakeBoard("adafruit_feather_usb_host", "Adafruit", "Feather RP2040 USB Host", "0x239a", "0x8129", 250, "ADAFRUIT_FEATHER_RP2040_USB_HOST", 8, "boot2_w25q080_2_padded_checksum")
|
||||
@@ -384,6 +402,9 @@ MakeBoard("arduino_nano_connect", "Arduino", "Nano RP2040 Connect", "0x2341", ["
|
||||
# ArtronShop
|
||||
MakeBoard("artronshop_rp2_nano", "ArtronShop", "RP2 Nano", "0x2e8a", "0x000a", 250, "ARTRONSHOP_RP2_NANO", 2, "boot2_w25q080_2_padded_checksum")
|
||||
|
||||
# Breadstick
|
||||
MakeBoard("breadstick_raspberry", "Breadstick", "Raspberry", "0x2e8a", "0x105e" , 500, "Breadstick_Raspberry", 16, "boot2_w25q080_2_padded_checksum", board_url="https://shop.breadstick.ca/products/raspberry-breadstick-rp2040")
|
||||
|
||||
# BridgeTek
|
||||
MakeBoard("bridgetek_idm2040-7a", "BridgeTek", "IDM2040-7A", "0x2e8a", "0x1041", 250, "BRIDGETEK_IDM2040-7A", 8, "boot2_w25q080_2_padded_checksum", ["FT8XX_TYPE=BT817", "DISPLAY_RES=WVGA", "PLATFORM_RP2040"])
|
||||
|
||||
@@ -407,13 +428,15 @@ MakeBoard("dfrobot_beetle_rp2040", "DFRobot", "Beetle RP2040", "0x3343", "0x4253
|
||||
# DudesCab
|
||||
MakeBoard("DudesCab", "L'atelier d'Arnoz", "DudesCab", "0x2e8a", "0x106F", 250, "RASPBERRY_PI_PICO", 4, "boot2_w25q080_2_padded_checksum")
|
||||
|
||||
|
||||
# ElectronicCat
|
||||
MakeBoard("electroniccats_huntercat_nfc", "ElectronicCats", "HunterCat NFC RP2040", "0x2E8A", "0x1037", 500, "ELECTRONICCATS_HUNTERCAT_NFC", 2, "boot2_w25q080_2_padded_checksum")
|
||||
|
||||
# ExtremeElectronics
|
||||
MakeBoard("extelec_rc2040", "ExtremeElectronics", "RC2040", "0x2e8a", "0xee20", 250, "EXTREMEELEXTRONICS_RC2040", 2, "boot2_w25q080_2_padded_checksum")
|
||||
|
||||
# GroundStudio
|
||||
MakeBoard('groundstudio_marble_pico', "GroundStudio", "Marble Pico", "0x2e8a", "0x0003", 500, "MARBLE_PICO", 8, "boot2_w25q16jvxq_4_padded_checksum", None, "https://ardushop.ro/2652-marble-pico.html")
|
||||
|
||||
# iLabs
|
||||
MakeBoard("challenger_2040_lte", "iLabs", "Challenger 2040 LTE", "0x2e8a", "0x100b", 500, "CHALLENGER_2040_LTE_RP2040", 8, "boot2_w25q080_2_padded_checksum")
|
||||
MakeBoard("challenger_2040_lora", "iLabs", "Challenger 2040 LoRa", "0x2e8a", "0x1023", 250, "CHALLENGER_2040_LORA_RP2040", 8, "boot2_w25q080_2_padded_checksum")
|
||||
@@ -432,6 +455,9 @@ MakeBoard("ilabs_rpico32", "iLabs", "RPICO32", "0x2e8a", "0x1010", 250, "ILABS_2
|
||||
MakeBoard("melopero_cookie_rp2040", "Melopero", "Cookie RP2040", "0x2e8a", "0x1011", 250, "MELOPERO_COOKIE_RP2040", 8, "boot2_w25q080_2_padded_checksum")
|
||||
MakeBoard("melopero_shake_rp2040", "Melopero", "Shake RP2040", "0x2e8a", "0x1005", 250, "MELOPERO_SHAKE_RP2040", 16, "boot2_w25q080_2_padded_checksum")
|
||||
|
||||
# Mete Hoca
|
||||
MakeBoard("akana_r1", "METE HOCA", "Akana R1", "0x2e8a", "0x3001", 500, "METEHOCA_AKANA_R1", 16, "boot2_generic_03h_4_padded_checksum", board_url="https://www.metehoca.com/")
|
||||
|
||||
# Neko Systems
|
||||
MakeBoard("nekosystems_bl2040_mini", "Neko Systems", "BL2040 Mini", "0x2e8a", "0x000a", 500, "NEKOSYSTEMS_BL2040_MINI", 4, "boot2_generic_03h_2_padded_checksum")
|
||||
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
#pragma once
|
||||
|
||||
// LEDs
|
||||
#define PIN_LED (13u)
|
||||
|
||||
// NeoPixel
|
||||
#define PIN_NEOPIXEL (17u)
|
||||
|
||||
// 'Boot0' button also on GPIO #7
|
||||
#define PIN_BUTTON (7u)
|
||||
|
||||
// SD Card connector
|
||||
#define PIN_CARD_DETECT (16u)
|
||||
#define PIN_SD_CLK (18u)
|
||||
#define PIN_SD_CMD_MOSI (19u)
|
||||
#define PIN_SD_DAT0_MISO (20u)
|
||||
#define PIN_SD_DAT1 (21u)
|
||||
#define PIN_SD_DAT2 (22u)
|
||||
#define PIN_SD_DAT3_CS (23u)
|
||||
|
||||
// Serial
|
||||
#define PIN_SERIAL1_TX (0u)
|
||||
#define PIN_SERIAL1_RX (1u)
|
||||
|
||||
// Not pinned out
|
||||
#define PIN_SERIAL2_TX (31u)
|
||||
#define PIN_SERIAL2_RX (31u)
|
||||
|
||||
// SPI
|
||||
#define PIN_SPI0_MISO (8u)
|
||||
#define PIN_SPI0_MOSI (15u)
|
||||
#define PIN_SPI0_SCK (14u)
|
||||
#define PIN_SPI0_SS (13u)
|
||||
#define __SPI0_DEVICE spi1
|
||||
|
||||
// SPI1 for SD card
|
||||
#define PIN_SPI1_MISO PIN_SD_DAT0_MISO
|
||||
#define PIN_SPI1_MOSI PIN_SD_CMD_MOSI
|
||||
#define PIN_SPI1_SCK PIN_SD_CLK
|
||||
#define PIN_SPI1_SS PIN_SD_DAT3_CS
|
||||
#define __SPI1_DEVICE spi0
|
||||
|
||||
// Wire
|
||||
#define PIN_WIRE0_SDA (2u)
|
||||
#define PIN_WIRE0_SCL (3u)
|
||||
#define __WIRE0_DEVICE i2c1
|
||||
|
||||
#define PIN_WIRE1_SDA (31u)
|
||||
#define PIN_WIRE1_SCL (31u)
|
||||
#define __WIRE1_DEVICE i2c0
|
||||
|
||||
#define SERIAL_HOWMANY (2u)
|
||||
#define SPI_HOWMANY (2u)
|
||||
#define WIRE_HOWMANY (1u)
|
||||
|
||||
#include "../generic/common.h"
|
||||
@@ -0,0 +1,46 @@
|
||||
#pragma once
|
||||
|
||||
// METE HOCA Akana R1 Pin Definitions
|
||||
|
||||
// LEDs
|
||||
#define PIN_LED (25u)
|
||||
#define PIN_NEO (24u)
|
||||
|
||||
// Buttons
|
||||
#define BTN_ENTER (14u)
|
||||
#define BTN_BACK (15u)
|
||||
#define BTN_UP (22u)
|
||||
#define BTN_DOWN (23u)
|
||||
#define BTN_LEFT (20u)
|
||||
#define BTN_RIGHT (21u)
|
||||
|
||||
// Serial
|
||||
#define PIN_SERIAL1_TX (0u)
|
||||
#define PIN_SERIAL1_RX (1u)
|
||||
|
||||
#define PIN_SERIAL2_TX (8u)
|
||||
#define PIN_SERIAL2_RX (9u)
|
||||
|
||||
// SPI
|
||||
#define PIN_SPI0_MISO (16u) // RX
|
||||
#define PIN_SPI0_MOSI (19u) // TX
|
||||
#define PIN_SPI0_SCK (18u) // SCK
|
||||
#define PIN_SPI0_SS (17u) // CSn
|
||||
|
||||
#define PIN_SPI1_MISO (12u) // RX
|
||||
#define PIN_SPI1_MOSI (11u) // TX
|
||||
#define PIN_SPI1_SCK (10u) // SCK
|
||||
#define PIN_SPI1_SS (13u) // CSn
|
||||
|
||||
// Wire
|
||||
#define PIN_WIRE0_SDA (4u)
|
||||
#define PIN_WIRE0_SCL (5u)
|
||||
|
||||
#define PIN_WIRE1_SDA (6u)
|
||||
#define PIN_WIRE1_SCL (7u)
|
||||
|
||||
#define SERIAL_HOWMANY (3u)
|
||||
#define SPI_HOWMANY (2u)
|
||||
#define WIRE_HOWMANY (2u)
|
||||
|
||||
#include "../generic/common.h"
|
||||
@@ -0,0 +1,95 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
|
||||
// Pin definitions taken from:
|
||||
// https://github.com/Breadstick-Innovations/Raspberry-Breadstick
|
||||
|
||||
|
||||
// Serial
|
||||
#define PIN_SERIAL1_TX (20u)
|
||||
#define PIN_SERIAL1_RX (21u)
|
||||
|
||||
// SPI
|
||||
|
||||
#define PIN_SPI1_MISO (8u)
|
||||
#define PIN_SPI1_MOSI (11u)
|
||||
#define PIN_SPI1_SCK (10u)
|
||||
#define PIN_SPI1_SS (9u)
|
||||
|
||||
// Wire
|
||||
#define PIN_WIRE0_SDA (12u)
|
||||
#define PIN_WIRE0_SCL (13u)
|
||||
|
||||
#define PIN_WIRE1_SDA (22u)
|
||||
#define PIN_WIRE1_SCL (23u)
|
||||
|
||||
#define SERIAL_HOWMANY (2u)
|
||||
#define SPI_HOWMANY (1u)
|
||||
#define WIRE_HOWMANY (2u)
|
||||
|
||||
#define PINS_COUNT (22u)
|
||||
#define NUM_DIGITAL_PINS (22u)
|
||||
#define NUM_ANALOG_INPUTS (4u)
|
||||
#define NUM_ANALOG_OUTPUTS (0u)
|
||||
#define ADC_RESOLUTION (12u)
|
||||
#define WIRE_INTERFACES_COUNT (WIRE_HOWMANY)
|
||||
|
||||
static const uint8_t D1 = (27u);
|
||||
static const uint8_t D2 = (26u);
|
||||
static const uint8_t D3 = (11u);
|
||||
static const uint8_t D4 = (10u);
|
||||
static const uint8_t D5 = (9u);
|
||||
static const uint8_t D6 = (8u);
|
||||
static const uint8_t D7 = (7u);
|
||||
static const uint8_t D8 = (6u);
|
||||
static const uint8_t D9 = (5u);
|
||||
static const uint8_t D10 = (24u);
|
||||
static const uint8_t D11 = (23u);
|
||||
static const uint8_t D12 = (22u);
|
||||
static const uint8_t D13 = (21u);
|
||||
static const uint8_t D14 = (20u);
|
||||
static const uint8_t D15 = (19u);
|
||||
static const uint8_t D16 = (18u);
|
||||
static const uint8_t D17 = (29u);
|
||||
static const uint8_t D18 = (28u);
|
||||
|
||||
|
||||
#ifdef __PIN_A2
|
||||
static const uint8_t A2 = __PIN_A2;
|
||||
#else
|
||||
static const uint8_t A2 = (26u);
|
||||
#endif
|
||||
|
||||
#ifdef __PIN_A1
|
||||
static const uint8_t A1 = __PIN_A1;
|
||||
#else
|
||||
static const uint8_t A1 = (27u);
|
||||
#endif
|
||||
|
||||
#ifdef __PIN_A18
|
||||
static const uint8_t A18 = __PIN_A18;
|
||||
#else
|
||||
static const uint8_t A18 = (28u);
|
||||
#endif
|
||||
|
||||
#ifdef __PIN_A17
|
||||
static const uint8_t A17 = __PIN_A17;
|
||||
#else
|
||||
static const uint8_t A17 = (29u);
|
||||
#endif
|
||||
|
||||
static const uint8_t SS = PIN_SPI1_SS;
|
||||
static const uint8_t MOSI = PIN_SPI1_MOSI;
|
||||
static const uint8_t MISO = PIN_SPI1_MISO;
|
||||
static const uint8_t SCK = PIN_SPI1_SCK;
|
||||
|
||||
static const uint8_t SDA = PIN_WIRE1_SDA;
|
||||
static const uint8_t SCL = PIN_WIRE1_SCL;
|
||||
|
||||
static const uint8_t IMU_SDA = PIN_WIRE0_SDA;
|
||||
static const uint8_t IMU_SCL = PIN_WIRE0_SCL;
|
||||
|
||||
static const uint8_t DOTSTAR_CLOCK = (16u);
|
||||
static const uint8_t DOTSTAR_DATA = (17u);
|
||||
@@ -0,0 +1,51 @@
|
||||
// GroundStudio Marble Pico
|
||||
//
|
||||
// Reference Pinout:
|
||||
// https://raw.githubusercontent.com/GroundStudio/GroundStudio_Marble_Pico/main/Documentation/REV0.0.3/RLJDMV_GS%20REV0.0.3%20GroundStudio%20Marble%20Pico%20Pinout%20REV%201.1.pdf
|
||||
// Reference Schematic:
|
||||
// https://raw.githubusercontent.com/GroundStudio/GroundStudio_Marble_Pico/main/Documentation/REV0.0.3/RLJDMV_GS%20REV0.0.3%20GroundStudio%20Marble%20Pico%20Schematic.pdf
|
||||
|
||||
// Built-in LED
|
||||
#define PIN_LED (25u)
|
||||
|
||||
// Built-in battery charging circuit
|
||||
#define PIN_VBAT (24u) // J17 Default Connection
|
||||
|
||||
// Built-in SD reader
|
||||
#define PIN_SD_SWITCH (24u) // J17 Alternative Connection
|
||||
#define PIN_SPI0_MISO (16u)
|
||||
#define PIN_SPI0_MOSI (19u)
|
||||
#define PIN_SPI0_SCK (18u)
|
||||
#define PIN_SPI0_SS (17u)
|
||||
|
||||
// ADC GPIO pins
|
||||
#define PIN_A0 (26u)
|
||||
#define PIN_A1 (27u)
|
||||
#define PIN_A2 (28u)
|
||||
|
||||
// Serial
|
||||
#define PIN_SERIAL1_TX (0u)
|
||||
#define PIN_SERIAL1_RX (1u)
|
||||
|
||||
#define PIN_SERIAL2_TX (8u)
|
||||
#define PIN_SERIAL2_RX (9u)
|
||||
|
||||
// SPI
|
||||
#define PIN_SPI1_MISO (12u)
|
||||
#define PIN_SPI1_MOSI (11u)
|
||||
#define PIN_SPI1_SCK (10u)
|
||||
#define PIN_SPI1_SS (13u)
|
||||
|
||||
// Wire
|
||||
// Built-in I2C connector
|
||||
#define PIN_WIRE0_SDA (4u)
|
||||
#define PIN_WIRE0_SCL (5u)
|
||||
|
||||
#define PIN_WIRE1_SDA (26u)
|
||||
#define PIN_WIRE1_SCL (27u)
|
||||
|
||||
#define SERIAL_HOWMANY (3u)
|
||||
#define SPI_HOWMANY (2u)
|
||||
#define WIRE_HOWMANY (2u)
|
||||
|
||||
#include "../generic/common.h"
|
||||
@@ -46,4 +46,35 @@
|
||||
#define SPI_HOWMANY (2u)
|
||||
#define WIRE_HOWMANY (2u)
|
||||
|
||||
#define GPIO0 (0u)
|
||||
#define GPIO1 (1u)
|
||||
#define GPIO2 (2u)
|
||||
#define GPIO3 (3u)
|
||||
#define GPIO4 (4u)
|
||||
#define GPIO5 (5u)
|
||||
#define GPIO6 (6u)
|
||||
#define GPIO7 (7u)
|
||||
#define GPIO8 (8u)
|
||||
#define GPIO9 (9u)
|
||||
#define GPIO10 (10u)
|
||||
#define GPIO11 (11u)
|
||||
#define GPIO12 (12u)
|
||||
#define GPIO13 (13u)
|
||||
#define GPIO14 (14u)
|
||||
#define GPIO15 (15u)
|
||||
#define GPIO16 (16u)
|
||||
#define GPIO17 (17u)
|
||||
#define GPIO18 (18u)
|
||||
#define GPIO19 (19u)
|
||||
#define GPIO20 (20u)
|
||||
#define GPIO21 (21u)
|
||||
#define GPIO22 (22u)
|
||||
#define GPIO23 (23u)
|
||||
#define GPIO24 (24u)
|
||||
#define GPIO25 (25u)
|
||||
#define GPIO26 (26u)
|
||||
#define GPIO27 (27u)
|
||||
#define GPIO28 (28u)
|
||||
#define GPIO29 (29u)
|
||||
|
||||
#include "../generic/common.h"
|
||||
Reference in New Issue
Block a user