def get_driver(use_ftdi=False, port=SERIAL_PORT, baud=SERIAL_BAUD, file=False, rtscts=False): """ Get a driver based on configuration options Parameters ---------- use_ftdi : bool For serial driver, use the pyftdi driver, otherwise use the pyserial driver. port : string Serial port to read. baud : int Serial port baud rate to set. """ try: if use_ftdi: return PyFTDIDriver(baud) if file: return FileDriver(open(port, 'rb')) # HACK - if we are on OSX and the device appears to be a CDC device, open as a binary file for each in serial.tools.list_ports.comports(): if port == each[0] and sys.platform == "darwin": if each[1].startswith("Gadget Serial") or each[1].startswith( "Piksi"): print("Opening a file driver") return CdcDriver(open(port, 'w+b', 0)) return PySerialDriver(port, baud, rtscts=rtscts) # if finding the driver fails we should exit with a return code # currently sbp's py serial driver raises SystemExit, so we trap it # here except SystemExit: sys.exit(1)
def main(): args = get_args() open_args = 'rb' if args.format == 'bin' else 'r' with open(args.file, open_args) as fd: if args.format == 'json': iterator = JSONLogIterator(fd) elif args.format == 'bin': driver = FileDriver(fd) iterator = Framer(driver.read, driver.write) else: raise Exception( "Usage Error: Unknown input format. Valid input formats for -f arg are bin and json." ) msg_class = None for my_id, my_class in _SBP_TABLE.iteritems(): if my_class.__name__ == args.type or (args.id and my_id == int(args.id)): print("Extracing class {} with msg_id {}".format( my_class, my_id)) msg_class = my_class assert msg_class is not None, "Invalid message type specified" with open(msg_class.__name__ + "_" + args.outfile, 'w+') as outfile: conv = MsgExtractor(outfile, msg_class, metadata=(args.format == 'json')) if args.format == 'json': iterator = iterator.next() while True: try: (msg, data) = iterator.next() if isinstance(msg, msg_class): conv._callback(msg, data) except StopIteration: break
def main(): # First, we start up an SBP driver reading from STDInput first = True args = get_args() with open(args.file, 'r') as fd: if args.format == 'json': iterator = JSONLogIterator(fd) elif args.format == 'bin': driver = FileDriver(fd) iterator = Framer(driver.read, driver.write) else: raise ("unkonwn format") with open(args.outfile, 'w+') as outfile: conv = Extractor(outfile) if args.format == 'json': iterator = iterator.next() while True: try: (msg, data) = iterator.next() if first: first = False if isinstance(msg, MsgCommandResp): conv._callback(msg) except StopIteration: break df = pd.read_csv(open(args.outfile, 'r')) fig = plt.figure(figsize=[20, 10]) plt.plot(df["tow (ms)"], df['acc_x']) plt.legend(['acc_x']) fig.savefig('acc.png')
def main(): # First, we start up an SBP driver reading from STDInput first = True args = get_args() with open(args.file, 'r') as fd: if args.format == 'json': iterator = JSONLogIterator(fd) elif args.format == 'bin': driver = FileDriver(fd) iterator = Framer(driver.read, driver.write) else: raise ("unkonwn format") with open(args.type + "_" + args.outfile, 'w+') as outfile: conv = MsgExtractor(outfile, args.type) if args.format == 'json': iterator = iterator.next() while True: try: (msg, data) = iterator.next() if first: first = False if isinstance(msg, eval(args.type)): conv._callback(msg) except StopIteration: break
def main(): args = get_args() open_args = 'rb' if args.format == 'bin' else 'r' with open(args.file, open_args) as fd: if args.format == 'json': iterator = JSONLogIterator(fd) elif args.format == 'bin': driver = FileDriver(fd) iterator = Framer(driver.read, driver.write) else: raise Exception( "Usage Error: Unknown input format. Valid input formats for -f arg are bin and json." ) msg_class = None with open(args.outfile, 'wb') as outfile: conv = MsgInjector(outfile, msg_class, metadata=(args.format == 'json')) if args.format == 'json': iterator = iterator.next() while True: try: (msg, data) = iterator.next() if msg.msg_type == SBP_MSG_IMU_RAW: conv.imu_raw_callback(msg, data) else: conv.any_callback(msg, data) except StopIteration: break
def test_log(): """ Abstract interface won't work """ log_datafile = "./data/serial_link_log_20141125-150750_test2.log.dat" with LogIterator(FileDriver(log_datafile)) as log: with pytest.raises(NotImplementedError) as exc_info: for delta, timestamp, msg in log.next(): pass assert exc_info.value.message == "next() not implemented!"
def test_pickle_log_missing(): """ Remove a key from the dispatch and make sure that the iterator chokes. """ log_datafile = "./data/serial_link_log_20141125-150750_test2.log.dat" new_table = _SBP_TABLE.copy() new_table.pop(SBP_MSG_PRINT, None) d = lambda msg: dispatch(msg, table=new_table) with PickleLogIterator(FileDriver(log_datafile), dispatcher=d) as log: with pytest.raises(InvalidSBPMessageType) as exc_info: for delta, timestamp, msg in log.next(): pass assert str(exc_info.value).find("No message found for msg_type id 16*")
def test_json_log(): """ JSON log iterator sanity tests. """ log_datafile = "./data/serial_link_log_20150310-115522-test.log.dat" count = 0 with warnings.catch_warnings(record=True) as w: with JSONLogIterator(FileDriver(log_datafile)) as log: for delta, timestamp, msg in log.next(): assert type(delta) == int assert type(timestamp) == int assert isinstance(msg, SBP) or issubclass(type(msg), SBP) count += 1 warnings.simplefilter("always") assert len(w) == 0 assert count == 2650
def main(): tow = [] hacc = [] plt.xlabel('TOW - Time of Week') plt.ylabel('Horizontal Acceleration') swiftBinary = open('28-220741.sbp', 'rb') filestream = FileDriver(swiftBinary) with Handler(Framer(filestream.read, None, verbose=True), autostart=True) as src: try: for msg, meta in src.filter(SBP_MSG_POS_LLH_GNSS): tow.append(msg.tow) hacc.append(msg.h_accuracy) except KeyboardInterrupt: pass plt.plot(tow, hacc) plt.xlim(min(tow), max(tow)) plt.ylim(min(hacc), max(hacc)) plt.show()
def test_pickle_log(): """ pickle log iterator sanity tests. """ log_datafile = "./data/serial_link_log_20141125-150750_test2.log.dat" count = 0 with PickleLogIterator(FileDriver(log_datafile)) as log: with warnings.catch_warnings(record=True) as w: for delta, timestamp, msg in log.next(): assert type(delta) == int assert type(timestamp) == int assert isinstance(msg, SBP) count += 1 warnings.simplefilter("always") # Check for warnings. assert len(w) == 1 assert issubclass(w[0].category, RuntimeWarning) assert "SBP payload deserialization error! 0x18" in w[0].message assert count == 1111
def main(): # open a file, iterate through it, # do something when particular message type is found args = get_args() with open(args.file, 'r') as fd: if args.format == 'json': iterator = JSONLogIterator(fd).next() elif args.format == 'bin': driver = FileDriver(fd) iterator = Framer(driver.read, driver.write) else: raise ("unknown format: possible formats are bin and json") conv = EventExtractor() while True: try: (msg, data) = iterator.next() if isinstance(msg, MsgExtEvent): conv._event_callback(msg) except StopIteration: break
def main(): args = get_args() open_args = 'rb' if args.format == 'bin' else 'r' json = False with open(args.file, open_args) as fd: if args.format == 'json': json = True iterator = JSONLogIterator(fd, conventional=True) elif args.format == 'bin': driver = FileDriver(fd) iterator = Framer(driver.read, driver.write, dispatcher=None) else: raise Exception( "Usage Error: Unknown input format. Valid input formats for -f arg are bin and json." ) msg_class = None msg_id = None for my_id, my_class in _SBP_TABLE.items(): if my_class.__name__ == args.type or (args.id and my_id == int(args.id)): msg_class = my_class msg_id = my_id assert msg_class is not None, "Invalid message type specified" outfile = msg_class.__name__ if args.outfile: outfile += "_" + args.outfile outfile += ".csv" print("Extracing class {} with msg_id {} to csv file {}".format( msg_class, msg_id, outfile)) with open(outfile, 'w+') as outfp: conv = MsgExtractor(outfp, msg_class, metadata=json) while True: try: msg, data = iterator.__next__() if msg.msg_type == msg_id: conv._callback(msg, data) if msg is None: break except StopIteration: break
def main(): # First, we start up an SBP driver reading from STDInput first = True args = get_args() outfile_str = "" with open(args.file, 'r') as fd: if args.format == 'json': iterator = JSONLogIterator(fd) elif args.format == 'bin': driver = FileDriver(fd) iterator = Framer(driver.read, driver.write) else: raise ("unkonwn format") outfile_str = args.outfile + args.file + "imu.csv" with open(outfile_str, 'w') as outfile: conv = MagExtractor(outfile) if args.format == 'json': iterator = iterator.next() while True: try: (msg, data) = iterator.next() if first: first = False if isinstance(msg, MsgImuRaw): conv.mag_callback(msg) except StopIteration: break df = pd.read_csv(open(outfile_str, 'r')) fig = plt.figure(figsize=[20, 10]) fig = plt.figure(figsize=[20, 10]) plt.subplot(3, 1, 1) plt.plot(df["tow (ms)"], df["tow (ms)"].diff()) plt.ylabel(['tow period (milliseconds)']) ax = plt.subplot(3, 1, 2) df["tow (ms)"].diff().hist(ax=ax) fig.savefig(args.file + '.png')
help='Type of message to interpolate.') parser.add_argument('-d', '--debouncetime', type=int, default=[1000], nargs=1, help='Specify the debounce time for trigger in ms.') args = parser.parse_args() return args if __name__ == '__main__': args = get_args() if args.type[0] == 'MsgBaselineNED' or args.type[ 0] == 'MsgPosECEF' or args.type[0] == 'MsgPosLLH' or args.type[ 0] == 'MsgBaselineECEF': if args.filename[0]: infile = open(args.filename[0], 'r') if args.binary: driver = FileDriver(infile) iterator = Framer(driver.read, driver.write, True) else: iterator = JSONLogIterator(infile).next() a, b, c, d, e, f, g, h = collect_positions(iterator, args.type[0], args.debouncetime[0]) display_data(a, b, c, d, e, f, g, h, args.type[0], args.outfile[0]) else: print("Please provide a filename argument") else: print("Incorrect Message Type!!")