CodexPad Arduino Lib 4.0.0
Loading...
Searching...
No Matches
client.cpp
1#include "client.h"
2
3#include <Arduino.h>
4
5#include <memory>
6
7#include "WString.h"
8// #include "cyf.h"
9// #include "cyf/log.h"
10
11namespace codex_pad {
12namespace {
13constexpr uint16_t kGapServiceUuid{0x1800};
14constexpr uint16_t kGapDeviceNameUuid{0x2A00};
15
16constexpr uint16_t kInputsServiceUuid{0xFFA0};
17constexpr uint16_t kInputsCharacteristicUuid{0xFFA1};
18
19constexpr uint16_t kBatteryServiceUuid{0x180F};
20constexpr uint16_t kBatteryLevelCharacteristicUuid{0x2A19};
21
22constexpr uint16_t kDeviceInfoServiceUuid{0x180A};
23constexpr uint16_t kModelNumberCharacteristicUuid{0x2A24};
24constexpr uint16_t kSerialNumberCharacteristicUuid{0x2A25};
25constexpr uint16_t kFirmwareRevisionCharacteristicUuid{0x2A26};
26constexpr uint16_t kManufacturerNameCharacteristicUuid{0x2A29};
27
28constexpr uint16_t kConnectionParamMinInterval{6};
29constexpr uint16_t kConnectionParamMaxInterval{8};
30constexpr uint16_t kConnectionParamLatency{5};
31constexpr uint16_t kConnectionParamSupervisionTimeout{30};
32
33static_assert(kConnectionParamSupervisionTimeout * 10.0 >
34 (1 + kConnectionParamLatency) * kConnectionParamMaxInterval * 4 * 1.25);
35} // namespace
36
37Client::Client() noexcept {}
38
39Client::~Client() noexcept { Reset(); }
40
41void Client::Init() noexcept {
42 if (!NimBLEDevice::isInitialized()) {
43 NimBLEDevice::init("Client");
44 }
45}
46
47bool Client::Connect(const std::string& bluetooth_device_address, const uint32_t timeout_ms) noexcept {
48 // check mac address is valid
49 if (bluetooth_device_address.length() != 17 || bluetooth_device_address[2] != ':' || bluetooth_device_address[5] != ':' ||
50 bluetooth_device_address[8] != ':' || bluetooth_device_address[11] != ':' || bluetooth_device_address[14] != ':') {
51 abort();
52 return false;
53 }
54
55 return Connect(NimBLEAddress(bluetooth_device_address, 0), false, timeout_ms);
56}
57
58bool Client::ScanAndConnect(const gamepad::input::Button buttons) noexcept {
59 auto scanner = NimBLEDevice::getScan();
60 scanner->setActiveScan(true); // active scan uses more power, but get results faster
61 scanner->setInterval(1000);
62 scanner->setWindow(999); // less or equal setInterval value
63
64 if (!scanner->start(1000)) {
65 scanner->stop();
66 scanner->clearResults();
67 // printf("Scan failed\n");
68 return false;
69 }
70
71 while (scanner->isScanning()) {
72 delay(100);
73 }
74
75 // printf("Scan done, device count: %d\n", scanner->getResults().getCount());
76
77 int8_t rssi = INT8_MIN;
78 NimBLEAddress address;
79
80#pragma pack(push, 1)
81 struct ManufacturerSpecificData {
82 uint16_t company_id = 0xFFFF;
83 uint8_t header[8] = {'C', 'o', 'd', 'e', 'x', 'P', 'a', 'd'};
84 uint8_t version_major = 0;
85 uint8_t version_minor = 0;
86 uint8_t version_patch = 0;
87 uint32_t button_state = 0;
88 uint8_t button_states_duration_seconds = 0;
89 };
90#pragma pack(pop)
91
92 for (const auto device : scanner->getResults()) {
93 if (device->haveName() && String(device->getName().c_str()).startsWith("CodexPad-") && device->haveManufacturerData()) {
94 // printf("Name: %s\n", device->getName().c_str());
95 const auto manufacturer_data = device->getManufacturerData();
96 if (manufacturer_data.length() >= sizeof(ManufacturerSpecificData)) {
97 const auto data = reinterpret_cast<const ManufacturerSpecificData*>(manufacturer_data.c_str());
98 if (data->company_id == 0xFFFF // company id
99 && memcmp(data->header, "CodexPad", 8) == 0 // header
100 && data->button_state == static_cast<uint32_t>(buttons) // button mask
101 && device->getRSSI() > rssi // rssi
102 && (data->version_major < 2 || data->button_states_duration_seconds >= 1) // button states duration
103 ) {
104 rssi = device->getRSSI();
105 address = device->getAddress();
106 // printf("Found device, rssi: %d, address: %s\n", rssi, address.toString().c_str());
107 }
108 }
109 }
110 }
111
112 scanner->clearResults();
113
114 return address.isNull() ? false : Connect(address, 2000);
115}
116
117const gamepad::input::Tracker& Client::Update() noexcept {
118 if (ble_client_ == nullptr) {
119 return input_tracker_;
120 }
121
122 if (!ble_client_->isConnected()) {
123 Reset();
124 return input_tracker_;
125 }
126
127 input_tracker_.Tick();
128
129 do {
130 std::lock_guard<std::mutex> l(mutex_);
131 if (inputs_queue_.empty()) {
132 break;
133 }
134
135 input_tracker_.Update(inputs_queue_.front());
136 inputs_queue_.pop();
137 } while (false);
138
139 return input_tracker_;
140}
141
142bool Client::is_connected() const noexcept { return ble_client_ != nullptr && ble_client_->isConnected(); }
143
144bool Client::Connect(const NimBLEAddress& address, bool async_connect, const uint32_t timeout_ms) {
145 Reset();
146 assert(ble_client_ == nullptr);
147 ble_client_ = NimBLEDevice::createClient(address);
148 ble_client_->setConnectTimeout(timeout_ms);
149 ble_client_->setConnectionParams(kConnectionParamMinInterval, kConnectionParamMaxInterval, kConnectionParamLatency,
150 kConnectionParamSupervisionTimeout);
151 ble_client_->setClientCallbacks(this, false);
152 auto ret = ble_client_->connect(true, async_connect, true);
153
154 if (!ret || !ble_client_->isConnected()) {
155 goto FAILED;
156 }
157
158 remote_device_name_ = ble_client_->getValue(kGapServiceUuid, kGapDeviceNameUuid);
159 remote_model_number_ = ble_client_->getValue(kDeviceInfoServiceUuid, kModelNumberCharacteristicUuid);
160 {
161 auto firmware_revision = ble_client_->getValue(kDeviceInfoServiceUuid, kFirmwareRevisionCharacteristicUuid);
162 if (firmware_revision.length() == remote_firmware_version_.size()) {
163 memcpy(remote_firmware_version_.data(), firmware_revision.data(), firmware_revision.length());
164 }
165 }
166
167 {
168 auto remote_service = ble_client_->getService(kInputsServiceUuid);
169 if (remote_service == nullptr) {
170 goto FAILED;
171 }
172
173 auto remote_characteristic = remote_service->getCharacteristic(kInputsCharacteristicUuid);
174 if (remote_characteristic == nullptr) {
175 goto FAILED;
176 }
177
178 if (!remote_characteristic->canNotify()) {
179 goto FAILED;
180 }
181
182 if (!remote_characteristic->subscribe(true, std::bind(&Client::OnNotify, this, std::placeholders::_1, std::placeholders::_2,
183 std::placeholders::_3, std::placeholders::_4))) {
184 goto FAILED;
185 }
186 }
187
188 ble_client_->updatePhy(BLE_GAP_LE_PHY_CODED_MASK, BLE_GAP_LE_PHY_CODED_MASK, BLE_GAP_LE_PHY_CODED_S8);
189
190 return ret;
191
192FAILED:
193 Reset();
194 return false;
195}
196
197void Client::OnNotify(const NimBLERemoteCharacteristic* remote_characteristic, const uint8_t* data, const size_t length,
198 const bool is_notify) {
199 if (remote_characteristic != nullptr && remote_characteristic->getUUID().equals(kInputsCharacteristicUuid)) {
200 if (length != sizeof(gamepad::input::State)) {
201 printf("WARNING: length != sizeof(Inputs)\n");
202 return;
203 }
204
205 std::lock_guard<std::mutex> l(mutex_);
206 if (inputs_queue_.size() > kInputsQueueMax) {
207 inputs_queue_.pop();
208 }
209 inputs_queue_.emplace(gamepad::input::State::FromBytes(data));
210 }
211}
212
213void Client::Reset() {
214 if (ble_client_ != nullptr) {
215 ble_client_->cancelConnect();
216 ble_client_->disconnect();
217 NimBLEDevice::deleteClient(ble_client_);
218 ble_client_ = nullptr;
219 }
220
221 remote_device_name_.clear();
222 remote_model_number_.clear();
223 remote_firmware_version_.fill(0);
224 input_tracker_.Reset();
225 std::lock_guard<std::mutex> l(mutex_);
226 inputs_queue_ = {};
227}
228
229int32_t Client::rssi() const noexcept { return ble_client_ == nullptr ? 0 : ble_client_->getRssi(); }
230
231void Client::onPhyUpdate(NimBLEClient*, [[maybe_unused]] uint8_t tx_phy, [[maybe_unused]] uint8_t rx_phy) {
232 // CLOGI("tx_phy: %d, rx_phy: %d", tx_phy, rx_phy);
233}
234} // namespace codex_pad
Client() noexcept
Constructor.
Definition client.cpp:37
const gamepad::input::Tracker & Update() noexcept
Update, need to be called in Loop.
Definition client.cpp:117
bool is_connected() const noexcept
Is connected.
Definition client.cpp:142
void Init() noexcept
Initialize.
Definition client.cpp:41
bool ScanAndConnect(gamepad::input::Button buttons) noexcept
Scans for nearby CodexPad devices and automatically connects to a device whose button state matches t...
Definition client.cpp:58
bool Connect(const std::string &bluetooth_device_address, uint32_t timeout_ms=5000) noexcept
Connect.
Definition client.cpp:47
int32_t rssi() const noexcept
Get the RSSI of the CodexPad.
Definition client.cpp:229
~Client() noexcept
Destructor.
Definition client.cpp:39