forked from sickcodes/python3-baudrate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
baudrate.py
executable file
·380 lines (317 loc) · 11.5 KB
/
baudrate.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
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
#!/usr/bin/env python3
# License: MIT
# Authors:
# Craig Heffner @devttys0 https://github.com/devttys0
# @Loris1123 https://github.com/Loris1123
# Sick.Codes @sickcodes https://github.com/sickcodes
# Usage:
# pip install -r requirements.txt
# sudo python baudrate.py /dev/ttyUSB0
import sys
import time
import serial
from threading import Thread
import tty
import termios
import subprocess
from getopt import getopt as GetOpt, GetoptError
import getch
class RawInput:
"""Gets a single character from standard input. Does not echo to the screen."""
def __init__(self):
try:
self.impl = RawInputWindows()
except ImportError:
self.impl = RawInputUnix()
def __call__(self): return self.impl()
class RawInputUnix:
def __call__(self):
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
class RawInputWindows:
def __call__(self):
return getch.getch()
class Baudrate:
VERSION = '3.0'
READ_TIMEOUT = 5
BAUDRATES = [
"110",
"300",
"600",
"1200",
"1800",
"2400",
"3600",
"4800",
"7200",
"9600",
"14400",
"19200",
"28800",
"31250",
"38400",
"57600",
"76800",
"115200",
"128000",
"153600",
"230400",
"250000",
"256000",
"307200",
"345600",
"460800",
"500000",
"512000",
"921600",
"1024000",
"2000000",
"2500000",
"3000000",
"3686400",
]
UPKEYS = ['u', 'U', 'A']
DOWNKEYS = ['d', 'D', 'B']
MIN_CHAR_COUNT = 25
WHITESPACE = [' ', '\t', '\r', '\n']
PUNCTUATION = ['.', ',', ':', ';', '?', '!']
VOWELS = ['a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U']
def __init__(self, port=None, threshold=MIN_CHAR_COUNT, timeout=READ_TIMEOUT, name=None, auto=True, verbose=False):
self.port = port
self.threshold = threshold
self.timeout = timeout
self.name = name
self.auto_detect = auto
self.verbose = verbose
self.index = 0
self.valid_characters = []
self.ctlc = False
self.thread = None
self.startbaudrate = len(self.BAUDRATES) - 1
self.endbaudate = self.index
self._gen_char_list()
def _gen_char_list(self):
c = ' '
while c <= '~':
self.valid_characters.append(c)
c = chr(ord(c) + 1)
for c in self.WHITESPACE:
if c not in self.valid_characters:
self.valid_characters.append(c)
def _print(self, data):
if self.verbose:
sys.stderr.buffer.write(data)
sys.stderr.buffer.flush()
def Open(self, startbaudrate, endbaudrate):
pass
self.startbaudrate = startbaudrate
self.endbaudrate = endbaudrate
self.serial = serial.Serial(self.port, timeout=self.timeout)
self.index = startbaudrate
self.NextBaudrate(0)
def NextBaudrate(self, updn):
self.index -= updn
if self.index < self.endbaudrate:
self.index = self.startbaudrate
elif self.index > self.startbaudrate:
self.index = endbaudrate
sys.stderr.write('\n\n@@@@@@@@@@@@@@@@@@@@@ Baudrate: %s @@@@@@@@@@@@@@@@@@@@@\n\n' % self.BAUDRATES[self.index])
self.serial.flush()
self.serial.baudrate = self.BAUDRATES[self.index]
self.serial.flush()
def Detect(self):
count = 0
whitespace = 0
punctuation = 0
vowels = 0
start_time = 0
timed_out = False
clear_counters = False
if not self.auto_detect:
self.thread = Thread(None, self.HandleKeypress, None, (self, 1))
self.thread.start()
while True:
if start_time == 0:
start_time = time.time()
byte = self.serial.read(1)
if byte:
if self.auto_detect and byte in self.valid_characters:
if byte in self.WHITESPACE:
whitespace += 1
elif byte in self.PUNCTUATION:
punctuation += 1
elif byte in self.VOWELS:
vowels += 1
count += 1
else:
clear_counters = True
self._print(byte)
if count >= self.threshold and whitespace > 0 and punctuation > 0 and vowels > 0:
break
elif (time.time() - start_time) >= self.timeout:
timed_out = True
else:
timed_out = True
if timed_out and self.auto_detect:
start_time = 0
self.NextBaudrate(1)
clear_counters = True
timed_out = False
if clear_counters:
whitespace = 0
punctuation = 0
vowels = 0
count = 0
clear_counters = False
if self.ctlc:
break
return self.BAUDRATES[self.index]
def HandleKeypress(self, *args):
userinput = RawInput()
while not self.ctlc:
c = userinput()
if c in self.UPKEYS:
self.NextBaudrate(1)
elif c in self.DOWNKEYS:
self.NextBaudrate(-1)
elif c == '\x03':
self.ctlc = True
def MinicomConfig(self, name=None):
success = True
if name is None:
name = self.name
config = "########################################################################\n"
config += "# Minicom configuration file - use \"minicom -s\" to change parameters.\n"
config += "pu port %s\n" % self.port
config += "pu baudrate %s\n" % self.BAUDRATES[self.index]
config += "pu bits 8\n"
config += "pu parity N\n"
config += "pu stopbits 1\n"
config += "pu rtscts No\n"
config += "########################################################################\n"
if name is not None and name:
try:
open("/etc/minicom/minirc.%s" % name, "w").write(config)
except Exception as e:
print("Error saving minicom config file:", str(e))
success = False
return (success, config)
def Close(self):
self.ctlc = True
self.serial.close()
if __name__ == '__main__':
def usageStartEnd(start, end):
print("ATENTION:")
print("Start baudrate ({start}) must be greater than end baudratei ({end}).".format(start=start, end=end))
print("Starting the tests from the lowest baudrate will generate false positives, so the test is always successful starting from the highest to the lowest.")
def usage():
baud = Baudrate()
print("Baudrate v%s" % baud.VERSION)
print("Craig Heffner, http://www.devttys0.com")
print("@Loris1123, https://github.com/Loris1123")
print("Sick.Codes, https://sick.codes")
print("")
print("Usage: %s [OPTIONS]" % sys.argv[0])
print("")
print("\t-p <serial port> Specify the serial port to use [/dev/ttyUSB0]")
print("\t-t <seconds> Set the timeout period used when switching baudrates in auto detect mode [%d]" % baud.READ_TIMEOUT)
print("\t-c <num> Set the minimum ASCII character threshold used during auto detect mode [%d]" % baud.MIN_CHAR_COUNT)
print("\t-n <name> Save the resulting serial configuration as <name> and automatically invoke minicom (implies -a)")
print("\t-a Enable auto detect mode")
print("\t-b Display supported baud rates and exit")
print("\t-q Do not display data read from the serial port")
print("\t-h Display help")
print("")
sys.exit(1)
def main():
display = False
verbose = True
auto = False
run = False
threshold = 25
timeout = 1
name = None
port = '/dev/ttyUSB0'
startbaudrate = len(Baudrate.BAUDRATES) - 1
endbaudrate = 0
try:
(opts, args) = GetOpt(sys.argv[1:], 'e:s:p:t:c:n:abqh')
except GetoptError as e:
print(e)
usage()
for opt, arg in opts:
if opt == '-t':
timeout = int(arg)
elif opt == '-c':
threshold = int(arg)
elif opt == '-p':
port = arg
elif opt == '-n':
name = arg
auto = True
run = True
elif opt == '-a':
auto = True
elif opt == '-b':
display = True
elif opt == '-q':
verbose = False
elif opt == '-e': # value of end baudrate
endbaudrate = Baudrate.BAUDRATES.index(arg)
elif opt == '-s': # value of start baudrate
startbaudrate = Baudrate.BAUDRATES.index(arg)
else:
usage()
if startbaudrate < endbaudrate:
usageStartEnd(start=Baudrate.BAUDRATES[startbaudrate], end=Baudrate.BAUDRATES[endbaudrate])
usage()
baud = Baudrate(port, threshold=threshold, timeout=timeout, name=name, verbose=verbose, auto=auto)
if display:
print("")
for rate in baud.BAUDRATES:
print("\t{}".format(rate))
print("")
else:
print("")
print("Starting baudrate detection on %s, turn on your serial device now." % port)
print("Using baudrate:")
print("\tFrom %s"% Baudrate.BAUDRATES[startbaudrate])
print("\tto %s"% Baudrate.BAUDRATES[endbaudrate])
print("Press Up/Down to switch baudrates.")
print("Press Ctl+C to quit.")
print("\nPress 'Enter' to start! ", end=" ")
sys.stdin.readline().strip()
print("")
baud.Open(startbaudrate=startbaudrate, endbaudrate=endbaudrate)
try:
rate = baud.Detect()
print("\nDetected baudrate: {}".format(rate))
if name is None:
print("\nSave minicom configuration as: ", end=" ")
name = sys.stdin.readline().strip()
print("")
(ok, config) = baud.MinicomConfig(name)
if name and name is not None:
if ok:
if not run:
print("Configuration saved. Run minicom now [n/Y]? ", end=" ")
yn = sys.stdin.readline().strip()
print("")
if yn == "" or yn.lower().startswith('y'):
run = True
if run:
subprocess.call(["minicom", name])
else:
print(config)
else:
print(config)
except KeyboardInterrupt:
pass
baud.Close()
main()