-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkeyboard.cpp
More file actions
289 lines (230 loc) · 7.92 KB
/
Copy pathkeyboard.cpp
File metadata and controls
289 lines (230 loc) · 7.92 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
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
#include "keyboard.h"
#include "config.h"
#include "display.h"
#include <BLEAdvertisedDevice.h>
#include <BLEClient.h>
#include <BLEDevice.h>
#include <BLESecurity.h>
#include <BLEUtils.h>
#include <vector>
Keyboard keyboard;
static BLEUUID hidServiceUUID((uint16_t)0x1812);
static BLEUUID reportCharUUID((uint16_t)0x2A4D);
static BLEAdvertisedDevice* keyboardDevice = nullptr;
static BLEClient* bleClient = nullptr;
static bool shouldConnect = false;
static bool shouldScan = false;
static bool connected = false;
static bool scanStarted = false;
static uint8_t previousReport[7] = {};
static std::vector<KeyboardEvent> pendingEvents;
static bool isShiftPressed(uint8_t modifier) {
return (modifier & 0x22) != 0;
}
static bool isCtrlPressed(uint8_t modifier) {
return (modifier & 0x11) != 0;
}
static bool keyWasPressed(uint8_t keycode) {
for (uint8_t i = 1; i < sizeof(previousReport); i++) {
if (previousReport[i] == keycode) {
return true;
}
}
return false;
}
static char keycodeToAscii(uint8_t keycode, bool shifted) {
if (keycode >= 0x04 && keycode <= 0x1D) {
const char base = shifted ? 'A' : 'a';
return base + (keycode - 0x04);
}
if (keycode >= 0x1E && keycode <= 0x27) {
const char normal[] = "1234567890";
const char shiftedChars[] = "!@#$%^&*()";
const uint8_t index = keycode == 0x27 ? 9 : keycode - 0x1E;
return shifted ? shiftedChars[index] : normal[index];
}
switch (keycode) {
case 0x28: return '\n';
case 0x2B: return '\t';
case 0x2C: return ' ';
case 0x2D: return shifted ? '_' : '-';
case 0x2E: return shifted ? '+' : '=';
case 0x2F: return shifted ? '{' : '[';
case 0x30: return shifted ? '}' : ']';
case 0x31: return shifted ? '|' : '\\';
case 0x33: return shifted ? ':' : ';';
case 0x34: return shifted ? '"' : '\'';
case 0x35: return shifted ? '~' : '`';
case 0x36: return shifted ? '<' : ',';
case 0x37: return shifted ? '>' : '.';
case 0x38: return shifted ? '?' : '/';
default: return '\0';
}
}
static void queueKeyboardReport(const uint8_t* data, size_t length) {
if (length < sizeof(previousReport)) {
return;
}
const bool shifted = isShiftPressed(data[0]);
const bool ctrl = isCtrlPressed(data[0]);
for (uint8_t i = 1; i < sizeof(previousReport); i++) {
const uint8_t keycode = data[i];
if (keycode == 0 || keyWasPressed(keycode)) {
continue;
}
KeyboardEvent event = {
keycodeToAscii(keycode, shifted),
keycode,
ctrl,
shifted
};
if (event.character != '\0' || keycode == 0x28 || keycode == 0x29 || keycode == 0x2A || keycode == 0x51 || keycode == 0x52) {
pendingEvents.push_back(event);
}
else {
Serial.print("Unhandled HID keycode: ");
Serial.println(keycode);
}
}
memcpy(previousReport, data, sizeof(previousReport));
}
static void notifyCallback(BLERemoteCharacteristic* characteristic, uint8_t* data, size_t length, bool isNotify) {
(void)characteristic;
(void)isNotify;
queueKeyboardReport(data, length);
}
class KeyboardClientCallbacks : public BLEClientCallbacks {
void onConnect(BLEClient* client) override {
(void)client;
Serial.println("Connected to BLE keyboard.");
}
void onDisconnect(BLEClient* client) override {
(void)client;
connected = false;
Serial.println("Disconnected from BLE keyboard.");
}
};
static bool subscribeToKeyboardReports(BLERemoteService* hidService) {
std::map<std::string, BLERemoteCharacteristic*>* characteristics = hidService->getCharacteristics();
uint8_t subscribedCount = 0;
for (auto const& entry : *characteristics) {
BLERemoteCharacteristic* characteristic = entry.second;
if (!characteristic->getUUID().equals(reportCharUUID) || !characteristic->canNotify()) {
continue;
}
Serial.print("Subscribing to report characteristic handle 0x");
Serial.println(characteristic->getHandle(), HEX);
characteristic->registerForNotify(notifyCallback);
subscribedCount++;
}
if (subscribedCount == 0) {
Serial.println("No notify-capable HID report characteristics found.");
return false;
}
connected = true;
Serial.print("Subscribed to ");
Serial.print(subscribedCount);
Serial.println(" HID input report characteristic(s). Press keys now.");
return true;
}
static bool connectToKeyboard() {
if (keyboardDevice == nullptr) {
return false;
}
Serial.print("Connecting to ");
Serial.print(keyboardDevice->getName().c_str());
Serial.print(" at ");
Serial.println(keyboardDevice->getAddress().toString().c_str());
bleClient = BLEDevice::createClient();
bleClient->setClientCallbacks(new KeyboardClientCallbacks());
if (!bleClient->connect(keyboardDevice)) {
Serial.println("BLE keyboard connect failed.");
return false;
}
bleClient->setMTU(185);
BLERemoteService* hidService = bleClient->getService(hidServiceUUID);
if (hidService == nullptr) {
Serial.println("Connected, but HID service was not found.");
bleClient->disconnect();
return false;
}
Serial.println("Found HID service.");
if (!subscribeToKeyboardReports(hidService)) {
bleClient->disconnect();
return false;
}
return true;
}
class BleKeyboardScanCallbacks : public BLEAdvertisedDeviceCallbacks {
void onResult(BLEAdvertisedDevice device) override {
const bool advertisesHid = device.haveServiceUUID() && device.isAdvertisingService(hidServiceUUID);
if (!advertisesHid) {
return;
}
Serial.print("BLE HID keyboard candidate: ");
if (device.haveName()) {
Serial.print(device.getName().c_str());
}
else {
Serial.print("(no name)");
}
Serial.print(" address=");
Serial.println(device.getAddress().toString().c_str());
BLEDevice::getScan()->stop();
keyboardDevice = new BLEAdvertisedDevice(device);
shouldConnect = true;
}
};
static void startKeyboardScan() {
Serial.println("Scanning for BLE keyboard. Put keyboard into pairing mode.");
BLEScan* scan = BLEDevice::getScan();
scan->setAdvertisedDeviceCallbacks(new BleKeyboardScanCallbacks(), true);
scan->setActiveScan(true);
scan->setInterval(100);
scan->setWindow(99);
scan->start(KEYBOARD_SCAN_SECONDS, false);
scanStarted = true;
}
bool Keyboard::begin() {
Serial.println("Starting BLE keyboard input...");
BLEDevice::init("ESP32-Typewriter");
BLESecurity* security = new BLESecurity();
security->setCapability(ESP_IO_CAP_NONE);
security->setAuthenticationMode(true, false, true);
BLEDevice::setSecurityCallbacks(new BLESecurityCallbacks());
shouldScan = true;
return true;
}
void Keyboard::update() {
if (shouldScan) {
shouldScan = false;
startKeyboardScan();
}
if (shouldConnect) {
shouldConnect = false;
if (!connectToKeyboard()) {
Serial.println("Connection failed. Restart the board to scan again.");
}
}
if (!connected && scanStarted && !shouldConnect) {
scanStarted = false;
Serial.println("BLE scan finished. Restart the board to scan again.");
display.printText(
TEXT_LEFT,
TEXT_TOP,
"Keyboard not found.\n\nRestart the board to scan again.",
TEXT_SIZE
);
}
}
bool Keyboard::isConnected() const {
return connected;
}
bool Keyboard::readEvent(KeyboardEvent& event) {
if (pendingEvents.empty()) {
return false;
}
event = pendingEvents.front();
pendingEvents.erase(pendingEvents.begin());
return true;
}