-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbu03_util.py
More file actions
295 lines (241 loc) · 9.58 KB
/
Copy pathbu03_util.py
File metadata and controls
295 lines (241 loc) · 9.58 KB
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
#!/usr/bin/env python3
"""
Simple BU03 UWB Module Utility
Handles the quirks of the BU03 (like auto-reboot after AT+SAVE)
"""
import serial
import time
import sys
PORT = '/dev/ttyUSB0'
BAUD = 115200
class BU03Device:
def __init__(self, port=PORT, baud=BAUD):
self.port = port
self.baud = baud
self.ser = None
self.connect()
def connect(self):
"""Connect to the device"""
if self.ser and self.ser.is_open:
self.ser.close()
self.ser = serial.Serial(
port=self.port,
baudrate=self.baud,
bytesize=serial.EIGHTBITS,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
timeout=1,
xonxoff=False,
rtscts=False,
dsrdtr=False
)
time.sleep(0.5)
self.ser.reset_input_buffer()
self.ser.reset_output_buffer()
def send(self, cmd, wait=0.5):
"""Send command and return response"""
self.ser.reset_input_buffer()
self.ser.write((cmd + '\r\n').encode())
self.ser.flush()
time.sleep(wait)
response = b''
start = time.time()
while time.time() - start < 2:
if self.ser.in_waiting > 0:
response += self.ser.read(self.ser.in_waiting)
time.sleep(0.1)
elif response:
break
else:
time.sleep(0.05)
return response.decode('utf-8', errors='replace').strip()
def send_with_reboot(self, cmd, reboot_wait=3, wait_for_reconnect=True):
"""Send command that causes device to reboot (like AT+SAVE)"""
response = self.send(cmd)
if "OK" in response:
if wait_for_reconnect:
print(f"Device rebooting, waiting {reboot_wait}s...")
time.sleep(reboot_wait)
# Read and discard boot messages
if self.ser.in_waiting > 0:
self.ser.read(self.ser.in_waiting)
# Reconnect to ensure clean state
self.connect()
print("Device reconnected")
else:
print("Device will reboot in background")
return response
def get_config(self):
"""Get current configuration"""
response = self.send("AT+GETCFG")
print(f"Current configuration:\n{response}")
return response
def set_config(self, device_id, role, channel, rate, save=True):
"""
Set configuration and optionally save
device_id: 0-10
role: 0=tag, 1=base station
channel: 0=channel 9, 1=channel 5
rate: 0=850K, 1=6.8M
save: automatically save config
"""
cmd = f"AT+SETCFG={device_id},{role},{channel},{rate}"
response = self.send(cmd)
print(f"Set config: {response}")
if save and "OK" in response:
print("\nSaving configuration (device will reboot)...")
self.send_with_reboot("AT+SAVE")
return response
def get_version(self):
"""Get software version"""
return self.send("AT+GETVER")
def get_distance(self):
"""Get distance measurement"""
response = self.send("AT+DISTANCE")
# Parse distance value
try:
# Response format: "distance: 0.340000"
for line in response.split('\n'):
if 'distance:' in line:
dist = float(line.split(':')[1].strip())
return dist
except:
pass
return None
def get_sensor(self):
"""Get accelerometer data"""
return self.send("AT+GETSENSOR")
def get_device_params(self):
"""
Get device parameters (AT+GETDEV)
Returns the device coefficient settings
"""
response = self.send("AT+GETDEV")
print(f"Device parameters:\n{response}")
return response
def set_device_params(self, label_rate=5, antenna_delay=16336,
kalman_enable=1, kalman_q=0.018, kalman_r=0.642,
correction_a=1.0, correction_b=0.0,
positioning_enable=0, positioning_dim=0, save=True):
"""
Set device parameters (AT+SETDEV)
Args:
label_rate: Label capacity/refresh rate (default: 5)
antenna_delay: Antenna delay parameter for UWB timing (default: 16336)
kalman_enable: Enable Kalman filter 0/1 (default: 1)
kalman_q: Kalman filter Q parameter (default: 0.018)
kalman_r: Kalman filter R parameter (default: 0.642)
correction_a: Distance correction scale factor - unitless (default: 1.0)
correction_b: Distance correction offset in millimeters (default: 0.0)
positioning_enable: Enable positioning 0/1 (default: 0)
positioning_dim: Positioning dimension setting (default: 0)
save: Automatically save config (triggers reboot)
Note: Distance correction formula: corrected = a * measured + b (where b is in mm)
"""
cmd = f"AT+SETDEV={label_rate},{antenna_delay},{kalman_enable}," \
f"{kalman_q},{kalman_r},{correction_a:.4f},{correction_b:.2f}," \
f"{positioning_enable},{positioning_dim}"
print(f"Writing device parameters (a={correction_a:.4f}, b={correction_b:.2f}mm)...")
response = self.send(cmd)
if save and "OK" in response:
print("Saving configuration...")
# Don't wait for reconnect - let device reboot in background
self.send_with_reboot("AT+SAVE", wait_for_reconnect=False)
return response
def restart(self):
"""Restart the device"""
print("Restarting device...")
self.send_with_reboot("AT+RESTART")
def close(self):
"""Close connection"""
if self.ser and self.ser.is_open:
self.ser.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
def interactive():
"""Interactive command-line interface"""
print("BU03 UWB Module - Interactive Mode")
print("="*50)
with BU03Device() as bu03:
# Show initial info
print("\n" + bu03.get_version())
print("\n" + bu03.get_config())
print("\nCommands:")
print(" cfg - Show current configuration")
print(" set <id> <role> <ch> <rate> - Set config (auto-saves)")
print(" ver - Show version")
print(" dist - Get distance")
print(" sensor - Get sensor data")
print(" restart - Restart device")
print(" <any AT cmd> - Send raw AT command")
print(" quit - Exit")
while True:
try:
cmd = input("\n> ").strip()
if not cmd:
continue
if cmd.lower() in ['quit', 'exit', 'q']:
break
elif cmd == 'cfg':
bu03.get_config()
elif cmd.startswith('set '):
parts = cmd.split()
if len(parts) == 5:
_, dev_id, role, ch, rate = parts
bu03.set_config(int(dev_id), int(role), int(ch), int(rate))
else:
print("Usage: set <device_id> <role> <channel> <rate>")
print(" device_id: 0-10")
print(" role: 0=tag, 1=base")
print(" channel: 0=ch9, 1=ch5")
print(" rate: 0=850K, 1=6.8M")
elif cmd == 'ver':
print(bu03.get_version())
elif cmd == 'dist':
dist = bu03.get_distance()
if dist is not None:
print(f"Distance: {dist:.3f} m")
else:
print("Could not read distance")
elif cmd == 'sensor':
print(bu03.get_sensor())
elif cmd == 'restart':
bu03.restart()
else:
# Raw AT command
response = bu03.send(cmd if cmd.startswith('AT') else f'AT+{cmd}')
print(response)
except KeyboardInterrupt:
print("\nUse 'quit' to exit")
except Exception as e:
print(f"Error: {e}")
print("\nGoodbye!")
if __name__ == "__main__":
if len(sys.argv) > 1:
# Command-line usage
cmd = sys.argv[1].lower()
with BU03Device() as bu03:
if cmd == 'info':
print(bu03.get_version())
print(bu03.get_config())
elif cmd == 'config':
bu03.get_config()
elif cmd == 'set' and len(sys.argv) == 6:
_, _, dev_id, role, ch, rate = sys.argv
bu03.set_config(int(dev_id), int(role), int(ch), int(rate))
elif cmd == 'distance':
dist = bu03.get_distance()
if dist:
print(f"{dist:.3f}")
else:
print("Usage:")
print(" python3 bu03_util.py # Interactive mode")
print(" python3 bu03_util.py info # Show version and config")
print(" python3 bu03_util.py config # Show config")
print(" python3 bu03_util.py set <id> <role> <ch> <rate>")
print(" python3 bu03_util.py distance # Get distance")
else:
# Interactive mode
interactive()