-
Notifications
You must be signed in to change notification settings - Fork 11
/
accessory.py
220 lines (171 loc) · 5.64 KB
/
accessory.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
#!/usr/bin/python
# accessory.py
# License GPLv2
# (c) Manuel Di Cerbo, Nexus-Computing GmbH
import usb.core
import usb.util
import fcntl
import struct
import time
import threading
import os
import sys
import socket
from attribs import *
ACCESSORY_VID = 0x18D1
ACCESSORY_PID = (0x2D00, 0x2D01, 0x2D04, 0x2D05)
NETLINK_KOBJECT_UEVENT = 15
def main():
if len(sys.argv) >= 2:
parts = sys.argv[1].split('/')
accessory_task(int(parts[0],16))
return
while True:
print("no arguments given, starting in daemon mode")
try:
sock = socket.socket(
socket.AF_NETLINK,
socket.SOCK_RAW,
NETLINK_KOBJECT_UEVENT
)
sock.bind((os.getpid(), -1))
vid = 0
while True:
data = sock.recv(512)
try:
vid = parse_uevent(data)
if vid != None:
break
except ValueError:
print("unable to parse uevent")
sock.close()
accessory_task(vid)
except ValueError as e:
print(e)
print("accessory task finished")
def parse_uevent(data):
lines = data.split('\0')
keys = []
for line in lines:
val = line.split('=')
if len(val) == 2:
keys.append((val[0], val[1]))
attributes = dict(keys)
if 'ACTION' in attributes and 'PRODUCT' in attributes:
if attributes['ACTION'] == 'add':
parts = attributes['PRODUCT'].split('/')
return int(parts[0], 16)
return None
def accessory_task(vid):
dev = usb.core.find(idVendor=vid)
if dev is None:
raise ValueError("No compatible device not found")
print("compatible device found")
if dev.idProduct in ACCESSORY_PID:
print("device is in accessory mode")
else:
print("device is not in accessory mode yet, VID %04X" % vid)
accessory(dev)
dev = usb.core.find(idVendor=ACCESSORY_VID)
if dev is None:
raise ValueError("No compatible device not found")
if dev.idProduct in ACCESSORY_PID:
print("device is in accessory mode")
else:
raise ValueError("")
tries = 5
while True:
try:
if tries <= 0:
break
dev.set_configuration()
break
except:
print("unable to set configuration, retrying")
tries -= 1
time.sleep(1)
# even if the Android device is already in accessory mode
# setting the configuration will result in the
# UsbManager starting an "accessory connected" intent
# and hence a small delay is required before communication
# works properly
time.sleep(1)
dev = usb.core.find(idVendor = ACCESSORY_VID);
if dev is None:
dev = usb.core.find(idVendor = vid);
if dev is None:
raise ValueError("device set to accessory mode but VID %04X not found" % vid)
cfg = dev.get_active_configuration()
if_num = cfg[(0,0)].bInterfaceNumber
intf = usb.util.find_descriptor(cfg, bInterfaceNumber = if_num)
ep_out = usb.util.find_descriptor(
intf,
custom_match = \
lambda e: \
usb.util.endpoint_direction(e.bEndpointAddress) == \
usb.util.ENDPOINT_OUT
)
ep_in = usb.util.find_descriptor(
intf,
custom_match = \
lambda e: \
usb.util.endpoint_direction(e.bEndpointAddress) == \
usb.util.ENDPOINT_IN
)
writer_thread = threading.Thread(target = writer, args = (ep_out, ))
writer_thread.start()
length = -1
while True:
try:
data = ep_in.read(size = 1, timeout = 0)
print("read value %d" % data[0])
except usb.core.USBError as e:
print("failed to send IN transfer")
print(e)
break
writer_thread.join()
print("exiting application")
def writer (ep_out):
while True:
try:
length = ep_out.write([0], timeout = 0)
print("%d bytes written" % length)
time.sleep(0.5)
except usb.core.USBError:
print("error in writer thread")
break
def accessory(dev):
version = dev.ctrl_transfer(
usb.util.CTRL_TYPE_VENDOR | usb.util.CTRL_IN,
51, 0, 0, 2)
print("version is: %d" % struct.unpack('<H',version))
assert dev.ctrl_transfer(
usb.util.CTRL_TYPE_VENDOR | usb.util.CTRL_OUT,
52, 0, 0, MANUFACTURER) == len(MANUFACTURER)
assert dev.ctrl_transfer(
usb.util.CTRL_TYPE_VENDOR | usb.util.CTRL_OUT,
52, 0, 1, MODEL_NAME) == len(MODEL_NAME)
assert dev.ctrl_transfer(
usb.util.CTRL_TYPE_VENDOR | usb.util.CTRL_OUT,
52, 0, 2, DESCRIPTION) == len(DESCRIPTION)
assert dev.ctrl_transfer(
usb.util.CTRL_TYPE_VENDOR | usb.util.CTRL_OUT,
52, 0, 3, VERSION) == len(VERSION)
assert dev.ctrl_transfer(
usb.util.CTRL_TYPE_VENDOR | usb.util.CTRL_OUT,
52, 0, 4, URL) == len(URL)
assert dev.ctrl_transfer(
usb.util.CTRL_TYPE_VENDOR | usb.util.CTRL_OUT,
52, 0, 5, SERIAL_NUMBER) == len(SERIAL_NUMBER)
dev.ctrl_transfer(
usb.util.CTRL_TYPE_VENDOR | usb.util.CTRL_OUT,
53, 0, 0, None)
time.sleep(1)
if __name__ == "__main__":
pid_file = '/root/program.pid'
fp = open(pid_file, 'w')
try:
fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
sys.exit(0)
main()