def test_send_recv(serial_sender=None, serial_reciever=None): p_send = Panda(serial_sender) p_recv = Panda(serial_reciever) p_send.set_safety_mode(Panda.SAFETY_ALLOUTPUT) p_send.set_can_loopback(False) p_recv.set_can_loopback(False) assert not p_send.legacy assert not p_recv.legacy p_send.can_send_many([(0x1ba, 0, "message", 0)] * 2) time.sleep(0.05) p_recv.can_recv() p_send.can_recv() busses = [0, 1, 2] for bus in busses: for speed in [100, 250, 500, 750, 1000]: p_send.set_can_speed_kbps(bus, speed) p_recv.set_can_speed_kbps(bus, speed) time.sleep(0.05) comp_kbps = time_many_sends(p_send, bus, p_recv, two_pandas=True) saturation_pct = (comp_kbps / speed) * 100.0 assert_greater(saturation_pct, 80) assert_less(saturation_pct, 100) print( "two pandas bus {}, 100 messages at speed {:4d}, comp speed is {:7.2f}, percent {:6.2f}" .format(bus, speed, comp_kbps, saturation_pct))
def tesla_tester(): try: print("Trying to connect to Panda over USB...") p = Panda() except AssertionError: print("USB connection failed. Trying WiFi...") try: p = Panda("WIFI") except: print( "WiFi connection timed out. Please make sure your Panda is connected and try again." ) sys.exit(0) body_bus_speed = 125 # Tesla Body busses (B, BF) are 125kbps, rest are 500kbps body_bus_num = 1 # My TDC to OBD adapter has PT on bus0 BDY on bus1 and CH on bus2 p.set_can_speed_kbps(body_bus_num, body_bus_speed) # Now set the panda from its default of SAFETY_SILENT (read only) to SAFETY_ALLOUTPUT # Careful, as this will let us send any CAN messages we want (which could be very bad!) print("Setting Panda to output mode...") p.set_safety_mode(Panda.SAFETY_ALLOUTPUT) # BDY 0x248 is the MCU_commands message, which includes folding mirrors, opening the trunk, frunk, setting the cars lock state and more. For our test, we will edit the 3rd byte, which is MCU_lockRequest. 0x01 will lock, 0x02 will unlock: print("Unlocking Tesla...") p.can_send(0x248, b"\x00\x00\x02\x00\x00\x00\x00\x00", body_bus_num) #Or, we can set the first byte, MCU_frontHoodCommand + MCU_liftgateSwitch, to 0x01 to pop the frunk, or 0x04 to open/close the trunk (0x05 should open both) print("Opening Frunk...") p.can_send(0x248, b"\x01\x00\x00\x00\x00\x00\x00\x00", body_bus_num) #Back to safety... print("Disabling output on Panda...") p.set_safety_mode(Panda.SAFETY_SILENT) print( "Reading VIN from 0x568. This is painfully slow and can take up to 3 minutes (1 minute per message; 3 messages needed for full VIN)..." ) vin = {} while True: #Read the VIN can_recv = p.can_recv() for address, _, dat, src in can_recv: if src == body_bus_num: if address == 1384: #0x568 is VIN vin_index = int(binascii.hexlify(dat) [:2]) #first byte is the index, 00, 01, 02 vin_string = binascii.hexlify(dat)[ 2:] #rest of the string is the actual VIN data vin[vin_index] = vin_string.decode("hex") print("Got VIN index " + str(vin_index) + " data " + vin[vin_index]) #if we have all 3 parts of the VIN, print it and break out of our while loop if 0 in vin and 1 in vin and 2 in vin: print("VIN: " + vin[0] + vin[1] + vin[2][:3]) break
def send_thread(serial): panda = Panda(serial) panda.set_safety_mode(Panda.SAFETY_ALLOUTPUT) panda.set_can_loopback(False) can_sock = messaging.sub_sock(service_list['can'].port) while True: # Send messages one bus 0 and 1 tsc = messaging.recv_one(can_sock) snd = can_capnp_to_can_list(tsc.can) snd = filter(lambda x: x[-1] <= 2, snd) panda.can_send_many(snd) # Drain panda message buffer panda.can_recv()
def car_speed_pub(): # Create a set up the publisher for car speed: pub = rospy.Publisher('car_speed', Float64, queue_size=10) rospy.init_node('car_speed_pub', anonymous=True) pub_rate = rospy.Rate(10) # 10 Hz # Interface to Panda: panda = Panda() # Run endlessly while ROS is running: while not rospy.is_shutdown(): # Get the CAN message from the Panda: data = panda.can_recv() # Find and parse wheel speed data message: for i in range(0, len(data)): if data[i][0] == 597: wheel_speed = data[i][2] wheel_speed_b = wheel_speed[0] for i in range(1, len(wheel_speed)): wheel_speed_b = (wheel_speed_b << 8) + wheel_speed[i] WS_FL = KPH_TO_MPS * wheel_speed[0] WS_FR = KPH_TO_MPS * wheel_speed[1] WS_RL = KPH_TO_MPS * wheel_speed[2] WS_RR = KPH_TO_MPS * wheel_speed[3] #print "WS_FL = " + str(WS_FL) + "; WS_FR = " + str(WS_FR) + "; WS_RL = " + str(WS_RL) + "; WS_RR = " + str(WS_RR) pub.publish(0.25 * (WS_FL + WS_FR + WS_RL + WS_RR)) pub_rate.sleep()
def send_thread(serial): try: panda = Panda(serial) panda.set_safety_mode(Panda.SAFETY_ALLOUTPUT) panda.set_can_loopback(False) can_sock = messaging.sub_sock('can') while True: # Send messages one bus 0 and 1 tsc = messaging.recv_one(can_sock) snd = can_capnp_to_can_list(tsc.can) snd = list(filter(lambda x: x[-1] <= 2, snd)) panda.can_send_many(snd) # Drain panda message buffer panda.can_recv() except Exception: traceback.print_exc()
def can_logger(): try: print("Trying to connect to Panda over USB...") p = Panda() except AssertionError: print("USB connection failed. Trying WiFi...") try: p = Panda("WIFI") except: print( "WiFi connection timed out. Please make sure your Panda is connected and try again." ) sys.exit(0) try: outputfile = open('output.csv', 'wb') csvwriter = csv.writer(outputfile) #Write Header csvwriter.writerow(['Bus', 'MessageID', 'Message', 'MessageLength']) print("Writing csv file output.csv. Press Ctrl-C to exit...\n") bus0_msg_cnt = 0 bus1_msg_cnt = 0 bus2_msg_cnt = 0 while True: can_recv = p.can_recv() for address, _, dat, src in can_recv: csvwriter.writerow([ str(src), str(hex(address)), "0x" + binascii.hexlify(dat), len(dat) ]) if src == 0: bus0_msg_cnt += 1 elif src == 1: bus1_msg_cnt += 1 elif src == 2: bus2_msg_cnt += 1 print("Message Counts... Bus 0: " + str(bus0_msg_cnt) + " Bus 1: " + str(bus1_msg_cnt) + " Bus 2: " + str(bus2_msg_cnt), end='\r') except KeyboardInterrupt: print("\nNow exiting. Final message Counts... Bus 0: " + str(bus0_msg_cnt) + " Bus 1: " + str(bus1_msg_cnt) + " Bus 2: " + str(bus2_msg_cnt)) outputfile.close()
def connect_wo_esp(): # connect to the panda p = Panda() # power down the ESP p.set_esp_power(False) return p # clear old junk while len(p.can_recv()) > 0: pass
class Prius(object): def __init__(self): panda_list = Panda.list() # choose panda serial prot if len(panda_list) > 1: for i, s in enumerate(panda_list, 1): print('{}) {}'.format(i, s)) serial = panda_list[input('Please input 1, 2,.... or 10 number: ') - 1] else: serial = panda_list[0] # Connect to panda if serial in panda_list: self.panda = Panda(serial) self.panda.set_safety_mode(Panda.SAFETY_ALLOUTPUT) self.panda.can_clear(0) self.frame = 0 print('Connect Panda [Send]') else: print('Not Panda connect') exit() def send_speed(self, speed=0): can_send = [] # speedometer can_send.append(create_speedometer(self.frame, 0xB4, speed, 0, True)) can_send.append(create_speedometer2(self.frame, 0xB1, speed, 0, True)) can_send.append(create_speedometer3(self.frame, 0xB3, speed, 0, True)) can_send.append(create_speedometer4(self.frame, 0x3ca, speed, 0)) self.frame += 1 self.panda.can_send_many(can_send) def send_door_lock(self, lock=True): can_send = [] if lock: msg = struct.pack('!BBB', 0xe4, 0x81, 0x00) can_send.append([0x5B6, 0, msg, 0]) self.panda.can_send_many(can_send) else: msg = struct.pack('!BBB', 0xe4, 0x00, 0x00) can_send.append([0x5B6, 0, msg, 0]) self.panda.can_send_many(can_send) def recv(self): can_msgs = self.panda.can_recv() can_msgs_bytes = [] for address, _, dat, src in can_msgs: can_msgs_bytes.append((address, 0, bytes(dat), src)) if address == 0xb4: print("Address: {}\t Data: {}\t src: {}".format( address, binary_show(dat), src))
class PandaBridge(object): def __init__(self, rate=200): self.can_pub = rospy.Publisher('can_frame_msgs', Frame, queue_size=10) rospy.loginfo("Setting up publisher to: " + str(self.can_pub.resolved_name)) self.rate = rate rospy.loginfo("Reading from panda board at " + str(self.rate) + " Hz.") rospy.loginfo("Connecting to Panda board...") self.panda = Panda() self.panda.set_safety_mode(self.panda.SAFETY_HONDA) rospy.loginfo("Connected.") def run(self): rate = rospy.Rate(self.rate) while not rospy.is_shutdown(): # Reading gives us up to 256 messages can_msg_block = self.panda.can_recv() # print can_msg_block # A message looks like: # [(420, 55639, bytearray(b'\x00f\x00\x00\x00\x00\x00:'), 0), # (428, 55761, bytearray(b'\x7f\xff\x00\x00\x00\x08\x002'), 0), # ... ] if can_msg_block: for msg in can_msg_block: frame = self.convert_panda_to_msg(msg) self.can_pub.publish(frame) rate.sleep() def convert_panda_to_msg(self, can_msg): frame = Frame() frame.id = can_msg[0] frame.dlc = 8 frame.is_error = 0 frame.is_rtr = 0 frame.is_extended = 0 # hacky conversion to uint8 frame.data = str(can_msg[2]) frame.header.frame_id = "" frame.header.stamp = rospy.get_rostime() return frame
def can_proxy(): print("Trying to connect to Panda over USB...") p = Panda() p.set_safety_mode(Panda.SAFETY_ALLOUTPUT) p.can_clear(0) try: while True: can_recv = p.can_recv() for address, _, dat, src in can_recv: if src == 2: if address == 0x180: dat = can_modify(dat) p.can_send(address, bytearray(dat), 0) print("sent message") except KeyboardInterrupt: print("\nNow exiting.")
def can_logger(): try: p = Panda() outputfile = open('output.csv', 'wb') csvwriter = csv.writer(outputfile) #Write Header csvwriter.writerow(['Bus', 'MessageID', 'Message']) print("Writing csv file. Press Ctrl-C to exit...") while True: can_recv = p.can_recv() for address, _, dat, src in can_recv: csvwriter.writerow([str(src), str(address), binascii.hexlify(dat)]) except KeyboardInterrupt: print("Exiting...") outputfile.close()
def can_printer(): p = Panda() start = sec_since_boot() lp = sec_since_boot() msgs = defaultdict(list) canbus = int(os.getenv("CAN", 0)) while True: can_recv = p.can_recv() for address, _, dat, src in can_recv: if src == canbus: msgs[address].append(dat) if sec_since_boot() - lp > 0.1: dd = chr(27) + "[2J" dd += "%5.2f\n" % (sec_since_boot() - start) for k,v in sorted(zip(msgs.keys(), map(lambda x: x[-1].encode("hex"), msgs.values()))): dd += "%s(%6d) %s\n" % ("%04X(%4d)" % (k,k),len(msgs[k]), v) print(dd) lp = sec_since_boot()
def panda_bridge_ros(): can_pub_ = rospy.Publisher('can_frame_msgs', Frame, queue_size=10) rospy.init_node('can_bridge', anonymous=True) rate = rospy.Rate(200) # 10hz panda = Panda() while not rospy.is_shutdown(): can_msg = panda.can_recv() if can_msg: frame = convert_panda_to_msg(can_msg[0]) frame.header.frame_id = "" frame.header.stamp = rospy.get_rostime() can_pub_.publish(frame) rate.sleep()
def can_printer(): p = Panda() p.set_safety_mode(Panda.SAFETY_ALLOUTPUT) start = sec_since_boot() lp = sec_since_boot() msgs = defaultdict(list) canbus = int(os.getenv("CAN", 0)) while True: can_recv = p.can_recv() for address, _, dat, src in can_recv: if src == canbus: msgs[address].append(dat) if sec_since_boot() - lp > 0.1: dd = chr(27) + "[2J" dd += "%5.2f\n" % (sec_since_boot() - start) for k,v in sorted(zip(list(msgs.keys()), [binascii.hexlify(x[-1]) for x in list(msgs.values())])): dd += "%s(%6d) %s\n" % ("%04X(%4d)" % (k,k),len(msgs[k]), v) print(dd) lp = sec_since_boot()
def can_logger(): p = Panda() try: outputfile = open('output.csv', 'w') csvwriter = csv.writer(outputfile) # Write Header csvwriter.writerow(['Bus', 'MessageID', 'Message', 'MessageLength']) print("Writing csv file output.csv. Press Ctrl-C to exit...\n") bus0_msg_cnt = 0 bus1_msg_cnt = 0 bus2_msg_cnt = 0 while True: can_recv = p.can_recv() for address, _, dat, src in can_recv: csvwriter.writerow( [str(src), str(hex(address)), f"0x{dat.hex()}", len(dat)]) if src == 0: bus0_msg_cnt += 1 elif src == 1: bus1_msg_cnt += 1 elif src == 2: bus2_msg_cnt += 1 print( f"Message Counts... Bus 0: {bus0_msg_cnt} Bus 1: {bus1_msg_cnt} Bus 2: {bus2_msg_cnt}", end='\r') except KeyboardInterrupt: print( f"\nNow exiting. Final message Counts... Bus 0: {bus0_msg_cnt} Bus 1: {bus1_msg_cnt} Bus 2: {bus2_msg_cnt}" ) outputfile.close()
def can_printer(): p = Panda() start = sec_since_boot() lp = sec_since_boot() msgs = defaultdict(list) canbus = int(os.getenv("CAN", 0)) while True: can_recv = p.can_recv() for address, _, dat, src in can_recv: if src == canbus: msgs[address].append(dat) if sec_since_boot() - lp > 0.1: dd = chr(27) + "[2J" dd += "%5.2f\n" % (sec_since_boot() - start) for k, v in sorted( zip(msgs.keys(), map(lambda x: x[-1].encode("hex"), msgs.values()))): dd += "%s(%6d) %s\n" % ("%04X(%4d)" % (k, k), len(msgs[k]), v) print(dd) lp = sec_since_boot()
#p_in = Panda("02001b000f51363038363036") p_in = Panda("WIFI") print(p_in.get_serial()) p_in = PandaWifiStreaming() # type: ignore #while True: # p_in.can_recv() #sys.exit(0) p_out.set_safety_mode(Panda.SAFETY_ALLOUTPUT) set_out, set_in = set(), set() # drain p_out.can_recv() p_in.can_recv() BATCH_SIZE = 16 for a in tqdm(list(range(0, 10000, BATCH_SIZE))): for b in range(0, BATCH_SIZE): msg = b"\xaa" * 4 + struct.pack("I", a + b) if a % 1 == 0: p_out.can_send(0xaa, msg, 0) dat_out, dat_in = p_out.can_recv(), p_in.can_recv() if len(dat_in) != 0: print(len(dat_in)) num_out = [struct.unpack("I", i[4:])[0] for _, _, i, _ in dat_out] num_in = [struct.unpack("I", i[4:])[0] for _, _, i, _ in dat_in]
from redis import StrictRedis from panda import Panda import time import binascii panda = Panda() r = StrictRedis() messages = 0 last = time.time() seen = set() while True: can_recv = panda.can_recv() for can_message in can_recv: can_id = can_message[0] if can_id in [ # g sensors 145, 146 ]: continue if bytes(can_message[2]) in seen: continue if r.sismember("can:%s" % (can_message[0]), bytes(can_message[2])): continue print( can_message[0], ''.join(format(ord(byte), '08b') for byte in str(can_message[2]))) seen.add(bytes(can_message[2]))
#p_in = Panda("02001b000f51363038363036") p_in = Panda("WIFI") print(p_in.get_serial()) p_in = PandaWifiStreaming() #while True: # p_in.can_recv() #sys.exit(0) p_out.set_controls_allowed(True) set_out, set_in = set(), set() # drain p_out.can_recv() p_in.can_recv() BATCH_SIZE = 16 for a in tqdm(range(0, 10000, BATCH_SIZE)): for b in range(0, BATCH_SIZE): msg = b"\xaa"*4 + struct.pack("I", a+b) if a%1 == 0: p_out.can_send(0xaa, msg, 0) dat_out, dat_in = p_out.can_recv(), p_in.can_recv() if len(dat_in) != 0: print(len(dat_in)) num_out = [struct.unpack("I", i[4:])[0] for _, _, i, _ in dat_out] num_in = [struct.unpack("I", i[4:])[0] for _, _, i, _ in dat_in]
from panda import Panda import binascii panda = Panda() raw_input("press any key to start background logging") msgs = {} def get_bits(bytes): return list(bin(int(binascii.hexlify(bytes), base=16)).zfill(len(binascii.hexlify(bytes)*8))) try: while True: data = panda.can_recv() for addr, _, dat, src in data: bits = get_bits(dat) if addr not in msgs[src]: msgs[src][addr] = bits else: for bit in msgs[src][addr]: bit = 2 if bit != bits.pop(0) else bit except KeyboardInterrupt: pass raw_input("press any key to start logging again") try: while True:
def can_logger(car_dbc=None, leddar_dbc=None, port=None, sample_time=0.2, filename=None, ni_device='Dev1'): try: print("Trying to connect to Panda over USB...") if port != None: p = Panda(port) else: p = Panda() # default port p.can_clear(0xFFFF) print('Buffer cleaned') # Send leddar request to start transmitting - Read LeddarVu 8 documentation p.set_safety_mode(Panda.SAFETY_ALLOUTPUT) dat = '0301000000000000' p.can_send(0x740, dat.decode('hex'), 1) p.serial_clear(1) except AssertionError: print("USB connection failed. Trying WiFi...") try: p = Panda("WIFI") except: print("WiFi connection timed out. Please make sure\ your Panda is connected and try again.") sys.exit(0) try: columns = [ 'time_rel', 'timestamp', 'vehicle_speed_mph', 'eng_speed_rpm', 'pedal_per', 'gap_m', 'latitude_deg', 'longitude_deg', 'axle_torque_ch_0_V', 'axle_torque_ch_1_V' ] df = pd.DataFrame(columns=columns) rel_time = 0 dt = sample_time while True: time.sleep(dt) row = {} row[columns[0]] = rel_time row[columns[1]] = str(datetime.now()) can_recv = p.can_recv() gps = p.serial_read(1) for address, _, dat, _ in can_recv: if address == 0x215: msg = car_dbc.decode_message(address, dat) row[columns[2]] = ( msg['Veh_wheel_speed_RR_CAN_kph_'] + msg['Veh_wheel_speed_FL_CAN_kph_'] + msg['Veh_wheel_speed_RL_CAN_kph_'] + msg['Veh_wheel_speed_FR_CAN_kph_']) * 0.25 * 0.62137119 elif address == 0x201: msg = car_dbc.decode_message(address, dat) row[columns[3]] = msg['Eng_speed_CAN_rpm_'] row[columns[4]] = msg['Pedal_accel_pos_CAN_per_'] elif (address == 0x752 or address == 0x753 or address == 0x754 or address == 0x755 or address == 0x756 or address == 0x757 or address == 0x758 or address == 0x759): msg = leddar_dbc.decode_message(address, dat) if msg['lidar_channel'] == 4: row[columns[5]] = msg['lidar_distance_m'] # Clear the CAN bus to avoid the buffer p.can_clear(0xFFFF) lat, long = lat_longitude_from_serial(gps) row[columns[6]] = lat row[columns[7]] = long # Add nidaqmx channels with nidaqmx.Task() as task: task.ai_channels.add_ai_voltage_chan( device + "/ai0", terminal_config=TerminalConfiguration.RSE) task.ai_channels.add_ai_voltage_chan( device + "/ai1", terminal_config=TerminalConfiguration.RSE) analog_channels = np.array( task.read(number_of_samples_per_channel=100)).mean(axis=1) row[columns[8]] = analog_channels[0] row[columns[9]] = analog_channels[1] print(row) df = df.append(row, ignore_index=True) rel_time += dt except KeyboardInterrupt: if filename == None: filename = datetime.now().strftime("%Y%m%d%H%M%S") + '_output.csv' else: filename = datetime.now().strftime( "%Y%m%d%H%M%S") + '_' + filename + '.csv' df.to_csv(filename, index=False) # Print and plot results in the screen plt.figure() plt.subplot(2, 1, 1) plt.plot(df['time_rel'], df['gap_m']) plt.ylabel('gap (m)') plt.subplot(2, 1, 2) plt.plot(df['time_rel'], df['axle_torque_ch_0_V']) plt.plot(df['time_rel'], df['axle_torque_ch_1_V']) plt.ylabel('torque voltages') plt.xlabel('time (sec)') plt.legend() plt.show()
if __name__ == "__main__": if os.getenv("WIFI") is not None: p = Panda("WIFI") else: p = Panda() print(p.get_serial()) print(p.health()) t1 = time.time() for i in range(100): p.get_serial() t2 = time.time() print("100 requests took %.2f ms" % ((t2 - t1) * 1000)) p.set_controls_mode() a = 0 while True: # flood msg = b"\xaa" * 4 + struct.pack("I", a) p.can_send(0xaa, msg, 0) p.can_send(0xaa, msg, 1) p.can_send(0xaa, msg, 4) time.sleep(0.01) dat = p.can_recv() if len(dat) > 0: print(dat) a += 1
print('Sending!') msg = b"\xaa" * 4 packet = [[0xaa, None, msg, 0], [0xaa, None, msg, 1], [0xaa, None, msg, 2] ] * NUM_MESSAGES_PER_BUS panda.can_send_many(packet) print(f"Done sending {3*NUM_MESSAGES_PER_BUS} messages!") if __name__ == "__main__": serials = Panda.list() if len(serials) != 2: raise Exception("Connect two pandas to perform this test!") sender = Panda(serials[0]) receiver = Panda(serials[1]) sender.set_safety_mode(Panda.SAFETY_ALLOUTPUT) receiver.set_safety_mode(Panda.SAFETY_ALLOUTPUT) # Start transmisson threading.Thread(target=flood_tx, args=(sender, )).start() # Receive as much as we can in a few second time period rx = [] old_len = 0 start_time = time.time() while time.time() - start_time < 2 or len(rx) > old_len: old_len = len(rx) rx.extend(receiver.can_recv()) print(f"Received {len(rx)} messages")
def test_udp_doesnt_drop(serials=None): connect_wifi(serials[0]) p = Panda(serials[0]) p.set_safety_mode(Panda.SAFETY_ALLOUTPUT) p.set_can_loopback(True) pwifi = PandaWifiStreaming() while 1: if len(pwifi.can_recv()) == 0: break for msg_count in [1, 100]: saturation_pcts = [] for i in range({1: 0x80, 100: 0x20}[msg_count]): pwifi.kick() speed = 500 p.set_can_speed_kbps(0, speed) comp_kbps = time_many_sends(p, 0, pwifi, msg_count=msg_count, msg_id=0x100 + i) saturation_pct = (comp_kbps / speed) * 100.0 if msg_count == 1: sys.stdout.write(".") sys.stdout.flush() else: print( "UDP WIFI loopback %d messages at speed %d, comp speed is %.2f, percent %.2f" % (msg_count, speed, comp_kbps, saturation_pct)) assert_greater(saturation_pct, 20) #sometimes the wifi can be slow... assert_less(saturation_pct, 100) saturation_pcts.append(saturation_pct) if len(saturation_pcts) > 0: assert_greater(sum(saturation_pcts) / len(saturation_pcts), 60) time.sleep(5) usb_ok_cnt = 0 REQ_USB_OK_CNT = 500 st = time.time() msg_id = 0x1bb bus = 0 last_missing_msg = 0 while usb_ok_cnt < REQ_USB_OK_CNT and (time.time() - st) < 40: p.can_send(msg_id, "message", bus) time.sleep(0.01) r = [1] missing = True while len(r) > 0: r = p.can_recv() r = filter(lambda x: x[3] == bus and x[0] == msg_id, r) if len(r) > 0: missing = False usb_ok_cnt += len(r) if missing: last_missing_msg = time.time() et = time.time() - st last_missing_msg = last_missing_msg - st print( "waited {} for panda to recv can on usb, {} msgs, last missing at {}". format(et, usb_ok_cnt, last_missing_msg)) assert usb_ok_cnt >= REQ_USB_OK_CNT, "Unable to recv can on USB after UDP"
class AllPublisher(object): def __init__(self): rp = RosPack() pkgpath = rp.get_path('panda_bridge_ros') pkgpath += '/config/honda_civic_touring_2016_can_for_cantools.dbc' self.parser = load_dbc_file(pkgpath) self.p = Panda() self.p.set_safety_mode(self.p.SAFETY_ALLOUTPUT) self.gas_val = 0 self.brake_val = 0 self.steer_val = 0 self.engine_modifier = 0.0 self.sub_engine = rospy.Subscriber('/joy', Joy, self.engine_cb, queue_size=1) self.sub_steer = rospy.Subscriber('/steering_amount', Int16, self.steer_cb, queue_size=1) self.sub_brake = rospy.Subscriber('/braking_amount', Int16, self.brake_cb, queue_size=1) def engine_cb(self, data): self.engine_modifier = data.axes[1] def steer_cb(self, data): # print("steer_cb: " + str(data)) if data.data > 3840: self.steer_val = 3840 elif data.data < -3840: self.steer_val = -3840 self.steer_val = data.data def brake_cb(self, data): # print("brake_cb: " + str(data)) if data.data > 1023: self.brake_val = 1023 elif data.data < 0: self.brake_val = 0 self.brake_val = data.data def run(self): print("Publishing...") idx_counter = 0 idx_counter_engine = 0 total_cmds_sent = 0 last_received_xmission_speed = 0 last_received_odometer = 0 last_received_xmission_speed_2 = 0 last_engine_rpm = 0 iterations = 0 while not rospy.is_shutdown(): # receive first block = self.p.can_recv() for msg in block: # if its an engine message if msg[0] == 344 and msg[3] == 0: fields = self.parser.decode_message(msg[0], msg[2]) # print("we read engine message with speed:") # print(fields['XMISSION_SPEED']) last_received_xmission_speed = fields['XMISSION_SPEED'] last_received_odometer = fields['ODOMETER'] last_received_xmission_speed_2 = fields['XMISSION_SPEED2'] last_engine_rpm = fields['ENGINE_RPM'] break # Engine rpm stuff if self.engine_modifier != 0.0: # we need to invert the modifier signal # cause we are tricking the cruise control to go at the speed we want # so we need to create a engine data message that ssays # we are driving slower than we should in order for it to accelerate # limit to +- 15kmph the max acceleration requested speed = last_received_xmission_speed + \ (15.0 * self.engine_modifier * -1.0) print("latest_received_xmission_speed: " + str(last_received_xmission_speed)) print("we modify by: " + str((15.0 * self.engine_modifier * -1.0))) print("which results in: " + str(speed)) # (xmission_speed, engine_rpm=2000, odometer=3, idx=0): cmd = create_engine_data(speed, last_engine_rpm, last_received_odometer, idx_counter_engine) idx_counter_engine += 1 idx_counter_engine %= 4 print("command is: " + str(cmd)) print("Sending: " + str(cmd) + " (#" + str(total_cmds_sent) + ") engine modifier val: " + str(self.engine_modifier)) print("speed:" + str(speed) + " rpm: " + str(last_engine_rpm)) self.p.can_send(cmd[0], cmd[2], 0) if iterations % 5 == 0: cmd = create_steering_control(self.steer_val, idx_counter)[0] # print("Sending: " + str(cmd) + # " (#" + str(total_cmds_sent) + # ") steer val: " + str(self.steer_val)) self.p.can_send(cmd[0], cmd[2], 1) # (apply_brake, pcm_override, pcm_cancel_cmd, chime, idx): cmd = create_brake_command(self.brake_val, 1, 0, 0, idx_counter) # print("Sending: " + str(cmd) + # " (#" + str(total_cmds_sent) + # ") brake val: " + str(self.brake_val)) self.p.can_send(cmd[0], cmd[2], 1) idx_counter += 1 idx_counter %= 4 # its wrong, but who cares total_cmds_sent += 1 time.sleep(0.002) iterations += 1
if __name__ == "__main__": if os.getenv("WIFI") is not None: p = Panda("WIFI") else: p = Panda() print(p.get_serial()) print(p.health()) t1 = time.time() for i in range(100): p.get_serial() t2 = time.time() print("100 requests took %.2f ms" % ((t2-t1)*1000)) p.set_controls_allowed(True) a = 0 while True: # flood msg = b"\xaa"*4 + struct.pack("I", a) p.can_send(0xaa, msg, 0) p.can_send(0xaa, msg, 1) p.can_send(0xaa, msg, 4) time.sleep(0.01) dat = p.can_recv() if len(dat) > 0: print(dat) a += 1
#!/usr/bin/env python import time from panda import Panda p = Panda() p.set_safety_mode(Panda.SAFETY_ALLOUTPUT) # hack anything on bus p.set_gmlan(bus=2) time.sleep(0.1) while len(p.can_recv()) > 0: print "clearing" time.sleep(0.1) print "cleared" p.set_gmlan(bus=None) iden = 18000 dat = "\x01\x02\x03\x04\x05\x06\x07\x08" while 1: iden += 1 p.can_send(iden, dat, bus=3) time.sleep(0.01)
from panda import Panda from binascii import hexlify, unhexlify from time import sleep CAN_BUS = 0x0 if __name__ == "__main__": try: panda = Panda() # allow all output panda.set_safety_mode(0x1337) # clear tx buffer panda.can_clear(0x0) # clear rx buffer panda.can_clear(0xFFFF) data = unhexlify(b'10082324F0010098') addr = 0x0 for i in range(0x800): print('Try', hex(addr + i)) panda.can_send(addr + i, data, CAN_BUS) sleep(0.1) for _ in range(100): messages = panda.can_recv() for rx_addr, rx_ts, rx_data, rx_bus in messages: if rx_data[0:1] == unhexlify(b'30'): print('Found addr', hex(addr + i)) sys.exit(0) except Exception as e: print(e)
#!/usr/bin/env python3 import os import sys import time sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..")) from panda import Panda # This script is intended to be used in conjunction with the echo_loopback_test.py test script from panda jungle. # It sends a reversed response back for every message received containing b"test". # Resend every CAN message that has been received on the same bus, but with the data reversed if __name__ == "__main__": p = Panda() p.set_safety_mode(Panda.SAFETY_ALLOUTPUT) while True: incoming = p.can_recv() for message in incoming: address, notused, data, bus = message if b'test' in data: p.can_send(address, data[::-1], bus)
from panda import Panda p1 = Panda('380016000551363338383037') p2 = Panda('430026000951363338383037') # this is a test, no safety p1.set_safety_mode(Panda.SAFETY_ALLOUTPUT) p2.set_safety_mode(Panda.SAFETY_ALLOUTPUT) # get versions print(p1.get_version()) print(p2.get_version()) # this sets bus 2 to actually be GMLAN p2.set_gmlan(bus=2) # send w bitbang then without #iden = 123 iden = 18000 #dat = "\x01\x02" dat = "\x01\x02\x03\x04\x05\x06\x07\x08" while 1: iden += 1 p1.set_gmlan(bus=None) p1.can_send(iden, dat, bus=3) #p1.set_gmlan(bus=2) #p1.can_send(iden, dat, bus=3) time.sleep(0.01) print(p2.can_recv()) #exit(0)
last_steer = 0 last_gas = 0 last_brake = 0 last_speed = 0 while True: ret, frame = cap.read() if not ret: print('No Frame Detected') raise KeyboardInterrupt frame = invert_frame(frame) can_recv = p.can_recv() #print(can_recv) steering_angle_codes = [] gas_pedal_codes = [] brake_pedal_codes = [] speed_codes = [] for address, _, dat, src in can_recv: #dat = bytearray(dat) #print(address) #address = hex(address) #print(dat) #print(type(dat)) #print(hex(address)) #CONVERT DATA TO AN ARRAY OF HEX MESSAGES
def bulkRead(self, endpoint, length, timeout=0): dat = struct.pack("HH", endpoint, 0) return self.transact(dat) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Flash pedal over can') parser.add_argument('--recover', action='store_true') parser.add_argument("fn", type=str, nargs='?', help="flash file") args = parser.parse_args() p = Panda() p.set_safety_mode(Panda.SAFETY_ALLOUTPUT) while 1: if len(p.can_recv()) == 0: break if args.recover: p.can_send(0x366, b"\xce\xfa\xad\xde\x1e\x0b\xb0\x02", 0) exit(0) else: p.can_send(0x366, b"\xce\xfa\xad\xde\x1e\x0b\xb0\x0a", 0) if args.fn: time.sleep(0.1) print("flashing", args.fn) code = open(args.fn, "rb").read() Panda.flash_static(CanHandle(p), code) print("can flash done")
#!/usr/bin/env python3 import time from panda import Panda p = Panda() p.set_safety_mode(Panda.SAFETY_ALLOUTPUT) p.set_gmlan(bus=2) #p.can_send(0xaaa, "\x00\x00", bus=3) last_add = None while 1: ret = p.can_recv() if len(ret) > 0: add = ret[0][0] if last_add is not None and add != last_add+1: print("MISS %d %d" % (last_add, add)) last_add = add print(ret)