3 #include "AudioBLEStream.h"
4 #include "ConstantsArduino.h"
5 #include <ArduinoBLE.h>
10 static AudioBLEClient *selfAudioBLEClient =
nullptr;
23 selfAudioBLEClient =
this;
24 max_transfer_size = mtu;
28 bool begin(
const char *localName,
int seconds) {
32 BLE.setLocalName(localName);
33 BLE.scanForUuid(BLE_AUDIO_SERVICE_UUID);
43 size_t readBytes(uint8_t *data,
size_t len)
override {
45 if (!setupBLEClient()) {
49 if (!ch01_char.canRead())
52 return ch01_char.readValue(data, len);
55 int available()
override {
return BLE_MTU - BLE_MTU_OVERHEAD; }
57 size_t write(
const uint8_t *data,
size_t len)
override {
59 if (!setupBLEClient()) {
63 if (!ch02_char.canWrite()) {
68 writeChannel2Characteristic(data, len);
72 for (
int j = 0; j < len; j++) {
73 write_buffer.
write(data[j]);
74 if (write_buffer.
isFull()) {
75 writeChannel2Characteristic(write_buffer.
data(),
84 int availableForWrite()
override {
85 return is_framed ? (BLE_MTU - BLE_MTU_OVERHEAD) : DEFAULT_BUFFER_SIZE;
88 bool connected()
override {
return setupBLEClient(); }
90 void setWriteThrottle(
int ms) { write_throttle = ms; }
92 void setConfirmWrite(
bool flag) { write_confirmation_flag = flag; }
96 BLECharacteristic ch01_char;
97 BLECharacteristic ch02_char;
98 BLECharacteristic info_char;
99 SingleBuffer<uint8_t> write_buffer{0};
100 int write_throttle = 0;
101 bool write_confirmation_flag =
false;
103 void writeAudioInfoCharacteristic(AudioInfo info)
override {
106 info_char.writeValue((uint8_t *)&info,
sizeof(AudioInfo));
109 void writeChannel2Characteristic(
const uint8_t *data,
size_t len) {
110 if (ch02_char.canWrite()) {
111 ch02_char.writeValue((uint8_t *)data, len, write_confirmation_flag);
112 delay(write_throttle);
116 bool readAudioInfoCharacteristic() {
117 if (!info_char.canRead())
119 const uint8_t *str = info_char.value();
120 int len = info_char.valueLength();
128 static void onInfoUpdated(BLEDevice central,
129 BLECharacteristic characteristic) {
130 selfAudioBLEClient->
setAudioInfo(characteristic.value(),
131 characteristic.valueLength());
134 bool setupBLEClient() {
136 if (peripheral.connected()) {
143 if (write_buffer.size() == 0) {
144 write_buffer.resize(getMTU() - BLE_MTU_OVERHEAD);
147 peripheral = BLE.available();
154 if (!peripheral.connect()) {
158 if (peripheral.discoverAttributes()) {
159 LOGI(
"Attributes discovered");
161 LOGE(
"Attribute discovery failed!");
162 peripheral.disconnect();
166 ch01_char = peripheral.characteristic(BLE_CH1_UUID);
168 peripheral.disconnect();
172 ch02_char = peripheral.characteristic(BLE_CH2_UUID);
174 peripheral.disconnect();
178 if (is_audio_info_active) {
179 info_char = peripheral.characteristic(BLE_INFO_UUID);
180 info_char.setEventHandler(BLEUpdated, onInfoUpdated);