Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 963
Expand file tree
/
Copy path__init__.py
More file actions
Latest commit
808 lines (657 loc) · 26 KB
/
Copy path__init__.py
File metadata and controls
808 lines (657 loc) · 26 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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
# python library to interface with panda
importos
importre
importsys
importtime
importusb1
importstruct
importhashlib
importbinascii
importctypes
fromfunctoolsimportwraps, partial
fromitertoolsimportaccumulate
importopendbc
fromopendbc.car.structsimportCarParams
from .baseimportBaseHandle
from .constantsimportBASEDIR, FW_PATH, McuType, compute_version_hash
from .dfuimportPandaDFU
from .spiimportPandaSpiHandle, PandaSpiException, PandaProtocolMismatch
from .usbimportPandaUsbHandle
from .utilsimportlogger
# load libusb from pip package
try:
importlibusb_package
usb1._libusb1.loadLibrary(ctypes.CDLL(str(libusb_package.get_library_path())))
exceptImportError:
# TODO: remove this on next AGNOS update
pass
__version__='0.0.10'
CANPACKET_HEAD_SIZE=0x6
DLC_TO_LEN= [0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 16, 20, 24, 32, 48, 64]
LEN_TO_DLC= {length: dlcfor (dlc, length) inenumerate(DLC_TO_LEN)}
PANDA_CAN_CNT=3
defcalculate_checksum(data):
res=0
forbindata:
res^=b
returnres
def_parse_c_struct(path, name):
type_to_format= {"uint8_t": "B", "uint16_t": "H", "uint32_t": "I", "float": "f"}
withopen(path) asf:
lines= [l.strip() forlinf.read().split(f"struct __attribute__((packed)) {name} {{", 1)[1].split("};", 1)[0].splitlines() ifl.strip()]
fields= [re.fullmatch(rf"({'|'.join(type_to_format)})\s+\w+;", l) forlinlines]
ifnotall(fields):
raiseValueError(f"unsupported {name} layout in {path}")
returnstruct.Struct("<"+"".join(type_to_format[m[1]] forminfields))
defpack_can_buffer(arr, chunk=False, fd=False):
snds= [bytearray(), ]
foraddress, dat, businarr:
extended=1ifaddress>=0x800else0
data_len_code=LEN_TO_DLC[len(dat)]
header=bytearray(CANPACKET_HEAD_SIZE)
word_4b= (address<<3) | (extended<<2)
header[0] = (data_len_code<<4) | (bus<<1) |int(fd)
header[1] =word_4b&0xFF
header[2] = (word_4b>>8) &0xFF
header[3] = (word_4b>>16) &0xFF
header[4] = (word_4b>>24) &0xFF
header[5] =calculate_checksum(header[:5] +dat)
snds[-1].extend(header)
snds[-1].extend(dat)
ifchunkandlen(snds[-1]) >256:
snds.append(bytearray())
returnsnds
defunpack_can_buffer(dat):
ret= []
whilelen(dat) >=CANPACKET_HEAD_SIZE:
data_len=DLC_TO_LEN[(dat[0]>>4)]
header=dat[:CANPACKET_HEAD_SIZE]
bus= (header[0] >>1) &0x7
address= (header[4] <<24|header[3] <<16|header[2] <<8|header[1]) >>3
if (header[1] >>1) &0x1:
# returned
bus+=128
ifheader[1] &0x1:
# rejected
bus+=192
# we need more from the next transfer
ifdata_len>len(dat) -CANPACKET_HEAD_SIZE:
break
assertcalculate_checksum(dat[:(CANPACKET_HEAD_SIZE+data_len)]) ==0, "CAN packet checksum incorrect"
data=dat[CANPACKET_HEAD_SIZE:(CANPACKET_HEAD_SIZE+data_len)]
dat=dat[(CANPACKET_HEAD_SIZE+data_len):]
ret.append((address, data, bus))
return (ret, dat)
defensure_version(desc, lib_field, panda_field, fn):
@wraps(fn)
defwrapper(self, *args, **kwargs):
lib_version=getattr(self, lib_field)
panda_version=getattr(self, panda_field)
iflib_version!=panda_version:
raiseRuntimeError(f"{desc} packet version mismatch: panda's firmware v{panda_version}, library v{lib_version}. Reflash panda.")
returnfn(self, *args, **kwargs)
returnwrapper
ensure_can_packet_version=partial(ensure_version, "CAN", "CAN_PACKET_VERSION", "can_version")
ensure_health_packet_version=partial(ensure_version, "health", "HEALTH_PACKET_VERSION", "health_version")
classPanda:
SERIAL_DEBUG=0
SERIAL_SOM_DEBUG=4
USB_VIDS= (0xbbaa, 0x3801) # 0x3801 is comma's registered VID
USB_PIDS= (0xddee, 0xddcc)
REQUEST_IN=usb1.ENDPOINT_IN|usb1.TYPE_VENDOR|usb1.RECIPIENT_DEVICE
REQUEST_OUT=usb1.ENDPOINT_OUT|usb1.TYPE_VENDOR|usb1.RECIPIENT_DEVICE
# from https://github.com/commaai/openpilot/blob/103b4df18cbc38f4129555ab8b15824d1a672bdf/cereal/log.capnp#L648
HW_TYPE_UNKNOWN=b'\x00'
HW_TYPE_RED_PANDA=b'\x07'
HW_TYPE_TRES=b'\x09'
HW_TYPE_CUATRO=b'\x0a'
HW_TYPE_BODY=b'\xb1'
CAN_PACKET_VERSION=compute_version_hash(os.path.join(opendbc.INCLUDE_PATH, "opendbc/safety/can.h"))
HEALTH_PACKET_VERSION=compute_version_hash(os.path.join(BASEDIR, "board/health.h"))
HEALTH_STRUCT=_parse_c_struct(os.path.join(BASEDIR, "board/health.h"), "health_t")
CAN_HEALTH_STRUCT=struct.Struct("<BIBBBBBBBBIIIIIIIHHBBBIIII")
H7_DEVICES= [HW_TYPE_RED_PANDA, HW_TYPE_TRES, HW_TYPE_CUATRO, HW_TYPE_BODY]
SUPPORTED_DEVICES=H7_DEVICES
INTERNAL_DEVICES= (HW_TYPE_TRES, HW_TYPE_CUATRO)
HARNESS_STATUS_NC=0
HARNESS_STATUS_NORMAL=1
HARNESS_STATUS_FLIPPED=2
def__init__(self, serial: str|None=None, claim: bool=True, disable_checks: bool=True, can_speed_kbps: int=500, cli: bool=True):
self._disable_checks=disable_checks
self._handle: BaseHandle
self._handle_open=False
self.can_rx_overflow_buffer=b''
self._can_speed_kbps=can_speed_kbps
ifcliandserialisNone:
self._connect_serial=self._cli_select_panda()
else:
self._connect_serial=serial
self.connect(claim)
def_cli_select_panda(self):
dfu_pandas=PandaDFU.list()
iflen(dfu_pandas) >0:
print("INFO: some attached pandas are in DFU mode.")
pandas=self.list()
iflen(pandas) ==0:
print("INFO: panda not available")
returnNone
iflen(pandas) ==1:
print(f"INFO: connecting to panda {pandas[0]}")
returnpandas[0]
whileTrue:
print("Multiple pandas available:")
pandas.sort()
foridx, serialinenumerate(pandas):
print(f"{[idx]}: {serial}")
try:
choice=int(input("Choose serial [0]:") or"0")
returnpandas[choice]
except (ValueError, IndexError):
print("Enter a valid index.")
def__enter__(self):
returnself
def__exit__(self, *args):
self.close()
defclose(self):
ifself._handle_open:
self._handle.close()
self._handle_open=False
ifself._contextisnotNone:
self._context.close()
defconnect(self, claim=True, wait=False):
self.close()
self._handle=None
whileself._handleisNone:
# try USB first, then SPI
self._context, self._handle, serial, self.bootstub=self.usb_connect(self._connect_serial, claim=claim, no_error=wait)
ifself._handleisNone:
self._context, self._handle, serial, self.bootstub=self.spi_connect(self._connect_serial)
ifnotwait:
break
ifself._handleisNone:
raiseException("failed to connect to panda")
self._serial=serial
self._connect_serial=serial
self._handle_open=True
self.health_version, self.can_version=self.get_packets_versions()
logger.debug("connected")
# disable openpilot's heartbeat checks
ifself._disable_checks:
self.set_heartbeat_disabled()
self.set_power_save(0)
# reset comms
self.can_reset_communications()
# disable automatic CAN-FD switching
forbusinrange(PANDA_CAN_CNT):
self.set_canfd_auto(bus, False)
# set CAN speed
forbusinrange(PANDA_CAN_CNT):
self.set_can_speed_kbps(bus, self._can_speed_kbps)
@property
defspi(self) ->bool:
returnisinstance(self._handle, PandaSpiHandle)
@classmethod
defspi_connect(cls, serial, ignore_version=False):
try:
handle=PandaSpiHandle()
dat=handle.get_protocol_version()
exceptPandaSpiException:
returnNone, None, None, False
spi_serial=binascii.hexlify(dat[:12]).decode()
pid=dat[13]
ifpidnotin (0xcc, 0xee):
raisePandaProtocolMismatch(f"invalid bootstub status ({pid=}). reflash panda")
bootstub=pid==0xee
spi_version=dat[14]
# did we get the right panda?
ifserialisnotNoneandspi_serial!=serial:
returnNone, None, None, False
# ensure our protocol version matches the panda
if (notignore_version) andspi_version!=handle.PROTOCOL_VERSION:
raisePandaProtocolMismatch(f"panda protocol mismatch: expected {handle.PROTOCOL_VERSION}, got {spi_version}. reflash panda")
# got a device and all good
returnNone, handle, spi_serial, bootstub
@classmethod
defusb_connect(cls, serial, claim=True, no_error=False):
handle, usb_serial, bootstub=None, None, None
context=usb1.USBContext()
context.open()
try:
fordeviceincontext.getDeviceList(skip_on_error=True):
ifdevice.getVendorID() incls.USB_VIDSanddevice.getProductID() incls.USB_PIDS:
try:
this_serial=device.getSerialNumber()
exceptException:
# Allow to ignore errors on reconnect. USB hubs need some time to initialize after panda reset
ifnotno_error:
logger.exception("failed to get serial number of panda")
continue
ifserialisNoneorthis_serial==serial:
logger.debug("opening device %s %s", this_serial, hex(device.getProductID()))
usb_serial=this_serial
bootstub= (device.getProductID() &0xF0) ==0xe0
handle=device.open()
ifsys.platformnotin ("win32", "cygwin", "msys", "darwin"):
handle.setAutoDetachKernelDriver(True)
ifclaimorsys.platform=="darwin":
handle.claimInterface(0)
# handle.setInterfaceAltSetting(0, 0) # Issue in USB stack
break
exceptException:
logger.exception("USB connect error")
usb_handle=None
ifhandleisnotNone:
usb_handle=PandaUsbHandle(handle)
else:
context.close()
returncontext, usb_handle, usb_serial, bootstub
defis_connected_spi(self):
returnisinstance(self._handle, PandaSpiHandle)
defis_connected_usb(self):
returnisinstance(self._handle, PandaUsbHandle)
@classmethod
deflist(cls, usb_only: bool=False):
ret=cls.usb_list()
ifnotusb_only:
ret+=cls.spi_list()
returnlist(set(ret))
@classmethod
defusb_list(cls):
ret= []
try:
withusb1.USBContext() ascontext:
fordeviceincontext.getDeviceList(skip_on_error=True):
ifdevice.getVendorID() incls.USB_VIDSanddevice.getProductID() incls.USB_PIDS:
try:
serial=device.getSerialNumber()
iflen(serial) ==24:
ret.append(serial)
else:
logger.warning(f"found device with panda descriptors but invalid serial: {serial}", RuntimeWarning)
exceptException:
logger.exception("error connecting to panda")
exceptException:
logger.exception("exception while listing pandas")
returnret
@classmethod
defspi_list(cls):
_, _, serial, _=cls.spi_connect(None, ignore_version=True)
ifserialisnotNone:
return [serial, ]
return []
defreset(self, enter_bootstub=False, enter_bootloader=False, reconnect=True):
ifenter_bootstuborenter_bootloader:
assert (hw_type:=self.get_type()) inself.SUPPORTED_DEVICES, f"Unknown HW: {hw_type}"
# no response is expected since it resets right away
timeout=5000ifisinstance(self._handle, PandaSpiHandle) else15000
try:
ifenter_bootloader:
self._handle.controlWrite(Panda.REQUEST_IN, 0xd1, 0, 0, b'', timeout=timeout, expect_disconnect=True)
else:
ifenter_bootstub:
self._handle.controlWrite(Panda.REQUEST_IN, 0xd1, 1, 0, b'', timeout=timeout, expect_disconnect=True)
else:
self._handle.controlWrite(Panda.REQUEST_IN, 0xd8, 0, 0, b'', timeout=timeout, expect_disconnect=True)
exceptException:
pass
self.close()
ifnotenter_bootloaderandreconnect:
self.reconnect()
@property
defconnected(self) ->bool:
returnself._handle_open
defreconnect(self):
ifself._handle_open:
self.close()
success=False
# wait up to 15 seconds
for_inrange(15*10):
try:
self.connect(claim=False, wait=True)
success=True
break
exceptException:
pass
time.sleep(0.1)
ifnotsuccess:
raiseException("reconnect failed")
@staticmethod
defflasher_present(handle: BaseHandle) ->bool:
fr=handle.controlRead(Panda.REQUEST_IN, 0xb0, 0, 0, 0xc)
returnfr[4:8] ==b"\xde\xad\xd0\x0d"
@staticmethod
defflash_static(handle, code, mcu_type):
assertmcu_typeisnotNone, "must set valid mcu_type to flash"
# confirm flasher is present
assertPanda.flasher_present(handle)
# determine sectors to erase
apps_sectors_cumsum=accumulate(mcu_type.config.sector_sizes[1:])
last_sector=next((i+1fori, vinenumerate(apps_sectors_cumsum) ifv>len(code)), -1)
assertlast_sector>=1, "Binary too small? No sector to erase."
assertlast_sector<7, "Binary too large! Risk of overwriting provisioning chunk."
# unlock flash
logger.info("flash: unlocking")
handle.controlWrite(Panda.REQUEST_IN, 0xb1, 0, 0, b'')
# erase sectors
logger.info(f"flash: erasing sectors 1 - {last_sector}")
foriinrange(1, last_sector+1):
handle.controlWrite(Panda.REQUEST_IN, 0xb2, i, 0, b'')
# flash over EP2
STEP=0x200
logger.info("flash: flashing")
foriinrange(0, len(code), STEP):
handle.bulkWrite(2, code[i:i+STEP])
# reset
logger.info("flash: resetting")
try:
handle.controlWrite(Panda.REQUEST_IN, 0xd8, 0, 0, b'', expect_disconnect=True)
exceptException:
pass
defflash(self, fn=None, code=None, reconnect=True):
assert (hw_type:=self.get_type()) inself.SUPPORTED_DEVICES, f"Unknown HW: {hw_type}"
ifself.up_to_date(fn=fn):
logger.info("flash: already up to date")
return
ifnotfn:
fn=os.path.join(FW_PATH, McuType.H7.config.app_fn)
assertos.path.isfile(fn)
logger.debug("flash: main version is %s", self.get_version())
ifnotself.bootstub:
self.reset(enter_bootstub=True)
assert(self.bootstub)
ifcodeisNone:
withopen(fn, "rb") asf:
code=f.read()
# get version
logger.debug("flash: bootstub version is %s", self.get_version())
# do flash
Panda.flash_static(self._handle, code, mcu_type=McuType.H7)
# reconnect
ifreconnect:
self.reconnect()
defrecover(self, timeout: int|None=60, reset: bool=True) ->bool:
dfu_serial=self.get_dfu_serial()
ifreset:
self.reset(enter_bootstub=True)
self.reset(enter_bootloader=True)
ifnotself.wait_for_dfu(dfu_serial, timeout=timeout):
returnFalse
dfu=PandaDFU(dfu_serial)
dfu.recover()
# reflash after recover
self.connect(True, True)
self.flash()
returnTrue
@staticmethod
defwait_for_dfu(dfu_serial: str|None, timeout: int|None=None) ->bool:
t_start=time.monotonic()
dfu_list=PandaDFU.list()
while (dfu_serialisNoneandlen(dfu_list) ==0) or (dfu_serialisnotNoneanddfu_serialnotindfu_list):
logger.debug("waiting for DFU...")
time.sleep(0.1)
iftimeoutisnotNoneand (time.monotonic() -t_start) >timeout:
returnFalse
dfu_list=PandaDFU.list()
returnTrue
@classmethod
defwait_for_panda(cls, serial: str|None, timeout: int) ->bool:
t_start=time.monotonic()
serials=cls.list()
while (serialisNoneandlen(serials) ==0) or (serialisnotNoneandserialnotinserials):
logger.debug("waiting for panda...")
time.sleep(0.1)
iftimeoutisnotNoneand (time.monotonic() -t_start) >timeout:
returnFalse
serials=cls.list()
returnTrue
defup_to_date(self, fn=None) ->bool:
current=self.get_signature()
iffnisNone:
fn=os.path.join(FW_PATH, McuType.H7.config.app_fn)
expected=Panda.get_signature_from_firmware(fn)
return (current==expected)
defcall_control_api(self, msg):
self._handle.controlWrite(Panda.REQUEST_OUT, msg, 0, 0, b'')
# ******************* health *******************
@ensure_health_packet_version
defhealth(self):
dat=self._handle.controlRead(Panda.REQUEST_IN, 0xd2, 0, 0, self.HEALTH_STRUCT.size)
a=self.HEALTH_STRUCT.unpack(dat)
return {
"uptime": a[0],
"voltage": a[1],
"current": a[2],
"safety_tx_blocked": a[3],
"safety_rx_invalid": a[4],
"tx_buffer_overflow": a[5],
"rx_buffer_overflow": a[6],
"faults": a[7],
"ignition_line": a[8],
"ignition_can": a[9],
"controls_allowed": a[10],
"car_harness_status": a[11],
"safety_mode": a[12],
"safety_param": a[13],
"fault_status": a[14],
"power_save_enabled": a[15],
"heartbeat_lost": a[16],
"alternative_experience": a[17],
"interrupt_load": a[18],
"fan_power": a[19],
"safety_rx_checks_invalid": a[20],
"spi_error_count": a[21],
"sbu1_voltage_mV": a[22],
"sbu2_voltage_mV": a[23],
"som_reset_triggered": a[24],
"sound_output_level": a[25],
"temperature": a[26],
}
@ensure_health_packet_version
defcan_health(self, can_number):
LEC_ERROR_CODE= {
0: "No error",
1: "Stuff error",
2: "Form error",
3: "AckError",
4: "Bit1Error",
5: "Bit0Error",
6: "CRCError",
7: "NoChange",
}
dat=self._handle.controlRead(Panda.REQUEST_IN, 0xc2, int(can_number), 0, self.CAN_HEALTH_STRUCT.size)
a=self.CAN_HEALTH_STRUCT.unpack(dat)
return {
"bus_off": a[0],
"bus_off_cnt": a[1],
"error_warning": a[2],
"error_passive": a[3],
"last_error": LEC_ERROR_CODE[a[4]],
"last_stored_error": LEC_ERROR_CODE[a[5]],
"last_data_error": LEC_ERROR_CODE[a[6]],
"last_data_stored_error": LEC_ERROR_CODE[a[7]],
"receive_error_cnt": a[8],
"transmit_error_cnt": a[9],
"total_error_cnt": a[10],
"total_tx_lost_cnt": a[11],
"total_rx_lost_cnt": a[12],
"total_tx_cnt": a[13],
"total_rx_cnt": a[14],
"total_fwd_cnt": a[15],
"total_tx_checksum_error_cnt": a[16],
"can_speed": a[17],
"can_data_speed": a[18],
"canfd_enabled": a[19],
"brs_enabled": a[20],
"canfd_non_iso": a[21],
"irq0_call_rate": a[22],
"irq1_call_rate": a[23],
"irq2_call_rate": a[24],
"can_core_reset_count": a[25],
}
# ******************* control *******************
defget_version(self):
returnself._handle.controlRead(Panda.REQUEST_IN, 0xd6, 0, 0, 0x40).decode('utf8')
@staticmethod
defget_signature_from_firmware(fn) ->bytes:
withopen(fn, 'rb') asf:
f.seek(-128, 2) # Seek from end of file
returnf.read(128)
defget_signature(self) ->bytes:
part_1=self._handle.controlRead(Panda.REQUEST_IN, 0xd3, 0, 0, 0x40)
part_2=self._handle.controlRead(Panda.REQUEST_IN, 0xd4, 0, 0, 0x40)
returnbytes(part_1+part_2)
defget_type(self):
returnself._handle.controlRead(Panda.REQUEST_IN, 0xc1, 0, 0, 0x40)
defget_packets_versions(self):
dat=self._handle.controlRead(Panda.REQUEST_IN, 0xdd, 0, 0, 8)
ifdatandlen(dat) ==8:
returnstruct.unpack("<II", dat)
return (0, 0)
defis_internal(self):
returnself.get_type() inPanda.INTERNAL_DEVICES
defget_serial(self):
"""
Returns the comma-issued dongle ID from our provisioning
"""
dat=self._handle.controlRead(Panda.REQUEST_IN, 0xd0, 0, 0, 0x20)
hashsig, calc_hash=dat[0x1c:], hashlib.sha1(dat[0:0x1c]).digest()[0:4]
assert(hashsig==calc_hash)
return [dat[0:0x10].decode("utf8"), dat[0x10:0x10+10].decode("utf8")]
defget_usb_serial(self):
"""
Returns the serial number reported from the USB descriptor;
matches the MCU UID
"""
returnself._serial
defget_dfu_serial(self):
returnPandaDFU.st_serial_to_dfu_serial(self._serial, McuType.H7)
defget_uid(self):
"""
Returns the UID from the MCU
"""
dat=self._handle.controlRead(Panda.REQUEST_IN, 0xc3, 0, 0, 12)
returnbinascii.hexlify(dat).decode()
defget_secret(self):
returnself._handle.controlRead(Panda.REQUEST_IN, 0xd0, 1, 0, 0x10)
defget_interrupt_call_rate(self, irqnum):
dat=self._handle.controlRead(Panda.REQUEST_IN, 0xc4, int(irqnum), 0, 4)
returnstruct.unpack("I", dat)[0]
# ******************* configuration *******************
defset_alternative_experience(self, alternative_experience):
self._handle.controlWrite(Panda.REQUEST_OUT, 0xdf, int(alternative_experience), 0, b'')
defset_power_save(self, power_save_enabled=0):
self._handle.controlWrite(Panda.REQUEST_OUT, 0xe7, int(power_save_enabled), 0, b'')
defenter_stop_mode(self):
self._handle.controlWrite(Panda.REQUEST_OUT, 0xb5, 0, 0, b'', expect_disconnect=True)
defset_safety_mode(self, mode=CarParams.SafetyModel.silent, param=0):
self._handle.controlWrite(Panda.REQUEST_OUT, 0xdc, mode, param, b'')
defset_obd(self, obd):
self._handle.controlWrite(Panda.REQUEST_OUT, 0xdb, int(obd), 0, b'')
defset_can_loopback(self, enable):
# set can loopback mode for all buses
self._handle.controlWrite(Panda.REQUEST_OUT, 0xe5, int(enable), 0, b'')
defset_can_enable(self, bus_num, enable):
# sets the can transceiver enable pin
self._handle.controlWrite(Panda.REQUEST_OUT, 0xf4, int(bus_num), int(enable), b'')
defset_can_speed_kbps(self, bus, speed):
self._handle.controlWrite(Panda.REQUEST_OUT, 0xde, bus, int(speed*10), b'')
defset_can_data_speed_kbps(self, bus, speed):
self._handle.controlWrite(Panda.REQUEST_OUT, 0xf9, bus, int(speed*10), b'')
defset_canfd_non_iso(self, bus, non_iso):
self._handle.controlWrite(Panda.REQUEST_OUT, 0xfc, bus, int(non_iso), b'')
defset_canfd_auto(self, bus, auto):
self._handle.controlWrite(Panda.REQUEST_OUT, 0xe8, bus, int(auto), b'')
defset_uart_baud(self, uart, rate):
self._handle.controlWrite(Panda.REQUEST_OUT, 0xe4, uart, int(rate/300), b'')
defset_uart_parity(self, uart, parity):
# parity, 0=off, 1=even, 2=odd
self._handle.controlWrite(Panda.REQUEST_OUT, 0xe2, uart, parity, b'')
defset_uart_callback(self, uart, install):
self._handle.controlWrite(Panda.REQUEST_OUT, 0xe3, uart, int(install), b'')
# ******************* can *******************
# The panda will NAK CAN writes when there is CAN congestion.
# libusb will try to send it again, with a max timeout.
# Timeout is in ms. If set to 0, the timeout is infinite.
CAN_SEND_TIMEOUT_MS=10
defcan_reset_communications(self):
self._handle.controlWrite(Panda.REQUEST_OUT, 0xc0, 0, 0, b'')
@ensure_can_packet_version
defcan_send_many(self, arr, *, fd=False, timeout=CAN_SEND_TIMEOUT_MS):
snds=pack_can_buffer(arr, chunk=(notself.spi), fd=fd)
fortxinsnds:
whilelen(tx) >0:
bs=self._handle.bulkWrite(3, tx, timeout=timeout)
tx=tx[bs:]
defcan_send(self, addr, dat, bus, *, fd=False, timeout=CAN_SEND_TIMEOUT_MS):
self.can_send_many([[addr, dat, bus]], fd=fd, timeout=timeout)
@ensure_can_packet_version
defcan_recv(self):
dat=bytearray()
whileTrue:
try:
dat=self._handle.bulkRead(1, 16384) # Max receive batch size + 2 extra reserve frames
break
except (usb1.USBErrorIO, usb1.USBErrorOverflow):
logger.error("CAN: BAD RECV, RETRYING")
time.sleep(0.1)
msgs, self.can_rx_overflow_buffer=unpack_can_buffer(self.can_rx_overflow_buffer+dat)
returnmsgs
defcan_clear(self, bus):
"""Clears all messages from the specified internal CAN ringbuffer as
though it were drained.
Args:
bus (int): can bus number to clear a tx queue, or 0xFFFF to clear the
global can rx queue.
"""
self._handle.controlWrite(Panda.REQUEST_OUT, 0xf1, bus, 0, b'')
# ******************* serial *******************
defserial_read(self, port_number, maxlen=1024):
ret=b''
while1:
r=bytes(self._handle.controlRead(Panda.REQUEST_IN, 0xe0, port_number, 0, 0x40))
iflen(r) ==0orlen(ret) >=maxlen:
break
ret+=r
returnret
defserial_write(self, port_number, ln):
ret=0
ifisinstance(ln, str):
ln=bytes(ln, 'utf-8')
foriinrange(0, len(ln), 0x20):
ret+=self._handle.bulkWrite(2, struct.pack("B", port_number) +ln[i:i+0x20])
returnret
defsend_heartbeat(self, engaged=True):
self._handle.controlWrite(Panda.REQUEST_OUT, 0xf3, engaged, 0, b'')
# disable heartbeat checks for use outside of openpilot
# sending a heartbeat will reenable the checks
defset_heartbeat_disabled(self):
self._handle.controlWrite(Panda.REQUEST_OUT, 0xf8, 0, 0, b'')
# ****************** Timer *****************
defget_microsecond_timer(self):
dat=self._handle.controlRead(Panda.REQUEST_IN, 0xa8, 0, 0, 4)
returnstruct.unpack("I", dat)[0]
# ******************* IR *******************
defset_ir_power(self, percentage):
self._handle.controlWrite(Panda.REQUEST_OUT, 0xb0, int(percentage), 0, b'')
# ******************* Fan ******************
defset_fan_power(self, percentage):
self._handle.controlWrite(Panda.REQUEST_OUT, 0xb1, int(percentage), 0, b'')
defget_fan_rpm(self):
dat=self._handle.controlRead(Panda.REQUEST_IN, 0xb2, 0, 0, 2)
a=struct.unpack("H", dat)
returna[0]
# ****************** Siren *****************
defset_siren(self, enabled):
self._handle.controlWrite(Panda.REQUEST_OUT, 0xf6, int(enabled), 0, b'')
# ****************** Debug *****************
# arr: timer period
# ccrN: channel N pulse length
defset_clock_source_timer_params(self, arr, ccr1, ccr2, ccr3):
param1= ((ccr1&0xFF) <<8) | (ccr2&0xFF)
param2= ((ccr3&0xFF) <<8) | (arr&0xFF)
self._handle.controlWrite(Panda.REQUEST_OUT, 0xe6, param1, param2, b'')
defforce_relay_drive(self, intercept_relay_drive, ignition_relay_drive):
self._handle.controlWrite(Panda.REQUEST_OUT, 0xc5, (int(intercept_relay_drive) |int(ignition_relay_drive) <<1), 0, b'')
defread_som_gpio(self) ->bool:
r=self._handle.controlRead(Panda.REQUEST_IN, 0xc6, 0, 0, 1)
returnr[0] ==1