Python can.Bus() Examples

The following are 12 code examples of can.Bus(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module can , or try the search function .
Example #1
Source File: test_can_connector.py    From thingsboard-gateway with Apache License 2.0 6 votes vote down vote up
def _create_bus(self):
        return Bus(
            channel="virtual_channel",
            bustype="virtual",
            receive_own_messages=False,
            is_fd=True
        ) 
Example #2
Source File: test_can_connector.py    From thingsboard-gateway with Apache License 2.0 5 votes vote down vote up
def _create_bus(self):
        return Bus(
            channel="virtual_channel",
            bustype="virtual",
            receive_own_messages=False
        ) 
Example #3
Source File: test_can_connector.py    From thingsboard-gateway with Apache License 2.0 5 votes vote down vote up
def _create_bus(self):
        return Bus(
            channel="virtual_channel",
            bustype="virtual",
            receive_own_messages=False,
            is_fd=True
        ) 
Example #4
Source File: monitor.py    From cantools with MIT License 5 votes vote down vote up
def create_bus(self, args):
        kwargs = {}

        if args.bit_rate is not None:
            kwargs['bitrate'] = int(args.bit_rate)

        try:
            return can.Bus(bustype=args.bus_type,
                           channel=args.channel,
                           **kwargs)
        except:
            raise Exception(
                "Failed to create CAN bus with bustype='{}' and "
                "channel='{}'.".format(args.bus_type,
                                       args.channel)) 
Example #5
Source File: python_can.py    From pyxcp with GNU General Public License v2.0 5 votes vote down vote up
def connect(self):
        self.kwargs = OrderedDict()
        # Fetch driver keyword arguments.
        self._fetch_kwargs(False)
        self._fetch_kwargs(True)
        self.bus = Bus(bustype = self.bustype, **self.kwargs)
        self.bus.set_filters(None)
        self.parent.logger.debug("Python-CAN driver: {} - {}]".format(self.bustype, self.bus))
        self.connected = True 
Example #6
Source File: CANData.py    From CANalyzat0r with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self,
                 ifaceName,
                 bitrate=500000,
                 fdBitrate=2000000,
                 isFD=False):
        """
        This method initializes the can.Message CAN interface using the passed parameters and the start() method.
        Please note the active-flag which protects the object from being deleted while being in use.

        :param ifaceName: Name of the interface as displayed by ``ifconfig -a``
        :param bitrate: Desired bitrate of the interface
        """

        self.ifaceName = ifaceName
        self.VCAN = self.checkVCAN()

        self.bitrate = bitrate if not self.VCAN else -1
        self.fdBitrate = fdBitrate if not self.VCAN else -1
        self.isFD = isFD

        self.iface = can.Bus(
            interface="socketcan",
            channel=self.ifaceName,
            receive_own_messages=False,
            fd=isFD)

        self.updateBitrate(bitrate, fdBitrate, fd=isFD)

        #: 100 ms read timeout for async reads (see :func:`readPacketAsync`)
        self.timeout = 0.1

        self.active = False 
Example #7
Source File: mock_ecu.py    From caringcaribou with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, bus=None):
        self.message_process = None
        if bus is None:
            self.bus = can.Bus(DEFAULT_INTERFACE)
        else:
            self.bus = bus 
Example #8
Source File: test_iso_15765_2.py    From caringcaribou with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        # Initialize mock ECU
        self.ecu = MockEcuIsoTp(self.ARB_ID_REQUEST, self.ARB_ID_RESPONSE)
        self.ecu.start_server()
        # Initialize virtual CAN bus
        can_bus = can.Bus(DEFAULT_INTERFACE)
        # Setup ISO-TP layer
        self.tp = iso15765_2.IsoTp(self.ARB_ID_REQUEST, self.ARB_ID_RESPONSE, bus=can_bus) 
Example #9
Source File: test_iso_14229_1.py    From caringcaribou with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        # Initialize mock ECU
        self.ecu = MockEcuIso14229(self.ARB_ID_REQUEST, self.ARB_ID_RESPONSE)
        self.ecu.start_server()
        # Initialize virtual CAN bus
        can_bus = can.Bus(DEFAULT_INTERFACE)
        # Setup diagnostics on top of ISO-TP layer
        self.tp = iso15765_2.IsoTp(self.ARB_ID_REQUEST, self.ARB_ID_RESPONSE, bus=can_bus)
        self.diagnostics = iso14229_1.Iso14229_1(self.tp)
        # Reduce timeout value to speed up testing
        self.diagnostics.P3_CLIENT = 0.5 
Example #10
Source File: can_actions.py    From caringcaribou with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, arb_id=None, notifier_enabled=True):
        """
        CanActions constructor

        :param arb_id: int default arbitration ID for object or None
        :param notifier_enabled: bool indicating whether a notifier for incoming message callbacks should be enabled
        """
        self.bus = can.Bus(DEFAULT_INTERFACE)
        self.arb_id = arb_id
        self.bruteforce_running = False
        self.notifier = None
        if notifier_enabled:
            self.enable_notifier() 
Example #11
Source File: CANData.py    From CANalyzat0r with GNU General Public License v3.0 4 votes vote down vote up
def updateBitrate(self, bitrate, fdBitrate, fd=False):
        """
        Updates the bitrate of the SocketCAN interface (if possible).

        :param bitrate: The desired bitrate in bit/s
        :return: A boolean value indicating success of updating the bitrate value
        """

        # Physical CAN or CAN FD or virtual CAN ?
        if not self.VCAN:
            # Put interface down first so the new bitrate can be applied
            cmds = []
            cmds.append("ip link set " + self.ifaceName + " down")
            cmds.append("ip link set " + self.ifaceName + " type can fd off")

            for cmd in cmds:
                process = subprocess.Popen(
                    cmd.split(),
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE)
                output, error = process.communicate()

            # prepare cmd for next call
            if fd:

                cmd = "ip link set " + self.ifaceName + " up type can bitrate " + str(
                    bitrate) + " dbitrate " + str(fdBitrate) + " fd on"

            else:
                cmd = "ip link set " + self.ifaceName + \
                    " up type can bitrate " + str(bitrate)

        else:
            cmd = "ip link set up " + self.ifaceName

        process = subprocess.Popen(
            cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        output, error = process.communicate()

        if output.decode("utf-8") == "" and error.decode("utf-8") == "":
            if self.VCAN:
                self.bitrate = -1
                self.fdBitrate = -1
                self.isFD = False
            else:
                self.bitrate = bitrate
                self.fdBitrate = fdBitrate
                self.isFD = fd

            self.iface = can.Bus(
                interface="socketcan",
                channel=self.ifaceName,
                receive_own_messages=False,
                fd=fd)

            return True

        else:
            CANData.logger.error(error.decode("utf-8"))
            return False 
Example #12
Source File: can_actions.py    From caringcaribou with GNU General Public License v3.0 4 votes vote down vote up
def auto_blacklist(bus, duration, classifier_function, print_results):
    """Listens for false positives on the CAN bus and generates an arbitration ID blacklist.

    Finds all can.Message <msg> on 'bus' where 'classifier_function(msg)' evaluates to True.
    Terminates after 'duration' seconds and returns a set of all matching arbitration IDs.
    Prints progress, time countdown and list of results if 'print_results' is True.

    :param bus: CAN bus instance
    :param duration: duration in seconds
    :param classifier_function: function which, when called upon a can.Message instance,
                                returns a bool indicating if it should be blacklisted
    :param print_results: whether progress and results should be printed to stdout
    :type bus: can.Bus
    :type duration: float
    :type classifier_function: function
    :type print_results: bool
    :return set of matching arbitration IDs to blacklist
    :rtype set(int)
    """
    if print_results:
        print("Scanning for arbitration IDs to blacklist")
    blacklist = set()
    start_time = time.time()
    end_time = start_time + duration
    while time.time() < end_time:
        if print_results:
            time_left = end_time - time.time()
            num_matches = len(blacklist)
            print("\r{0:> 5.1f} seconds left, {1} found".format(time_left, num_matches), end="")
            stdout.flush()
        # Receive message
        msg = bus.recv(0.1)
        if msg is None:
            continue
        # Classify
        if classifier_function(msg):
            # Add to blacklist
            blacklist.add(msg.arbitration_id)
    if print_results:
        num_matches = len(blacklist)
        print("\r  0.0 seconds left, {0} found".format(num_matches), end="")
        if len(blacklist) > 0:
            print("\n  Detected IDs: {0}".format(" ".join(sorted(list(map(hex, blacklist))))))
        else:
            print()
    return blacklist