def main(): verbosity = 2 logging_level_name = ['critical', 'error', 'warning', 'info', 'debug', 'subdebug'][min(5, verbosity)] can.set_logging_level(logging_level_name) can_filters = [] config = {"can_filters": can_filters, "single_handle": True} config["interface"] = "socketcan" config["bitrate"] = 125000 bus = Bus("can1", **config) print('Connected to {}: {}'.format(bus.__class__.__name__, bus.channel_info)) print('Can Logger (Started on {})\n'.format(datetime.now())) try: while True: msg = bus.recv(1) if msg is not None: de=decon(msg.arbitration_id) m= { "prio": hex(de[0]), "type": hex(de[1]), "dst": hex(de[2]), "src": hex(de[3]), "cmd": hex(de[4]), "target": hex(msg.data[0]) } if de[2] is 3 and msg.data[0] is 3 and de[1] is 0 and de[3] is 3 and de[4] is 3 : print(m) m = can.Message(arbitration_id=0x0C030900, data=[3], extended_id=True) try: bus.send(m) except BaseException as e: logging.error("Error sending can message {%s}: %s" % (m, e)) except KeyboardInterrupt: pass finally: bus.shutdown()
def main(): verbosity = 2 logging_level_name = ['critical', 'error', 'warning', 'info', 'debug', 'subdebug'][min(5, verbosity)] can.set_logging_level(logging_level_name) can_filters = [] config = {"can_filters": can_filters, "single_handle": True} config["interface"] = "socketcan" config["bitrate"] = 125000 bus = Bus("can1", **config) print('Connected to {}: {}'.format(bus.__class__.__name__, bus.channel_info)) print('Can Logger (Started on {})\n'.format(datetime.now())) mcp_mqtt = mqtt.Client() mcp_mqtt.on_connect = on_connect mcp_mqtt.on_message = on_message mcp_mqtt.user_data_set(bus) mcp_mqtt.connect("mcp", 1883, 60) try: while True: mcp_mqtt.loop() except KeyboardInterrupt: pass finally: bus.shutdown()
def main(): verbosity = 2 logging_level_name = ['critical', 'error', 'warning', 'info', 'debug', 'subdebug'][min(5, verbosity)] can.set_logging_level(logging_level_name) can_filters = [] config = {"can_filters": can_filters, "single_handle": True} config["interface"] = "socketcan" config["bitrate"] = 125000 bus = Bus("can1", **config) print('Connected to {}: {}'.format(bus.__class__.__name__, bus.channel_info)) print('Can Logger (Started on {})\n'.format(datetime.now())) mcp_mqtt = mqtt.Client() mcp_mqtt.on_connect = on_connect mcp_mqtt.on_message = on_message mcp_mqtt.user_data_set(bus) mcp_mqtt.connect("mcp", 1883, 60) try: while True: mcp_mqtt.loop_start() except KeyboardInterrupt: pass finally: bus.shutdown()
def main(): verbosity = 2 logging_level_name = ['critical', 'error', 'warning', 'info', 'debug', 'subdebug'][min(5, verbosity)] can.set_logging_level(logging_level_name) can_filters = [] config = {"can_filters": can_filters, "single_handle": True} config["interface"] = "socketcan" config["bitrate"] = 125000 bus = Bus("can1", **config) print('Connected to {}: {}'.format(bus.__class__.__name__, bus.channel_info)) print('Can Logger (Started on {})\n'.format(datetime.now())) mcp_mqtt = mqtt.Client() mcp_mqtt.on_connect = on_connect mcp_mqtt.on_message = on_message mcp_mqtt.user_data_set(bus) mcp_mqtt.connect("mcp", 1883, 60) try: while True: mcp_mqtt.loop_start() msg = bus.recv(1) if msg is not None: de=decon(msg.arbitration_id) m= { "prio": hex(de[0]), "type": hex(de[1]), "dst": hex(de[2]), "src": hex(de[3]), "cmd": hex(de[4]), "action": hex(msg.data[0]) } # print(m) # mcp_mqtt.publish("can/rx", str(m)) except KeyboardInterrupt: pass finally: bus.shutdown()
def main(): verbosity = 2 logging_level_name = [ 'critical', 'error', 'warning', 'info', 'debug', 'subdebug' ][min(5, verbosity)] can.set_logging_level(logging_level_name) can_filters = [] config = {"can_filters": can_filters, "single_handle": True} config["interface"] = "socketcan_native" config["bitrate"] = 125000 bus = Bus("can1", **config) print('Connected to {}: {}'.format(bus.__class__.__name__, bus.channel_info)) print('Can Logger (Started on {})\n'.format(datetime.now())) mcp_mqtt = mqtt.Client() mcp_mqtt.on_connect = on_connect mcp_mqtt.on_message = on_message mcp_mqtt.user_data_set(bus) mcp_mqtt.connect("mcp", 1883, 60) mcp_mqtt.loop_start() try: while True: msg = bus.recv(1) if msg is not None: de = decon(msg.arbitration_id) m = { "prio": hex(de[0]), "type": hex(de[1]), "dst": hex(de[2]), "src": hex(de[3]), "cmd": hex(de[4]), "action": hex(msg.data[0]) } if de[2] == 0 and de[4] == 6: print("received state: ", hex(de[3]), hex(msg.data[0]), hex(msg.data[1])) for key in light_map: address = light_map[key] if address[0] == de[3] and address[ 1] == msg.data[0] + 1: print("light/" + key + " changed to " + str(msg.data[1])) mcp_mqtt.publish("light/" + key + "/state", msg.data[1], retain=1) except KeyboardInterrupt: pass finally: bus.shutdown()
def main(): parser = argparse.ArgumentParser( "python -m can.server", description="Remote CAN server") parser.add_argument('-v', action='count', dest="verbosity", help='''How much information do you want to see at the command line? You can add several of these e.g., -vv is DEBUG''', default=3) 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". The server will only serve this channel. Start additional servers at different ports to share more channels.''') parser.add_argument('-i', '--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='''Force to use a specific bitrate. This will override any requested bitrate by the clients.''') parser.add_argument('-H', '--host', help='''Host to listen to (default 0.0.0.0).''', default='0.0.0.0') parser.add_argument('-p', '--port', type=int, help='''TCP port to listen on (default %d).''' % remote.DEFAULT_PORT, default=remote.DEFAULT_PORT) 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 = {} if results.channel: config["channel"] = results.channel if results.interface: config["bustype"] = results.interface if results.bitrate: config["bitrate"] = results.bitrate server = remote.RemoteServer(results.host, results.port, **config) try: server.serve_forever() except KeyboardInterrupt: pass logging.info("Closing server") server.server_close()
def main(): #['critical', 'error', 'warning', 'info', 'debug', 'subdebug'][min(5, verbosity)] logging_level_name = 'info' can.set_logging_level(logging_level_name) can_filters = [] config = {"can_filters": can_filters, "single_handle": True} config["bustype"] = 'vector' config["bitrate"] = 500000 bus = can.interface.Bus(0, **config) print('Connected to {}: {}'.format(bus.__class__.__name__, bus.channel_info)) print('Can Logger (Started on {})\n'.format(datetime.datetime.now())) prev_position = 0 wakeup_msg = can.Message(arbitration_id=0x59e, data=[0, 0, 0, 0, 0, 0, 0, 0], extended_id=False) try: bus.send(wakeup_msg) while True: msg = bus.recv(1) if msg is not None: if msg.arbitration_id == 0x5a: position = (msg.data[3] & 0xf8) >> 3 bus.send(wakeup_msg) if (prev_position != position): if (position == 0x01): print("Park") if (position == 0x02): print("Reverse") if (position == 0x04): print("Neutral") if (position == 0x08): print("Drive") if (position == 0x16): print("Sport") prev_position = position except KeyboardInterrupt: pass finally: bus.shutdown()
def _create_bus(parsed_args: Any, **kwargs: Any) -> can.Bus: logging_level_names = [ "critical", "error", "warning", "info", "debug", "subdebug" ] can.set_logging_level(logging_level_names[min(5, parsed_args.verbosity)]) config: Dict[str, Any] = {"single_handle": True, **kwargs} if parsed_args.interface: config["interface"] = parsed_args.interface if parsed_args.bitrate: config["bitrate"] = parsed_args.bitrate if parsed_args.fd: config["fd"] = True if parsed_args.data_bitrate: config["data_bitrate"] = parsed_args.data_bitrate return Bus(parsed_args.channel, **config) # type: ignore
def main(): parser = argparse.ArgumentParser( "python -m can.logger", description= "Log CAN traffic, printing messages to stdout or to a given file.") parser.add_argument( "-f", "--file_name", dest="log_file", help= """Path and base log filename, for supported types see can.Logger.""", default=None) parser.add_argument( "-v", action="count", dest="verbosity", help='''How much information do you want to see at the command line? You can add several of these e.g., -vv is DEBUG''', 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( '--filter', help= '''Comma separated filters can be specified for the given CAN interface: <can_id>:<can_mask> (matches when <received_can_id> & mask == can_id & mask) <can_id>~<can_mask> (matches when <received_can_id> & mask != can_id & mask) ''', nargs=argparse.REMAINDER, default='') parser.add_argument('-b', '--bitrate', type=int, help='''Bitrate to use for the CAN bus.''') state_group = parser.add_mutually_exclusive_group(required=False) state_group.add_argument( '--active', help="Start the bus as active, this is applied by default.", action='store_true') state_group.add_argument('--passive', help="Start the bus as passive.", action='store_true') # print help message when no arguments wre 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) can_filters = [] if len(results.filter) > 0: print('Adding filter/s', results.filter) for filt in results.filter: if ':' in filt: _ = filt.split(":") can_id, can_mask = int(_[0], base=16), int(_[1], base=16) elif "~" in filt: can_id, can_mask = filt.split("~") can_id = int(can_id, base=16) | 0x20000000 # CAN_INV_FILTER can_mask = int(can_mask, base=16) & socket.CAN_ERR_FLAG can_filters.append({"can_id": can_id, "can_mask": can_mask}) config = {"can_filters": can_filters, "single_handle": True} if results.interface: config["interface"] = results.interface if results.bitrate: config["bitrate"] = results.bitrate bus = Bus(results.channel, **config) if results.active: bus.state = BusState.ACTIVE elif results.passive: bus.state = BusState.PASSIVE print('Connected to {}: {}'.format(bus.__class__.__name__, bus.channel_info)) print('Can Logger (Started on {})\n'.format(datetime.now())) logger = Logger(results.log_file) try: while True: msg = bus.recv(1) if msg is not None: logger(msg) except KeyboardInterrupt: pass finally: bus.shutdown() logger.stop()
Valid choices: {} Alternatively the CAN_INTERFACE environment variable can be set. '''.format(can.interfaces.VALID_INTERFACES))) return parser.parse_args() if __name__ == "__main__": args = parse_arguments() verbosity = args.verbosity logging_level_name = ['critical', 'error', 'warning', 'info', 'debug', 'subdebug'][min(5, verbosity)] can.set_logging_level(logging_level_name) filters = [] if args.pgn is not None: print('Have to filter pgns: ', args.pgn) for pgn in args.pgn: if pgn.startswith('0x'): pgn = int(pgn[2:], base=16) filters.append({'pgn': int(pgn)}) if args.source is not None: for src in args.source: if src.startswith("0x"): src = int(src[2:], base=16) filters.append({"source": int(src)}) if args.filter is not None: filters = json.load(args.filter)
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.logger", description= "Log CAN traffic, printing messages to stdout or to a given file.", ) parser.add_argument( "-f", "--file_name", dest="log_file", help= """Path and base log filename, for supported types see can.Logger.""", default=None, ) 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( "-v", action="count", dest="verbosity", help="""How much information do you want to see at the command line? You can add several of these e.g., -vv is DEBUG""", 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( "--filter", help= """Comma separated filters can be specified for the given CAN interface: <can_id>:<can_mask> (matches when <received_can_id> & mask == can_id & mask) <can_id>~<can_mask> (matches when <received_can_id> & mask != can_id & mask) """, nargs=argparse.REMAINDER, default="", ) 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.""", ) state_group = parser.add_mutually_exclusive_group(required=False) state_group.add_argument( "--active", help="Start the bus as active, this is applied by default.", action="store_true", ) state_group.add_argument("--passive", help="Start the bus as passive.", action="store_true") # print help message when no arguments wre 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) can_filters = [] if results.filter: print(f"Adding filter(s): {results.filter}") for filt in results.filter: if ":" in filt: _ = filt.split(":") can_id, can_mask = int(_[0], base=16), int(_[1], base=16) elif "~" in filt: can_id, can_mask = filt.split("~") can_id = int(can_id, base=16) | 0x20000000 # CAN_INV_FILTER can_mask = int(can_mask, base=16) & socket.CAN_ERR_FLAG can_filters.append({"can_id": can_id, "can_mask": can_mask}) config = {"can_filters": can_filters, "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) if results.active: bus.state = BusState.ACTIVE elif results.passive: bus.state = BusState.PASSIVE print(f"Connected to {bus.__class__.__name__}: {bus.channel_info}") print(f"Can Logger (Started on {datetime.now()})") if results.file_size: logger = SizedRotatingLogger(base_filename=results.log_file, max_bytes=results.file_size) else: logger = Logger(filename=results.log_file) try: while True: msg = bus.recv(1) if msg is not None: logger(msg) except KeyboardInterrupt: pass finally: bus.shutdown() logger.stop()
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 Other channel examples are: can0, vcan0''', default=can.rc['channel']) parser.add_argument('--filter', help='''Comma separated filters can be specified for the given CAN interface: <can_id>:<can_mask> (matches when <received_can_id> & mask == can_id & mask) <can_id>~<can_mask> (matches when <received_can_id> & mask != can_id & mask) ''', nargs=argparse.REMAINDER, default='') 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) can_filters = [] if len(results.filter) > 0: print('we have filter/s', results.filter) for filt in results.filter: if ':' in filt: _ = filt.split(":") can_id, can_mask = int(_[0], base=16), int(_[1], base=16) elif "~" in filt: can_id, can_mask = filt.split("~") can_id = int(can_id, base=16) | 0x20000000 # CAN_INV_FILTER can_mask = int(can_mask, base=16) & socket.CAN_ERR_FLAG can_filters.append({"can_id": can_id, "can_mask": can_mask}) bus = can.interface.Bus(results.channel, can_filters=can_filters)
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 main(): parser = argparse.ArgumentParser( description= "Log CAN traffic, printing messages to stdout or to a given file") parser.add_argument( "-f", "--file_name", dest="log_file", help= """Path and base log filename, extension can be .txt, .asc, .csv, .db, .npz""", default=None) parser.add_argument( "-v", action="count", dest="verbosity", help='''How much information do you want to see at the command line? You can add several of these e.g., -vv is DEBUG''', 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( '--filter', help= '''Comma separated filters can be specified for the given CAN interface: <can_id>:<can_mask> (matches when <received_can_id> & mask == can_id & mask) <can_id>~<can_mask> (matches when <received_can_id> & mask != can_id & mask) ''', nargs=argparse.REMAINDER, default='') parser.add_argument('-b', '--bitrate', type=int, help='''Bitrate to use for the CAN bus.''') 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) can_filters = [] if len(results.filter) > 0: print('Adding filter/s', results.filter) for filt in results.filter: if ':' in filt: _ = filt.split(":") can_id, can_mask = int(_[0], base=16), int(_[1], base=16) elif "~" in filt: can_id, can_mask = filt.split("~") can_id = int(can_id, base=16) | 0x20000000 # CAN_INV_FILTER can_mask = int(can_mask, base=16) & socket.CAN_ERR_FLAG can_filters.append({"can_id": can_id, "can_mask": can_mask}) config = {"can_filters": can_filters, "single_handle": True} if results.interface: config["bustype"] = results.interface if results.bitrate: config["bitrate"] = results.bitrate bus = can.interface.Bus(results.channel, **config) print('Can Logger (Started on {})\n'.format(datetime.datetime.now())) logger = Logger(results.log_file) try: while True: msg = bus.recv(1) if msg is not None: logger(msg) except KeyboardInterrupt: pass finally: bus.shutdown() logger.stop()
#!/usr/bin/env python import logging import argparse try: import ssl except ImportError: ssl = None import can from .server import RemoteServer from . import DEFAULT_PORT logging.basicConfig(format='%(asctime)-15s %(message)s', level=logging.DEBUG) can.set_logging_level("DEBUG") def main(): parser = argparse.ArgumentParser("python -m can_server", description="Remote CAN server") parser.add_argument( '-v', action='count', dest="verbosity", help='''How much information do you want to see at the command line? You can add several of these e.g., -vv is DEBUG''', default=3) parser.add_argument( '-c', '--channel', help='''Most backend interfaces require some sort of channel.
'--interface', dest="interface", default='socketcan') return parser.parse_args() if __name__ == "__main__": args = parse_arguments() verbosity = args.verbosity logging_level_name = [ 'critical', 'error', 'warning', 'info', 'debug', 'subdebug' ][min(3, verbosity)] setlogging(logging_level_name) can.set_logging_level('error') # logging_level_name) logging.info("Start") # r_dic = RedisDict(namespace='app_name') # r = redis.Redis(host='localhost', port=6379, db=0) # r.set('startlogging', 1) # q = Queue(connection=Redis()) filters = [] if args.pgn is not None: print('Have to filter pgns: ', args.pgn) for pgn in args.pgn: if pgn.startswith('0x'): pgn = int(pgn[2:], base=16) filters.append({'pgn': int(pgn)})
def main(): parser = argparse.ArgumentParser( "python -m can.logger", description="Log CAN traffic, printing messages to stdout or to a given file.") parser.add_argument("-f", "--file_name", dest="log_file", help="""Path and base log filename, for supported types see can.Logger.""", default=None) parser.add_argument("-v", action="count", dest="verbosity", help='''How much information do you want to see at the command line? You can add several of these e.g., -vv is DEBUG''', 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('--filter', help='''Comma separated filters can be specified for the given CAN interface: <can_id>:<can_mask> (matches when <received_can_id> & mask == can_id & mask) <can_id>~<can_mask> (matches when <received_can_id> & mask != can_id & mask) ''', nargs=argparse.REMAINDER, default='') parser.add_argument('-b', '--bitrate', type=int, help='''Bitrate to use for the CAN bus.''') group = parser.add_mutually_exclusive_group(required=False) group.add_argument('--active', help="Start the bus as active, this is applied the default.", action='store_true') group.add_argument('--passive', help="Start the bus as passive.", action='store_true') # print help message when no arguments wre 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) can_filters = [] if len(results.filter) > 0: print('Adding filter/s', results.filter) for filt in results.filter: if ':' in filt: _ = filt.split(":") can_id, can_mask = int(_[0], base=16), int(_[1], base=16) elif "~" in filt: can_id, can_mask = filt.split("~") can_id = int(can_id, base=16) | 0x20000000 # CAN_INV_FILTER can_mask = int(can_mask, base=16) & socket.CAN_ERR_FLAG can_filters.append({"can_id": can_id, "can_mask": can_mask}) config = {"can_filters": can_filters, "single_handle": True} if results.interface: config["interface"] = results.interface if results.bitrate: config["bitrate"] = results.bitrate bus = Bus(results.channel, **config) if results.active: bus.state = BusState.ACTIVE if results.passive: bus.state = BusState.PASSIVE print('Connected to {}: {}'.format(bus.__class__.__name__, bus.channel_info)) print('Can Logger (Started on {})\n'.format(datetime.now())) logger = Logger(results.log_file) try: while True: msg = bus.recv(1) if msg is not None: logger(msg) except KeyboardInterrupt: pass finally: bus.shutdown() logger.stop()