def main(): parser = ArgumentParser( description="Convert a log file from one format to another.", ) parser.add_argument( "-s", "--file_size", dest="file_size", type=int, help="Maximum file size in bytes. Rotate log file when size threshold is reached.", default=None, ) parser.add_argument( "input", metavar="INFILE", type=str, help="Input filename. The type is dependent on the suffix, see can.LogReader.", ) parser.add_argument( "output", metavar="OUTFILE", type=str, help="Output filename. The type is dependent on the suffix, see can.Logger.", ) args = parser.parse_args() with LogReader(args.input) as reader: if args.file_size: logger = SizedRotatingLogger( base_filename=args.output, max_bytes=args.file_size ) else: logger = Logger(filename=args.output) with logger: try: for m in reader: # pylint: disable=not-an-iterable logger(m) except KeyboardInterrupt: sys.exit(1)
def main(): parser = argparse.ArgumentParser( "python -m can.player", description="Replay CAN traffic.") parser.add_argument("-f", "--file_name", dest="log_file", help="""Path and base log filename, for supported types see can.LogReader.""", default=None) parser.add_argument("-v", action="count", dest="verbosity", help='''Also print can frames to stdout. You can add several of these to enable debugging''', default=2) parser.add_argument('-c', '--channel', help='''Most backend interfaces require some sort of channel. For example with the serial interface the channel might be a rfcomm device: "/dev/rfcomm0" With the socketcan interfaces valid channel examples include: "can0", "vcan0"''') parser.add_argument('-i', '--interface', dest="interface", help='''Specify the backend CAN interface to use. If left blank, fall back to reading from configuration files.''', choices=can.VALID_INTERFACES) parser.add_argument('-b', '--bitrate', type=int, help='''Bitrate to use for the CAN bus.''') parser.add_argument('--ignore-timestamps', dest='timestamps', help='''Ignore timestamps (send all frames immediately with minimum gap between frames)''', action='store_false') parser.add_argument('-g', '--gap', type=float, help='''<s> minimum time between replayed frames''', default=0.0001) parser.add_argument('-s', '--skip', type=float, default=60*60*24, help='''<s> skip gaps greater than 's' seconds''') parser.add_argument('infile', metavar='input-file', type=str, help='The file to replay. For supported types see can.LogReader.') # print help message when no arguments were given if len(sys.argv) < 2: parser.print_help(sys.stderr) import errno raise SystemExit(errno.EINVAL) results = parser.parse_args() verbosity = results.verbosity logging_level_name = ['critical', 'error', 'warning', 'info', 'debug', 'subdebug'][min(5, verbosity)] can.set_logging_level(logging_level_name) config = {"single_handle": True} if results.interface: config["interface"] = results.interface if results.bitrate: config["bitrate"] = results.bitrate bus = Bus(results.channel, **config) reader = LogReader(results.infile) in_sync = MessageSync(reader, timestamps=results.timestamps, gap=results.gap, skip=results.skip) print('Can LogReader (Started on {})'.format(datetime.now())) try: for m in in_sync: if verbosity >= 3: print(m) bus.send(m) except KeyboardInterrupt: pass finally: bus.shutdown() reader.stop()
def main(): parser = argparse.ArgumentParser( "python -m can.player", description="Replay CAN traffic." ) parser.add_argument( "-f", "--file_name", dest="log_file", help="""Path and base log filename, for supported types see can.LogReader.""", default=None, ) parser.add_argument( "-v", action="count", dest="verbosity", help="""Also print can frames to stdout. You can add several of these to enable debugging""", default=2, ) parser.add_argument( "-c", "--channel", help='''Most backend interfaces require some sort of channel. For example with the serial interface the channel might be a rfcomm device: "/dev/rfcomm0" With the socketcan interfaces valid channel examples include: "can0", "vcan0"''', ) parser.add_argument( "-i", "--interface", dest="interface", help="""Specify the backend CAN interface to use. If left blank, fall back to reading from configuration files.""", choices=can.VALID_INTERFACES, ) parser.add_argument( "-b", "--bitrate", type=int, help="""Bitrate to use for the CAN bus.""" ) parser.add_argument("--fd", help="Activate CAN-FD support", action="store_true") parser.add_argument( "--data_bitrate", type=int, help="""Bitrate to use for the data phase in case of CAN-FD.""", ) parser.add_argument( "--ignore-timestamps", dest="timestamps", help="""Ignore timestamps (send all frames immediately with minimum gap between frames)""", action="store_false", ) parser.add_argument( "--error-frames", help="Also send error frames to the interface.", action="store_true", ) parser.add_argument( "-g", "--gap", type=float, help="""<s> minimum time between replayed frames""", default=0.0001, ) parser.add_argument( "-s", "--skip", type=float, default=60 * 60 * 24, help="""<s> skip gaps greater than 's' seconds""", ) parser.add_argument( "infile", metavar="input-file", type=str, help="The file to replay. For supported types see can.LogReader.", ) # print help message when no arguments were given if len(sys.argv) < 2: parser.print_help(sys.stderr) raise SystemExit(errno.EINVAL) results = parser.parse_args() verbosity = results.verbosity logging_level_name = ["critical", "error", "warning", "info", "debug", "subdebug"][ min(5, verbosity) ] can.set_logging_level(logging_level_name) error_frames = results.error_frames config = {"single_handle": True} if results.interface: config["interface"] = results.interface if results.bitrate: config["bitrate"] = results.bitrate if results.fd: config["fd"] = True if results.data_bitrate: config["data_bitrate"] = results.data_bitrate bus = Bus(results.channel, **config) reader = LogReader(results.infile) in_sync = MessageSync( reader, timestamps=results.timestamps, gap=results.gap, skip=results.skip ) print(f"Can LogReader (Started on {datetime.now()})") try: for m in in_sync: if m.is_error_frame and not error_frames: continue if verbosity >= 3: print(m) bus.send(m) except KeyboardInterrupt: pass finally: bus.shutdown() reader.stop()
def logimport(filename, tagdict={}, db_info={ "ip": "10.8.0.1", "port": 8086, "dbname": "canlogger" }): canalyse = J1939CANanalyser() reader = LogReader(filename) # for Synchronized readings # in_sync = MessageSync( # reader, timestamps=args.timestamps, gap=args.gap, skip=args.skip # ) # dbip="localhost" client = InfluxDBClient(host=db_info.get("ip"), port=db_info.get("port"), username="******", password="******", database=db_info.get("dbname")) databaselist = client.get_list_database() dbfound = False for elem in databaselist: if elem.get('name') == db_info.get("dbname"): dbfound = True if dbfound == False: client.create_database(db_info.get("dbname")) client.switch_database(db_info.get("dbname")) # only Influx DB2.0 # client = InfluxDBClient(url="http://localhost:9999", token="test", org="gpi") # bucket = "logger" # write_api = client.write_api(write_options=SYNCHRONOUS) # write_client = client.write_api(write_options=WriteOptions(batch_size=500, # flush_interval=10_000, # jitter_interval=2_000, # retry_interval=5_000, # max_retries=5, # max_retry_delay=30_000, # exponential_base=2)) # query_api = client.query_api() # p = Point("my_measurement").tag("location", "Prague").field("temperature", 25.3) # p1 = Point("my_measurement").tag("location", "Prague").field("temperature", 25.3) # p2 = Point("my_measurement").tag("location", "New York").field("temperature", 24.3) # write_api.write(bucket='canlogger', record=[p,p1,p2]) # tables = query_api.query('from(bucket:"my-bucket") |> range(start: -10m)') print(f"Can LogReader (Started on {datetime.now()})") count = 0 pointlist = [] try: for msg in reader: # print(msg) data = bytes(msg.data) canid = msg.arbitration_id j1939vals = canalyse.translate(canid, data) pgn = j1939vals.pop('pgn') # self.ids[key] sa = j1939vals.pop('sa') da = j1939vals.pop('da') point = makePointj1938(msg.timestamp, canid, pgn, sa, da, j1939vals, data, tagdict=tagdict) if point is not None: pointlist.append(point) if len(pointlist) > 5000: count += len(pointlist) ts = datetime.fromtimestamp(msg.timestamp) print(filn, ts, count) client.write_points(pointlist) pointlist = [] except KeyboardInterrupt: pass finally: reader.stop()
def main() -> None: parser = argparse.ArgumentParser(description="Replay CAN traffic.") _create_base_argument_parser(parser) parser.add_argument( "-f", "--file_name", dest="log_file", help="Path and base log filename, for supported types see can.LogReader.", default=None, ) parser.add_argument( "-v", action="count", dest="verbosity", help="""Also print can frames to stdout. You can add several of these to enable debugging""", default=2, ) parser.add_argument( "--ignore-timestamps", dest="timestamps", help="""Ignore timestamps (send all frames immediately with minimum gap between frames)""", action="store_false", ) parser.add_argument( "--error-frames", help="Also send error frames to the interface.", action="store_true", ) parser.add_argument( "-g", "--gap", type=float, help="<s> minimum time between replayed frames", default=0.0001, ) parser.add_argument( "-s", "--skip", type=float, default=60 * 60 * 24, help="<s> skip gaps greater than 's' seconds", ) parser.add_argument( "infile", metavar="input-file", type=str, help="The file to replay. For supported types see can.LogReader.", ) # print help message when no arguments were given if len(sys.argv) < 2: parser.print_help(sys.stderr) raise SystemExit(errno.EINVAL) results = parser.parse_args() verbosity = results.verbosity error_frames = results.error_frames with _create_bus(results) as bus: with LogReader(results.infile) as reader: in_sync = MessageSync( cast(Iterable[Message], reader), timestamps=results.timestamps, gap=results.gap, skip=results.skip, ) print(f"Can LogReader (Started on {datetime.now()})") try: for message in in_sync: if message.is_error_frame and not error_frames: continue if verbosity >= 3: print(message) bus.send(message) except KeyboardInterrupt: pass