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