ajout BLE

This commit is contained in:
thomas committed 2026-10-24 00:14:53 +02:00
1 parent 66bb319423
commit 3757975e51
48 files changed
+293826 -284536

No files matched your search

+34
View File
@@ -0,0 +1,34 @@
#ifndef REMOTE_BLE_H
#define REMOTE_BLE_H
#ifdef __cplusplus
extern "C" {
#endif
/* Controle a distance par BLE (module ST67W611M1 de la X-NUCLEO-67W61M1, liaison SPI4).
* Une tache FreeRTOS initialise le module, annonce un serveur GATT "CelloFX" et applique les
* commandes recues aux parametres d'effets (voir remote_params.h).
*
* Service c3110000-7e8a-4b1c-9d52-f0a1e4b7c600
* Control c3110001-... ecriture (avec ou sans reponse)
* State c3110002-... notification
*
* Les deux caracteristiques echangent des enregistrements de 3 octets :
* [id : uint8] [valeur : int16 little-endian]
* Plusieurs enregistrements peuvent tenir dans une ecriture (jusqu'a la taille du MTU).
* Control : le client envoie des commandes. L'identifiant 0xFF demande un instantane de l'etat.
* State : le serveur notifie les valeurs courantes (a l'abonnement du client, et sur 0xFF).
*
* Le module est appaire en "Just Works" : n'importe quel appareil a portee peut piloter les
* effets. A durcir (code PIN) avant tout usage hors banc d'essai.
*/
/* Cree la tache de controle. A appeler une fois, avant osKernelStart(). Sans effet sur l'audio :
* si le module est absent ou ne repond pas, la tache s'arrete et le reste tourne normalement. */
void RemoteBle_Start(void);
#ifdef __cplusplus
}
#endif
#endif /* REMOTE_BLE_H */
+45
View File
@@ -0,0 +1,45 @@
#ifndef REMOTE_PARAMS_H
#define REMOTE_PARAMS_H
#include <stdbool.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Couche commune du controle a distance (BLE maintenant, Wi-Fi ensuite) : elle expose les
* parametres de AudioEffects_GetParams() sous forme d'identifiants d'un octet avec une valeur
* entiere signee 16 bits. Aucune dependance au transport.
*
* Valeur sur le fil (int16) = valeur reelle * echelle, bornee a la plage du parametre :
* booleen (actif/inactif) 0 ou 1
* niveaux 0.0..1.0 echelle 1000 (500 = 0.5)
* gain d'une bande d'egaliseur echelle 10 (-60 = -6.0 dB)
* delai d'echo echelle 1 (250 = 250 ms)
*
* Identifiants :
* 0x00 audio_on_off 0x01 master_volume
* 0x10 octaver.enabled 0x11 down2 0x12 down1 0x13 dry 0x14 up1 0x15 up2
* 0x20 equalizer.enabled 0x30..0x39 gain des bandes 0 a 9
* 0x50 overdrive.enabled 0x51 drive 0x52 tone 0x53 level
* 0x60 saturation.enabled 0x61 drive 0x62 level
* 0x70 echo.enabled 0x71 delay_ms 0x72 feedback 0x73 mix
* 0x80 reverb.enabled 0x81 room_size 0x82 damping 0x83 mix
*/
/* Applique une valeur recue. Retourne false si l'identifiant est inconnu. */
bool RemoteParams_Set(uint8_t id, int16_t value);
/* Lit la valeur courante d'un parametre. Retourne false si l'identifiant est inconnu. */
bool RemoteParams_Get(uint8_t id, int16_t *value);
/* Parcours de tous les parametres (pour envoyer un instantane de l'etat). */
uint8_t RemoteParams_Count(void);
uint8_t RemoteParams_IdAt(uint8_t index);
#ifdef __cplusplus
}
#endif
#endif /* REMOTE_PARAMS_H */
+24
View File
@@ -0,0 +1,24 @@
#ifndef ST67_GLUE_H
#define ST67_GLUE_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/* A appeler depuis HAL_GPIO_EXTI_Callback() pour toute broche : ne fait rien sauf pour SPI_RDY,
* dont les fronts cadencent la liaison SPI avec le module ST67W611M1. */
void ST67_ExtiCallback(uint16_t gpio_pin);
/* Journal du driver ST67 : tampon circulaire en RAM, lisible au debogueur (variables
* st67_log_ring / st67_log_head). Pas de liaison serie disponible pour les traces. */
#define ST67_LOG_RING_SIZE 4096U
extern char st67_log_ring[ST67_LOG_RING_SIZE];
extern volatile uint32_t st67_log_head; /* prochain octet a ecrire (modulo la taille) */
#ifdef __cplusplus
}
#endif
#endif /* ST67_GLUE_H */
+2
View File
@@ -29,6 +29,7 @@
#include "audio_effects.h"
#include "audio_analysis.h"
#include "audio_looper.h"
#include "remote_ble.h"
#include <string.h>
/* USER CODE END Includes */
@@ -264,6 +265,7 @@ int main(void)
/* USER CODE BEGIN RTOS_THREADS */
/* add threads, ... */
RemoteBle_Start(); /* controle a distance BLE (module ST67W611M1) */
/* USER CODE END RTOS_THREADS */
/* USER CODE BEGIN RTOS_EVENTS */
+292
View File
@@ -0,0 +1,292 @@
#include "remote_ble.h"
#include <inttypes.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include "FreeRTOS.h"
#include "event_groups.h"
#include "cmsis_os2.h"
#include "w6x_api.h"
#include "logging.h"
#include "remote_params.h"
/* Identifiants GATT : UUID 128 bits en notation canonique, sans tirets (format du module). */
#define SERVICE_UUID "c31100007e8a4b1c9d52f0a1e4b7c600"
#define CHAR_CONTROL_UUID "c31100017e8a4b1c9d52f0a1e4b7c600"
#define CHAR_STATE_UUID "c31100027e8a4b1c9d52f0a1e4b7c600"
#define SERVICE_INDEX 0U
#define CHAR_CONTROL_INDEX 0U
#define CHAR_STATE_INDEX 1U
#define DEVICE_NAME "CelloFX"
/* Donnees d'annonce BLE brutes (hexadecimal) :
* annonce : flags (LE General Discoverable, BR/EDR non supporte) + nom complet "CelloFX"
* reponse au scan : liste complete de l'UUID 128 bits du service, en little-endian */
#define ADV_DATA "020106" "0809" "43656C6C6F4658"
#define SCAN_RESP_DATA "1107" "00C6B7E4A1F0529D1C4B8A7E000011C3"
#define RECORD_SIZE 3U
#define CMD_SNAPSHOT 0xFFU
/* 6 enregistrements = 18 octets : tient dans une notification avec le MTU ATT par defaut (23). */
#define NOTIFY_MAX_RECORDS 6U
#define RX_BUFFER_SIZE 247U
#define INIT_RETRIES 3U
#define INIT_RETRY_DELAY_MS 3000U
#define EVT_CONNECTED (1UL << 0)
#define EVT_DISCONNECTED (1UL << 1)
#define EVT_SNAPSHOT (1UL << 2)
#define EVT_ALL (EVT_CONNECTED | EVT_DISCONNECTED | EVT_SNAPSHOT)
static uint8_t rx_buffer[RX_BUFFER_SIZE]; /* le module y copie les donnees ecrites par le client */
static EventGroupHandle_t events;
static volatile uint32_t conn_handle = 0xFFU;
static volatile bool connected;
static bool started;
static const osThreadAttr_t task_attr = {
.name = "remoteBle",
.stack_size = 3072,
.priority = (osPriority_t)osPriorityBelowNormal,
};
/* Les callbacks du driver s'executent dans son propre contexte : ils doivent rester courts et
* n'appellent aucune fonction W6X_* (l'envoi des notifications est fait par la tache). */
static void on_ble_data(const W6X_Ble_CbParamData_t *p)
{
uint32_t len = p->available_data_length;
if (len > RX_BUFFER_SIZE)
{
len = RX_BUFFER_SIZE;
}
for (uint32_t i = 0; i + RECORD_SIZE <= len; i += RECORD_SIZE)
{
uint8_t id = rx_buffer[i];
int16_t value = (int16_t)((uint16_t)rx_buffer[i + 1] | ((uint16_t)rx_buffer[i + 2] << 8));
if (id == CMD_SNAPSHOT)
{
(void)xEventGroupSetBits(events, EVT_SNAPSHOT);
}
else if (!RemoteParams_Set(id, value))
{
LogWarn("BLE: identifiant de parametre inconnu 0x%02X\n", (unsigned)id);
}
}
}
static void app_ble_cb(W6X_event_id_t event_id, void *event_args)
{
const W6X_Ble_CbParamData_t *p = (const W6X_Ble_CbParamData_t *)event_args;
switch (event_id)
{
case W6X_BLE_EVT_CONNECTED_ID:
conn_handle = p->remote_ble_device.conn_handle;
connected = true;
LogInfo("BLE: client connecte (handle %" PRIu32 ")\n", conn_handle);
(void)xEventGroupSetBits(events, EVT_CONNECTED);
break;
case W6X_BLE_EVT_DISCONNECTED_ID:
connected = false;
conn_handle = 0xFFU;
LogInfo("BLE: client deconnecte\n");
(void)xEventGroupSetBits(events, EVT_DISCONNECTED);
break;
case W6X_BLE_EVT_WRITE_ID:
if (p->service_idx == SERVICE_INDEX && p->charac_idx == CHAR_CONTROL_INDEX)
{
on_ble_data(p);
}
break;
case W6X_BLE_EVT_NOTIFICATION_STATUS_ENABLED_ID:
/* le client s'abonne : on lui envoie l'etat complet pour qu'il se synchronise */
(void)xEventGroupSetBits(events, EVT_SNAPSHOT);
break;
default:
break;
}
}
/* Le driver exige des callbacks valides pour toutes les familles d'evenements. */
static void app_unused_cb(W6X_event_id_t event_id, void *event_args)
{
(void)event_id;
(void)event_args;
}
static void app_error_cb(W6X_Status_t status, char const *func_name)
{
LogError("ST67: erreur %" PRIi32 " dans %s\n", (int32_t)status, func_name);
}
static W6X_Status_t configure_server(void)
{
W6X_Status_t ret;
char name[W6X_BLE_DEVICE_NAME_SIZE] = DEVICE_NAME; /* l'API lit un tableau de taille fixe */
ret = W6X_Ble_SetDeviceName(name);
if (ret != W6X_STATUS_OK) { LogError("BLE: nom\n"); return ret; }
ret = W6X_Ble_SetTxPower(0);
if (ret != W6X_STATUS_OK) { LogError("BLE: puissance d'emission\n"); return ret; }
ret = W6X_Ble_SetAdvData(ADV_DATA);
if (ret != W6X_STATUS_OK) { LogError("BLE: donnees d'annonce\n"); return ret; }
ret = W6X_Ble_SetScanRespData(SCAN_RESP_DATA);
if (ret != W6X_STATUS_OK) { LogError("BLE: reponse au scan\n"); return ret; }
ret = W6X_Ble_CreateService(SERVICE_INDEX, SERVICE_UUID, W6X_BLE_UUID_TYPE_128);
if (ret != W6X_STATUS_OK) { LogError("BLE: creation du service\n"); return ret; }
ret = W6X_Ble_CreateCharacteristic(SERVICE_INDEX, CHAR_CONTROL_INDEX, CHAR_CONTROL_UUID,
W6X_BLE_UUID_TYPE_128,
W6X_BLE_CHAR_PROP_WRITE_WITHOUT_RESP | W6X_BLE_CHAR_PROP_WRITE_WITH_RESP,
W6X_BLE_CHAR_PERM_WRITE);
if (ret != W6X_STATUS_OK) { LogError("BLE: caracteristique Control\n"); return ret; }
ret = W6X_Ble_CreateCharacteristic(SERVICE_INDEX, CHAR_STATE_INDEX, CHAR_STATE_UUID,
W6X_BLE_UUID_TYPE_128,
W6X_BLE_CHAR_PROP_NOTIFY,
W6X_BLE_CHAR_PERM_READ);
if (ret != W6X_STATUS_OK) { LogError("BLE: caracteristique State\n"); return ret; }
ret = W6X_Ble_RegisterCharacteristics();
if (ret != W6X_STATUS_OK) { LogError("BLE: enregistrement des caracteristiques\n"); return ret; }
ret = W6X_Ble_SetSecurityParam(W6X_BLE_SEC_IO_NO_INPUT_OUTPUT);
if (ret != W6X_STATUS_OK) { LogWarn("BLE: parametres de securite\n"); }
return W6X_Ble_AdvStart();
}
static void send_snapshot(void)
{
if (!connected)
{
return;
}
uint8_t buffer[NOTIFY_MAX_RECORDS * RECORD_SIZE];
uint8_t count = RemoteParams_Count();
uint8_t index = 0;
while (index < count && connected)
{
uint32_t used = 0;
while (index < count && used < sizeof(buffer))
{
uint8_t id = RemoteParams_IdAt(index);
int16_t value = 0;
(void)RemoteParams_Get(id, &value);
buffer[used++] = id;
buffer[used++] = (uint8_t)((uint16_t)value & 0xFFU);
buffer[used++] = (uint8_t)(((uint16_t)value >> 8) & 0xFFU);
index++;
}
uint32_t sent = 0;
W6X_Status_t ret = W6X_Ble_ServerNotify((uint8_t)conn_handle, SERVICE_INDEX, CHAR_STATE_INDEX,
buffer, used, &sent, 1000);
if (ret != W6X_STATUS_OK)
{
LogError("BLE: echec de notification (%" PRIi32 ")\n", (int32_t)ret);
return;
}
osDelay(20); /* laisse le temps au lien radio d'ecouler la notification */
}
}
static bool start_module(void)
{
W6X_App_Cb_t cb = {0};
cb.APP_wifi_cb = app_unused_cb;
cb.APP_net_cb = app_unused_cb;
cb.APP_mqtt_cb = app_unused_cb;
cb.APP_ble_cb = app_ble_cb;
cb.APP_error_cb = app_error_cb;
(void)W6X_RegisterAppCb(&cb);
for (uint32_t attempt = 1; attempt <= INIT_RETRIES; attempt++)
{
W6X_Status_t ret = W6X_Init();
if (ret == W6X_STATUS_OK)
{
ret = W6X_Ble_Init(W6X_BLE_MODE_SERVER, rx_buffer, sizeof(rx_buffer) - 1U);
if (ret == W6X_STATUS_OK)
{
ret = configure_server();
if (ret == W6X_STATUS_OK)
{
return true;
}
}
}
LogError("ST67: initialisation impossible (essai %" PRIu32 "/%u, code %" PRIi32 ")\n",
attempt, (unsigned)INIT_RETRIES, (int32_t)ret);
W6X_DeInit();
osDelay(INIT_RETRY_DELAY_MS);
}
return false;
}
static void remote_ble_task(void *argument)
{
(void)argument;
if (!start_module())
{
LogError("ST67: module absent ou muet, controle a distance desactive\n");
osThreadExit();
}
LogInfo("BLE: annonce \"" DEVICE_NAME "\" demarree\n");
LogInfo("tas FreeRTOS libre: %u octets (minimum atteint: %u)\n",
(unsigned)xPortGetFreeHeapSize(), (unsigned)xPortGetMinimumEverFreeHeapSize());
for (;;)
{
EventBits_t bits = xEventGroupWaitBits(events, EVT_ALL, pdTRUE, pdFALSE, portMAX_DELAY);
if ((bits & EVT_DISCONNECTED) != 0U)
{
W6X_Status_t ret = W6X_Ble_AdvStart(); /* redevient visible apres une deconnexion */
if (ret != W6X_STATUS_OK)
{
LogWarn("BLE: relance de l'annonce (%" PRIi32 ")\n", (int32_t)ret);
}
}
if ((bits & EVT_SNAPSHOT) != 0U)
{
send_snapshot();
}
}
}
void RemoteBle_Start(void)
{
if (started)
{
return;
}
started = true;
events = xEventGroupCreate();
if (events == NULL || osThreadNew(remote_ble_task, NULL, &task_attr) == NULL)
{
LogError("ST67: creation de la tache de controle impossible\n");
}
}
+136
View File
@@ -0,0 +1,136 @@
#include "remote_params.h"
#include <stddef.h>
#include <math.h>
#include "audio_effects.h"
typedef enum
{
PARAM_BOOL,
PARAM_FLOAT
} ParamKind;
typedef struct
{
uint8_t id;
ParamKind kind;
uint16_t offset; /* position du champ dans AudioEffectsParams */
float scale; /* valeur sur le fil = reel * scale */
float min;
float max;
} ParamDesc;
#define P_BOOL(id, field) { (id), PARAM_BOOL, offsetof(AudioEffectsParams, field), 1.0f, 0.0f, 1.0f }
#define P_UNIT(id, field) { (id), PARAM_FLOAT, offsetof(AudioEffectsParams, field), 1000.0f, 0.0f, 1.0f }
#define P_UNIT_MAX(id, field, vmax) { (id), PARAM_FLOAT, offsetof(AudioEffectsParams, field), 1000.0f, 0.0f, (vmax) }
#define P_EQ_GAIN(i) { (uint8_t)(0x30 + (i)), PARAM_FLOAT, \
offsetof(AudioEffectsParams, equalizer.bands[i].gain_db), 10.0f, -24.0f, 24.0f }
static const ParamDesc k_params[] =
{
P_BOOL(0x00, audio_on_off),
P_UNIT(0x01, master_volume),
P_BOOL(0x10, octaver.enabled),
P_UNIT(0x11, octaver.level_down2),
P_UNIT(0x12, octaver.level_down1),
P_UNIT(0x13, octaver.level_dry),
P_UNIT(0x14, octaver.level_up1),
P_UNIT(0x15, octaver.level_up2),
P_BOOL(0x20, equalizer.enabled),
P_EQ_GAIN(0), P_EQ_GAIN(1), P_EQ_GAIN(2), P_EQ_GAIN(3), P_EQ_GAIN(4),
P_EQ_GAIN(5), P_EQ_GAIN(6), P_EQ_GAIN(7), P_EQ_GAIN(8), P_EQ_GAIN(9),
P_BOOL(0x50, overdrive.enabled),
P_UNIT(0x51, overdrive.drive),
P_UNIT(0x52, overdrive.tone),
P_UNIT(0x53, overdrive.level),
P_BOOL(0x60, saturation.enabled),
P_UNIT(0x61, saturation.drive),
P_UNIT(0x62, saturation.level),
P_BOOL(0x70, echo.enabled),
{ 0x71, PARAM_FLOAT, offsetof(AudioEffectsParams, echo.delay_ms), 1.0f, 0.0f, (float)FX_ECHO_MAX_DELAY_MS },
P_UNIT_MAX(0x72, echo.feedback, 0.95f), /* < 1.0 pour eviter l'emballement */
P_UNIT(0x73, echo.mix),
P_BOOL(0x80, reverb.enabled),
P_UNIT(0x81, reverb.room_size),
P_UNIT(0x82, reverb.damping),
P_UNIT(0x83, reverb.mix),
};
#define PARAM_COUNT (sizeof(k_params) / sizeof(k_params[0]))
_Static_assert(FX_EQ_NUM_BANDS == 10U, "la table des bandes d'egaliseur suppose 10 bandes");
_Static_assert(PARAM_COUNT < 256U, "RemoteParams_Count() tient sur un octet");
static const ParamDesc *find(uint8_t id)
{
for (size_t i = 0; i < PARAM_COUNT; i++)
{
if (k_params[i].id == id)
{
return &k_params[i];
}
}
return NULL;
}
bool RemoteParams_Set(uint8_t id, int16_t value)
{
const ParamDesc *d = find(id);
if (d == NULL)
{
return false;
}
uint8_t *base = (uint8_t *)AudioEffects_GetParams();
if (d->kind == PARAM_BOOL)
{
*(bool *)(base + d->offset) = (value != 0);
}
else
{
float v = (float)value / d->scale;
if (v < d->min) { v = d->min; }
if (v > d->max) { v = d->max; }
*(float *)(base + d->offset) = v;
}
return true;
}
bool RemoteParams_Get(uint8_t id, int16_t *value)
{
const ParamDesc *d = find(id);
if (d == NULL || value == NULL)
{
return false;
}
const uint8_t *base = (const uint8_t *)AudioEffects_GetParams();
if (d->kind == PARAM_BOOL)
{
*value = *(const bool *)(base + d->offset) ? 1 : 0;
}
else
{
float raw = roundf(*(const float *)(base + d->offset) * d->scale);
if (raw > 32767.0f) { raw = 32767.0f; }
if (raw < -32768.0f) { raw = -32768.0f; }
*value = (int16_t)raw;
}
return true;
}
uint8_t RemoteParams_Count(void)
{
return (uint8_t)PARAM_COUNT;
}
uint8_t RemoteParams_IdAt(uint8_t index)
{
return (index < PARAM_COUNT) ? k_params[index].id : 0xFFU;
}
+98
View File
@@ -0,0 +1,98 @@
#include "st67_glue.h"
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include "main.h"
#include "logging.h"
#include "spi_iface.h"
char st67_log_ring[ST67_LOG_RING_SIZE];
volatile uint32_t st67_log_head;
/* Niveau le plus verbeux conserve dans le tampon (LOG_ERROR < LOG_WARN < LOG_INFO < LOG_DEBUG). */
#define ST67_LOG_MAX_LEVEL LOG_INFO
static const char *level_tag(uint32_t level)
{
switch (level)
{
case LOG_ERROR: return "E ";
case LOG_WARN: return "W ";
case LOG_INFO: return "I ";
default: return "D ";
}
}
static void ring_write(const char *text, uint32_t len)
{
uint32_t primask = __get_PRIMASK();
__disable_irq();
uint32_t head = st67_log_head;
for (uint32_t i = 0; i < len; i++)
{
st67_log_ring[head] = text[i];
head = (head + 1U) % ST67_LOG_RING_SIZE;
}
st67_log_head = head;
__set_PRIMASK(primask);
}
/* Implementation attendue par les macros LogInfo/LogError/... du driver (composant "Logging" non
* retenu, et pas de UART : les traces vont dans le tampon circulaire st67_log_ring). */
void vLoggingPrintf(uint32_t log_level,
const uint8_t metadata_print,
const uint32_t line_number,
const char *const p_file_name,
const char *const p_format,
...)
{
char line[128];
int n = 0;
if (log_level > ST67_LOG_MAX_LEVEL)
{
return; /* les traces DEBUG du driver saturent le tampon circulaire */
}
n += snprintf(line + n, sizeof(line) - (size_t)n, "%s", level_tag(log_level));
if (metadata_print != 0U && p_file_name != NULL)
{
n += snprintf(line + n, sizeof(line) - (size_t)n, "%s:%lu ", p_file_name, (unsigned long)line_number);
}
va_list args;
va_start(args, p_format);
int m = vsnprintf(line + n, sizeof(line) - (size_t)n, p_format, args);
va_end(args);
if (m < 0)
{
return;
}
n += m;
if ((size_t)n >= sizeof(line))
{
n = (int)sizeof(line) - 1; /* ligne tronquee */
}
ring_write(line, (uint32_t)n);
}
void ST67_ExtiCallback(uint16_t gpio_pin)
{
if (gpio_pin != SPI_RDY_Pin)
{
return;
}
/* front montant : le module a des donnees a transmettre ; front descendant : il a acquitte l'en-tete */
if (HAL_GPIO_ReadPin(SPI_RDY_GPIO_Port, SPI_RDY_Pin) == GPIO_PIN_SET)
{
(void)spi_on_txn_data_ready();
}
else
{
(void)spi_on_header_ack();
}
}