Compare commits

...
29 Commits
Author SHA1 Message Date
Earle F. Philhower, III 679be8520f Update version 2024-05-29 14:54:32 -07:00
Earle F. Philhower, III 01e9dc99f2 Add A2DP sink (speaker) support (#2177)
Provide direct connection from BT audio to I2S and PWM audio outputs.
Example included showing play/pause operation.
2024-05-29 14:53:06 -07:00
Earle F. Philhower, III ec5e62e533 Add Bluetooth audio out (A2DP) on the PicoW (#2174)
Adds a library to run classic Bluetooth A2DP source (output) audio from
the PicoW.  Simple example showing operation and callbacks.

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

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

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

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

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

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

Also, protect netif_add/_remove on the very small possibilty of being
called by LwipIntfDev devices while the CYW43 driver is doing work.
2024-05-13 19:08:38 -07:00
Earle F. Philhower, III d850de15fa Update version 2024-05-13 12:07:12 -07:00
Daniel Egnor 819a73ba5a Fix PID specification for arduino-cli (#2157) 2024-05-13 12:06:31 -07:00
Earle F. Philhower, III 8d4ef5ef8c FreeRTOS: Disable IRQs when task switching disabled (#2155)
Avoids crash seen in #2132
2024-05-10 18:53:45 -07:00
Juraj Andrássy 8673da2505 Ethernet legacy API compatibility layer (#2147)
With example from the Arduino Ethernet library
2024-05-06 10:06:51 -07:00
Earle F. Philhower, III fa58b6987a CI can use custom defines, add ESPHost/WINC tests (#2142)
If a file called `.ci.defines` is present in a directory, apply those
while building the specified sketch.

* Add an lwip_ESPHost test, like the wired Ethernet ones
* Add WINC1500 test and CI hook
* Remove 1 minor warning in WINC build
2024-05-02 13:37:50 -07:00
Earle F. Philhower, III 0b4afab56c Update README.md (#2141)
Add missing boards and WiFi types
2024-05-02 12:42:27 -07:00
Juraj Andrássy 597251d6b5 Add lwIP_WINC1500 - new WiFi driver for ATWINC1500 (#2140) 2024-05-02 12:13:21 -07:00
Earle F. Philhower, III 56e5559357 Minor keyword addition for syntax hilighting (#2139) 2024-05-01 12:27:03 -07:00
Earle F. Philhower, III 0b4394468b Update to latest Joystick upstream (#2138)
Fixes #2136
2024-04-30 12:46:28 -07:00
Dominic PearmanandDominic Pearman 315bfdace1 BTstack: remove superfluous call during setup. (#2137)
Co-authored-by: Dominic Pearman <dominic@phymorous.de>
2024-04-30 10:23:35 -07:00
Calvin Huang 783bee5c49 Add functions to set PDM pins, remove unused pwrPin (#2133)
* functions to set PDM pins

* change pin set method to better match existing libs
2024-04-29 09:32:22 -07:00
Dominic PearmanandDominic Pearman a439028087 BTstack: added function to set scan respone data. (#2134)
Co-authored-by: Dominic Pearman <dominic@phymorous.de>
2024-04-29 08:06:50 -07:00
Earle F. Philhower, III a49bcd4a95 Remove "EXAMPLE" from LWIP header (#2128)
The lwipopts.h file started with the PicoW example one, but no longer
tracks it, so remove the EXAMPLE define guard.
2024-04-26 11:00:11 -07:00
Earle F. Philhower, III 6279b60179 Add missing JSON files for new boards (#2125) 2024-04-25 15:39:09 -07:00
Earle F. Philhower, III a8e6634776 Avoid swapping L/R channels on I2S input (#2124)
Fixes #2123
2024-04-25 11:22:07 -07:00
Earle F. Philhower, III bd8eb9bca2 Shift I2S input data by 1 bit (#2121)
Fixes #2037
2024-04-24 11:20:22 -07:00
142 changed files with 90283 additions and 597 deletions
+2 -2
View File
@@ -24,8 +24,8 @@ jobs:
- name: Run codespell
uses: codespell-project/actions-codespell@master
with:
skip: ./ArduinoCore-API,./libraries/ESP8266SdFat,./libraries/Adafruit_TinyUSB_Arduino,./libraries/LittleFS/lib,./tools/pyserial,./pico-sdk,./.github,./docs/i2s.rst,./cores/rp2040/api,./libraries/FreeRTOS,./tools/libbearssl/bearssl,./include,./libraries/WiFi/examples/BearSSL_Server,./ota/uzlib,./libraries/http-parser/lib,./libraries/WebServer/examples/HelloServerBearSSL/HelloServerBearSSL.ino,./libraries/HTTPUpdateServer/examples/SecureBearSSLUpdater/SecureBearSSLUpdater.ino,./.git,./libraries/FatFS/lib/fatfs,./libraries/FatFS/src/diskio.h,./libraries/FatFS/src/ff.cpp,./libraries/FatFS/src/ffconf.h,./libraries/FatFS/src/ffsystem.cpp,./libraries/FatFS/src/ff.h
ignore_words_list: ser,dout
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
# Consistent style
astyle:
+8 -2
View File
@@ -50,6 +50,8 @@ Read the [Contributing Guide](https://github.com/earlephilhower/arduino-pico/blo
* Melopero Cookie RP2040
* Melopero Shake RP2040
* Neko Systems BL2040 Mini
* Olimex RP2040-Pico30
* Newsan Archi
* nullbits Bit-C PRO
* Pimoroni PGA2040
* Pimoroni Plasma2040
@@ -62,6 +64,7 @@ Read the [Contributing Guide](https://github.com/earlephilhower/arduino-pico/blo
* Seeed XIAO RP2040
* Silicognition RP2040-Shim
* Solder Party RP2040 Stamp
* SparkFun MicroMod RP2040
* SparkFun ProMicro RP2040
* SparkFun Thing Plus RP2040
* uPesy RP2040 DevKit
@@ -72,6 +75,8 @@ Read the [Contributing Guide](https://github.com/earlephilhower/arduino-pico/blo
* Waveshare RP2040 Plus
* Waveshare RP2040 LCD 0.96
* Waveshare RP2040 LCD 1.28
* Waveshare RP2040 Matrix
* Waveshare RP2040 PiZero
* WIZnet W5100S-EVB-Pico
* WIZnet W5500-EVB-Pico
* WIZnet WizFi360-EVB-Pico
@@ -81,7 +86,7 @@ Read the [Contributing Guide](https://github.com/earlephilhower/arduino-pico/blo
* 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
* Generic Arduino USB Serial, Keyboard, Joystick, and Mouse emulation
* WiFi (Pico W)
* WiFi (Pico W, ESP32-based ESPHost, Atmel WINC1500)
* Ethernet (Wired W5500, W5100, ENC28J60)
* HTTP client and server (WebServer)
* SSL/TLS/HTTPS
@@ -93,7 +98,8 @@ Read the [Contributing Guide](https://github.com/earlephilhower/arduino-pico/blo
* digitalWrite/Read, shiftIn/Out, tone, analogWrite(PWM)/Read, temperature
* Analog stereo audio in using DMA and the built-in ADC
* Analog stereo audio out using PWM hardware
* USB drive mode for data loggers (SingleFileDrive)
* Bluetooth A2DP audio source (output) 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
+1192 -310
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -1,5 +1,5 @@
#pragma once
#define ARDUINO_PICO_MAJOR 3
#define ARDUINO_PICO_MINOR 8
#define ARDUINO_PICO_MINOR 9
#define ARDUINO_PICO_REVISION 0
#define ARDUINO_PICO_VERSION_STR "3.8.0"
#define ARDUINO_PICO_VERSION_STR "3.9.0"
+32
View File
@@ -0,0 +1,32 @@
// Use to create a callback thunk from C to C++
// #define CCALLBACKNAME to a unique per-file name and #include this file
// To make a CB use a define of the form:
/*
#define PACKETHANDLERCB(class, cbFcn) \
(CCALLBACKNAME<void(uint8_t, uint16_t, uint8_t*, uint16_t), __COUNTER__>::func = std::bind(&class::cbFcn, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4), \
static_cast<btstack_packet_handler_t>(<CCALLBACKNAMEvoid(uint8_t, uint16_t, uint8_t*, uint16_t), __COUNTER__ - 1>::callback))
*/
#include <functional>
// Thank you to https://stackoverflow.com/questions/66474621/multiple-non-static-callbacks-of-c-member-functions for the following beautiful hack
#ifndef CCALLBACKNAME
#define CCALLBACKNAME _CCallback
#endif
template <typename T, int tag>
struct CCALLBACKNAME;
template <typename Ret, typename... Params, int tag>
struct CCALLBACKNAME<Ret(Params...), tag> {
template <typename... Args>
static Ret callback(Args... args) {
return func(args...);
}
int _tag = tag;
static std::function<Ret(Params...)> func;
};
template <typename Ret, typename... Params, int tag>
std::function<Ret(Params...)> CCALLBACKNAME<Ret(Params...), tag>::func;
+12
View File
@@ -358,4 +358,16 @@ extern "C" {
__real_raw_remove(pcb);
}
extern struct netif *__real_netif_add(struct netif *netif, const ip4_addr_t *ipaddr, const ip4_addr_t *netmask, const ip4_addr_t *gw, void *state, netif_init_fn init, netif_input_fn input);
struct netif *__wrap_netif_add(struct netif *netif, const ip4_addr_t *ipaddr, const ip4_addr_t *netmask, const ip4_addr_t *gw, void *state, netif_init_fn init, netif_input_fn input) {
LWIPMutex m;
return __real_netif_add(netif, ipaddr, netmask, gw, state, init, input);
}
extern void __real_netif_remove(struct netif *netif);
void __wrap_netif_remove(struct netif *netif) {
LWIPMutex m;
__real_netif_remove(netif);
}
}; // extern "C"
+1 -1
View File
@@ -1212,7 +1212,7 @@ static uint16_t handle_prepare_write_request(att_connection_t * att_connection,
}
/*
@brief transcation queue of prepared writes, e.g., after disconnect
@brief transaction queue of prepared writes, e.g., after disconnect
*/
void att_clear_transaction_queue(att_connection_t * att_connection) {
(*att_write_callback)(att_connection->con_handle, 0, ATT_TRANSACTION_MODE_CANCEL, 0, NULL, 0);
+1 -1
View File
@@ -257,7 +257,7 @@ extern "C" {
uint8_t * response_buffer);
/**
@brief transcation queue of prepared writes, e.g., after disconnect
@brief transaction queue of prepared writes, e.g., after disconnect
@return att_connection
*/
void att_clear_transaction_queue(att_connection_t * att_connection);
+121
View File
@@ -0,0 +1,121 @@
// Taken from LWIP's inet_chksum.c just to set the -O2 flag
/*
Copyright (c) 2001-2004 Swedish Institute of Computer Science.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
This file is part of the lwIP TCP/IP stack.
Author: Adam Dunkels <adam@sics.se>
*/
#include "lwip/opt.h"
#include "lwip/inet_chksum.h"
#include "lwip/def.h"
#include "lwip/ip_addr.h"
#pragma GCC optimize ("O2")
/**
An optimized checksum routine. Basically, it uses loop-unrolling on
the checksum loop, treating the head and tail bytes specially, whereas
the inner loop acts on 8 bytes at a time.
@arg start of buffer to be checksummed. May be an odd byte address.
@len number of bytes in the buffer to be checksummed.
@return host order (!) lwip checksum (non-inverted Internet sum)
by Curt McDowell, Broadcom Corp. December 8th, 2005
*/
extern "C" u16_t lwip_standard_chksum(const void *dataptr, int len) {
const u8_t *pb = (const u8_t *)dataptr;
const u16_t *ps;
u16_t t = 0;
const u32_t *pl;
u32_t sum = 0, tmp;
/* starts at odd byte address? */
int odd = ((mem_ptr_t)pb & 1);
if (odd && len > 0) {
((u8_t *)&t)[1] = *pb++;
len--;
}
ps = (const u16_t *)(const void *)pb;
if (((mem_ptr_t)ps & 3) && len > 1) {
sum += *ps++;
len -= 2;
}
pl = (const u32_t *)(const void *)ps;
while (len > 7) {
tmp = sum + *pl++; /* ping */
if (tmp < sum) {
tmp++; /* add back carry */
}
sum = tmp + *pl++; /* pong */
if (sum < tmp) {
sum++; /* add back carry */
}
len -= 8;
}
/* make room in upper bits */
sum = FOLD_U32T(sum);
ps = (const u16_t *)pl;
/* 16-bit aligned word remaining? */
while (len > 1) {
sum += *ps++;
len -= 2;
}
/* dangling tail byte remaining? */
if (len > 0) { /* include odd byte */
((u8_t *)&t)[0] = *(const u8_t *)ps;
}
sum += t; /* add end bytes */
/* Fold 32-bit sum to 16 bits
calling this twice is probably faster than if statements... */
sum = FOLD_U32T(sum);
sum = FOLD_U32T(sum);
if (odd) {
sum = SWAP_BYTES_IN_WORD(sum);
}
return (u16_t)sum;
}
+2 -2
View File
@@ -40,8 +40,8 @@ For many BTStack examples, you simply need call the included
called afterwards to start processing (in the background).
You will also need to acquire the BT ``async_context`` system lock before
calling any BTStack APIs. See the ``libraries/PicoBluetoothHID`` helper
class for an example of how to do this.
calling any BTStack APIs. ``__lockBluetooth`` and ``unlockBluetooth`` are
provided in the PicoW variant code.
Note that if you need to modify the system ``btstack_config.h`` file, do so
in the ``tools/libpico`` directory and rebuild the Pico SDK static library.
+2 -2
View File
@@ -54,9 +54,9 @@ author = u'Earle F. Philhower, III'
# built documents.
#
# The short X.Y version.
version = u'3.8.0'
version = u'3.9.0'
# The full version, including alpha/beta/rc tags.
release = u'3.8.0'
release = u'3.9.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
+2 -2
View File
@@ -597,7 +597,7 @@ close
Close the file. No other operations should be performed on *File* object
after ``close`` function was called.
openNextFile (compatibiity method, not recommended for new code)
openNextFile (compatibility method, not recommended for new code)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. code:: cpp
@@ -609,7 +609,7 @@ openNextFile (compatibiity method, not recommended for new code)
Opens the next file in the directory pointed to by the File. Only valid
when ``File.isDirectory() == true``.
rewindDirectory (compatibiity method, not recommended for new code)
rewindDirectory (compatibility method, not recommended for new code)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. code:: cpp
+37 -5
View File
@@ -8,10 +8,10 @@ SPI pinouts can be set **before SPI.begin()** using the following calls:
.. code:: cpp
bool setRX(pin_size_t pin);
bool setRX(pin_size_t pin); // or setMISO()
bool setCS(pin_size_t pin);
bool setSCK(pin_size_t pin);
bool setTX(pin_size_t pin);
bool setTX(pin_size_t pin); // or setMOSI()
Note that the ``CS`` pin can be hardware or software controlled by the sketch.
When software controlled, the ``setCS()`` call is ignored.
@@ -39,7 +39,39 @@ in order to consunme the received data and provide data to transmit.
* The callbacks operate at IRQ time and may be called very frequently at high SPI frequencies. So, make then small, fast, and with no memory allocations or locking.
Examples
~~~~~~~~
Asynchronous Operation
======================
See the SPItoMyself example for a complete Master and Slave application.
Applications can use asynchronous SPI calls to allow for processing while long-running SPI transfers are
being performed. For example, a game could send a full screen update out over SPI and immediately start
processing the next frame without waiting for the first one to be sent. DMA is used to handle
the transfer to/from the hardware freeing the CPU from bit-banging or busy waiting.
Note that asynchronous operations can not be intersped with normal, synchronous ones. ``transferAsync``
should still occur after a ``beginTransaction()`` and when ``finishedAsync()`` returns ``true`` then
``endTransaction()`` should also be called.
All buffers need to be valid throughout the entire operation. Read data cannot be accessed until
the transaction is completed and can't be "peeked" at while the operation is ongoing.
bool transferAsync(const void \*send, void \*recv, size_t bytes)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Begins an SPI asynchronous transaction. Either ``send`` or ``recv`` can be ``nullptr`` if data only needs
to be transferred in one direction.
Check ``finishedAsync()`` to determine when the operation completes and conclude the transaction.
This operation needs to allocate a buffer from heap equal to ``bytes`` in size if ``LSBMODE`` is used.
bool finishedAsync()
~~~~~~~~~~~~~~~~~~~~
Call to check if the asynchronous operations is completed and the buffer passed in can be either read or
reused. Frees the allocated memory and completes the asynchronous transaction.
void abortAsync()
~~~~~~~~~~~~~~~~~
Cancels the outstanding asynchronous transaction and frees any allocated memory.
Examples
========
See the SPItoMyself and SPItoMyselfAsync examples for a complete Master and Slave application.
+38
View File
@@ -24,3 +24,41 @@ Master transmissions are buffered (up to 256 bytes) and only performed
on ``endTransmission``, as is standard with modern Arduino Wire implementations.
For more detailed information, check the `Arduino Wire documentation <https://www.arduino.cc/en/reference/wire>`_ .
Asynchronous Operation
----------------------
Applications can use asynchronous I2C calls to allow for processing while long-running I2C operations are
being performed. For example, a game could send a full screen update out over I2C and immediately start
processing the next frame without waiting for the first one to be sent over I2C. DMA is used to handle
the transfer to/from the I2C hardware freeing the CPU from bit-banging or busy waiting.
Note that asynchronous operations can not be intersped with normal, synchronous ones. Fully complete an
asynchronous operation before attempting to do a normal ``Wire.beginTransaction()`` or ``Wire.requestFrom``.
Also, all buffers need to be valid throughout the entire operation. Read data cannot be accessed until
the transaction is completed and can't be "peeked" at while the operation is ongoing.
bool writeAsync(uint8_t address, const void \*buffer, size_t bytes, bool sendStop)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Begins an I2C asynchronous write transaction. Writes to ``address`` of ``bytes`` from ``buffer`` and
at the end will send an I2C stop if ``sendStop`` is ``true``.
Check ``finishedAsync()`` to determine when the operation completes and conclude the transaction.
This operation needs to allocate a buffer from heap equal to 2x ``bytes`` in size.
bool readAsync(uint8_t address, void \*buffer, size_t bytes, bool sendStop)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Begins an I2C asynchronous read transaction. Reads from ``address`` for ``bytes`` into ``buffer`` and
at the end will send an I2C stop if ``sendStop`` is ``true``.
Check ``finishedAsync()`` to determine when the operation completes and conclude the transaction.
This operation needs to allocate a buffer from heap equal to 4x ``bytes`` in size.
bool finishedAsync()
~~~~~~~~~~~~~~~~~~~~
Call to check if the asynchronous operations is completed and the buffer passed in can be either read or
reused. Frees the allocated memory and completes the asynchronous transaction.
void abortAsync()
~~~~~~~~~~~~~~~~~
Cancels the outstanding asynchronous transaction and frees any allocated memory.
+7 -10
View File
@@ -1,11 +1,9 @@
#ifndef _LWIPOPTS_EXAMPLE_COMMONH_H
#define _LWIPOPTS_EXAMPLE_COMMONH_H
#pragma once
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
// Critical section protection
extern void noInterrupts();
extern void interrupts();
@@ -40,12 +38,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 0
#define SYS_STATS 0
#define MEMP_STATS 0
#define MEM_STATS 1
#define SYS_STATS 1
#define MEMP_STATS 1
#define LINK_STATS 0
// #define ETH_PAD_SIZE 2
#define LWIP_CHKSUM_ALGORITHM 3
#define LWIP_CHKSUM_ALGORITHM 0
#define LWIP_DHCP 1
#define LWIP_IPV4 1
#define LWIP_TCP 1
@@ -74,6 +72,8 @@ extern void __setSystemTime(unsigned long long sec, unsigned long us);
#define LWIP_DEBUG 1
#define LWIP_STATS 1
#define LWIP_STATS_DISPLAY 1
#define MEMP_STATS 1
#define MEM_STATS 1
#endif
#define ETHARP_DEBUG LWIP_DBG_OFF
@@ -108,6 +108,3 @@ extern void __setSystemTime(unsigned long long sec, unsigned long us);
#ifdef __cplusplus
}
#endif // __cplusplus
#endif /* __LWIPOPTS_H__ */
+3
View File
@@ -3,6 +3,7 @@
#######################################
Arduino KEYWORD3 RESERVED_WORD
defined KEYWORD3 RESERVED_WORD
#######################################
# Datatypes (KEYWORD1)
@@ -89,3 +90,5 @@ OUTPUT_2MA LITERAL1
OUTPUT_4MA LITERAL1
OUTPUT_8MA LITERAL1
OUTPUT_12MA LITERAL1
ARDUINO_ARCH_RP2040 LITERAL1
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+3
View File
@@ -203,6 +203,9 @@
-Wl,--wrap=raw_sendto
-Wl,--wrap=raw_remove
-Wl,--wrap=netif_add
-Wl,--wrap=netif_remove
-Wl,--wrap=cyw43_cb_process_ethernet
-Wl,--wrap=cyw43_cb_tcpip_set_link_up
-Wl,--wrap=cyw43_cb_tcpip_set_link_down
+3 -3
View File
@@ -808,9 +808,6 @@ void BTstackManager::setup(const char * name) {
hci_add_event_handler(&hci_event_callback_registration);
l2cap_init();
// setup central device db
le_device_db_init();
sm_init();
att_server_init(att_db_util_get_address(), att_read_callback, att_write_callback);
@@ -889,6 +886,9 @@ uint16_t BTstackManager::addGATTCharacteristicDynamic(UUID * uuid, uint16_t flag
void BTstackManager::setAdvData(uint16_t adv_data_len, const uint8_t * adv_data) {
gap_advertisements_set_data(adv_data_len, (uint8_t*) adv_data);
}
void BTstackManager::setScanData(uint16_t scan_data_len, const uint8_t * scan_data) {
gap_scan_response_set_data(scan_data_len, (uint8_t*) scan_data);
}
void BTstackManager::startAdvertising() {
gap_advertisements_enable(1);
}
+1
View File
@@ -143,6 +143,7 @@ extern "C" {
void enableDebugLogger();
void setAdvData(uint16_t size, const uint8_t * data);
void setScanData(uint16_t size, const uint8_t * data);
void iBeaconConfigure(UUID * uuid, uint16_t major_id, uint16_t minor_id, uint8_t measured_power = 0xc6);
void startAdvertising();
void stopAdvertising();
@@ -0,0 +1,59 @@
// A2DPSink example - Released to the public domain in 2024 by Earle F. Philhower, III
// Hook up a phono plug to GP0 and GP1 (and GND of course...the 1st 3 pins on the PCB)
// Connect wired earbuds up and connect over BT from your phone and play some music.
#include <BluetoothAudio.h>
#include <PWMAudio.h>
PWMAudio pwm;
A2DPSink a2dp;
volatile A2DPSink::PlaybackStatus status = A2DPSink::STOPPED;
void volumeCB(void *param, int pct) {
(void) param;
Serial.printf("Speaker volume changed to %d%%\n", pct);
}
void connectCB(void *param, bool connected) {
(void) param;
if (connected) {
Serial.printf("A2DP connection started to %s\n", bd_addr_to_str(a2dp.getSourceAddress()));
} else {
Serial.printf("A2DP connection stopped\n");
}
}
void playbackCB(void *param, A2DPSink::PlaybackStatus state) {
(void) param;
status = state;
}
void setup() {
Serial.begin(115200);
delay(3000);
Serial.printf("Starting, connect to the PicoW and start playing music\n");
Serial.printf("Use BOOTSEL to pause/resume playback\n");
a2dp.setName("PicoW Boom 00:00:00:00:00:00");
a2dp.setConsumer(new BluetoothAudioConsumerPWM(pwm));
a2dp.onVolume(volumeCB);
a2dp.onConnect(connectCB);
a2dp.onPlaybackStatus(playbackCB);
a2dp.begin();
}
void loop() {
if (BOOTSEL) {
__lockBluetooth();
if (status == A2DPSink::PAUSED) {
a2dp.play();
Serial.printf("Resuming\n");
} else if (status == A2DPSink::PLAYING) {
a2dp.pause();
Serial.printf("Pausing\n");
}
__unlockBluetooth();
while (BOOTSEL);
}
}
@@ -0,0 +1,100 @@
// Plays tones and Au Claire De La Lune over an A2DP connection
// Released to the public domain by Earle Philhower <earlephilhowwer@yahoo.com>
#include <BluetoothAudio.h>
#include "raw.h"
A2DPSource a2dp;
int16_t pcm[64 * 2];
uint32_t phase = 0;
volatile uint32_t fr = 32;
volatile uint32_t fl = 16;
volatile bool paused = false;
volatile bool playwav = false;
void avrcpCB(void *param, avrcp_operation_id_t op, int pressed) {
(void) param;
if (pressed && op == AVRCP_OPERATION_ID_FORWARD) {
// Change the sound when they hit play
fr = random(8, 64);
fl = random(8, 64);
Serial.printf("Now generating %lu, %lu\n", fr, fl);
} else if (pressed && op == AVRCP_OPERATION_ID_PLAY) {
paused = !paused;
if (paused) {
Serial.printf("Pausing\n");
} else {
Serial.printf("Resuming\n");
}
} else if (pressed && op == AVRCP_OPERATION_ID_BACKWARD) {
playwav = !playwav;
Serial.println(playwav ? "Playing 'Au Claire De La Lune'" : "Playing tones");
}
}
void volumeCB(void *param, int pct) {
(void) param;
Serial.printf("Speaker volume changed to %d%%\n", pct);
}
void connectCB(void *param, bool connected) {
(void) param;
if (connected) {
Serial.printf("A2DP connection started to %s\n", bd_addr_to_str(a2dp.getSinkAddress()));
} else {
Serial.printf("A2DP connection stopped\n");
}
}
void fillPCM() {
if (paused) {
bzero(pcm, sizeof(pcm));
return;
}
if (playwav) {
for (int i = 0; i < 64; i++) {
// Audio in flash is 8-bit signed mono, so shift left to make 16-bit and then play over both channels
pcm[i * 2] = auclairedelalune_raw[(i + phase) % sizeof(auclairedelalune_raw)] << 8;
pcm[i * 2 + 1] = auclairedelalune_raw[(i + phase) % sizeof(auclairedelalune_raw)] << 8;
}
} else {
for (int i = 0; i < 64; i++) {
pcm[i * 2] = ((i + phase) / fr) & 1 ? 3000 : -3000;
pcm[i * 2 + 1] = ((i + phase) / fl) & 1 ? 1000 : -1000;
}
}
phase += 64;
}
void setup() {
delay(2000);
a2dp.onAVRCP(avrcpCB);
a2dp.onVolume(volumeCB);
a2dp.onConnect(connectCB);
a2dp.begin();
Serial.printf("Starting, press BOOTSEL to pair to first found speaker\n");
Serial.printf("Use the forward button on speaker to change tones\n");
Serial.printf("Use the reverse button on speaker to alternate between tones and Au Claire De La Lune\n");
Serial.printf("Use the play button on speaker to pause/unpause the tone\n");
}
void loop() {
while ((size_t)a2dp.availableForWrite() > sizeof(pcm)) {
fillPCM();
a2dp.write((const uint8_t *)pcm, sizeof(pcm));
}
if (BOOTSEL) {
while (BOOTSEL) {
delay(1);
}
a2dp.disconnect();
a2dp.clearPairing();
Serial.printf("Connecting...");
if (a2dp.connect()) {
Serial.printf("Connected!\n");
} else {
Serial.printf("Failed! :(\n");
}
}
}
File diff suppressed because it is too large Load Diff
+67
View File
@@ -0,0 +1,67 @@
#######################################
# Syntax Coloring Map
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
BluetoothAudio KEYWORD1
BluetoothHCI KEYWORD1
A2DPSource KEYWORD1
BTDeviceInfo KEYWORD1
BluetoothAudioConsumer KEYWORD1
BluetoothAudioConsumerI2S KEYWORD1
BluetoothAudioConsumerPWM KEYWORD1
A2DPSink KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
begin KEYWORD2
end KEYWORD2
setConsumer KEYWORD2
setFrequency KEYWORD2
setName KEYWORD2
setsetBufferSize KEYWORD2
getUnderflow KEYWORD2
getSinkAddress KEYWORD2
scan KEYWORD2
connect KEYWORD2
connected KEYWORD2
disconnect KEYWORD2
clearPairing KEYWORD2
connect KEYWORD2
play KEYWORD2
stop KEYWORD2
pause KEYWORD2
fastForward KEYWORD2
rewind KEYWORD2
forward KEYWORD2
backward KEYWORD2
volumeUp KEYWORD2
volumeDown KEYWORD2
mute KEYWORD2
onTransmit KEYWORD2
onAVRCP KEYWORD2
onBattery KEYWORD2
onVolume KEYWORD2
onConnect KEYWORD2
onPlaybackStatus KEYWORD2
# BTDeviceInfo
deviceClass KEYWORD2
address KEYWORD2
addressString KEYWORD2
rssi KEYWORD2
name KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################
STOPPED LITERAL
PLAYING LITERAL
PAUSED LITERAL
@@ -0,0 +1,10 @@
name=BluetoothAudio
version=1.0
author=Earle F. Philhower, III <earlephilhower@yahoo.com>
maintainer=Earle F. Philhower, III <earlephilhower@yahoo.com>
sentence=Plays and receives audio over Bluetooth A2DP
paragraph=Plays and receives audio over Bluetooth A2DP
category=Communication
url=http://github.com/earlephilhower/arduino-pico
architectures=rp2040
dot_a_linkage=true
+800
View File
@@ -0,0 +1,800 @@
/*
A2DP Sink (Bluetooth audio receiver)
Copyright (c) 2024 Earle F. Philhower, III <earlephilhower@yahoo.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "A2DPSink.h"
#include <functional>
#define CCALLBACKNAME _A2DPSINKCB
#include <ctocppcallback.h>
#define PACKETHANDLERCB(class, cbFcn) \
(CCALLBACKNAME<void(uint8_t, uint16_t, uint8_t*, uint16_t), __COUNTER__>::func = std::bind(&class::cbFcn, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4), \
static_cast<btstack_packet_handler_t>(CCALLBACKNAME<void(uint8_t, uint16_t, uint8_t*, uint16_t), __COUNTER__ - 1>::callback))
#define L2CAPPACKETHANDLERCB(class, cbFcn) \
(CCALLBACKNAME<void(uint8_t, uint8_t*, uint16_t), __COUNTER__>::func = std::bind(&class::cbFcn, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3), \
static_cast<void (*)(uint8_t, uint8_t *, uint16_t)>(CCALLBACKNAME<void(uint8_t, uint8_t*, uint16_t), __COUNTER__ - 1>::callback))
#define PCMDECODERCB(class, cbFcn) \
(CCALLBACKNAME<void(int16_t*, int, int, int, void*), __COUNTER__>::func = std::bind(&class::cbFcn, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5), \
static_cast<void (*)(int16_t *, int, int, int, void *)>(CCALLBACKNAME<void(int16_t *, int, int, int, void *), __COUNTER__ - 1>::callback))
// Based off of the BlueKitchen A2DP sink demo
/*
Copyright (C) 2023 BlueKitchen GmbH
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the names of
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
4. Any redistribution, use, or modification is done solely for
personal benefit and not for any commercial purpose or for
monetary gain.
THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN
GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
Please inquire about commercial licensing options at
contact@bluekitchen-gmbh.com
*/
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "btstack.h"
#include "btstack_resample.h"
#include "btstack_ring_buffer.h"
bool A2DPSink::begin() {
if (_running || !_consumer) {
return false;
}
// init protocols
l2cap_init();
sdp_init();
#ifdef ENABLE_BLE
// Initialize LE Security Manager. Needed for cross-transport key derivation
sm_init();
#endif
// Init profiles
a2dp_sink_init();
avrcp_init();
avrcp_controller_init();
avrcp_target_init();
// Configure A2DP Sink
a2dp_sink_register_packet_handler(PACKETHANDLERCB(A2DPSink, a2dp_sink_packet_handler));
a2dp_sink_register_media_handler(L2CAPPACKETHANDLERCB(A2DPSink, handle_l2cap_media_data_packet));
a2dp_sink_stream_endpoint_t * stream_endpoint = &a2dp_sink_stream_endpoint;
avdtp_stream_endpoint_t * local_stream_endpoint = a2dp_sink_create_stream_endpoint(AVDTP_AUDIO,
AVDTP_CODEC_SBC, media_sbc_codec_capabilities, sizeof(media_sbc_codec_capabilities),
stream_endpoint->media_sbc_codec_configuration, sizeof(stream_endpoint->media_sbc_codec_configuration));
if (!local_stream_endpoint) {
DEBUGV("A2DP Source: not enough memory to create local stream endpoint\n");
return false;
}
// - Store stream enpoint's SEP ID, as it is used by A2DP API to identify the stream endpoint
stream_endpoint->a2dp_local_seid = avdtp_local_seid(local_stream_endpoint);
// Configure AVRCP Controller + Target
avrcp_register_packet_handler(PACKETHANDLERCB(A2DPSink, avrcp_packet_handler));
avrcp_controller_register_packet_handler(PACKETHANDLERCB(A2DPSink, avrcp_controller_packet_handler));
avrcp_target_register_packet_handler(PACKETHANDLERCB(A2DPSink, avrcp_target_packet_handler));
// Configure SDP
// - Create and register A2DP Sink service record
memset(sdp_avdtp_sink_service_buffer, 0, sizeof(sdp_avdtp_sink_service_buffer));
a2dp_sink_create_sdp_record(sdp_avdtp_sink_service_buffer, sdp_create_service_record_handle(),
AVDTP_SINK_FEATURE_MASK_HEADPHONE, NULL, NULL);
sdp_register_service(sdp_avdtp_sink_service_buffer);
// - Create AVRCP Controller service record and register it with SDP. We send Category 1 commands to the media player, e.g. play/pause
memset(sdp_avrcp_controller_service_buffer, 0, sizeof(sdp_avrcp_controller_service_buffer));
uint16_t controller_supported_features = 1 << AVRCP_CONTROLLER_SUPPORTED_FEATURE_CATEGORY_PLAYER_OR_RECORDER;
avrcp_controller_create_sdp_record(sdp_avrcp_controller_service_buffer, sdp_create_service_record_handle(),
controller_supported_features, NULL, NULL);
sdp_register_service(sdp_avrcp_controller_service_buffer);
// - Create and register A2DP Sink service record
// - We receive Category 2 commands from the media player, e.g. volume up/down
memset(sdp_avrcp_target_service_buffer, 0, sizeof(sdp_avrcp_target_service_buffer));
uint16_t target_supported_features = 1 << AVRCP_TARGET_SUPPORTED_FEATURE_CATEGORY_MONITOR_OR_AMPLIFIER;
avrcp_target_create_sdp_record(sdp_avrcp_target_service_buffer,
sdp_create_service_record_handle(), target_supported_features, NULL, NULL);
sdp_register_service(sdp_avrcp_target_service_buffer);
// - Create and register Device ID (PnP) service record
memset(device_id_sdp_service_buffer, 0, sizeof(device_id_sdp_service_buffer));
device_id_create_sdp_record(device_id_sdp_service_buffer,
sdp_create_service_record_handle(), DEVICE_ID_VENDOR_ID_SOURCE_BLUETOOTH, BLUETOOTH_COMPANY_ID_BLUEKITCHEN_GMBH, 1, 1);
sdp_register_service(device_id_sdp_service_buffer);
// Configure GAP - discovery / connection
// - Set local name with a template Bluetooth address, that will be automatically
// replaced with an actual address once it is available, i.e. when BTstack boots
// up and starts talking to a Bluetooth module.
if (!_name) {
setName("PicoW A2DP 00:00:00:00:00:00");
}
gap_set_local_name(_name);
// - Allow to show up in Bluetooth inquiry
gap_discoverable_control(1);
// - Set Class of Device - Service Class: Audio, Major Device Class: Audio, Minor: Loudspeaker
gap_set_class_of_device(0x200414);
// - Allow for role switch in general and sniff mode
gap_set_default_link_policy_settings(LM_LINK_POLICY_ENABLE_ROLE_SWITCH | LM_LINK_POLICY_ENABLE_SNIFF_MODE);
// - Allow for role switch on outgoing connections
// - This allows A2DP Source, e.g. smartphone, to become master when we re-connect to it.
gap_set_allow_role_switch(true);
// Register for HCI events
// hci_event_callback_registration.callback = &hci_packet_handler;
// hci_add_event_handler(&hci_event_callback_registration);
_hci.install();
_running = true;
_hci.begin();
return true;
}
bool A2DPSink::disconnect() {
__lockBluetooth();
a2dp_sink_disconnect(a2dp_sink_a2dp_connection.a2dp_cid);
__unlockBluetooth();
if (!_running || !_connected) {
return false;
}
_connected = false;
return true;
}
void A2DPSink::clearPairing() {
disconnect();
__lockBluetooth();
gap_delete_all_link_keys();
__unlockBluetooth();
}
void A2DPSink::playback_handler(int16_t * buffer, uint16_t num_audio_frames) {
// called from lower-layer but guaranteed to be on main thread
if (sbc_frame_size == 0) {
memset(buffer, 0, num_audio_frames * BYTES_PER_FRAME);
return;
}
// first fill from resampled audio
uint32_t bytes_read;
btstack_ring_buffer_read(&decoded_audio_ring_buffer, (uint8_t *) buffer, num_audio_frames * BYTES_PER_FRAME, &bytes_read);
buffer += bytes_read / NUM_CHANNELS;
num_audio_frames -= bytes_read / BYTES_PER_FRAME;
// then start decoding sbc frames using request_* globals
request_buffer = buffer;
request_frames = num_audio_frames;
while (request_frames && btstack_ring_buffer_bytes_available(&sbc_frame_ring_buffer) >= sbc_frame_size) {
// decode frame
uint8_t sbc_frame[MAX_SBC_FRAME_SIZE];
btstack_ring_buffer_read(&sbc_frame_ring_buffer, sbc_frame, sbc_frame_size, &bytes_read);
btstack_sbc_decoder_process_data(&state, 0, sbc_frame, sbc_frame_size);
}
while (request_frames) {
*(request_buffer++) = 0;
*(request_buffer++) = 0;
request_frames--;
}
}
void A2DPSink::handle_pcm_data(int16_t * data, int num_audio_frames, int num_channels, int sample_rate, void * context) {
UNUSED(sample_rate);
UNUSED(context);
UNUSED(num_channels); // must be stereo == 2
// resample into request buffer - add some additional space for resampling
uint32_t resampled_frames = btstack_resample_block(&resample_instance, data, num_audio_frames, output_buffer);
// store data in btstack_audio buffer first
int frames_to_copy = btstack_min(resampled_frames, request_frames);
memcpy(request_buffer, output_buffer, frames_to_copy * BYTES_PER_FRAME);
request_frames -= frames_to_copy;
request_buffer += frames_to_copy * NUM_CHANNELS;
// and rest in ring buffer
int frames_to_store = resampled_frames - frames_to_copy;
if (frames_to_store) {
int status = btstack_ring_buffer_write(&decoded_audio_ring_buffer, (uint8_t *)&output_buffer[frames_to_copy * NUM_CHANNELS], frames_to_store * BYTES_PER_FRAME);
if (status) {
DEBUGV("Error storing samples in PCM ring buffer!!!\n");
}
}
}
int A2DPSink::media_processing_init(BluetoothMediaCodecConfigurationSBC * configuration) {
if (media_initialized) {
return 0;
}
btstack_sbc_decoder_init(&state, mode, PCMDECODERCB(A2DPSink, handle_pcm_data), NULL);
btstack_ring_buffer_init(&sbc_frame_ring_buffer, sbc_frame_storage, sizeof(sbc_frame_storage));
btstack_ring_buffer_init(&decoded_audio_ring_buffer, decoded_audio_storage, sizeof(decoded_audio_storage));
btstack_resample_init(&resample_instance, configuration->num_channels);
// setup audio playback
_consumer->init(NUM_CHANNELS, configuration->sampling_frequency, this);
audio_stream_started = 0;
media_initialized = 1;
return 0;
}
void A2DPSink::media_processing_start(void) {
if (!media_initialized) {
return;
}
// setup audio playback
_consumer->startStream();
audio_stream_started = 1;
}
void A2DPSink::media_processing_pause(void) {
if (!media_initialized) {
return;
}
// stop audio playback
audio_stream_started = 0;
_consumer->stopStream();
// discard pending data
btstack_ring_buffer_reset(&decoded_audio_ring_buffer);
btstack_ring_buffer_reset(&sbc_frame_ring_buffer);
}
void A2DPSink::media_processing_close(void) {
if (!media_initialized) {
return;
}
media_initialized = 0;
audio_stream_started = 0;
sbc_frame_size = 0;
// stop audio playback
_consumer->close();
}
/* @section Handle Media Data Packet
@text Here the audio data, are received through the handle_l2cap_media_data_packet callback.
Currently, only the SBC media codec is supported. Hence, the media data consists of the media packet header and the SBC packet.
The SBC frame will be stored in a ring buffer for later processing (instead of decoding it to PCM right away which would require a much larger buffer).
If the audio stream wasn't started already and there are enough SBC frames in the ring buffer, start playback.
*/
void A2DPSink::handle_l2cap_media_data_packet(uint8_t seid, uint8_t *packet, uint16_t size) {
UNUSED(seid);
int pos = 0;
avdtp_media_packet_header_t media_header;
if (!read_media_data_header(packet, size, &pos, &media_header)) {
return;
}
avdtp_sbc_codec_header_t sbc_header;
if (!read_sbc_header(packet, size, &pos, &sbc_header)) {
return;
}
int packet_length = size - pos;
uint8_t *packet_begin = packet + pos;
// store sbc frame size for buffer management
sbc_frame_size = packet_length / sbc_header.num_frames;
int status = btstack_ring_buffer_write(&sbc_frame_ring_buffer, packet_begin, packet_length);
if (status != ERROR_CODE_SUCCESS) {
DEBUGV("Error storing samples in SBC ring buffer!!!\n");
}
// decide on audio sync drift based on number of sbc frames in queue
int sbc_frames_in_buffer = btstack_ring_buffer_bytes_available(&sbc_frame_ring_buffer) / sbc_frame_size;
uint32_t resampling_factor;
// nominal factor (fixed-point 2^16) and compensation offset
uint32_t nominal_factor = 0x10000;
uint32_t compensation = 0x00100;
if (sbc_frames_in_buffer < OPTIMAL_FRAMES_MIN) {
resampling_factor = nominal_factor - compensation; // stretch samples
} else if (sbc_frames_in_buffer <= OPTIMAL_FRAMES_MAX) {
resampling_factor = nominal_factor; // nothing to do
} else {
resampling_factor = nominal_factor + compensation; // compress samples
}
btstack_resample_set_factor(&resample_instance, resampling_factor);
// start stream if enough frames buffered
if (!audio_stream_started && sbc_frames_in_buffer >= OPTIMAL_FRAMES_MIN) {
media_processing_start();
}
}
int A2DPSink::read_sbc_header(uint8_t * packet, int size, int * offset, avdtp_sbc_codec_header_t * sbc_header) {
int sbc_header_len = 12; // without crc
int pos = *offset;
if (size - pos < sbc_header_len) {
DEBUGV("Not enough data to read SBC header, expected %d, received %d\n", sbc_header_len, size - pos);
return 0;
}
sbc_header->fragmentation = get_bit16(packet[pos], 7);
sbc_header->starting_packet = get_bit16(packet[pos], 6);
sbc_header->last_packet = get_bit16(packet[pos], 5);
sbc_header->num_frames = packet[pos] & 0x0f;
pos++;
*offset = pos;
return 1;
}
int A2DPSink::read_media_data_header(uint8_t *packet, int size, int *offset, avdtp_media_packet_header_t *media_header) {
int media_header_len = 12; // without crc
int pos = *offset;
if (size - pos < media_header_len) {
DEBUGV("Not enough data to read media packet header, expected %d, received %d\n", media_header_len, size - pos);
return 0;
}
media_header->version = packet[pos] & 0x03;
media_header->padding = get_bit16(packet[pos], 2);
media_header->extension = get_bit16(packet[pos], 3);
media_header->csrc_count = (packet[pos] >> 4) & 0x0F;
pos++;
media_header->marker = get_bit16(packet[pos], 0);
media_header->payload_type = (packet[pos] >> 1) & 0x7F;
pos++;
media_header->sequence_number = big_endian_read_16(packet, pos);
pos += 2;
media_header->timestamp = big_endian_read_32(packet, pos);
pos += 4;
media_header->synchronization_source = big_endian_read_32(packet, pos);
pos += 4;
*offset = pos;
return 1;
}
void A2DPSink::avrcp_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
UNUSED(channel);
UNUSED(size);
uint16_t local_cid;
uint8_t status;
bd_addr_t address;
a2dp_sink_avrcp_connection_t * connection = &a2dp_sink_avrcp_connection;
if (packet_type != HCI_EVENT_PACKET) {
return;
}
if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) {
return;
}
switch (packet[2]) {
case AVRCP_SUBEVENT_CONNECTION_ESTABLISHED: {
local_cid = avrcp_subevent_connection_established_get_avrcp_cid(packet);
status = avrcp_subevent_connection_established_get_status(packet);
if (status != ERROR_CODE_SUCCESS) {
DEBUGV("AVRCP: Connection failed, status 0x%02x\n", status);
connection->avrcp_cid = 0;
return;
}
connection->avrcp_cid = local_cid;
avrcp_subevent_connection_established_get_bd_addr(packet, address);
DEBUGV("AVRCP: Connected to %s, cid 0x%02x\n", bd_addr_to_str(address), connection->avrcp_cid);
avrcp_target_support_event(connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_VOLUME_CHANGED);
avrcp_target_support_event(connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_BATT_STATUS_CHANGED);
avrcp_target_battery_status_changed(connection->avrcp_cid, battery_status);
// query supported events:
avrcp_controller_get_supported_events(connection->avrcp_cid);
return;
}
case AVRCP_SUBEVENT_CONNECTION_RELEASED:
DEBUGV("AVRCP: Channel released: cid 0x%02x\n", avrcp_subevent_connection_released_get_avrcp_cid(packet));
connection->avrcp_cid = 0;
connection->notifications_supported_by_target = 0;
return;
default:
break;
}
}
void A2DPSink::avrcp_controller_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
UNUSED(channel);
UNUSED(size);
// helper to print c strings
uint8_t avrcp_subevent_value[256];
uint8_t play_status;
uint8_t event_id;
a2dp_sink_avrcp_connection_t * avrcp_connection = &a2dp_sink_avrcp_connection;
if (packet_type != HCI_EVENT_PACKET) {
return;
}
if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) {
return;
}
if (avrcp_connection->avrcp_cid == 0) {
return;
}
memset(avrcp_subevent_value, 0, sizeof(avrcp_subevent_value));
switch (packet[2]) {
case AVRCP_SUBEVENT_GET_CAPABILITY_EVENT_ID:
avrcp_connection->notifications_supported_by_target |= (1 << avrcp_subevent_get_capability_event_id_get_event_id(packet));
break;
case AVRCP_SUBEVENT_GET_CAPABILITY_EVENT_ID_DONE:
DEBUGV("AVRCP Controller: supported notifications by target:\n");
for (event_id = (uint8_t) AVRCP_NOTIFICATION_EVENT_FIRST_INDEX; event_id < (uint8_t) AVRCP_NOTIFICATION_EVENT_LAST_INDEX; event_id++) {
DEBUGV(" - [%s] %s\n",
(avrcp_connection->notifications_supported_by_target & (1 << event_id)) != 0 ? "X" : " ",
avrcp_notification2str((avrcp_notification_event_id_t)event_id));
}
DEBUGV("\n\n");
// automatically enable notifications
avrcp_controller_enable_notification(avrcp_connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_PLAYBACK_STATUS_CHANGED);
avrcp_controller_enable_notification(avrcp_connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_NOW_PLAYING_CONTENT_CHANGED);
avrcp_controller_enable_notification(avrcp_connection->avrcp_cid, AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED);
break;
case AVRCP_SUBEVENT_NOTIFICATION_STATE:
event_id = (avrcp_notification_event_id_t)avrcp_subevent_notification_state_get_event_id(packet);
DEBUGV("AVRCP Controller: %s notification registered\n", avrcp_notification2str((avrcp_notification_event_id_t)event_id));
break;
case AVRCP_SUBEVENT_NOTIFICATION_PLAYBACK_POS_CHANGED:
DEBUGV("AVRCP Controller: Playback position changed, position %d ms\n", (unsigned int) avrcp_subevent_notification_playback_pos_changed_get_playback_position_ms(packet));
break;
case AVRCP_SUBEVENT_NOTIFICATION_PLAYBACK_STATUS_CHANGED:
DEBUGV("AVRCP Controller: Playback status changed %s\n", avrcp_play_status2str(avrcp_subevent_notification_playback_status_changed_get_play_status(packet)));
play_status = avrcp_subevent_notification_playback_status_changed_get_play_status(packet);
switch (play_status) {
case AVRCP_PLAYBACK_STATUS_PLAYING:
avrcp_connection->playing = true;
break;
default:
avrcp_connection->playing = false;
break;
}
if (_playbackStatusCB) {
PlaybackStatus status;
switch (play_status) {
case AVRCP_PLAYBACK_STATUS_PLAYING:
status = PLAYING;
break;
case AVRCP_PLAYBACK_STATUS_PAUSED:
status = PAUSED;
break;
default:
status = STOPPED;
break;
}
_playbackStatusCB(_playbackStatusData, status);
}
break;
case AVRCP_SUBEVENT_NOTIFICATION_NOW_PLAYING_CONTENT_CHANGED:
DEBUGV("AVRCP Controller: Playing content changed\n");
break;
case AVRCP_SUBEVENT_NOTIFICATION_TRACK_CHANGED:
DEBUGV("AVRCP Controller: Track changed\n");
break;
case AVRCP_SUBEVENT_NOTIFICATION_AVAILABLE_PLAYERS_CHANGED:
DEBUGV("AVRCP Controller: Available Players Changed\n");
break;
case AVRCP_SUBEVENT_SHUFFLE_AND_REPEAT_MODE: {
uint8_t shuffle_mode = avrcp_subevent_shuffle_and_repeat_mode_get_shuffle_mode(packet);
uint8_t repeat_mode = avrcp_subevent_shuffle_and_repeat_mode_get_repeat_mode(packet);
(void) shuffle_mode;
(void) repeat_mode;
DEBUGV("AVRCP Controller: %s, %s\n", avrcp_shuffle2str(shuffle_mode), avrcp_repeat2str(repeat_mode));
break;
}
case AVRCP_SUBEVENT_NOW_PLAYING_TRACK_INFO:
DEBUGV("AVRCP Controller: Track %d\n", avrcp_subevent_now_playing_track_info_get_track(packet));
break;
case AVRCP_SUBEVENT_NOW_PLAYING_TOTAL_TRACKS_INFO:
DEBUGV("AVRCP Controller: Total Tracks %d\n", avrcp_subevent_now_playing_total_tracks_info_get_total_tracks(packet));
break;
case AVRCP_SUBEVENT_NOW_PLAYING_TITLE_INFO:
if (avrcp_subevent_now_playing_title_info_get_value_len(packet) > 0) {
memcpy(avrcp_subevent_value, avrcp_subevent_now_playing_title_info_get_value(packet), avrcp_subevent_now_playing_title_info_get_value_len(packet));
DEBUGV("AVRCP Controller: Title %s\n", avrcp_subevent_value);
}
break;
case AVRCP_SUBEVENT_NOW_PLAYING_ARTIST_INFO:
if (avrcp_subevent_now_playing_artist_info_get_value_len(packet) > 0) {
memcpy(avrcp_subevent_value, avrcp_subevent_now_playing_artist_info_get_value(packet), avrcp_subevent_now_playing_artist_info_get_value_len(packet));
DEBUGV("AVRCP Controller: Artist %s\n", avrcp_subevent_value);
}
break;
case AVRCP_SUBEVENT_NOW_PLAYING_ALBUM_INFO:
if (avrcp_subevent_now_playing_album_info_get_value_len(packet) > 0) {
memcpy(avrcp_subevent_value, avrcp_subevent_now_playing_album_info_get_value(packet), avrcp_subevent_now_playing_album_info_get_value_len(packet));
DEBUGV("AVRCP Controller: Album %s\n", avrcp_subevent_value);
}
break;
case AVRCP_SUBEVENT_NOW_PLAYING_GENRE_INFO:
if (avrcp_subevent_now_playing_genre_info_get_value_len(packet) > 0) {
memcpy(avrcp_subevent_value, avrcp_subevent_now_playing_genre_info_get_value(packet), avrcp_subevent_now_playing_genre_info_get_value_len(packet));
DEBUGV("AVRCP Controller: Genre %s\n", avrcp_subevent_value);
}
break;
case AVRCP_SUBEVENT_PLAY_STATUS:
DEBUGV("AVRCP Controller: Song length %" PRIu32 " ms, Song position %" PRIu32 " ms, Play status %s\n",
avrcp_subevent_play_status_get_song_length(packet),
avrcp_subevent_play_status_get_song_position(packet),
avrcp_play_status2str(avrcp_subevent_play_status_get_play_status(packet)));
break;
case AVRCP_SUBEVENT_OPERATION_COMPLETE:
DEBUGV("AVRCP Controller: %s complete\n", avrcp_operation2str(avrcp_subevent_operation_complete_get_operation_id(packet)));
break;
case AVRCP_SUBEVENT_OPERATION_START:
DEBUGV("AVRCP Controller: %s start\n", avrcp_operation2str(avrcp_subevent_operation_start_get_operation_id(packet)));
break;
case AVRCP_SUBEVENT_NOTIFICATION_EVENT_TRACK_REACHED_END:
DEBUGV("AVRCP Controller: Track reached end\n");
break;
case AVRCP_SUBEVENT_PLAYER_APPLICATION_VALUE_RESPONSE:
DEBUGV("AVRCP Controller: Set Player App Value %s\n", avrcp_ctype2str(avrcp_subevent_player_application_value_response_get_command_type(packet)));
break;
default:
break;
}
}
void A2DPSink::avrcp_target_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
UNUSED(channel);
UNUSED(size);
if (packet_type != HCI_EVENT_PACKET) {
return;
}
if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) {
return;
}
uint8_t volume;
char const * button_state;
(void) button_state;
avrcp_operation_id_t operation_id;
switch (packet[2]) {
case AVRCP_SUBEVENT_NOTIFICATION_VOLUME_CHANGED:
volume = avrcp_subevent_notification_volume_changed_get_absolute_volume(packet);
volume_percentage = volume * 100 / 127;
DEBUGV("AVRCP Target : Volume set to %d%% (%d)\n", volume_percentage, volume);
_consumer->setVolume(volume);
break;
case AVRCP_SUBEVENT_OPERATION:
operation_id = (avrcp_operation_id_t)avrcp_subevent_operation_get_operation_id(packet);
button_state = avrcp_subevent_operation_get_button_pressed(packet) > 0 ? "PRESS" : "RELEASE";
DEBUGV("AVRCP Target: operation %s (%s)\n", avrcp_operation2str(operation_id), button_state);
if (_avrcpCB) {
_avrcpCB(_avrcpData, operation_id, avrcp_subevent_operation_get_button_pressed(packet) > 0);
}
switch (operation_id) {
case AVRCP_OPERATION_ID_VOLUME_UP:
DEBUGV("AVRCP Target : VOLUME UP (%s)\n", button_state);
break;
case AVRCP_OPERATION_ID_VOLUME_DOWN:
DEBUGV("AVRCP Target : VOLUME DOWN (%s)\n", button_state);
break;
default:
return;
}
break;
default:
DEBUGV("AVRCP Target : Event 0x%02x is not parsed\n", packet[2]);
break;
}
}
void A2DPSink::a2dp_sink_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
UNUSED(channel);
UNUSED(size);
uint8_t status;
uint8_t allocation_method;
if (packet_type != HCI_EVENT_PACKET) {
return;
}
if (hci_event_packet_get_type(packet) != HCI_EVENT_A2DP_META) {
return;
}
a2dp_sink_a2dp_connection_t * a2dp_conn = &a2dp_sink_a2dp_connection;
switch (packet[2]) {
case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_OTHER_CONFIGURATION:
DEBUGV("A2DP Sink : Received non SBC codec - not implemented\n");
break;
case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_SBC_CONFIGURATION: {
DEBUGV("A2DP Sink : Received SBC codec configuration\n");
a2dp_conn->sbc_configuration.reconfigure = a2dp_subevent_signaling_media_codec_sbc_configuration_get_reconfigure(packet);
a2dp_conn->sbc_configuration.num_channels = a2dp_subevent_signaling_media_codec_sbc_configuration_get_num_channels(packet);
a2dp_conn->sbc_configuration.sampling_frequency = a2dp_subevent_signaling_media_codec_sbc_configuration_get_sampling_frequency(packet);
a2dp_conn->sbc_configuration.block_length = a2dp_subevent_signaling_media_codec_sbc_configuration_get_block_length(packet);
a2dp_conn->sbc_configuration.subbands = a2dp_subevent_signaling_media_codec_sbc_configuration_get_subbands(packet);
a2dp_conn->sbc_configuration.min_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_min_bitpool_value(packet);
a2dp_conn->sbc_configuration.max_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_max_bitpool_value(packet);
allocation_method = a2dp_subevent_signaling_media_codec_sbc_configuration_get_allocation_method(packet);
// Adapt Bluetooth spec definition to SBC Encoder expected input
a2dp_conn->sbc_configuration.allocation_method = (btstack_sbc_allocation_method_t)(allocation_method - 1);
switch (a2dp_subevent_signaling_media_codec_sbc_configuration_get_channel_mode(packet)) {
case AVDTP_CHANNEL_MODE_JOINT_STEREO:
a2dp_conn->sbc_configuration.channel_mode = SBC_CHANNEL_MODE_JOINT_STEREO;
break;
case AVDTP_CHANNEL_MODE_STEREO:
a2dp_conn->sbc_configuration.channel_mode = SBC_CHANNEL_MODE_STEREO;
break;
case AVDTP_CHANNEL_MODE_DUAL_CHANNEL:
a2dp_conn->sbc_configuration.channel_mode = SBC_CHANNEL_MODE_DUAL_CHANNEL;
break;
case AVDTP_CHANNEL_MODE_MONO:
a2dp_conn->sbc_configuration.channel_mode = SBC_CHANNEL_MODE_MONO;
break;
default:
btstack_assert(false);
break;
}
a2dp_conn->sbc_configuration.dump();
break;
}
case A2DP_SUBEVENT_STREAM_ESTABLISHED:
status = a2dp_subevent_stream_established_get_status(packet);
if (status != ERROR_CODE_SUCCESS) {
DEBUGV("A2DP Sink : Streaming connection failed, status 0x%02x\n", status);
break;
}
a2dp_subevent_stream_established_get_bd_addr(packet, a2dp_conn->addr);
a2dp_conn->a2dp_cid = a2dp_subevent_stream_established_get_a2dp_cid(packet);
a2dp_conn->a2dp_local_seid = a2dp_subevent_stream_established_get_local_seid(packet);
a2dp_conn->stream_state = STREAM_STATE_OPEN;
DEBUGV("A2DP Sink : Streaming connection is established, address %s, cid 0x%02x, local seid %d\n",
bd_addr_to_str(a2dp_conn->addr), a2dp_conn->a2dp_cid, a2dp_conn->a2dp_local_seid);
memcpy(_sourceAddress, a2dp_conn->addr, sizeof(_sourceAddress));
break;
case A2DP_SUBEVENT_STREAM_STARTED:
DEBUGV("A2DP Sink : Stream started\n");
a2dp_conn->stream_state = STREAM_STATE_PLAYING;
if (a2dp_conn->sbc_configuration.reconfigure) {
media_processing_close();
}
// prepare media processing
media_processing_init(&a2dp_conn->sbc_configuration);
// audio stream is started when buffer reaches minimal level
_connected = true;
if (_connectCB) {
_connectCB(_connectData, true);
}
break;
case A2DP_SUBEVENT_STREAM_SUSPENDED:
DEBUGV("A2DP Sink : Stream paused\n");
a2dp_conn->stream_state = STREAM_STATE_PAUSED;
media_processing_pause();
break;
case A2DP_SUBEVENT_STREAM_RELEASED:
DEBUGV("A2DP Sink : Stream released\n");
a2dp_conn->stream_state = STREAM_STATE_CLOSED;
media_processing_close();
break;
case A2DP_SUBEVENT_SIGNALING_CONNECTION_RELEASED:
DEBUGV("A2DP Sink : Signaling connection released\n");
a2dp_conn->a2dp_cid = 0;
media_processing_close();
_connected = false;
if (_connectCB) {
_connectCB(_connectData, false);
}
break;
default:
break;
}
}
+293
View File
@@ -0,0 +1,293 @@
/*
A2DP Sink (Bluetooth audio receiver)
Copyright (c) 2024 Earle F. Philhower, III <earlephilhower@yahoo.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#pragma once
#include <Arduino.h>
#include "BluetoothHCI.h"
#include "BluetoothAudioConsumer.h"
#include "BluetoothMediaConfigurationSBC.h"
#include "btstack.h"
#include "btstack_resample.h"
#include "btstack_ring_buffer.h"
class A2DPSink : public Stream {
public:
A2DPSink() {
}
virtual int available() override {
return 0; // Unreadable, this is output only
}
virtual int read() override {
return 0;
}
virtual int peek() override {
return 0;
}
virtual void flush() override {
}
virtual size_t write(const uint8_t *buffer, size_t size) override {
(void) buffer;
(void) size;
return 0;
}
virtual int availableForWrite() override {
return 0;
}
virtual size_t write(uint8_t s) override {
(void) s;
return 0;
}
bool setName(const char *name) {
if (_running) {
return false;
}
free(_name);
_name = strdup(name);
return true;
}
void onTransmit(void (*cb)(void *), void *cbData = nullptr) {
_transmitCB = cb;
_transmitData = cbData;
}
void onAVRCP(void (*cb)(void *, avrcp_operation_id_t, int), void *cbData = nullptr) {
_avrcpCB = cb;
_avrcpData = cbData;
}
void onBattery(void (*cb)(void *, avrcp_battery_status_t), void *cbData = nullptr) {
_batteryCB = cb;
_batteryData = cbData;
}
void onVolume(void (*cb)(void *, int), void *cbData = nullptr) {
_volumeCB = cb;
_volumeData = cbData;
}
void onConnect(void (*cb)(void *, bool), void *cbData = nullptr) {
_connectCB = cb;
_connectData = cbData;
}
typedef enum { STOPPED, PLAYING, PAUSED } PlaybackStatus;
void onPlaybackStatus(void (*cb)(void *, PlaybackStatus), void *cbData = nullptr) {
_playbackStatusCB = cb;
_playbackStatusData = cbData;
}
const uint8_t *getSourceAddress() {
if (!_connected) {
return nullptr;
} else {
return _sourceAddress;
}
}
void setConsumer(BluetoothAudioConsumer_ *c) {
_consumer = c;
}
bool begin();
bool disconnect();
void clearPairing();
void playback_handler(int16_t * buffer, uint16_t num_audio_frames);
void play() {
if (_connected) {
avrcp_controller_play(a2dp_sink_avrcp_connection.avrcp_cid);
}
}
void stop() {
if (_connected) {
avrcp_controller_stop(a2dp_sink_avrcp_connection.avrcp_cid);
}
}
void pause() {
if (_connected) {
avrcp_controller_pause(a2dp_sink_avrcp_connection.avrcp_cid);
}
}
void fastForward() {
if (_connected) {
avrcp_controller_fast_forward(a2dp_sink_avrcp_connection.avrcp_cid);
}
}
void rewind() {
if (_connected) {
avrcp_controller_rewind(a2dp_sink_avrcp_connection.avrcp_cid);
}
}
void forward() {
if (_connected) {
avrcp_controller_forward(a2dp_sink_avrcp_connection.avrcp_cid);
}
}
void backward() {
if (_connected) {
avrcp_controller_backward(a2dp_sink_avrcp_connection.avrcp_cid);
}
}
void volumeUp() {
if (_connected) {
avrcp_controller_volume_up(a2dp_sink_avrcp_connection.avrcp_cid);
}
}
void volumeDown() {
if (_connected) {
avrcp_controller_volume_down(a2dp_sink_avrcp_connection.avrcp_cid);
}
}
void mute() {
if (_connected) {
avrcp_controller_mute(a2dp_sink_avrcp_connection.avrcp_cid);
}
}
private:
void handle_pcm_data(int16_t * data, int num_audio_frames, int num_channels, int sample_rate, void * context);
int media_processing_init(BluetoothMediaCodecConfigurationSBC * configuration);
void media_processing_start();
void media_processing_pause();
void media_processing_close();
void handle_l2cap_media_data_packet(uint8_t seid, uint8_t *packet, uint16_t size);
int read_sbc_header(uint8_t * packet, int size, int * offset, avdtp_sbc_codec_header_t * sbc_header);
int read_media_data_header(uint8_t *packet, int size, int *offset, avdtp_media_packet_header_t *media_header);
void avrcp_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
void avrcp_controller_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
void avrcp_target_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
void a2dp_sink_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
BluetoothHCI_ _hci;
BluetoothAudioConsumer_ *_consumer = nullptr;
bool _running = false;
bool _connected = false;
// Callbacks
void (*_transmitCB)(void *) = nullptr;
void *_transmitData;
void (*_avrcpCB)(void *, avrcp_operation_id_t, int) = nullptr;
void *_avrcpData;
void (*_batteryCB)(void *, avrcp_battery_status_t) = nullptr;
void *_batteryData;
void (*_volumeCB)(void *, int) = nullptr;
void *_volumeData;
void (*_connectCB)(void *, bool) = nullptr;
void *_connectData;
void (*_playbackStatusCB)(void *, PlaybackStatus) = nullptr;
void *_playbackStatusData;
char *_name = nullptr;
uint8_t _sourceAddress[6];
enum { NUM_CHANNELS = 2, BYTES_PER_FRAME = (2 * NUM_CHANNELS), MAX_SBC_FRAME_SIZE = 120 };
uint8_t sdp_avdtp_sink_service_buffer[150];
uint8_t sdp_avrcp_target_service_buffer[150];
uint8_t sdp_avrcp_controller_service_buffer[200];
uint8_t device_id_sdp_service_buffer[100];
// we support all configurations with bitpool 2-53
const uint8_t media_sbc_codec_capabilities[4] = {
0xFF,//(AVDTP_SBC_44100 << 4) | AVDTP_SBC_STEREO,
0xFF,//(AVDTP_SBC_BLOCK_LENGTH_16 << 4) | (AVDTP_SBC_SUBBANDS_8 << 2) | AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS,
2, 53
};
// SBC Decoder for WAV file or live playback
btstack_sbc_decoder_state_t state;
btstack_sbc_mode_t mode = SBC_MODE_STANDARD;
// ring buffer for SBC Frames
// below 30: add samples, 30-40: fine, above 40: drop samples
enum { OPTIMAL_FRAMES_MIN = 60, OPTIMAL_FRAMES_MAX = 80, ADDITIONAL_FRAMES = 30 };
uint8_t sbc_frame_storage[(OPTIMAL_FRAMES_MAX + ADDITIONAL_FRAMES) * MAX_SBC_FRAME_SIZE];
btstack_ring_buffer_t sbc_frame_ring_buffer;
unsigned int sbc_frame_size;
// overflow buffer for not fully used sbc frames, with additional frames for resampling
uint8_t decoded_audio_storage[(128 + 16) * BYTES_PER_FRAME];
btstack_ring_buffer_t decoded_audio_ring_buffer;
int media_initialized = 0;
int audio_stream_started;
btstack_resample_t resample_instance;
// temp storage of lower-layer request for audio samples
int16_t * request_buffer;
int request_frames;
// sink state
int volume_percentage = 0;
avrcp_battery_status_t battery_status = AVRCP_BATTERY_STATUS_WARNING;
typedef enum {
STREAM_STATE_CLOSED,
STREAM_STATE_OPEN,
STREAM_STATE_PLAYING,
STREAM_STATE_PAUSED,
} stream_state_t;
typedef struct {
uint8_t a2dp_local_seid;
uint8_t media_sbc_codec_configuration[4];
} a2dp_sink_stream_endpoint_t;
a2dp_sink_stream_endpoint_t a2dp_sink_stream_endpoint;
typedef struct {
bd_addr_t addr;
uint16_t a2dp_cid;
uint8_t a2dp_local_seid;
stream_state_t stream_state;
BluetoothMediaCodecConfigurationSBC sbc_configuration;
} a2dp_sink_a2dp_connection_t;
a2dp_sink_a2dp_connection_t a2dp_sink_a2dp_connection;
typedef struct {
bd_addr_t addr;
uint16_t avrcp_cid;
bool playing;
uint16_t notifications_supported_by_target;
} a2dp_sink_avrcp_connection_t;
a2dp_sink_avrcp_connection_t a2dp_sink_avrcp_connection;
int16_t output_buffer[(128 + 16) * NUM_CHANNELS]; // 16 * 8 * 2
};
+722
View File
@@ -0,0 +1,722 @@
/*
A1DP Source (Bluetooth audio sender)
Copyright (c) 2024 Earle F. Philhower, III <earlephilhower@yahoo.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
// Based heavily off of the a2dp_source example from BlueKitchen BTStack
/*
Copyright (C) 2016 BlueKitchen GmbH
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the names of
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
4. Any redistribution, use, or modification is done solely for
personal benefit and not for any commercial purpose or for
monetary gain.
THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN
GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
Please inquire about commercial licensing options at
contact@bluekitchen-gmbh.com
*/
#include <Arduino.h>
#include "A2DPSource.h"
#define CCALLBACKNAME _A2DPSOURCECB
#include <ctocppcallback.h>
#define PACKETHANDLERCB(class, cbFcn) \
(_A2DPSOURCECB<void(uint8_t, uint16_t, uint8_t*, uint16_t), __COUNTER__>::func = std::bind(&class::cbFcn, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4), \
static_cast<btstack_packet_handler_t>(_A2DPSOURCECB<void(uint8_t, uint16_t, uint8_t*, uint16_t), __COUNTER__ - 1>::callback))
#define TIMEOUTHANDLERCB(class, cbFcn) \
(_A2DPSOURCECB<void(btstack_timer_source_t *), __COUNTER__>::func = std::bind(&class::cbFcn, this, std::placeholders::_1), \
static_cast<void(*)(btstack_timer_source_t*)>(_A2DPSOURCECB<void(btstack_timer_source_t*), __COUNTER__ - 1>::callback))
bool A2DPSource::begin() {
if (_running) {
return false;
}
_pcmBuffer = (int16_t *)malloc(_pcmBufferSize * sizeof(int16_t));
if (!_pcmBuffer) {
DEBUGV("A2DPSource: OOM for pcm buffer\n");
return false;
}
_pcmWriter = 0;
_pcmReader = 0;
// Request role change on reconnecting headset to always use them in slave mode
hci_set_master_slave_policy(0);
// enabled EIR
hci_set_inquiry_mode(INQUIRY_MODE_RSSI_AND_EIR);
l2cap_init();
#ifdef ENABLE_BLE
// Initialize LE Security Manager. Needed for cross-transport key derivation
sm_init();
#endif
// Initialize A2DP Source
a2dp_source_init();
a2dp_source_register_packet_handler(PACKETHANDLERCB(A2DPSource, a2dp_source_packet_handler));
// Create stream endpoint
avdtp_stream_endpoint_t * local_stream_endpoint = a2dp_source_create_stream_endpoint(AVDTP_AUDIO, AVDTP_CODEC_SBC, media_sbc_codec_capabilities, sizeof(media_sbc_codec_capabilities), media_sbc_codec_configuration, sizeof(media_sbc_codec_configuration));
if (!local_stream_endpoint) {
DEBUGV("A2DP Source: not enough memory to create local stream endpoint\n");
return false;
}
// Store stream endpoint's SEP ID, as it is used by A2DP API to identify the stream endpoint
media_tracker.local_seid = avdtp_local_seid(local_stream_endpoint);
avdtp_source_register_delay_reporting_category(media_tracker.local_seid);
// Initialize AVRCP Service
avrcp_init();
avrcp_register_packet_handler(PACKETHANDLERCB(A2DPSource, avrcp_packet_handler));
// Initialize AVRCP Target
avrcp_target_init();
avrcp_target_register_packet_handler(PACKETHANDLERCB(A2DPSource, avrcp_target_packet_handler));
// Initialize AVRCP Controller
avrcp_controller_init();
avrcp_controller_register_packet_handler(PACKETHANDLERCB(A2DPSource, avrcp_controller_packet_handler));
// Initialize SDP,
sdp_init();
// Create A2DP Source service record and register it with SDP
memset(sdp_a2dp_source_service_buffer, 0, sizeof(sdp_a2dp_source_service_buffer));
a2dp_source_create_sdp_record(sdp_a2dp_source_service_buffer, 0x10001, AVDTP_SOURCE_FEATURE_MASK_PLAYER, NULL, NULL);
sdp_register_service(sdp_a2dp_source_service_buffer);
// Create AVRCP Target service record and register it with SDP. We receive Category 1 commands from the headphone, e.g. play/pause
memset(sdp_avrcp_target_service_buffer, 0, sizeof(sdp_avrcp_target_service_buffer));
uint16_t supported_features = AVRCP_FEATURE_MASK_CATEGORY_PLAYER_OR_RECORDER;
#ifdef AVRCP_BROWSING_ENABLED
supported_features |= AVRCP_FEATURE_MASK_BROWSING;
#endif
avrcp_target_create_sdp_record(sdp_avrcp_target_service_buffer, 0x10002, supported_features, NULL, NULL);
sdp_register_service(sdp_avrcp_target_service_buffer);
// Create AVRCP Controller service record and register it with SDP. We send Category 2 commands to the headphone, e.g. volume up/down
memset(sdp_avrcp_controller_service_buffer, 0, sizeof(sdp_avrcp_controller_service_buffer));
uint16_t controller_supported_features = AVRCP_FEATURE_MASK_CATEGORY_MONITOR_OR_AMPLIFIER;
avrcp_controller_create_sdp_record(sdp_avrcp_controller_service_buffer, 0x10003, controller_supported_features, NULL, NULL);
sdp_register_service(sdp_avrcp_controller_service_buffer);
// Register Device ID (PnP) service SDP record
memset(device_id_sdp_service_buffer, 0, sizeof(device_id_sdp_service_buffer));
device_id_create_sdp_record(device_id_sdp_service_buffer, 0x10004, DEVICE_ID_VENDOR_ID_SOURCE_BLUETOOTH, BLUETOOTH_COMPANY_ID_BLUEKITCHEN_GMBH, 1, 1);
sdp_register_service(device_id_sdp_service_buffer);
// Set local name with a template Bluetooth address, that will be automatically
// replaced with a actual address once it is available, i.e. when BTstack boots
// up and starts talking to a Bluetooth module.
if (!_name) {
setName("PicoW A2DP 00:00:00:00:00:00");
}
gap_set_local_name(_name);
gap_discoverable_control(1);
gap_set_class_of_device(0x200408);
// Register for HCI events.
_hci.install();
_running = true;
_hci.begin();
return true;
}
bool A2DPSource::connect(const uint8_t *addr) {
if (!_running) {
return false;
}
while (!_hci.running()) {
delay(10);
}
uint8_t a[6];
if (addr) {
memcpy(a, addr, sizeof(a));
auto ret = !a2dp_source_establish_stream(a, &media_tracker.a2dp_cid);
return ret;
} else {
clearPairing();
auto l = scan();
for (auto e : l) {
DEBUGV("Scan connecting %s at %s ... ", e.name(), e.addressString());
memcpy(a, e.address(), sizeof(a));
if (!a2dp_source_establish_stream(a, &media_tracker.a2dp_cid)) {
DEBUGV("Connection established\n");
return true;
}
DEBUGV("Failed\n");
}
return false;
}
}
bool A2DPSource::disconnect() {
__lockBluetooth();
a2dp_source_disconnect(media_tracker.a2dp_cid);
__unlockBluetooth();
if (!_running || !_connected) {
return false;
}
_connected = false;
return true;
}
void A2DPSource::clearPairing() {
disconnect();
__lockBluetooth();
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) {
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;
if (end - start > size) {
end = start + size;
}
memcpy(_pcmBuffer + start, buffer, (end - start) * sizeof(int16_t));
count += (end - start) * sizeof(int16_t);
size -= end - start;
_pcmWriter += end - start;
_pcmWriter %= _pcmBufferSize;
// Possibly wraparound to 0 if still left
if (size) {
start = 0;
end = _pcmReader;
if (end - start > size) {
end = size;
}
memcpy(_pcmBuffer + start, buffer, (end - start) * sizeof(int16_t));
count += (end - start) * sizeof(int16_t);
size -= end - start;
_pcmWriter += end - start;
_pcmWriter %= _pcmBufferSize;
}
__unlockBluetooth();
return count;
}
int A2DPSource::availableForWrite() {
int avail = 0;
__lockBluetooth();
if (_pcmWriter == _pcmReader) {
avail = _pcmBufferSize - 1;
} else if (_pcmReader > _pcmWriter) {
avail = _pcmReader - _pcmWriter - 1;
} else {
avail = _pcmBufferSize - _pcmWriter + _pcmReader - 1;
}
__unlockBluetooth();
return avail;
}
void A2DPSource::a2dp_timer_start(a2dp_media_sending_context_t * context) {
context->max_media_payload_size = btstack_min(a2dp_max_media_payload_size(context->a2dp_cid, context->local_seid), SBC_STORAGE_SIZE);
context->sbc_storage_count = 0;
context->sbc_ready_to_send = 0;
context->streaming = 1;
btstack_run_loop_remove_timer(&context->audio_timer);
btstack_run_loop_set_timer_handler(&context->audio_timer, TIMEOUTHANDLERCB(A2DPSource, a2dp_audio_timeout_handler));
btstack_run_loop_set_timer_context(&context->audio_timer, context);
btstack_run_loop_set_timer(&context->audio_timer, AUDIO_TIMEOUT_MS);
btstack_run_loop_add_timer(&context->audio_timer);
}
void A2DPSource::a2dp_timer_stop(a2dp_media_sending_context_t * context) {
context->time_audio_data_sent = 0;
context->acc_num_missed_samples = 0;
context->samples_ready = 0;
context->streaming = 1;
context->sbc_storage_count = 0;
context->sbc_ready_to_send = 0;
btstack_run_loop_remove_timer(&context->audio_timer);
}
int A2DPSource::a2dp_fill_sbc_audio_buffer(a2dp_media_sending_context_t * context) {
// perform sbc encoding
int total_num_bytes_read = 0;
unsigned int num_audio_samples_per_sbc_buffer = btstack_sbc_encoder_num_audio_frames();
while (context->samples_ready >= num_audio_samples_per_sbc_buffer
&& (context->max_media_payload_size - context->sbc_storage_count) >= btstack_sbc_encoder_sbc_buffer_length()) {
if ((_pcmWriter / 256) != (_pcmReader / 256)) {
btstack_sbc_encoder_process_data(_pcmBuffer + _pcmReader);
asm volatile("" ::: "memory"); // Ensure the data is processed before advancing
auto next_reader = (_pcmReader + 256) % _pcmBufferSize;
asm volatile("" ::: "memory"); // Ensure the reader value is only written once, correctly
_pcmReader = next_reader;
} else {
_underflow = true;
// Just keep sending old data
btstack_sbc_encoder_process_data(_pcmBuffer + _pcmReader);
}
uint16_t sbc_frame_size = btstack_sbc_encoder_sbc_buffer_length();
uint8_t *sbc_frame = btstack_sbc_encoder_sbc_buffer();
total_num_bytes_read += num_audio_samples_per_sbc_buffer;
// first byte in sbc storage contains sbc media header
memcpy(&context->sbc_storage[1 + context->sbc_storage_count], sbc_frame, sbc_frame_size);
context->sbc_storage_count += sbc_frame_size;
context->samples_ready -= num_audio_samples_per_sbc_buffer;
}
return total_num_bytes_read;
}
void A2DPSource::a2dp_audio_timeout_handler(btstack_timer_source_t * timer) {
a2dp_media_sending_context_t * context = (a2dp_media_sending_context_t *) btstack_run_loop_get_timer_context(timer);
btstack_run_loop_set_timer(&context->audio_timer, AUDIO_TIMEOUT_MS);
btstack_run_loop_add_timer(&context->audio_timer);
uint32_t now = btstack_run_loop_get_time_ms();
uint32_t update_period_ms = AUDIO_TIMEOUT_MS;
if (context->time_audio_data_sent > 0) {
update_period_ms = now - context->time_audio_data_sent;
}
uint32_t num_samples = (update_period_ms * _frequency) / 1000;
context->acc_num_missed_samples += (update_period_ms * _frequency) % 1000;
while (context->acc_num_missed_samples >= 1000) {
num_samples++;
context->acc_num_missed_samples -= 1000;
}
context->time_audio_data_sent = now;
context->samples_ready += num_samples;
if (context->sbc_ready_to_send) {
return;
}
a2dp_fill_sbc_audio_buffer(context);
if ((context->sbc_storage_count + btstack_sbc_encoder_sbc_buffer_length()) > context->max_media_payload_size) {
// schedule sending
context->sbc_ready_to_send = 1;
a2dp_source_stream_endpoint_request_can_send_now(context->a2dp_cid, context->local_seid);
}
}
void A2DPSource::a2dp_send_media_packet() {
int num_bytes_in_frame = btstack_sbc_encoder_sbc_buffer_length();
int bytes_in_storage = media_tracker.sbc_storage_count;
uint8_t num_sbc_frames = bytes_in_storage / num_bytes_in_frame;
// Prepend SBC Header
media_tracker.sbc_storage[0] = num_sbc_frames; // (fragmentation << 7) | (starting_packet << 6) | (last_packet << 5) | num_frames;
a2dp_source_stream_send_media_payload_rtp(media_tracker.a2dp_cid, media_tracker.local_seid, 0,
media_tracker.rtp_timestamp,
media_tracker.sbc_storage, bytes_in_storage + 1);
// update rtp_timestamp
unsigned int num_audio_samples_per_sbc_buffer = btstack_sbc_encoder_num_audio_frames();
media_tracker.rtp_timestamp += num_sbc_frames * num_audio_samples_per_sbc_buffer;
media_tracker.sbc_storage_count = 0;
media_tracker.sbc_ready_to_send = 0;
if (_transmitCB) {
_transmitCB(_transmitData);
}
}
void A2DPSource::a2dp_source_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
UNUSED(channel);
UNUSED(size);
uint8_t status;
uint8_t local_seid;
bd_addr_t address;
uint16_t cid;
avdtp_channel_mode_t channel_mode;
uint8_t allocation_method;
if (packet_type != HCI_EVENT_PACKET) {
return;
}
if (hci_event_packet_get_type(packet) != HCI_EVENT_A2DP_META) {
return;
}
switch (hci_event_a2dp_meta_get_subevent_code(packet)) {
case A2DP_SUBEVENT_SIGNALING_CONNECTION_ESTABLISHED:
a2dp_subevent_signaling_connection_established_get_bd_addr(packet, address);
cid = a2dp_subevent_signaling_connection_established_get_a2dp_cid(packet);
status = a2dp_subevent_signaling_connection_established_get_status(packet);
if (status != ERROR_CODE_SUCCESS) {
DEBUGV("A2DP Source: Connection failed, status 0x%02x, cid 0x%02x, a2dp_cid 0x%02x \n", status, cid, media_tracker.a2dp_cid);
media_tracker.a2dp_cid = 0;
break;
}
media_tracker.a2dp_cid = cid;
media_tracker.volume = 32;
memcpy(_sinkAddress, address, sizeof(_sinkAddress));
DEBUGV("A2DP Source: Connected to address %s, a2dp cid 0x%02x, local seid 0x%02x.\n", bd_addr_to_str(address), media_tracker.a2dp_cid, media_tracker.local_seid);
break;
case A2DP_SUBEVENT_SIGNALING_MEDIA_CODEC_SBC_CONFIGURATION: {
cid = avdtp_subevent_signaling_media_codec_sbc_configuration_get_avdtp_cid(packet);
if (cid != media_tracker.a2dp_cid) {
return;
}
media_tracker.remote_seid = a2dp_subevent_signaling_media_codec_sbc_configuration_get_remote_seid(packet);
sbc_configuration.reconfigure = a2dp_subevent_signaling_media_codec_sbc_configuration_get_reconfigure(packet);
sbc_configuration.num_channels = a2dp_subevent_signaling_media_codec_sbc_configuration_get_num_channels(packet);
sbc_configuration.sampling_frequency = a2dp_subevent_signaling_media_codec_sbc_configuration_get_sampling_frequency(packet);
sbc_configuration.block_length = a2dp_subevent_signaling_media_codec_sbc_configuration_get_block_length(packet);
sbc_configuration.subbands = a2dp_subevent_signaling_media_codec_sbc_configuration_get_subbands(packet);
sbc_configuration.min_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_min_bitpool_value(packet);
sbc_configuration.max_bitpool_value = a2dp_subevent_signaling_media_codec_sbc_configuration_get_max_bitpool_value(packet);
channel_mode = (avdtp_channel_mode_t) a2dp_subevent_signaling_media_codec_sbc_configuration_get_channel_mode(packet);
allocation_method = a2dp_subevent_signaling_media_codec_sbc_configuration_get_allocation_method(packet);
DEBUGV("A2DP Source: Received SBC codec configuration, sampling frequency %u, a2dp_cid 0x%02x, local seid 0x%02x, remote seid 0x%02x.\n",
sbc_configuration.sampling_frequency, cid,
a2dp_subevent_signaling_media_codec_sbc_configuration_get_local_seid(packet),
a2dp_subevent_signaling_media_codec_sbc_configuration_get_remote_seid(packet));
// Adapt Bluetooth spec definition to SBC Encoder expected input
sbc_configuration.allocation_method = (btstack_sbc_allocation_method_t)(allocation_method - 1);
switch (channel_mode) {
case AVDTP_CHANNEL_MODE_JOINT_STEREO:
sbc_configuration.channel_mode = SBC_CHANNEL_MODE_JOINT_STEREO;
break;
case AVDTP_CHANNEL_MODE_STEREO:
sbc_configuration.channel_mode = SBC_CHANNEL_MODE_STEREO;
break;
case AVDTP_CHANNEL_MODE_DUAL_CHANNEL:
sbc_configuration.channel_mode = SBC_CHANNEL_MODE_DUAL_CHANNEL;
break;
case AVDTP_CHANNEL_MODE_MONO:
sbc_configuration.channel_mode = SBC_CHANNEL_MODE_MONO;
break;
default:
btstack_assert(false);
break;
}
sbc_configuration.dump();
btstack_sbc_encoder_init(&sbc_encoder_state, SBC_MODE_STANDARD,
sbc_configuration.block_length, sbc_configuration.subbands,
sbc_configuration.allocation_method, sbc_configuration.sampling_frequency,
sbc_configuration.max_bitpool_value,
sbc_configuration.channel_mode);
break;
}
case A2DP_SUBEVENT_SIGNALING_DELAY_REPORTING_CAPABILITY:
DEBUGV("A2DP Source: remote supports delay report, remote seid %d\n",
avdtp_subevent_signaling_delay_reporting_capability_get_remote_seid(packet));
break;
case A2DP_SUBEVENT_SIGNALING_CAPABILITIES_DONE:
DEBUGV("A2DP Source: All capabilities reported, remote seid %d\n",
avdtp_subevent_signaling_capabilities_done_get_remote_seid(packet));
break;
case A2DP_SUBEVENT_SIGNALING_DELAY_REPORT:
DEBUGV("A2DP Source: Received delay report of %d.%0d ms, local seid %d\n",
avdtp_subevent_signaling_delay_report_get_delay_100us(packet) / 10, avdtp_subevent_signaling_delay_report_get_delay_100us(packet) % 10,
avdtp_subevent_signaling_delay_report_get_local_seid(packet));
break;
case A2DP_SUBEVENT_STREAM_ESTABLISHED:
a2dp_subevent_stream_established_get_bd_addr(packet, address);
status = a2dp_subevent_stream_established_get_status(packet);
if (status != ERROR_CODE_SUCCESS) {
DEBUGV("A2DP Source: Stream failed, status 0x%02x.\n", status);
break;
}
local_seid = a2dp_subevent_stream_established_get_local_seid(packet);
cid = a2dp_subevent_stream_established_get_a2dp_cid(packet);
(void) local_seid;
DEBUGV("A2DP Source: Stream established a2dp_cid 0x%02x, local_seid 0x%02x, remote_seid 0x%02x\n", cid, local_seid, a2dp_subevent_stream_established_get_remote_seid(packet));
media_tracker.stream_opened = 1;
status = a2dp_source_start_stream(media_tracker.a2dp_cid, media_tracker.local_seid);
break;
case A2DP_SUBEVENT_STREAM_RECONFIGURED:
status = a2dp_subevent_stream_reconfigured_get_status(packet);
local_seid = a2dp_subevent_stream_reconfigured_get_local_seid(packet);
cid = a2dp_subevent_stream_reconfigured_get_a2dp_cid(packet);
if (status != ERROR_CODE_SUCCESS) {
DEBUGV("A2DP Source: Stream reconfiguration failed, status 0x%02x\n", status);
break;
}
DEBUGV("A2DP Source: Stream reconfigured a2dp_cid 0x%02x, local_seid 0x%02x\n", cid, local_seid);
status = a2dp_source_start_stream(media_tracker.a2dp_cid, media_tracker.local_seid);
break;
case A2DP_SUBEVENT_STREAM_STARTED:
local_seid = a2dp_subevent_stream_started_get_local_seid(packet);
cid = a2dp_subevent_stream_started_get_a2dp_cid(packet);
play_info.status = AVRCP_PLAYBACK_STATUS_PLAYING;
if (media_tracker.avrcp_cid) {
avrcp_target_set_now_playing_info(media_tracker.avrcp_cid, &_currentTrack, _tracks);
avrcp_target_set_playback_status(media_tracker.avrcp_cid, AVRCP_PLAYBACK_STATUS_PLAYING);
}
a2dp_timer_start(&media_tracker);
DEBUGV("A2DP Source: Stream started, a2dp_cid 0x%02x, local_seid 0x%02x\n", cid, local_seid);
_connected = true;
if (_connectCB) {
_connectCB(_connectData, true);
}
break;
case A2DP_SUBEVENT_STREAMING_CAN_SEND_MEDIA_PACKET_NOW:
local_seid = a2dp_subevent_streaming_can_send_media_packet_now_get_local_seid(packet);
cid = a2dp_subevent_signaling_media_codec_sbc_configuration_get_a2dp_cid(packet);
a2dp_send_media_packet();
break;
case A2DP_SUBEVENT_STREAM_SUSPENDED:
local_seid = a2dp_subevent_stream_suspended_get_local_seid(packet);
cid = a2dp_subevent_stream_suspended_get_a2dp_cid(packet);
play_info.status = AVRCP_PLAYBACK_STATUS_PAUSED;
if (media_tracker.avrcp_cid) {
avrcp_target_set_playback_status(media_tracker.avrcp_cid, AVRCP_PLAYBACK_STATUS_PAUSED);
}
DEBUGV("A2DP Source: Stream paused, a2dp_cid 0x%02x, local_seid 0x%02x\n", cid, local_seid);
a2dp_timer_stop(&media_tracker);
break;
case A2DP_SUBEVENT_STREAM_RELEASED:
play_info.status = AVRCP_PLAYBACK_STATUS_STOPPED;
cid = a2dp_subevent_stream_released_get_a2dp_cid(packet);
local_seid = a2dp_subevent_stream_released_get_local_seid(packet);
DEBUGV("A2DP Source: Stream released, a2dp_cid 0x%02x, local_seid 0x%02x\n", cid, local_seid);
if (cid == media_tracker.a2dp_cid) {
media_tracker.stream_opened = 0;
DEBUGV("A2DP Source: Stream released.\n");
}
if (media_tracker.avrcp_cid) {
avrcp_target_set_now_playing_info(media_tracker.avrcp_cid, NULL, _tracks);
avrcp_target_set_playback_status(media_tracker.avrcp_cid, AVRCP_PLAYBACK_STATUS_STOPPED);
}
a2dp_timer_stop(&media_tracker);
break;
case A2DP_SUBEVENT_SIGNALING_CONNECTION_RELEASED:
cid = a2dp_subevent_signaling_connection_released_get_a2dp_cid(packet);
if (cid == media_tracker.a2dp_cid) {
media_tracker.avrcp_cid = 0;
media_tracker.a2dp_cid = 0;
DEBUGV("A2DP Source: Signaling released.\n\n");
_connected = false;
if (_connectCB) {
_connectCB(_connectData, false);
}
}
break;
default:
break;
}
}
void A2DPSource::avrcp_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
UNUSED(channel);
UNUSED(size);
bd_addr_t event_addr;
uint16_t local_cid;
uint8_t status = ERROR_CODE_SUCCESS;
if (packet_type != HCI_EVENT_PACKET) {
return;
}
if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) {
return;
}
switch (packet[2]) {
case AVRCP_SUBEVENT_CONNECTION_ESTABLISHED:
local_cid = avrcp_subevent_connection_established_get_avrcp_cid(packet);
status = avrcp_subevent_connection_established_get_status(packet);
if (status != ERROR_CODE_SUCCESS) {
DEBUGV("AVRCP: Connection failed, local cid 0x%02x, status 0x%02x\n", local_cid, status);
return;
}
media_tracker.avrcp_cid = local_cid;
avrcp_subevent_connection_established_get_bd_addr(packet, event_addr);
DEBUGV("AVRCP: Channel to %s successfully opened, avrcp_cid 0x%02x\n", bd_addr_to_str(event_addr), media_tracker.avrcp_cid);
avrcp_target_support_event(media_tracker.avrcp_cid, AVRCP_NOTIFICATION_EVENT_PLAYBACK_STATUS_CHANGED);
avrcp_target_support_event(media_tracker.avrcp_cid, AVRCP_NOTIFICATION_EVENT_TRACK_CHANGED);
avrcp_target_support_event(media_tracker.avrcp_cid, AVRCP_NOTIFICATION_EVENT_NOW_PLAYING_CONTENT_CHANGED);
avrcp_target_set_now_playing_info(media_tracker.avrcp_cid, NULL, _tracks);
DEBUGV("Enable Volume Change notification\n");
avrcp_controller_enable_notification(media_tracker.avrcp_cid, AVRCP_NOTIFICATION_EVENT_VOLUME_CHANGED);
DEBUGV("Enable Battery Status Change notification\n");
avrcp_controller_enable_notification(media_tracker.avrcp_cid, AVRCP_NOTIFICATION_EVENT_BATT_STATUS_CHANGED);
return;
case AVRCP_SUBEVENT_CONNECTION_RELEASED:
DEBUGV("AVRCP Target: Disconnected, avrcp_cid 0x%02x\n", avrcp_subevent_connection_released_get_avrcp_cid(packet));
media_tracker.avrcp_cid = 0;
return;
default:
break;
}
if (status != ERROR_CODE_SUCCESS) {
DEBUGV("Responding to event 0x%02x failed, status 0x%02x\n", packet[2], status);
}
}
void A2DPSource::avrcp_target_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
UNUSED(channel);
UNUSED(size);
uint8_t status = ERROR_CODE_SUCCESS;
if (packet_type != HCI_EVENT_PACKET) {
return;
}
if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) {
return;
}
bool button_pressed;
char const * button_state;
avrcp_operation_id_t operation_id;
switch (packet[2]) {
case AVRCP_SUBEVENT_PLAY_STATUS_QUERY:
status = avrcp_target_play_status(media_tracker.avrcp_cid, play_info.song_length_ms, play_info.song_position_ms, play_info.status);
break;
// case AVRCP_SUBEVENT_NOW_PLAYING_INFO_QUERY:
// status = avrcp_target_now_playing_info(avrcp_cid);
// break;
case AVRCP_SUBEVENT_OPERATION:
operation_id = (avrcp_operation_id_t)avrcp_subevent_operation_get_operation_id(packet);
button_pressed = avrcp_subevent_operation_get_button_pressed(packet) > 0;
button_state = button_pressed ? "PRESS" : "RELEASE";
(void) button_state;
DEBUGV("AVRCP Target: operation %s (%s)\n", avrcp_operation2str(operation_id), button_state);
if (_avrcpCB) {
_avrcpCB(_avrcpData, operation_id, button_pressed);
}
if (!button_pressed) {
break;
}
switch (operation_id) {
case AVRCP_OPERATION_ID_PLAY:
status = a2dp_source_start_stream(media_tracker.a2dp_cid, media_tracker.local_seid);
break;
case AVRCP_OPERATION_ID_PAUSE:
status = a2dp_source_pause_stream(media_tracker.a2dp_cid, media_tracker.local_seid);
break;
case AVRCP_OPERATION_ID_STOP:
status = a2dp_source_disconnect(media_tracker.a2dp_cid);
break;
default:
break;
}
break;
default:
break;
}
if (status != ERROR_CODE_SUCCESS) {
DEBUGV("Responding to event 0x%02x failed, status 0x%02x\n", packet[2], status);
}
}
void A2DPSource::avrcp_controller_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
UNUSED(channel);
UNUSED(size);
if (packet_type != HCI_EVENT_PACKET) {
return;
}
if (hci_event_packet_get_type(packet) != HCI_EVENT_AVRCP_META) {
return;
}
if (!media_tracker.avrcp_cid) {
return;
}
switch (packet[2]) {
case AVRCP_SUBEVENT_NOTIFICATION_VOLUME_CHANGED:
DEBUGV("AVRCP Controller: Notification Absolute Volume %d %%\n", avrcp_subevent_notification_volume_changed_get_absolute_volume(packet) * 100 / 127);
if (_volumeCB) {
_volumeCB(_volumeData, avrcp_subevent_notification_volume_changed_get_absolute_volume(packet) * 100 / 127);
}
break;
case AVRCP_SUBEVENT_NOTIFICATION_EVENT_BATT_STATUS_CHANGED:
// see avrcp_battery_status_t
DEBUGV("AVRCP Controller: Notification Battery Status 0x%02x\n", avrcp_subevent_notification_event_batt_status_changed_get_battery_status(packet));
if (_batteryCB) {
_batteryCB(_batteryData, (avrcp_battery_status_t)avrcp_subevent_notification_event_batt_status_changed_get_battery_status(packet));
}
break;
case AVRCP_SUBEVENT_NOTIFICATION_STATE:
DEBUGV("AVRCP Controller: Notification %s - %s\n",
avrcp_event2str(avrcp_subevent_notification_state_get_event_id(packet)),
avrcp_subevent_notification_state_get_enabled(packet) != 0 ? "enabled" : "disabled");
break;
default:
break;
}
}
+238
View File
@@ -0,0 +1,238 @@
/*
A1DP Source (Bluetooth audio sender)
Copyright (c) 2024 Earle F. Philhower, III <earlephilhower@yahoo.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#pragma once
#include <Arduino.h>
#include "BluetoothHCI.h"
#include "BluetoothMediaConfigurationSBC.h"
#include <functional>
#include <list>
#include <memory>
class A2DPSource : public Stream {
public:
A2DPSource() {
}
bool setFrequency(uint32_t rate) {
if (_running || ((rate != 44100) && (rate != 48000))) {
return false;
}
_frequency = rate;
return true;
}
bool setName(const char *name) {
if (_running) {
return false;
}
free(_name);
_name = strdup(name);
return true;
}
void onTransmit(void (*cb)(void *), void *cbData = nullptr) {
_transmitCB = cb;
_transmitData = cbData;
}
void onAVRCP(void (*cb)(void *, avrcp_operation_id_t, int), void *cbData = nullptr) {
_avrcpCB = cb;
_avrcpData = cbData;
}
void onBattery(void (*cb)(void *, avrcp_battery_status_t), void *cbData = nullptr) {
_batteryCB = cb;
_batteryData = cbData;
}
void onVolume(void (*cb)(void *, int), void *cbData = nullptr) {
_volumeCB = cb;
_volumeData = cbData;
}
void onConnect(void (*cb)(void *, bool), void *cbData = nullptr) {
_connectCB = cb;
_connectData = cbData;
}
bool setBufferSize(size_t size) {
if (_running || (size & 127) || (size < 1024)) {
return false;
}
_pcmBufferSize = size;
return true;
}
bool getUnderflow() {
if (!_running) {
return false;
}
__lockBluetooth();
auto ret = _underflow;
_underflow = false;
__unlockBluetooth();
return ret;
}
const uint8_t *getSinkAddress() {
if (!_connected) {
return nullptr;
} else {
return _sinkAddress;
}
}
bool begin();
std::list<BTDeviceInfo> scan(uint32_t mask = BluetoothHCI_::speaker_cod, int scanTimeSec = 5, bool async = false) {
return _hci.scan(mask, scanTimeSec, async);
}
bool connect(const uint8_t *addr = nullptr);
bool connected() {
return _connected;
}
bool disconnect();
void clearPairing();
// from Stream
virtual int available() override {
return 0; // Unreadable, this is output only
}
virtual int read() override {
return 0;
}
virtual int peek() override {
return 0;
}
virtual void flush() override {
}
// from Print (see notes on write() methods below)
virtual size_t write(const uint8_t *buffer, size_t size) override;
virtual int availableForWrite() override;
virtual size_t write(uint8_t s) override {
(void) s;
return 0; // Never any reason to write 8-bit data, make it always fail.
}
private:
BluetoothHCI_ _hci;
bool _running = false;
bool _connected = false;
char *_name = nullptr;
int _frequency = 44100;
// Callbacks
void (*_transmitCB)(void *) = nullptr;
void *_transmitData;
void (*_avrcpCB)(void *, avrcp_operation_id_t, int) = nullptr;
void *_avrcpData;
void (*_batteryCB)(void *, avrcp_battery_status_t) = nullptr;
void *_batteryData;
void (*_volumeCB)(void *, int) = nullptr;
void *_volumeData;
void (*_connectCB)(void *, bool) = nullptr;
void *_connectData;
const uint8_t media_sbc_codec_capabilities[4] = {
(AVDTP_SBC_44100 << 4) | AVDTP_SBC_STEREO,
0xFF,//(AVDTP_SBC_BLOCK_LENGTH_16 << 4) | (AVDTP_SBC_SUBBANDS_8 << 2) | AVDTP_SBC_ALLOCATION_METHOD_LOUDNESS,
2, 53
};
uint8_t media_sbc_codec_configuration[4];
enum {SBC_STORAGE_SIZE = 1030, AUDIO_TIMEOUT_MS = 5};
typedef struct {
uint16_t a2dp_cid;
uint8_t local_seid;
uint8_t remote_seid;
uint8_t stream_opened;
uint16_t avrcp_cid;
uint32_t time_audio_data_sent; // ms
uint32_t acc_num_missed_samples;
uint32_t samples_ready;
btstack_timer_source_t audio_timer;
uint8_t streaming;
int max_media_payload_size;
uint32_t rtp_timestamp;
uint8_t sbc_storage[SBC_STORAGE_SIZE];
uint16_t sbc_storage_count;
uint8_t sbc_ready_to_send;
uint8_t volume;
} a2dp_media_sending_context_t;
uint8_t sdp_a2dp_source_service_buffer[150];
uint8_t sdp_avrcp_target_service_buffer[200];
uint8_t sdp_avrcp_controller_service_buffer[200];
uint8_t device_id_sdp_service_buffer[100];
BluetoothMediaCodecConfigurationSBC sbc_configuration;
btstack_sbc_encoder_state_t sbc_encoder_state;
a2dp_media_sending_context_t media_tracker;
typedef struct {
uint8_t track_id[8];
uint32_t song_length_ms;
avrcp_playback_status_t status;
uint32_t song_position_ms; // 0xFFFFFFFF if not supported
} avrcp_play_status_info_t;
avrcp_play_status_info_t play_info;
void a2dp_timer_start(a2dp_media_sending_context_t * context);
void a2dp_timer_stop(a2dp_media_sending_context_t * context);
int16_t *_pcmBuffer = nullptr;
size_t _pcmBufferSize = 4096; // Multiple of 128 required
uint32_t _pcmWriter;
uint32_t _pcmReader;
bool _underflow;
int a2dp_fill_sbc_audio_buffer(a2dp_media_sending_context_t * context);
void a2dp_audio_timeout_handler(btstack_timer_source_t * timer);
void a2dp_send_media_packet();
int _tracks = 1;
avrcp_track_t _currentTrack;
uint8_t _sinkAddress[6];
void a2dp_source_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
void avrcp_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
void avrcp_target_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
void avrcp_controller_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
};
@@ -0,0 +1,8 @@
#include "BluetoothDevice.h"
#include "BluetoothHCI.h"
#include "BluetoothMediaConfigurationSBC.h"
#include "A2DPSource.h"
#include "A2DPSink.h"
#include "BluetoothAudioConsumer.h"
#include "BluetoothAudioConsumerPWM.h"
#include "BluetoothAudioConsumerI2S.h"
@@ -0,0 +1,45 @@
/*
Bluetooth A2DP audio stream consumer
Copyright (c) 2024 Earle F. Philhower, III <earlephilhower@yahoo.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#pragma once
class A2DPSink;
class BluetoothAudioConsumer_ {
public:
BluetoothAudioConsumer_() {
_state = STATE_OFF;
}
virtual ~BluetoothAudioConsumer_() {
/* noop */
}
virtual bool init(uint8_t channels, uint32_t samplerate, A2DPSink *a2dpSink) = 0;
virtual void setVolume(uint8_t gain) = 0;
virtual void startStream() = 0;
virtual void stopStream() = 0;
virtual void close() = 0;
protected:
typedef enum { STATE_OFF = 0, STATE_INITIALIZED, STATE_STREAMING } State;
A2DPSink *_a2dpSink;
State _state;
uint8_t _gain;
int _channels;
int _samplerate;
};
@@ -0,0 +1,84 @@
/*
Bluetooth A2DP audio stream consumer - PWMAudio
Copyright (c) 2024 Earle F. Philhower, III <earlephilhower@yahoo.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "BluetoothAudioConsumerI2S.h"
#include "A2DPSink.h"
#include <functional>
#define CCALLBACKNAME _BTA2DPI2S
#include <ctocppcallback.h>
#define NOPARAMCB(class, cbFcn) \
(CCALLBACKNAME<void(void), __COUNTER__>::func = std::bind(&class::cbFcn, this), \
static_cast<void (*)(void)>(CCALLBACKNAME<void(void), __COUNTER__ - 1>::callback))
bool BluetoothAudioConsumerI2S::init(uint8_t channels, uint32_t samplerate, A2DPSink *a2dpSink) {
_channels = channels;
_samplerate = samplerate;
_a2dpSink = a2dpSink;
_i2s->setBuffers(16, 64);
_i2s->onTransmit(NOPARAMCB(BluetoothAudioConsumerI2S, fill));
if (_i2s->begin(samplerate)) {
_state = STATE_INITIALIZED;
_gain = 64;
return true;
}
return false;
}
void BluetoothAudioConsumerI2S::setVolume(uint8_t gain) {
_gain = gain;
}
void BluetoothAudioConsumerI2S::startStream() {
if (_state != STATE_INITIALIZED) {
return;
}
_state = STATE_STREAMING;
}
void BluetoothAudioConsumerI2S::stopStream() {
if (_state != STATE_STREAMING) {
return;
}
_state = STATE_INITIALIZED;
}
void BluetoothAudioConsumerI2S::close() {
if (_state == STATE_STREAMING) {
stopStream();
}
_state = STATE_OFF;
_i2s->end();
}
void BluetoothAudioConsumerI2S::fill() {
int num_samples = _i2s->availableForWrite() / 2;
int16_t buff[32 * 2];
while (num_samples > 63) {
_a2dpSink->playback_handler((int16_t *) buff, 32);
num_samples -= 64;
for (int i = 0; i < 64; i++) {
int32_t tmp = buff[i];
tmp *= _gain;
tmp >>= 8;
_i2s->write((int16_t)tmp);
}
}
}
@@ -0,0 +1,41 @@
/*
Bluetooth A2DP audio stream consumer - I2S
Copyright (c) 2024 Earle F. Philhower, III <earlephilhower@yahoo.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#pragma once
#include <I2S.h>
#include "BluetoothAudioConsumer.h"
class BluetoothAudioConsumerI2S : public BluetoothAudioConsumer_ {
public:
BluetoothAudioConsumerI2S(I2S &i2s) : BluetoothAudioConsumer_() {
_i2s = &i2s;
}
virtual bool init(uint8_t channels, uint32_t samplerate, A2DPSink *a2dpSink) override;
virtual void setVolume(uint8_t gain) override;
virtual void startStream() override;
virtual void stopStream() override;
virtual void close() override;
private:
I2S *_i2s;
void fill();
};
@@ -0,0 +1,85 @@
/*
Bluetooth A2DP audio stream consumer - PWMAudio
Copyright (c) 2024 Earle F. Philhower, III <earlephilhower@yahoo.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "BluetoothAudioConsumerPWM.h"
#include "A2DPSink.h"
#include <functional>
#define CCALLBACKNAME _BTA2DPPWM
#include <ctocppcallback.h>
#define NOPARAMCB(class, cbFcn) \
(CCALLBACKNAME<void(void), __COUNTER__>::func = std::bind(&class::cbFcn, this), \
static_cast<void (*)(void)>(CCALLBACKNAME<void(void), __COUNTER__ - 1>::callback))
bool BluetoothAudioConsumerPWM::init(uint8_t channels, uint32_t samplerate, A2DPSink *a2dpSink) {
_channels = channels;
_samplerate = samplerate;
_a2dpSink = a2dpSink;
_pwm->setStereo(channels == 2);
_pwm->setBuffers(16, 64);
_pwm->onTransmit(NOPARAMCB(BluetoothAudioConsumerPWM, fill));
if (_pwm->begin(samplerate)) {
_state = STATE_INITIALIZED;
_gain = 64;
return true;
}
return false;
}
void BluetoothAudioConsumerPWM::setVolume(uint8_t gain) {
_gain = gain;
}
void BluetoothAudioConsumerPWM::startStream() {
if (_state != STATE_INITIALIZED) {
return;
}
_state = STATE_STREAMING;
}
void BluetoothAudioConsumerPWM::stopStream() {
if (_state != STATE_STREAMING) {
return;
}
_state = STATE_INITIALIZED;
}
void BluetoothAudioConsumerPWM::close() {
if (_state == STATE_STREAMING) {
stopStream();
}
_state = STATE_OFF;
_pwm->end();
}
void BluetoothAudioConsumerPWM::fill() {
int num_samples = _pwm->availableForWrite() / 2;
int16_t buff[32 * 2];
while (num_samples > 63) {
_a2dpSink->playback_handler((int16_t *) buff, 32);
num_samples -= 64;
for (int i = 0; i < 64; i++) {
int32_t tmp = buff[i];
tmp *= _gain;
tmp >>= 8;
_pwm->write((int16_t)tmp);
}
}
}
@@ -0,0 +1,41 @@
/*
Bluetooth A2DP audio stream consumer - PWMAudio
Copyright (c) 2024 Earle F. Philhower, III <earlephilhower@yahoo.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#pragma once
#include <PWMAudio.h>
#include "BluetoothAudioConsumer.h"
class BluetoothAudioConsumerPWM : public BluetoothAudioConsumer_ {
public:
BluetoothAudioConsumerPWM(PWMAudio &pwm) : BluetoothAudioConsumer_() {
_pwm = &pwm;
}
virtual bool init(uint8_t channels, uint32_t samplerate, A2DPSink *a2dpSink) override;
virtual void setVolume(uint8_t gain) override;
virtual void startStream() override;
virtual void stopStream() override;
virtual void close() override;
private:
PWMAudio *_pwm;
void fill();
};
@@ -0,0 +1,66 @@
/*
Bluetooth device helper class
Copyright (c) 2024 Earle F. Philhower, III <earlephilhower@yahoo.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#pragma once
#include <Arduino.h>
class BTDeviceInfo {
public:
BTDeviceInfo(uint32_t dc, const uint8_t addr[6], int rssi, const char *name) {
_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]);
_rssi = rssi;
_name = strdup(name);
}
// 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);
}
~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;
}
private:
uint32_t _deviceClass;
uint8_t _address[6];
char _addressString[18];
int8_t _rssi;
char *_name;
};
@@ -0,0 +1,162 @@
/*
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,52 @@
/*
Bluetooth HCI packet handler class
Copyright (c) 2024 Earle F. Philhower, III <earlephilhower@yahoo.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#pragma once
#include <Arduino.h>
#include <list>
#include <memory>
#include "BluetoothDevice.h"
#include <btstack.h>
class BluetoothHCI_ {
public:
void install();
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);
bool scanAsyncDone();
std::list<BTDeviceInfo> scanAsyncResult();
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;
volatile bool _scanning = false;
bool _running = false;
};
@@ -0,0 +1,47 @@
/*
A1DP Source (Bluetooth audio sender)
Copyright (c) 2024 Earle F. Philhower, III <earlephilhower@yahoo.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#pragma once
#include <Arduino.h>
class BluetoothMediaCodecConfigurationSBC {
public:
uint8_t reconfigure;
uint8_t num_channels;
uint16_t sampling_frequency;
uint8_t block_length;
uint8_t subbands;
uint8_t min_bitpool_value;
uint8_t max_bitpool_value;
btstack_sbc_channel_mode_t channel_mode;
btstack_sbc_allocation_method_t allocation_method;
void dump() {
DEBUGV(" - num_channels: %d\n", num_channels);
DEBUGV(" - sampling_frequency: %d\n", sampling_frequency);
DEBUGV(" - channel_mode: %d\n", channel_mode);
DEBUGV(" - block_length: %d\n", block_length);
DEBUGV(" - subbands: %d\n", subbands);
DEBUGV(" - allocation_method: %d\n", allocation_method);
DEBUGV(" - bitpool_value [%d, %d] \n", min_bitpool_value, max_bitpool_value);
DEBUGV("\n");
}
};
@@ -29,7 +29,7 @@ const char *softAP_password = APPSK;
/* hostname for mDNS. Should work at least on windows. Try http://picow.local */
const char *myHostname = "picow";
/* Don't set this wifi credentials. They are configurated at runtime and stored on EEPROM */
/* Don't set this wifi credentials. They are configured at runtime and stored on EEPROM */
char ssid[33] = "";
char password[65] = "";
@@ -12,7 +12,7 @@
#include <task.h>
#include <semphr.h>
#define SERIAL_PORT Serial1
#define SERIAL_PORT Serial
#define BLINK_ON_TIME 250
#define BLINK_OFF_TIME 500
@@ -58,6 +58,7 @@ void led_ON(void *pvParameters)
digitalWrite(LED_BUILTIN, HIGH);
delay(BLINK_ON_TIME);
xSemaphoreGive( xSemaphore );
delay(1);
}
}
@@ -71,6 +72,7 @@ void led_OFF(void *pvParameters)
digitalWrite(LED_BUILTIN, LOW);
delay(BLINK_OFF_TIME);
xSemaphoreGive( xSemaphore );
delay(1);
}
}
-2
View File
@@ -19,8 +19,6 @@ setCanSendNowCB KEYWORD2
startHID KEYWORD2
connected KEYWORD2
send KEYWORD2
lockBluetooth KEYWORD2
unlockBluetooth KEYWORD2
getCID KEYWORD2
setBattery KEYWORD2
@@ -20,4 +20,80 @@
#include "PicoBluetoothBLEHID.h"
#define CCALLBACKNAME _BLEHIDCB
#include <ctocppcallback.h>
#define PACKETHANDLERCB(class, cbFcn) \
(CCALLBACKNAME<void(uint8_t, uint16_t, uint8_t*, uint16_t), __COUNTER__>::func = std::bind(&class::cbFcn, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4), \
static_cast<btstack_packet_handler_t>(CCALLBACKNAME<void(uint8_t, uint16_t, uint8_t*, uint16_t), __COUNTER__ - 1>::callback))
bool PicoBluetoothBLEHID_::startHID(const char *localName, const char *hidName, uint16_t appearance, const uint8_t *hidDescriptor, uint16_t hidDescriptorSize, int battery) {
if (_running) {
return false;
}
_running = true;
_buildAdvData(localName, appearance);
_buildAttdb(hidName);
_battery = battery;
// Setup L2CAP
l2cap_init();
// Setup SM
sm_init();
sm_set_io_capabilities(IO_CAPABILITY_NO_INPUT_NO_OUTPUT);
sm_set_authentication_requirements(SM_AUTHREQ_SECURE_CONNECTION | SM_AUTHREQ_BONDING);
// Setup ATT server
att_server_init(_attdb, NULL, NULL);
// Setup battery service
battery_service_server_init(battery);
// Setup device information service
device_information_service_server_init();
// Setup HID Device service, depending on activated reports
uint8_t numreports = 1; //start with 1 (feature report)
if (__BLEInstallKeyboard) {
numreports += 2; //add keycodes + consumer keys
}
if (__BLEInstallMouse) {
numreports += 1;
}
if (__BLEInstallJoystick) {
numreports += 1;
}
//allocate memory for hid reports
_reportStorage = (hids_device_report_t *) malloc(sizeof(hids_device_report_t) * numreports);
hids_device_init_with_storage(0, hidDescriptor, hidDescriptorSize, numreports, _reportStorage);
// Setup advertisements
uint16_t adv_int_min = 0x0030;
uint16_t adv_int_max = 0x0030;
uint8_t adv_type = 0;
bd_addr_t null_addr;
memset(null_addr, 0, 6);
gap_advertisements_set_params(adv_int_min, adv_int_max, adv_type, 0, null_addr, 0x07, 0x00);
gap_advertisements_set_data(_advDataLen, _advData);
gap_advertisements_enable(1);
// Register for HCI events
_hci_event_callback_registration.callback = PACKETHANDLERCB(PicoBluetoothBLEHID_, packetHandler);
hci_add_event_handler(&_hci_event_callback_registration);
// Register for SM events
_sm_event_callback_registration.callback = PACKETHANDLERCB(PicoBluetoothBLEHID_, packetHandler);
sm_add_event_handler(&_sm_event_callback_registration);
// Register for HIDS events
hids_device_register_packet_handler(PACKETHANDLERCB(PicoBluetoothBLEHID_, packetHandler));
// GO!
hci_power_control(HCI_POWER_ON);
return true;
}
PicoBluetoothBLEHID_ PicoBluetoothBLEHID;
@@ -79,79 +79,9 @@ public:
_onCanSendNow = cb;
}
bool startHID(const char *localName, const char *hidName, uint16_t appearance, const uint8_t *hidDescriptor, uint16_t hidDescriptorSize, int battery = 100) {
if (_running) {
return false;
}
_running = true;
_buildAdvData(localName, appearance);
_buildAttdb(hidName);
_battery = battery;
// Setup L2CAP
l2cap_init();
// Setup SM
sm_init();
sm_set_io_capabilities(IO_CAPABILITY_NO_INPUT_NO_OUTPUT);
sm_set_authentication_requirements(SM_AUTHREQ_SECURE_CONNECTION | SM_AUTHREQ_BONDING);
// Setup ATT server
att_server_init(_attdb, NULL, NULL);
// Setup battery service
battery_service_server_init(battery);
// Setup device information service
device_information_service_server_init();
// Setup HID Device service, depending on activated reports
uint8_t numreports = 1; //start with 1 (feature report)
if (__BLEInstallKeyboard) {
numreports += 2; //add keycodes + consumer keys
}
if (__BLEInstallMouse) {
numreports += 1;
}
if (__BLEInstallJoystick) {
numreports += 1;
}
//allocate memory for hid reports
_reportStorage = (hids_device_report_t *) malloc(sizeof(hids_device_report_t) * numreports);
hids_device_init_with_storage(0, hidDescriptor, hidDescriptorSize, numreports, _reportStorage);
// Setup advertisements
uint16_t adv_int_min = 0x0030;
uint16_t adv_int_max = 0x0030;
uint8_t adv_type = 0;
bd_addr_t null_addr;
memset(null_addr, 0, 6);
gap_advertisements_set_params(adv_int_min, adv_int_max, adv_type, 0, null_addr, 0x07, 0x00);
gap_advertisements_set_data(_advDataLen, _advData);
gap_advertisements_enable(1);
// Register for HCI events
_hci_event_callback_registration.callback = PacketHandlerWrapper;
hci_add_event_handler(&_hci_event_callback_registration);
// Register for SM events
_sm_event_callback_registration.callback = PacketHandlerWrapper;
sm_add_event_handler(&_sm_event_callback_registration);
// Register for HIDS events
hids_device_register_packet_handler(PacketHandlerWrapper);
// GO!
hci_power_control(HCI_POWER_ON);
return true;
}
static void PacketHandlerWrapper(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t packet_size) {
PicoBluetoothBLEHID.packetHandler(packet_type, channel, packet, packet_size);
}
bool startHID(const char *localName, const char *hidName, uint16_t appearance, const uint8_t *hidDescriptor, uint16_t hidDescriptorSize, int battery = 100);
private:
void packetHandler(uint8_t type, uint16_t channel, uint8_t *packet, uint16_t size) {
uint8_t result;
uint8_t reportID;
@@ -214,14 +144,6 @@ public:
if (result) {
Serial.printf("Error sending %d - report ID: %d\n", result, reportID);
}
//else Serial.printf("Sent report for ID: %d\n",reportID);
#if 0
Serial.printf("Sending report for ID %d, len: %d:\n", reportID, _sendReportLen);
for (uint8_t i = 0; i < _sendReportLen; i++) {
Serial.printf("0x%02X - ", ((const uint8_t *)_sendReport)[i]);
}
Serial.println("");
#endif
break;
default:
break;
@@ -237,7 +159,7 @@ public:
break;
}
}
public:
bool end() {
if (_running) {
hci_power_control(HCI_POWER_OFF);
@@ -259,9 +181,9 @@ public:
_needToSend = true;
_sendReport = rpt;
_sendReportLen = len;
lockBluetooth();
__lockBluetooth();
hids_device_request_can_send_now_event(_con_handle);
unlockBluetooth();
__unlockBluetooth();
while (connected() && _needToSend) {
/* noop busy wait */
}
@@ -276,14 +198,6 @@ public:
return true;
}
static void lockBluetooth() {
async_context_acquire_lock_blocking(cyw43_arch_async_context());
}
static void unlockBluetooth() {
async_context_release_lock(cyw43_arch_async_context());
}
uint8_t *_attdb = nullptr;
int _attdbLen = 0;
@@ -20,4 +20,81 @@
#include "PicoBluetoothHID.h"
#define CCALLBACKNAME _BTHIDCB
#include <ctocppcallback.h>
#define PACKETHANDLERCB(class, cbFcn) \
(CCALLBACKNAME<void(uint8_t, uint16_t, uint8_t*, uint16_t), __COUNTER__>::func = std::bind(&class::cbFcn, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4), \
static_cast<btstack_packet_handler_t>(CCALLBACKNAME<void(uint8_t, uint16_t, uint8_t*, uint16_t), __COUNTER__ - 1>::callback))
bool PicoBluetoothHID_::startHID(const char *localName, const char *hidName, uint16_t hidClass, uint8_t hidSubclass, const uint8_t *hidDescriptor, uint16_t hidDescriptorSize) {
if (_running) {
return false;
}
_running = true;
// Allow finding via inquiry
gap_discoverable_control(1);
// Use Limited Discoverable Mode; Peripheral; Keyboard as CoD
gap_set_class_of_device(hidClass);
// Set local name to be identified - zeroes will be replaced by actual BD ADDR
gap_set_local_name(localName);
// Allow for role switch in general and sniff mode
gap_set_default_link_policy_settings(LM_LINK_POLICY_ENABLE_ROLE_SWITCH | LM_LINK_POLICY_ENABLE_SNIFF_MODE);
// Allow for role switch on outgoing connections - this allow HID Host to become master when we re-connect to it
gap_set_allow_role_switch(true);
// L2CAP
l2cap_init();
#ifdef ENABLE_BLE
// Initialize LE Security Manager. Needed for cross-transport key derivation
sm_init();
#endif
// SDP Server
sdp_init();
bzero(_hid_service_buffer, sizeof(_hid_service_buffer));
const uint8_t hid_boot_device = 0;
const uint8_t hid_virtual_cable = 0;
const uint8_t hid_remote_wake = 1;
const uint8_t hid_reconnect_initiate = 1;
const uint8_t hid_normally_connectable = 1;
// When not set to 0xffff, sniff and sniff subrating are enabled
const uint16_t host_max_latency = 1600;
const uint16_t host_min_timeout = 3200;
hid_sdp_record_t hid_params = {
hidClass, hidSubclass,
hid_virtual_cable, hid_remote_wake,
hid_reconnect_initiate, (bool)hid_normally_connectable,
(bool)hid_boot_device,
host_max_latency, host_min_timeout,
3200,
hidDescriptor,
hidDescriptorSize,
hidName
};
hid_create_sdp_record(_hid_service_buffer, 0x10001, &hid_params);
sdp_register_service(_hid_service_buffer);
// See https://www.bluetooth.com/specifications/assigned-numbers/company-identifiers if you don't have a USB Vendor ID and need a Bluetooth Vendor ID
// device info: BlueKitchen GmbH, product 1, version 1
device_id_create_sdp_record(_device_id_sdp_service_buffer, 0x10003, DEVICE_ID_VENDOR_ID_SOURCE_BLUETOOTH, BLUETOOTH_COMPANY_ID_BLUEKITCHEN_GMBH, 1, 1);
sdp_register_service(_device_id_sdp_service_buffer);
// HID Device
hid_device_init(hid_boot_device, hidDescriptorSize, hidDescriptor);
// register for HCI events
_hci_event_callback_registration.callback = PACKETHANDLERCB(PicoBluetoothHID_, packetHandler);
hci_add_event_handler(&_hci_event_callback_registration);
// register for HID events
hid_device_register_packet_handler(PACKETHANDLERCB(PicoBluetoothHID_, packetHandler));
hci_power_control(HCI_POWER_ON);
return true;
}
PicoBluetoothHID_ PicoBluetoothHID;
+5 -84
View File
@@ -68,80 +68,9 @@ public:
_onCanSendNow = cb;
}
bool startHID(const char *localName, const char *hidName, uint16_t hidClass, uint8_t hidSubclass, const uint8_t *hidDescriptor, uint16_t hidDescriptorSize) {
if (_running) {
return false;
}
_running = true;
// Allow finding via inquiry
gap_discoverable_control(1);
// Use Limited Discoverable Mode; Peripheral; Keyboard as CoD
gap_set_class_of_device(hidClass);
// Set local name to be identified - zeroes will be replaced by actual BD ADDR
gap_set_local_name(localName);
// Allow for role switch in general and sniff mode
gap_set_default_link_policy_settings(LM_LINK_POLICY_ENABLE_ROLE_SWITCH | LM_LINK_POLICY_ENABLE_SNIFF_MODE);
// Allow for role switch on outgoing connections - this allow HID Host to become master when we re-connect to it
gap_set_allow_role_switch(true);
// L2CAP
l2cap_init();
#ifdef ENABLE_BLE
// Initialize LE Security Manager. Needed for cross-transport key derivation
sm_init();
#endif
// SDP Server
sdp_init();
bzero(_hid_service_buffer, sizeof(_hid_service_buffer));
const uint8_t hid_boot_device = 0;
const uint8_t hid_virtual_cable = 0;
const uint8_t hid_remote_wake = 1;
const uint8_t hid_reconnect_initiate = 1;
const uint8_t hid_normally_connectable = 1;
// When not set to 0xffff, sniff and sniff subrating are enabled
const uint16_t host_max_latency = 1600;
const uint16_t host_min_timeout = 3200;
hid_sdp_record_t hid_params = {
hidClass, hidSubclass,
hid_virtual_cable, hid_remote_wake,
hid_reconnect_initiate, (bool)hid_normally_connectable,
(bool)hid_boot_device,
host_max_latency, host_min_timeout,
3200,
hidDescriptor,
hidDescriptorSize,
hidName
};
hid_create_sdp_record(_hid_service_buffer, 0x10001, &hid_params);
sdp_register_service(_hid_service_buffer);
// See https://www.bluetooth.com/specifications/assigned-numbers/company-identifiers if you don't have a USB Vendor ID and need a Bluetooth Vendor ID
// device info: BlueKitchen GmbH, product 1, version 1
device_id_create_sdp_record(_device_id_sdp_service_buffer, 0x10003, DEVICE_ID_VENDOR_ID_SOURCE_BLUETOOTH, BLUETOOTH_COMPANY_ID_BLUEKITCHEN_GMBH, 1, 1);
sdp_register_service(_device_id_sdp_service_buffer);
// HID Device
hid_device_init(hid_boot_device, hidDescriptorSize, hidDescriptor);
// register for HCI events
_hci_event_callback_registration.callback = PacketHandlerWrapper;
hci_add_event_handler(&_hci_event_callback_registration);
// register for HID events
hid_device_register_packet_handler(PacketHandlerWrapper);
hci_power_control(HCI_POWER_ON);
return true;
}
static void PacketHandlerWrapper(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t packet_size) {
PicoBluetoothHID.packetHandler(packet_type, channel, packet, packet_size);
}
bool startHID(const char *localName, const char *hidName, uint16_t hidClass, uint8_t hidSubclass, const uint8_t *hidDescriptor, uint16_t hidDescriptorSize);
private:
void packetHandler(uint8_t type, uint16_t channel, uint8_t *packet, uint16_t size) {
uint8_t status;
if (type != HCI_EVENT_PACKET) {
@@ -198,7 +127,7 @@ public:
}
}
}
public:
bool end() {
if (_running) {
hci_power_control(HCI_POWER_OFF);
@@ -217,23 +146,15 @@ public:
_sendReportID = id;
_sendReport = rpt;
_sendReportLen = len;
lockBluetooth();
__lockBluetooth();
hid_device_request_can_send_now_event(getCID());
unlockBluetooth();
__unlockBluetooth();
while (connected() && _needToSend) {
/* noop busy wait */
}
return connected();
}
static void lockBluetooth() {
async_context_acquire_lock_blocking(cyw43_arch_async_context());
}
static void unlockBluetooth() {
async_context_release_lock(cyw43_arch_async_context());
}
uint16_t getCID() {
return _hid_cid;
}
+3
View File
@@ -294,6 +294,9 @@ static inline void pio_i2s_in_program_init(PIO pio, uint sm, uint offset, uint d
pio_sm_set_pins(pio, sm, 0); // clear pins
pio_sm_exec(pio, sm, pio_encode_set(pio_y, bits - 2));
pio_sm_exec(pio, sm, pio_encode_in(pio_pins, bits)); // Shift in 1st L data
pio_sm_exec(pio, sm, pio_encode_in(pio_pins, bits - 1)); // Shift in 1st R data modulo one bit, avoiding bit shift from #2037
}
%}
+2
View File
@@ -378,6 +378,8 @@ static inline void pio_i2s_in_program_init(PIO pio, uint sm, uint offset, uint d
pio_sm_set_pindirs_with_mask(pio, sm, pin_mask, pin_mask);
pio_sm_set_pins(pio, sm, 0); // clear pins
pio_sm_exec(pio, sm, pio_encode_set(pio_y, bits - 2));
pio_sm_exec(pio, sm, pio_encode_in(pio_pins, bits)); // Shift in 1st L data
pio_sm_exec(pio, sm, pio_encode_in(pio_pins, bits - 1)); // Shift in 1st R data modulo one bit, avoiding bit shift from #2037
}
#endif
+1 -1
View File
@@ -1336,7 +1336,7 @@ bool MDNSResponder::_writeMDNSHostDomain(const char* p_pcHostname, bool p_bPrepe
A very simple form of name compression is applied here: see '_writeMDNSHostDomain'
The cache differentiates of course between service domains which includes
the instance name (p_bIncludeName is set) and thoose who don't.
the instance name (p_bIncludeName is set) and those who don't.
*/
bool
+3 -4
View File
@@ -25,9 +25,11 @@
class PDMClass {
public:
PDMClass(int dinPin, int clkPin, int pwrPin);
PDMClass(int dinPin, int clkPin);
virtual ~PDMClass();
void setDIN(int dinPin);
void setCLK(int clkPin);
int begin(int channels, int sampleRate);
void end();
@@ -49,7 +51,6 @@ public:
private:
int _dinPin;
int _clkPin;
int _pwrPin;
int _channels;
int _samplerate;
@@ -70,6 +71,4 @@ private:
void (*_onReceive)(void);
};
#ifdef PIN_PDM_DIN
extern PDMClass PDM;
#endif
+22 -4
View File
@@ -36,10 +36,9 @@ extern "C" {
}
PDMClass::PDMClass(int dinPin, int clkPin, int pwrPin) :
PDMClass::PDMClass(int dinPin, int clkPin) :
_dinPin(dinPin),
_clkPin(clkPin),
_pwrPin(pwrPin),
_onReceive(NULL),
_gain(-1),
_channels(-1),
@@ -55,6 +54,14 @@ PDMClass::PDMClass(int dinPin, int clkPin, int pwrPin) :
PDMClass::~PDMClass() {
}
void PDMClass::setCLK(int clkPin) {
_clkPin = clkPin;
}
void PDMClass::setDIN(int dinPin) {
_dinPin = dinPin;
}
int PDMClass::begin(int channels, int sampleRate) {
if (_init == 1) {
@@ -62,6 +69,11 @@ int PDMClass::begin(int channels, int sampleRate) {
return 0;
}
if (_dinPin == -1 || _clkPin == -1) {
//ERROR: please call setDIN/setCLK first
return 0;
}
//_channels = channels; // only one channel available
// clear the final buffers
@@ -228,8 +240,14 @@ void PDMClass::IrqHandler(bool halftranfer) {
_onReceive();
}
}
#ifdef PIN_PDM_DIN
PDMClass PDM(PIN_PDM_DIN, PIN_PDM_CLK, -1);
#ifndef PIN_PDM_DIN
#define PIN_PDM_DIN -1
#endif // PIN_PDM_DIN
//
#ifndef PIN_PDM_CLK
#define PIN_PDM_CLK -1
#endif // PIN_PDM_CLK
PDMClass PDM(PIN_PDM_DIN, PIN_PDM_CLK);
@@ -0,0 +1,93 @@
// Shows how to use SPISlave on a single device in asynchronous mode
// Core0 runs as an SPI master and initiates a transmission to the slave
// Core1 runs the SPI Slave mode and provides a unique reply to messages from the master
//
// Released to the public domain 2024 by Earle F. Philhower, III <earlephilhower@yahoo.com>
#include <SPI.h>
#include <SPISlave.h>
// Wiring:
// Master RX GP0 <-> GP11 Slave TX
// Master CS GP1 <-> GP9 Slave CS
// Master CK GP2 <-> GP10 Slave CK
// Master TX GP3 <-> GP8 Slave RX
SPISettings spisettings(1000000, MSBFIRST, SPI_MODE0);
// Core 0 will be SPI master
void setup() {
SPI.setRX(0);
SPI.setCS(1);
SPI.setSCK(2);
SPI.setTX(3);
SPI.begin(true);
delay(5000);
}
int transmits = 0;
void loop() {
char msg[42];
int loops = 0;
memset(msg, 0, sizeof(msg));
sprintf(msg, "What's up? This is transmission %d", transmits);
Serial.printf("\n\nM-SEND: '%s'\n", msg);
SPI.beginTransaction(spisettings);
SPI.transferAsync(msg, msg, sizeof(msg));
while (!SPI.finishedAsync()) {
loops++;
}
SPI.endTransaction();
Serial.printf("M-RECV: '%s', idle loops %d\n", msg, loops);
transmits++;
delay(5000);
}
// Core 1 will be SPI slave
volatile bool recvBuffReady = false;
char recvBuff[42] = "";
int recvIdx = 0;
void recvCallback(uint8_t *data, size_t len) {
memcpy(recvBuff + recvIdx, data, len);
recvIdx += len;
if (recvIdx == sizeof(recvBuff)) {
recvBuffReady = true;
recvIdx = 0;
}
}
int sendcbs = 0;
// Note that the buffer needs to be long lived, the SPISlave doesn't copy it. So no local stack variables, only globals or heap(malloc/new) allocations.
char sendBuff[42];
void sentCallback() {
memset(sendBuff, 0, sizeof(sendBuff));
sprintf(sendBuff, "Slave to Master Xmission %d", sendcbs++);
SPISlave1.setData((uint8_t*)sendBuff, sizeof(sendBuff));
}
// Note that we use SPISlave1 here **not** because we're running on
// Core 1, but because SPI0 is being used already. You can use
// SPISlave or SPISlave1 on any core.
void setup1() {
SPISlave1.setRX(8);
SPISlave1.setCS(9);
SPISlave1.setSCK(10);
SPISlave1.setTX(11);
// Ensure we start with something to send...
sentCallback();
// Hook our callbacks into the slave
SPISlave1.onDataRecv(recvCallback);
SPISlave1.onDataSent(sentCallback);
SPISlave1.begin(spisettings);
delay(3000);
Serial.println("S-INFO: SPISlave started");
}
void loop1() {
if (recvBuffReady) {
Serial.printf("S-RECV: '%s'\n", recvBuff);
recvBuffReady = false;
}
}
+3
View File
@@ -26,6 +26,9 @@ setRX KEYWORD2
setTX KEYWORD2
setSCK KEYWORD2
setCS KEYWORD2
transferAsync KEYWORD2
finishedAsync KEYWORD2
abortAsync KEYWORD2
#######################################
# Constants (LITERAL1)
+99 -1
View File
@@ -19,6 +19,7 @@
*/
#include "SPI.h"
#include <hardware/dma.h>
#include <hardware/spi.h>
#include <hardware/gpio.h>
#include <hardware/structs/iobank0.h>
@@ -218,7 +219,7 @@ void SPIClassRP2040::beginTransaction(SPISettings settings) {
void SPIClassRP2040::endTransaction(void) {
noInterrupts(); // Avoid race condition so the GPIO IRQs won't come back until all state is restored
DEBUGSPI("SPI::endTransaction()\n");
// Re-enablke IRQs
// Re-enable IRQs
for (auto entry : _usingIRQs) {
int gpio = entry.first;
int mode = entry.second;
@@ -230,6 +231,103 @@ void SPIClassRP2040::endTransaction(void) {
interrupts();
}
bool SPIClassRP2040::transferAsync(const void *send, void *recv, size_t bytes) {
DEBUGSPI("SPI::transferAsync(%p, %p, %d)\n", send, recv, bytes);
const uint8_t *txbuff = reinterpret_cast<const uint8_t *>(send);
uint8_t *rxbuff = reinterpret_cast<uint8_t *>(recv);
_dummy = 0xffffffff;
if (!_initted || (!send && !recv)) {
return false;
}
_channelDMA = dma_claim_unused_channel(false);
if (_channelDMA == -1) {
return false;
}
_channelSendDMA = dma_claim_unused_channel(false);
if (_channelSendDMA == -1) {
dma_channel_unclaim(_channelDMA);
return false;
}
if (send && (_spis.getBitOrder() != MSBFIRST)) {
_dmaBuffer = (uint8_t *)malloc(bytes);
if (!_dmaBuffer) {
dma_channel_unclaim(_channelDMA);
dma_channel_unclaim(_channelSendDMA);
return false;
}
for (size_t i = 0; i < bytes; i++) {
_dmaBuffer[i] = reverseByte(txbuff[i]);
}
}
_dmaBytes = bytes;
_rxFinalBuffer = rxbuff;
hw_write_masked(&spi_get_hw(_spi)->cr0, (8 - 1) << SPI_SSPCR0_DSS_LSB, SPI_SSPCR0_DSS_BITS); // Fast set to 8-bits
dma_channel_config c = dma_channel_get_default_config(_channelSendDMA);
channel_config_set_transfer_data_size(&c, DMA_SIZE_8); // 8b transfers into SPI FIFO
channel_config_set_read_increment(&c, send ? true : false); // Reading incrementing addresses
channel_config_set_write_increment(&c, false); // Writing to the same FIFO address
channel_config_set_dreq(&c, spi_get_dreq(_spi, true)); // Wait for the TX FIFO specified
channel_config_set_chain_to(&c, _channelSendDMA); // No chaining
channel_config_set_irq_quiet(&c, true); // No need for IRQ
dma_channel_configure(_channelSendDMA, &c, &spi_get_hw(_spi)->dr, !send ? (uint8_t *)&_dummy : (_spis.getBitOrder() != MSBFIRST ? _dmaBuffer : txbuff), bytes, false);
c = dma_channel_get_default_config(_channelDMA);
channel_config_set_transfer_data_size(&c, DMA_SIZE_8); // 8b transfers into SPI FIFO
channel_config_set_read_increment(&c, false); // Reading same FIFO address
channel_config_set_write_increment(&c, recv ? true : false); // Writing to the buffer
channel_config_set_dreq(&c, spi_get_dreq(_spi, false)); // Wait for the RX FIFO specified
channel_config_set_chain_to(&c, _channelDMA); // No chaining
channel_config_set_irq_quiet(&c, true); // No need for IRQ
dma_channel_configure(_channelDMA, &c, !recv ? (uint8_t *)&_dummy : rxbuff, &spi_get_hw(_spi)->dr, bytes, false);
spi_get_hw(_spi)->dmacr = 1 | (1 << 1); // TDMAE | RDMAE
dma_channel_start(_channelDMA);
dma_channel_start(_channelSendDMA);
return true;
}
bool SPIClassRP2040::finishedAsync() {
if (!_initted) {
return true;
}
if (dma_channel_is_busy(_channelDMA) || (spi_get_hw(_spi)->sr & SPI_SSPSR_BSY_BITS)) {
return false;
}
dma_channel_cleanup(_channelDMA);
dma_channel_unclaim(_channelDMA);
dma_channel_cleanup(_channelSendDMA);
dma_channel_unclaim(_channelSendDMA);
spi_get_hw(_spi)->dmacr = 0;
if (_spis.getBitOrder() != MSBFIRST) {
for (int i = 0; i < _dmaBytes; i++) {
_rxFinalBuffer[i] = reverseByte(_rxFinalBuffer[i]);
}
free(_dmaBuffer);
_dmaBuffer = nullptr;
}
return true;
}
void SPIClassRP2040::abortAsync() {
if (!_initted) {
return;
}
dma_channel_cleanup(_channelDMA);
dma_channel_unclaim(_channelDMA);
dma_channel_cleanup(_channelSendDMA);
dma_channel_unclaim(_channelSendDMA);
spi_get_hw(_spi)->dmacr = 0;
free(_dmaBuffer);
_dmaBuffer = nullptr;
}
bool SPIClassRP2040::setRX(pin_size_t pin) {
constexpr uint32_t valid[2] = { __bitset({0, 4, 16, 20}) /* SPI0 */,
__bitset({8, 12, 24, 28}) /* SPI1 */
+21
View File
@@ -39,15 +39,28 @@ public:
// Sends one buffer and receives into another, much faster! can set rx or txbuf to nullptr
void transfer(const void *txbuf, void *rxbuf, size_t count) override;
// DMA/asynchronous transfers. Do not combime with synchronous runs or bad stuff will happen
// All buffers must be valid for entire DMA and not touched until `finished()` returns true.
bool transferAsync(const void *send, void *recv, size_t bytes);
bool finishedAsync(); // Call to check if the async operations is completed and the buffer can be reused/read
void abortAsync(); // Cancel an outstanding async operation
// Call before/after every complete transaction
void beginTransaction(SPISettings settings) override;
void endTransaction(void) override;
// Assign pins, call before begin()
bool setRX(pin_size_t pin);
inline bool setMISO(pin_size_t pin) {
return setRX(pin);
}
bool setCS(pin_size_t pin);
bool setSCK(pin_size_t pin);
bool setTX(pin_size_t pin);
inline bool setMOSI(pin_size_t pin) {
return setTX(pin);
}
// Call once to init/deinit SPI class, select pins, etc.
virtual void begin() override {
@@ -86,6 +99,14 @@ private:
bool _initted; // Transaction begun
std::map<int, int> _usingIRQs;
// DMA
int _channelDMA;
int _channelSendDMA;
uint8_t *_dmaBuffer = nullptr;
int _dmaBytes;
uint8_t *_rxFinalBuffer;
uint32_t _dummy;
};
extern SPIClassRP2040 SPI;
+15 -8
View File
@@ -20,6 +20,13 @@
#include "SerialBT.h"
#include <CoreMutex.h>
#define CCALLBACKNAME _SERIALBTCB
#include <ctocppcallback.h>
#define PACKETHANDLERCB(class, cbFcn) \
(CCALLBACKNAME<void(uint8_t, uint16_t, uint8_t*, uint16_t), __COUNTER__>::func = std::bind(&class::cbFcn, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4), \
static_cast<btstack_packet_handler_t>(CCALLBACKNAME<void(uint8_t, uint16_t, uint8_t*, uint16_t), __COUNTER__ - 1>::callback))
bool SerialBT_::setFIFOSize(size_t size) {
if (!size || _running) {
@@ -48,7 +55,7 @@ void SerialBT_::begin(unsigned long baud, uint16_t config) {
_reader = 0;
// register for HCI events
_hci_event_callback_registration.callback = &SerialBT_::PacketHandlerWrapper;
_hci_event_callback_registration.callback = PACKETHANDLERCB(SerialBT_, packetHandler);
hci_add_event_handler(&_hci_event_callback_registration);
l2cap_init();
@@ -59,7 +66,7 @@ void SerialBT_::begin(unsigned long baud, uint16_t config) {
#endif
rfcomm_init();
rfcomm_register_service(SerialBT_::PacketHandlerWrapper, RFCOMM_SERVER_CHANNEL, 0xffff); // reserved channel, mtu limited by l2cap
rfcomm_register_service(PACKETHANDLERCB(SerialBT_, packetHandler), RFCOMM_SERVER_CHANNEL, 0xffff); // reserved channel, mtu limited by l2cap
// init SDP, create record for SPP and register with SDP
sdp_init();
@@ -84,9 +91,9 @@ void SerialBT_::end() {
_running = false;
hci_power_control(HCI_POWER_OFF);
lockBluetooth();
__lockBluetooth();
delete[] _queue;
unlockBluetooth();
__unlockBluetooth();
}
int SerialBT_::peek() {
@@ -121,10 +128,10 @@ bool SerialBT_::overflow() {
return false;
}
lockBluetooth();
__lockBluetooth();
bool ovf = _overflow;
_overflow = false;
unlockBluetooth();
__unlockBluetooth();
return ovf;
}
@@ -160,9 +167,9 @@ size_t SerialBT_::write(const uint8_t *p, size_t len) {
}
_writeBuff = p;
_writeLen = len;
lockBluetooth();
__lockBluetooth();
rfcomm_request_can_send_now_event(_channelID);
unlockBluetooth();
__unlockBluetooth();
while (_connected && _writeLen) {
/* noop busy wait */
}
+1 -14
View File
@@ -60,26 +60,13 @@ public:
(void) unused;
}
static void PacketHandlerWrapper(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t packet_size) {
SerialBT.packetHandler(packet_type, channel, packet, packet_size);
}
void packetHandler(uint8_t type, uint16_t channel, uint8_t *packet, uint16_t size);
static void lockBluetooth() {
async_context_acquire_lock_blocking(cyw43_arch_async_context());
}
static void unlockBluetooth() {
async_context_release_lock(cyw43_arch_async_context());
}
private:
bool _running = false;
mutex_t _mutex;
bool _overflow = false;
volatile bool _connected = false;
void packetHandler(uint8_t type, uint16_t channel, uint8_t *packet, uint16_t size);
// Lockless, IRQ-handled circular queue
uint32_t _writer;
+11 -2
View File
@@ -9,12 +9,20 @@
WiFi KEYWORD1
WiFiUdp KEYWORD1
WiFiClient KEYWORD1
WiFiSSLClient KEYWORD1
WiFiClientSecure KEYWORD1
WiFiServer KEYWORD1
WiFiServerSecure KEYWORD1
WiFiUDP KEYWORD1
WiFiMulti KEYWORD1
NTP KEYWORD1
BearSSL KEYWORD1
PublicKey KEYWORD1
PrivateKey KEYWORD1
X509List KEYWORD1
Session KEYWORD1
ServerSessions KEYWORD1
HashSHA256 KEYWORD1
SigningVerifier KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
@@ -38,6 +46,7 @@ macAddress KEYWORD2
localIP KEYWORD2
subnetMask KEYWORD2
gatewayIP KEYWORD2
scanNetworks KEYWORD2
SSID KEYWORD2
BSSID KEYWORD2
RSSI KEYWORD2
+2
View File
@@ -34,6 +34,8 @@
static CYW43lwIP _wifi(1);
#elif defined(ESPHOSTSPI)
static ESPHostLwIP _wifi;
#elif defined(WINC1501_SPI)
static WINC1500LwIP _wifi;
#else
static NoDriverLwIP _wifi;
#endif
+2
View File
@@ -27,6 +27,8 @@
#include <lwIP_CYW43.h>
#elif defined(ESPHOSTSPI)
#include <lwIP_ESPHost.h>
#elif defined(WINC1501_SPI)
#include <lwIP_WINC1500.h>
#else
#include "utility/lwIP_nodriver.h"
#endif
@@ -0,0 +1,90 @@
// Simple asynchronous I2C master and slave demo - Earle F. Philhower, III
// Released into the public domain.
//
// Using both onboard I2C interfaces, have one master and one slave
// and send data both ways between them.
//
// Uses the async Wire calls to allow applications to do other work while
// I2C transactions are ongoing.
//
// To run, connect GPIO0 to GPIO2, GPIO1 to GPIO3 on a single Pico
#include <Wire.h>
void setup() {
Serial.begin(115200);
delay(5000);
Wire.setSDA(0);
Wire.setSCL(1);
Wire.begin();
Wire1.setSDA(2);
Wire1.setSCL(3);
Wire1.begin(0x30);
Wire1.onReceive(recv);
Wire1.onRequest(req);
}
static char buff[100];
void loop() {
static int p;
char b[90];
int loops;
// Write a value over I2C to the slave
Serial.println("\n\nSending...");
sprintf(b, "This buffer is larger than the I2C FIFO by a whole lot, Pass #%d", p++);
Wire.writeAsync(0x30, b, strlen(b), true);
// A real application would go do some useful work here and check the
// finishedAsync value when it needs the I2S operation to be completed
// Here' we'll just increment a counter to show how much work could be done...
loops = 0;
while (!Wire.finishedAsync()) {
loops++;
}
Serial.printf("Write idle loops: %d\n", loops);
// Ensure the slave processing is done and print it out
delay(1000);
Serial.printf("buff: '%s'\n", buff);
Serial.printf("Receiving...\n");
// Read from the slave and print out
bzero(b, sizeof(b));
Wire.readAsync(0x30, b, 73, true);
loops = 0;
while (!Wire.finishedAsync()) {
loops++;
}
Serial.printf("Read idle loops: %d\n", loops);
Serial.print("recv: '");
for (int i = 0; i < 73; i++) {
Serial.print(b[i]);
}
Serial.println("'");
delay(1000);
}
// These are called in an **INTERRUPT CONTEXT** which means NO serial port
// access (i.e. Serial.print is illegal) and no memory allocations, etc.
// Called when the I2C slave gets written to
void recv(int len) {
int i;
// Just stuff the sent bytes into a global the main routine can pick up and use
for (i = 0; i < len; i++) {
buff[i] = Wire1.read();
}
buff[i] = 0;
}
// Called when the I2C slave is read from
void req() {
static int ctr = 765;
char buff[100];
// Return a simple incrementing hex value
sprintf(buff, "Slave responds with a message that's longer than FIFO as well, id #%06X", (ctr++) % 65535);
Wire1.write(buff, 73);
}
+4
View File
@@ -21,6 +21,10 @@ onReceive KEYWORD2
onRequest KEYWORD2
setSDA KEYWORD2
setSCL KEYWORD2
writeAsync KEYWORD2
readAsync KEYWORD2
finishedAsync KEYWORD2
abortAsync KEYWORD2
#######################################
# Instances (KEYWORD2)
+171
View File
@@ -22,6 +22,7 @@
*/
#include <Arduino.h>
#include <hardware/dma.h>
#include <hardware/gpio.h>
#include <hardware/i2c.h>
#include <hardware/irq.h>
@@ -441,6 +442,176 @@ void TwoWire::flush(void) {
}
// DMA/asynchronous transfers. Do not combime with synchronous runs or bad stuff will happen
// All buffers must be valid for entire DMA and not touched until `finished()` returns true.
bool TwoWire::writeAsync(uint8_t address, const void *buffer, size_t bytes, bool sendStop) {
if (!_running || _txBegun || _rxBegun) {
return false;
}
// We need to expand the data to include side-channel start/stop bits for the I2C FIFO
_dmaBuffer = (uint16_t*)malloc(bytes * 2);
if (!_dmaBuffer) {
return false;
}
const uint8_t *srcBuff = (const uint8_t *)buffer;
for (size_t i = 0; i < bytes; i++) {
bool first = i == 0;
bool last = i == bytes - 1;
_dmaBuffer[i] = bool_to_bit(first && _i2c->restart_on_next) << I2C_IC_DATA_CMD_RESTART_LSB | bool_to_bit(last && sendStop) << I2C_IC_DATA_CMD_STOP_LSB | srcBuff[i];
}
_channelDMA = dma_claim_unused_channel(false);
if (_channelDMA == -1) {
free(_dmaBuffer);
_dmaBuffer = nullptr;
return false;
}
dma_channel_config c = dma_channel_get_default_config(_channelDMA);
channel_config_set_transfer_data_size(&c, DMA_SIZE_16); // 16b transfers into I2C FIFO
channel_config_set_read_increment(&c, true); // Reading incrementing addresses
channel_config_set_write_increment(&c, false); // Writing to the same FIFO address
channel_config_set_dreq(&c, i2c_get_dreq(_i2c, true)); // Wait for the TX FIFO specified
channel_config_set_chain_to(&c, _channelDMA); // No chaining
channel_config_set_irq_quiet(&c, true); // No need for IRQ
dma_channel_configure(_channelDMA, &c, &_i2c->hw->data_cmd, _dmaBuffer, bytes, false);
_i2c->hw->enable = 0;
_i2c->hw->tar = address;
_i2c->hw->dma_cr = 1 << 1; // TDMAE
_i2c->hw->enable = 1;
_i2c->restart_on_next = !sendStop;
dma_channel_start(_channelDMA);
_txBegun = true;
return true;
}
bool TwoWire::readAsync(uint8_t address, void *buffer, size_t bytes, bool sendStop) {
if (!_running || _txBegun || _rxBegun) {
return false;
}
_channelDMA = dma_claim_unused_channel(false);
if (_channelDMA == -1) {
return false;
}
_channelSendDMA = dma_claim_unused_channel(false);
if (_channelSendDMA == -1) {
dma_channel_unclaim(_channelDMA);
return false;
}
// We need to expand the data to include side-channel start/stop bits for the I2C FIFO
_dmaBuffer = (uint16_t*)malloc(bytes * 2);
if (!_dmaBuffer) {
return false;
}
// We need to write one entry for every byte we want to read for the sideband info
_dmaSendBuffer = (uint16_t *)malloc(bytes * 2);
if (!_dmaSendBuffer) {
free(_dmaBuffer);
_dmaBuffer = nullptr;
return false;
}
for (size_t i = 0; i < bytes; i++) {
bool first = i == 0;
bool last = i == bytes - 1;
_dmaSendBuffer[i] =
bool_to_bit(first && _i2c->restart_on_next) << I2C_IC_DATA_CMD_RESTART_LSB |
bool_to_bit(last && sendStop) << I2C_IC_DATA_CMD_STOP_LSB |
I2C_IC_DATA_CMD_CMD_BITS; // -> 1 for read
}
_dmaBytes = bytes;
_rxFinalBuffer = (uint8_t *)buffer;
dma_channel_config c = dma_channel_get_default_config(_channelSendDMA);
channel_config_set_transfer_data_size(&c, DMA_SIZE_16); // 16b transfers into I2C FIFO
channel_config_set_read_increment(&c, true); // Reading incrementing addresses
channel_config_set_write_increment(&c, false); // Writing to the same FIFO address
channel_config_set_dreq(&c, i2c_get_dreq(_i2c, true)); // Wait for the TX FIFO specified
channel_config_set_chain_to(&c, _channelSendDMA); // No chaining
channel_config_set_irq_quiet(&c, true); // No need for IRQ
dma_channel_configure(_channelSendDMA, &c, &_i2c->hw->data_cmd, _dmaSendBuffer, bytes, false);
c = dma_channel_get_default_config(_channelDMA);
channel_config_set_transfer_data_size(&c, DMA_SIZE_16); // 16b transfers into I2C FIFO
channel_config_set_read_increment(&c, false); // Reading same FIFO address
channel_config_set_write_increment(&c, true); // Writing to the buffer
channel_config_set_dreq(&c, i2c_get_dreq(_i2c, false)); // Wait for the RX FIFO specified
channel_config_set_chain_to(&c, _channelDMA); // No chaining
channel_config_set_irq_quiet(&c, true); // No need for IRQ
dma_channel_configure(_channelDMA, &c, _dmaBuffer, &_i2c->hw->data_cmd, bytes, false);
_i2c->hw->enable = 0;
_i2c->hw->tar = address;
_i2c->hw->dma_cr = 1 | (1 << 1); // TDMAE | RDMAE
_i2c->hw->enable = 1;
_i2c->restart_on_next = !sendStop;
dma_channel_start(_channelDMA);
dma_channel_start(_channelSendDMA);
_rxBegun = true;
return true;
}
bool TwoWire::finishedAsync() {
if (!_running || !_dmaBuffer) {
return true;
}
if (dma_channel_is_busy(_channelDMA)) {
return false;
}
if (_txBegun) {
if (_i2c->hw->txflr) {
return false;
}
dma_channel_cleanup(_channelDMA);
dma_channel_unclaim(_channelDMA);
_i2c->hw->dma_cr = 0;
free(_dmaBuffer);
_dmaBuffer = nullptr;
_txBegun = false;
return true;
} else if (_rxBegun) {
// For RX, don't care if more data in FIFO. The DMA read is done for the size requested
dma_channel_cleanup(_channelDMA);
dma_channel_unclaim(_channelDMA);
dma_channel_cleanup(_channelSendDMA);
dma_channel_unclaim(_channelSendDMA);
_i2c->hw->dma_cr = 0;
// Need to convert from x16 to x8, strip off the status bits
for (auto i = 0; i < _dmaBytes; i++) {
_rxFinalBuffer[i] = _dmaBuffer[i] & 0xff;
}
free(_dmaBuffer);
_dmaBuffer = nullptr;
free(_dmaSendBuffer);
_dmaSendBuffer = nullptr;
_rxBegun = false;
return true;
}
return true;
}
void TwoWire::abortAsync() {
if (!_running || !_dmaBuffer) {
return;
}
dma_channel_cleanup(_channelDMA);
dma_channel_unclaim(_channelDMA);
if (_rxBegun) {
dma_channel_cleanup(_channelSendDMA);
dma_channel_unclaim(_channelSendDMA);
}
_i2c->hw->dma_cr = 0;
free(_dmaBuffer);
_dmaBuffer = nullptr;
free(_dmaSendBuffer);
_dmaSendBuffer = nullptr;
_rxBegun = false;
_txBegun = false;
}
void TwoWire::onReceive(void(*function)(int)) {
_onReceiveCallback = function;
}
+16
View File
@@ -82,6 +82,13 @@ public:
}
using Print::write;
// DMA/asynchronous transfers. Do not combime with synchronous runs or bad stuff will happen
// All buffers must be valid for entire DMA and not touched until `finished()` returns true.
bool writeAsync(uint8_t address, const void *buffer, size_t bytes, bool sendStop);
bool readAsync(uint8_t address, void *buffer, size_t bytes, bool sendStop);
bool finishedAsync(); // Call to check if the async operations is completed and the buffer can be reused/read
void abortAsync(); // Cancel an outstanding async I2C operation
void setTimeout(uint32_t timeout = 25, bool reset_with_timeout = false); // sets the maximum number of milliseconds to wait
bool getTimeoutFlag(void);
void clearTimeoutFlag(void);
@@ -116,6 +123,15 @@ private:
// TWI clock frequency
static const uint32_t TWI_CLOCK = 100000;
// DMA
bool _rxBegun = false;
int _channelDMA;
int _channelSendDMA;
uint16_t *_dmaBuffer = nullptr;
uint16_t *_dmaSendBuffer = nullptr;
int _dmaBytes;
uint8_t *_rxFinalBuffer;
};
extern TwoWire Wire;
@@ -104,11 +104,14 @@ void CYW43::end() {
_netif = nullptr;
cyw43_deinit(&cyw43_state);
}
int fails = 0;
int calls = 0;
uint16_t CYW43::sendFrame(const uint8_t* data, uint16_t datalen) {
calls++;
if (0 == cyw43_send_ethernet(_self, _itf, datalen, data, false)) {
return datalen;
}
fails++;
return 0;
}
@@ -0,0 +1 @@
-DESPHOST_RESET=D5 -DESPHOST_HANDSHAKE=D7 -DESPHOST_DATA_READY=D6 -DESPHOST_CS=D1 -DESPHOSTSPI=SPI
@@ -0,0 +1,101 @@
/*
This sketch establishes a TCP connection to a "quote of the day" service.
It sends a "hello" message, and then prints received data.
*/
#ifndef ESPHOSTSPI
#error This example requires an ESP-Hosted-FG WiFi chip to be defined, see the documentation
// For example, add this to your boards.local.txt:
// rpipico.build.extra_flags=-DESPHOST_RESET=D5 -DESPHOST_HANDSHAKE=D7 -DESPHOST_DATA_READY=D6 -DESPHOST_CS=D1 -DESPHOSTSPI=SPI
#endif
#include <WiFi.h>
#ifndef STASSID
#define STASSID "your-ssid"
#define STAPSK "your-password"
#endif
const char* ssid = STASSID;
const char* password = STAPSK;
const char* host = "djxmmx.net";
const uint16_t port = 17;
WiFiMulti multi;
void setup() {
Serial.begin(115200);
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
multi.addAP(ssid, password);
if (multi.run() != WL_CONNECTED) {
Serial.println("Unable to connect to network, rebooting in 10 seconds...");
delay(10000);
rp2040.reboot();
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
static bool wait = false;
Serial.print("connecting to ");
Serial.print(host);
Serial.print(':');
Serial.println(port);
// Use WiFiClient class to create TCP connections
WiFiClient client;
if (!client.connect(host, port)) {
Serial.println("connection failed");
delay(5000);
return;
}
// This will send a string to the server
Serial.println("sending data to server");
if (client.connected()) {
client.println("hello from RP2040");
}
// wait for data to be available
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println(">>> Client Timeout !");
client.stop();
delay(60000);
return;
}
}
// Read all the lines of the reply from server and print them to Serial
Serial.println("receiving from remote server");
// not testing 'client.connected()' since we do not need to send data here
while (client.available()) {
char ch = static_cast<char>(client.read());
Serial.print(ch);
}
// Close the connection
Serial.println();
Serial.println("closing connection");
client.stop();
if (wait) {
delay(300000); // execute once every 5 minutes, don't flood remote service
}
wait = true;
}
@@ -0,0 +1,134 @@
/*
Web client
This sketch connects to a website (http://www.google.com)
using an Arduino WIZnet Ethernet shield.
Circuit:
Ethernet shield attached to default SPI pins
created 18 Dec 2009
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe, based on work by Adrian McEwen
*/
#include <SPI.h>
#include <EthernetCompat.h>
ArduinoWiznet5500lwIP Ethernet(D10, SPI, D2);
//ArduinoWiznet5100lwIP Ethernet(D10, SPI, D2);
//ArduinoENC28J60lwIP Ethernet(D10, SPI, D2);
// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128); // numeric IP for Google (no DNS)
char server[] = "www.google.com"; // name address for Google (using DNS)
// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 177);
IPAddress myDns(192, 168, 0, 1);
// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;
// Variables to measure the speed
unsigned long beginMicros, endMicros;
unsigned long byteCount = 0;
bool printWebData = true; // set to false for better speed measurement
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// start the Ethernet connection:
Serial.println("Initialize Ethernet with DHCP:");
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// Check for Ethernet hardware present
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
while (true) {
delay(1); // do nothing, no point running without Ethernet hardware
}
}
if (Ethernet.linkStatus() == LinkOFF) {
Serial.println("Ethernet cable is not connected.");
}
// try to configure using IP address instead of DHCP:
Ethernet.begin(mac, ip, myDns);
} else {
Serial.print(" DHCP assigned IP ");
Serial.println(Ethernet.localIP());
}
// give the Ethernet shield a second to initialize:
delay(1000);
Serial.print("connecting to ");
Serial.print(server);
Serial.println("...");
// if you get a connection, report back via serial:
if (client.connect(server, 80)) {
Serial.print("connected to ");
Serial.println(client.remoteIP());
// Make a HTTP request:
client.println("GET /search?q=arduino HTTP/1.1");
client.println("Host: www.google.com");
client.println("Connection: close");
client.println();
} else {
// if you didn't get a connection to the server:
Serial.println("connection failed");
}
beginMicros = micros();
}
void loop() {
// if there are incoming bytes available
// from the server, read them and print them:
int len = client.available();
if (len > 0) {
byte buffer[80];
if (len > 80) {
len = 80;
}
client.read(buffer, len);
if (printWebData) {
Serial.write(buffer, len); // show in the serial monitor (slows some boards)
}
byteCount = byteCount + len;
}
// if the server's disconnected, stop the client:
if (!client.connected()) {
endMicros = micros();
Serial.println();
Serial.println("disconnecting.");
client.stop();
Serial.print("Received ");
Serial.print(byteCount);
Serial.print(" bytes in ");
float seconds = (float)(endMicros - beginMicros) / 1000000.0;
Serial.print(seconds, 4);
float rate = (float) byteCount / seconds / 1000.0;
Serial.print(", rate = ");
Serial.print(rate);
Serial.print(" kbytes/second");
Serial.println();
// do nothing forevermore:
while (true) {
delay(1);
}
}
}
@@ -0,0 +1,100 @@
#pragma once
#include <LwipIntfDev.h>
#include <W5100lwIP.h>
#include <W5500lwIP.h>
#include <ENC28J60lwIP.h>
#include <WiFiUdp.h>
#include <WiFiClient.h>
#include <WiFiServer.h>
using EthernetUDP = WiFiUDP;
using EthernetClient = WiFiClient;
using EthernetServer = WiFiServer;
enum HardwareStatus {
EthernetNoHardware,
EthernetHardwareFound,
};
template<class RawDev>
class ArduinoEthernet : public LwipIntfDev<RawDev> {
public:
ArduinoEthernet(int8_t cs = SS, SPIClass &spi = SPI, int8_t intr = -1) :
LwipIntfDev<RawDev>(cs, spi, intr) {
_hardwareStatus = EthernetNoHardware;
}
// Arduino-Ethernet API compatibility, order can be either:
// mac, ip, gateway, netmask, dns (esp8266 or natural order)
// mac, ip, dns, gateway, netmask (Arduino legacy)
boolean begin(const uint8_t *macAddress, IPAddress local_ip = IPADDR_NONE, IPAddress arg1 = IPADDR_NONE, IPAddress arg2 = IPADDR_NONE, IPAddress arg3 = IPADDR_NONE) {
if (local_ip.isSet() && local_ip.isV4()) {
// setting auto values using arduino ordering of parameters
if (arg1 == IPADDR_NONE) { // else dns or gw
arg1 = local_ip;
arg1[3] = 1;
}
if (arg2 == IPADDR_NONE) { // else gw or mask
arg2 = local_ip;
arg2[3] = 1;
}
// if arg2 is mask (esp ordering), let DNS IP unconfigured
if (arg3 == IPADDR_NONE && arg2[0] != 255) { // else mask or dns
arg3 = IPAddress(255, 255, 255, 0);
}
}
bool ret = true;
if (local_ip.isSet()) {
ret = LwipIntfDev<RawDev>::config(local_ip, arg1, arg2, arg3);
}
if (ret) {
ret = LwipIntfDev<RawDev>::begin(macAddress);
if (!local_ip.isSet()) {
// Arduino API waits for DHCP answer
while (!LwipIntfDev<RawDev>::connected()) {
delay(100);
}
}
}
if (ret) {
_hardwareStatus = EthernetHardwareFound;
}
return ret;
}
void end() {
ip_addr_copy(LwipIntfDev<RawDev>::_netif.ip_addr, ip_addr_any); // to allow DHCP at next begin
LwipIntfDev<RawDev>::end();
}
void MACAddress(uint8_t *mac) {
LwipIntfDev<RawDev>::macAddress(mac);
}
IPAddress dnsServerIP() const {
return LwipIntfDev<RawDev>::dnsIP(0);
}
void setDnsServerIP(const IPAddress dnsIP) {
LwipIntfDev<RawDev>::setDNS(dnsIP);
}
HardwareStatus hardwareStatus() const {
return _hardwareStatus;
}
int maintain() const {
return 0;
}
protected:
HardwareStatus _hardwareStatus;
};
using ArduinoWiznet5500lwIP = ArduinoEthernet<Wiznet5500>;
using ArduinoWiznet5100lwIP = ArduinoEthernet<Wiznet5100>;
using ArduinoENC28J60lwIP = ArduinoEthernet<ENC28J60>;
+7 -2
View File
@@ -205,8 +205,8 @@ u8_t LwipIntfDev<RawDev>::_pingCB(void *arg, struct raw_pcb *pcb, struct pbuf *p
(void) addr;
LwipIntfDev<RawDev> *w = (LwipIntfDev<RawDev> *)arg;
struct icmp_echo_hdr *iecho;
if (pbuf_header(p, -20) == 0) {
iecho = (struct icmp_echo_hdr *)p->payload;
if (p->len > 20) {
iecho = (struct icmp_echo_hdr *)((uint8_t*)p->payload + 20);
if ((iecho->id == w->_ping_id) && (iecho->seqno == htons(w->_ping_seq_num))) {
w->_ping_ttl = pcb->ttl;
pbuf_free(p);
@@ -310,6 +310,11 @@ bool LwipIntfDev<RawDev>::config(IPAddress local_ip, IPAddress dns) {
extern char wifi_station_hostname[];
template<class RawDev>
bool LwipIntfDev<RawDev>::begin(const uint8_t* macAddress, const uint16_t mtu) {
if (_started) {
// ERROR - Need to ::end before calling ::begin again
return false;
}
lwip_init();
__startEthernetContext();
+21
View File
@@ -0,0 +1,21 @@
# lwIP_WINC1500 library
RP2040 Arduino driver for Arduino WiFi101 shield and Adafruit WINC1500 shields and modules.
The Adafruit learning system has instruction for wiring the WINC1500 modules and the shields should work well with Adafruit Metro RP2040.
The driver wraps the Atmel driver for ATWIC1500 chip and is based on code from the Arduino WiFi101 library.
## Configuration
Pins are configured with defines. To add the defines, modify boards.txt or create boards.local.txt next to boards.txt and add `<board>.build.extra_flags`.
The WiFi library uses this driver if `WINC1501_SPI` is defined. The value of `WINC1501_SPI` is the SPI interface to use. The driver will use default pins of the SPI interface.
Defaults for additional pins are as for the shields: RESET 5, INTN 7 and CS 10. The pins can be changed with defines in `<board>.build.extra_flags`
Example of complete settings:
```
rpipico.build.extra_flags=-DWINC1501_SPI=SPI -DWINC1501_RESET_PIN=D5 -DWINC1501_INTN_PIN=D7 -DWINC1501_SPI_CS_PIN=D10
```
@@ -0,0 +1 @@
-DWINC1501_SPI=SPI -DWINC1501_RESET_PIN=D5 -DWINC1501_INTN_PIN=D7 -DWINC1501_SPI_CS_PIN=D10
@@ -0,0 +1,101 @@
/*
This sketch establishes a TCP connection to a "quote of the day" service.
It sends a "hello" message, and then prints received data.
*/
#ifndef WINC1501_SPI
#error This example requires a WINC1500 WiFi chip to be defined, see the documentation
// For example, add this to your boards.local.txt:
// rpipico.build.extra_flags=-DWINC1501_SPI=SPI -DWINC1501_RESET_PIN=D5 -DWINC1501_INTN_PIN=D7 -DWINC1501_SPI_CS_PIN=D10
#endif
#include <WiFi.h>
#ifndef STASSID
#define STASSID "your-ssid"
#define STAPSK "your-password"
#endif
const char* ssid = STASSID;
const char* password = STAPSK;
const char* host = "djxmmx.net";
const uint16_t port = 17;
WiFiMulti multi;
void setup() {
Serial.begin(115200);
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
multi.addAP(ssid, password);
if (multi.run() != WL_CONNECTED) {
Serial.println("Unable to connect to network, rebooting in 10 seconds...");
delay(10000);
rp2040.reboot();
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
static bool wait = false;
Serial.print("connecting to ");
Serial.print(host);
Serial.print(':');
Serial.println(port);
// Use WiFiClient class to create TCP connections
WiFiClient client;
if (!client.connect(host, port)) {
Serial.println("connection failed");
delay(5000);
return;
}
// This will send a string to the server
Serial.println("sending data to server");
if (client.connected()) {
client.println("hello from RP2040");
}
// wait for data to be available
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println(">>> Client Timeout !");
client.stop();
delay(60000);
return;
}
}
// Read all the lines of the reply from server and print them to Serial
Serial.println("receiving from remote server");
// not testing 'client.connected()' since we do not need to send data here
while (client.available()) {
char ch = static_cast<char>(client.read());
Serial.print(ch);
}
// Close the connection
Serial.println();
Serial.println("closing connection");
client.stop();
if (wait) {
delay(300000); // execute once every 5 minutes, don't flood remote service
}
wait = true;
}
@@ -0,0 +1,10 @@
name=lwIP_WINC1500
version=1
author=Juraj Andrassy
maintainer=Juraj Andrassy <juraj.andrassy@gmail.com>
sentence=RP2040 Core ATWINC1500 wifi driver
paragraph=This library implements a network driver for devices based on the ATMEL WINC1500 WiFi module
category=Communication
url=https://github.com/earlephilhower/arduino-pico
architectures=rp2040
dot_a_linkage=true
@@ -0,0 +1,283 @@
/**
*
* \file
*
* \brief WINC BSP API Declarations.
*
* Copyright (c) 2015 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
/** \defgroup nm_bsp BSP
*/
/**@defgroup BSPDefine Defines
* @ingroup nm_bsp
* @{
*/
#ifndef _NM_BSP_H_
#define _NM_BSP_H_
#define NMI_API
/*!<
* Attribute used to define memory section to map Functions in host memory.
*/
#define CONST const
/*!<
* Used for code portability.
*/
/*!
* @typedef void (*tpfNmBspIsr) (void);
* @brief Pointer to function.\n
* Used as a data type of ISR function registered by \ref nm_bsp_register_isr
* @return None
*/
typedef void (*tpfNmBspIsr)(void);
#ifndef NULL
#define NULL ((void*)0)
#endif
/*!<
* Void Pointer to '0' in case of NULL is not defined.
*/
#define BSP_MIN(x,y) ((x)>(y)?(y):(x))
/*!<
* Computes the minimum of \b x and \b y.
*/
//@}
/**@defgroup DataT DataTypes
* @ingroup nm_bsp
* @{
*/
/*!
* @ingroup DataTypes
* @typedef unsigned char uint8;
* @brief Range of values between 0 to 255
*/
typedef unsigned char uint8;
/*!
* @ingroup DataTypes
* @typedef unsigned short uint16;
* @brief Range of values between 0 to 65535
*/
typedef unsigned short uint16;
/*!
* @ingroup Data Types
* @typedef unsigned long uint32;
* @brief Range of values between 0 to 4294967295
*/
typedef unsigned long uint32;
/*!
* @ingroup Data Types
* @typedef signed char sint8;
* @brief Range of values between -128 to 127
*/
typedef signed char sint8;
/*!
* @ingroup DataTypes
* @typedef signed short sint16;
* @brief Range of values between -32768 to 32767
*/
typedef signed short sint16;
/*!
* @ingroup DataTypes
* @typedef signed long sint32;
* @brief Range of values between -2147483648 to 2147483647
*/
typedef signed long sint32;
//@}
#ifndef CORTUS_APP
#ifdef __cplusplus
extern "C"{
#endif
/** \defgroup BSPAPI Function
* @ingroup nm_bsp
*/
/** @defgroup NmBspInitFn nm_bsp_init
* @ingroup BSPAPI
* Initialization for BSP such as Reset and Chip Enable Pins for WINC, delays, register ISR, enable/disable IRQ for WINC, ...etc. You must use this function in the head of your application to
* enable WINC and Host Driver communicate each other.
*/
/**@{*/
/*!
* @fn sint8 nm_bsp_init(void);
* @note Implementation of this function is host dependent.
* @warning Missing use will lead to unavailability of host communication.\n
*
* @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise.
*/
sint8 nm_bsp_init(void);
/**@}*/
/** @defgroup NmBspDeinitFn nm_bsp_deinit
* @ingroup BSPAPI
* De-initialization for BSP (\e Board \e Support \e Package)
*/
/**@{*/
/*!
* @fn sint8 nm_bsp_deinit(void);
* @pre Initialize \ref nm_bsp_init first
* @note Implementation of this function is host dependent.
* @warning Missing use may lead to unknown behavior in case of soft reset.\n
* @see nm_bsp_init
* @return The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise.
*/
sint8 nm_bsp_deinit(void);
/**@}*/
/** @defgroup NmBspResetFn nm_bsp_reset
* @ingroup BSPAPI
* Resetting NMC1500 SoC by setting CHIP_EN and RESET_N signals low, then after specific delay the function will put CHIP_EN high then RESET_N high,
* for the timing between signals please review the WINC data-sheet
*/
/**@{*/
/*!
* @fn void nm_bsp_reset(void);
* @param [in] None
* @pre Initialize \ref nm_bsp_init first
* @note Implementation of this function is host dependent and called by HIF layer.
* @see nm_bsp_init
* @return None
*/
void nm_bsp_reset(void);
/**@}*/
/** @defgroup NmBspSleepFn nm_bsp_sleep
* @ingroup BSPAPI
* Sleep in units of milliseconds.\n
* This function used by HIF Layer according to different situations.
*/
/**@{*/
/*!
* @fn void nm_bsp_sleep(uint32);
* @brief
* @param [in] u32TimeMsec
* Time unit in milliseconds
* @pre Initialize \ref nm_bsp_init first
* @warning Maximum value must nor exceed 4294967295 milliseconds which is equal to 4294967.295 seconds.\n
* @note Implementation of this function is host dependent.
* @see nm_bsp_init
* @return None
*/
void nm_bsp_sleep(uint32 u32TimeMsec);
/**@}*/
/** @defgroup NmBspRegisterFn nm_bsp_register_isr
* @ingroup BSPAPI
* Register ISR (Interrupt Service Routine) in the initialization of HIF (Host Interface) Layer.
* When the interrupt trigger the BSP layer should call the pfisr function once inside the interrupt.
*/
/**@{*/
/*!
* @fn void nm_bsp_register_isr(tpfNmBspIsr);
* @param [in] tpfNmBspIsr pfIsr
* Pointer to ISR handler in HIF
* @warning Make sure that ISR for IRQ pin for WINC is disabled by default in your implementation.
* @note Implementation of this function is host dependent and called by HIF layer.
* @see tpfNmBspIsr
* @return None
*/
void nm_bsp_register_isr(tpfNmBspIsr pfIsr);
/**@}*/
/** @defgroup NmBspInterruptCtrl nm_bsp_interrupt_ctrl
* @ingroup BSPAPI
* Synchronous enable/disable interrupts function
*/
/**@{*/
/*!
* @fn void nm_bsp_interrupt_ctrl(uint8);
* @brief Enable/Disable interrupts
* @param [in] u8Enable
* '0' disable interrupts. '1' enable interrupts
* @see tpfNmBspIsr
* @note Implementation of this function is host dependent and called by HIF layer.
* @return None
*/
void nm_bsp_interrupt_ctrl(uint8 u8Enable);
/**@}*/
#ifdef __cplusplus
}
#endif
#endif
#ifdef _NM_BSP_BIG_END
#define NM_BSP_B_L_32(x) \
((((x) & 0x000000FF) << 24) + \
(((x) & 0x0000FF00) << 8) + \
(((x) & 0x00FF0000) >> 8) + \
(((x) & 0xFF000000) >> 24))
#define NM_BSP_B_L_16(x) \
((((x) & 0x00FF) << 8) + \
(((x) & 0xFF00) >> 8))
#else
#define NM_BSP_B_L_32(x) (x)
#define NM_BSP_B_L_16(x) (x)
#endif
#endif /*_NM_BSP_H_*/
@@ -0,0 +1,74 @@
/**
*
* \file
*
* \brief This module contains NMC1500 BSP APIs definitions.
*
* Copyright (c) 2015 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
#ifndef _NM_BSP_ARDUINO_H_
#define _NM_BSP_ARDUINO_H_
#include <stdint.h>
#include <Arduino.h>
/*
* Arduino variants may redefine those pins.
* If no pins are specified the following defaults are used:
* WINC1501_RESET_PIN - pin 5
* WINC1501_INTN_PIN - pin 7
* WINC1501_CHIP_EN_PIN - not connected (tied to VCC)
*/
#if !defined(WINC1501_RESET_PIN)
#define WINC1501_RESET_PIN 5
#endif
#if !defined(WINC1501_INTN_PIN)
#define WINC1501_INTN_PIN 7
#endif
#if !defined(WINC1501_SPI_CS_PIN)
#define WINC1501_SPI_CS_PIN 10
#endif
#if !defined(WINC1501_CHIP_EN_PIN)
#define WINC1501_CHIP_EN_PIN -1
#endif
extern int8_t gi8Winc1501CsPin;
extern int8_t gi8Winc1501ResetPin;
extern int8_t gi8Winc1501IntnPin;
extern int8_t gi8Winc1501ChipEnPin;
#endif /* _NM_BSP_ARDUINO_H_ */
@@ -0,0 +1,59 @@
/**
*
* \file
*
* \brief This module contains NMC1500 BSP APIs declarations.
*
* Copyright (c) 2015 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
/**@defgroup BSPDefine Defines
* @ingroup nm_bsp
* @{
*/
#ifndef _NM_BSP_INTERNAL_H_
#define _NM_BSP_INTERNAL_H_
void winc1500debug(const char* fmt, ...);
#define CONF_WINC_PRINTF winc1500debug
#define CONF_WINC_USE_SPI 1
#define NM_EDGE_INTERRUPT 1
#define ETH_MODE
#define CONF_PERIPH
#endif //_NM_BSP_INTERNAL_H_
@@ -0,0 +1,214 @@
/**
*
* \file
*
* \brief This module contains SAMD21 BSP APIs implementation.
*
* Copyright (c) 2014 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an
* Atmel microcontroller product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
#include "bsp/include/nm_bsp.h"
#include "bsp/include/nm_bsp_arduino.h"
#include "common/include/nm_common.h"
int8_t gi8Winc1501CsPin = WINC1501_SPI_CS_PIN;
int8_t gi8Winc1501ResetPin = WINC1501_RESET_PIN;
int8_t gi8Winc1501IntnPin = WINC1501_INTN_PIN;
int8_t gi8Winc1501ChipEnPin = WINC1501_CHIP_EN_PIN;
static tpfNmBspIsr gpfIsr;
void __attribute__((weak)) attachInterruptMultiArch(uint32_t pin, void *chip_isr, uint32_t mode)
{
attachInterrupt(pin, chip_isr, mode);
}
void __attribute__((weak)) detachInterruptMultiArch(uint32_t pin)
{
detachInterrupt(pin);
}
static void chip_isr(void)
{
if (gpfIsr) {
gpfIsr();
}
}
/*
* @fn init_chip_pins
* @brief Initialize reset, chip enable and wake pin
* @author M.S.M
* @date 11 July 2012
* @version 1.0
*/
static void init_chip_pins(void)
{
if (gi8Winc1501ResetPin > -1)
{
/* Configure RESETN pin as output. */
pinMode(gi8Winc1501ResetPin, OUTPUT);
digitalWrite(gi8Winc1501ResetPin, HIGH);
}
/* Configure INTN pins as input. */
pinMode(gi8Winc1501IntnPin, INPUT);
if (gi8Winc1501ChipEnPin > -1)
{
/* Configure CHIP_EN as pull-up */
pinMode(gi8Winc1501ChipEnPin, INPUT_PULLUP);
}
}
static void deinit_chip_pins(void)
{
if (gi8Winc1501ResetPin > -1)
{
digitalWrite(gi8Winc1501ResetPin, LOW);
pinMode(gi8Winc1501ResetPin, INPUT);
}
if (gi8Winc1501ChipEnPin > -1)
{
pinMode(gi8Winc1501ChipEnPin, INPUT);
}
}
/*
* @fn nm_bsp_init
* @brief Initialize BSP
* @return 0 in case of success and -1 in case of failure
* @author M.S.M
* @date 11 July 2012
* @version 1.0
*/
sint8 nm_bsp_init(void)
{
gpfIsr = NULL;
init_chip_pins();
nm_bsp_reset();
return M2M_SUCCESS;
}
/**
* @fn nm_bsp_deinit
* @brief De-iInitialize BSP
* @return 0 in case of success and -1 in case of failure
* @author M. Abdelmawla
* @date 11 July 2012
* @version 1.0
*/
sint8 nm_bsp_deinit(void)
{
deinit_chip_pins();
return M2M_SUCCESS;
}
/**
* @fn nm_bsp_reset
* @brief Reset NMC1500 SoC by setting CHIP_EN and RESET_N signals low,
* CHIP_EN high then RESET_N high
* @author M. Abdelmawla
* @date 11 July 2012
* @version 1.0
*/
void nm_bsp_reset(void)
{
if (gi8Winc1501ResetPin > -1)
{
digitalWrite(gi8Winc1501ResetPin, LOW);
nm_bsp_sleep(100);
digitalWrite(gi8Winc1501ResetPin, HIGH);
nm_bsp_sleep(100);
}
}
/*
* @fn nm_bsp_sleep
* @brief Sleep in units of mSec
* @param[IN] u32TimeMsec
* Time in milliseconds
* @author M.S.M
* @date 28 OCT 2013
* @version 1.0
*/
void nm_bsp_sleep(uint32 u32TimeMsec)
{
while (u32TimeMsec--) {
delay(1);
}
}
/*
* @fn nm_bsp_register_isr
* @brief Register interrupt service routine
* @param[IN] pfIsr
* Pointer to ISR handler
* @author M.S.M
* @date 28 OCT 2013
* @sa tpfNmBspIsr
* @version 1.0
*/
void nm_bsp_register_isr(tpfNmBspIsr pfIsr)
{
gpfIsr = pfIsr;
attachInterruptMultiArch(gi8Winc1501IntnPin, chip_isr, FALLING);
}
/*
* @fn nm_bsp_interrupt_ctrl
* @brief Enable/Disable interrupts
* @param[IN] u8Enable
* '0' disable interrupts. '1' enable interrupts
* @author M.S.M
* @date 28 OCT 2013
* @version 1.0
*/
void nm_bsp_interrupt_ctrl(uint8 u8Enable)
{
if (u8Enable) {
attachInterruptMultiArch(gi8Winc1501IntnPin, chip_isr, FALLING);
} else {
detachInterruptMultiArch(gi8Winc1501IntnPin);
}
}
@@ -0,0 +1,177 @@
/**
*
* \file
*
* \brief This module contains NMC1000 bus wrapper APIs declarations.
*
* Copyright (c) 2015 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
#ifndef _NM_BUS_WRAPPER_H_
#define _NM_BUS_WRAPPER_H_
#include "common/include/nm_common.h"
/**
BUS Type
**/
#define NM_BUS_TYPE_I2C ((uint8)0)
#define NM_BUS_TYPE_SPI ((uint8)1)
#define NM_BUS_TYPE_UART ((uint8)2)
/**
IOCTL commands
**/
#define NM_BUS_IOCTL_R ((uint8)0) /*!< Read only ==> I2C/UART. Parameter:tstrNmI2cDefault/tstrNmUartDefault */
#define NM_BUS_IOCTL_W ((uint8)1) /*!< Write only ==> I2C/UART. Parameter type tstrNmI2cDefault/tstrNmUartDefault*/
#define NM_BUS_IOCTL_W_SPECIAL ((uint8)2) /*!< Write two buffers within the same transaction
(same start/stop conditions) ==> I2C only. Parameter:tstrNmI2cSpecial */
#define NM_BUS_IOCTL_RW ((uint8)3) /*!< Read/Write at the same time ==> SPI only. Parameter:tstrNmSpiRw */
#define NM_BUS_IOCTL_WR_RESTART ((uint8)4) /*!< Write buffer then made restart condition then read ==> I2C only. parameter:tstrNmI2cSpecial */
/**
* @struct tstrNmBusCapabilities
* @brief Structure holding bus capabilities information
* @sa NM_BUS_TYPE_I2C, NM_BUS_TYPE_SPI
*/
typedef struct
{
uint16 u16MaxTrxSz; /*!< Maximum transfer size. Must be >= 16 bytes*/
} tstrNmBusCapabilities;
/**
* @struct tstrNmI2cDefault
* @brief Structure holding I2C default operation parameters
* @sa NM_BUS_IOCTL_R, NM_BUS_IOCTL_W
*/
typedef struct
{
uint8 u8SlaveAdr;
uint8 *pu8Buf; /*!< Operation buffer */
uint16 u16Sz; /*!< Operation size */
} tstrNmI2cDefault;
/**
* @struct tstrNmI2cSpecial
* @brief Structure holding I2C special operation parameters
* @sa NM_BUS_IOCTL_W_SPECIAL
*/
typedef struct
{
uint8 u8SlaveAdr;
uint8 *pu8Buf1; /*!< pointer to the 1st buffer */
uint8 *pu8Buf2; /*!< pointer to the 2nd buffer */
uint16 u16Sz1; /*!< 1st buffer size */
uint16 u16Sz2; /*!< 2nd buffer size */
} tstrNmI2cSpecial;
/**
* @struct tstrNmSpiRw
* @brief Structure holding SPI R/W parameters
* @sa NM_BUS_IOCTL_RW
*/
typedef struct
{
uint8 *pu8InBuf; /*!< pointer to input buffer.
Can be set to null and in this case zeros should be sent at MOSI */
uint8 *pu8OutBuf; /*!< pointer to output buffer.
Can be set to null and in this case data from MISO can be ignored */
uint16 u16Sz; /*!< Transfere size */
} tstrNmSpiRw;
/**
* @struct tstrNmUartDefault
* @brief Structure holding UART default operation parameters
* @sa NM_BUS_IOCTL_R, NM_BUS_IOCTL_W
*/
typedef struct
{
uint8 *pu8Buf; /*!< Operation buffer */
uint16 u16Sz; /*!< Operation size */
} tstrNmUartDefault;
/*!< Bus capabilities. This structure must be declared at platform specific bus wrapper */
extern tstrNmBusCapabilities egstrNmBusCapabilities;
#ifdef __cplusplus
extern "C" {
#endif
/**
* @fn nm_bus_init
* @brief Initialize the bus wrapper
* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure
*/
sint8 nm_bus_init(void *);
/**
* @fn nm_bus_ioctl
* @brief send/receive from the bus
* @param [in] u8Cmd
* IOCTL command for the operation
* @param [in] pvParameter
* Arbitrary parameter depending on IOCTL
* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure
* @note For SPI only, it's important to be able to send/receive at the same time
*/
sint8 nm_bus_ioctl(uint8 u8Cmd, void* pvParameter);
/**
* @fn nm_bus_deinit
* @brief De-initialize the bus wrapper
* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure
*/
sint8 nm_bus_deinit(void);
/*
* @fn nm_bus_reinit
* @brief re-initialize the bus wrapper
* @param [in] void *config
* re-init configuration data
* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure
*/
sint8 nm_bus_reinit(void *);
/*
* @fn nm_bus_get_chip_type
* @brief get chip type
* @return ZERO in case of success and M2M_ERR_BUS_FAIL in case of failure
*/
#ifdef CONF_WINC_USE_UART
uint8 nm_bus_get_chip_type(void);
#endif
#ifdef __cplusplus
}
#endif
#endif /*_NM_BUS_WRAPPER_H_*/
@@ -0,0 +1,200 @@
/**
*
* \file
*
* \brief This module contains NMC1000 bus wrapper APIs implementation.
*
* Copyright (c) 2014 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an
* Atmel microcontroller product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
#include <Arduino.h>
#include <SPI.h>
/*
* Variants may define an alternative SPI instace to use for WiFi101.
* If not defined the following defaults are used:
* WINC1501_SPI - SPI
*/
#if !defined(WINC1501_SPI)
#define WINC1501_SPI SPI
#endif
extern "C" {
#include "bsp/include/nm_bsp.h"
#include "bsp/include/nm_bsp_arduino.h"
#include "common/include/nm_common.h"
#include "bus_wrapper/include/nm_bus_wrapper.h"
}
#define NM_BUS_MAX_TRX_SZ 256
tstrNmBusCapabilities egstrNmBusCapabilities =
{
NM_BUS_MAX_TRX_SZ
};
static const SPISettings wifi_SPISettings(12000000L, MSBFIRST, SPI_MODE0);
static sint8 spi_rw(uint8* pu8Mosi, uint8* pu8Miso, uint16 u16Sz)
{
uint8 u8Dummy = 0;
uint8 u8SkipMosi = 0, u8SkipMiso = 0;
if (!pu8Mosi) {
pu8Mosi = &u8Dummy;
u8SkipMosi = 1;
}
else if(!pu8Miso) {
pu8Miso = &u8Dummy;
u8SkipMiso = 1;
}
else {
return M2M_ERR_BUS_FAIL;
}
WINC1501_SPI.beginTransaction(wifi_SPISettings);
digitalWrite(gi8Winc1501CsPin, LOW);
while (u16Sz) {
*pu8Miso = WINC1501_SPI.transfer(*pu8Mosi);
u16Sz--;
if (!u8SkipMiso)
pu8Miso++;
if (!u8SkipMosi)
pu8Mosi++;
}
digitalWrite(gi8Winc1501CsPin, HIGH);
WINC1501_SPI.endTransaction();
return M2M_SUCCESS;
}
extern "C" {
/*
* @fn nm_bus_init
* @brief Initialize the bus wrapper
* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure
* @author M.S.M
* @date 28 oct 2013
* @version 1.0
*/
sint8 nm_bus_init(void * /* pvInitValue */)
{
sint8 result = M2M_SUCCESS;
/* Configure SPI peripheral. */
WINC1501_SPI.begin();
/* Configure CS PIN. */
pinMode(gi8Winc1501CsPin, OUTPUT);
digitalWrite(gi8Winc1501CsPin, HIGH);
/* Reset WINC1500. */
nm_bsp_reset();
nm_bsp_sleep(1);
return result;
}
/*
* @fn nm_bus_ioctl
* @brief send/receive from the bus
* @param[IN] u8Cmd
* IOCTL command for the operation
* @param[IN] pvParameter
* Arbitrary parameter depenging on IOCTL
* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure
* @author M.S.M
* @date 28 oct 2013
* @note For SPI only, it's important to be able to send/receive at the same time
* @version 1.0
*/
sint8 nm_bus_ioctl(uint8 u8Cmd, void* pvParameter)
{
sint8 s8Ret = 0;
switch(u8Cmd)
{
case NM_BUS_IOCTL_RW: {
tstrNmSpiRw *pstrParam = (tstrNmSpiRw *)pvParameter;
s8Ret = spi_rw(pstrParam->pu8InBuf, pstrParam->pu8OutBuf, pstrParam->u16Sz);
}
break;
default:
s8Ret = -1;
M2M_ERR("invalide ioclt cmd\n");
break;
}
return s8Ret;
}
/*
* @fn nm_bus_deinit
* @brief De-initialize the bus wrapper
* @author M.S.M
* @date 28 oct 2013
* @version 1.0
*/
sint8 nm_bus_deinit(void)
{
WINC1501_SPI.end();
return 0;
}
/*
* @fn nm_bus_reinit
* @brief re-initialize the bus wrapper
* @param [in] void *config
* re-init configuration data
* @return M2M_SUCCESS in case of success and M2M_ERR_BUS_FAIL in case of failure
* @author Dina El Sissy
* @date 19 Sept 2012
* @version 1.0
*/
sint8 nm_bus_reinit(void* /* config */)
{
return M2M_SUCCESS;
}
} // extern "C"
@@ -0,0 +1,153 @@
/**
*
* \file
*
* \brief WINC Driver Common API Declarations.
*
* Copyright (c) 2016-2017 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
#ifndef _NM_COMMON_H_
#define _NM_COMMON_H_
#include "bsp/include/nm_bsp.h"
#include "common/include/nm_debug.h"
/**@defgroup CommonDefines CommonDefines
* @ingroup WlanDefines
*/
/**@{*/
#define M2M_TIME_OUT_DELAY 10000
/*states*/
#define M2M_SUCCESS ((sint8)0)
#define M2M_ERR_SEND ((sint8)-1)
#define M2M_ERR_RCV ((sint8)-2)
#define M2M_ERR_MEM_ALLOC ((sint8)-3)
#define M2M_ERR_TIME_OUT ((sint8)-4)
#define M2M_ERR_INIT ((sint8)-5)
#define M2M_ERR_BUS_FAIL ((sint8)-6)
#define M2M_NOT_YET ((sint8)-7)
#define M2M_ERR_FIRMWARE ((sint8)-8)
#define M2M_SPI_FAIL ((sint8)-9)
#define M2M_ERR_FIRMWARE_bURN ((sint8)-10)
#define M2M_ACK ((sint8)-11)
#define M2M_ERR_FAIL ((sint8)-12)
#define M2M_ERR_FW_VER_MISMATCH ((sint8)-13)
#define M2M_ERR_SCAN_IN_PROGRESS ((sint8)-14)
#define M2M_ERR_INVALID_ARG ((sint8)-15)
#define M2M_ERR_INVALID ((sint8)-16)
/*i2c MAASTER ERR*/
#define I2C_ERR_LARGE_ADDRESS 0xE1UL /*the address exceed the max addressing mode in i2c flash*/
#define I2C_ERR_TX_ABRT 0xE2UL /*NO ACK from slave*/
#define I2C_ERR_OVER_SIZE 0xE3UL /**/
#define ERR_PREFIX_NMIS 0xE4UL /*wrong first four byte in flash NMIS*/
#define ERR_FIRMEWARE_EXCEED_SIZE 0xE5UL /*Total size of firmware exceed the max size 256k*/
/**/
#define PROGRAM_START 0x26961735UL
#define BOOT_SUCCESS 0x10add09eUL
#define BOOT_START 0x12345678UL
#define NBIT31 (0x80000000)
#define NBIT30 (0x40000000)
#define NBIT29 (0x20000000)
#define NBIT28 (0x10000000)
#define NBIT27 (0x08000000)
#define NBIT26 (0x04000000)
#define NBIT25 (0x02000000)
#define NBIT24 (0x01000000)
#define NBIT23 (0x00800000)
#define NBIT22 (0x00400000)
#define NBIT21 (0x00200000)
#define NBIT20 (0x00100000)
#define NBIT19 (0x00080000)
#define NBIT18 (0x00040000)
#define NBIT17 (0x00020000)
#define NBIT16 (0x00010000)
#define NBIT15 (0x00008000)
#define NBIT14 (0x00004000)
#define NBIT13 (0x00002000)
#define NBIT12 (0x00001000)
#define NBIT11 (0x00000800)
#define NBIT10 (0x00000400)
#define NBIT9 (0x00000200)
#define NBIT8 (0x00000100)
#define NBIT7 (0x00000080)
#define NBIT6 (0x00000040)
#define NBIT5 (0x00000020)
#define NBIT4 (0x00000010)
#define NBIT3 (0x00000008)
#define NBIT2 (0x00000004)
#define NBIT1 (0x00000002)
#define NBIT0 (0x00000001)
#define M2M_MAX(A,B) ((A) > (B) ? (A) : (B))
#define M2M_SEL(x,m1,m2,m3) ((x>1)?((x>2)?(m3):(m2)):(m1))
#define WORD_ALIGN(val) (((val) & 0x03) ? ((val) + 4 - ((val) & 0x03)) : (val))
#define DATA_PKT_OFFSET 4
#ifndef BIG_ENDIAN
#define BYTE_0(word) ((uint8)(((word) >> 0 ) & 0x000000FFUL))
#define BYTE_1(word) ((uint8)(((word) >> 8 ) & 0x000000FFUL))
#define BYTE_2(word) ((uint8)(((word) >> 16) & 0x000000FFUL))
#define BYTE_3(word) ((uint8)(((word) >> 24) & 0x000000FFUL))
#else
#define BYTE_0(word) ((uint8)(((word) >> 24) & 0x000000FFUL))
#define BYTE_1(word) ((uint8)(((word) >> 16) & 0x000000FFUL))
#define BYTE_2(word) ((uint8)(((word) >> 8 ) & 0x000000FFUL))
#define BYTE_3(word) ((uint8)(((word) >> 0 ) & 0x000000FFUL))
#endif
/**@}*/
#ifdef __cplusplus
extern "C" {
#endif
NMI_API void m2m_memcpy(uint8* pDst,uint8* pSrc,uint32 sz);
NMI_API void m2m_memset(uint8* pBuf,uint8 val,uint32 sz);
NMI_API uint16 m2m_strlen(uint8 * pcStr);
NMI_API sint8 m2m_memcmp(uint8 *pu8Buff1,uint8 *pu8Buff2 ,uint32 u32Size);
NMI_API uint8 m2m_strncmp(uint8 *pcS1, uint8 *pcS2, uint16 u16Len);
NMI_API uint8 * m2m_strstr(uint8 *pcIn, uint8 *pcStr);
NMI_API uint8 m2m_checksum(uint8* buf, int sz);
#ifdef __cplusplus
}
#endif
#endif /*_NM_COMMON_H_*/
@@ -0,0 +1,95 @@
/**
*
* \file
*
* \brief This module contains debug APIs declarations.
*
* Copyright (c) 2016-2017 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
#ifndef _NM_DEBUG_H_
#define _NM_DEBUG_H_
#include "bsp/include/nm_bsp.h"
#include "bsp/include/nm_bsp_internal.h"
/**@defgroup DebugDefines DebugDefines
* @ingroup WlanDefines
*/
/**@{*/
#define M2M_LOG_NONE 0
#define M2M_LOG_ERROR 1
#define M2M_LOG_INFO 2
#define M2M_LOG_REQ 3
#define M2M_LOG_DBG 4
#if (defined __APS3_CORTUS__)
#define M2M_LOG_LEVEL M2M_LOG_INFO
#else
#define M2M_LOG_LEVEL M2M_LOG_REQ
#endif
#define M2M_ERR(...)
#define M2M_INFO(...)
#define M2M_REQ(...)
#define M2M_DBG(...)
#define M2M_PRINT(...)
#if (CONF_WINC_DEBUG == 1)
#undef M2M_PRINT
#define M2M_PRINT(...) do{CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0)
#if (M2M_LOG_LEVEL >= M2M_LOG_ERROR)
#undef M2M_ERR
#define M2M_ERR(...) do{CONF_WINC_PRINTF("(APP)(ERR)[%s][%d]",__FUNCTION__,__LINE__); CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0)
#if (M2M_LOG_LEVEL >= M2M_LOG_INFO)
#undef M2M_INFO
#define M2M_INFO(...) do{CONF_WINC_PRINTF("(APP)(INFO)"); CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0)
#if (M2M_LOG_LEVEL >= M2M_LOG_REQ)
#undef M2M_REQ
#define M2M_REQ(...) do{CONF_WINC_PRINTF("(APP)(R)"); CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0)
#if (M2M_LOG_LEVEL >= M2M_LOG_DBG)
#undef M2M_DBG
#define M2M_DBG(...) do{CONF_WINC_PRINTF("(APP)(DBG)[%s][%d]",__FUNCTION__,__LINE__); CONF_WINC_PRINTF(__VA_ARGS__);CONF_WINC_PRINTF("\r");}while(0)
#endif /*M2M_LOG_DBG*/
#endif /*M2M_LOG_REQ*/
#endif /*M2M_LOG_INFO*/
#endif /*M2M_LOG_ERROR*/
#endif /*CONF_WINC_DEBUG */
/**@}*/
#endif /* _NM_DEBUG_H_ */
@@ -0,0 +1,136 @@
/**
*
* \file
*
* \brief This module contains common APIs declarations.
*
* Copyright (c) 2016 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
#include "common/include/nm_common.h"
void m2m_memcpy(uint8* pDst,uint8* pSrc,uint32 sz)
{
if(sz == 0) return;
do
{
*pDst = *pSrc;
pDst++;
pSrc++;
}while(--sz);
}
uint8 m2m_checksum(uint8* buf, int sz)
{
uint8 cs = 0;
while(--sz)
{
cs ^= *buf;
buf++;
}
return cs;
}
void m2m_memset(uint8* pBuf,uint8 val,uint32 sz)
{
if(sz == 0) return;
do
{
*pBuf = val;
pBuf++;
}while(--sz);
}
uint16 m2m_strlen(uint8 * pcStr)
{
uint16 u16StrLen = 0;
while(*pcStr)
{
u16StrLen ++;
pcStr++;
}
return u16StrLen;
}
uint8 m2m_strncmp(uint8 *pcS1, uint8 *pcS2, uint16 u16Len)
{
for ( ; u16Len > 0; pcS1++, pcS2++, --u16Len)
if (*pcS1 != *pcS2)
return ((*(uint8 *)pcS1 < *(uint8 *)pcS2) ? -1 : +1);
else if (*pcS1 == '\0')
return 0;
return 0;
}
/* Finds the occurance of pcStr in pcIn.
If pcStr is part of pcIn it returns a valid pointer to the start of pcStr within pcIn.
Otherwise a NULL Pointer is returned.
*/
uint8 * m2m_strstr(uint8 *pcIn, uint8 *pcStr)
{
uint8 u8c;
uint16 u16StrLen;
u8c = *pcStr++;
if (!u8c)
return (uint8 *) pcIn; // Trivial empty string case
u16StrLen = m2m_strlen(pcStr);
do {
uint8 u8Sc;
do {
u8Sc = *pcIn++;
if (!u8Sc)
return (uint8 *) 0;
} while (u8Sc != u8c);
} while (m2m_strncmp(pcIn, pcStr, u16StrLen) != 0);
return (uint8 *) (pcIn - 1);
}
sint8 m2m_memcmp(uint8 *pu8Buff1,uint8 *pu8Buff2 ,uint32 u32Size)
{
uint32 i;
sint8 s8Result = 0;
for(i = 0 ; i < u32Size ; i++)
{
if(pu8Buff1[i] != pu8Buff2[i])
{
s8Result = 1;
break;
}
}
return s8Result;
}
@@ -0,0 +1,245 @@
/**
*
* \file
*
* \brief WINC Application Interface Internal Types.
*
* Copyright (c) 2017 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
#ifndef __ECC_TYPES_H__
#define __ECC_TYPES_H__
/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
INCLUDES
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
#include "m2m_types.h"
/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
MACROS
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
#define ECC_LARGEST_CURVE_SIZE (32)
/*!<
The size of the the largest supported EC. For now, assuming
the 256-bit EC is the largest supported curve type.
*/
#define ECC_POINT_MAX_SIZE ECC_LARGEST_CURVE_SIZE
/*!<
Maximum size of one coordinate of an EC point.
*/
#define ECC_POINT_MAX_SIZE_WORDS (ECC_POINT_MAX_SIZE / 4)
/*!<
SIZE in 32-bit words.
*/
#if 0
#define ECC_NUM_SUPP_CURVES ((sizeof(gastrECCSuppList)) / (sizeof(tstrEllipticCurve)))
#endif
/*!<
*/
/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
DATA TYPES
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
/*!
@enum \
tenuEcNamedCurve
@brief EC Named Curves
Defines a list of supported ECC named curves.
*/
typedef enum EcNamedCurve{
EC_SECP192R1 = 19,
/*!<
It is defined by NIST as P192 and by the SEC Group as secp192r1.
*/
EC_SECP256R1 = 23,
/*!<
It is defined by NIST as P256 and by the SEC Group as secp256r1.
*/
EC_SECP384R1 = 24,
/*!<
It is defined by NIST as P384 and by the SEC Group as secp384r1.
*/
EC_SECP521R1 = 25,
/*!<
It is defined by NIST as P521 and by the SEC Group as secp521r1.
*/
EC_UNKNOWN = 255
}tenuEcNamedCurve;
/*!
@struct \
tstrECPoint
@brief Elliptic Curve point representation
*/
typedef struct EcPoint{
uint8 X[ECC_POINT_MAX_SIZE];
/*!<
The X-coordinate of the ec point.
*/
uint8 Y[ECC_POINT_MAX_SIZE];
/*!<
The Y-coordinate of the ec point.
*/
uint16 u16Size;
/*!<
Point size in bytes (for each of the coordinates).
*/
uint16 u16PrivKeyID;
/*!<
ID for the corresponding private key.
*/
}tstrECPoint;
/*!
@struct \
tstrECDomainParam
@brief ECC Curve Domain Parameters
The structure defines the ECC domain parameters for curves defined over prime finite fields.
*/
typedef struct EcDomainParam{
uint32 p[ECC_POINT_MAX_SIZE_WORDS];
uint32 a[ECC_POINT_MAX_SIZE_WORDS];
uint32 b[ECC_POINT_MAX_SIZE_WORDS];
tstrECPoint G;
}tstrECDomainParam;
/*!
@struct \
tstrEllipticCurve
@brief
Definition of an elliptic curve
*/
typedef struct{
tenuEcNamedCurve enuType;
tstrECDomainParam strParam;
}tstrEllipticCurve;
typedef enum{
ECC_REQ_NONE,
ECC_REQ_CLIENT_ECDH,
ECC_REQ_SERVER_ECDH,
ECC_REQ_GEN_KEY,
ECC_REQ_SIGN_GEN,
ECC_REQ_SIGN_VERIFY
}tenuEccREQ;
typedef struct{
tstrECPoint strPubKey;
uint8 au8Key[ECC_POINT_MAX_SIZE];
}tstrEcdhReqInfo;
typedef struct{
uint32 u32nSig;
}tstrEcdsaVerifyReqInfo;
typedef struct{
uint16 u16CurveType;
uint16 u16HashSz;
}tstrEcdsaSignReqInfo;
typedef struct{
uint16 u16REQ;
uint16 u16Status;
uint32 u32UserData;
uint32 u32SeqNo;
union{
tstrEcdhReqInfo strEcdhREQ;
tstrEcdsaSignReqInfo strEcdsaSignREQ;
tstrEcdsaVerifyReqInfo strEcdsaVerifyREQ;
};
}tstrEccReqInfo;
/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
GLOBALS
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
#if 0
static tstrEllipticCurve gastrECCSuppList[] = {
{
EC_SECP256R1,
{
{0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0xFFFFFFFF},
{0xFFFFFFFC, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0xFFFFFFFF},
{0x27D2604B, 0x3BCE3C3E, 0xCC53B0F6, 0x651D06B0, 0x769886BC, 0xB3EBBD55, 0xAA3A93E7, 0x5AC635D8},
{
{
0x6B, 0x17, 0xD1, 0xF2, 0xE1, 0x2C, 0x42, 0x47, 0xF8, 0xBC, 0xE6, 0xE5, 0x63, 0xA4, 0x40, 0xF2,
0x77, 0x03, 0x7D, 0x81, 0x2D, 0xEB, 0x33, 0xA0, 0xF4, 0xA1, 0x39, 0x45, 0xD8, 0x98, 0xC2, 0x96
},
{
0x4F, 0xE3, 0x42, 0xE2, 0xFE, 0x1A, 0x7F, 0x9B, 0x8E, 0xE7, 0xEB, 0x4A, 0x7C, 0x0F, 0x9E, 0x16,
0x2B, 0xCE, 0x33, 0x57, 0x6B, 0x31, 0x5E, 0xCE, 0xCB, 0xB6, 0x40, 0x68, 0x37, 0xBF, 0x51, 0xF5
},
32
}
}
}
};
#endif
/*!<
List of supported Elliptic Curves ordered by security level (most secure curve is at index ZERO).
*/
#endif /* __ECC_TYPES_H__ */
@@ -0,0 +1,732 @@
/**
*
* \file
*
* \brief WINC ATE Test Driver Interface.
*
* Copyright (c) 2016-2017 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
#ifdef _M2M_ATE_FW_
#ifndef _M2M_ATE_MODE_H_
#define _M2M_ATE_MODE_H_
/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
INCLUDES
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
#include "common/include/nm_common.h"
#include "driver/include/m2m_types.h"
/** \defgroup m2m_ate ATE
*/
/**@defgroup ATEDefine Defines
* @ingroup m2m_ate
* @{
*/
/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
MACROS
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
#define M2M_ATE_MAX_NUM_OF_RATES (20)
/*!<
Maximum number of all rates (b,g and n)
*/
#define M2M_ATE_MAX_FRAME_LENGTH (1024)
/*!< Maximum number of length for each frame
*/
#define M2M_ATE_MIN_FRAME_LENGTH (1)
/*!< Minimum number of length for each frame
*/
#define M2M_ATE_SUCCESS (M2M_SUCCESS)
/*!< No Error and operation has been completed successfully.
*/
#define M2M_ATE_ERR_VALIDATE (M2M_ERR_FAIL)
/*!< Error in parameters passed to functions.
*/
#define M2M_ATE_ERR_TX_ALREADY_RUNNING (-1)
/*!< Error in starting a transmission test. Another test is already running and its not allowed to start another ATE test.
*/
#define M2M_ATE_ERR_RX_ALREADY_RUNNING (-2)
/*!< Error in starting a reception test. Another test is already running and its not allowed to start another ATE test.
*/
#define M2M_ATE_ERR_UNHANDLED_CASE (-3)
/*!< Invalid case.
*/
#define M2M_ATE_RX_DISABLE_DA 0x0
/*!< Filter selection for received frames: Disable filtering received frames by the destination address.
*/
#define M2M_ATE_RX_ENABLE_DA 0x1
/*!< Filter selection for received frames: Enable filtering received frames by the destination address.
*/
#define M2M_ATE_RX_DISABLE_SA 0x0
/*!< Filter selection for received frames: Disable filtering received frames by the source address.
*/
#define M2M_ATE_RX_ENABLE_SA 0x1
/*!< Filter selection for received frames: Enable filtering received frames by the source address.
*/
#define M2M_ATE_DISABLE_SELF_MACADDR 0x0
/*!<Disable setting a new mac address through the ATE test application and use the pre-set mac address in the firmware.
*/
#define M2M_ATE_SET_SELF_MACADDR 0x1
/*!<Enable setting a new mac address through the ATE test application and use the pre-set mac address.
*/
#define M2M_ATE_TX_DUTY_MAX_VALUE M2M_ATE_TX_DUTY_1
/*!< The maximum value of duty cycle
*/
#define M2M_ATE_TX_DUTY_MIN_VALUE M2M_ATE_TX_DUTY_10
/*!< The minimum value of duty cycle
*/
//@}
/**@defgroup ATEDataTypes DataTypes
* @ingroup m2m_ate
* @{
*/
/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
DATA TYPES
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
/*!
*@enum tenuM2mAteFwState
*@brief Enumeration used to change ATE firmware states
*/
typedef enum {
M2M_ATE_FW_STATE_STOP = 0x00,
/*!< State to stop ATE firmware
*/
M2M_ATE_FW_STATE_RUN = 0x01,
/*!< State to run ATE firmware
*/
}tenuM2mAteFwState;
/*!
*@enum tenuM2mAteTxRates
*@brief Enumeration used to index the TX rates that can be used during the transmission test.
*/
typedef enum {
M2M_ATE_TX_RATE_1_Mbps_INDEX = 0x00,
M2M_ATE_TX_RATE_2_Mbps_INDEX = 0x01,
M2M_ATE_TX_RATE_55_Mbps_INDEX = 0x02,
M2M_ATE_TX_RATE_11_Mbps_INDEX = 0x03,
/*!< B-Rates
*/
M2M_ATE_TX_RATE_6_Mbps_INDEX = 0x04,
M2M_ATE_TX_RATE_9_Mbps_INDEX = 0x05,
M2M_ATE_TX_RATE_12_Mbps_INDEX = 0x06,
M2M_ATE_TX_RATE_18_Mbps_INDEX = 0x07,
M2M_ATE_TX_RATE_24_Mbps_INDEX = 0x08,
M2M_ATE_TX_RATE_36_Mbps_INDEX = 0x09,
M2M_ATE_TX_RATE_48_Mbps_INDEX = 0x0A,
M2M_ATE_TX_RATE_54_Mbps_INDEX = 0x0B,
/*!< G-Rates
*/
M2M_ATE_TX_RATE_MCS_0_INDEX = 0x0C,
M2M_ATE_TX_RATE_MCS_1_INDEX = 0x0D,
M2M_ATE_TX_RATE_MCS_2_INDEX = 0x0E,
M2M_ATE_TX_RATE_MCS_3_INDEX = 0x0F,
M2M_ATE_TX_RATE_MCS_4_INDEX = 0x10,
M2M_ATE_TX_RATE_MCS_5_INDEX = 0x11,
M2M_ATE_TX_RATE_MCS_6_INDEX = 0x12,
M2M_ATE_TX_RATE_MCS_7_INDEX = 0x13,
/*!< N-Rates
*/
}tenuM2mAteTxIndexOfRates;
/*!
*@enum tenuM2mAteTxDutyCycle
*@brief Enumeration used to index the TX duty cycle that can be used during the transmission test.
*/
typedef enum {
M2M_ATE_TX_DUTY_1 = 0x01,
M2M_ATE_TX_DUTY_2 = 0x02,
M2M_ATE_TX_DUTY_3 = 0x03,
M2M_ATE_TX_DUTY_4 = 0x04,
M2M_ATE_TX_DUTY_5 = 0x05,
M2M_ATE_TX_DUTY_6 = 0x06,
M2M_ATE_TX_DUTY_7 = 0x07,
M2M_ATE_TX_DUTY_8 = 0x08,
M2M_ATE_TX_DUTY_9 = 0x09,
M2M_ATE_TX_DUTY_10 = 0xA0,
}tenuM2mAteTxDutyCycle;
/*!
*@enum tenuM2mAteTxDpdControl
*@brief Enumeration for the allowed Digital-pre distortion(DPD) control values.
*/
typedef enum {
M2M_ATE_TX_DPD_DYNAMIC = 0x00,
/*!< Dynamic mode indicates that DPD values will be set dynamically from a lookup table pre-set with the DPD coefficents.
*/
M2M_ATE_TX_DPD_BYPASS = 0x01,
/*!< Bypass mode indicates that the DPD control will be bypassed.
*/
M2M_ATE_TX_DPD_ENABLED = 0x02,
/*!< Enabled mode allows the tester to manually set the DPD coefficients.
*/
}tenuM2mAteTxDpdControl;
/*!
*@enum tenuM2mAteTxGainSetting
*@brief Enumeration for the allowed TX gain selection modes.
*/
typedef enum {
M2M_ATE_TX_GAIN_DYNAMIC = 0x00,
/*!< Dynamic mode indicates that Tx gain values for the digital gain,pa and ppa, will be set dynamically from a lookup table based on the Tx_rate configured.
*/
M2M_ATE_TX_GAIN_BYPASS = 0x01,
/*!< Bypass mode indicates that Tx gain configurations will be bypassed.
*/
M2M_ATE_TX_GAIN_FCC = 0x02,
/*!< Using the FCC tx gain configuration indicates that the tx gain values will be used from the FCC flashed table(pre-configured values from a customer).
*/
M2M_ATE_TX_GAIN_TELEC = 0x03,
/*!< Using the TELEC tx gain configuration indicates that the tx gain values will be used from the TELEC flashed table(pre-configured values from a customer).
*/
}tenuM2mAteTxGainSetting;
/*!
*@enum tenuM2mAtePMUSetting
*@brief Used to Enable PMU or disable it
*/
typedef enum {
M2M_ATE_PMU_DISBLE = 0x00,
/*!< Disable using PMU mode
*/
M2M_ATE_PMU_ENABLE = 0x01,
/*!< Enable using PMU mode
*/
}tenuM2mAtePMUSetting;
/*!
*@enum tenuM2mAteTxSource
*@brief Used to define the Tx source, either PHY mode or MAC mode.
*/
typedef enum {
M2M_ATE_TX_SRC_MAC = 0x00,
/*!< When the TX Source is set to MAC, it indicates that the TX frames are manually framed and sent from the MAC layer
*/
M2M_ATE_TX_SRC_PHY = 0x01,
/*!< When the TX source is set to PHY, it indicates that transmission sequence occurs from PHY layer in the form of pulses
*/
}tenuM2mAteTxSource;
/*!
*@enum tenuM2mAteTxMode
*@brief Used to define the mode of PHY TX transmission source: Continuous Wave(CW) or Normal(i.e CW is disabled) TX sequence
*/
typedef enum {
M2M_ATE_TX_MODE_NORM = 0x00,
/*!< When the TX source is set to PHY,normal mode indicates that continous transmission is disabled.
*/
M2M_ATE_TX_MODE_CW = 0x01,
/*!< When the TX source is set to PHY, continous mode indicates that transmission sequences occur back to back in a continous wave from the PHY layer.
*/
}tenuM2mAteTxMode;
/*!
*@enum tenuM2mAteRxPwrMode
*@brief Used to define type of RX mode either high power or low power
*/
typedef enum {
M2M_ATE_RX_PWR_HIGH = 0x00,
/*!< Indicates that receive mode is operating at high power
*/
M2M_ATE_RX_PWR_LOW = 0x01,
/*!< Indicates that receive mode is operating at low power
*/
}tenuM2mAteRxPwrMode;
/*!
*@enum tenuM2mAteChannels
*@brief Available channels for TX and RX in the 2.4GHz spectrum starting at 2412MHz with a 5MHz bandwidth.
*/
typedef enum {
M2M_ATE_CHANNEL_1 = 0x01,
/*!< Channel 1: 2412MHz
*/
M2M_ATE_CHANNEL_2 = 0x02,
/*!< Channel 2: 2417MHz
*/
M2M_ATE_CHANNEL_3 = 0x03,
/*!< Channel 3: 2422MHz
*/
M2M_ATE_CHANNEL_4 = 0x04,
/*!< Channel 4: 2427MHz
*/
M2M_ATE_CHANNEL_5 = 0x05,
/*!< Channel 5: 2432MHz
*/
M2M_ATE_CHANNEL_6 = 0x06,
/*!< Channel 6: 2437MHz
*/
M2M_ATE_CHANNEL_7 = 0x07,
/*!< Channel 7: 2442MHz
*/
M2M_ATE_CHANNEL_8 = 0x08,
/*!< Channel 8: 2447MHz
*/
M2M_ATE_CHANNEL_9 = 0x09,
/*!< Channel 9: 2452MHz
*/
M2M_ATE_CHANNEL_10 = 0x0A,
/*!< Channel 10: 2462MHz
*/
M2M_ATE_CHANNEL_11 = 0x0B,
/*!< Channel 11: 2467MHz
*/
M2M_ATE_CHANNEL_12 = 0x0C,
/*!< Channel 12: 2472MHz
*/
M2M_ATE_CHANNEL_13 = 0x0D,
/*!< Channel 13: 2472MHz
*/
M2M_ATE_CHANNEL_14 = 0x0E,
/*!< Channel 14: 2484MHz
*/
}tenuM2mAteChannels;
/*!
*@struct tstrM2mAteRxStatus
*@brief Used to save statistics for receive(RX) test case
*/
typedef struct {
uint32 num_rx_pkts;
/*!< Number of total RX packets
*/
uint32 num_err_pkts;
/*!< Number of RX failed packets
*/
uint32 num_good_pkts;
/*!< Number of RX packets actually received
*/
} tstrM2mAteRxStatus;
/*!
*@struct tstrM2mAteRxStatus
*@brief Used to save recieve test case configuration
*@see tenuM2mAteRxPwrMode
*/
typedef struct {
uint8 u8RxPwrMode;
/*!< RX power mode review \ref tenuM2mAteRxPwrMode
*/
} tstrM2mAteInit;
/*!
*@struct tstrM2mAteTx
*@brief Used for the transmission(Tx) test configuration.
*/
typedef struct {
uint32 num_frames;
/*!< Number of frames to be sent where maximum number allowed is 4294967295 ul, and ZERO means infinite number of frames
*/
uint32 data_rate;
/*!< Rate to send packets, to select a rate use values from the enumeration \ref tenuM2mAteTxIndexOfRates and pass it to \ref m2m_ate_get_tx_rate
*/
uint8 channel_num;
/*!< Channel number as enumerated at \ref tenuM2mAteChannels
*/
uint8 duty_cycle;
/*!< Duty cycle value between from 1 to 10, where maximum = 1, minimum = 10. As enumerated \ref tenuM2mAteTxDutyCycle
*/
uint16 frame_len;
/*!< Use @ref M2M_ATE_MAX_FRAME_LENGTH (1024) as the maximum value while @ref M2M_ATE_MIN_FRAME_LENGTH (1) is the minimum value
*/
uint8 tx_gain_sel;
/*!< TX gain mode selection value \ref tenuM2mAteTxGainSetting
*/
uint8 dpd_ctrl;
/*!< DPD mode value\ref tenuM2mAteTxDpdControl
*/
uint8 use_pmu;
/*!< This is 0 if PMU is not used otherwise it must be be 1 \ref tenuM2mAtePMUSetting
*/
uint8 phy_burst_tx;
/*!< Source of Burst TX either PHY or MAC \ref tenuM2mAteTxSource
*/
uint8 cw_tx;
/*!< Mode of Phy TX transmission either normal TX sequence or CW(Continuous Wave) TX sequence \ref tenuM2mAteTxMode
*/
uint32 xo_offset_x1000;
/*!< Signed XO offset value in Part Per Million(PPM) multiplied by 1000.
*/
uint8 use_efuse_xo_offset;
/*!< Set to 0 to use the XO offset provided in xo_offset_x1000. Set to 1 to use XO offset programmed on WINC efuse.
*/
uint8 peer_mac_addr[6];
/*!< Set peer address to send directed frames to a certain address.
*/
} tstrM2mAteTx;
/*!
*@struct tstrM2mAteRx
*@brief Used for the reception(Rx) test configuration.
*/
typedef struct {
uint8 channel_num;
/*!< Channel number \ref tenuM2mAteChannels
*/
uint8 use_pmu;
/*!< This is 0 if PMU is not used otherwise it must be be 1 \ref tenuM2mAtePMUSetting
*/
uint32 xo_offset_x1000;
/*!< Signed XO offset value in PPM (Part Per Million) multiplied by 1000.
*/
uint8 use_efuse_xo_offset;
/*!< Set to 0 to use the XO offset provided in xo_offset_x1000. Set to 1 to use XO offset programmed on WINC efuse.
*/
uint8 self_mac_addr[6];
/*!< Set to the self mac address required to be overriden.
*/
uint8 peer_mac_addr[6];
/*!< Set to the source mac address expected to filter frames from.
*/
uint8 mac_filter_en_da;
/*!< Flag set to enable or disable reception with destination address as a filter. Using the following flags \ref M2M_ATE_RX_ENABLE_DA
\ref M2M_ATE_RX_DISABLE_DA
*/
uint8 mac_filter_en_sa;
/*!< Flag set to enable or disable reception with source address as a filter.Using the following flags \ref M2M_ATE_RX_ENABLE_SA
\ref M2M_ATE_RX_DISABLE_SA
*/
uint8 override_self_mac_addr;
/*!< Flag set to enable or disable self mac address feature. Using the following flags \ref M2M_ATE_DISABLE_SELF_MACADDR
\ref M2M_ATE_SET_SELF_MACADDR
*/
} tstrM2mAteRx;
//@}
/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
FUNCTION PROTOTYPES
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
#ifdef __cplusplus
extern "C" {
#endif
/**@defgroup ATEFunction Function
* @ingroup m2m_ate
* @{
*/
/*!
@fn \
sint8 m2m_ate_init(void);
@brief
This function used to download the ATE firmware from flash and start it.
@return
The function SHALL return @ref M2M_SUCCESS for success and a negative value otherwise.
@see
m2m_ate_init_param
*/
sint8 m2m_ate_init(void);
/*!
@fn \
sint8 m2m_ate_init(tstrM2mAteInit *pstrInit);
@brief
This function is used to download and start the ATE firmware with an initialization value
stating the rx mode power \ref tstrM2mAteInit.
@param [in] tstrM2mAteInit *
Pointer to a structure \ref tstrM2mAteInit, defining the initial RX mode value.
@return
The function SHALL return @ref M2M_SUCCESS for success and a negative value otherwise.
@see
m2m_ate_init
*/
sint8 m2m_ate_init_param(tstrM2mAteInit *pstrInit);
/*!
@fn \
sint8 m2m_ate_deinit(void);
@brief
De-Initialization of ATE firmware mode
@return
The function SHALL return @ref M2M_SUCCESS for success and a negative value otherwise.
*/
sint8 m2m_ate_deinit(void);
/*!
@fn \
sint8 m2m_ate_set_fw_state(uint8);
@brief
This function is used to change the ATE firmware status from running to stopped or vice versa.
@param [in] u8State
Required state of the ATE firmware, one of \ref tenuM2mAteFwState enumeration values.
@return
The function SHALL return @ref M2M_SUCCESS for success and a negative value otherwise.
@see
m2m_ate_init
*/
sint8 m2m_ate_set_fw_state(uint8);
/*!
@fn \
sint8 m2m_ate_get_fw_state(uint8);
@brief
This function is used to return the status of ATE firmware.
@return
The function SHALL return the status of ATE firmware, one of \ref tenuM2mAteFwState enumeration values.
@see
m2m_ate_init, m2m_ate_set_fw_state
*/
sint8 m2m_ate_get_fw_state(void);
/*!
@fn \
uint32 m2m_ate_get_tx_rate(uint8);
@brief
This function is used to return value of TX rate required by application developer.
@param [in] u8Index
Index of the required rate , one of \ref tenuM2mAteTxIndexOfRates enumeration values.
@return
The function SHALL return 0 in case of receiving invalid index, otherwise the selected rate value is returned.
@see
tenuM2mAteTxIndexOfRates
*/
uint32 m2m_ate_get_tx_rate(uint8);
/*!
@fn \
sint8 m2m_ate_get_tx_status(void);
@brief
This function is used to return the status of TX test case either running or stopped.
@return
The function SHALL return the status of ATE firmware, 1 if TX test case is running or 0 if TX test case has been stopped.
@see
m2m_ate_start_tx, m2m_ate_stop_tx
*/
sint8 m2m_ate_get_tx_status(void);
/*!
@fn \
sint8 m2m_ate_start_tx(tstrM2mAteTx *)
@brief
This function is used to start the TX test case.
@param [in] strM2mAteTx
Type of \ref tstrM2mAteTx, with the values required to enable TX test case. Application must use \ref m2m_ate_init first.
@return
The function SHALL return 0 for success and a negative value otherwise.
@see
m2m_ate_init, m2m_ate_stop_tx, m2m_ate_get_tx_status
*/
sint8 m2m_ate_start_tx(tstrM2mAteTx *);
/*!
@fn \
sint8 m2m_ate_stop_tx(void)
@brief
This function is used to stop the TX test case.
@return
The function SHALL return @ref M2M_SUCCESS for success and a negative value otherwise.
@see
m2m_ate_init, m2m_ate_start_tx, m2m_ate_get_tx_status
*/
sint8 m2m_ate_stop_tx(void);
/*!
@fn \
sint8 m2m_ate_get_rx_status(uint8);
@brief
This function is used to return the status of RX test case either running or stopped.
@return
The function SHALL return status of ATE firmware, 1 if RX test case is running or 0 when the test case has been stopped.
@see
m2m_ate_start_rx, m2m_ate_stop_rx
*/
sint8 m2m_ate_get_rx_status(void);
/*!
@fn \
sint8 m2m_ate_start_rx(tstrM2mAteRx *)
@brief
This function is used to start RX test case.
@param [in] strM2mAteRx
Type of \ref tstrM2mAteRx, with the values required to enable RX test case. Application must use \ref m2m_ate_init first.
@return
The function SHALL return @ref M2M_SUCCESS for success and a negative value otherwise.
@see
m2m_ate_init, m2m_ate_stop_rx, m2m_ate_get_rx_status
*/
sint8 m2m_ate_start_rx(tstrM2mAteRx *);
/*!
@fn \
sint8 m2m_ate_stop_rx(void)
@brief
This function is used to stop RX test case.
@return
The function SHALL return @ref M2M_SUCCESS for success and a negative value otherwise.
@see
m2m_ate_init, m2m_ate_start_rx, m2m_ate_get_rx_status
*/
sint8 m2m_ate_stop_rx(void);
/*!
@fn \
sint8 m2m_ate_read_rx_status(tstrM2mAteRxStatus *)
@brief
This function is used to read RX statistics from the ATE firmware.
@param [out] strM2mAteRxStatus
Type of \ref tstrM2mAteRxStatus used to save statistics of RX test case. Application must use \ref m2m_ate_start_rx first.
@return
The function SHALL return @ref M2M_SUCCESS for success and a negative value otherwise.
@see
m2m_ate_init, m2m_ate_start_rx
*/
sint8 m2m_ate_read_rx_status(tstrM2mAteRxStatus *);
/*!
@fn \
sint8 m2m_ate_set_dig_gain(double dGaindB)
@brief
This function is used to set the digital gain value to the HW registers in dB.
@param [in] double dGaindB
The digital gain value required to be set.
@return
The function SHALL return @ref M2M_SUCCESS for success and a negative value otherwise.
@see
m2m_ate_get_dig_gain, m2m_ate_get_pa_gain,m2m_ate_get_ppa_gain,m2m_ate_get_tot_gain
*/
sint8 m2m_ate_set_dig_gain(double dGaindB);
/*!
@fn \
sint8 m2m_ate_get_dig_gain(double * dGaindB)
@brief
This function is used to retrieve the digital gain value from the HW registers in dB.
Digital gain is one of the values that are set to calculate the total tx gain value.
@param [out] double * dGaindB
The retrieved digital gain value obtained from HW registers in dB.
@return
The function SHALL return @ref M2M_SUCCESS for success and a negative value otherwise.
@see
m2m_ate_set_dig_gain, m2m_ate_get_pa_gain,m2m_ate_get_ppa_gain,m2m_ate_get_tot_gain
*/
sint8 m2m_ate_get_dig_gain(double * dGaindB);
/*!
@fn \
void m2m_ate_set_pa_gain(uint8 gain_db)
@brief
This function is used to set the PA gain (18/15/12/9/6/3/0 only)
@param [in] uint8 gain_db
PA gain level allowed (18/15/12/9/6/3/0 only)
*/
void m2m_ate_set_pa_gain(uint8 gain_db);
/*!
@fn \
sint8 m2m_ate_get_pa_gain(double *paGaindB)
@brief
This function is used to get the Power Amplifier(PA) gain
@param [out] double *paGaindB
The retrieved PA gain value obtained from HW registers in dB.
@return
The function SHALL return @ref M2M_SUCCESS for success and a negative value otherwise.
@see
m2m_ate_set_dig_gain, m2m_ate_get_dig_gain,m2m_ate_get_ppa_gain,m2m_ate_get_tot_gain
*/
sint8 m2m_ate_get_pa_gain(double *paGaindB);
/*!
@fn \
sint8 m2m_ate_get_ppa_gain(double * ppaGaindB)
@brief
This function is used to get the Pre-Power Amplifier(PPA) gain
@param [out] uint32 * ppaGaindB
The retrieved PPA gain value obtained from HW registers in dB.
@return
The function SHALL return 0 for success and a negative value otherwise.
@see
m2m_ate_set_dig_gain, m2m_ate_get_dig_gain,m2m_ate_get_pa_gain,m2m_ate_get_tot_gain
*/
sint8 m2m_ate_get_ppa_gain(double * ppaGaindB);
/*!
@fn \
sint8 m2m_ate_get_tot_gain(double * totGaindB)
@brief
This function is used to calculate the total tx gain value
@param [out] double * totGaindB
The retrieved total gain value obtained from calculations made based on the digital gain, PA and PPA gain values.
@return
The function SHALL return @ref M2M_SUCCESS for success and a negative value otherwise.
@see
m2m_ate_set_dig_gain, m2m_ate_get_dig_gain,m2m_ate_get_pa_gain,m2m_ate_get_ppa_gain
*/
sint8 m2m_ate_get_tot_gain(double * totGaindB);
//@}
#ifdef __cplusplus
}
#endif
#endif /* _M2M_CONFIG_MODE_H_ */
#endif //_M2M_ATE_FW_
@@ -0,0 +1,272 @@
/**
*
* \file
*
* \brief WINC Crypto Application Interface.
*
* Copyright (c) 2016-2017 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
#ifndef __M2M_CRYPTO_H__
#define __M2M_CRYPTO_H__
/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
INCLUDES
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
#include "common/include/nm_common.h"
#include "driver/include/m2m_types.h"
#include "driver/source/m2m_hif.h"
/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
MACROS
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
#define M2M_MAX_RSA_LEN (256)
#define M2M_SHA256_DIGEST_LEN 32
#define M2M_SHA256_MAX_DATA (M2M_BUFFER_MAX_SIZE - M2M_SHA256_CONTEXT_BUFF_LEN - M2M_HIF_HDR_OFFSET)
/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
DATA TYPES
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
/*!
@struct \
tstrM2mSha256Ctxt
@brief
SHA256 context data
*/
typedef struct sha256ctxt{
uint32 au32Sha256CtxtBuff[M2M_SHA256_CONTEXT_BUFF_LEN/sizeof(uint32)];
} tstrM2mSha256Ctxt;
/*!
@enum \
tenuRsaSignStatus
@brief
RSA Signature status: pass or fail.
@see
m2m_crypto_rsa_sign_gen
*/
typedef enum{
M2M_RSA_SIGN_OK,
M2M_RSA_SIGN_FAIL
} tenuRsaSignStatus;
/*!
@typedef \
tpfAppCryproCb
@brief Crypto Calback function receiving the crypto related messages
@param [in] u8MsgType
Crypto command about which the notification is received.
@param [in] pvResp
A pointer to the result associated with the notification.
@param [in] pvMsg
A pointer to a buffer containing the notification parameters (if any). It should be
Casted to the correct data type corresponding to the notification type.
@see
m2m_crypto_init
tenuM2mCryptoCmd
*/
typedef void (*tpfAppCryproCb) (uint8 u8MsgType,void * pvResp, void * pvMsg);
/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
FUNCTION PROTOTYPES
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
#ifdef __cplusplus
extern "C" {
#endif
/*!
@fn \
sint8 m2m_crypto_init();
@brief crypto initialization.
@param[in] pfAppCryproCb
Pointer to the Crypto Calback function receiving the crypto related messages.
@see
tpfAppCryproCb
@return
The function returns @ref M2M_SUCCESS for successful operation and a negative value otherwise.
*/
sint8 m2m_crypto_init(tpfAppCryproCb pfAppCryproCb);
/*!
@fn \
sint8 m2m_sha256_hash_init(tstrM2mSha256Ctxt *psha256Ctxt);
@brief SHA256 hash initialization
@param[in] psha256Ctxt
Pointer to a sha256 context allocated by the caller.
@return
The function returns @ref M2M_SUCCESS for successful operation and a negative value otherwise.
*/
sint8 m2m_crypto_sha256_hash_init(tstrM2mSha256Ctxt *psha256Ctxt);
/*!
@fn \
sint8 m2m_sha256_hash_update(tstrM2mSha256Ctxt *psha256Ctxt, uint8 *pu8Data, uint16 u16DataLength);
@brief SHA256 hash update
@param [in] psha256Ctxt
Pointer to the sha256 context.
@param [in] pu8Data
Buffer holding the data submitted to the hash.
@param [in] u16DataLength
Size of the data bufefr in bytes.
@pre SHA256 module should be initialized first through m2m_crypto_sha256_hash_init function.
@see m2m_crypto_sha256_hash_init
@return
The function returns @ref M2M_SUCCESS for successful operation and a negative value otherwise.
*/
sint8 m2m_crypto_sha256_hash_update(tstrM2mSha256Ctxt *psha256Ctxt, uint8 *pu8Data, uint16 u16DataLength);
/*!
@fn \
sint8 m2m_sha256_hash_finish(tstrM2mSha256Ctxt *psha256Ctxt, uint8 *pu8Sha256Digest);
@brief SHA256 hash finalization
@param[in] psha256Ctxt
Pointer to a sha256 context allocated by the caller.
@param [in] pu8Sha256Digest
Buffer allocated by the caller which will hold the resultant SHA256 Digest. It must be allocated no less than M2M_SHA256_DIGEST_LEN.
@return
The function returns @ref M2M_SUCCESS for successful operation and a negative value otherwise.
*/
sint8 m2m_crypto_sha256_hash_finish(tstrM2mSha256Ctxt *psha256Ctxt, uint8 *pu8Sha256Digest);
/*!
@fn \
sint8 m2m_rsa_sign_verify(uint8 *pu8N, uint16 u16NSize, uint8 *pu8E, uint16 u16ESize, uint8 *pu8SignedMsgHash, \
uint16 u16HashLength, uint8 *pu8RsaSignature);
@brief RSA Signature Verification
The function shall request the RSA Signature verification from the WINC Firmware for the given message. The signed message shall be
compressed to the corresponding hash algorithm before calling this function.
The hash type is identified by the given hash length. For example, if the hash length is 32 bytes, then it is SHA256.
@param[in] pu8N
RSA Key modulus n.
@param[in] u16NSize
Size of the RSA modulus n in bytes.
@param[in] pu8E
RSA public exponent.
@param[in] u16ESize
Size of the RSA public exponent in bytes.
@param[in] pu8SignedMsgHash
The hash digest of the signed message.
@param[in] u16HashLength
The length of the hash digest.
@param[out] pu8RsaSignature
Signature value to be verified.
@return
The function returns @ref M2M_SUCCESS for successful operation and a negative value otherwise.
*/
sint8 m2m_crypto_rsa_sign_verify(uint8 *pu8N, uint16 u16NSize, uint8 *pu8E, uint16 u16ESize, uint8 *pu8SignedMsgHash,
uint16 u16HashLength, uint8 *pu8RsaSignature);
/*!
@fn \
sint8 m2m_rsa_sign_gen(uint8 *pu8N, uint16 u16NSize, uint8 *pu8d, uint16 u16dSize, uint8 *pu8SignedMsgHash, \
uint16 u16HashLength, uint8 *pu8RsaSignature);
@brief RSA Signature Generation
The function shall request the RSA Signature generation from the WINC Firmware for the given message. The signed message shall be
compressed to the corresponding hash algorithm before calling this function.
The hash type is identified by the given hash length. For example, if the hash length is 32 bytes, then it is SHA256.
@param[in] pu8N
RSA Key modulus n.
@param[in] u16NSize
Size of the RSA modulus n in bytes.
@param[in] pu8d
RSA private exponent.
@param[in] u16dSize
Size of the RSA private exponent in bytes.
@param[in] pu8SignedMsgHash
The hash digest of the signed message.
@param[in] u16HashLength
The length of the hash digest.
@param[out] pu8RsaSignature
Pointer to a user buffer allocated by teh caller shall hold the generated signature.
@return
The function returns @ref M2M_SUCCESS for successful operation and a negative value otherwise.
*/
sint8 m2m_crypto_rsa_sign_gen(uint8 *pu8N, uint16 u16NSize, uint8 *pu8d, uint16 u16dSize, uint8 *pu8SignedMsgHash,
uint16 u16HashLength, uint8 *pu8RsaSignature);
#ifdef __cplusplus
}
#endif
#endif /* __M2M_CRYPTO_H__ */
@@ -0,0 +1,428 @@
/**
*
* \file
*
* \brief WINC OTA Upgrade API Interface.
*
* Copyright (c) 2016-2017 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
#ifndef __M2M_OTA_H__
#define __M2M_OTA_H__
/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
INCLUDES
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
#include "common/include/nm_common.h"
#include "driver/include/m2m_types.h"
#include "driver/source/nmdrv.h"
/**@addtogroup WlanEnums DataTypes
* @ingroup m2m_wifi
*/
/* @{ */
/*!
@typedef void (*tpfOtaNotifCb) (tstrOtaUpdateInfo *);
@brief
A callback to get notification about a potential OTA update.
@param[in] pstrOtaUpdateInfo
A structure to provide notification payload.
@sa
tstrOtaUpdateInfo
@warning
The notification is not supported (Not implemented yet)
*/
typedef void (*tpfOtaNotifCb) (tstrOtaUpdateInfo * pstrOtaUpdateInfo);
/*!
@typedef void (*tpfOtaUpdateCb) (uint8 u8OtaUpdateStatusType ,uint8 u8OtaUpdateStatus);
@brief
A callback to get OTA status update, the callback provide the status type and its status.
The OTA callback provides the download status, the switch to the downloaded firmware status and roll-back status.
@param[in] u8OtaUpdateStatusType Possible values are listed in tenuOtaUpdateStatusType.
@param[in] u8OtaUpdateStatus Possible values are listed as enumerated by @ref tenuOtaUpdateStatus.
@see
tenuOtaUpdateStatusType
tenuOtaUpdateStatus
*/
typedef void (*tpfOtaUpdateCb) (uint8 u8OtaUpdateStatusType ,uint8 u8OtaUpdateStatus);
/**@}*/
/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
FUNCTION PROTOTYPES
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
#ifdef __cplusplus
extern "C" {
#endif
/** @defgroup OtaInitFn m2m_ota_init
* @ingroup WLANAPI
* Synchronous initialization function for the OTA layer by registering the update callback.
* The notification callback is not supported at the current version. Calling this API is a
* MUST for all the OTA API's.
*/
/**@{*/
/*!
@fn \
NMI_API sint8 m2m_ota_init(tpfOtaUpdateCb pfOtaUpdateCb,tpfOtaNotifCb pfOtaNotifCb)
@param [in] pfOtaUpdateCb
OTA Update callback function
@param [in] pfOtaNotifCb
OTA notify callback function
@return
The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise.
*/
NMI_API sint8 m2m_ota_init(tpfOtaUpdateCb pfOtaUpdateCb,tpfOtaNotifCb pfOtaNotifCb);
/**@}*/
/** @defgroup OtaNotifStFn m2m_ota_notif_set_url
* @ingroup WLANAPI
* Set the OTA notification server URL, the functions need to be called before any check for update
*/
/**@{*/
/*!
@fn \
NMI_API sint8 m2m_ota_notif_set_url(uint8 * u8Url);
@param [in] u8Url
Set the OTA notification server URL, the functions need to be called before any check for update.
@warning
Calling m2m_ota_init is required
Notification Server is not supported in the current version (function is not implemented)
@see
m2m_ota_init
@return
The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise.
*/
NMI_API sint8 m2m_ota_notif_set_url(uint8 * u8Url);
/**@}*/
/** @defgroup OtaNotifCheckFn m2m_ota_notif_check_for_update
* @ingroup WLANAPI
* Synchronous function to check for the OTA update using the Notification Server
* URL. Function is not implemented (not supported at the current version)
*
*/
/**@{*/
/*!
@fn \
NMI_API sint8 m2m_ota_notif_check_for_update(void);
@warning
Function is not implemented (not supported at the current version)
@sa
m2m_ota_init
m2m_ota_notif_set_url
@return
The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise.
*/
NMI_API sint8 m2m_ota_notif_check_for_update(void);
/**@}*/
/** @defgroup OtaSched m2m_ota_notif_sched
* @ingroup WLANAPI
* Schedule OTA notification Server check for update request after specific number of days
*/
/**@{*/
/*!
@fn \
NMI_API sint8 m2m_ota_notif_sched(uint32 u32Period);
@param [in] u32Period
Period in days
@sa
m2m_ota_init
m2m_ota_notif_check_for_update
m2m_ota_notif_set_url
@return
The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise.
*/
NMI_API sint8 m2m_ota_notif_sched(uint32 u32Period);
/**@}*/
/** @defgroup OtaStartUpdatefn m2m_ota_start_update
* @ingroup WLANAPI
* Request OTA start update using the downloaded URL, the OTA module will download the OTA image and ensure integrity of the image,
* and update the validity of the image in control structure. Switching to that image requires calling @ref m2m_ota_switch_firmware API.
* As a prerequisite @ref m2m_ota_init should be called before using @ref m2m_ota_start().
*/
/**@{*/
/*!
@fn \
NMI_API sint8 m2m_ota_start_update(uint8 * u8DownloadUrl);
@param [in] u8DownloadUrl
The download firmware URL, you get it from device info according to the application server
@warning
Calling this API does not guarantee OTA WINC image update, It depends on the connection with the download server and the validity of the image.
If the API response is failure this may invalidate the roll-back image if it was previously valid, since the WINC does not have any internal memory
except the flash roll-back image location to validate the downloaded image from
@see
m2m_ota_init
tpfOtaUpdateCb
@return
The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise.
\section Example
The example shows an example of how the OTA image update is carried out.
@code
static void OtaUpdateCb(uint8 u8OtaUpdateStatusType ,uint8 u8OtaUpdateStatus)
{
if(u8OtaUpdateStatusType == DL_STATUS) {
if(u8OtaUpdateStatus == OTA_STATUS_SUCSESS) {
//switch to the upgraded firmware
m2m_ota_switch_firmware();
}
}
else if(u8OtaUpdateStatusType == SW_STATUS) {
if(u8OtaUpdateStatus == OTA_STATUS_SUCSESS) {
M2M_INFO("Now OTA successfully done");
//start the host SW upgrade then system reset is required (Reinitialize the driver)
}
}
}
void wifi_event_cb(uint8 u8WiFiEvent, void * pvMsg)
{
case M2M_WIFI_REQ_DHCP_CONF:
{
//after successfully connection, start the over air upgrade
m2m_ota_start_update(OTA_URL);
}
break;
default:
break;
}
int main (void)
{
tstrWifiInitParam param;
tstr1xAuthCredentials gstrCred1x = AUTH_CREDENTIALS;
nm_bsp_init();
m2m_memset((uint8*)&param, 0, sizeof(param));
param.pfAppWifiCb = wifi_event_cb;
//Initialize the WINC Driver
ret = m2m_wifi_init(&param);
if (M2M_SUCCESS != ret)
{
M2M_ERR("Driver Init Failed <%d>\n",ret);
while(1);
}
//Initialize the OTA module
m2m_ota_init(OtaUpdateCb,NULL);
//connect to AP that provide connection to the OTA server
m2m_wifi_default_connect();
while(1)
{
//Handle the app state machine plus the WINC event handler
while(m2m_wifi_handle_events(NULL) != M2M_SUCCESS) {
}
}
}
@endcode
*/
NMI_API sint8 m2m_ota_start_update(uint8 * u8DownloadUrl);
/**@}*/
/** @defgroup OtaStartUpdatefn m2m_ota_start_update_crt
* @ingroup WLANAPI
* Request OTA start for cortus application image using the downloaded URL, the OTA module will download the OTA image and ensure integrity of the image,
* and update the validity of the image in control structure. Switching to that image requires calling @ref m2m_ota_switch_crt API.
* As a prerequisite @ref m2m_ota_init should be called before using @ref m2m_ota_start_update_crt().
*/
/**@{*/
/*!
@fn \
NMI_API sint8 m2m_ota_start_update_crt(uint8 * u8DownloadUrl);
@param [in] u8DownloadUrl
The cortus application image url.
@warning
Calling this API does not guarantee cortus application image update, It depends on the connection with the download server and the validity of the image.
If the API response is failure this may invalidate the roll-back image if it was previously valid, since the WINC does not have any internal memory
except the flash roll-back image location to validate the downloaded image from
@see
m2m_ota_init
tpfOtaUpdateCb
@return
The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise.
*/
NMI_API sint8 m2m_ota_start_update_crt(uint8 * u8DownloadUrl);
/**@}*/
/** @defgroup OtaRollbackfn m2m_ota_rollback
* @ingroup WLANAPI
Request OTA Roll-back to the old (other) WINC image, the WINC firmware will check the validation of the Roll-back image
and switch to it if it is valid.
If the API response is success, system restart is required (re-initialize the driver with hardware rest) update the host driver version may
be required if it is did not match the minimum version supported by the WINC firmware.
*/
/**@{*/
/*!
@fn \
NMI_API sint8 m2m_ota_rollback(void);
@sa
m2m_ota_init
m2m_ota_start_update
@return
The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise.
*/
NMI_API sint8 m2m_ota_rollback(void);
/**@}*/
/** @defgroup OtaRollbackfn m2m_ota_rollback_crt
* @ingroup WLANAPI
Request Cortus application OTA Roll-back to the old (other) cortus application image, the WINC firmware will check the validation of the Roll-back image
and switch to it if it is valid.
If the API response is success, system restart is required (re-initialize the driver with hardware rest) update the host driver version may
be required.
*/
/**@{*/
/*!
@fn \
NMI_API sint8 m2m_ota_rollback_crt(void);
@sa
m2m_ota_init
m2m_ota_start_update_crt
@return
The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise.
*/
NMI_API sint8 m2m_ota_rollback_crt(void);
/**@}*/
/** @defgroup OtaAbortfn m2m_ota_abort
* @ingroup WLANAPI
Request abort of current OTA download.
The WINC firmware will terminate the OTA download if one is in progress.
If no download is in progress, the API will respond with failure.
*/
/**@{*/
/*!
@fn \
NMI_API sint8 m2m_ota_abort(void);
@return
The function returns @ref M2M_SUCCESS for successful operation and a negative value otherwise.
*/
NMI_API sint8 m2m_ota_abort(void);
/**@}*/
/**@}*/
/** @defgroup OtaSwitchFirmware m2m_ota_switch_firmware
* @ingroup WLANAPI
* Switch to the upgraded Firmware, that API will update the control structure working image to the upgraded image
take effect will be on the next system restart
*/
/**@{*/
/*!
@fn \
NMI_API sint8 m2m_ota_switch_firmware(void);
@warning
It is important to note that if the API succeeds, system restart is required (re-initializing the driver with hardware reset) updating the host driver version may be required
if it does not match the minimum driver version supported by the WINC's firmware.
@sa
m2m_ota_init
m2m_ota_start_update
@return
The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise.
*/
NMI_API sint8 m2m_ota_switch_firmware(void);
/**@}*/
/**@}*/
/** @defgroup OtaSwitchFirmware m2m_ota_switch_crt
* @ingroup WLANAPI
* Switch to the upgraded cortus application, that API will update the control structure working image to the upgraded image
take effect will be on the next system restart
*/
/**@{*/
/*!
@fn \
NMI_API sint8 m2m_ota_switch_firmware(void);
@warning
It is important to note that if the API succeeds, system restart is required (re-initializing the driver with hardware reset) updating the host driver version may be required
if it does not match the minimum driver version supported by the WINC's firmware.
@sa
m2m_ota_init
m2m_ota_start_update_crt
@return
The function returns @ref M2M_SUCCESS for successful operations and a negative value otherwise.
*/
NMI_API sint8 m2m_ota_switch_crt(void);
/*!
@fn \
NMI_API sint8 m2m_ota_get_firmware_version(void);
@brief
Get the OTA Firmware version.
@return
The function SHALL return 0 for success and a negative value otherwise.
*/
NMI_API sint8 m2m_ota_get_firmware_version(tstrM2mRev *pstrRev);
/**@}*/
NMI_API sint8 m2m_ota_test(void);
#ifdef __cplusplus
}
#endif
#endif /* __M2M_OTA_H__ */
@@ -0,0 +1,411 @@
/**
*
* \file
*
* \brief WINC Peripherals Application Interface.
*
* Copyright (c) 2016 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
#ifndef _M2M_PERIPH_H_
#define _M2M_PERIPH_H_
/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
INCLUDES
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
#include "common/include/nm_common.h"
#include "driver/include/m2m_types.h"
/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
MACROS
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
DATA TYPES
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
/*!
@struct \
tstrPerphInitParam
@brief
Peripheral module initialization parameters.
*/
typedef struct {
void * arg;
} tstrPerphInitParam;
/*!
@enum \
tenuGpioNum
@brief
A list of GPIO numbers configurable through the m2m_periph module.
*/
typedef enum {
M2M_PERIPH_GPIO3, /*!< GPIO15 pad */
M2M_PERIPH_GPIO4, /*!< GPIO16 pad */
M2M_PERIPH_GPIO5, /*!< GPIO18 pad */
M2M_PERIPH_GPIO6, /*!< GPIO18 pad */
M2M_PERIPH_GPIO15, /*!< GPIO15 pad */
M2M_PERIPH_GPIO16, /*!< GPIO16 pad */
M2M_PERIPH_GPIO18, /*!< GPIO18 pad */
M2M_PERIPH_GPIO_MAX
} tenuGpioNum;
/*!
@enum \
tenuI2cMasterSclMuxOpt
@brief
Allowed pin multiplexing options for I2C master SCL signal.
*/
typedef enum {
M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_HOST_WAKEUP, /*!< I2C master SCL is avaiable on HOST_WAKEUP. */
M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_SD_DAT3, /*!< I2C master SCL is avaiable on SD_DAT3 (GPIO 7). */
M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_GPIO13, /*!< I2C master SCL is avaiable on GPIO 13. */
M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_GPIO4, /*!< I2C master SCL is avaiable on GPIO 4.*/
M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_I2C_SCL, /*!< I2C master SCL is avaiable on I2C slave SCL. */
M2M_PERIPH_I2C_MASTER_SCL_MUX_OPT_NUM
} tenuI2cMasterSclMuxOpt;
/*!
@enum \
tenuI2cMasterSdaMuxOpt
@brief
Allowed pin multiplexing options for I2C master SDA signal.
*/
typedef enum {
M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_RTC_CLK , /*!< I2C master SDA is avaiable on RTC_CLK. */
M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_SD_CLK, /*!< I2C master SDA is avaiable on SD_CLK (GPIO 8). */
M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_GPIO14, /*!< I2C master SDA is avaiable on GPIO 14. */
M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_GPIO6, /*!< I2C master SDA is avaiable on GPIO 6.*/
M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_I2C_SDA, /*!< I2C master SDA is avaiable on I2C slave SDA. */
M2M_PERIPH_I2C_MASTER_SDA_MUX_OPT_NUM
} tenuI2cMasterSdaMuxOpt;
/*!
@struct \
tstrI2cMasterInitParam
@brief
I2C master configuration parameters.
@sa
tenuI2cMasterSclMuxOpt
tenuI2cMasterSdaMuxOpt
*/
typedef struct {
uint8 enuSclMuxOpt; /*!< SCL multiplexing option. Allowed value are defined in tenuI2cMasterSclMuxOpt */
uint8 enuSdaMuxOpt; /*!< SDA multiplexing option. Allowed value are defined in tenuI2cMasterSdaMuxOpt */
uint8 u8ClkSpeedKHz; /*!< I2C master clock speed in KHz. */
} tstrI2cMasterInitParam;
/*!
@enum \
tenuI2cMasterFlags
@brief
Bitwise-ORed flags for use in m2m_periph_i2c_master_write and m2m_periph_i2c_master_read
@sa
m2m_periph_i2c_master_write
m2m_periph_i2c_master_read
*/
typedef enum {
I2C_MASTER_NO_FLAGS = 0x00,
/*!< No flags. */
I2C_MASTER_NO_STOP = 0x01,
/*!< No stop bit after this transaction. Useful for scattered buffer read/write operations. */
I2C_MASTER_NO_START = 0x02,
/*!< No start bit at the beginning of this transaction. Useful for scattered buffer read/write operations.*/
} tenuI2cMasterFlags;
/*!
@enum \
tenuPullupMask
@brief
Bitwise-ORed flags for use in m2m_perph_pullup_ctrl.
@sa
m2m_periph_pullup_ctrl
*/
typedef enum {
M2M_PERIPH_PULLUP_DIS_HOST_WAKEUP = (1ul << 0),
M2M_PERIPH_PULLUP_DIS_RTC_CLK = (1ul << 1),
M2M_PERIPH_PULLUP_DIS_IRQN = (1ul << 2),
M2M_PERIPH_PULLUP_DIS_GPIO_3 = (1ul << 3),
M2M_PERIPH_PULLUP_DIS_GPIO_4 = (1ul << 4),
M2M_PERIPH_PULLUP_DIS_GPIO_5 = (1ul << 5),
M2M_PERIPH_PULLUP_DIS_SD_DAT3 = (1ul << 6),
M2M_PERIPH_PULLUP_DIS_SD_DAT2_SPI_RXD = (1ul << 7),
M2M_PERIPH_PULLUP_DIS_SD_DAT1_SPI_SSN = (1ul << 9),
M2M_PERIPH_PULLUP_DIS_SD_CMD_SPI_SCK = (1ul << 10),
M2M_PERIPH_PULLUP_DIS_SD_DAT0_SPI_TXD = (1ul << 11),
M2M_PERIPH_PULLUP_DIS_GPIO_6 = (1ul << 12),
M2M_PERIPH_PULLUP_DIS_SD_CLK = (1ul << 13),
M2M_PERIPH_PULLUP_DIS_I2C_SCL = (1ul << 14),
M2M_PERIPH_PULLUP_DIS_I2C_SDA = (1ul << 15),
M2M_PERIPH_PULLUP_DIS_GPIO_11 = (1ul << 16),
M2M_PERIPH_PULLUP_DIS_GPIO_12 = (1ul << 17),
M2M_PERIPH_PULLUP_DIS_GPIO_13 = (1ul << 18),
M2M_PERIPH_PULLUP_DIS_GPIO_14 = (1ul << 19),
M2M_PERIPH_PULLUP_DIS_GPIO_15 = (1ul << 20),
M2M_PERIPH_PULLUP_DIS_GPIO_16 = (1ul << 21),
M2M_PERIPH_PULLUP_DIS_GPIO_17 = (1ul << 22),
M2M_PERIPH_PULLUP_DIS_GPIO_18 = (1ul << 23),
M2M_PERIPH_PULLUP_DIS_GPIO_19 = (1ul << 24),
M2M_PERIPH_PULLUP_DIS_GPIO_20 = (1ul << 25),
M2M_PERIPH_PULLUP_DIS_GPIO_21 = (1ul << 26),
M2M_PERIPH_PULLUP_DIS_GPIO_22 = (1ul << 27),
M2M_PERIPH_PULLUP_DIS_GPIO_23 = (1ul << 28),
M2M_PERIPH_PULLUP_DIS_GPIO_24 = (1ul << 29),
} tenuPullupMask;
/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
FUNCTION PROTOTYPES
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
#ifdef __cplusplus
extern "C" {
#endif
/*!
@fn \
NMI_API sint8 m2m_periph_init(tstrPerphInitParam * param);
@brief
Initialize the NMC1500 peripheral driver module.
@param [in] param
Peripheral module initialization structure. See members of tstrPerphInitParam.
@return
The function SHALL return 0 for success and a negative value otherwise.
@sa
tstrPerphInitParam
*/
NMI_API sint8 m2m_periph_init(tstrPerphInitParam * param);
/*!
@fn \
NMI_API sint8 m2m_periph_gpio_set_dir(uint8 u8GpioNum, uint8 u8GpioDir);
@brief
Configure a specific NMC1500 pad as a GPIO and sets its direction (input or output).
@param [in] u8GpioNum
GPIO number. Allowed values are defined in tenuGpioNum.
@param [in] u8GpioDir
GPIO direction: Zero = input. Non-zero = output.
@return
The function SHALL return 0 for success and a negative value otherwise.
@sa
tenuGpioNum
*/
NMI_API sint8 m2m_periph_gpio_set_dir(uint8 u8GpioNum, uint8 u8GpioDir);
/*!
@fn \
NMI_API sint8 m2m_periph_gpio_set_val(uint8 u8GpioNum, uint8 u8GpioVal);
@brief
Set an NMC1500 GPIO output level high or low.
@param [in] u8GpioNum
GPIO number. Allowed values are defined in tenuGpioNum.
@param [in] u8GpioVal
GPIO output value. Zero = low, non-zero = high.
@return
The function SHALL return 0 for success and a negative value otherwise.
@sa
tenuGpioNum
*/
NMI_API sint8 m2m_periph_gpio_set_val(uint8 u8GpioNum, uint8 u8GpioVal);
/*!
@fn \
NMI_API sint8 m2m_periph_gpio_get_val(uint8 u8GpioNum, uint8 * pu8GpioVal);
@brief
Read an NMC1500 GPIO input level.
@param [in] u8GpioNum
GPIO number. Allowed values are defined in tenuGpioNum.
@param [out] pu8GpioVal
GPIO input value. Zero = low, non-zero = high.
@return
The function SHALL return 0 for success and a negative value otherwise.
@sa
tenuGpioNum
*/
NMI_API sint8 m2m_periph_gpio_get_val(uint8 u8GpioNum, uint8 * pu8GpioVal);
/*!
@fn \
NMI_API sint8 m2m_periph_gpio_pullup_ctrl(uint8 u8GpioNum, uint8 u8PullupEn);
@brief
Set an NMC1500 GPIO pullup resisitor enable or disable.
@param [in] u8GpioNum
GPIO number. Allowed values are defined in tenuGpioNum.
@param [in] u8PullupEn
Zero: pullup disabled. Non-zero: pullup enabled.
@return
The function SHALL return 0 for success and a negative value otherwise.
@sa
tenuGpioNum
*/
NMI_API sint8 m2m_periph_gpio_pullup_ctrl(uint8 u8GpioNum, uint8 u8PullupEn);
/*!
@fn \
NMI_API sint8 m2m_periph_i2c_master_init(tstrI2cMasterInitParam * param);
@brief
Initialize and configure the NMC1500 I2C master peripheral.
@param [in] param
I2C master initialization structure. See members of tstrI2cMasterInitParam.
@return
The function SHALL return 0 for success and a negative value otherwise.
@sa
tstrI2cMasterInitParam
*/
NMI_API sint8 m2m_periph_i2c_master_init(tstrI2cMasterInitParam * param);
/*!
@fn \
NMI_API sint8 m2m_periph_i2c_master_write(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint8 flags);
@brief
Write a stream of bytes to the I2C slave device.
@param [in] u8SlaveAddr
7-bit I2C slave address.
@param [in] pu8Buf
A pointer to an input buffer which contains a stream of bytes.
@param [in] u16BufLen
Input buffer length in bytes.
@param [in] flags
Write operation bitwise-ORed flags. See tenuI2cMasterFlags.
@return
The function SHALL return 0 for success and a negative value otherwise.
@sa
tenuI2cMasterFlags
*/
NMI_API sint8 m2m_periph_i2c_master_write(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint8 flags);
/*!
@fn \
NMI_API sint8 m2m_periph_i2c_master_read(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint16 * pu16ReadLen, uint8 flags);
@brief
Write a stream of bytes to the I2C slave device.
@param [in] u8SlaveAddr
7-bit I2C slave address.
@param [out] pu8Buf
A pointer to an output buffer in which a stream of bytes are received.
@param [in] u16BufLen
Max output buffer length in bytes.
@param [out] pu16ReadLen
Actual number of bytes received.
@param [in] flags
Write operation bitwise-ORed flags. See tenuI2cMasterFlags.
@return
The function SHALL return 0 for success and a negative value otherwise.
@sa
tenuI2cMasterFlags
*/
NMI_API sint8 m2m_periph_i2c_master_read(uint8 u8SlaveAddr, uint8 * pu8Buf, uint16 u16BufLen, uint16 * pu16ReadLen, uint8 flags);
/*!
@fn \
NMI_API sint8 m2m_periph_pullup_ctrl(uint32 pinmask, uint8 enable);
@brief
Control the programmable pull-up resistor on the chip pads .
@param [in] pinmask
Write operation bitwise-ORed mask for which pads to control. Allowed values are defined in tenuPullupMask.
@param [in] enable
Set to 0 to disable pull-up resistor. Non-zero will enable the pull-up.
@return
The function SHALL return 0 for success and a negative value otherwise.
@sa
tenuPullupMask
*/
NMI_API sint8 m2m_periph_pullup_ctrl(uint32 pinmask, uint8 enable);
#ifdef __cplusplus
}
#endif
#endif /* _M2M_PERIPH_H_ */
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,826 @@
/**
*
* \file
*
* \brief NMC1500 Peripherials Application Interface.
*
* Copyright (c) 2016-2017 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
#ifdef _M2M_ATE_FW_
/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
INCLUDES
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
#include "driver/include/m2m_ate_mode.h"
#include "driver/source/nmasic.h"
#include "driver/source/nmdrv.h"
#include "m2m_hif.h"
#include "driver/source/nmbus.h"
#include "bsp/include/nm_bsp.h"
/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
MACROS
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
#define rInterrupt_CORTUS_0 (0x10a8)
#define rInterrupt_CORTUS_1 (0x10ac)
#define rInterrupt_CORTUS_2 (0x10b0)
#define rBurstTx_NMI_TX_RATE (0x161d00)
#define rBurstTx_NMI_NUM_TX_FRAMES (0x161d04)
#define rBurstTx_NMI_TX_FRAME_LEN (0x161d08)
#define rBurstTx_NMI_TX_CW_PARAM (0x161d0c)
#define rBurstTx_NMI_TX_GAIN (0x161d10)
#define rBurstTx_NMI_TX_DPD_CTRL (0x161d14)
#define rBurstTx_NMI_USE_PMU (0x161d18)
#define rBurstTx_NMI_TEST_CH (0x161d1c)
#define rBurstTx_NMI_TX_PHY_CONT (0x161d20)
#define rBurstTx_NMI_TX_CW_MODE (0x161d24)
#define rBurstTx_NMI_TEST_XO_OFF (0x161d28)
#define rBurstTx_NMI_USE_EFUSE_XO_OFF (0x161d2c)
#define rBurstTx_NMI_MAC_FILTER_ENABLE_DA (0x161d30)
#define rBurstTx_NMI_MAC_ADDR_LO_PEER (0x161d34)
#define rBurstTx_NMI_MAC_ADDR_LO_SELF (0x161d38)
#define rBurstTx_NMI_MAC_ADDR_HI_PEER (0x161d3c)
#define rBurstTx_NMI_MAC_ADDR_HI_SELF (0x161d40)
#define rBurstTx_NMI_RX_PKT_CNT_SUCCESS (0x161d44)
#define rBurstTx_NMI_RX_PKT_CNT_FAIL (0x161d48)
#define rBurstTx_NMI_SET_SELF_MAC_ADDR (0x161d4c)
#define rBurstTx_NMI_MAC_ADDR_LO_SA (0x161d50)
#define rBurstTx_NMI_MAC_ADDR_HI_SA (0x161d54)
#define rBurstTx_NMI_MAC_FILTER_ENABLE_SA (0x161d58)
#define rBurstRx_NMI_RX_ALL_PKTS_CONT (0x9898)
#define rBurstRx_NMI_RX_ERR_PKTS_CONT (0x988c)
#define TX_DGAIN_MAX_NUM_REGS (4)
#define TX_DGAIN_REG_BASE_ADDRESS (0x1240)
#define TX_GAIN_CODE_MAX_NUM_REGS (3)
#define TX_GAIN_CODE_BASE_ADDRESS (0x1250)
#define TX_PA_MAX_NUM_REGS (3)
#define TX_PA_BASE_ADDRESS (0x1e58)
/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
VARIABLES
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
volatile static uint8 gu8AteIsRunning = 0; /*!< ATE firmware status, 1 means ATE is running otherwise stopped */
volatile static uint8 gu8RxState = 0; /*!< RX status, 1 means Rx is running otherwise stopped */
volatile static uint8 gu8TxState = 0; /*!< TX status, 1 means Tx is running otherwise stopped */
volatile static uint32 gaAteFwTxRates[M2M_ATE_MAX_NUM_OF_RATES] =
{
0x01, 0x02, 0x05, 0x0B, /*B-Rats*/
0x06, 0x09, 0x0C, 0x12, 0x18, 0x24, 0x30, 0x36, /*G-Rats*/
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87 /*N-Rats*/
};
/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
STATIC FUNCTIONS
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
static void m2m_ate_set_rx_status(uint8 u8Value)
{
gu8RxState = u8Value;
}
static void m2m_ate_set_tx_status(uint8 u8Value)
{
gu8TxState = u8Value;
}
/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
FUNCTION IMPLEMENTATION
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
/*!
@fn \
sint8 m2m_ate_init(void);
@brief
This function used to download ATE firmware from flash and start it
@return
The function SHALL return 0 for success and a negative value otherwise.
*/
sint8 m2m_ate_init(void)
{
sint8 s8Ret = M2M_SUCCESS;
uint8 u8WifiMode = M2M_WIFI_MODE_ATE_HIGH;
s8Ret = nm_drv_init(&u8WifiMode);
return s8Ret;
}
/*!
@fn \
sint8 m2m_ate_init(tstrM2mAteInit *pstrInit);
@brief
This function used to download ATE firmware from flash and start it
@return
The function SHALL return 0 for success and a negative value otherwise.
*/
sint8 m2m_ate_init_param(tstrM2mAteInit *pstrInit)
{
sint8 s8Ret = M2M_SUCCESS;
s8Ret = nm_drv_init((void*)&pstrInit->u8RxPwrMode);
return s8Ret;
}
/*!
@fn \
sint8 m2m_ate_deinit(void);
@brief
De-Initialization of ATE firmware mode
@return
The function SHALL return 0 for success and a negative value otherwise.
*/
sint8 m2m_ate_deinit(void)
{
return nm_drv_deinit(NULL);
}
/*!
@fn \
sint8 m2m_ate_set_fw_state(uint8);
@brief
This function used to change ATE firmware status from running to stopped or vice versa.
@param [in] u8State
Required state of ATE firmware, one of \ref tenuM2mAteFwState enumeration values.
@return
The function SHALL return 0 for success and a negative value otherwise.
\sa
m2m_ate_init
*/
sint8 m2m_ate_set_fw_state(uint8 u8State)
{
sint8 s8Ret = M2M_SUCCESS;
uint32_t u32Val = 0;
if((M2M_ATE_FW_STATE_STOP == u8State) && (M2M_ATE_FW_STATE_STOP != gu8AteIsRunning))
{
u32Val = nm_read_reg(rNMI_GLB_RESET);
u32Val &= ~(1 << 10);
s8Ret = nm_write_reg(rNMI_GLB_RESET, u32Val);
gu8AteIsRunning = M2M_ATE_FW_STATE_STOP;
}
else if((M2M_ATE_FW_STATE_RUN == u8State) && (M2M_ATE_FW_STATE_RUN != gu8AteIsRunning))
{
/* 0x1118[0]=0 at power-on-reset: pad-based control. */
/* Switch cortus reset register to register control. 0x1118[0]=1. */
u32Val = nm_read_reg(rNMI_BOOT_RESET_MUX);
u32Val |= (1 << 0);
s8Ret = nm_write_reg(rNMI_BOOT_RESET_MUX, u32Val);
if(M2M_SUCCESS != s8Ret)
{
goto __EXIT;
}
/**
Write the firmware download complete magic value 0x10ADD09E at
location 0xFFFF000C (Cortus map) or C000C (AHB map).
This will let the boot-rom code execute from RAM.
**/
s8Ret = nm_write_reg(0xc0000, 0x71);
if(M2M_SUCCESS != s8Ret)
{
goto __EXIT;
}
u32Val = nm_read_reg(rNMI_GLB_RESET);
if((u32Val & (1ul << 10)) == (1ul << 10))
{
u32Val &= ~(1ul << 10);
s8Ret = nm_write_reg(rNMI_GLB_RESET, u32Val);
if(M2M_SUCCESS != s8Ret)
{
goto __EXIT;
}
}
u32Val |= (1ul << 10);
s8Ret = nm_write_reg(rNMI_GLB_RESET, u32Val);
if(M2M_SUCCESS != s8Ret)
{
goto __EXIT;
}
gu8AteIsRunning = M2M_ATE_FW_STATE_RUN;
}
else
{
s8Ret = M2M_ATE_ERR_UNHANDLED_CASE;
}
__EXIT:
if((M2M_SUCCESS == s8Ret) && (M2M_ATE_FW_STATE_RUN == gu8AteIsRunning))
{
nm_bsp_sleep(500); /*wait for ATE firmware start up*/
}
return s8Ret;
}
/*!
@fn \
sint8 m2m_ate_get_fw_state(uint8);
@brief
This function used to return status of ATE firmware.
@return
The function SHALL return status of ATE firmware, one of \ref tenuM2mAteFwState enumeration values.
\sa
m2m_ate_init, m2m_ate_set_fw_state
*/
sint8 m2m_ate_get_fw_state(void)
{
return gu8AteIsRunning;
}
/*!
@fn \
uint32 m2m_ate_get_tx_rate(uint8);
@brief
This function used to return value of TX rate required by application developer.
@param [in] u8Index
Index of required rate , one of \ref tenuM2mAteTxIndexOfRates enumeration values.
@return
The function SHALL return 0 for in case of failure otherwise selected rate value.
\sa
tenuM2mAteTxIndexOfRates
*/
uint32 m2m_ate_get_tx_rate(uint8 u8Index)
{
if(M2M_ATE_MAX_NUM_OF_RATES <= u8Index)
{
return 0;
}
return gaAteFwTxRates[u8Index];
}
/*!
@fn \
sint8 m2m_ate_get_tx_status(void);
@brief
This function used to return status of TX test case either running or stopped.
@return
The function SHALL return status of ATE firmware, 1 if TX is running otherwise 0.
\sa
m2m_ate_start_tx, m2m_ate_stop_tx
*/
sint8 m2m_ate_get_tx_status(void)
{
return gu8TxState;
}
/*!
@fn \
sint8 m2m_ate_start_tx(tstrM2mAteTx *)
@brief
This function used to start TX test case.
@param [in] strM2mAteTx
Type of \ref tstrM2mAteTx, with the values required to enable TX test case. You must use \ref m2m_ate_init first.
@return
The function SHALL return 0 for success and a negative value otherwise.
\sa
m2m_ate_init, m2m_ate_stop_tx, m2m_ate_get_tx_status
*/
sint8 m2m_ate_start_tx(tstrM2mAteTx * strM2mAteTx)
{
sint8 s8Ret = M2M_SUCCESS;
uint8 u8LoopCntr = 0;
uint32_t val32;
if(NULL == strM2mAteTx)
{
s8Ret = M2M_ATE_ERR_VALIDATE;
goto __EXIT;
}
if(0 != m2m_ate_get_tx_status())
{
s8Ret = M2M_ATE_ERR_TX_ALREADY_RUNNING;
goto __EXIT;
}
if(0 != m2m_ate_get_rx_status())
{
s8Ret = M2M_ATE_ERR_RX_ALREADY_RUNNING;
goto __EXIT;
}
if( (strM2mAteTx->channel_num < M2M_ATE_CHANNEL_1) ||
(strM2mAteTx->channel_num > M2M_ATE_CHANNEL_14) ||
(strM2mAteTx->tx_gain_sel < M2M_ATE_TX_GAIN_DYNAMIC) ||
(strM2mAteTx->tx_gain_sel > M2M_ATE_TX_GAIN_TELEC) ||
(strM2mAteTx->frame_len > M2M_ATE_MAX_FRAME_LENGTH) ||
(strM2mAteTx->frame_len < M2M_ATE_MIN_FRAME_LENGTH)
)
{
s8Ret = M2M_ATE_ERR_VALIDATE;
goto __EXIT;
}
if( (strM2mAteTx->duty_cycle < M2M_ATE_TX_DUTY_MAX_VALUE /*1*/) ||
(strM2mAteTx->duty_cycle > M2M_ATE_TX_DUTY_MIN_VALUE /*10*/ ) ||
(strM2mAteTx->dpd_ctrl < M2M_ATE_TX_DPD_DYNAMIC) ||
(strM2mAteTx->dpd_ctrl > M2M_ATE_TX_DPD_ENABLED) ||
(strM2mAteTx->use_pmu > M2M_ATE_PMU_ENABLE) ||
(strM2mAteTx->phy_burst_tx < M2M_ATE_TX_SRC_MAC) ||
(strM2mAteTx->phy_burst_tx > M2M_ATE_TX_SRC_PHY) ||
(strM2mAteTx->cw_tx < M2M_ATE_TX_MODE_NORM) ||
(strM2mAteTx->cw_tx > M2M_ATE_TX_MODE_CW)
)
{
s8Ret = M2M_ATE_ERR_VALIDATE;
goto __EXIT;
}
for(u8LoopCntr=0; u8LoopCntr<M2M_ATE_MAX_NUM_OF_RATES; u8LoopCntr++)
{
if(gaAteFwTxRates[u8LoopCntr] == strM2mAteTx->data_rate)
{
break;
}
}
if(M2M_ATE_MAX_NUM_OF_RATES == u8LoopCntr)
{
s8Ret = M2M_ATE_ERR_VALIDATE;
goto __EXIT;
}
s8Ret += nm_write_reg(rBurstTx_NMI_USE_PMU, strM2mAteTx->use_pmu);
s8Ret += nm_write_reg(rBurstTx_NMI_TX_PHY_CONT, strM2mAteTx->phy_burst_tx);
s8Ret += nm_write_reg(rBurstTx_NMI_NUM_TX_FRAMES, strM2mAteTx->num_frames);
s8Ret += nm_write_reg(rBurstTx_NMI_TX_GAIN, strM2mAteTx->tx_gain_sel);
s8Ret += nm_write_reg(rBurstTx_NMI_TEST_CH, strM2mAteTx->channel_num);
s8Ret += nm_write_reg(rBurstTx_NMI_TX_FRAME_LEN, strM2mAteTx->frame_len);
s8Ret += nm_write_reg(rBurstTx_NMI_TX_CW_PARAM, strM2mAteTx->duty_cycle);
s8Ret += nm_write_reg(rBurstTx_NMI_TX_DPD_CTRL, strM2mAteTx->dpd_ctrl);
s8Ret += nm_write_reg(rBurstTx_NMI_TX_RATE, strM2mAteTx->data_rate);
s8Ret += nm_write_reg(rBurstTx_NMI_TX_CW_MODE, strM2mAteTx->cw_tx);
s8Ret += nm_write_reg(rBurstTx_NMI_TEST_XO_OFF, strM2mAteTx->xo_offset_x1000);
s8Ret += nm_write_reg(rBurstTx_NMI_USE_EFUSE_XO_OFF, strM2mAteTx->use_efuse_xo_offset);
val32 = strM2mAteTx->peer_mac_addr[5] << 0;
val32 |= strM2mAteTx->peer_mac_addr[4] << 8;
val32 |= strM2mAteTx->peer_mac_addr[3] << 16;
nm_write_reg(rBurstTx_NMI_MAC_ADDR_LO_PEER, val32 );
val32 = strM2mAteTx->peer_mac_addr[2] << 0;
val32 |= strM2mAteTx->peer_mac_addr[1] << 8;
val32 |= strM2mAteTx->peer_mac_addr[0] << 16;
nm_write_reg(rBurstTx_NMI_MAC_ADDR_HI_PEER, val32 );
if(M2M_SUCCESS == s8Ret)
{
s8Ret += nm_write_reg(rInterrupt_CORTUS_0, 1); /*Interrupt Cortus*/
m2m_ate_set_tx_status(1);
nm_bsp_sleep(200); /*Recommended*/
}
__EXIT:
return s8Ret;
}
/*!
@fn \
sint8 m2m_ate_stop_tx(void)
@brief
This function used to stop TX test case.
@return
The function SHALL return 0 for success and a negative value otherwise.
\sa
m2m_ate_init, m2m_ate_start_tx, m2m_ate_get_tx_status
*/
sint8 m2m_ate_stop_tx(void)
{
sint8 s8Ret = M2M_SUCCESS;
s8Ret = nm_write_reg(rInterrupt_CORTUS_1, 1);
if(M2M_SUCCESS == s8Ret)
{
m2m_ate_set_tx_status(0);
}
return s8Ret;
}
/*!
@fn \
sint8 m2m_ate_get_rx_status(uint8);
@brief
This function used to return status of RX test case either running or stopped.
@return
The function SHALL return status of ATE firmware, 1 if RX is running otherwise 0.
\sa
m2m_ate_start_rx, m2m_ate_stop_rx
*/
sint8 m2m_ate_get_rx_status(void)
{
return gu8RxState;
}
/*!
@fn \
sint8 m2m_ate_start_rx(tstrM2mAteRx *)
@brief
This function used to start RX test case.
@param [in] strM2mAteRx
Type of \ref tstrM2mAteRx, with the values required to enable RX test case. You must use \ref m2m_ate_init first.
@return
The function SHALL return 0 for success and a negative value otherwise.
\sa
m2m_ate_init, m2m_ate_stop_rx, m2m_ate_get_rx_status
*/
sint8 m2m_ate_start_rx(tstrM2mAteRx * strM2mAteRxStr)
{
sint8 s8Ret = M2M_SUCCESS;
uint32 val32;
if(NULL == strM2mAteRxStr)
{
s8Ret = M2M_ATE_ERR_VALIDATE;
goto __EXIT;
}
if(0 != m2m_ate_get_tx_status())
{
s8Ret = M2M_ATE_ERR_TX_ALREADY_RUNNING;
goto __EXIT;
}
if(0 != m2m_ate_get_rx_status())
{
s8Ret = M2M_ATE_ERR_RX_ALREADY_RUNNING;
goto __EXIT;
}
if( (strM2mAteRxStr->channel_num < M2M_ATE_CHANNEL_1) ||
(strM2mAteRxStr->channel_num > M2M_ATE_CHANNEL_14)||
(strM2mAteRxStr->use_pmu > M2M_ATE_PMU_ENABLE)
)
{
s8Ret = M2M_ATE_ERR_VALIDATE;
goto __EXIT;
}
s8Ret += nm_write_reg(rBurstTx_NMI_TEST_CH, strM2mAteRxStr->channel_num);
s8Ret += nm_write_reg(rBurstTx_NMI_USE_PMU, strM2mAteRxStr->use_pmu);
s8Ret += nm_write_reg(rBurstTx_NMI_TEST_XO_OFF, strM2mAteRxStr->xo_offset_x1000);
s8Ret += nm_write_reg(rBurstTx_NMI_USE_EFUSE_XO_OFF, strM2mAteRxStr->use_efuse_xo_offset);
if(strM2mAteRxStr->override_self_mac_addr)
{
val32 = strM2mAteRxStr->self_mac_addr[5] << 0;
val32 |= strM2mAteRxStr->self_mac_addr[4] << 8;
val32 |= strM2mAteRxStr->self_mac_addr[3] << 16;
nm_write_reg(rBurstTx_NMI_MAC_ADDR_LO_SELF, val32 );
val32 = strM2mAteRxStr->self_mac_addr[2] << 0;
val32 |= strM2mAteRxStr->self_mac_addr[1] << 8;
val32 |= strM2mAteRxStr->self_mac_addr[0] << 16;
nm_write_reg(rBurstTx_NMI_MAC_ADDR_HI_SELF, val32 );
}
if(strM2mAteRxStr->mac_filter_en_sa)
{
val32 = strM2mAteRxStr->peer_mac_addr[5] << 0;
val32 |= strM2mAteRxStr->peer_mac_addr[4] << 8;
val32 |= strM2mAteRxStr->peer_mac_addr[3] << 16;
nm_write_reg(rBurstTx_NMI_MAC_ADDR_LO_SA, val32 );
val32 = strM2mAteRxStr->peer_mac_addr[2] << 0;
val32 |= strM2mAteRxStr->peer_mac_addr[1] << 8;
val32 |= strM2mAteRxStr->peer_mac_addr[0] << 16;
nm_write_reg(rBurstTx_NMI_MAC_ADDR_HI_SA, val32 );
}
nm_write_reg(rBurstTx_NMI_MAC_FILTER_ENABLE_DA, strM2mAteRxStr->mac_filter_en_da);
nm_write_reg(rBurstTx_NMI_MAC_FILTER_ENABLE_SA, strM2mAteRxStr->mac_filter_en_sa);
nm_write_reg(rBurstTx_NMI_SET_SELF_MAC_ADDR, strM2mAteRxStr->override_self_mac_addr);
if(M2M_SUCCESS == s8Ret)
{
s8Ret += nm_write_reg(rInterrupt_CORTUS_2, 1); /*Interrupt Cortus*/
m2m_ate_set_rx_status(1);
nm_bsp_sleep(10); /*Recommended*/
}
__EXIT:
return s8Ret;
}
/*!
@fn \
sint8 m2m_ate_stop_rx(void)
@brief
This function used to stop RX test case.
@return
The function SHALL return 0 for success and a negative value otherwise.
\sa
m2m_ate_init, m2m_ate_start_rx, m2m_ate_get_rx_status
*/
sint8 m2m_ate_stop_rx(void)
{
m2m_ate_set_rx_status(0);
nm_bsp_sleep(200); /*Recommended*/
return M2M_SUCCESS;
}
/*!
@fn \
sint8 m2m_ate_read_rx_status(tstrM2mAteRxStatus *)
@brief
This function used to read RX statistics from ATE firmware.
@param [out] strM2mAteRxStatus
Type of \ref tstrM2mAteRxStatus used to save statistics of RX test case. You must use \ref m2m_ate_start_rx first.
@return
The function SHALL return 0 for success and a negative value otherwise.
\sa
m2m_ate_init, m2m_ate_start_rx
*/
sint8 m2m_ate_read_rx_status(tstrM2mAteRxStatus *strM2mAteRxStatus)
{
sint8 s8Ret = M2M_SUCCESS;
if(NULL == strM2mAteRxStatus)
{
s8Ret = M2M_ATE_ERR_VALIDATE;
goto __EXIT;
}
if(0 != m2m_ate_get_tx_status())
{
s8Ret = M2M_ATE_ERR_TX_ALREADY_RUNNING;
goto __EXIT;
}
if (nm_read_reg(rBurstTx_NMI_MAC_FILTER_ENABLE_DA) || nm_read_reg(rBurstTx_NMI_MAC_FILTER_ENABLE_SA))
{
strM2mAteRxStatus->num_rx_pkts = nm_read_reg(rBurstTx_NMI_RX_PKT_CNT_SUCCESS) + nm_read_reg(rBurstTx_NMI_RX_PKT_CNT_FAIL);
strM2mAteRxStatus->num_good_pkts = nm_read_reg(rBurstTx_NMI_RX_PKT_CNT_SUCCESS);
strM2mAteRxStatus->num_err_pkts = nm_read_reg(rBurstTx_NMI_RX_PKT_CNT_FAIL);
}
else
{
strM2mAteRxStatus->num_rx_pkts = nm_read_reg(rBurstRx_NMI_RX_ALL_PKTS_CONT) + nm_read_reg(0x989c);
strM2mAteRxStatus->num_err_pkts = nm_read_reg(rBurstRx_NMI_RX_ERR_PKTS_CONT);
strM2mAteRxStatus->num_good_pkts = strM2mAteRxStatus->num_rx_pkts - strM2mAteRxStatus->num_err_pkts;
}
__EXIT:
return s8Ret;
}
/*!
@fn \
sint8 m2m_ate_set_dig_gain(double dGaindB)
@brief
This function is used to set the digital gain
@param [in] double dGaindB
The digital gain value required to be set.
@return
The function SHALL return 0 for success and a negative value otherwise.
*/
sint8 m2m_ate_set_dig_gain(double dGaindB)
{
uint32_t dGain, val32;
dGain = (uint32_t)(pow(10, dGaindB/20.0) * 1024.0);
val32 = nm_read_reg(0x160cd0);
val32 &= ~(0x1ffful << 0);
val32 |= (((uint32_t)dGain) << 0);
nm_write_reg(0x160cd0, val32);
return M2M_SUCCESS;
}
/*!
@fn \
sint8 m2m_ate_get_dig_gain(double * dGaindB)
@brief
This function is used to get the digital gain
@param [out] double * dGaindB
The retrieved digital gain value obtained from HW registers in dB.
@return
The function SHALL return 0 for success and a negative value otherwise.
*/
sint8 m2m_ate_get_dig_gain(double * dGaindB)
{
uint32 dGain, val32;
if(!dGaindB) return M2M_ERR_INVALID_ARG;
val32 = nm_read_reg(0x160cd0);
dGain = (val32 >> 0) & 0x1ffful;
*dGaindB = 20.0*log10((double)dGain / 1024.0);
return M2M_SUCCESS;
}
/*!
@fn \
void m2m_ate_set_pa_gain(uint8 gain_db)
@brief
This function is used to set the PA gain (18/15/12/9/6/3/0 only)
@param [in] uint8 gain_db
PA gain level allowed (18/15/12/9/6/3/0 only)
*/
void m2m_ate_set_pa_gain(uint8 gain_db)
{
uint32 PA_1e9c;
uint8 aGain[] = {
/* "0 dB" */ 0x00,
/* "3 dB" */ 0x01,
/* "6 dB" */ 0x03,
/* "9 dB" */ 0x07,
/* "12 dB" */ 0x0f,
/* "15 dB" */ 0x1f,
/* "18 dB" */ 0x3f };
/* The variable PA gain is valid only for High power mode */
PA_1e9c = nm_read_reg(0x1e9c);
/* TX bank 0. */
PA_1e9c &= ~(0x3ful << 8);
PA_1e9c |= (((uint32)aGain[gain_db/3] & 0x3f) << 8);
nm_write_reg(0x1e9c, PA_1e9c);
}
/*!
@fn \
sint8 m2m_ate_get_pa_gain(double *paGaindB)
@brief
This function is used to get the PA gain
@param [out] double *paGaindB
The retrieved PA gain value obtained from HW registers in dB.
@return
The function SHALL return 0 for success and a negative value otherwise.
*/
sint8 m2m_ate_get_pa_gain(double *paGaindB)
{
uint32 val32, paGain;
uint32 m_cmbPAGainStep;
if(!paGaindB)
return M2M_ERR_INVALID_ARG;
val32 = nm_read_reg(0x1e9c);
paGain = (val32 >> 8) & 0x3f;
switch(paGain){
case 0x1:
m_cmbPAGainStep = 5;
break;
case 0x3:
m_cmbPAGainStep = 4;
break;
case 0x7:
m_cmbPAGainStep = 3;
break;
case 0xf:
m_cmbPAGainStep = 2;
break;
case 0x1f:
m_cmbPAGainStep = 1;
break;
case 0x3f:
m_cmbPAGainStep = 0;
break;
default:
m_cmbPAGainStep = 0;
break;
}
*paGaindB = 18 - m_cmbPAGainStep*3;
return M2M_SUCCESS;
}
/*!
@fn \
sint8 m2m_ate_get_ppa_gain(double * ppaGaindB)
@brief
This function is used to get the PPA gain
@param [out] uint32 * ppaGaindB
The retrieved PPA gain value obtained from HW registers in dB.
@return
The function SHALL return 0 for success and a negative value otherwise.
*/
sint8 m2m_ate_get_ppa_gain(double * ppaGaindB)
{
uint32 val32, ppaGain, m_cmbPPAGainStep;
if(!ppaGaindB) return M2M_ERR_INVALID_ARG;
val32 = nm_read_reg(0x1ea0);
ppaGain = (val32 >> 5) & 0x7;
switch(ppaGain){
case 0x1:
m_cmbPPAGainStep = 2;
break;
case 0x3:
m_cmbPPAGainStep = 1;
break;
case 0x7:
m_cmbPPAGainStep = 0;
break;
default:
m_cmbPPAGainStep = 3;
break;
}
*ppaGaindB = 9 - m_cmbPPAGainStep*3;
return M2M_SUCCESS;
}
/*!
@fn \
sint8 m2m_ate_get_tot_gain(double * totGaindB)
@brief
This function is used to calculate the total gain
@param [out] double * totGaindB
The retrieved total gain value obtained from calculations made based on the digital gain, PA and PPA gain values.
@return
The function SHALL return 0 for success and a negative value otherwise.
*/
sint8 m2m_ate_get_tot_gain(double * totGaindB)
{
double dGaindB, paGaindB, ppaGaindB;
if(!totGaindB) return M2M_ERR_INVALID_ARG;
m2m_ate_get_pa_gain(&paGaindB);
m2m_ate_get_ppa_gain(&ppaGaindB);
m2m_ate_get_dig_gain(&dGaindB);
*totGaindB = dGaindB + paGaindB + ppaGaindB;
return M2M_SUCCESS;
}
#endif //_M2M_ATE_FW_
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,766 @@
/**
*
* \file
*
* \brief This module contains M2M host interface APIs implementation.
*
* Copyright (c) 2016-2017 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
#include "common/include/nm_common.h"
#include "driver/source/nmbus.h"
#include "bsp/include/nm_bsp.h"
#include "m2m_hif.h"
#include "driver/include/m2m_types.h"
#include "driver/source/nmasic.h"
#include "driver/include/m2m_periph.h"
#if (defined NM_EDGE_INTERRUPT)&&(defined NM_LEVEL_INTERRUPT)
#error "only one type of interrupt NM_EDGE_INTERRUPT,NM_LEVEL_INTERRUPT"
#endif
#if !((defined NM_EDGE_INTERRUPT)||(defined NM_LEVEL_INTERRUPT))
#error "define interrupt type NM_EDGE_INTERRUPT,NM_LEVEL_INTERRUPT"
#endif
#ifndef CORTUS_APP
#define NMI_AHB_DATA_MEM_BASE 0x30000
#define NMI_AHB_SHARE_MEM_BASE 0xd0000
#define WIFI_HOST_RCV_CTRL_0 (0x1070)
#define WIFI_HOST_RCV_CTRL_1 (0x1084)
#define WIFI_HOST_RCV_CTRL_2 (0x1078)
#define WIFI_HOST_RCV_CTRL_3 (0x106c)
#define WIFI_HOST_RCV_CTRL_4 (0x150400)
#define WIFI_HOST_RCV_CTRL_5 (0x1088)
typedef struct {
uint8 u8ChipMode;
uint8 u8ChipSleep;
uint8 u8HifRXDone;
uint8 u8Interrupt;
uint32 u32RxAddr;
uint32 u32RxSize;
tpfHifCallBack pfWifiCb;
tpfHifCallBack pfIpCb;
tpfHifCallBack pfOtaCb;
tpfHifCallBack pfSigmaCb;
tpfHifCallBack pfHifCb;
tpfHifCallBack pfCryptoCb;
tpfHifCallBack pfSslCb;
}tstrHifContext;
volatile tstrHifContext gstrHifCxt;
#ifdef ARDUINO
volatile uint8 hif_receive_blocked = 0;
#endif
static void isr(void)
{
gstrHifCxt.u8Interrupt++;
#ifdef NM_LEVEL_INTERRUPT
nm_bsp_interrupt_ctrl(0);
#endif
}
static sint8 hif_set_rx_done(void)
{
uint32 reg;
sint8 ret = M2M_SUCCESS;
#ifdef ARDUINO
hif_receive_blocked = 0;
#endif
gstrHifCxt.u8HifRXDone = 0;
#ifdef NM_EDGE_INTERRUPT
nm_bsp_interrupt_ctrl(1);
#endif
ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0,&reg);
if(ret != M2M_SUCCESS)goto ERR1;
/* Set RX Done */
reg |= NBIT1;
ret = nm_write_reg(WIFI_HOST_RCV_CTRL_0,reg);
if(ret != M2M_SUCCESS)goto ERR1;
#ifdef NM_LEVEL_INTERRUPT
nm_bsp_interrupt_ctrl(1);
#endif
ERR1:
return ret;
}
/**
* @fn static void m2m_hif_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr)
* @brief WiFi call back function
* @param [in] u8OpCode
* HIF Opcode type.
* @param [in] u16DataSize
* HIF data length.
* @param [in] u32Addr
* HIF address.
* @param [in] grp
* HIF group type.
* @author
* @date
* @version 1.0
*/
static void m2m_hif_cb(uint8 u8OpCode, uint16 u16DataSize, uint32 u32Addr)
{
#ifdef ARDUINO
// Silence "unused" warning
(void)u8OpCode;
(void)u16DataSize;
(void)u32Addr;
#endif
}
/**
* @fn NMI_API sint8 hif_chip_wake(void);
* @brief To Wakeup the chip.
* @return The function shall return ZERO for successful operation and a negative value otherwise.
*/
sint8 hif_chip_wake(void)
{
sint8 ret = M2M_SUCCESS;
if(gstrHifCxt.u8HifRXDone)
{
/*chip already wake for the rx not done no need to send wake request*/
return ret;
}
if(gstrHifCxt.u8ChipSleep == 0)
{
if(gstrHifCxt.u8ChipMode != M2M_NO_PS)
{
ret = chip_wake();
if(ret != M2M_SUCCESS)goto ERR1;
}
else
{
}
}
gstrHifCxt.u8ChipSleep++;
ERR1:
return ret;
}
/*!
@fn \
NMI_API void hif_set_sleep_mode(uint8 u8Pstype);
@brief
Set the sleep mode of the HIF layer.
@param [in] u8Pstype
Sleep mode.
@return
The function SHALL return 0 for success and a negative value otherwise.
*/
void hif_set_sleep_mode(uint8 u8Pstype)
{
gstrHifCxt.u8ChipMode = u8Pstype;
}
/*!
@fn \
NMI_API uint8 hif_get_sleep_mode(void);
@brief
Get the sleep mode of the HIF layer.
@return
The function SHALL return the sleep mode of the HIF layer.
*/
uint8 hif_get_sleep_mode(void)
{
return gstrHifCxt.u8ChipMode;
}
/**
* @fn NMI_API sint8 hif_chip_sleep_sc(void);
* @brief To clear the chip sleep but keep the chip sleep
* @return The function shall return ZERO for successful operation and a negative value otherwise.
*/
sint8 hif_chip_sleep_sc(void)
{
if(gstrHifCxt.u8ChipSleep >= 1)
{
gstrHifCxt.u8ChipSleep--;
}
return M2M_SUCCESS;
}
/**
* @fn NMI_API sint8 hif_chip_sleep(void);
* @brief To make the chip sleep.
* @return The function shall return ZERO for successful operation and a negative value otherwise.
*/
sint8 hif_chip_sleep(void)
{
sint8 ret = M2M_SUCCESS;
if(gstrHifCxt.u8ChipSleep >= 1)
{
gstrHifCxt.u8ChipSleep--;
}
if(gstrHifCxt.u8ChipSleep == 0)
{
if(gstrHifCxt.u8ChipMode != M2M_NO_PS)
{
ret = chip_sleep();
if(ret != M2M_SUCCESS)goto ERR1;
}
else
{
}
}
ERR1:
return ret;
}
/**
* @fn NMI_API sint8 hif_init(void * arg);
* @brief To initialize HIF layer.
* @param [in] arg
* Pointer to the arguments.
* @return The function shall return ZERO for successful operation and a negative value otherwise.
*/
sint8 hif_init(void * arg)
{
#ifdef ARDUINO
(void)arg; // Silence "unused" warning
#endif
m2m_memset((uint8*)&gstrHifCxt,0,sizeof(tstrHifContext));
nm_bsp_register_isr(isr);
hif_register_cb(M2M_REQ_GROUP_HIF,m2m_hif_cb);
return M2M_SUCCESS;
}
/**
* @fn NMI_API sint8 hif_deinit(void * arg);
* @brief To De-initialize HIF layer.
* @param [in] arg
* Pointer to the arguments.
* @return The function shall return ZERO for successful operation and a negative value otherwise.
*/
sint8 hif_deinit(void * arg)
{
#ifdef ARDUINO
(void)arg; // Silence "unused" warning
#endif
sint8 ret = M2M_SUCCESS;
ret = hif_chip_wake();
m2m_memset((uint8*)&gstrHifCxt,0,sizeof(tstrHifContext));
return ret;
}
/**
* @fn NMI_API sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize,
uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset)
* @brief Send packet using host interface.
* @param [in] u8Gid
* Group ID.
* @param [in] u8Opcode
* Operation ID.
* @param [in] pu8CtrlBuf
* Pointer to the Control buffer.
* @param [in] u16CtrlBufSize
Control buffer size.
* @param [in] u16DataOffset
Packet Data offset.
* @param [in] pu8DataBuf
* Packet buffer Allocated by the caller.
* @param [in] u16DataSize
Packet buffer size (including the HIF header).
* @return The function shall return ZERO for successful operation and a negative value otherwise.
*/
sint8 hif_send(uint8 u8Gid,uint8 u8Opcode,uint8 *pu8CtrlBuf,uint16 u16CtrlBufSize,
uint8 *pu8DataBuf,uint16 u16DataSize, uint16 u16DataOffset)
{
sint8 ret = M2M_ERR_SEND;
volatile tstrHifHdr strHif;
strHif.u8Opcode = u8Opcode&(~NBIT7);
strHif.u8Gid = u8Gid;
strHif.u16Length = M2M_HIF_HDR_OFFSET;
if(pu8DataBuf != NULL)
{
strHif.u16Length += u16DataOffset + u16DataSize;
}
else
{
strHif.u16Length += u16CtrlBufSize;
}
ret = hif_chip_wake();
if(ret == M2M_SUCCESS)
{
volatile uint32 reg, dma_addr = 0;
volatile uint16 cnt = 0;
//#define OPTIMIZE_BUS
/*please define in firmware also*/
#ifndef OPTIMIZE_BUS
reg = 0UL;
reg |= (uint32)u8Gid;
reg |= ((uint32)u8Opcode<<8);
reg |= ((uint32)strHif.u16Length<<16);
ret = nm_write_reg(NMI_STATE_REG,reg);
if(M2M_SUCCESS != ret) goto ERR1;
reg = 0UL;
reg |= NBIT1;
ret = nm_write_reg(WIFI_HOST_RCV_CTRL_2, reg);
if(M2M_SUCCESS != ret) goto ERR1;
#else
reg = 0UL;
reg |= NBIT1;
reg |= ((u8Opcode & NBIT7) ? (NBIT2):(0)); /*Data = 1 or config*/
reg |= (u8Gid == M2M_REQ_GROUP_IP) ? (NBIT3):(0); /*IP = 1 or non IP*/
reg |= ((uint32)strHif.u16Length << 4); /*length of pkt max = 4096*/
ret = nm_write_reg(WIFI_HOST_RCV_CTRL_2, reg);
if(M2M_SUCCESS != ret) goto ERR1;
#endif
dma_addr = 0;
for(cnt = 0; cnt < 1000; cnt ++)
{
ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_2,(uint32 *)&reg);
if(ret != M2M_SUCCESS) break;
/*
* If it takes too long to get a response, the slow down to
* avoid back-to-back register read operations.
*/
if(cnt >= 500) {
if(cnt < 501) {
M2M_INFO("Slowing down...\n");
}
nm_bsp_sleep(1);
}
if (!(reg & NBIT1))
{
ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_4,(uint32 *)&dma_addr);
if(ret != M2M_SUCCESS) {
/*in case of read error clear the DMA address and return error*/
dma_addr = 0;
goto ERR1;
}
/*in case of success break */
break;
}
}
if (dma_addr != 0)
{
volatile uint32 u32CurrAddr;
u32CurrAddr = dma_addr;
strHif.u16Length=NM_BSP_B_L_16(strHif.u16Length);
ret = nm_write_block(u32CurrAddr, (uint8*)&strHif, M2M_HIF_HDR_OFFSET);
if(M2M_SUCCESS != ret) goto ERR1;
u32CurrAddr += M2M_HIF_HDR_OFFSET;
if(pu8CtrlBuf != NULL)
{
ret = nm_write_block(u32CurrAddr, pu8CtrlBuf, u16CtrlBufSize);
if(M2M_SUCCESS != ret) goto ERR1;
u32CurrAddr += u16CtrlBufSize;
}
if(pu8DataBuf != NULL)
{
u32CurrAddr += (u16DataOffset - u16CtrlBufSize);
ret = nm_write_block(u32CurrAddr, pu8DataBuf, u16DataSize);
if(M2M_SUCCESS != ret) goto ERR1;
u32CurrAddr += u16DataSize;
}
reg = dma_addr << 2;
reg |= NBIT1;
ret = nm_write_reg(WIFI_HOST_RCV_CTRL_3, reg);
if(M2M_SUCCESS != ret) goto ERR1;
}
else
{
ret = hif_chip_sleep();
M2M_DBG("Failed to alloc rx size %d\r",ret);
ret = M2M_ERR_MEM_ALLOC;
goto ERR2;
}
}
else
{
M2M_ERR("(HIF)Fail to wakup the chip\n");
goto ERR2;
}
/*actual sleep ret = M2M_SUCCESS*/
ret = hif_chip_sleep();
return ret;
ERR1:
/*reset the count but no actual sleep as it already bus error*/
hif_chip_sleep_sc();
ERR2:
/*logical error*/
return ret;
}
/**
* @fn hif_isr
* @brief Host interface interrupt service routine
* @author M. Abdelmawla
* @date 15 July 2012
* @return 1 in case of interrupt received else 0 will be returned
* @version 1.0
*/
static sint8 hif_isr(void)
{
sint8 ret = M2M_SUCCESS;
volatile uint32 reg;
volatile tstrHifHdr strHif;
#ifdef ARDUINO
ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0, (uint32*)&reg);
#else
ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_0, &reg);
#endif
if(M2M_SUCCESS == ret)
{
if(reg & 0x1) /* New interrupt has been received */
{
uint16 size;
nm_bsp_interrupt_ctrl(0);
/*Clearing RX interrupt*/
reg &= ~NBIT0;
ret = nm_write_reg(WIFI_HOST_RCV_CTRL_0,reg);
if(ret != M2M_SUCCESS)goto ERR1;
gstrHifCxt.u8HifRXDone = 1;
size = (uint16)((reg >> 2) & 0xfff);
if (size > 0) {
uint32 address = 0;
/**
start bus transfer
**/
ret = nm_read_reg_with_ret(WIFI_HOST_RCV_CTRL_1, &address);
if(M2M_SUCCESS != ret)
{
M2M_ERR("(hif) WIFI_HOST_RCV_CTRL_1 bus fail\n");
nm_bsp_interrupt_ctrl(1);
goto ERR1;
}
gstrHifCxt.u32RxAddr = address;
gstrHifCxt.u32RxSize = size;
ret = nm_read_block(address, (uint8*)&strHif, sizeof(tstrHifHdr));
strHif.u16Length = NM_BSP_B_L_16(strHif.u16Length);
if(M2M_SUCCESS != ret)
{
M2M_ERR("(hif) address bus fail\n");
nm_bsp_interrupt_ctrl(1);
goto ERR1;
}
if(strHif.u16Length != size)
{
if((size - strHif.u16Length) > 4)
{
M2M_ERR("(hif) Corrupted packet Size = %u <L = %u, G = %u, OP = %02X>\n",
size, strHif.u16Length, strHif.u8Gid, strHif.u8Opcode);
nm_bsp_interrupt_ctrl(1);
ret = M2M_ERR_BUS_FAIL;
goto ERR1;
}
}
if(M2M_REQ_GROUP_WIFI == strHif.u8Gid)
{
if(gstrHifCxt.pfWifiCb)
gstrHifCxt.pfWifiCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET);
else
#ifdef ARDUINO
{
#endif
M2M_ERR("WIFI callback is not registered\n");
#ifdef ARDUINO
}
#endif
}
else if(M2M_REQ_GROUP_IP == strHif.u8Gid)
{
if(gstrHifCxt.pfIpCb)
gstrHifCxt.pfIpCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET);
else
#ifdef ARDUINO
{
#endif
M2M_ERR("Scoket callback is not registered\n");
#ifdef ARDUINO
}
#endif
}
else if(M2M_REQ_GROUP_OTA == strHif.u8Gid)
{
if(gstrHifCxt.pfOtaCb)
gstrHifCxt.pfOtaCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET);
else
#ifdef ARDUINO
{
#endif
M2M_ERR("Ota callback is not registered\n");
#ifdef ARDUINO
}
#endif
}
else if(M2M_REQ_GROUP_CRYPTO == strHif.u8Gid)
{
if(gstrHifCxt.pfCryptoCb)
gstrHifCxt.pfCryptoCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET);
else
#ifdef ARDUINO
{
#endif
M2M_ERR("Crypto callback is not registered\n");
#ifdef ARDUINO
}
#endif
}
else if(M2M_REQ_GROUP_SIGMA == strHif.u8Gid)
{
if(gstrHifCxt.pfSigmaCb)
gstrHifCxt.pfSigmaCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET);
else
#ifdef ARDUINO
{
#endif
M2M_ERR("Sigma callback is not registered\n");
#ifdef ARDUINO
}
#endif
}
else if(M2M_REQ_GROUP_SSL == strHif.u8Gid)
{
if(gstrHifCxt.pfSslCb)
gstrHifCxt.pfSslCb(strHif.u8Opcode,strHif.u16Length - M2M_HIF_HDR_OFFSET, address + M2M_HIF_HDR_OFFSET);
}
else
{
M2M_ERR("(hif) invalid group ID\n");
ret = M2M_ERR_BUS_FAIL;
goto ERR1;
}
#ifdef ARDUINO
if (hif_receive_blocked) {
return ret;
}
#endif
if(gstrHifCxt.u8HifRXDone)
{
M2M_ERR("(hif) host app didn't set RX Done <%u><%X>\n", strHif.u8Gid, strHif.u8Opcode);
ret = hif_set_rx_done();
if(ret != M2M_SUCCESS) goto ERR1;
}
}
else
{
M2M_ERR("(hif) Wrong Size\n");
ret = M2M_ERR_RCV;
goto ERR1;
}
}
else
{
#ifndef WIN32
M2M_ERR("(hif) False interrupt %lx",reg);
#ifdef ARDUINO
// ignore false interrupts, since they cause infinite loops in hif_handle_isr
#else
ret = M2M_ERR_FAIL;
#endif
goto ERR1;
#else
#endif
}
}
else
{
M2M_ERR("(hif) Fail to Read interrupt reg\n");
goto ERR1;
}
ERR1:
return ret;
}
/**
* @fn hif_handle_isr(void)
* @brief Handle interrupt received from NMC1500 firmware.
* @return The function SHALL return 0 for success and a negative value otherwise.
*/
sint8 hif_handle_isr(void)
{
sint8 ret = M2M_SUCCESS;
#ifdef ARDUINO
if (hif_receive_blocked) {
return ret;
}
#endif
while (gstrHifCxt.u8Interrupt) {
/*must be at that place because of the race of interrupt increment and that decrement*/
/*when the interrupt enabled*/
gstrHifCxt.u8Interrupt--;
while(1)
{
ret = hif_isr();
#ifdef ARDUINO
if (hif_receive_blocked) {
return ret;
}
#endif
if(ret == M2M_SUCCESS) {
/*we will try forever untill we get that interrupt*/
/*Fail return errors here due to bus errors (reading expected values)*/
break;
} else {
M2M_ERR("(HIF) Fail to handle interrupt %d try Again..\n",ret);
}
}
}
return ret;
}
/*
* @fn hif_receive
* @brief Host interface interrupt serviece routine
* @param [in] u32Addr
* Receive start address
* @param [out] pu8Buf
* Pointer to receive buffer. Allocated by the caller
* @param [in] u16Sz
* Receive buffer size
* @param [in] isDone
* If you don't need any more packets send True otherwise send false
* @return The function shall return ZERO for successful operation and a negative value otherwise.
*/
sint8 hif_receive(uint32 u32Addr, uint8 *pu8Buf, uint16 u16Sz, uint8 isDone)
{
sint8 ret = M2M_SUCCESS;
if((u32Addr == 0)||(pu8Buf == NULL) || (u16Sz == 0))
{
if(isDone)
{
/* set RX done */
ret = hif_set_rx_done();
}
else
{
ret = M2M_ERR_FAIL;
M2M_ERR(" hif_receive: Invalid argument\n");
}
goto ERR1;
}
if(u16Sz > gstrHifCxt.u32RxSize)
{
ret = M2M_ERR_FAIL;
M2M_ERR("APP Requested Size is larger than the recived buffer size <%u><%lu>\n",u16Sz, gstrHifCxt.u32RxSize);
goto ERR1;
}
if((u32Addr < gstrHifCxt.u32RxAddr)||((u32Addr + u16Sz)>(gstrHifCxt.u32RxAddr + gstrHifCxt.u32RxSize)))
{
ret = M2M_ERR_FAIL;
M2M_ERR("APP Requested Address beyond the recived buffer address and length\n");
goto ERR1;
}
/* Receive the payload */
ret = nm_read_block(u32Addr, pu8Buf, u16Sz);
if(ret != M2M_SUCCESS)goto ERR1;
/* check if this is the last packet */
if((((gstrHifCxt.u32RxAddr + gstrHifCxt.u32RxSize) - (u32Addr + u16Sz)) <= 0) || isDone)
{
/* set RX done */
ret = hif_set_rx_done();
}
ERR1:
return ret;
}
/**
* @fn hif_register_cb
* @brief To set Callback function for every compantent Component
* @param [in] u8Grp
* Group to which the Callback function should be set.
* @param [in] fn
* function to be set
* @return The function shall return ZERO for successful operation and a negative value otherwise.
*/
sint8 hif_register_cb(uint8 u8Grp,tpfHifCallBack fn)
{
sint8 ret = M2M_SUCCESS;
switch(u8Grp)
{
case M2M_REQ_GROUP_IP:
gstrHifCxt.pfIpCb = fn;
break;
case M2M_REQ_GROUP_WIFI:
gstrHifCxt.pfWifiCb = fn;
break;
case M2M_REQ_GROUP_OTA:
gstrHifCxt.pfOtaCb = fn;
break;
case M2M_REQ_GROUP_HIF:
gstrHifCxt.pfHifCb = fn;
break;
case M2M_REQ_GROUP_CRYPTO:
gstrHifCxt.pfCryptoCb = fn;
break;
case M2M_REQ_GROUP_SIGMA:
gstrHifCxt.pfSigmaCb = fn;
break;
case M2M_REQ_GROUP_SSL:
gstrHifCxt.pfSslCb = fn;
break;
default:
M2M_ERR("GRp ? %d\n",u8Grp);
ret = M2M_ERR_FAIL;
break;
}
return ret;
}
#endif

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