-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtry.py
191 lines (158 loc) · 5.16 KB
/
try.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
from __future__ import print_function
import hid
from time import sleep
import random
import threading
import typing
from typing import Callable, Any
from dataclasses import dataclass
import os
@dataclass
class HidIntf:
h: hid.device
kill_thread = False
read_bytecount = 0
write_bytecount = 0
@classmethod
def print_hexified_buffer(cls, buffer: list[int]):
bufsize = len(buffer)
hexified = ' '.join([f"{x:02x}" for x in buffer])
print(f"len={bufsize: 3d}:\n{hexified}")
def clear_bytecount(self):
self.read_bytecount = 0
self.write_bytecount = 0
def print_bytecount(self):
print(f"Total Write Byte Count = {self.write_bytecount}")
print(f"Total Read Byte Count = {self.read_bytecount}")
def read_and_print(self) -> None:
buf = self.h.read(64)
self.print_hexified_buffer(buf)
def loop_write(
self,
count: int = 1,
byte_count: int = 64,
write_interval: float = 0.00,
generator: Any = None,
write_padding: bool = True,
verbose: bool = True,
) -> None:
for _ in range(count):
match generator:
case bytes() | bytearray():
words = list(generator)
case list():
words = generator
case _:
if isinstance(generator, Callable):
words = generator(byte_count)
else:
# words = [random.randint(0, 255) for _ in range(byte_count)]
words = [x % 256 for x in range(byte_count)]
# Pad with zeros if words are not multiple of 64 bytes
if write_padding:
words_len = len(words)
remainder = words_len % 64
padding_count = 64 - remainder if remainder else 0
words += [0] * padding_count
# FIRST BYTE IS ZERO work-around to accommodate hidapi's hid_write()
# Prepend a zero byte if words[0]==0
new_words = [0] + words if words[0] == 0 else [] + words
if verbose:
print(f"WR:", end=" ")
self.print_hexified_buffer(new_words)
self.h.write(new_words)
self.write_bytecount += len(new_words)
if write_interval > 0.0:
sleep(write_interval)
def loop_read(self, timeout_ms: int = 0, verbose: bool = True) -> None:
while not self.kill_thread:
buffer = self.h.read(64, timeout_ms=timeout_ms)
running_count = len(buffer)
if running_count > 1:
if verbose:
print(f"RD:", end=" ")
self.print_hexified_buffer(buffer)
self.read_bytecount += running_count
def loop_write_read(
self,
count: int = 1,
byte_count: int = 64,
write_interval: float = 0.100,
read_timeout_ms: int = 0,
generator: Any | None = None,
write_padding: bool = True,
verbose: bool = True,
) -> None:
self.kill_thread = False
thread_read = threading.Thread(
target=self.loop_read,
args=(
read_timeout_ms,
verbose,
),
)
thread_write = threading.Thread(
target=self.loop_write,
args=(
count,
byte_count,
write_interval,
generator,
write_padding,
verbose,
),
)
thread_read.start()
sleep(0.1)
thread_write.start()
# Wait until thread is completly executed
thread_write.join()
sleep(0.1)
self.kill_thread = True
self.print_bytecount()
# enumerate USB devices
# for d in hid.enumerate():
# keys = list(d.keys())
# keys.sort()
# for key in keys:
# print("%s : %s" % (key, d[key]))
# print()
# try opening a device, then perform write and read
try:
print("Opening the device")
h = hid.device()
h.open(
vendor_id=0xCAFE,
product_id=0x4004,
serial_number=os.getenv('SERIAL') or "DE623134CF856234",
)
# h.open(0xCAFE, 0x4004) # VendorID/ProductID
print("Manufacturer: %s" % h.get_manufacturer_string())
print("Product: %s" % h.get_product_string())
print("Serial No: %s" % h.get_serial_number_string())
# enable non-blocking mode
h.set_nonblocking(1)
# # write some data to the device
# print("Write the data")
# h.write([0, 63, 35, 35] + [0] * 61)
# wait
sleep(0.05)
# Interface to HID
hif = HidIntf(h)
# # read back the answer
# print("Read the data")
# while True:
# d = h.read(64)
# if d:
# print(d)
# else:
# break
# __import__('pdb').set_trace()
# print("Closing the device")
# h.close()
except IOError as ex:
print(ex)
print("You probably don't have the hard-coded device.")
print("Update the h.open() line in this script with the one")
print("from the enumeration list output above and try again.")
print("Done")