class TestPanda(unittest.TestCase): def setUp(self): self.ivo = Panda('Ivo', '*****@*****.**', 'male') def test_str(self): self.assertEqual(str(self.ivo), "Ivo") def test_eq(self): rado = Panda('rado', '*****@*****.**', 'male') rado2 = Panda('Ivo', '*****@*****.**', 'male') self.assertFalse(self.ivo == rado) self.assertTrue(self.ivo == rado2) def test_name(self): self.assertEqual(self.ivo.name(), 'Ivo') def test_email(self): self.assertEqual(self.ivo.email(), '*****@*****.**') def test_gender(self): self.assertEqual(self.ivo.gender(), 'male') def test_is_male(self): self.assertTrue(self.ivo.isMale()) def test_is_female(self): self.assertFalse(self.ivo.isFemale())
class TestPandaClass(unittest.TestCase): def setUp(self): self.test_obj = Panda("Ivo", "*****@*****.**", "male") self.test_obj2 = Panda("Rado", "*****@*****.**", "male") self.test_obj3 = Panda("Ivo", "*****@*****.**", "male") def test_init(self): self.assertTrue(isinstance(self.test_obj, Panda)) def test_wrong_init(self): with self.assertRaises(ValueError): wrong_answ = Panda("mitio", "mitko.com", "male") def test_str_method(self): self.assertEqual(str(self.test_obj), "Ivo") def test_eq_method(self): self.assertFalse(self.test_obj == self.test_obj2) self.assertEqual(self.test_obj, self.test_obj3) def test_get_name(self): self.assertEqual(self.test_obj.get_name(), "Ivo") def test_get_email(self): self.assertEqual(self.test_obj.get_email(), "*****@*****.**") def test_is_Female(self): self.assertFalse(self.test_obj.isFemale()) def test_is_Male(self): self.assertTrue(self.test_obj.isMale()) def test_gender(self): self.assertEqual(self.test_obj.get_gender(), "male")
def __init__(self, screen): self.__screen = screen self.__playtime = 0.0 self.__clock = pygame.time.Clock() self.__date = ParallelDate(144.0) self.__panda = Panda() self.__setup_panda(self.__panda) self.__initialize()
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 filterDriverPacks(self, paths): try: from panda import Panda except ImportError: ctx.logger.debug("Installing all driver packages since panda module is not installed.") return paths panda = Panda() # filter all driver packages foundDriverPackages = set(yali.pisiiface.getPathsByPackageName(panda.get_all_driver_packages())) ctx.logger.debug("Found driver packages: %s" % foundDriverPackages) allPackages = set(paths) packages = allPackages - foundDriverPackages # detect hardware neededDriverPackages = set(yali.pisiiface.getPathsByPackageName(panda.get_needed_driver_packages())) ctx.logger.debug("Known driver packages for this hardware: %s" % neededDriverPackages) # if alternatives are available ask to user, otherwise return if neededDriverPackages and neededDriverPackages.issubset(allPackages): answer = ctx.interface.messageWindow( _("Proprietary Hardware Drivers"), _("<qt>Proprietary drivers are available which may be required " "to utilize the full capabilities of your video card. " "These drivers are developed by the hardware manufacturer " "and not supported by Pardus developers since their " "source code is not publicly available." "<br><br>" "<b>Do you want to install and use these proprietary drivers " "instead of the default drivers?</b></qt>"), type="custom", customIcon="question", customButtons=[_("Yes"), _("No")]) if answer == 0: packages.update(neededDriverPackages) ctx.blacklistedKernelModules.append(panda.get_blacklisted_module()) ctx.logger.debug("These driver packages will be installed: %s" % neededDriverPackages) return list(packages)
def run_test(sleep_duration): pandas = Panda.list() print(pandas) if len(pandas) == 0: print("NO PANDAS") assert False if len(pandas) == 1: # if we only have one on USB, assume the other is on wifi pandas.append("WIFI") run_test_w_pandas(pandas, sleep_duration)
def test_elm_panda_safety_mode_ISO15765(): s = elm_connect() serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None p_car = Panda(serial) # Configure this so the messages will send p_car.set_can_speed_kbps(0, 500) p_car.set_safety_mode(Panda.SAFETY_ALLOUTPUT) p_elm = Panda("WIFI") p_elm.set_safety_mode(0xE327); #sim = elm_car_simulator.ELMCarSimulator(serial, lin=False) #sim.start() def did_send(p, addr, dat, bus): p.can_send(addr, dat, bus) t = time.time() while time.time()-t < 0.5: msg = p.can_recv() for addrin, _, datin, busin in msg: if (0x80 | bus) == busin and addr == addrin and datin == dat: return True time.sleep(0.01) return False try: sync_reset(s) # Reset elm (which requests the ELM327 safety mode) #29 bit assert not did_send(p_elm, 0x18DB33F1, b'\x02\x01\x00\x00\x00\x00\x00\x00', 1) #wrong canid assert not did_send(p_elm, 0x18DB33F1, b'\x02\x01\x00', 0) #wrong length assert not did_send(p_elm, 0x10000000, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) #bad addr assert not did_send(p_elm, 0x18DAF133, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) #bad addr (phy addr) assert not did_send(p_elm, 0x18DAF000, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) #bad addr assert not did_send(p_elm, 0x18DAF1F3, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) #bad addr! (phys rsp to elm) assert did_send(p_elm, 0x18DB33F1, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) #good! (obd func req) assert did_send(p_elm, 0x18DA10F1, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) #good! (phys response) #11 bit assert not did_send(p_elm, 0X7DF, b'\x02\x01\x00\x00\x00\x00\x00\x00', 1) #wrong canid assert not did_send(p_elm, 0X7DF, b'\x02\x01\x00', 0) #wrong length assert not did_send(p_elm, 0xAA, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) #bad addr assert not did_send(p_elm, 0x7DA, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) #bad addr (phy addr) assert not did_send(p_elm, 0x7E8, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) #bad addr (sending 'response') assert did_send(p_elm, 0x7DF, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) #good! (obd func req) assert did_send(p_elm, 0x7E1, b'\x02\x01\x00\x00\x00\x00\x00\x00', 0) #good! (phys response) finally: s.close()
def test_elm_panda_safety_mode_KWPFast(): serial = os.getenv("CANSIMSERIAL") if os.getenv("CANSIMSERIAL") else None p_car = Panda(serial) # Configure this so the messages will send p_car.set_safety_mode(Panda.SAFETY_ALLOUTPUT) p_car.kline_drain() p_elm = Panda("WIFI") p_elm.set_safety_mode(0xE327); def get_checksum(dat): result = 0 result += sum(map(ord, dat)) if isinstance(b'dat', str) else sum(dat) return struct.pack("B", result % 0x100) def timed_recv_check(p, bus, goodmsg): t = time.time() msg = bytearray() while time.time()-t < 0.5 and len(msg) != len(goodmsg): msg += p._handle.controlRead(Panda.REQUEST_OUT, 0xe0, bus, 0, len(goodmsg)-len(msg)) #print("Received", repr(msg)) if msg == goodmsg: return True time.sleep(0.01) return False def kline_send(p, x, bus=2): p.kline_drain(bus=bus) p._handle.bulkWrite(2, chr(bus).encode()+x) return timed_recv_check(p, bus, x) def did_send(priority, toaddr, fromaddr, dat, bus=2, checkbyte=None): msgout = struct.pack("BBB", priority | len(dat), toaddr, fromaddr) + dat msgout += get_checksum(msgout) if checkbyte is None else checkbyte print("Sending", hex(priority), hex(toaddr), hex(fromaddr), repr(msgout)) if not kline_send(p_elm, msgout, bus=bus): return False return timed_recv_check(p_car, bus, msgout) assert not did_send(0xC0, 0x33, 0xF1, b'\x01\x0F', bus=3) #wrong bus assert not did_send(0xC0, 0x33, 0xF1, b'') #wrong length assert not did_send(0xB0, 0x33, 0xF1, b'\x01\x0E') #bad priority assert not did_send(0xC0, 0x00, 0xF1, b'\x01\x0D') #bad addr assert not did_send(0xC0, 0x33, 0x00, b'\x01\x0C') #bad addr assert did_send(0xC0, 0x33, 0xF1, b'\x01\x0B') #good! (obd func req)
def test_recv_only(): p = Panda() p.set_safety_mode(Panda.SAFETY_ALLOUTPUT) p.set_can_loopback(True) pwifi = Panda("WIFI") # TODO: msg_count=1000 drops packets, is this fixable? for msg_count in [10,100,200]: speed = 500 p.set_can_speed_kbps(0, speed) comp_kbps = time_many_sends(p, 0, pwifi, msg_count) saturation_pct = (comp_kbps/speed) * 100.0 print("HT WIFI loopback %d messages at speed %d, comp speed is %.2f, percent %.2f" % (msg_count, speed, comp_kbps, saturation_pct))
def handle_event(self, event): if not self.__panda.get_alive(): if event.type == pygame.MOUSEBUTTONDOWN: self.__panda = Panda() self.__playtime = 0.0 return if event.type == pygame.MOUSEBUTTONDOWN: for i in range(0, 5): b = self.__buttons[i] if b.pressed(event.pos): b.action(i) if event.type == self.__panda.EVENT_HUNGRY: self.__panda.update_hungry(self.__panda.NEGATIVE_UPDATE) elif event.type == self.__panda.EVENT_DIRTY: self.__panda.update_dirty(self.__panda.NEGATIVE_UPDATE) elif event.type == self.__panda.EVENT_PLAYFUL: self.__panda.update_playful(self.__panda.NEGATIVE_UPDATE) elif event.type == self.__panda.EVENT_SLEEPY: self.__panda.update_sleepy(self.__panda.NEGATIVE_UPDATE) elif event.type == self.__panda.EVENT_ILL: self.__panda.update_ill(self.__panda.NEGATIVE_UPDATE)
def test_throughput(): p = Panda() # enable output mode p.set_safety_mode(Panda.SAFETY_ALLOUTPUT) # enable CAN loopback mode p.set_can_loopback(True) p = Panda("WIFI") for speed in [100,250,500,750,1000]: # set bus 0 speed to speed p.set_can_speed_kbps(0, speed) time.sleep(0.05) comp_kbps = time_many_sends(p, 0) # bit count from https://en.wikipedia.org/wiki/CAN_bus saturation_pct = (comp_kbps/speed) * 100.0 #assert_greater(saturation_pct, 80) #assert_less(saturation_pct, 100) print("WIFI loopback 100 messages at speed %d, comp speed is %.2f, percent %.2f" % (speed, comp_kbps, saturation_pct))
def test_get_serial(): p = Panda() print(p.get_serial())
def test_flash_wifi(): Panda.flash_ota_wifi() connect_wifi()
import _thread from functools import wraps from panda import Panda from nose.tools import timed, assert_equal, assert_less, assert_greater from parameterized import parameterized, param SPEED_NORMAL = 500 SPEED_GMLAN = 33.3 test_all_types = parameterized([ param(panda_type=Panda.HW_TYPE_WHITE_PANDA), param(panda_type=Panda.HW_TYPE_GREY_PANDA), param(panda_type=Panda.HW_TYPE_BLACK_PANDA) ]) test_all_pandas = parameterized( Panda.list() ) test_white_and_grey = parameterized([ param(panda_type=Panda.HW_TYPE_WHITE_PANDA), param(panda_type=Panda.HW_TYPE_GREY_PANDA) ]) test_white = parameterized([ param(panda_type=Panda.HW_TYPE_WHITE_PANDA) ]) test_grey = parameterized([ param(panda_type=Panda.HW_TYPE_GREY_PANDA) ]) test_two_panda = parameterized([ param(panda_type=[Panda.HW_TYPE_GREY_PANDA, Panda.HW_TYPE_WHITE_PANDA]), param(panda_type=[Panda.HW_TYPE_WHITE_PANDA, Panda.HW_TYPE_GREY_PANDA]), param(panda_type=[Panda.HW_TYPE_BLACK_PANDA, Panda.HW_TYPE_BLACK_PANDA])
def test_get_serial_wifi(): connect_wifi() p = Panda("WIFI") print(p.get_serial())
def test_state_no_change(self): panda = Panda() panda.eat() self.assertNotEqual(panda._state, panda.STATE_EATING)
def test_kill(self): panda = Panda() panda.kill() self.assertFalse(panda.get_alive())
def test_calculate_happiness(self): panda = Panda() panda.update_dirty(panda.NEGATIVE_UPDATE) self.assertEqual(panda.get_happiness(), 0.9)
import os import sys import time import select sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..")) from panda import Panda setcolor = ["\033[1;32;40m", "\033[1;31;40m"] unsetcolor = "\033[00m" if __name__ == "__main__": port_number = int(os.getenv("PORT", 0)) serials = Panda.list() if os.getenv("SERIAL"): serials = filter(lambda x: x == os.getenv("SERIAL"), serials) pandas = list(map(lambda x: Panda(x, False), serials)) for i, p in enumerate(pandas): print("%s Panda %s%s" % (setcolor[i], p._serial, unsetcolor)) while True: for i, panda in enumerate(pandas): while True: ret = panda.serial_read(port_number) if len(ret) > 0: sys.stdout.write(setcolor[i] + ret.decode('utf8') + unsetcolor)
def __init__(self, port, baudrate=115200, timeout=0, panda=False, grey=False): self.serial_device = port self.baudrate = baudrate self.use_sendrecv = False self.read_only = False self.debug_level = 0 if panda: from panda import Panda, PandaSerial self.panda = Panda() # resetting U-Blox module self.panda.set_esp_power(0) time.sleep(0.1) self.panda.set_esp_power(1) time.sleep(0.5) # can't set above 9600 now... self.baudrate = 9600 self.dev = PandaSerial(self.panda, 1, self.baudrate) self.baudrate = 460800 print("upping baud:", self.baudrate) self.send_nmea("$PUBX,41,1,0007,0003,%u,0" % self.baudrate) time.sleep(0.1) self.dev = PandaSerial(self.panda, 1, self.baudrate) elif grey: import cereal.messaging as messaging class BoarddSerial(): def __init__(self): self.ubloxRaw = messaging.sub_sock('ubloxRaw') self.buf = "" def read(self, n): for msg in messaging.drain_sock(self.ubloxRaw, len(self.buf) < n): self.buf += msg.ubloxRaw ret = self.buf[:n] self.buf = self.buf[n:] return ret def write(self, dat): pass self.dev = BoarddSerial() else: if self.serial_device.startswith("tcp:"): import socket a = self.serial_device.split(':') destination_addr = (a[1], int(a[2])) self.dev = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.dev.connect(destination_addr) self.dev.setblocking(1) self.dev.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1) self.use_sendrecv = True elif os.path.isfile(self.serial_device): self.read_only = True self.dev = open(self.serial_device, mode='rb') else: import serial self.dev = serial.Serial(self.serial_device, baudrate=self.baudrate, dsrdtr=False, rtscts=False, xonxoff=False, timeout=timeout) self.logfile = None self.log = None self.preferred_dynamic_model = None self.preferred_usePPP = None self.preferred_dgps_timeout = None
class UBlox: '''main UBlox control class. port can be a file (for reading only) or a serial device ''' def __init__(self, port, baudrate=115200, timeout=0, panda=False, grey=False): self.serial_device = port self.baudrate = baudrate self.use_sendrecv = False self.read_only = False self.debug_level = 0 if panda: from panda import Panda, PandaSerial self.panda = Panda() # resetting U-Blox module self.panda.set_esp_power(0) time.sleep(0.1) self.panda.set_esp_power(1) time.sleep(0.5) # can't set above 9600 now... self.baudrate = 9600 self.dev = PandaSerial(self.panda, 1, self.baudrate) self.baudrate = 460800 print("upping baud:", self.baudrate) self.send_nmea("$PUBX,41,1,0007,0003,%u,0" % self.baudrate) time.sleep(0.1) self.dev = PandaSerial(self.panda, 1, self.baudrate) elif grey: import cereal.messaging as messaging class BoarddSerial(): def __init__(self): self.ubloxRaw = messaging.sub_sock('ubloxRaw') self.buf = "" def read(self, n): for msg in messaging.drain_sock(self.ubloxRaw, len(self.buf) < n): self.buf += msg.ubloxRaw ret = self.buf[:n] self.buf = self.buf[n:] return ret def write(self, dat): pass self.dev = BoarddSerial() else: if self.serial_device.startswith("tcp:"): import socket a = self.serial_device.split(':') destination_addr = (a[1], int(a[2])) self.dev = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.dev.connect(destination_addr) self.dev.setblocking(1) self.dev.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1) self.use_sendrecv = True elif os.path.isfile(self.serial_device): self.read_only = True self.dev = open(self.serial_device, mode='rb') else: import serial self.dev = serial.Serial(self.serial_device, baudrate=self.baudrate, dsrdtr=False, rtscts=False, xonxoff=False, timeout=timeout) self.logfile = None self.log = None self.preferred_dynamic_model = None self.preferred_usePPP = None self.preferred_dgps_timeout = None def close(self): '''close the device''' self.dev.close() self.dev = None def set_debug(self, debug_level): '''set debug level''' self.debug_level = debug_level def debug(self, level, msg): '''write a debug message''' if self.debug_level >= level: print(msg) def set_logfile(self, logfile, append=False): '''setup logging to a file''' if self.log is not None: self.log.close() self.log = None self.logfile = logfile if self.logfile is not None: if append: mode = 'ab' else: mode = 'wb' self.log = open(self.logfile, mode=mode) def set_preferred_dynamic_model(self, model): '''set the preferred dynamic model for receiver''' self.preferred_dynamic_model = model if model is not None: self.configure_poll(CLASS_CFG, MSG_CFG_NAV5) def set_preferred_dgps_timeout(self, timeout): '''set the preferred DGPS timeout for receiver''' self.preferred_dgps_timeout = timeout if timeout is not None: self.configure_poll(CLASS_CFG, MSG_CFG_NAV5) def set_preferred_usePPP(self, usePPP): '''set the preferred usePPP setting for the receiver''' if usePPP is None: self.preferred_usePPP = None return self.preferred_usePPP = int(usePPP) self.configure_poll(CLASS_CFG, MSG_CFG_NAVX5) def nmea_checksum(self, msg): d = msg[1:] cs = 0 for i in d: cs ^= ord(i) return cs def write(self, buf): '''write some bytes''' if not self.read_only: if self.use_sendrecv: return self.dev.send(buf) if type(buf) == str: return self.dev.write(str.encode(buf)) else: return self.dev.write(buf) def read(self, n): '''read some bytes''' if self.use_sendrecv: import socket try: return self.dev.recv(n) except socket.error: return '' return self.dev.read(n) def send_nmea(self, msg): if not self.read_only: s = msg + "*%02X" % self.nmea_checksum(msg) + "\r\n" self.write(s) def set_binary(self): '''put a UBlox into binary mode using a NMEA string''' if not self.read_only: print("try set binary at %u" % self.baudrate) self.send_nmea("$PUBX,41,0,0007,0001,%u,0" % self.baudrate) self.send_nmea("$PUBX,41,1,0007,0001,%u,0" % self.baudrate) self.send_nmea("$PUBX,41,2,0007,0001,%u,0" % self.baudrate) self.send_nmea("$PUBX,41,3,0007,0001,%u,0" % self.baudrate) self.send_nmea("$PUBX,41,4,0007,0001,%u,0" % self.baudrate) self.send_nmea("$PUBX,41,5,0007,0001,%u,0" % self.baudrate) def disable_nmea(self): ''' stop sending all types of nmea messages ''' self.send_nmea("$PUBX,40,GSV,1,1,1,1,1,0") self.send_nmea("$PUBX,40,GGA,0,0,0,0,0,0") self.send_nmea("$PUBX,40,GSA,0,0,0,0,0,0") self.send_nmea("$PUBX,40,VTG,0,0,0,0,0,0") self.send_nmea("$PUBX,40,TXT,0,0,0,0,0,0") self.send_nmea("$PUBX,40,RMC,0,0,0,0,0,0") def seek_percent(self, pct): '''seek to the given percentage of a file''' self.dev.seek(0, 2) filesize = self.dev.tell() self.dev.seek(pct * 0.01 * filesize) def special_handling(self, msg): '''handle automatic configuration changes''' if msg.name() == 'CFG_NAV5': msg.unpack() sendit = False pollit = False if self.preferred_dynamic_model is not None and msg.dynModel != self.preferred_dynamic_model: msg.dynModel = self.preferred_dynamic_model sendit = True pollit = True if self.preferred_dgps_timeout is not None and msg.dgpsTimeOut != self.preferred_dgps_timeout: msg.dgpsTimeOut = self.preferred_dgps_timeout self.debug(2, "Setting dgpsTimeOut=%u" % msg.dgpsTimeOut) sendit = True # we don't re-poll for this one, as some receivers refuse to set it if sendit: msg.pack() self.send(msg) if pollit: self.configure_poll(CLASS_CFG, MSG_CFG_NAV5) if msg.name() == 'CFG_NAVX5' and self.preferred_usePPP is not None: msg.unpack() if msg.usePPP != self.preferred_usePPP: msg.usePPP = self.preferred_usePPP msg.mask = 1 << 13 msg.pack() self.send(msg) self.configure_poll(CLASS_CFG, MSG_CFG_NAVX5) def receive_message(self, ignore_eof=False): '''blocking receive of one ublox message''' msg = UBloxMessage() while True: n = msg.needed_bytes() b = self.read(n) if not b: if ignore_eof: time.sleep(0.01) continue if len(msg._buf) > 0: self.debug(1, "dropping %d bytes" % len(msg._buf)) return None msg.add(b) if self.log is not None: self.log.write(b) self.log.flush() if msg.valid(): self.special_handling(msg) return msg def receive_message_noerror(self, ignore_eof=False): '''blocking receive of one ublox message, ignoring errors''' try: return self.receive_message(ignore_eof=ignore_eof) except UBloxError as e: print(e) return None except OSError as e: # Occasionally we get hit with 'resource temporarily unavailable' # messages here on the serial device, catch them too. print(e) return None def send(self, msg): '''send a preformatted ublox message''' if not msg.valid(): self.debug(1, "invalid send") return if not self.read_only: self.write(msg._buf) def send_message(self, msg_class, msg_id, payload): '''send a ublox message with class, id and payload''' msg = UBloxMessage() msg._buf = struct.pack('<BBBBH', 0xb5, 0x62, msg_class, msg_id, len(payload)) msg._buf += payload (ck_a, ck_b) = msg.checksum(msg._buf[2:]) msg._buf += struct.pack('<BB', ck_a, ck_b) self.send(msg) def configure_solution_rate(self, rate_ms=200, nav_rate=1, timeref=0): '''configure the solution rate in milliseconds''' payload = struct.pack('<HHH', rate_ms, nav_rate, timeref) self.send_message(CLASS_CFG, MSG_CFG_RATE, payload) def configure_message_rate(self, msg_class, msg_id, rate): '''configure the message rate for a given message''' payload = struct.pack('<BBB', msg_class, msg_id, rate) self.send_message(CLASS_CFG, MSG_CFG_SET_RATE, payload) def configure_port(self, port=1, inMask=3, outMask=3, mode=2240, baudrate=None): '''configure a IO port''' if baudrate is None: baudrate = self.baudrate payload = struct.pack('<BBH8BHHBBBB', port, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, inMask, outMask, 0, 0, 0, 0) self.send_message(CLASS_CFG, MSG_CFG_PRT, payload) def configure_loadsave(self, clearMask=0, saveMask=0, loadMask=0, deviceMask=0): '''configure configuration load/save''' payload = struct.pack('<IIIB', clearMask, saveMask, loadMask, deviceMask) self.send_message(CLASS_CFG, MSG_CFG_CFG, payload) def configure_poll(self, msg_class, msg_id, payload=b''): '''poll a configuration message''' self.send_message(msg_class, msg_id, payload) def configure_poll_port(self, portID=None): '''poll a port configuration''' if portID is None: self.configure_poll(CLASS_CFG, MSG_CFG_PRT) else: self.configure_poll(CLASS_CFG, MSG_CFG_PRT, struct.pack('<B', portID)) def configure_min_max_sats(self, min_sats=4, max_sats=32): '''Set the minimum/maximum number of satellites for a solution in the NAVX5 message''' payload = struct.pack('<HHIBBBBBBBBBBHIBBBBBBHII', 0, 4, 0, 0, 0, min_sats, max_sats, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) self.send_message(CLASS_CFG, MSG_CFG_NAVX5, payload) def module_reset(self, set, mode): ''' Reset the module for hot/warm/cold start''' payload = struct.pack('<HBB', set, mode, 0) self.send_message(CLASS_CFG, MSG_CFG_RST, payload)
def update_panda(): with open(os.path.join(BASEDIR, "VERSION")) as f: repo_version = f.read() #repo_version += "-EON" if os.path.isfile('/EON') else "-DEV" repo_version += "-EON-unknown-DEBUG" panda = None panda_dfu = None cloudlog.info("Connecting to panda") while True: # break on normal mode Panda panda_list = Panda.list() if len(panda_list) > 0: cloudlog.info("Panda found, connecting") panda = Panda(panda_list[0]) break # flash on DFU mode Panda panda_dfu = PandaDFU.list() if len(panda_dfu) > 0: cloudlog.info("Panda in DFU mode found, flashing recovery") panda_dfu = PandaDFU(panda_dfu[0]) panda_dfu.recover() print "waiting for board..." time.sleep(1) current_version = "bootstub" if panda.bootstub else str( panda.get_version()) cloudlog.info("Panda connected, version: %s, expected %s" % (current_version, repo_version)) if panda.bootstub or not current_version.startswith(repo_version): cloudlog.info("Panda firmware out of date, update required") signed_fn = os.path.join(BASEDIR, "board", "obj", "panda.bin.signed") if os.path.exists(signed_fn): cloudlog.info("Flashing signed firmware") panda.flash(fn=signed_fn) else: cloudlog.info("Building and flashing unsigned firmware") panda.flash() cloudlog.info("Done flashing") if panda.bootstub: cloudlog.info( "Flashed firmware not booting, flashing development bootloader") panda.recover() cloudlog.info("Done flashing bootloader") if panda.bootstub: cloudlog.info("Panda still not booting, exiting") raise AssertionError version = str(panda.get_version()) if not version.startswith(repo_version): cloudlog.info("Version mismatch after flashing, exiting") raise AssertionError
raise ValueError("Data must not be longer than 0x10") dat = struct.pack("HH", endpoint, len(data)) + data return self.transact(dat) 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(0x200, b"\xce\xfa\xad\xde\x1e\x0b\xb0\x02", 0) exit(0) else: p.can_send(0x200, b"\xce\xfa\xad\xde\x1e\x0b\xb0\x0a", 0) if args.fn: time.sleep(0.1) print("flashing", args.fn)
class DoubleEnv(): def __init__(self): # create simulation (GUI) self.urdfRootPath = pybullet_data.getDataPath() p.connect(p.GUI) p.setGravity(0, 0, -9.81) # set up camera self._set_camera() # load some scene objects p.loadURDF(os.path.join(self.urdfRootPath, "plane.urdf"), basePosition=[0, 0, -0.65]) p.loadURDF(os.path.join(self.urdfRootPath, "table/table.urdf"), basePosition=[0.5, 0, -0.65]) p.loadURDF(os.path.join(self.urdfRootPath, "table/table.urdf"), basePosition=[0.5, 1, -0.65]) # example YCB object obj1 = YCBObject('003_cracker_box') obj1.load() p.resetBasePositionAndOrientation(obj1.body_id, [0.7, -0.2, 0.1], [0, 0, 0, 1]) # example RBO object obj2 = RBOObject('book') obj2.load() p.resetBasePositionAndOrientation(obj2.body_id, [0.8, 1.1, 0.5], [0, 0, 1, 1]) # load a panda robot self.panda1 = Panda([0, 0, 0]) self.panda2 = Panda([0, 1, 0]) def reset(self): self.panda1.reset() self.panda2.reset() return [self.panda1.state, self.panda2.state] def close(self): p.disconnect() def step(self, action): # get current state state = [self.panda1.state, self.panda2.state] # action in this example is the end-effector velocity action1 = [action[0], action[1], action[2]] action2 = [action[3], action[4], action[5]] self.panda1.step(dposition=action1) self.panda2.step(dposition=action2) # take simulation step p.stepSimulation() # return next_state, reward, done, info next_state = [self.panda1.state, self.panda2.state] reward = 0.0 done = False info = {} return next_state, reward, done, info def render(self): (width, height, pxl, depth, segmentation) = p.getCameraImage(width=self.camera_width, height=self.camera_height, viewMatrix=self.view_matrix, projectionMatrix=self.proj_matrix) rgb_array = np.array(pxl, dtype=np.uint8) rgb_array = np.reshape(rgb_array, (self.camera_height, self.camera_width, 4)) rgb_array = rgb_array[:, :, :3] return rgb_array def _set_camera(self): self.camera_width = 256 self.camera_height = 256 p.resetDebugVisualizerCamera(cameraDistance=1.5, cameraYaw=20, cameraPitch=-30, cameraTargetPosition=[0.5, -0.2, 0.0]) self.view_matrix = p.computeViewMatrixFromYawPitchRoll( cameraTargetPosition=[0.5, 0, 0], distance=1.0, yaw=90, pitch=-50, roll=0, upAxisIndex=2) self.proj_matrix = p.computeProjectionMatrixFOV( fov=60, aspect=float(self.camera_width) / self.camera_height, nearVal=0.1, farVal=100.0)
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_NOOUTPUT (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_NOOUTPUT) 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
class TestPanda(unittest.TestCase): def setUp(self): self.ivo = Panda("Ivo", "*****@*****.**", "male") def test_panda_init(self): self.assertEqual(self.ivo.name(), "Ivo") self.assertEqual(self.ivo.gender(), "male") self.assertEqual(self.ivo.email(), "*****@*****.**") # def test_panda_mail_is_not_valid(self): # with self.assertRaises(ValueError): # Panda("Rado", "*****@*****.**", "male") def test_panda_str(self): self.assertEqual(str(self.ivo), "Ivo is a male panda with email: [email protected]") # def test_panda_repr(self): # pass def test_panda_eq(self): ivo2 = Panda("Ivo", "*****@*****.**", "male") rado = Panda("Rado", "*****@*****.**", "male") self.assertEqual(self.ivo, ivo2) self.assertNotEqual(self.ivo, rado) # def test_hash(self): # pass def test_name(self): self.assertEqual(self.ivo.name(), "Ivo") self.assertNotEqual(self.ivo.name(), "Rado") def test_mail(self): self.assertEqual(self.ivo.email(), "*****@*****.**") self.assertNotEqual(self.ivo.email(), "*****@*****.**") def test_gender(self): self.assertEqual(self.ivo.gender(), "male") self.assertNotEqual(self.ivo.gender(), "female") def test_isMale(self): mimi = Panda("Mimi", "*****@*****.**", "female") self.assertTrue(self.ivo.isMale()) self.assertFalse(mimi.isMale()) def test_isFemale(self): mimi = Panda("Mimi", "*****@*****.**", "female") self.assertFalse(self.ivo.isFemale()) self.assertTrue(mimi.isFemale())
def setUp(self): self.ivo = Panda("Ivo", "*****@*****.**", "male")
from random import random from time import sleep from threading import Thread, Event app = Flask(__name__) app.use_reloader = False app.debug = False app.config['SECRET_KEY'] = 'secret!' app.config['DEBUG'] = True #turn the flask app into a socketio app socketio = SocketIO(app, async_mode=None, logger=True, engineio_logger=True, debug=False, use_reloader=False) panda = Panda("x86_64", mem="1G",qcow="bionic-server-cloudimg-amd64-noaslr-nokaslr.qcow2", expect_prompt=rb"root@ubuntu:.*", extra_args=["-nographic", "-net", "nic,netdev=net0", "-netdev", "user,id=net0,", ]) panda.set_os_name("linux-64-ubuntu:4.15.0-72-generic-noaslr-nokaslr") class Process(object): def __init__(self, proc_object): self.pid = proc_object.pid self.ppid = proc_object.ppid self.start_time = proc_object.create_time try: self.name = ffi.string(proc_object.name).decode() except: self.name = "?"
def test_update_sleepy(self): panda = Panda() panda.update_sleepy(panda.NEGATIVE_UPDATE) panda.update_sleepy(panda.NEGATIVE_UPDATE) self.assertEqual(panda.get_sleep(), 0.5)
#!/usr/bin/env python import os import sys import datetime sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..")) from panda import Panda if __name__ == "__main__": p = Panda() p.set_datetime(datetime.datetime.now()) print(p.get_datetime())
def test_healing_state(self): panda = Panda() panda.update_ill(panda.NEGATIVE_UPDATE) panda.heal() self.assertEqual(panda._state, panda.STATE_HEALING)
app.config['suppress_callback_exceptions'] = True app.css.config.serve_locally = True app.scripts.config.serve_locally = True # Boostrap CSS file (local) @app.server.route('/static/<path:path>') def static_file(path): static_folder = os.path.join(os.getcwd(), 'static') return send_from_directory(static_folder, path) # Global variables and initialization # Open panda device (comma ai) and clear the buffer panda_port = get_panda_id('ford_fusion', 'send') PANDA = Panda(panda_port) PANDA.can_clear(0xFFFF) PANDA.set_safety_mode(Panda.SAFETY_ALLOUTPUT) # Send request to broadcast leddar messages dat = '0301000000000000' PANDA.can_send(0x740, dat.decode('hex'), 1) # DBC files: car and leddar base_path = dirname(abspath(__file__)) leddar = join(base_path, 'dbc_files/leddar_vu_8_segments.dbc') car = join(base_path, 'dbc_files/ford_fusion_2011.dbc') CAR_DBC = cantools.database.load_file(car) LEDDAR_DBC = cantools.database.load_file(leddar) SPEED = 0 PEDAL_MODEL = PM('ford_fusion') DEV = get_nidaqmx_dev_name()
def flash_panda(panda_serial: str) -> Panda: panda = Panda(panda_serial) fw_signature = get_expected_signature(panda) panda_version = "bootstub" if panda.bootstub else panda.get_version() panda_signature = b"" if panda.bootstub else panda.get_signature() cloudlog.warning(f"Panda {panda_serial} connected, version: {panda_version}, signature {panda_signature.hex()[:16]}, expected {fw_signature.hex()[:16]}") if panda.bootstub or panda_signature != fw_signature: cloudlog.info("Panda firmware out of date, update required") panda.flash() cloudlog.info("Done flashing") if panda.bootstub: spinner = Spinner() spinner.update("Restoring panda") panda.recover() spinner.close() if panda.bootstub: spinner = Spinner() spinner.update("Restoring panda") try: if panda.get_mcu_type() == MCU_TYPE_H7: subprocess.run("cd /data/openpilot/panda/board; ./recover_h7.sh", capture_output=True, shell=True) else: subprocess.run("cd /data/openpilot/panda/board; ./recover.sh", capture_output=True, shell=True) panda.reset() panda.reconnect() finally: spinner.close() if panda.bootstub: cloudlog.info("Panda still not booting, exiting") raise AssertionError panda_signature = panda.get_signature() if panda_signature != fw_signature: cloudlog.info("Version mismatch after flashing, exiting") raise AssertionError return panda
#!/usr/bin/env python3 ''' example_multiple_callbacks.py This example registers the before_block_exec and after_block_exec callbacks and prints a message and sleeps each time the callback is hit. Run with: python3 example_multiple_callbacks.py ''' from time import sleep from sys import argv from panda import Panda # Single arg of arch, defaults to i386 arch = "i386" if len(argv) <= 1 else argv[1] panda = Panda(generic=arch) recording_name = "test.recording" ctr = 0 @panda.cb_before_block_exec() def my_before_block_execute(cpustate, transblock): print("before block in python... sleeping 1s") sleep(1) @panda.cb_after_block_exec() def my_after_block_execute(cpustate, transblock, exit): print("after block in python")
def test_flash_wifi(serials=None): connect_wifi(serials[0]) assert Panda.flash_ota_wifi(release=False), "OTA Wifi Flash Failed" connect_wifi(serials[0])
"(Lane Assist). Useful for enabling HCA on cars without factory Lane Assist that want to use " + \ "openpilot integrated at the CAN gateway (J533)." epilog_text = "This tool is meant to run directly on a vehicle-installed comma two or comma three, with the " + \ "openpilot/tmux processes stopped. It should also work on a separate PC with a USB-attached comma " + \ "panda. Vehicle ignition must be on. Recommend engine not be running when making changes. Must " + \ "turn ignition off and on again for any changes to take effect." parser = argparse.ArgumentParser(description=desc_text, epilog=epilog_text) parser.add_argument("--debug", action="store_true", help="enable ISO-TP/UDS stack debugging output") parser.add_argument("action", choices={"show", "enable", "disable"}, help="show or modify current EPS HCA config") args = parser.parse_args() panda = Panda() panda.set_safety_mode(Panda.SAFETY_ELM327) bus = 1 if panda.has_obd() else 0 uds_client = UdsClient(panda, MQB_EPS_CAN_ADDR, MQB_EPS_CAN_ADDR + RX_OFFSET, bus, timeout=0.2, debug=args.debug) try: uds_client.diagnostic_session_control(SESSION_TYPE.EXTENDED_DIAGNOSTIC) except MessageTimeoutError: print("Timeout opening session with EPS") quit()
def test_get_serial_in_flash_mode(): p = Panda() p.reset(enter_bootstub=True) assert(p.bootstub) print(p.get_serial()) p.reset()
from panda import Panda, blocking, ffi panda = Panda(generic="i386") panda.load_plugin("syscalls2") (execve_entered, execve_returned) = (False, False) # Callback to run when we enter execve @panda.ppp("syscalls2", "on_sys_execve_enter") def on_sys_execve_enter(cpu, pc, fname_ptr, argv_ptr, envp): global execve_entered execve_entered = True # Callback to run when we return from execve @panda.ppp("syscalls2", "on_sys_execve_return") def on_sys_execve_return(cpu, pc, fname_ptr, argv_ptr, envp): global execve_returned execve_returned = True # In a separate thread, revert the test, run `whoami` and then end our analysis @blocking def guest_cmds(): panda.revert_sync("root") print("Username is", panda.run_serial_cmd("whoami")) panda.end_analysis() # Queue functions to run once guest starts, then start the guest panda.queue_async(guest_cmds) panda.run() assert(execve_entered), "Syscalls never called execve enter"
def test_wifi_flash_st(): Panda.flash_ota_st()
def connect_wifi(serial=None): p = Panda(serial=serial) p.set_esp_power(True) dongle_id, pw = p.get_serial() assert (dongle_id.isalnum()) _connect_wifi(dongle_id, pw)
def update_panda(): panda = None panda_dfu = None cloudlog.info("Connecting to panda") while True: # break on normal mode Panda panda_list = Panda.list() if len(panda_list) > 0: cloudlog.info("Panda found, connecting") panda = Panda(panda_list[0]) break # flash on DFU mode Panda panda_dfu = PandaDFU.list() if len(panda_dfu) > 0: cloudlog.info("Panda in DFU mode found, flashing recovery") panda_dfu = PandaDFU(panda_dfu[0]) panda_dfu.recover() time.sleep(1) fw_fn = get_firmware_fn() fw_signature = get_expected_signature(fw_fn) try: serial = panda.get_serial()[0].decode("utf-8") except Exception: serial = None panda_version = "bootstub" if panda.bootstub else panda.get_version() panda_signature = b"" if panda.bootstub else panda.get_signature() cloudlog.warning( "Panda %s connected, version: %s, signature %s, expected %s" % ( serial, panda_version, panda_signature.hex(), fw_signature.hex(), )) if panda.bootstub or panda_signature != fw_signature: cloudlog.info("Panda firmware out of date, update required") panda.flash(fw_fn) cloudlog.info("Done flashing") if panda.bootstub: bootstub_version = panda.get_version() cloudlog.info( f"Flashed firmware not booting, flashing development bootloader. Bootstub version: {bootstub_version}" ) panda.recover() cloudlog.info("Done flashing bootloader") if panda.bootstub: cloudlog.info("Panda still not booting, exiting") raise AssertionError panda_signature = panda.get_signature() if panda_signature != fw_signature: cloudlog.info("Version mismatch after flashing, exiting") raise AssertionError
#!/usr/bin/env python3 import os import sys import struct import time sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..")) from panda import Panda # noqa: E402 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_safety_mode(Panda.SAFETY_ALLOUTPUT) a = 0 while True: # flood msg = b"\xaa" * 4 + struct.pack("I", a) p.can_send(0xaa, msg, 0)
def test_isFemale(self): mimi = Panda("Mimi", "*****@*****.**", "female") self.assertFalse(self.ivo.isFemale()) self.assertTrue(mimi.isFemale())
#!/usr/bin/env python3 from sys import argv from panda import blocking, Panda # No arguments, i386. Otherwise argument should be guest arch generic_type = argv[1] if len(argv) > 1 else "i386" panda = Panda(generic=generic_type) @blocking def run_cmd(): # First revert to root snapshot, then type a command via serial panda.revert_sync("root") print(panda.run_serial_cmd("uname -a")) print("Finding cat in cat's memory map:") maps = panda.run_serial_cmd("cat /proc/self/maps") for line in maps.split("\n"): if "cat" in line: print(line) panda.end_analysis() panda.queue_async(run_cmd) panda.run()
def test_below_limit_update(self): panda = Panda() for i in range(1, 10): panda.update_hungry(panda.NEGATIVE_UPDATE) self.assertEqual(panda.get_feed(), 0.0)
#!/usr/bin/env python3 import os import sys import random sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..")) from panda import Panda # noqa: E402 def get_test_string(): return b"test" + os.urandom(10) if __name__ == "__main__": p = Panda() p.set_safety_mode(Panda.SAFETY_ALLOUTPUT) print("Spamming all buses...") while True: at = random.randint(1, 2000) st = get_test_string()[0:8] bus = random.randint(0, 2) p.can_send(at, st, bus) # print("Sent message on bus: ", bus)
def test_update_ill(self): panda = Panda() panda.update_ill(panda.NEGATIVE_UPDATE) self.assertEqual(panda.get_cure(), 0.5)
def flash_release(path=None, st_serial=None): from panda import Panda, PandaDFU from zipfile import ZipFile def status(x): print("\033[1;32;40m" + x + "\033[00m") if st_serial is not None: # look for Panda panda_list = Panda.list() if len(panda_list) == 0: raise Exception( "panda not found, make sure it's connected and your user can access it" ) elif len(panda_list) > 1: raise Exception("Please only connect one panda") st_serial = panda_list[0] print("Using panda with serial %s" % st_serial) if path is None: print( "Fetching latest firmware from github.com/commaai/panda-artifacts") r = requests.get( "https://raw.githubusercontent.com/commaai/panda-artifacts/master/latest.json" ) url = json.loads(r.text)['url'] r = requests.get(url) print("Fetching firmware from %s" % url) path = io.BytesIO(r.content) zf = ZipFile(path) zf.printdir() version = zf.read("version").decode().strip() status("0. Preparing to flash " + str(version)) code_bootstub = zf.read("bootstub.panda.bin") code_panda = zf.read("panda.bin") # enter DFU mode status("1. Entering DFU mode") panda = Panda(st_serial) panda.reset(enter_bootstub=True) panda.reset(enter_bootloader=True) time.sleep(1) # program bootstub status("2. Programming bootstub") dfu = PandaDFU(PandaDFU.st_serial_to_dfu_serial(st_serial)) dfu.program_bootstub(code_bootstub) time.sleep(1) # flash main code status("3. Flashing main code") panda = Panda(st_serial) panda.flash(code=code_panda) panda.close() # check for connection status("4. Verifying version") panda = Panda(st_serial) my_version = panda.get_version() print("dongle id: %s" % panda.get_serial()[0]) print(my_version, "should be", version) assert (str(version) == str(my_version)) # done! status("6. Success!")
def test_update_dirty(self): panda = Panda() panda.update_dirty(panda.NEGATIVE_UPDATE) panda.update_dirty(panda.NEGATIVE_UPDATE) self.assertEqual(panda.get_clean(), 0.0)
def test_get_serial_wifi(serials=None): connect_wifi(serials[0]) p = Panda("WIFI") print(p.get_serial())
def test_dead_state(self): panda = Panda() panda.kill() self.assertEqual(panda._state, panda.STATE_DEAD)
def flash_release(path=None, st_serial=None): from panda import Panda, PandaDFU, ESPROM, CesantaFlasher from zipfile import ZipFile def status(x): print("\033[1;32;40m" + x + "\033[00m") if st_serial == None: # look for Panda panda_list = Panda.list() if len(panda_list) == 0: raise Exception( "panda not found, make sure it's connected and your user can access it" ) elif len(panda_list) > 1: raise Exception("Please only connect one panda") st_serial = panda_list[0] print("Using panda with serial %s" % st_serial) if path == None: print( "Fetching latest firmware from github.com/commaai/panda-artifacts") r = requests.get( "https://raw.githubusercontent.com/commaai/panda-artifacts/master/latest.json" ) url = json.loads(r.text)['url'] r = requests.get(url) print("Fetching firmware from %s" % url) path = StringIO.StringIO(r.content) zf = ZipFile(path) zf.printdir() version = zf.read("version") status("0. Preparing to flash " + version) code_bootstub = zf.read("bootstub.panda.bin") code_panda = zf.read("panda.bin") code_boot_15 = zf.read("boot_v1.5.bin") code_boot_15 = code_boot_15[0:2] + "\x00\x30" + code_boot_15[4:] code_user1 = zf.read("user1.bin") code_user2 = zf.read("user2.bin") # enter DFU mode status("1. Entering DFU mode") panda = Panda(st_serial) panda.enter_bootloader() time.sleep(1) # program bootstub status("2. Programming bootstub") dfu = PandaDFU(PandaDFU.st_serial_to_dfu_serial(st_serial)) dfu.program_bootstub(code_bootstub) time.sleep(1) # flash main code status("3. Flashing main code") panda = Panda(st_serial) panda.flash(code=code_panda) panda.close() # flashing ESP status("4. Flashing ESP (slow!)") align = lambda x, sz=0x1000: x + "\xFF" * ((sz - len(x)) % sz) esp = ESPROM(st_serial) esp.connect() flasher = CesantaFlasher(esp, 230400) flasher.flash_write(0x0, align(code_boot_15), True) flasher.flash_write(0x1000, align(code_user1), True) flasher.flash_write(0x81000, align(code_user2), True) flasher.flash_write(0x3FE000, "\xFF" * 0x1000) flasher.boot_fw() del flasher del esp time.sleep(1) # check for connection status("5. Verifying version") panda = Panda(st_serial) my_version = panda.get_version() print("dongle id: %s" % panda.get_serial()[0]) print(my_version, "should be", version) assert (str(version) == str(my_version)) # done! status("6. Success!")
def test_playing_state(self): panda = Panda() panda.update_playful(panda.NEGATIVE_UPDATE) panda.play() self.assertEqual(panda._state, panda.STATE_PLAYING)
default=0x7DF) # default is functional (broadcast) address parser.add_argument("--bus", type=int, default=0) parser.add_argument('--debug', action='store_true') args = parser.parse_args() try: check_output(["pidof", "boardd"]) print( "boardd is running, please kill openpilot before running this script! (aborted)" ) sys.exit(1) except CalledProcessError as e: if e.returncode != 1: # 1 == no process found (boardd not running) raise e panda = Panda() panda.set_safety_mode(Panda.SAFETY_ELM327) uds_client = UdsClient(panda, args.addr, bus=args.bus, debug=args.debug) print("extended diagnostic session ...") try: uds_client.diagnostic_session_control(SESSION_TYPE.EXTENDED_DIAGNOSTIC) except MessageTimeoutError: # functional address isn't properly handled so a timeout occurs if args.addr != 0x7DF: raise print("clear diagnostic info ...") try: uds_client.clear_diagnostic_information(DTC_GROUP_TYPE.ALL) except MessageTimeoutError: # functional address isn't properly handled so a timeout occurs if args.addr != 0x7DF:
def test_above_limit_update(self): panda = Panda() panda.update_hungry(panda.POSITIVE_UPDATE) self.assertEqual(panda.get_feed(), 1.0)
#!/usr/bin/env python3 from sys import argv, path import time import pickle path.append("..") from panda import Panda from panda.helper.x86 import * # Single arg of arch, defaults to i386 arch = "i386" if len(argv) <= 1 else argv[1] extra = "-nographic -chardev socket,id=monitor,path=./monitor.sock,server,nowait -monitor chardev:monitor -serial telnet:127.0.0.1:4444,server,nowait" panda = Panda(generic=arch, extra_args=extra) with open("libc_syms.pickle", "rb") as f: libc = pickle.load(f) f = open("fwrite.out", "wb") @panda.hook_single_insn("fwrite_hook", libc["fwrite"], libraryname="libc", kernel=False) def fwrite_hook(cpustate, tb): # grab arguments ESP, arg1, arg2, arg3... ret = ffi.new("uint32_t[]", 5) size = ffi.cast("target_ptr_t", ffi.sizeof(ret)) faddr = ffi.cast("target_ptr_t", cpustate.env_ptr.regs[R_ESP]) # esp panda.virtual_memory_read(cpustate, faddr, ret, size) # XXX bad argus for virtual_memory_write string_arg = ffi.new("char[]", ret[2] * ret[3])
#!/usr/bin/env python3 import os from sys import argv from os import path from panda import Panda, blocking, ffi from panda.x86.helper import * # XXX omg these are 32-bit names from subprocess import Popen import docker arch = "x86_64" if len(argv) <= 1 else argv[1] panda = Panda( arch=arch, qcow="/home/luke/workspace/qcows/bionic-server-cloudimg-amd64.qcow2", extra_args="-nographic", expect_prompt=rb"root@ubuntu.*#", mem="1G") interesting_file_name = b"fakefile" panda.set_os_name("linux-64-ubuntu") panda.load_plugin("callstack_instr", args={"stack_type": "asid"}) panda.require("syscalls2") @blocking def mycmd(): panda.revert_sync("root") global kernel_version kernel_version = panda.run_serial_cmd("uname -r") #print("GUEST RUNNING COMMAND:\n\n# cat fakefile\n" + panda.run_serial_cmd("cat fakefile")) #panda.revert_sync("strace")
def _connect_wifi(dongle_id, pw, insecure_okay=False): ssid = str("panda-" + dongle_id) r = subprocess.call(["ping", "-W", "4", "-c", "1", "192.168.0.10"], stdout=FNULL, stderr=subprocess.STDOUT) if not r: #Can already ping, try connecting on wifi try: p = Panda("WIFI") p.get_serial() print("Already connected") return except: pass print("WIFI: connecting to %s" % ssid) while 1: if sys.platform == "darwin": os.system("networksetup -setairportnetwork en0 %s %s" % (ssid, pw)) else: wlan_interface = subprocess.check_output(["sh", "-c", "iw dev | awk '/Interface/ {print $2}'"]).strip() cnt = 0 MAX_TRIES = 10 while cnt < MAX_TRIES: print("WIFI: scanning %d" % cnt) os.system("iwlist %s scanning > /dev/null" % wlan_interface) os.system("nmcli device wifi rescan") wifi_scan = [x for x in subprocess.check_output(["nmcli","dev", "wifi", "list"]).split("\n") if ssid in x] if len(wifi_scan) != 0: break time.sleep(0.1) # MAX_TRIES tries, ~10 seconds max cnt += 1 assert cnt < MAX_TRIES if "-pair" in wifi_scan[0]: os.system("nmcli d wifi connect %s-pair" % (ssid)) connect_cnt = 0 MAX_TRIES = 20 while connect_cnt < MAX_TRIES: connect_cnt += 1 r = subprocess.call(["ping", "-W", "4", "-c", "1", "192.168.0.10"], stdout=FNULL, stderr=subprocess.STDOUT) if r: print("Waiting for panda to ping...") time.sleep(0.1) else: break if insecure_okay: break # fetch webpage print("connecting to insecure network to secure") try: r = requests.get("http://192.168.0.10/") except requests.ConnectionError: r = requests.get("http://192.168.0.10/") assert r.status_code==200 print("securing") try: r = requests.get("http://192.168.0.10/secure", timeout=0.01) except requests.exceptions.Timeout: print("timeout http request to secure") pass else: ret = os.system("nmcli d wifi connect %s password %s" % (ssid, pw)) if os.WEXITSTATUS(ret) == 0: #check ping too ping_ok = False connect_cnt = 0 MAX_TRIES = 10 while connect_cnt < MAX_TRIES: connect_cnt += 1 r = subprocess.call(["ping", "-W", "4", "-c", "1", "192.168.0.10"], stdout=FNULL, stderr=subprocess.STDOUT) if r: print("Waiting for panda to ping...") time.sleep(0.1) else: ping_ok = True break if ping_ok: break
# Demonstartion of using PANDA to run shellcode. Example modified from Unicorn Engine # https://github.com/unicorn-engine/unicorn/blob/master/bindings/python/sample_arm.py import capstone import os from panda import Panda, ffi from panda.helper.x86 import dump_regs, registers X86_CODE = b"\x40\x01\xC3\x41" # inc eax; add ebx, eax; inc ecx; ADDRESS = 0x1000 stop_addr = ADDRESS + len(X86_CODE) # Create a machine of type 'configurable' but with just a CPU specified (no peripherals or memory maps) panda = Panda("i386", extra_args=["-M", "configurable", "-nographic"]) @panda.cb_after_machine_init def setup(cpu): ''' After our CPU has been created, allocate memory and set starting state ''' # map 2MB memory for this emulation panda.map_memory("mymem", 2 * 1024 * 1024, ADDRESS) # Write code into memory panda.physical_memory_write(ADDRESS, X86_CODE) # Set up registers cpu.env_ptr.regs[registers["EAX"]] = 0x1
#!/usr/bin/env python3 from panda import Panda, blocking, ffi panda = Panda(generic="x86_64") panda.load_plugin("syscalls2") panda.load_plugin("osi") @panda.ppp("syscalls2", "on_sys_read_return") def on_sys_read_return(cpu, pc, fd, buf, count): proc = panda.plugins['osi'].get_current_process(cpu) procname = ffi.string(proc.name) if proc != ffi.NULL else "error" fname_ptr = panda.plugins['osi_linux'].osi_linux_fd_to_filename(cpu, proc, fd) fname = ffi.string(fname_ptr) if fname_ptr != ffi.NULL else "error" print(f"[PANDA] {procname} read from {fname}") @panda.ppp("syscalls2", "on_sys_execve_enter") def on_sys_execve_enter(cpu, pc, fname_ptr, argv_ptr, envp): # Log commands and arguments passed to execve unless in kernel if panda.in_kernel(cpu): return try: fname = panda.read_str(cpu, fname_ptr) argv_ptrlist = panda.virtual_memory_read(cpu, argv_ptr, 100, fmt='ptrlist') except ValueError: return argv = [] for ptr in argv_ptrlist: if ptr == 0: break try: argv.append(panda.read_str(cpu, ptr)) except ValueError: