Python can.CanError() Examples

The following are 12 code examples of can.CanError(). 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: can_connector.py    From thingsboard-gateway with Apache License 2.0 6 votes vote down vote up
def send_data_to_bus(self, data, config, data_check=True, raise_exception=False):
        try:
            self.__bus.send(Message(arbitration_id=config["nodeId"],
                                    is_extended_id=config.get("isExtendedId", self.DEFAULT_EXTENDED_ID_FLAG),
                                    is_fd=config.get("isFd", self.DEFAULT_FD_FLAG),
                                    bitrate_switch=config.get("bitrateSwitch", self.DEFAULT_BITRATE_SWITCH_FLAG),
                                    data=data,
                                    check=data_check))
            return True
        except (ValueError, TypeError) as e:
            log.error("[%s] Wrong CAN message data: %s", self.get_name(), str(e))
        except CanError as e:
            log.error("[%s] Failed to send CAN message: %s", self.get_name(), str(e))
            if raise_exception:
                raise e
            else:
                self.__on_bus_error(e)
        return False 
Example #2
Source File: cansocket_python_can.py    From scapy with GNU General Public License v2.0 6 votes vote down vote up
def internal_send(self, sender, msg):
        with self.pool_mutex:
            try:
                t = self.pool[sender.name]
            except KeyError:
                return

            try:
                t.bus.send(msg)
                for sock in t.sockets:
                    if sock != sender and sock._matches_filters(msg):
                        m = copy.copy(msg)
                        m.timestamp = time.time()
                        sock.rx_queue.put(m)
            except can_CanError:
                pass 
Example #3
Source File: notifier.py    From python-j1939 with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _rx_thread(self, bus):
        msg = None
        try:
            while self._running:
                if msg is not None:
                    with self._lock:
                        for callback in self.listeners:
                            callback(msg)
                msg = bus.recv(self.timeout)

        # 
        # The next two handlers are intended to mask race conditions that can occur when 
        # we are blocked on a can-receive and close the bus.
        except CanError as err:
            if self._running:
                raise
        except ValueError as err:
            if self._running:
                raise
                
        except Exception as exc:
            self.exception = exc
            raise 
Example #4
Source File: electronic_control_unit.py    From j1939 with MIT License 6 votes vote down vote up
def connect(self, *args, **kwargs):
        """Connect to CAN bus using python-can.

        Arguments are passed directly to :class:`can.BusABC`. Typically these
        may include:

        :param channel:
            Backend specific channel for the CAN interface.
        :param str bustype:
            Name of the interface. See
            `python-can manual <https://python-can.readthedocs.io/en/latest/configuration.html#interface-names>`__
            for full list of supported interfaces.
        :param int bitrate:
            Bitrate in bit/s.

        :raises can.CanError:
            When connection fails.
        """
        self._bus = can.interface.Bus(*args, **kwargs)
        logger.info("Connected to '%s'", self._bus.channel_info)
        self._notifier = can.Notifier(self._bus, self._listeners, 1) 
Example #5
Source File: electronic_control_unit.py    From j1939 with MIT License 6 votes vote down vote up
def send_message(self, can_id, data):
        """Send a raw CAN message to the bus.

        This method may be overridden in a subclass if you need to integrate
        this library with a custom backend.
        It is safe to call this from multiple threads.

        :param int can_id:
            CAN-ID of the message (always 29-bit)
        :param data:
            Data to be transmitted (anything that can be converted to bytes)

        :raises can.CanError:
            When the message fails to be transmitted
        """

        if not self._bus:
            raise RuntimeError("Not connected to CAN bus")
        msg = can.Message(extended_id=True,
                          arbitration_id=can_id,
                          data=data
                          )
        with self._send_lock:
            self._bus.send(msg)
        # TODO: check error receivement 
Example #6
Source File: cancomm.py    From socket-test with GNU General Public License v3.0 5 votes vote down vote up
def send_msg(self, msg):
        try:
            self.bus.send(msg)
            print("Message sent on {}".format(self.bus.channel_info))
        except can.CanError:
            print("Message NOT sent") 
Example #7
Source File: __init__.py    From python-j1939 with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _process_cts(self, msg):
        logger.debug("_process_cts")
        logger.debug("MIL8: cts message is: %s" % msg)
        #logger.debug("MIL8:    len(pdu-send-buffer) = %d" % len(self._incomplete_transmitted_pdus[0][23]))


        if msg.arbitration_id.pgn.pdu_specific in self._incomplete_transmitted_pdus:
            if msg.arbitration_id.source_address in self._incomplete_transmitted_pdus[
                    msg.arbitration_id.pgn.pdu_specific]:
                # Next packet number in CTS message (Packet numbers start at 1 not 0)
                start_index = msg.data[2] - 1
                # Using total number of packets in CTS message
                end_index = start_index + msg.data[1]
                for _msg in self._incomplete_transmitted_pdus[msg.arbitration_id.pgn.pdu_specific][
                        msg.arbitration_id.source_address][start_index:end_index]:
                    logger.debug("MIL8:        msg=%s" % (_msg))
                    # TODO: Needs to be pacing if we get this working...
                    try:
                        # Shouldent send a J1939 PDU as a CAN Message unless we are careful
                        canMessage =  Message(arbitration_id=_msg.arbitration_id, data=_msg.data)
                        self.can_bus.send(canMessage)
                    except CanError:
                        
                        if self._ignore_can_send_error:
                            pass
                        raise
        logger.debug("MIL8:    _process_cts complete") 
Example #8
Source File: __init__.py    From python-j1939 with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _throttler_function(self):
        while self.can_notifier._running:
            _msg = None
            try:
                _msg = self._long_message_segment_queue.get(timeout=0.1)
            except Empty:
                pass
            if _msg is not None:
                try:
                    self.can_bus.send(_msg)
                    time.sleep(0.05)
                except CanError:
                    if self._ignore_can_send_error:
                        pass
                    raise 
Example #9
Source File: python_can.py    From pyxcp with GNU General Public License v2.0 5 votes vote down vote up
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) 
Example #10
Source File: network.py    From canopen with MIT License 5 votes vote down vote up
def connect(self, *args, **kwargs):
        """Connect to CAN bus using python-can.

        Arguments are passed directly to :class:`can.BusABC`. Typically these
        may include:

        :param channel:
            Backend specific channel for the CAN interface.
        :param str bustype:
            Name of the interface. See
            `python-can manual <https://python-can.readthedocs.io/en/latest/configuration.html#interface-names>`__
            for full list of supported interfaces.
        :param int bitrate:
            Bitrate in bit/s.

        :raises can.CanError:
            When connection fails.
        """
        # If bitrate has not been specified, try to find one node where bitrate
        # has been specified
        if "bitrate" not in kwargs:
            for node in self.nodes.values():
                if node.object_dictionary.bitrate:
                    kwargs["bitrate"] = node.object_dictionary.bitrate
                    break
        self.bus = can.interface.Bus(*args, **kwargs)
        logger.info("Connected to '%s'", self.bus.channel_info)
        self.notifier = can.Notifier(self.bus, self.listeners, 1)
        return self 
Example #11
Source File: network.py    From canopen with MIT License 5 votes vote down vote up
def send_message(self, can_id, data, remote=False):
        """Send a raw CAN message to the network.

        This method may be overridden in a subclass if you need to integrate
        this library with a custom backend.
        It is safe to call this from multiple threads.

        :param int can_id:
            CAN-ID of the message
        :param data:
            Data to be transmitted (anything that can be converted to bytes)
        :param bool remote:
            Set to True to send remote frame

        :raises can.CanError:
            When the message fails to be transmitted
        """
        if not self.bus:
            raise RuntimeError("Not connected to CAN bus")
        msg = can.Message(is_extended_id=can_id > 0x7FF,
                          arbitration_id=can_id,
                          data=data,
                          is_remote_frame=remote)
        with self.send_lock:
            self.bus.send(msg)
        self.check() 
Example #12
Source File: abstract.py    From can-prog with MIT License 5 votes vote down vote up
def _send(self, msg):
        try:
            self._iface.send(msg)
            log.debug('TX: '+canframe_to_string(msg))
        except can.CanError:
            raise IOError('Sending error')