class TestMessageFiltering(unittest.TestCase):

    def setUp(self):
        self.bus = Bus(bustype='virtual', channel='testy')

    def tearDown(self):
        self.bus.shutdown()

    def test_match_all(self):
        # explicitly
        self.bus.set_filters()
        self.assertTrue(self.bus._matches_filters(EXAMPLE_MSG))
        # implicitly
        self.bus.set_filters(None)
        self.assertTrue(self.bus._matches_filters(EXAMPLE_MSG))

    def test_match_filters_is_empty(self):
        self.bus.set_filters([])
        for msg in TEST_ALL_MESSAGES:
            self.assertTrue(self.bus._matches_filters(msg))

    def test_match_example_message(self):
        self.bus.set_filters(MATCH_EXAMPLE)
        self.assertTrue(self.bus._matches_filters(EXAMPLE_MSG))
        self.assertFalse(self.bus._matches_filters(HIGHEST_MSG))
        self.bus.set_filters(MATCH_ONLY_HIGHEST)
        self.assertFalse(self.bus._matches_filters(EXAMPLE_MSG))
        self.assertTrue(self.bus._matches_filters(HIGHEST_MSG))
class TestMessageFiltering(unittest.TestCase):

    def setUp(self):
        self.bus = Bus(bustype='virtual', channel='testy')

    def tearDown(self):
        self.bus.shutdown()

    def test_match_all(self):
        # explicitly
        self.bus.set_filters()
        self.assertTrue(self.bus._matches_filters(EXAMPLE_MSG))
        # implicitly
        self.bus.set_filters(None)
        self.assertTrue(self.bus._matches_filters(EXAMPLE_MSG))

    def test_match_filters_is_empty(self):
        self.bus.set_filters([])
        for msg in TEST_ALL_MESSAGES:
            self.assertTrue(self.bus._matches_filters(msg))

    def test_match_example_message(self):
        self.bus.set_filters(MATCH_EXAMPLE)
        self.assertTrue(self.bus._matches_filters(EXAMPLE_MSG))
        self.assertFalse(self.bus._matches_filters(HIGHEST_MSG))
        self.bus.set_filters(MATCH_ONLY_HIGHEST)
        self.assertFalse(self.bus._matches_filters(EXAMPLE_MSG))
        self.assertTrue(self.bus._matches_filters(HIGHEST_MSG))
Esempio n. 3
0
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()
Esempio n. 4
0
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()
Esempio n. 5
0
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()
Esempio n. 6
0
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()
Esempio n. 7
0
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()
Esempio n. 8
0
class Can(SetState):
    def __init__(self, type="socketcan"):
        self.type = type
        self.interface = pysc.Interface()
        self.interface.listen_only = True
        self.state = State(self.interface.state.value)
        self.baudrates = (  # Common automotive CAN bus speeds
            33000,
            100000,
            125000,
            250000,
            500000,
        )

    @property
    def state(self):
        return State(self._state)

    @state.setter
    def state(self, state):
        if state.value:
            self.bus = Bus(self.interface.id, bustype=self.type)
        else:
            self.bus.shutdown()
        self._state = state

    @property
    def baud(self):
        return self.interface.baud

    @baud.setter
    def baud(self, rate):
        if rate not in self.baudrates:
            return print(f"Invalid. Please choose from {self.baudrates}")
        self.interface.baud = rate

    def detect_baud(self):
        """
        Automatically attempt to detect baudrate.

        Sets interface to each available rate and listens.
        Exits if messages are received within 2.5 seconds.
        """
        for rate in self.baudrates:
            self.baud = rate
            received = self.bus.recv(2)
            if received:
                return f"Baudrate successfully detected!"
        raise AttributeError("Something went wrong. Verify connections and try again.")
Esempio n. 9
0
def logCan():
    results = bus_Cofing()

    can_filters = []
    if len(results.filter) > 0:
        print('Adding filter are:')
        for filt in results.filter:
            if ':' in filt:
                _ = filt.split(":")
                can_id = int(_[0], base=16)
                can_mask = int(_[1], base=16)
                print('Can ID: ', hex(can_id), 'mask: ', hex(can_mask))

            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
                print('Can ID: ', can_id, 'mask: ', can_mask)
            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)

    print('\nConnected to {}: {}'.format(bus.__class__.__name__,
                                         bus.channel_info))
    print('Can Logger (Started on {})\n'.format(datetime.now()))
    logger = Logger(results.log_file)
    while keep_going:
        msg = bus.recv(1)
        if msg is not None:
            print(msg)
            logger(msg)

    bus.shutdown()
    logger.stop()
class TestMessageFiltering(unittest.TestCase):
    def setUp(self):
        self.node1 = Bus("test", bustype="virtual", preserve_timestamps=True)
        self.node2 = Bus("test", bustype="virtual")

    def tearDown(self):
        self.node1.shutdown()
        self.node2.shutdown()

    def test_sendmsg(self):
        self.node2.send(EXAMPLE_MSG1)
        r = self.node1.recv(0.1)
        assert r.timestamp != EXAMPLE_MSG1.timestamp
        assert r.arbitration_id == EXAMPLE_MSG1.arbitration_id
        assert r.data == EXAMPLE_MSG1.data

    def test_sendmsg_preserve_timestamp(self):
        self.node1.send(EXAMPLE_MSG1)
        r = self.node2.recv(0.1)
        assert r.timestamp == EXAMPLE_MSG1.timestamp
        assert r.arbitration_id == EXAMPLE_MSG1.arbitration_id
        assert r.data == EXAMPLE_MSG1.data
Esempio n. 11
0
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()
Esempio n. 12
0
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()
Esempio n. 13
0
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()
Esempio n. 14
0
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()
Esempio n. 15
0
class PythonCAN:
    """"""
    def __init__(self, bustype):
        self.bustype = bustype
        self.connected = False

    def init(self, parent, receive_callback):
        self.parent = parent
        self.is_fd = self.config.get("FD")

    def connect(self):
        if self.connected:
            return

        self.kwargs = OrderedDict()
        # Fetch driver keyword arguments.
        self._fetch_kwargs(False)
        self._fetch_kwargs(True)
        can_id = self.parent.can_id_master
        can_filter = {
            "can_id": can_id.id,
            "can_mask": can.MAX_29_BIT_IDENTIFIER
            if can_id.is_extended else can.MAX_11_BIT_IDENTIFIER,
            "extended": can_id.is_extended,
        }
        self.bus = Bus(bustype=self.bustype, **self.kwargs)
        self.bus.set_filters([can_filter])
        self.parent.logger.debug("Python-CAN driver: {} - {}]".format(
            self.bustype, self.bus))
        self.connected = True

    def _fetch_kwargs(self, local):
        if local:
            base = self
        else:
            base = self.parent
        for param, arg in base.PARAMETER_TO_KW_ARG_MAP.items():
            value = base.config.get(param)
            # if param == "CHANNEL":
            #    value = self._handle_channel(value)
            self.kwargs[arg] = value

    def _handle_channel(self, value):
        match = NUMBER.match(value)
        if match:
            gd = match.groupdict()
            base = 16 if not gd["hex"] is None else 10
            return int(value, base)
        else:
            return value

    def close(self):
        if self.connected:
            self.bus.shutdown()
        self.connected = False

    def transmit(self, payload):
        frame = Message(
            arbitration_id=self.parent.can_id_slave.id,
            is_extended_id=True
            if self.parent.can_id_slave.is_extended else False,
            is_fd=self.is_fd,
            data=payload,
        )
        self.bus.send(frame)

    def read(self):
        if not self.connected:
            return None
        try:
            frame = self.bus.recv(5)
        except CanError:
            return None
        else:
            if frame is None or frame.arbitration_id != self.parent.can_id_master.id or not len(
                    frame.data):
                return None  # Timeout condition.
            extended = frame.is_extended_id
            identifier = can.Identifier.make_identifier(
                frame.arbitration_id, extended)
            return can.Frame(
                id_=identifier,
                dlc=frame.dlc,
                data=frame.data,
                timestamp=frame.timestamp,
            )

    def getTimestampResolution(self):
        return 10 * 1000
Esempio n. 16
0
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()