-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathble_controller.cpp
More file actions
81 lines (67 loc) · 2.12 KB
/
Copy pathble_controller.cpp
File metadata and controls
81 lines (67 loc) · 2.12 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
/*
* BLE Controller Implementation
*
* Copyright (c) 2026 Dharagesh, Circuit Digest
*/
#include "ble_controller.h"
#include <BLEDevice.h>
#include <BLEUtils.h>
static BLEClient* pClient = nullptr;
static bool connectedToBms = false;
static bool clientInitialized = false;
// Client callbacks to monitor connection state
class ShieldClientCallbacks : public BLEClientCallbacks {
void onConnect(BLEClient* pclient) {
connectedToBms = true;
Serial.println("BLE Callback: Connected to BMS.");
}
void onDisconnect(BLEClient* pclient) {
connectedToBms = false;
Serial.println("BLE Callback: Disconnected from BMS.");
}
};
void initBleController() {
if (clientInitialized) return;
BLEDevice::init("");
pClient = BLEDevice::createClient();
pClient->setClientCallbacks(new ShieldClientCallbacks());
clientInitialized = true;
Serial.println("BLE Client Initialized.");
}
bool connectToBms(const String& macAddress, int brand) {
if (!clientInitialized) {
initBleController();
}
// If already connected, do nothing
if (connectedToBms && pClient != nullptr && pClient->isConnected()) {
return true;
}
Serial.print("Attempting link-layer connection to BMS (");
Serial.print(macAddress);
Serial.println(")...");
BLEAddress targetAddress(macAddress.c_str());
// Connect to device at BLE link layer
if (!pClient->connect(targetAddress)) {
Serial.println("Connection failed.");
return false;
}
connectedToBms = true;
Serial.println("Connected to BMS (Link-Layer lock active).");
return true;
}
void disconnectBms() {
if (pClient != nullptr && pClient->isConnected()) {
pClient->disconnect();
}
connectedToBms = false;
Serial.println("Manually disconnected BLE BMS link.");
}
bool isBmsConnected() {
return connectedToBms && pClient != nullptr && pClient->isConnected();
}
void handleBleController(const String& macAddress, int brand) {
// If not connected, attempt connection
if (!isBmsConnected()) {
connectToBms(macAddress, brand);
}
}