-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathble_functions
More file actions
204 lines (168 loc) · 6.04 KB
/
ble_functions
File metadata and controls
204 lines (168 loc) · 6.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
/* Handshake Process:
* 1. On connection, controller sends value 3
* 2. Central device responds with value 3
* 3. Controller marks handshake as complete
* 4. Normal movement values (0,1,2) can now be sent
*/
#include <ArduinoBLE.h>
// UUIDs are generated dynamically based on device number
// This ensures each device has a unique service UUID for easy filtering
String serviceUuidStr;
String characteristicUuidStr;
const char* SERVICE_UUID;
const char* CHARACTERISTIC_UUID;
BLEService* pongService = nullptr;
BLEByteCharacteristic* movementCharacteristic = nullptr;
int statusLedPin;
unsigned long lastConnectionAttempt = 0;
unsigned long lastLedToggle = 0;
unsigned long lastNotificationTime = 0;
const unsigned long CONNECTION_RETRY_INTERVAL = 2000;
const unsigned long LED_BLINK_INTERVAL = 500;
const unsigned long MIN_NOTIFICATION_INTERVAL = 20;
bool ledState = false;
bool serviceStarted = false;
bool handshakeComplete = false;
// Buffer for notification management
int lastSentValue = 0;
bool valueChanged = false;
// Strategy 1: Manufacturer data for device identification
// This helps the web app identify DFPONG devices more reliably
const uint8_t manufacturerData[] = {0xDF, 0x01}; // DF = DFPong, 01 = version
void onBLEConnected(BLEDevice central) {
Serial.print("Connected to central: ");
Serial.println(central.address());
digitalWrite(statusLedPin, HIGH);
handshakeComplete = false; // Reset handshake state on new connection
lastSentValue = 3; // Force initial handshake message
valueChanged = true;
}
void onBLEDisconnected(BLEDevice central) {
Serial.print("Disconnected from central: ");
Serial.println(central.address());
lastSentValue = 0;
valueChanged = false;
handshakeComplete = false;
}
void onCharacteristicWritten(BLEDevice central, BLECharacteristic characteristic) {
if (characteristic.uuid() == CHARACTERISTIC_UUID) {
byte value = movementCharacteristic->value();
if (value == 3) {
handshakeComplete = true;
}
}
}
// Generate unique UUIDs based on device number (1-25)
void generateUUIDs(int deviceNumber) {
// Base UUIDs (must match JavaScript exactly, ending with "12")
const String serviceBase = "19b10010-e8f2-537e-4f6c-d104768a12";
const String characteristicBase = "19b10011-e8f2-537e-4f6c-d104768a12";
// Calculate unique suffix (base 14 + deviceNumber - 1)
// Device 1 → 14 (0x0E), Device 2 → 15 (0x0F), etc.
int suffix = 13 + deviceNumber;
// Convert to hex string (2 digits, lowercase)
String hexSuffix = String(suffix, HEX);
if (hexSuffix.length() == 1) {
hexSuffix = "0" + hexSuffix;
}
hexSuffix.toLowerCase();
// Generate full UUIDs (must keep strings in memory)
serviceUuidStr = serviceBase + hexSuffix;
characteristicUuidStr = characteristicBase + hexSuffix;
// Store c_str pointers - strings must remain in scope
SERVICE_UUID = serviceUuidStr.c_str();
CHARACTERISTIC_UUID = characteristicUuidStr.c_str();
Serial.print("Device #");
Serial.println(deviceNumber);
Serial.print("Service UUID: ");
Serial.println(SERVICE_UUID);
Serial.print("Characteristic UUID: ");
Serial.println(CHARACTERISTIC_UUID);
}
void setupBLE(const char* deviceName, int deviceNumber, int ledPin) {
statusLedPin = ledPin;
pinMode(statusLedPin, OUTPUT);
// Generate unique UUIDs based on device number
generateUUIDs(deviceNumber);
// Create BLE service and characteristic with generated UUIDs
pongService = new BLEService(SERVICE_UUID);
movementCharacteristic = new BLEByteCharacteristic(CHARACTERISTIC_UUID, BLERead | BLENotify | BLEWrite);
// Initialize BLE with retry
for (int i = 0; i < 3; i++) {
if (BLE.begin()) {
break;
}
delay(500);
if (i == 2) {
while (1) {
digitalWrite(statusLedPin, HIGH);
delay(100);
digitalWrite(statusLedPin, LOW);
delay(100);
}
}
}
// Reset BLE state
BLE.disconnect();
delay(100);
BLE.stopAdvertise();
delay(100);
// Configure BLE parameters
BLE.setEventHandler(BLEConnected, onBLEConnected);
BLE.setEventHandler(BLEDisconnected, onBLEDisconnected);
movementCharacteristic->setEventHandler(BLEWritten, onCharacteristicWritten);
BLE.setLocalName(deviceName);
BLE.setAdvertisedServiceUuid(pongService->uuid());
// Strategy 1: Optimized connection parameters for crowded environments
// Longer intervals reduce radio congestion
BLE.setConnectionInterval(12, 24); // 15-30ms (was 8-16, now more conservative)
BLE.setPairable(false);
BLE.setAdvertisingInterval(160); // 100ms (was 80ms, reduces collisions)
// Strategy 1: Add manufacturer data for better device identification
BLE.setManufacturerData(manufacturerData, sizeof(manufacturerData));
pongService->addCharacteristic(*movementCharacteristic);
BLE.addService(*pongService);
movementCharacteristic->writeValue(0);
delay(100);
serviceStarted = true;
BLE.advertise();
Serial.println("BLE setup complete - Advertising started");
}
bool isConnected() {
return serviceStarted && BLE.connected() && movementCharacteristic->subscribed() && handshakeComplete;
}void updateLED() {
if (!isConnected()) {
unsigned long currentTime = millis();
if (currentTime - lastLedToggle >= LED_BLINK_INTERVAL) {
ledState = !ledState;
digitalWrite(statusLedPin, ledState);
lastLedToggle = currentTime;
}
}
}
void updateBLE() {
BLE.poll();
updateLED();
}
void sendMovement(int movement) {
if (!BLE.connected() || !movementCharacteristic->subscribed()) {
return;
}
// If not handshake complete, keep sending handshake message
if (!handshakeComplete) {
movement = 3;
}
unsigned long currentTime = millis();
// Check if value has changed
if (movement != lastSentValue) {
valueChanged = true;
}
// Only send if value changed and enough time has passed
if (valueChanged && (currentTime - lastNotificationTime >= MIN_NOTIFICATION_INTERVAL)) {
if (movementCharacteristic->writeValue(movement)) {
lastSentValue = movement;
lastNotificationTime = currentTime;
valueChanged = false;
}
}
}