Exemple #1
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()
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
Exemple #3
0
async def poll_elster_register(
    bus: can.Bus,
    elster_index: int,
    sender_id: int,
    receiver_id: int,
    interval: float,
    start_delay: float = 0.0,
):
    await asyncio.sleep(start_delay)

    while True:
        bus.send(
            create_can_message(
                ElsterReadRequestFrame(
                    timestamp=0,
                    sender=sender_id,
                    receiver=receiver_id,
                    elster_index=elster_index,
                )
            )
        )
        await asyncio.sleep(interval)
Exemple #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('-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()
Exemple #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()
Exemple #6
0
class PythonCAN:
    """
    """
    def __init__(self, bustype):
        self.bustype = bustype
        self.connected = False

    def init(self, parent, receive_callback):
        self.parent = parent

    def connect(self):
        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):
        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,
                        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:
                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