8constexpr uint16_t kGapServiceUuid{0x1800};
9constexpr uint16_t kGapDeviceNameUuid{0x2A00};
11constexpr uint16_t kInputsServiceUuid{0xFFA0};
12constexpr uint16_t kInputsCharacteristicUuid{0xFFA1};
14constexpr uint16_t kBatteryServiceUuid{0x180F};
15constexpr uint16_t kBatteryLevelCharacteristicUuid{0x2A19};
17constexpr uint16_t kDeviceInfoServiceUuid{0x180A};
18constexpr uint16_t kModelNumberCharacteristicUuid{0x2A24};
19constexpr uint16_t kSerialNumberCharacteristicUuid{0x2A25};
20constexpr uint16_t kFirmwareRevisionCharacteristicUuid{0x2A26};
21constexpr uint16_t kManufacturerNameCharacteristicUuid{0x2A29};
23bool HasAxisValueChangedSignificantly(
const int16_t prev_value,
const int16_t current_value,
const uint8_t threshold) {
24 return prev_value != current_value && (current_value == 0 || current_value == 255 || std::abs(current_value - prev_value) >= threshold);
33 if (!NimBLEDevice::isInitialized()) {
34 NimBLEDevice::init(
"CodexPadClient");
38bool CodexPad::Connect(
const std::string& bluetooth_device_address,
const uint32_t timeout_ms) {
40 if (bluetooth_device_address.length() != 17 || bluetooth_device_address[2] !=
':' || bluetooth_device_address[5] !=
':' ||
41 bluetooth_device_address[8] !=
':' || bluetooth_device_address[11] !=
':' || bluetooth_device_address[14] !=
':') {
46 return Connect(NimBLEAddress(bluetooth_device_address, 0),
false, timeout_ms);
50 auto scanner = NimBLEDevice::getScan();
51 scanner->setActiveScan(
true);
52 scanner->setInterval(1000);
53 scanner->setWindow(999);
55 if (!scanner->start(1000)) {
57 scanner->clearResults();
62 while (scanner->isScanning()) {
68 int8_t rssi = INT8_MIN;
69 NimBLEAddress address;
72 struct ManufacturerData {
73 uint16_t company_id = 0xFFFF;
74 uint8_t header[8] = {
'C',
'o',
'd',
'e',
'x',
'P',
'a',
'd'};
75 uint8_t version_major = 0;
76 uint8_t version_minor = 0;
77 uint8_t version_patch = 0;
82 for (
const auto device : scanner->getResults()) {
83 if (device->haveName() && String(device->getName().c_str()).startsWith(
"CodexPad-") && device->haveManufacturerData()) {
85 const auto manufacturer_data = device->getManufacturerData();
86 if (manufacturer_data.length() >=
sizeof(ManufacturerData)) {
87 const auto data =
reinterpret_cast<const ManufacturerData*
>(manufacturer_data.c_str());
88 if (data->company_id == 0xFFFF && memcmp(data->header,
"CodexPad", 8) == 0 && data->button_state == button_mask && device->getRSSI() > rssi) {
89 rssi = device->getRSSI();
90 address = device->getAddress();
97 scanner->clearResults();
99 return address.isNull() ? false :
Connect(address, 2000);
103 if (ble_client_ ==
nullptr) {
107 if (!ble_client_->isConnected()) {
112 prev_inputs_ = current_inputs_;
114 std::lock_guard<std::mutex> l(mutex_);
115 if (inputs_queue_.empty()) {
118 current_inputs_ = std::move(inputs_queue_.front());
126 if (ble_client_ ==
nullptr) {
130 if (!ble_client_->isConnected()) {
134 auto remote_service = ble_client_->getService(uint16_t{0x1804});
135 if (remote_service ==
nullptr) {
139 auto remote_characteristic = remote_service->getCharacteristic(uint16_t{0x2A07});
140 if (remote_characteristic ==
nullptr) {
144 return remote_characteristic->writeValue(
static_cast<uint8_t
>(tx_power));
148 return (prev_inputs_.button_states &
static_cast<uint32_t
>(button)) == 0 && (current_inputs_.button_states &
static_cast<uint32_t
>(button)) != 0;
152 return (prev_inputs_.button_states &
static_cast<uint32_t
>(button)) != 0 && (current_inputs_.button_states &
static_cast<uint32_t
>(button)) == 0;
156 return (prev_inputs_.button_states &
static_cast<uint32_t
>(button)) != 0 && (current_inputs_.button_states &
static_cast<uint32_t
>(button)) != 0;
174 return HasAxisValueChangedSignificantly(
175 current_inputs_.axis_values[
static_cast<size_t>(axis)], prev_inputs_.axis_values[
static_cast<size_t>(axis)], threshold);
178bool CodexPad::Connect(
const NimBLEAddress& address,
bool async_connect,
const uint32_t timeout_ms) {
180 assert(ble_client_ ==
nullptr);
181 ble_client_ = NimBLEDevice::createClient(address);
182 ble_client_->setConnectTimeout(timeout_ms);
183 auto ret = ble_client_->connect(
true, async_connect,
true);
185 if (!ret || !ble_client_->isConnected()) {
189 remote_device_name_ = ble_client_->getValue(kGapServiceUuid, kGapDeviceNameUuid);
190 remote_model_number_ = ble_client_->getValue(kDeviceInfoServiceUuid, kModelNumberCharacteristicUuid);
192 auto firmware_revision = ble_client_->getValue(kDeviceInfoServiceUuid, kFirmwareRevisionCharacteristicUuid);
193 if (firmware_revision.length() ==
sizeof(remote_firmware_version_)) {
194 memcpy(remote_firmware_version_.data(), firmware_revision.data(), firmware_revision.length());
199 auto remote_service = ble_client_->getService(kInputsServiceUuid);
200 if (remote_service ==
nullptr) {
204 auto remote_characteristic = remote_service->getCharacteristic(kInputsCharacteristicUuid);
205 if (remote_characteristic ==
nullptr) {
209 if (!remote_characteristic->canNotify()) {
213 if (!remote_characteristic->subscribe(
214 true, std::bind(&CodexPad::OnNotify,
this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4))) {
226void CodexPad::OnNotify(
const NimBLERemoteCharacteristic* remote_characteristic,
const uint8_t* data,
const size_t length,
const bool is_notify) {
227 if (remote_characteristic !=
nullptr && remote_characteristic->getUUID().equals(kInputsCharacteristicUuid)) {
228 if (length !=
sizeof(Inputs)) {
229 printf(
"WARNING: length != sizeof(Inputs)\n");
233 std::lock_guard<std::mutex> l(mutex_);
234 if (inputs_queue_.size() > kInputsQueueMax) {
238 memcpy(&inputs, data,
sizeof(inputs));
239 inputs_queue_.emplace(std::move(inputs));
243void CodexPad::Reset() {
244 if (ble_client_ !=
nullptr) {
245 ble_client_->cancelConnect();
246 ble_client_->disconnect();
247 NimBLEDevice::deleteClient(ble_client_);
248 ble_client_ =
nullptr;
251 remote_device_name_.clear();
252 remote_model_number_.clear();
253 remote_firmware_version_.fill(0);
255 current_inputs_ = {};
256 std::lock_guard<std::mutex> l(mutex_);
uint32_t button_states() const
Get all button states, return a 32-bit unsigned integer where each bit represents the state of a spec...
bool ScanAndConnect(const uint32_t button_mask)
Scans for nearby CodexPad devices and automatically connects to a device whose button state matches t...
bool pressed(const Button button) const
check if a button is pressed
static constexpr size_t kAxisValueNum
Number of axis values.
bool Connect(const std::string &bluetooth_device_address, const uint32_t timeout_ms=5000)
Connect.
uint8_t axis_value(const Axis axis) const
Get axis value.
bool HasAxisValueChanged(const Axis axis, const uint8_t threshold) const
check if an axis value has changed
static constexpr uint8_t kAxisCenter
Axis center value.
bool set_remote_tx_power(const TxPower power)
Set transmission power, only effective when connected, immediately effective for current connection,...
bool is_connected() const
Is connected.
bool released(const Button button) const
check if a button is released
std::array< uint8_t, kAxisValueNum > axis_values() const
Get current values of all analog axes.
void Update()
Update, need to be called in Loop.
bool button_state(const Button button) const
check if a button is pressed or held
bool holding(const Button button) const
check if a button is held