-
Notifications
You must be signed in to change notification settings - Fork 4
/
buspirate.py
159 lines (125 loc) · 3.78 KB
/
buspirate.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
#!/usr/bin/python3 -u
# coding=utf-8
"""
Bus Pirate scripting tool
"""
import sys
import os
import pathlib
import argparse
import time
import serial
import logging
from src.utils import *
from config import *
BP_SERIAL_SPEED = 115200
BP_SERIAL_TIMEOUT = 0.1
BP_RESET_DELAY = 500
BP_READY_SYMBOL = ">"
BP_BASICMODE_STR = "(BASIC)"
COMMENT_SYMBOL = "//"
log = None
args = None
# Serial port
gSerial = serial.Serial()
def connect(port):
global gSerial
gSerial.port = port
gSerial.baudrate = BP_SERIAL_SPEED
gSerial.timeout = BP_SERIAL_TIMEOUT
if(gSerial.isOpen()):
gSerial.close()
log.debug('--- Opening serial port')
try:
gSerial.open()
except:
pass
if not gSerial.isOpen():
log.error('!!! ERROR opening serial port, exiting program')
quit()
log.debug('--- Serial port open')
resp = send("")
if resp and BP_BASICMODE_STR in resp[-1]:
log.debug('--- Exiting BASIC mode')
send("exit")
def send(command):
log.info(f">>> {command}")
serialCommand = command + '\n'
gSerial.write(serialCommand.encode())
return waitresponse()
def waitresponse():
startTime = time.time()
lastRecTime = 0
response = []
while( True ):
line = gSerial.readline()
if(line):
line = line.decode()
response.append(line)
lastRecTime = time.time()
displine = line.replace('\n','')
log.info(f"<<< {displine}")
# Check if command was completed (response will be something like "HiZ>")
if line[-1] == BP_READY_SYMBOL:
break
else:
log.error('!!! Timeout waiting for response')
return response
def resetBoard():
log.debug('--- Resetting board')
send('#')
delay(BP_RESET_DELAY)
def sendScript(file):
data = open(file, encoding='utf8')
lines = [line.replace('\n', '').strip() for line in data]
log.debug(f'--- Sending script file ({file}) - {len(lines)} lines')
for line in lines:
line = line.strip()
if line == '#':
resetBoard() # Correctly handle reset timeout
else:
parts = line.split(COMMENT_SYMBOL)
command = parts.pop(0).strip()
comments = COMMENT_SYMBOL.join(parts)
if comments:
log.debug(f"/// {comments}")
if command == '':
delay(SCRIPT_BLANK_LINE_DELAY)
else:
send(command)
def main():
global log
global args
programStartTime = time.time()
parser = argparse.ArgumentParser()
parser.add_argument('scriptFileName', help='set script file to use')
parser.add_argument('-c', '--comPort', help='set COM port (default: {:s})'.format(SERIAL_PORT), default=SERIAL_PORT)
parser.add_argument('-l', '--logmode', action="store_true", help='log mode', )
args = parser.parse_args()
if args.logmode:
logging.basicConfig(
stream=sys.stdout,
format='%(asctime)s.%(msecs)03d %(message)s',
level=logging.INFO,
datefmt='%Y/%m/%d %H:%M:%S')
else:
logging.basicConfig(
stream=sys.stdout,
format='%(message)s',
level=logging.DEBUG)
log = logging.getLogger("buspirate")
log.debug('--- Bus Pirate scripting tool')
log.debug(f'--- Script file: {args.scriptFileName}')
log.debug(f'--- COM port: {args.comPort}')
log.debug(f'--- Log mode: {args.logmode}')
connect(args.comPort)
if RESET_AT_STARTUP:
resetBoard()
sendScript(args.scriptFileName)
if RESET_AT_END:
resetBoard()
log.debug('--- Closing serial port')
gSerial.close()
log.debug(f"--- Finished in {time.time() - programStartTime:.2f} seconds")
if __name__ == '__main__':
main()