-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathucp.go
More file actions
637 lines (558 loc) · 22.4 KB
/
Copy pathucp.go
File metadata and controls
637 lines (558 loc) · 22.4 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
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
package main
import (
"encoding/binary"
"fmt"
"io"
)
// CRC16 lookup tables (Modbus-style, from official UCP C implementation)
var crcHiTable = [256]byte{
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,
0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01,
0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81,
0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01,
0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,
0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01,
0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,
0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01,
0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,
0x40,
}
var crcLoTable = [256]byte{
0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7, 0x05, 0xC5, 0xC4,
0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,
0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD,
0x1D, 0x1C, 0xDC, 0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32, 0x36, 0xF6, 0xF7,
0x37, 0xF5, 0x35, 0x34, 0xF4, 0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A,
0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA, 0xEE,
0x2E, 0x2F, 0xEF, 0x2D, 0xED, 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60, 0x61, 0xA1, 0x63, 0xA3, 0xA2,
0x62, 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F,
0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68, 0x78, 0xB8, 0xB9, 0x79, 0xBB,
0x7B, 0x7A, 0xBA, 0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0, 0x50, 0x90, 0x91,
0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,
0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98, 0x88,
0x48, 0x49, 0x89, 0x4B, 0x8B, 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 0x43, 0x83, 0x41, 0x81, 0x80,
0x40,
}
// Calculate CRC16 checksum (Modbus-style, matching official UCP implementation)
func crc16(data []byte) uint16 {
crcHi := byte(0xFF)
crcLo := byte(0xFF)
for _, b := range data {
index := crcLo ^ b
crcLo = crcHi ^ crcHiTable[index]
crcHi = crcLoTable[index]
}
return uint16(crcHi)<<8 | uint16(crcLo)
}
// UCP Protocol Constants
const (
UCP_KEEP_ALIVE = 0x1
UCP_MOTOR_CTL = 0x2
UCP_IMU_CORRECTION_START = 0x3
UCP_IMU_CORRECTION_END = 0x4
UCP_RPM_REPORT = 0x5
UCP_IMU_WRITE = 0x6
UCP_MAG_WRITE = 0x7
UCP_IMUMAG_READ = 0x8
UCP_OTA = 0x9
UCP_STATE = 0xA
)
// UCP Header
type UCPHeader struct {
Len uint16
ID uint8
Index uint8
}
// UCP Telemetry Report (ID 0x5) - matches ucp_rep_t from ucp.h
type UCPTelemetry struct {
Header UCPHeader
BatteryPercent uint16 // Battery percentage (0-100) - bytes 6-7
RPM [4]int16 // Motor RPMs
Accel [3]int16 // Accelerometer (x,y,z)
Gyro [3]int16 // Gyroscope (x,y,z)
Mag [3]int16 // Magnetometer (x,y,z)
Heading int16 // Heading angle from IMU/mag
StopSwitch uint8 // Emergency stop switch status
ErrorCode uint8 // Error code for system state
Reserve uint16 // Reserved field
Version uint16 // Firmware/protocol version
Power uint8 // Power in watts - byte 36
Voltage uint8 // Voltage * 10 (divide by 10 to get actual voltage) - byte 37
Current uint16 // Current * 100 (divide by 100 to get actual current in A) - bytes 38-39
}
// Write UCP command packet to serial port
func WriteUCPCommand(port io.Writer, commandID uint8) error {
// UCP packet format: sync bytes (0xFD 0xFF) + header (len, id, index)
packet := []byte{
0xFD, 0xFF, // Sync bytes
0x00, 0x00, // Length (0 for commands)
commandID, // Command ID
0x00, // Index
}
_, err := port.Write(packet)
return err
}
// UCPPacket is a generic UCP packet that can hold different payload types
type UCPPacket struct {
Header UCPHeader
Telemetry *UCPTelemetry
Calibration *UCPCalibrationData
CalibrationRequest bool // True if STM32 is requesting calibration data from us
}
// Read UCP packet from serial port
func ReadUCPPacket(port io.Reader) (*UCPPacket, error) {
// Look for sync bytes (0xFD 0xFF)
syncBuf := make([]byte, 2)
syncAttempts := 0
for {
syncAttempts++
if _, err := io.ReadFull(port, syncBuf); err != nil {
if debugMode && syncAttempts > 1 {
fmt.Printf("[UCP] Sync search failed after %d attempts: %v\n", syncAttempts, err)
}
return nil, err
}
if syncBuf[0] == 0xFD && syncBuf[1] == 0xFF {
if debugMode && syncAttempts > 10 {
fmt.Printf("[UCP] Found sync after %d attempts\n", syncAttempts)
}
break
}
// Shift buffer and try again
syncBuf[0] = syncBuf[1]
}
// Read header
var header UCPHeader
headerBuf := make([]byte, 4)
if _, err := io.ReadFull(port, headerBuf); err != nil {
if debugMode {
fmt.Printf("[UCP] Header read failed: %v\n", err)
}
return nil, err
}
header.Len = binary.LittleEndian.Uint16(headerBuf[0:2])
header.ID = headerBuf[2]
header.Index = headerBuf[3]
// Handle different packet types
// 0x05 = Telemetry from STM32
// 0x06 = IMU calibration data from STM32 (after calibration)
// 0x07 = Mag calibration data from STM32 (after calibration)
// 0x08 = Calibration read REQUEST from STM32 (we need to respond)
if header.ID != UCP_RPM_REPORT && header.ID != UCP_IMU_WRITE &&
header.ID != UCP_MAG_WRITE && header.ID != UCP_IMUMAG_READ {
// Skip unsupported packet types
skipLen := header.Len - 4
skip := make([]byte, skipLen)
if _, err := io.ReadFull(port, skip); err != nil {
if debugMode {
fmt.Printf("[UCP] Skip read failed for ID 0x%02x: %v\n", header.ID, err)
}
return nil, err
}
// Read and discard CRC
crcBuf := make([]byte, 2)
io.ReadFull(port, crcBuf)
if debugMode {
fmt.Printf("[UCP] Skipped unsupported packet (ID: 0x%02x, len: %d)\n", header.ID, header.Len)
}
return nil, fmt.Errorf("skipping unsupported packet (ID: 0x%02x)", header.ID)
}
// Read telemetry payload - header.Len INCLUDES the 4-byte header, so payload is (Len - 4) bytes
payloadLen := header.Len - 4
payloadBuf := make([]byte, payloadLen)
if _, err := io.ReadFull(port, payloadBuf); err != nil {
if debugMode {
fmt.Printf("[UCP] Payload read failed (expected %d bytes): %v\n", payloadLen, err)
}
return nil, err
}
// Read CRC16 (2 bytes) - CRITICAL: UCP packets always end with CRC16
crcBuf := make([]byte, 2)
if _, err := io.ReadFull(port, crcBuf); err != nil {
if debugMode {
fmt.Printf("[UCP] CRC read failed: %v\n", err)
}
return nil, err
}
receivedCRC := binary.LittleEndian.Uint16(crcBuf)
// Calculate CRC over entire packet (sync + header + payload)
// Build the complete packet for CRC calculation
packetForCRC := make([]byte, 0, 2+4+header.Len)
packetForCRC = append(packetForCRC, 0xFD, 0xFF) // Sync bytes
headerBytes := make([]byte, 4)
binary.LittleEndian.PutUint16(headerBytes[0:2], header.Len)
headerBytes[2] = header.ID
headerBytes[3] = header.Index
packetForCRC = append(packetForCRC, headerBytes...)
packetForCRC = append(packetForCRC, payloadBuf...)
calculatedCRC := crc16(packetForCRC)
if calculatedCRC != receivedCRC {
if debugMode {
// Print first 32 bytes of packet for debugging
dumpLen := 32
if len(packetForCRC) < dumpLen {
dumpLen = len(packetForCRC)
}
fmt.Printf("[UCP] CRC FAIL - Header: len=%d id=0x%02X idx=%d\n", header.Len, header.ID, header.Index)
fmt.Printf("[UCP] CRC FAIL - Packet (first %d bytes): % 02X\n", dumpLen, packetForCRC[:dumpLen])
fmt.Printf("[UCP] CRC FAIL - CRC bytes: % 02X (LE=0x%04X)\n", crcBuf, receivedCRC)
fmt.Printf("[UCP] CRC FAIL - Calculated: 0x%04X, Received: 0x%04X\n", calculatedCRC, receivedCRC)
}
return nil, fmt.Errorf("CRC mismatch (calc: 0x%04X, recv: 0x%04X)", calculatedCRC, receivedCRC)
}
// Create packet based on ID
packet := &UCPPacket{Header: header}
if header.ID == UCP_IMUMAG_READ {
// This is a calibration read REQUEST from STM32
// STM32 is asking US for calibration data
packet.CalibrationRequest = true
if debugMode {
fmt.Printf("[UCP] Received calibration read request from STM32\n")
}
} else if header.ID == UCP_RPM_REPORT {
// Parse telemetry
telem := &UCPTelemetry{Header: header}
// Debug: show raw payload
if debugMode {
fmt.Printf("[UCP] Parsing telemetry packet, payload length: %d bytes\n", len(payloadBuf))
if len(payloadBuf) >= 36 {
fmt.Printf("[UCP] Bytes 30-35 (power/voltage/current/version): % 02X\n", payloadBuf[30:36])
}
}
offset := 0
telem.BatteryPercent = binary.LittleEndian.Uint16(payloadBuf[offset : offset+2])
offset += 2
for i := 0; i < 4; i++ {
telem.RPM[i] = int16(binary.LittleEndian.Uint16(payloadBuf[offset : offset+2]))
offset += 2
}
for i := 0; i < 3; i++ {
telem.Accel[i] = int16(binary.LittleEndian.Uint16(payloadBuf[offset : offset+2]))
offset += 2
}
for i := 0; i < 3; i++ {
telem.Gyro[i] = int16(binary.LittleEndian.Uint16(payloadBuf[offset : offset+2]))
offset += 2
}
for i := 0; i < 3; i++ {
telem.Mag[i] = int16(binary.LittleEndian.Uint16(payloadBuf[offset : offset+2]))
offset += 2
}
if offset+2 <= len(payloadBuf) {
telem.Heading = int16(binary.LittleEndian.Uint16(payloadBuf[offset : offset+2]))
offset += 2
}
// Parse power, voltage, current (bytes 30-33 in payload) BEFORE version
if offset+1 <= len(payloadBuf) {
telem.Power = payloadBuf[offset]
if debugMode {
fmt.Printf("[UCP] Power at offset %d: raw=%d (%dW)\n", offset, telem.Power, telem.Power)
}
offset += 1
}
if offset+1 <= len(payloadBuf) {
telem.Voltage = payloadBuf[offset]
if debugMode {
fmt.Printf("[UCP] Voltage at offset %d: raw=%d (%.1fV)\n", offset, telem.Voltage, float64(telem.Voltage)/10.0)
}
offset += 1
}
if offset+2 <= len(payloadBuf) {
telem.Current = binary.LittleEndian.Uint16(payloadBuf[offset : offset+2])
if debugMode {
fmt.Printf("[UCP] Current at offset %d: raw=%d (%.2fA)\n", offset, telem.Current, float64(telem.Current)/100.0)
}
offset += 2
}
// Version comes AFTER power/voltage/current (bytes 34-35 in payload)
if offset+2 <= len(payloadBuf) {
telem.Version = binary.LittleEndian.Uint16(payloadBuf[offset : offset+2])
offset += 2
}
// Note: StopSwitch, ErrorCode, Reserve are not in this packet version
// They may be in a future firmware update
packet.Telemetry = telem
} else if header.ID == UCP_IMU_WRITE {
// Parse IMU calibration packet (0x06) from STM32
// This is sent by STM32 after it completes IMU calibration
if payloadLen < 12 {
return nil, fmt.Errorf("IMU calibration payload too short: %d bytes (expected 12)", payloadLen)
}
cal := &UCPCalibrationData{}
offset := 0
cal.AccBiasX = binary.LittleEndian.Uint16(payloadBuf[offset : offset+2])
offset += 2
cal.AccBiasY = binary.LittleEndian.Uint16(payloadBuf[offset : offset+2])
offset += 2
cal.AccBiasZ = binary.LittleEndian.Uint16(payloadBuf[offset : offset+2])
offset += 2
cal.GyroBiasX = binary.LittleEndian.Uint16(payloadBuf[offset : offset+2])
offset += 2
cal.GyroBiasY = binary.LittleEndian.Uint16(payloadBuf[offset : offset+2])
offset += 2
cal.GyroBiasZ = binary.LittleEndian.Uint16(payloadBuf[offset : offset+2])
packet.Calibration = cal
if debugMode {
fmt.Printf("[UCP] Received IMU calibration from STM32: acc=[%d,%d,%d] gyro=[%d,%d,%d]\n",
cal.AccBiasX, cal.AccBiasY, cal.AccBiasZ,
cal.GyroBiasX, cal.GyroBiasY, cal.GyroBiasZ)
}
} else if header.ID == UCP_MAG_WRITE {
// Parse magnetometer calibration packet (0x07) from STM32
// This is sent by STM32 after it completes mag calibration
if payloadLen < 6 {
return nil, fmt.Errorf("mag calibration payload too short: %d bytes (expected 6)", payloadLen)
}
cal := &UCPCalibrationData{}
offset := 0
cal.MagBiasX = binary.LittleEndian.Uint16(payloadBuf[offset : offset+2])
offset += 2
cal.MagBiasY = binary.LittleEndian.Uint16(payloadBuf[offset : offset+2])
offset += 2
cal.MagBiasZ = binary.LittleEndian.Uint16(payloadBuf[offset : offset+2])
packet.Calibration = cal
if debugMode {
fmt.Printf("[UCP] Received mag calibration from STM32: mag=[%d,%d,%d]\n",
cal.MagBiasX, cal.MagBiasY, cal.MagBiasZ)
}
}
return packet, nil
}
// Convert raw IMU values to standard units
func (t *UCPTelemetry) GetAccelG() (x, y, z float64) {
// Assuming typical scale factor for accelerometer (adjust based on actual sensor)
scale := 1.0 / 16384.0 // for ±2g range
return float64(t.Accel[0]) * scale,
float64(t.Accel[1]) * scale,
float64(t.Accel[2]) * scale
}
func (t *UCPTelemetry) GetGyroDPS() (x, y, z float64) {
// Assuming typical scale factor for gyroscope (adjust based on actual sensor)
scale := 1.0 / 131.0 // for ±250°/s range
return float64(t.Gyro[0]) * scale,
float64(t.Gyro[1]) * scale,
float64(t.Gyro[2]) * scale
}
func (t *UCPTelemetry) GetMagUT() (x, y, z float64) {
// Magnetometer scale (microTesla)
scale := 0.15 // typical for many magnetometers
return float64(t.Mag[0]) * scale,
float64(t.Mag[1]) * scale,
float64(t.Mag[2]) * scale
}
func (t *UCPTelemetry) GetVoltage() float64 {
// Voltage field contains voltage * 10, so divide by 10 to get actual volts
return float64(t.Voltage) / 10.0
}
func (t *UCPTelemetry) GetBatteryPercent() int {
// BatteryPercent field is already the percentage (0-100) from STM32
return int(t.BatteryPercent)
}
func (t *UCPTelemetry) GetPower() float64 {
// Power field is in watts
return float64(t.Power)
}
func (t *UCPTelemetry) GetCurrent() float64 {
// Current field contains current * 100, so divide by 100 to get actual amps
return float64(t.Current) / 100.0
}
// ========================================================================
// UCP COMMAND STRUCTURES AND WRITE FUNCTIONS
// ========================================================================
// IMU Correction Types
const (
UICT_MAG = 1 // Magnetometer calibration
UICT_IMU = 2 // IMU (accelerometer/gyroscope) calibration
)
// Motor Control Command (ID 0x02)
type UCPMotorControl struct {
Speed int16 // Linear speed (-100 to 100)
Angular int16 // Angular velocity (-100 to 100)
FrontLED int16 // Front LED control
BackLED int16 // Back LED control
Version uint16 // Protocol version
Reserve1 uint16 // Reserved
Reserve2 uint32 // Reserved
}
// IMU Correction Command (ID 0x03 start, 0x04 end)
type UCPIMUCorrection struct {
Type uint8 // UICT_MAG or UICT_IMU
}
// IMU Write Command (ID 0x06)
type UCPIMUWrite struct {
AccBiasX uint16
AccBiasY uint16
AccBiasZ uint16
GyroBiasX uint16
GyroBiasY uint16
GyroBiasZ uint16
}
// Magnetometer Write Command (ID 0x07)
type UCPMagWrite struct {
MagBiasX uint16
MagBiasY uint16
MagBiasZ uint16
}
// IMU/Mag Calibration Read Response (ID 0x08)
type UCPCalibrationData struct {
Header UCPHeader
ErrorCode uint8 // Error code
AccBiasX uint16 // Accelerometer bias X
AccBiasY uint16 // Accelerometer bias Y
AccBiasZ uint16 // Accelerometer bias Z
GyroBiasX uint16 // Gyroscope bias X
GyroBiasY uint16 // Gyroscope bias Y
GyroBiasZ uint16 // Gyroscope bias Z
MagBiasX uint16 // Magnetometer bias X
MagBiasY uint16 // Magnetometer bias Y
MagBiasZ uint16 // Magnetometer bias Z
}
// Generic UCP packet writer with CRC16
func writeUCPPacket(port io.Writer, commandID uint8, payload []byte) error {
// Calculate total packet length (header + payload)
packetLen := uint16(4 + len(payload))
// Build complete packet for CRC calculation
packet := make([]byte, 0, 2+4+len(payload)+2)
// Add sync bytes
packet = append(packet, 0xFD, 0xFF)
// Add header
lenBytes := make([]byte, 2)
binary.LittleEndian.PutUint16(lenBytes, packetLen)
packet = append(packet, lenBytes...)
packet = append(packet, commandID)
packet = append(packet, 0) // Index
// Add payload
packet = append(packet, payload...)
// Calculate and append CRC16
crc := crc16(packet)
crcBytes := make([]byte, 2)
binary.LittleEndian.PutUint16(crcBytes, crc)
packet = append(packet, crcBytes...)
// Write entire packet
_, err := port.Write(packet)
return err
}
// WriteMotorControl sends a motor control command (ID 0x02)
func WriteMotorControl(port io.Writer, speed, angular, frontLED, backLED int16) error {
cmd := UCPMotorControl{
Speed: speed,
Angular: angular,
FrontLED: frontLED,
BackLED: backLED,
Version: 0,
Reserve1: 0,
Reserve2: 0,
}
// Serialize payload
payload := make([]byte, 18) // 2+2+2+2+2+2+4 = 18 bytes
binary.LittleEndian.PutUint16(payload[0:2], uint16(cmd.Speed))
binary.LittleEndian.PutUint16(payload[2:4], uint16(cmd.Angular))
binary.LittleEndian.PutUint16(payload[4:6], uint16(cmd.FrontLED))
binary.LittleEndian.PutUint16(payload[6:8], uint16(cmd.BackLED))
binary.LittleEndian.PutUint16(payload[8:10], cmd.Version)
binary.LittleEndian.PutUint16(payload[10:12], cmd.Reserve1)
binary.LittleEndian.PutUint32(payload[12:16], cmd.Reserve2)
return writeUCPPacket(port, UCP_MOTOR_CTL, payload)
}
// WriteKeepAlive sends a keep-alive/heartbeat command (ID 0x01)
func WriteKeepAlive(port io.Writer) error {
return writeUCPPacket(port, UCP_KEEP_ALIVE, nil)
}
// WriteIMUCorrectionStart sends command to start IMU/mag calibration (ID 0x03)
func WriteIMUCorrectionStart(port io.Writer, correctionType uint8) error {
payload := []byte{correctionType}
return writeUCPPacket(port, UCP_IMU_CORRECTION_START, payload)
}
// WriteIMUCorrectionEnd sends command to end IMU/mag calibration (ID 0x04)
func WriteIMUCorrectionEnd(port io.Writer, correctionType uint8) error {
payload := []byte{correctionType}
return writeUCPPacket(port, UCP_IMU_CORRECTION_END, payload)
}
// WriteIMUCalibration writes IMU calibration parameters (ID 0x06)
func WriteIMUCalibration(port io.Writer, cmd *UCPIMUWrite) error {
payload := make([]byte, 12) // 6 * 2 bytes
binary.LittleEndian.PutUint16(payload[0:2], cmd.AccBiasX)
binary.LittleEndian.PutUint16(payload[2:4], cmd.AccBiasY)
binary.LittleEndian.PutUint16(payload[4:6], cmd.AccBiasZ)
binary.LittleEndian.PutUint16(payload[6:8], cmd.GyroBiasX)
binary.LittleEndian.PutUint16(payload[8:10], cmd.GyroBiasY)
binary.LittleEndian.PutUint16(payload[10:12], cmd.GyroBiasZ)
return writeUCPPacket(port, UCP_IMU_WRITE, payload)
}
// WriteMagCalibration writes magnetometer calibration parameters (ID 0x07)
func WriteMagCalibration(port io.Writer, cmd *UCPMagWrite) error {
payload := make([]byte, 6) // 3 * 2 bytes
binary.LittleEndian.PutUint16(payload[0:2], cmd.MagBiasX)
binary.LittleEndian.PutUint16(payload[2:4], cmd.MagBiasY)
binary.LittleEndian.PutUint16(payload[4:6], cmd.MagBiasZ)
return writeUCPPacket(port, UCP_MAG_WRITE, payload)
}
// WriteIMUMagRead requests to read IMU and magnetometer calibration values (ID 0x08)
func WriteIMUMagRead(port io.Writer) error {
return writeUCPPacket(port, UCP_IMUMAG_READ, nil)
}
// WriteCalibrationData sends calibration data response (ID 0x08)
func WriteCalibrationData(port io.Writer, data *UCPCalibrationData) error {
payload := make([]byte, 19)
payload[0] = data.ErrorCode
binary.LittleEndian.PutUint16(payload[1:3], data.AccBiasX)
binary.LittleEndian.PutUint16(payload[3:5], data.AccBiasY)
binary.LittleEndian.PutUint16(payload[5:7], data.AccBiasZ)
binary.LittleEndian.PutUint16(payload[7:9], data.GyroBiasX)
binary.LittleEndian.PutUint16(payload[9:11], data.GyroBiasY)
binary.LittleEndian.PutUint16(payload[11:13], data.GyroBiasZ)
binary.LittleEndian.PutUint16(payload[13:15], data.MagBiasX)
binary.LittleEndian.PutUint16(payload[15:17], data.MagBiasY)
binary.LittleEndian.PutUint16(payload[17:19], data.MagBiasZ)
return writeUCPPacket(port, UCP_IMUMAG_READ, payload)
}
// WriteIMUCalibrationAck sends acknowledgment for received IMU calibration (ID 0x06 + error code)
func WriteIMUCalibrationAck(port io.Writer, errorCode uint8) error {
payload := []byte{errorCode}
return writeUCPPacket(port, UCP_IMU_WRITE, payload)
}
// WriteMagCalibrationAck sends acknowledgment for received mag calibration (ID 0x07 + error code)
func WriteMagCalibrationAck(port io.Writer, errorCode uint8) error {
payload := []byte{errorCode}
return writeUCPPacket(port, UCP_MAG_WRITE, payload)
}
// ParseCalibrationResponse parses a calibration read response packet (ID 0x08)
func ParseCalibrationResponse(payloadBuf []byte) (*UCPCalibrationData, error) {
if len(payloadBuf) < 19 {
return nil, fmt.Errorf("calibration payload too short: %d bytes (expected 19)", len(payloadBuf))
}
cal := &UCPCalibrationData{}
offset := 0
cal.ErrorCode = payloadBuf[offset]
offset += 1
cal.AccBiasX = binary.LittleEndian.Uint16(payloadBuf[offset : offset+2])
offset += 2
cal.AccBiasY = binary.LittleEndian.Uint16(payloadBuf[offset : offset+2])
offset += 2
cal.AccBiasZ = binary.LittleEndian.Uint16(payloadBuf[offset : offset+2])
offset += 2
cal.GyroBiasX = binary.LittleEndian.Uint16(payloadBuf[offset : offset+2])
offset += 2
cal.GyroBiasY = binary.LittleEndian.Uint16(payloadBuf[offset : offset+2])
offset += 2
cal.GyroBiasZ = binary.LittleEndian.Uint16(payloadBuf[offset : offset+2])
offset += 2
cal.MagBiasX = binary.LittleEndian.Uint16(payloadBuf[offset : offset+2])
offset += 2
cal.MagBiasY = binary.LittleEndian.Uint16(payloadBuf[offset : offset+2])
offset += 2
cal.MagBiasZ = binary.LittleEndian.Uint16(payloadBuf[offset : offset+2])
return cal, nil
}