-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.py
More file actions
202 lines (174 loc) · 7.45 KB
/
Copy pathcode.py
File metadata and controls
202 lines (174 loc) · 7.45 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
import struct
import time
import board
import digitalio
import _bleio
import alarm
NAME = "Simple Switch"
HOLD_SLEEP_MS = 3000 # hold any switch this long -> deep sleep
# Each switch: wired between its pin and GND. Internal pull-up is enabled,
# so no external resistors. Active-low (idle HIGH, pressed LOW).
# HID keycodes: 0x2C Space, 0x28 Enter, 0x2B Tab, 0x29 Esc, 0x2A Backspace,
# 0x4F Right, 0x50 Left, 0x51 Down, 0x52 Up, 0x04-0x1D a-z, 0x1E-0x27 1-9,0
SWITCHES = [
{"pin": board.D10, "keycode": 0x2C}, # switch 1 -> Space
{"pin": board.D9, "keycode": 0x28}, # switch 2 -> Enter
]
# Standard HID keyboard report descriptor (Report ID 1).
HID_DESCRIPTOR = bytes([
0x05, 0x01, # Usage Page (Generic Desktop)
0x09, 0x06, # Usage (Keyboard)
0xA1, 0x01, # Collection (Application)
0x85, 0x01, # Report ID (1)
0x05, 0x07, # Usage Page (Keyboard/Keypad)
0x19, 0xE0, # Usage Minimum (0xE0)
0x29, 0xE7, # Usage Maximum (0xE7)
0x15, 0x00, # Logical Minimum (0)
0x25, 0x01, # Logical Maximum (1)
0x75, 0x01, # Report Size (1)
0x95, 0x08, # Report Count (8) -> modifier byte
0x81, 0x02, # Input (Data,Var,Abs)
0x81, 0x01, # Input (Const) -> reserved byte
0x19, 0x00, # Usage Minimum (0)
0x29, 0x89, # Usage Maximum (0x89)
0x15, 0x00, # Logical Minimum (0)
0x25, 0x89, # Logical Maximum (137)
0x75, 0x08, # Report Size (8)
0x95, 0x06, # Report Count (6) -> key array
0x81, 0x00, # Input (Data,Array)
0x05, 0x08, # Usage Page (LEDs)
0x19, 0x01, # Usage Minimum (Num Lock)
0x29, 0x05, # Usage Maximum (Kana)
0x15, 0x00, # Logical Minimum (0)
0x25, 0x01, # Logical Maximum (1)
0x75, 0x01, # Report Size (1)
0x95, 0x05, # Report Count (5)
0x91, 0x02, # Output (Data,Var,Abs) -> LEDs
0x95, 0x03, # Report Count (3)
0x91, 0x01, # Output (Const) -> pad
0xC0, # End Collection
])
C = _bleio.Characteristic
A = _bleio.Attribute
# ---- Build the HID-over-GATT service (UUID 0x1812) ----
hid = _bleio.Service(_bleio.UUID(0x1812))
C.add_to_service(hid, _bleio.UUID(0x2A4B),
properties=C.READ, read_perm=A.ENCRYPT_NO_MITM, write_perm=A.NO_ACCESS,
max_length=len(HID_DESCRIPTOR), fixed_length=True, initial_value=HID_DESCRIPTOR)
C.add_to_service(hid, _bleio.UUID(0x2A4A),
properties=C.READ, read_perm=A.ENCRYPT_NO_MITM, write_perm=A.NO_ACCESS,
max_length=4, fixed_length=True, initial_value=b"\x01\x01\x00\x02")
C.add_to_service(hid, _bleio.UUID(0x2A4E),
properties=C.READ | C.WRITE_NO_RESPONSE,
read_perm=A.OPEN, write_perm=A.OPEN,
max_length=1, fixed_length=True, initial_value=b"\x01")
C.add_to_service(hid, _bleio.UUID(0x2A4C),
properties=C.WRITE_NO_RESPONSE,
read_perm=A.NO_ACCESS, write_perm=A.ENCRYPT_NO_MITM,
max_length=1, fixed_length=True, initial_value=b"\x00")
boot_in = C.add_to_service(hid, _bleio.UUID(0x2A22),
properties=C.READ | C.NOTIFY, read_perm=A.ENCRYPT_NO_MITM, write_perm=A.NO_ACCESS,
max_length=8, fixed_length=True, initial_value=b"\x00" * 8)
report = C.add_to_service(hid, _bleio.UUID(0x2A4D),
properties=C.READ | C.NOTIFY, read_perm=A.ENCRYPT_NO_MITM, write_perm=A.NO_ACCESS,
max_length=8, fixed_length=True, initial_value=b"\x00" * 8)
_bleio.Descriptor.add_to_characteristic(report, _bleio.UUID(0x2908),
read_perm=A.ENCRYPT_NO_MITM, write_perm=A.NO_ACCESS,
initial_value=struct.pack("<BB", 1, 1))
def build_advertising():
name_b = NAME.encode("ascii")
adv = bytes([
0x02, 0x01, 0x06, # Flags: LE General Disc, BR/EDR not supported
0x03, 0x02, 0x12, 0x18, # Complete 16-bit service UUIDs: 0x1812 (HID)
0x03, 0x19, 0xC1, 0x03, # Appearance: 0x03C1 = HID Keyboard
])
adv += bytes([len(name_b) + 1, 0x09]) + name_b
return adv
adapter = _bleio.adapter
adapter.name = NAME
adv_data = build_advertising()
# Set up the switches
for s in SWITCHES:
d = digitalio.DigitalInOut(s["pin"])
d.direction = digitalio.Direction.INPUT
d.pull = digitalio.Pull.UP
s["dio"] = d
s["pressed"] = False
s["press_start"] = 0
led = digitalio.DigitalInOut(board.RED_LED)
led.direction = digitalio.Direction.OUTPUT
# XIAO nRF52840 user LED is active-low: write False to light it.
LED_ACTIVE_LOW = True
def led_set(on):
led.value = (not on) if LED_ACTIVE_LOW else on
def blink(times, on=0.08, off=0.08):
for _ in range(times):
led_set(True); time.sleep(on)
led_set(False); time.sleep(off)
# Currently held keycodes (supports simultaneous presses / chords).
active_keys = set()
def update_report():
keys = sorted(active_keys)[:6]
rep = bytes([0, 0] + keys + [0] * (6 - len(keys)))
report.value = rep
boot_in.value = rep
def go_to_sleep():
print("going to sleep...")
active_keys.clear()
update_report()
try:
adapter.stop_advertising()
for conn in adapter.connections:
try: conn.disconnect()
except Exception: pass
except Exception: pass
blink(6)
led_set(False)
# Wait until every switch is released, then release the pins so the
# level-wake alarms can claim them.
while any(not s["dio"].value for s in SWITCHES):
time.sleep(0.05)
for s in SWITCHES:
s["dio"].deinit()
alarms = [alarm.pin.PinAlarm(pin=s["pin"], value=False, edge=False, pull=True)
for s in SWITCHES]
print("asleep. Press any switch to wake.")
alarm.exit_and_deep_sleep_until_alarms(*alarms)
print(NAME, "starting. Switches:", [(str(s["pin"]), hex(s["keycode"])) for s in SWITCHES])
adapter.start_advertising(adv_data, connectable=True, interval=0.1)
blink(2)
print("Advertising as", NAME, "- tap=key, hold %ds=sleep" % (HOLD_SLEEP_MS // 1000))
sleep_armed = False
while True:
now = time.monotonic()
any_pressed = False
for s in SWITCHES:
is_pressed = not s["dio"].value
if is_pressed:
any_pressed = True
if is_pressed and not s["pressed"]:
s["pressed"] = True
s["press_start"] = now
led_set(True)
if adapter.connected:
active_keys.add(s["keycode"])
update_report()
print("PRESSED", str(s["pin"]), "-> key", hex(s["keycode"]))
else:
print("PRESSED", str(s["pin"]), "(not connected -> no key)")
if s["pressed"] and is_pressed and not sleep_armed:
if (now - s["press_start"]) * 1000 >= HOLD_SLEEP_MS:
sleep_armed = True
print("held %.1fs -> sleep" % (now - s["press_start"]))
go_to_sleep()
if not is_pressed and s["pressed"]:
s["pressed"] = False
if adapter.connected and not sleep_armed:
active_keys.discard(s["keycode"])
update_report()
print("released", str(s["pin"]))
if not any_pressed:
led_set(False)
if not adapter.connected and not adapter.advertising:
adapter.start_advertising(adv_data, connectable=True, interval=0.1)
time.sleep(0.01)