Пример #1
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()
 def setUp(self):
     self.bus = Bus(bustype='virtual', channel='testy')
Пример #3
0
from uds import Uds
from can import Bus, Listener, Notifier
from time import sleep


def callback_onReceive(msg):

    if (msg.arbitration_id == 0x600):
        print("Bootloader Receive:", list(msg.data))
    if (msg.arbitration_id == 0x7E0):
        print("PCM Receive:", list(msg.data))


if __name__ == "__main__":

    recvBus = Bus("virtualInterface", bustype="virtual")

    listener = Listener()
    notifier = Notifier(recvBus, [listener], 0)

    listener.on_message_received = callback_onReceive

    a = Uds()

    a.send([0x22, 0xf1, 0x8C], responseRequired=False)

    sleep(2)
Пример #4
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(
        "--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)
        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)

    error_frames = results.error_frames

    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 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()
Пример #5
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()
Пример #6
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()
Пример #7
0
 def setUp(self):
     self.bus = Bus(bustype="virtual", channel="testy")
Пример #8
0
import copy
import numpy as np
import time

import rclpy
from rclpy.node import Node
from geometry_msgs.msg import Twist, Vector3
from std_msgs.msg import Float32
from std_srvs.srv import Trigger

import can
can.rc['interface'] = 'socketcan'
can.rc['channel'] = 'can0'
can.rc['bitrate'] = 1000000
from can import Bus
bus = Bus()
bus.receive_own_messages = False


class FilteredCanReader(can.BufferedReader):
    def __init__(self):
        can.BufferedReader.__init__(self)
        self.func_map = {}
        self.domain = None

    def register_callback(self, address):
        def wrapper(function):
            self.func_map[str(int(address))] = function
            return function

        return wrapper
Пример #9
0
 def state(self, state):
     if state.value:
         self.bus = Bus(self.interface.id, bustype=self.type)
     else:
         self.bus.shutdown()
     self._state = state
Пример #10
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.loop_start()

    mcp_mqtt.message_callback_add(base_topic + "/" + coil_topic + "/+",
                                  on_message_coil)
    mcp_mqtt.message_callback_add(base_topic + "/" + light_topic + "/+",
                                  on_message_light)
    mcp_mqtt.on_message = on_message
    mcp_mqtt.connect("mcp", 1883, 60)

    mcp_mqtt.loop_start()
    #mcp_mqtt.loop_forever()

    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 coil_map:
                        address = coil_map[key]
                        if address[1] == de[3] and address[
                                2] == msg.data[0] + 1:
                            print("coil/" + key + " changed to " +
                                  str(msg.data[1]))
                            mcp_mqtt.publish(base_topic + "/" + coil_topic +
                                             "/" + key + "/state",
                                             msg.data[1],
                                             retain=1)
                            if "L" in address[0]:
                                print("light/" + key + " changed to " +
                                      str(msg.data[1]))
                                mcp_mqtt.publish(base_topic + "/" +
                                                 light_topic + "/" + key +
                                                 "/state",
                                                 msg.data[1],
                                                 retain=1)
                elif de[2] == 0 and de[4] == 5:
                    print("received state: ", de[3], msg.data[0],
                          bin(msg.data[1]))
                    mcp_mqtt.publish(base_topic + "/" + switch_topic + "/" +
                                     str(de[3]) + "-" + str(msg.data[0]),
                                     bin(msg.data[1]),
                                     retain=1)

    except KeyboardInterrupt:
        pass
    finally:
        bus.shutdown()
Пример #11
0
 def setUp(self):
     self.node1 = Bus("test", bustype="virtual", preserve_timestamps=True)
     self.node2 = Bus("test", bustype="virtual")