forked from zmkfirmware/zmk
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathcentral.c
626 lines (497 loc) · 20.1 KB
/
central.c
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
/*
* Copyright (c) 2020 The ZMK Contributors
*
* SPDX-License-Identifier: MIT
*/
#include <zephyr/types.h>
#include <zephyr/init.h>
#include <zephyr/bluetooth/bluetooth.h>
#include <zephyr/bluetooth/conn.h>
#include <zephyr/bluetooth/uuid.h>
#include <zephyr/bluetooth/gatt.h>
#include <zephyr/bluetooth/hci.h>
#include <zephyr/sys/byteorder.h>
#include <zephyr/logging/log.h>
LOG_MODULE_DECLARE(zmk, CONFIG_ZMK_LOG_LEVEL);
#include <zmk/stdlib.h>
#include <zmk/ble.h>
#include <zmk/behavior.h>
#include <zmk/split/bluetooth/uuid.h>
#include <zmk/split/bluetooth/service.h>
#include <zmk/event_manager.h>
#include <zmk/events/position_state_changed.h>
static int start_scanning(void);
#define POSITION_STATE_DATA_LEN 16
enum peripheral_slot_state {
PERIPHERAL_SLOT_STATE_OPEN,
PERIPHERAL_SLOT_STATE_CONNECTING,
PERIPHERAL_SLOT_STATE_CONNECTED,
};
struct peripheral_slot {
enum peripheral_slot_state state;
struct bt_conn *conn;
struct bt_gatt_discover_params discover_params;
struct bt_gatt_subscribe_params subscribe_params;
struct bt_gatt_discover_params sub_discover_params;
uint16_t run_behavior_handle;
uint8_t position_state[POSITION_STATE_DATA_LEN];
uint8_t changed_positions[POSITION_STATE_DATA_LEN];
};
static struct peripheral_slot peripherals[ZMK_SPLIT_BLE_PERIPHERAL_COUNT];
static bool is_scanning = false;
static const struct bt_uuid_128 split_service_uuid = BT_UUID_INIT_128(ZMK_SPLIT_BT_SERVICE_UUID);
K_MSGQ_DEFINE(peripheral_event_msgq, sizeof(struct zmk_position_state_changed),
CONFIG_ZMK_SPLIT_BLE_CENTRAL_POSITION_QUEUE_SIZE, 4);
void peripheral_event_work_callback(struct k_work *work) {
struct zmk_position_state_changed ev;
while (k_msgq_get(&peripheral_event_msgq, &ev, K_NO_WAIT) == 0) {
LOG_DBG("Trigger key position state change for %d", ev.position);
ZMK_EVENT_RAISE(new_zmk_position_state_changed(ev));
}
}
K_WORK_DEFINE(peripheral_event_work, peripheral_event_work_callback);
int peripheral_slot_index_for_conn(struct bt_conn *conn) {
for (int i = 0; i < ZMK_SPLIT_BLE_PERIPHERAL_COUNT; i++) {
if (peripherals[i].conn == conn) {
return i;
}
}
return -EINVAL;
}
struct peripheral_slot *peripheral_slot_for_conn(struct bt_conn *conn) {
int idx = peripheral_slot_index_for_conn(conn);
if (idx < 0) {
return NULL;
}
return &peripherals[idx];
}
int release_peripheral_slot(int index) {
if (index < 0 || index >= ZMK_SPLIT_BLE_PERIPHERAL_COUNT) {
return -EINVAL;
}
struct peripheral_slot *slot = &peripherals[index];
if (slot->state == PERIPHERAL_SLOT_STATE_OPEN) {
return -EINVAL;
}
LOG_DBG("Releasing peripheral slot at %d", index);
if (slot->conn != NULL) {
bt_conn_unref(slot->conn);
slot->conn = NULL;
}
slot->state = PERIPHERAL_SLOT_STATE_OPEN;
// Raise events releasing any active positions from this peripheral
for (int i = 0; i < POSITION_STATE_DATA_LEN; i++) {
for (int j = 0; j < 8; j++) {
if (slot->position_state[i] & BIT(j)) {
uint32_t position = (i * 8) + j;
struct zmk_position_state_changed ev = {.source = index,
.position = position,
.state = false,
.timestamp = k_uptime_get()};
k_msgq_put(&peripheral_event_msgq, &ev, K_NO_WAIT);
k_work_submit(&peripheral_event_work);
}
}
}
for (int i = 0; i < POSITION_STATE_DATA_LEN; i++) {
slot->position_state[i] = 0U;
slot->changed_positions[i] = 0U;
}
// Clean up previously discovered handles;
slot->subscribe_params.value_handle = 0;
slot->run_behavior_handle = 0;
return 0;
}
int reserve_peripheral_slot(const bt_addr_le_t *addr) {
int i = zmk_ble_put_peripheral_addr(addr);
if (i >= 0) {
if (peripherals[i].state == PERIPHERAL_SLOT_STATE_OPEN) {
// Be sure the slot is fully reinitialized.
release_peripheral_slot(i);
peripherals[i].state = PERIPHERAL_SLOT_STATE_CONNECTING;
return i;
}
}
return -ENOMEM;
}
int release_peripheral_slot_for_conn(struct bt_conn *conn) {
int idx = peripheral_slot_index_for_conn(conn);
if (idx < 0) {
return idx;
}
return release_peripheral_slot(idx);
}
int confirm_peripheral_slot_conn(struct bt_conn *conn) {
int idx = peripheral_slot_index_for_conn(conn);
if (idx < 0) {
return idx;
}
peripherals[idx].state = PERIPHERAL_SLOT_STATE_CONNECTED;
return 0;
}
static uint8_t split_central_notify_func(struct bt_conn *conn,
struct bt_gatt_subscribe_params *params, const void *data,
uint16_t length) {
struct peripheral_slot *slot = peripheral_slot_for_conn(conn);
if (slot == NULL) {
LOG_ERR("No peripheral state found for connection");
return BT_GATT_ITER_CONTINUE;
}
if (!data) {
LOG_DBG("[UNSUBSCRIBED]");
params->value_handle = 0U;
return BT_GATT_ITER_STOP;
}
LOG_DBG("[NOTIFICATION] data %p length %u", data, length);
for (int i = 0; i < POSITION_STATE_DATA_LEN; i++) {
slot->changed_positions[i] = ((uint8_t *)data)[i] ^ slot->position_state[i];
slot->position_state[i] = ((uint8_t *)data)[i];
LOG_DBG("data: %d", slot->position_state[i]);
}
for (int i = 0; i < POSITION_STATE_DATA_LEN; i++) {
for (int j = 0; j < 8; j++) {
if (slot->changed_positions[i] & BIT(j)) {
uint32_t position = (i * 8) + j;
bool pressed = slot->position_state[i] & BIT(j);
struct zmk_position_state_changed ev = {.source =
peripheral_slot_index_for_conn(conn),
.position = position,
.state = pressed,
.timestamp = k_uptime_get()};
k_msgq_put(&peripheral_event_msgq, &ev, K_NO_WAIT);
k_work_submit(&peripheral_event_work);
}
}
}
return BT_GATT_ITER_CONTINUE;
}
static void split_central_subscribe(struct bt_conn *conn) {
struct peripheral_slot *slot = peripheral_slot_for_conn(conn);
if (slot == NULL) {
LOG_ERR("No peripheral state found for connection");
return;
}
int err = bt_gatt_subscribe(conn, &slot->subscribe_params);
switch (err) {
case -EALREADY:
LOG_DBG("[ALREADY SUBSCRIBED]");
break;
case 0:
LOG_DBG("[SUBSCRIBED]");
break;
default:
LOG_ERR("Subscribe failed (err %d)", err);
break;
}
}
static uint8_t split_central_chrc_discovery_func(struct bt_conn *conn,
const struct bt_gatt_attr *attr,
struct bt_gatt_discover_params *params) {
if (!attr) {
LOG_DBG("Discover complete");
return BT_GATT_ITER_STOP;
}
if (!attr->user_data) {
LOG_ERR("Required user data not passed to discovery");
return BT_GATT_ITER_STOP;
}
struct peripheral_slot *slot = peripheral_slot_for_conn(conn);
if (slot == NULL) {
LOG_ERR("No peripheral state found for connection");
return BT_GATT_ITER_STOP;
}
LOG_DBG("[ATTRIBUTE] handle %u", attr->handle);
if (!bt_uuid_cmp(((struct bt_gatt_chrc *)attr->user_data)->uuid,
BT_UUID_DECLARE_128(ZMK_SPLIT_BT_CHAR_POSITION_STATE_UUID))) {
LOG_DBG("Found position state characteristic");
slot->discover_params.uuid = NULL;
slot->discover_params.start_handle = attr->handle + 2;
slot->discover_params.type = BT_GATT_DISCOVER_CHARACTERISTIC;
slot->subscribe_params.disc_params = &slot->sub_discover_params;
slot->subscribe_params.end_handle = slot->discover_params.end_handle;
slot->subscribe_params.value_handle = bt_gatt_attr_value_handle(attr);
slot->subscribe_params.notify = split_central_notify_func;
slot->subscribe_params.value = BT_GATT_CCC_NOTIFY;
split_central_subscribe(conn);
} else if (!bt_uuid_cmp(((struct bt_gatt_chrc *)attr->user_data)->uuid,
BT_UUID_DECLARE_128(ZMK_SPLIT_BT_CHAR_RUN_BEHAVIOR_UUID))) {
LOG_DBG("Found run behavior handle");
slot->run_behavior_handle = bt_gatt_attr_value_handle(attr);
}
bool subscribed = (slot->run_behavior_handle && slot->subscribe_params.value_handle);
return subscribed ? BT_GATT_ITER_STOP : BT_GATT_ITER_CONTINUE;
}
static uint8_t split_central_service_discovery_func(struct bt_conn *conn,
const struct bt_gatt_attr *attr,
struct bt_gatt_discover_params *params) {
if (!attr) {
LOG_DBG("Discover complete");
(void)memset(params, 0, sizeof(*params));
return BT_GATT_ITER_STOP;
}
LOG_DBG("[ATTRIBUTE] handle %u", attr->handle);
struct peripheral_slot *slot = peripheral_slot_for_conn(conn);
if (slot == NULL) {
LOG_ERR("No peripheral state found for connection");
return BT_GATT_ITER_STOP;
}
if (bt_uuid_cmp(slot->discover_params.uuid, BT_UUID_DECLARE_128(ZMK_SPLIT_BT_SERVICE_UUID))) {
LOG_DBG("Found other service");
return BT_GATT_ITER_CONTINUE;
}
LOG_DBG("Found split service");
slot->discover_params.uuid = NULL;
slot->discover_params.func = split_central_chrc_discovery_func;
slot->discover_params.start_handle = attr->handle + 1;
slot->discover_params.type = BT_GATT_DISCOVER_CHARACTERISTIC;
int err = bt_gatt_discover(conn, &slot->discover_params);
if (err) {
LOG_ERR("Failed to start discovering split service characteristics (err %d)", err);
}
return BT_GATT_ITER_STOP;
}
static void split_central_process_connection(struct bt_conn *conn) {
int err;
LOG_DBG("Current security for connection: %d", bt_conn_get_security(conn));
err = bt_conn_set_security(conn, BT_SECURITY_L2);
if (err) {
LOG_ERR("Failed to set security (reason %d)", err);
return;
}
struct peripheral_slot *slot = peripheral_slot_for_conn(conn);
if (slot == NULL) {
LOG_ERR("No peripheral state found for connection");
return;
}
if (!slot->subscribe_params.value_handle) {
slot->discover_params.uuid = &split_service_uuid.uuid;
slot->discover_params.func = split_central_service_discovery_func;
slot->discover_params.start_handle = 0x0001;
slot->discover_params.end_handle = 0xffff;
slot->discover_params.type = BT_GATT_DISCOVER_PRIMARY;
err = bt_gatt_discover(slot->conn, &slot->discover_params);
if (err) {
LOG_ERR("Discover failed(err %d)", err);
return;
}
}
struct bt_conn_info info;
bt_conn_get_info(conn, &info);
LOG_DBG("New connection params: Interval: %d, Latency: %d, PHY: %d", info.le.interval,
info.le.latency, info.le.phy->rx_phy);
// Restart scanning if necessary.
start_scanning();
}
static int stop_scanning() {
LOG_DBG("Stopping peripheral scanning");
is_scanning = false;
int err = bt_le_scan_stop();
if (err < 0) {
LOG_ERR("Stop LE scan failed (err %d)", err);
return err;
}
return 0;
}
static bool split_central_eir_found(const bt_addr_le_t *addr) {
LOG_DBG("Found the split service");
// Stop scanning so we can connect to the peripheral device.
int err = stop_scanning();
if (err < 0) {
return false;
}
int slot_idx = reserve_peripheral_slot(addr);
if (slot_idx < 0) {
LOG_ERR("Failed to reserve peripheral slot (err %d)", slot_idx);
return false;
}
struct peripheral_slot *slot = &peripherals[slot_idx];
LOG_DBG("Initiating new connnection");
struct bt_le_conn_param *param = BT_LE_CONN_PARAM(0x0006, 0x0006, 30, 400);
err = bt_conn_le_create(addr, BT_CONN_LE_CREATE_CONN, param, &slot->conn);
if (err < 0) {
LOG_ERR("Create conn failed (err %d) (create conn? 0x%04x)", err, BT_HCI_OP_LE_CREATE_CONN);
release_peripheral_slot(slot_idx);
start_scanning();
}
return false;
}
static bool split_central_eir_parse(struct bt_data *data, void *user_data) {
bt_addr_le_t *addr = user_data;
int i;
LOG_DBG("[AD]: %u data_len %u", data->type, data->data_len);
switch (data->type) {
case BT_DATA_UUID128_SOME:
case BT_DATA_UUID128_ALL:
if (data->data_len % 16 != 0U) {
LOG_ERR("AD malformed");
return true;
}
for (i = 0; i < data->data_len; i += 16) {
struct bt_uuid_128 uuid;
if (!bt_uuid_create(&uuid.uuid, &data->data[i], 16)) {
LOG_ERR("Unable to load UUID");
continue;
}
if (bt_uuid_cmp(&uuid.uuid, BT_UUID_DECLARE_128(ZMK_SPLIT_BT_SERVICE_UUID))) {
char uuid_str[BT_UUID_STR_LEN];
char service_uuid_str[BT_UUID_STR_LEN];
bt_uuid_to_str(&uuid.uuid, uuid_str, sizeof(uuid_str));
bt_uuid_to_str(BT_UUID_DECLARE_128(ZMK_SPLIT_BT_SERVICE_UUID), service_uuid_str,
sizeof(service_uuid_str));
LOG_DBG("UUID %s does not match split UUID: %s", uuid_str, service_uuid_str);
continue;
}
return split_central_eir_found(addr);
}
}
return true;
}
static void split_central_device_found(const bt_addr_le_t *addr, int8_t rssi, uint8_t type,
struct net_buf_simple *ad) {
char dev[BT_ADDR_LE_STR_LEN];
bt_addr_le_to_str(addr, dev, sizeof(dev));
LOG_DBG("[DEVICE]: %s, AD evt type %u, AD data len %u, RSSI %i", dev, type, ad->len, rssi);
/* We're only interested in connectable events */
if (type == BT_GAP_ADV_TYPE_ADV_IND || type == BT_GAP_ADV_TYPE_ADV_DIRECT_IND) {
bt_data_parse(ad, split_central_eir_parse, (void *)addr);
}
}
static int start_scanning(void) {
// No action is necessary if central is already scanning.
if (is_scanning) {
LOG_DBG("Scanning already running");
return 0;
}
// If all the devices are connected, there is no need to scan.
bool has_unconnected = false;
for (int i = 0; i < CONFIG_ZMK_SPLIT_BLE_CENTRAL_PERIPHERALS; i++) {
if (peripherals[i].conn == NULL) {
has_unconnected = true;
break;
}
}
if (!has_unconnected) {
LOG_DBG("All devices are connected, scanning is unnecessary");
return 0;
}
// Start scanning otherwise.
is_scanning = true;
int err = bt_le_scan_start(BT_LE_SCAN_PASSIVE, split_central_device_found);
if (err < 0) {
LOG_ERR("Scanning failed to start (err %d)", err);
return err;
}
LOG_DBG("Scanning successfully started");
return 0;
}
static void split_central_connected(struct bt_conn *conn, uint8_t conn_err) {
char addr[BT_ADDR_LE_STR_LEN];
struct bt_conn_info info;
bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
bt_conn_get_info(conn, &info);
if (info.role != BT_CONN_ROLE_CENTRAL) {
LOG_DBG("SKIPPING FOR ROLE %d", info.role);
return;
}
if (conn_err) {
LOG_ERR("Failed to connect to %s (%u)", addr, conn_err);
release_peripheral_slot_for_conn(conn);
start_scanning();
return;
}
LOG_DBG("Connected: %s", addr);
confirm_peripheral_slot_conn(conn);
split_central_process_connection(conn);
}
static void split_central_disconnected(struct bt_conn *conn, uint8_t reason) {
char addr[BT_ADDR_LE_STR_LEN];
int err;
bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
LOG_DBG("Disconnected: %s (reason %d)", addr, reason);
err = release_peripheral_slot_for_conn(conn);
if (err < 0) {
return;
}
start_scanning();
}
static struct bt_conn_cb conn_callbacks = {
.connected = split_central_connected,
.disconnected = split_central_disconnected,
};
K_THREAD_STACK_DEFINE(split_central_split_run_q_stack,
CONFIG_ZMK_SPLIT_BLE_CENTRAL_SPLIT_RUN_STACK_SIZE);
struct k_work_q split_central_split_run_q;
struct zmk_split_run_behavior_payload_wrapper {
uint8_t source;
struct zmk_split_run_behavior_payload payload;
};
K_MSGQ_DEFINE(zmk_split_central_split_run_msgq,
sizeof(struct zmk_split_run_behavior_payload_wrapper),
CONFIG_ZMK_SPLIT_BLE_CENTRAL_SPLIT_RUN_QUEUE_SIZE, 4);
void split_central_split_run_callback(struct k_work *work) {
struct zmk_split_run_behavior_payload_wrapper payload_wrapper;
LOG_DBG("");
while (k_msgq_get(&zmk_split_central_split_run_msgq, &payload_wrapper, K_NO_WAIT) == 0) {
if (peripherals[payload_wrapper.source].state != PERIPHERAL_SLOT_STATE_CONNECTED) {
LOG_ERR("Source not connected");
continue;
}
if (!peripherals[payload_wrapper.source].run_behavior_handle) {
LOG_ERR("Run behavior handle not found");
continue;
}
int err = bt_gatt_write_without_response(
peripherals[payload_wrapper.source].conn,
peripherals[payload_wrapper.source].run_behavior_handle, &payload_wrapper.payload,
sizeof(struct zmk_split_run_behavior_payload), true);
if (err) {
LOG_ERR("Failed to write the behavior characteristic (err %d)", err);
}
}
}
K_WORK_DEFINE(split_central_split_run_work, split_central_split_run_callback);
static int
split_bt_invoke_behavior_payload(struct zmk_split_run_behavior_payload_wrapper payload_wrapper) {
LOG_DBG("");
int err = k_msgq_put(&zmk_split_central_split_run_msgq, &payload_wrapper, K_MSEC(100));
if (err) {
switch (err) {
case -EAGAIN: {
LOG_WRN("Consumer message queue full, popping first message and queueing again");
struct zmk_split_run_behavior_payload_wrapper discarded_report;
k_msgq_get(&zmk_split_central_split_run_msgq, &discarded_report, K_NO_WAIT);
return split_bt_invoke_behavior_payload(payload_wrapper);
}
default:
LOG_WRN("Failed to queue behavior to send (%d)", err);
return err;
}
}
k_work_submit_to_queue(&split_central_split_run_q, &split_central_split_run_work);
return 0;
};
int zmk_split_bt_invoke_behavior(uint8_t source, struct zmk_behavior_binding *binding,
struct zmk_behavior_binding_event event, bool state) {
struct zmk_split_run_behavior_payload payload = {.data = {
.param1 = binding->param1,
.param2 = binding->param2,
.position = event.position,
.state = state ? 1 : 0,
}};
const size_t payload_dev_size = sizeof(payload.behavior_dev);
if (strlcpy(payload.behavior_dev, binding->behavior_dev, payload_dev_size) >=
payload_dev_size) {
LOG_ERR("Truncated behavior label %s to %s before invoking peripheral behavior",
binding->behavior_dev, payload.behavior_dev);
}
struct zmk_split_run_behavior_payload_wrapper wrapper = {.source = source, .payload = payload};
return split_bt_invoke_behavior_payload(wrapper);
}
int zmk_split_bt_central_init(const struct device *_arg) {
k_work_queue_start(&split_central_split_run_q, split_central_split_run_q_stack,
K_THREAD_STACK_SIZEOF(split_central_split_run_q_stack),
CONFIG_ZMK_BLE_THREAD_PRIORITY, NULL);
bt_conn_cb_register(&conn_callbacks);
return start_scanning();
}
SYS_INIT(zmk_split_bt_central_init, APPLICATION, CONFIG_ZMK_BLE_INIT_PRIORITY);