-
Notifications
You must be signed in to change notification settings - Fork 11
/
bluetooth_2_hid.py
executable file
·245 lines (207 loc) · 10.1 KB
/
bluetooth_2_hid.py
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
#!/usr/bin/env python
"""
Author: @PixelGordo
Date: 2021-12-15
Version: 0.2
References: https://www.isticktoit.net/?p=1383
https://github.com/mikerr/pihidproxy
========================================================================================================================
Script that reads the inputs of one keyboard (typically you would like to read a bluetooth keyboard) and translates them
to HID proxy commands through the USB cable. This way you can have the connections below:
Keyboard --(bluetooth)--> Raspberry Pi Zero W --(usb)--> Computer
The final result is the computer (on the right) receives inputs as if they were coming from an USB keyboard. The
advantages of this technique are:
- You can use your bluetooth keyboard on any device that has USB connection, no bluetooth drivers or software is
required.
- You can use your bluetooth keyboard in the BIOS or GRUB menu.
- You can use any bluetooth keyboard, even when they require a pairing password. You must do the pairing between
the Raspberry Pi and the bluetooth using that password but after that, you don't need to repeat the process, the
raspberry pi and the keyboard will remain paired even when you connect the Raspberry Pi to a different computer
(similar to what happens with the typical USB dongles that come with Logitech mouses).
- ...not implemented, but you could create your own macros in this script that would work in any computer you plug
the keyboard+raspberry. I'm thinking about Ctr-Shift-L to automatically send the keys of Lorem Ipsum...
"""
import argparse
import os
import sys
import time
import atexit
import evdev
from libs import hid_codes
from libs import keyboard
# READ THIS: https://www.isticktoit.net/?p=1383
# Constants
#=======================================================================================================================
u_INPUT_DEV = u'/dev/input/event0' # In the Raspberry Pi Zero (apparently)
u_OUTPUT_DEV = u'/dev/hidg0'
u_LOG_FILE = u'/tmp/blu2hid.log'
# Helper Functions
#=======================================================================================================================
def _get_cmd_args():
"""
Function to get command line arguments.
:return:
"""
# [1/?] Defining the parser
#--------------------------
o_parser = argparse.ArgumentParser()
o_parser.add_argument('-i',
action='store',
default=u_INPUT_DEV,
help='Input device (Bluetooth Keyboard). By default it\'s "/dev/input/event0"')
o_parser.add_argument('-o',
action='store',
default=u_OUTPUT_DEV,
help='Output device (HID controller). By default it\'s "/dev/hidg0"')
o_parser.add_argument('-d',
action='store_true',
default=False,
help='Debug mode ON. It\'ll print on screen information about the input keys detected and the'
'output HID command sent')
o_parser.add_argument('-t',
action='store_true',
default=False,
help='Test mode ON. The program will read the inputs normally but it won\'t generate the'
'output HID commands. This mode is useful to check that everything is working fine apart'
'from the actual HID command delivery')
o_parser.add_argument('-l',
action='store_true',
default=False,
help='Log mode ON. The program will write a log file "/tmp/bluetooth2hid.log" containing any'
'unknown input key')
o_parsed_data = o_parser.parse_args()
# [2/?] Validation of the command line arguments
#-----------------------------------------------
# I validate the options first because depending on their values, we can relax the requirements on the output
b_mode_debug = o_parsed_data.d
b_mode_test = o_parsed_data.t
b_mode_log = o_parsed_data.l
print('[ pass ] Debug mode: %s' % b_mode_debug)
print('[ pass ] Test mode: %s' % b_mode_test)
print('[ pass ] Log mode: %s (%s)' % (b_mode_log, u_LOG_FILE))
# Input device
#-------------
# I'm not sure about this validation because I don't know what happens when you first connect the Bluetooth without
# any activity on the keyboard. If the keyboard doesn't activate, this validation will fail. Anyway, once the
# program is running, the main loop is able to keep trying the connection if it's not found.
u_input = str(o_parsed_data.i)
#if not (os.access(u_input, os.F_OK) and os.access(u_input, os.R_OK)):
# print('[ FAIL ] Input device: %s (can\'t be read or is not found)' % u_input)
# sys.exit()
#else:
# print('[ pass ] Input device: %s' % u_input)
print('[ pass ] Input device: %s' % u_input)
# Output device
#--------------
u_output = str(o_parsed_data.o)
#if not (os.access(u_input, os.F_OK) and os.access(u_input, os.W_OK)):
# if b_mode_test:
# print('[ INFO ] Output device: %s (can\'t be read or is not found)' % u_output)
# else:
# print('[ FAIL ] Output device: %s (can\'t be read or is not found)' % u_output)
# sys.exit()
#else:
# print('[ pass ] Output device: %s' % u_output)
print('[ pass ] Output device: %s' % u_output)
return {'u_input': u_input,
'u_output': u_output,
'b_mode_debug': b_mode_debug,
'b_mode_test': b_mode_test,
'b_mode_log': b_mode_log}
def _get_input_device(pu_device):
"""
Function to get the device object.
:param pu_device:
:return: The device object.
"""
o_device = None
while o_device is None:
try:
o_device = evdev.InputDevice(pu_device)
except OSError:
print('[ WAIT ] Opening Bluetooth input (%s)...' % u_INPUT_DEV)
time.sleep(3)
print('[ pass ] Bluetooth input open (%s)' % str(pu_device))
return o_device
def _get_output_device(pu_device):
"""
Function to get the output object.
:param pu_device:
:return: The device object.
"""
o_device = None
while o_device is None:
try:
o_device = open(pu_device, 'wb+', buffering=0)
except OSError:
print('[ WAIT ] Opening HID output (%s)...' % u_OUTPUT_DEV)
time.sleep(3)
print('[ pass ] HID output open (%s)' % str(pu_device))
return o_device
def _get_devices(pu_input, pu_output, po_input, po_output):
"""
Function to get both devices, input and output.
:param pu_input:
:param pu_output:
:return:
"""
pass
def _grab_device(device):
device.grab()
def _ungrab_device(device):
device.ungrab()
# Main Code
#=======================================================================================================================
if __name__ == '__main__':
print('Bluetooth to HID events translator v0.1 2019-01-29')
print('==================================================')
o_args = _get_cmd_args()
# Initialization
#---------------
is_debug_enabled = bool(o_args['b_mode_debug'])
is_test_mode_enabled = bool(o_args['b_mode_test'])
o_hid_keyboard = keyboard.HidKeyboard()
o_input_device = _get_input_device(o_args['u_input'])
_grab_device(o_input_device)
atexit.register(_ungrab_device, device = o_input_device)
o_output_device = _get_output_device(o_args['u_output'])
# Main loop
#----------
while True:
try:
for o_event in o_input_device.read_loop():
if o_event.type == evdev.ecodes.EV_KEY:
# Pre-parsing the event so it's easier to work with it for our purposes
o_data = evdev.categorize(o_event)
# [1/?] Getting the HID byte for the modifier keys
#-------------------------------------------------
# The modifier status will only change when they are pressed (1) or released (0) (not when they are
# hold)
if (o_data.keystate in (0, 1)) and (o_data.keycode in hid_codes.ds_MOD_CODES):
o_hid_keyboard.modifier_set(o_data.keycode, o_data.keystate)
# [2/?] Activating or deactivating keys in our HidKeyboard when needed
#---------------------------------------------------------------------
# We only send hid commands when there is a change, so with key-down (1) and key-up (0) events
if o_data.keystate == 0:
o_hid_keyboard.deactivate_key(o_data.keycode)
elif o_data.keystate == 1:
o_hid_keyboard.activate_key(o_data.keycode)
# [3/?] When any change occurs, we need to send the HID command
#--------------------------------------------------------------
if o_data.keystate in (0, 1):
if is_debug_enabled:
print(o_hid_keyboard.to_debug_command())
if not is_test_mode_enabled:
s_hid_command = o_hid_keyboard.to_hid_command()
try:
o_output_device.write(s_hid_command.encode('utf-8'))
except IOError:
print('--------------------------------------------------')
_get_output_device(o_args['u_output'])
print('--------------------------------------------------')
o_output_device.write(s_hid_command.encode('utf-8'))
# The o_input_device cannot be read
except IOError:
print('--------------------------------------------------')
o_input_device = _get_input_device(o_args['u_input'])
print('--------------------------------------------------')