INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Resets the receive and transmit queues of the PCAN Channel Remarks: A reset of the CAN controller is not performed Parameters: Channel : A TPCANHandle representing a PCAN Channel Returns: A TPCANStatus error code
def Reset( self, Channel): """ Resets the receive and transmit queues of the PCAN Channel Remarks: A reset of the CAN controller is not performed Parameters: Channel : A TPCANHandle representing a PCAN Channel Returns: A TPCANS...
Uninitializes one or all PCAN Channels initialized by CAN_Initialize Remarks: Giving the TPCANHandle value "PCAN_NONEBUS", uninitialize all initialized channels Parameters: Channel : A TPCANHandle representing a PCAN Channel Returns: A TPCANStatus error code
def Uninitialize( self, Channel): """ Uninitializes one or all PCAN Channels initialized by CAN_Initialize Remarks: Giving the TPCANHandle value "PCAN_NONEBUS", uninitialize all initialized channels Parameters: Channel : A TPCANHandle representin...
Initializes a FD capable PCAN Channel Parameters: Channel : The handle of a FD capable PCAN Channel BitrateFD : The speed for the communication (FD bit rate string) Remarks: See PCAN_BR_* values. * parameter and values must be separated by '=' * Couples of Pa...
def InitializeFD( self, Channel, BitrateFD): """ Initializes a FD capable PCAN Channel Parameters: Channel : The handle of a FD capable PCAN Channel BitrateFD : The speed for the communication (FD bit rate string) Remarks: See PCAN_BR_*...
Reads a CAN message from the receive queue of a PCAN Channel Remarks: The return value of this method is a 3-touple, where the first value is the result (TPCANStatus) of the method. The order of the values are: [0]: A TPCANStatus error code [1]: A TPCANMsg stru...
def Read( self, Channel): """ Reads a CAN message from the receive queue of a PCAN Channel Remarks: The return value of this method is a 3-touple, where the first value is the result (TPCANStatus) of the method. The order of the values are: ...
Reads a CAN message from the receive queue of a FD capable PCAN Channel Remarks: The return value of this method is a 3-touple, where the first value is the result (TPCANStatus) of the method. The order of the values are: [0]: A TPCANStatus error code [1]: A TP...
def ReadFD( self, Channel): """ Reads a CAN message from the receive queue of a FD capable PCAN Channel Remarks: The return value of this method is a 3-touple, where the first value is the result (TPCANStatus) of the method. The order of the valu...
Gets the current status of a PCAN Channel Parameters: Channel : A TPCANHandle representing a PCAN Channel Returns: A TPCANStatus error code
def GetStatus( self, Channel): """ Gets the current status of a PCAN Channel Parameters: Channel : A TPCANHandle representing a PCAN Channel Returns: A TPCANStatus error code """ try: res = self.__m_dllBasic.CAN_GetSta...
Transmits a CAN message Parameters: Channel : A TPCANHandle representing a PCAN Channel MessageBuffer: A TPCANMsg representing the CAN message to be sent Returns: A TPCANStatus error code
def Write( self, Channel, MessageBuffer): """ Transmits a CAN message Parameters: Channel : A TPCANHandle representing a PCAN Channel MessageBuffer: A TPCANMsg representing the CAN message to be sent Returns: A TPCANStatus e...
Transmits a CAN message over a FD capable PCAN Channel Parameters: Channel : The handle of a FD capable PCAN Channel MessageBuffer: A TPCANMsgFD buffer with the message to be sent Returns: A TPCANStatus error code
def WriteFD( self, Channel, MessageBuffer): """ Transmits a CAN message over a FD capable PCAN Channel Parameters: Channel : The handle of a FD capable PCAN Channel MessageBuffer: A TPCANMsgFD buffer with the message to be sent Return...
Configures the reception filter Remarks: The message filter will be expanded with every call to this function. If it is desired to reset the filter, please use the 'SetValue' function. Parameters: Channel : A TPCANHandle representing a PCAN Channel FromID : A c...
def FilterMessages( self, Channel, FromID, ToID, Mode): """ Configures the reception filter Remarks: The message filter will be expanded with every call to this function. If it is desired to reset the filter, please use the 'SetValu...
Retrieves a PCAN Channel value Remarks: Parameters can be present or not according with the kind of Hardware (PCAN Channel) being used. If a parameter is not available, a PCAN_ERROR_ILLPARAMTYPE error will be returned. The return value of this method is a 2-touple, wher...
def GetValue( self, Channel, Parameter): """ Retrieves a PCAN Channel value Remarks: Parameters can be present or not according with the kind of Hardware (PCAN Channel) being used. If a parameter is not available, a PCAN_ERROR_ILLPARAMTYP...
Returns a descriptive text of a given TPCANStatus error code, in any desired language Remarks: Parameters can be present or not according with the kind of Hardware (PCAN Channel) being used. If a parameter is not available, a PCAN_ERROR_ILLPARAMTYPE error will be returne...
def SetValue( self, Channel, Parameter, Buffer): """ Returns a descriptive text of a given TPCANStatus error code, in any desired language Remarks: Parameters can be present or not according with the kind of Hardware (PCAN Channel...
Configures or sets a PCAN Channel value Remarks: The current languages available for translation are: Neutral (0x00), German (0x07), English (0x09), Spanish (0x0A), Italian (0x10) and French (0x0C) The return value of this method is a 2-touple, where the firs...
def GetErrorText( self, Error, Language = 0): """ Configures or sets a PCAN Channel value Remarks: The current languages available for translation are: Neutral (0x00), German (0x07), English (0x09), Spanish (0x0A), Italian (0x10) and Fre...
Add a message to the log file. :param str message: an arbitrary message :param float timestamp: the absolute timestamp of the event
def log_event(self, message, timestamp=None): """Add a message to the log file. :param str message: an arbitrary message :param float timestamp: the absolute timestamp of the event """ if not message: # if empty or None logger.debug("ASCWriter: ignoring empty messag...
Returns all currently used channels as well as one other currently unused channel. .. note:: This method will run into problems if thousands of autodetected busses are used at once.
def _detect_available_configs(): """ Returns all currently used channels as well as one other currently unused channel. .. note:: This method will run into problems if thousands of autodetected busses are used at once. """ with channels_lock: ...
convert the message from the CANAL type to pythoncan type
def message_convert_rx(message_rx): """convert the message from the CANAL type to pythoncan type""" is_extended_id = bool(message_rx.flags & IS_ID_TYPE) is_remote_frame = bool(message_rx.flags & IS_REMOTE_FRAME) is_error_frame = bool(message_rx.flags & IS_ERROR_FRAME) return Message(timestamp=messa...
Shuts down connection to the device safely. :raise cam.CanError: is closing the connection did not work
def shutdown(self): """ Shuts down connection to the device safely. :raise cam.CanError: is closing the connection did not work """ status = self.can.close(self.handle) if status != CANAL_ERROR_SUCCESS: raise CanError("could not shut down bus: status == {}"....
Uses the Windows Management Instrumentation to identify serial devices. :param str serial_matcher (optional): search string for automatic detection of the device serial
def _detect_available_configs(serial_matcher=None): """ Uses the Windows Management Instrumentation to identify serial devices. :param str serial_matcher (optional): search string for automatic detection of the device serial """ if serial_matcher: channel...
Returns the main bus class for the given interface. :raises: NotImplementedError if the interface is not known :raises: ImportError if there was a problem while importing the interface or the bus class within that
def _get_class_for_interface(interface): """ Returns the main bus class for the given interface. :raises: NotImplementedError if the interface is not known :raises: ImportError if there was a problem while importing the interface or the bus class within that ...
Detect all configurations/channels that the interfaces could currently connect with. This might be quite time consuming. Automated configuration detection may not be implemented by every interface on every platform. This method will not raise an error in that case, but with rather return an empty ...
def detect_available_configs(interfaces=None): """Detect all configurations/channels that the interfaces could currently connect with. This might be quite time consuming. Automated configuration detection may not be implemented by every interface on every platform. This method will not raise a...
Add a bus for notification. :param can.BusABC bus: CAN bus instance.
def add_bus(self, bus): """Add a bus for notification. :param can.BusABC bus: CAN bus instance. """ if self._loop is not None and hasattr(bus, 'fileno') and bus.fileno() >= 0: # Use file descriptor to watch for messages reader = bus.fileno() ...
Stop notifying Listeners when new :class:`~can.Message` objects arrive and call :meth:`~can.Listener.stop` on each Listener. :param float timeout: Max time in seconds to wait for receive threads to finish. Should be longer than timeout given at instantiation.
def stop(self, timeout=5): """Stop notifying Listeners when new :class:`~can.Message` objects arrive and call :meth:`~can.Listener.stop` on each Listener. :param float timeout: Max time in seconds to wait for receive threads to finish. Should be longer than timeout given...
Send a message over the serial device. :param can.Message msg: Message to send. .. note:: Flags like ``extended_id``, ``is_remote_frame`` and ``is_error_frame`` will be ignored. .. note:: If the timestamp is a float value it will be converted ...
def send(self, msg, timeout=None): """ Send a message over the serial device. :param can.Message msg: Message to send. .. note:: Flags like ``extended_id``, ``is_remote_frame`` and ``is_error_frame`` will be ignored. .. note:: If the t...
Read a message from the serial device. :param timeout: .. warning:: This parameter will be ignored. The timeout value of the channel is used. :returns: Received message and False (because not filtering as taken place). .. warning:: ...
def _recv_internal(self, timeout): """ Read a message from the serial device. :param timeout: .. warning:: This parameter will be ignored. The timeout value of the channel is used. :returns: Received message and False (because not filtering as t...
Sends a message every 20ms with no explicit timeout Sleeps for 2 seconds then stops the task.
def simple_periodic_send(bus): """ Sends a message every 20ms with no explicit timeout Sleeps for 2 seconds then stops the task. """ print("Starting to send a message every 200ms for 2s") msg = can.Message(arbitration_id=0x123, data=[1, 2, 3, 4, 5, 6], is_extended_id=False) task = bus.send_p...
Sends one CAN message. When a transmission timeout is set the firmware tries to send a message within this timeout. If it could not be sent the firmware sets the "auto delete" state. Within this state all transmit CAN messages for this channel will be deleted automatically for not block...
def send(self, msg, timeout=None): """ Sends one CAN message. When a transmission timeout is set the firmware tries to send a message within this timeout. If it could not be sent the firmware sets the "auto delete" state. Within this state all transmit CAN messages for t...
Flushes the transmit buffer. :raises can.CanError: If flushing of the transmit buffer failed.
def flush_tx_buffer(self): """ Flushes the transmit buffer. :raises can.CanError: If flushing of the transmit buffer failed. """ log.info('Flushing transmit buffer') self._ucan.reset_can(self.channel, ResetFlags.RESET_ONLY_TX_BUFF)
Calculates AMR and ACR using CAN-ID as parameter. :param bool extended: if True parameters from_id and to_id contains 29-bit CAN-ID :param int from_id: first CAN-ID which should be received :param int to_id: last CAN-ID which should be received :pa...
def create_filter(extended, from_id, to_id, rtr_only, rtr_too): """ Calculates AMR and ACR using CAN-ID as parameter. :param bool extended: if True parameters from_id and to_id contains 29-bit CAN-ID :param int from_id: first CAN-ID which should be received ...
Shuts down all CAN interfaces and hardware interface.
def shutdown(self): """ Shuts down all CAN interfaces and hardware interface. """ try: self._ucan.shutdown() except Exception as ex: log.error(ex)
Loads config dict from environmental variables (if set): * CAN_INTERFACE * CAN_CHANNEL * CAN_BITRATE
def load_environment_config(): """ Loads config dict from environmental variables (if set): * CAN_INTERFACE * CAN_CHANNEL * CAN_BITRATE """ mapper = { 'interface': 'CAN_INTERFACE', 'channel': 'CAN_CHANNEL', 'bitrate': 'CAN_BITRATE', } return dict( (k...
Loads configuration from file with following content:: [default] interface = socketcan channel = can0 :param path: path to config file. If not specified, several sensible default locations are tried depending on platform. :param section: name of the section to r...
def load_file_config(path=None, section=None): """ Loads configuration from file with following content:: [default] interface = socketcan channel = can0 :param path: path to config file. If not specified, several sensible default locations are tried depending on pla...
Returns a dict with configuration details which is loaded from (in this order): - config - can.rc - Environment variables CAN_INTERFACE, CAN_CHANNEL, CAN_BITRATE - Config files ``/etc/can.conf`` or ``~/.can`` or ``~/.canrc`` where the latter may add or replace values of the former. Interface...
def load_config(path=None, config=None, context=None): """ Returns a dict with configuration details which is loaded from (in this order): - config - can.rc - Environment variables CAN_INTERFACE, CAN_CHANNEL, CAN_BITRATE - Config files ``/etc/can.conf`` or ``~/.can`` or ``~/.canrc`` where...
Set the logging level for the "can" logger. Expects one of: 'critical', 'error', 'warning', 'info', 'debug', 'subdebug'
def set_logging_level(level_name=None): """Set the logging level for the "can" logger. Expects one of: 'critical', 'error', 'warning', 'info', 'debug', 'subdebug' """ can_logger = logging.getLogger('can') try: can_logger.setLevel(getattr(logging, level_name.upper())) except AttributeErr...
Calculate the DLC from data length. :param int length: Length in number of bytes (0-64) :returns: DLC (0-15) :rtype: int
def len2dlc(length): """Calculate the DLC from data length. :param int length: Length in number of bytes (0-64) :returns: DLC (0-15) :rtype: int """ if length <= 8: return length for dlc, nof_bytes in enumerate(CAN_FD_DLC): if nof_bytes >= length: return dlc ...
Try to convert the channel to an integer. :param channel: Channel string (e.g. can0, CAN1) or integer :returns: Channel integer or `None` if unsuccessful :rtype: int
def channel2int(channel): """Try to convert the channel to an integer. :param channel: Channel string (e.g. can0, CAN1) or integer :returns: Channel integer or `None` if unsuccessful :rtype: int """ if channel is None: return None if isinstance(channel, int): re...
Block waiting for a message from the Bus. :type timeout: float or None :param timeout: seconds to wait for a message or None to wait indefinitely :rtype: can.Message or None :return: None on timeout or a :class:`can.Message` object. :raises can.CanError:...
def recv(self, timeout=None): """Block waiting for a message from the Bus. :type timeout: float or None :param timeout: seconds to wait for a message or None to wait indefinitely :rtype: can.Message or None :return: None on timeout or a :class:`can.Messa...
Start sending a message at a given period on this bus. The task will be active until one of the following conditions are met: - the (optional) duration expires - the Bus instance goes out of scope - the Bus instance is shutdown - :meth:`BusABC.stop_all_periodic_tasks()` is call...
def send_periodic(self, msg, period, duration=None, store_task=True): """Start sending a message at a given period on this bus. The task will be active until one of the following conditions are met: - the (optional) duration expires - the Bus instance goes out of scope - the Bu...
Default implementation of periodic message sending using threading. Override this method to enable a more efficient backend specific approach. :param can.Message msg: Message to transmit :param float period: Period in seconds between each message :param float du...
def _send_periodic_internal(self, msg, period, duration=None): """Default implementation of periodic message sending using threading. Override this method to enable a more efficient backend specific approach. :param can.Message msg: Message to transmit :param float period: ...
Stop sending any messages that were started using bus.send_periodic :param bool remove_tasks: Stop tracking the stopped tasks.
def stop_all_periodic_tasks(self, remove_tasks=True): """Stop sending any messages that were started using bus.send_periodic :param bool remove_tasks: Stop tracking the stopped tasks. """ for task in self._periodic_tasks: task.stop(remove_task=remove_tasks)
Apply filtering to all messages received by this Bus. All messages that match at least one filter are returned. If `filters` is `None` or a zero length sequence, all messages are matched. Calling without passing any filters will reset the applied filters to `None`. :pa...
def set_filters(self, filters=None): """Apply filtering to all messages received by this Bus. All messages that match at least one filter are returned. If `filters` is `None` or a zero length sequence, all messages are matched. Calling without passing any filters will reset the...
Checks whether the given message matches at least one of the current filters. See :meth:`~can.BusABC.set_filters` for details on how the filters work. This method should not be overridden. :param can.Message msg: the message to check if matching :rtype: bool ...
def _matches_filters(self, msg): """Checks whether the given message matches at least one of the current filters. See :meth:`~can.BusABC.set_filters` for details on how the filters work. This method should not be overridden. :param can.Message msg: the message to ch...
Checks if function :meth:`UcanServer.read_can_msg` returns a valid CAN message. :param ReturnCode result: Error code of the function. :return: True if a valid CAN messages was received, otherwise False. :rtype: bool
def check_valid_rx_can_msg(result): """ Checks if function :meth:`UcanServer.read_can_msg` returns a valid CAN message. :param ReturnCode result: Error code of the function. :return: True if a valid CAN messages was received, otherwise False. :rtype: bool """ return (result.value == ReturnC...
Checks if function :meth:`UcanServer.write_can_msg` successfully wrote CAN message(s). While using :meth:`UcanServer.write_can_msg_ex` the number of sent CAN messages can be less than the number of CAN messages which should be sent. :param ReturnCode result: Error code of the function. :return: True i...
def check_tx_ok(result): """ Checks if function :meth:`UcanServer.write_can_msg` successfully wrote CAN message(s). While using :meth:`UcanServer.write_can_msg_ex` the number of sent CAN messages can be less than the number of CAN messages which should be sent. :param ReturnCode result: Error code...
Checks if any function returns an error from USB-CAN-library. :param ReturnCode result: Error code of the function. :return: True if a function returned error, otherwise False. :rtype: bool
def check_error(result): """ Checks if any function returns an error from USB-CAN-library. :param ReturnCode result: Error code of the function. :return: True if a function returned error, otherwise False. :rtype: bool """ return (result.value != ReturnCode.SUCCESSFUL) and (result.value < R...
Checks if any function returns an error from firmware in USB-CANmodul. :param ReturnCode result: Error code of the function. :return: True if a function returned error from firmware, otherwise False. :rtype: bool
def check_error_cmd(result): """ Checks if any function returns an error from firmware in USB-CANmodul. :param ReturnCode result: Error code of the function. :return: True if a function returned error from firmware, otherwise False. :rtype: bool """ return (result.value >= ReturnCode.ERRCMD...
Initializes the device with the corresponding serial or device number. :param int or None serial: Serial number of the USB-CANmodul. :param int device_number: Device number (0 – 254, or :const:`ANY_MODULE` for the first device).
def init_hardware(self, serial=None, device_number=ANY_MODULE): """ Initializes the device with the corresponding serial or device number. :param int or None serial: Serial number of the USB-CANmodul. :param int device_number: Device number (0 – 254, or :const:`ANY_MODULE` for the first...
Initializes a specific CAN channel of a device. :param int channel: CAN channel to be initialized (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :param int BTR: Baud rate register BTR0 as high byte, baud rate register BTR1 as low byte (see enum :class:`Baudrate`). :pa...
def init_can(self, channel=Channel.CHANNEL_CH0, BTR=Baudrate.BAUD_1MBit, baudrate=BaudrateEx.BAUDEX_USE_BTR01, AMR=AMR_ALL, ACR=ACR_ALL, mode=Mode.MODE_NORMAL, OCR=OutputControl.OCR_DEFAULT, rx_buffer_entries=DEFAULT_BUFFER_ENTRIES, tx_buffer_entries=DEFAULT_BUFFER_ENTRIES): ""...
Reads one or more CAN-messages from the buffer of the specified CAN channel. :param int channel: CAN channel to read from (:data:`Channel.CHANNEL_CH0`, :data:`Channel.CHANNEL_CH1`, :data:`Channel.CHANNEL_ANY`). :param int count: The number of CAN messages to be received. ...
def read_can_msg(self, channel, count): """ Reads one or more CAN-messages from the buffer of the specified CAN channel. :param int channel: CAN channel to read from (:data:`Channel.CHANNEL_CH0`, :data:`Channel.CHANNEL_CH1`, :data:`Channel.CHANNEL_ANY`). :param i...
Transmits one ore more CAN messages through the specified CAN channel of the device. :param int channel: CAN channel, which is to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :param list(CanMsg) can_msg: List of CAN message structure (see structure :class:`CanMsg`)....
def write_can_msg(self, channel, can_msg): """ Transmits one ore more CAN messages through the specified CAN channel of the device. :param int channel: CAN channel, which is to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :param list(CanMsg) can_msg:...
This function is used to configure the baud rate of specific CAN channel of a device. :param int channel: CAN channel, which is to be configured (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :param int BTR: Baud rate register BTR0 as high byte, baud rate register...
def set_baudrate(self, channel, BTR, baudarate): """ This function is used to configure the baud rate of specific CAN channel of a device. :param int channel: CAN channel, which is to be configured (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :param int BTR:...
This function is used to change the acceptance filter values for a specific CAN channel on a device. :param int channel: CAN channel, which is to be configured (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :param int AMR: Acceptance filter mask (AMR). :param int ACR:...
def set_acceptance(self, channel=Channel.CHANNEL_CH0, AMR=AMR_ALL, ACR=ACR_ALL): """ This function is used to change the acceptance filter values for a specific CAN channel on a device. :param int channel: CAN channel, which is to be configured (:data:`Channel.CHANNEL_CH0` or :data:...
Returns the error status of a specific CAN channel. :param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :return: Tuple with CAN and USB status (see structure :class:`Status`). :rtype: tuple(int, int)
def get_status(self, channel=Channel.CHANNEL_CH0): """ Returns the error status of a specific CAN channel. :param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :return: Tuple with CAN and USB status (see structure :class:`Status`). ...
Reads the message counters of the specified CAN channel. :param int channel: CAN channel, which is to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :return: Tuple with number of CAN messages sent and received. :rtype: tuple(int, int)
def get_msg_count_info(self, channel=Channel.CHANNEL_CH0): """ Reads the message counters of the specified CAN channel. :param int channel: CAN channel, which is to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :return: Tuple with number of CAN messag...
Resets a CAN channel of a device (hardware reset, empty buffer, and so on). :param int channel: CAN channel, to be reset (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :param int flags: Flags defines what should be reset (see enum :class:`ResetFlags`).
def reset_can(self, channel=Channel.CHANNEL_CH0, flags=ResetFlags.RESET_ALL): """ Resets a CAN channel of a device (hardware reset, empty buffer, and so on). :param int channel: CAN channel, to be reset (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :param int flags: Flag...
Returns the extended hardware information of a device. With multi-channel USB-CANmoduls the information for both CAN channels are returned separately. :return: Tuple with extended hardware information structure (see structure :class:`HardwareInfoEx`) and structures with informat...
def get_hardware_info(self): """ Returns the extended hardware information of a device. With multi-channel USB-CANmoduls the information for both CAN channels are returned separately. :return: Tuple with extended hardware information structure (see structure :class:`Hardware...
Defines a list of CAN messages for automatic transmission. :param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :param list(CanMsg) can_msg: List of CAN messages (up to 16, see structure :class:`CanMsg`), or None to delete an older list.
def define_cyclic_can_msg(self, channel, can_msg=None): """ Defines a list of CAN messages for automatic transmission. :param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :param list(CanMsg) can_msg: List of CAN messages ...
Reads back the list of CAN messages for automatically sending. :param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :param int count: The number of cyclic CAN messages to be received. :return: List of received CAN messages (up to 16, see stru...
def read_cyclic_can_msg(self, channel, count): """ Reads back the list of CAN messages for automatically sending. :param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :param int count: The number of cyclic CAN messages to be received....
Returns the number of pending CAN messages. :param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :param int flags: Flags specifies which buffers should be checked (see enum :class:`PendingFlags`). :return: The number of pending messages. ...
def get_msg_pending(self, channel, flags): """ Returns the number of pending CAN messages. :param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :param int flags: Flags specifies which buffers should be checked (see enum :class:`Pendin...
Reads the current value of the error counters within the CAN controller. :param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :return: Tuple with the TX and RX error counter. :rtype: tuple(int, int) .. note:: Only available for syste...
def get_can_error_counter(self, channel): """ Reads the current value of the error counters within the CAN controller. :param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :return: Tuple with the TX and RX error counter. :rtyp...
Sets the transmission timeout. :param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :param float timeout: Transmit timeout in seconds (value 0 disables this feature).
def set_tx_timeout(self, channel, timeout): """ Sets the transmission timeout. :param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :param float timeout: Transmit timeout in seconds (value 0 disables this feature). """ ...
Shuts down all CAN interfaces and/or the hardware interface. :param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0`, :data:`Channel.CHANNEL_CH1` or :data:`Channel.CHANNEL_ALL`) :param bool shutdown_hardware: If true then the hardware interface will be closed to...
def shutdown(self, channel=Channel.CHANNEL_ALL, shutdown_hardware=True): """ Shuts down all CAN interfaces and/or the hardware interface. :param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0`, :data:`Channel.CHANNEL_CH1` or :data:`Channel.CHANNEL_ALL`)...
Converts a given CAN status value to the appropriate message string. :param can_status: CAN status value from method :meth:`get_status` (see enum :class:`CanStatus`) :return: Status message string. :rtype: str
def get_can_status_message(can_status): """ Converts a given CAN status value to the appropriate message string. :param can_status: CAN status value from method :meth:`get_status` (see enum :class:`CanStatus`) :return: Status message string. :rtype: str """ statu...
Converts a given baud rate value for GW-001/GW-002 to the appropriate message string. :param Baudrate baudrate: Bus Timing Registers, BTR0 in high order byte and BTR1 in low order byte (see enum :class:`Baudrate`) :return: Baud rate message string. :rtype: str
def get_baudrate_message(baudrate): """ Converts a given baud rate value for GW-001/GW-002 to the appropriate message string. :param Baudrate baudrate: Bus Timing Registers, BTR0 in high order byte and BTR1 in low order byte (see enum :class:`Baudrate`) :return: ...
Converts a given baud rate value for systec USB-CANmoduls to the appropriate message string. :param BaudrateEx baudrate_ex: Bus Timing Registers (see enum :class:`BaudrateEx`) :return: Baud rate message string. :rtype: str
def get_baudrate_ex_message(baudrate_ex): """ Converts a given baud rate value for systec USB-CANmoduls to the appropriate message string. :param BaudrateEx baudrate_ex: Bus Timing Registers (see enum :class:`BaudrateEx`) :return: Baud rate message string. :rtype: str ""...
Checks if the version is equal or higher than a specified value. :param int version: Version number to be checked. :param int cmp_major: Major version to be compared with. :param int cmp_minor: Minor version to be compared with. :return: True if equal or higher, otherwise False. ...
def check_version_is_equal_or_higher(cls, version, cmp_major, cmp_minor): """ Checks if the version is equal or higher than a specified value. :param int version: Version number to be checked. :param int cmp_major: Major version to be compared with. :param int cmp_minor: Minor v...
Checks whether the module supports automatically transmission of cyclic CAN messages. :param HardwareInfoEx hw_info_ex: Extended hardware information structure (see method :meth:`get_hardware_info`). :return: True when the module does support cyclic CAN messages, otherwise False. :r...
def check_support_cyclic_msg(cls, hw_info_ex): """ Checks whether the module supports automatically transmission of cyclic CAN messages. :param HardwareInfoEx hw_info_ex: Extended hardware information structure (see method :meth:`get_hardware_info`). :return: True when the m...
Checks whether the module supports a user I/O port. :param HardwareInfoEx hw_info_ex: Extended hardware information structure (see method :meth:`get_hardware_info`). :return: True when the module supports a user I/O port, otherwise False. :rtype: bool
def check_support_user_port(cls, hw_info_ex): """ Checks whether the module supports a user I/O port. :param HardwareInfoEx hw_info_ex: Extended hardware information structure (see method :meth:`get_hardware_info`). :return: True when the module supports a user I/O port, oth...
Checks whether the module supports the usage of USB-CANnetwork driver. :param HardwareInfoEx hw_info_ex: Extended hardware information structure (see method :meth:`get_hardware_info`). :return: True when the module does support the usage of the USB-CANnetwork driver, otherwise False. ...
def check_support_ucannet(cls, hw_info_ex): """ Checks whether the module supports the usage of USB-CANnetwork driver. :param HardwareInfoEx hw_info_ex: Extended hardware information structure (see method :meth:`get_hardware_info`). :return: True when the module does support...
Calculates AMR using CAN-ID range as parameter. :param bool is_extended: If True parameters from_id and to_id contains 29-bit CAN-ID. :param int from_id: First CAN-ID which should be received. :param int to_id: Last CAN-ID which should be received. :param bool rtr_only: If True only RTR...
def calculate_amr(cls, is_extended, from_id, to_id, rtr_only=False, rtr_too=True): """ Calculates AMR using CAN-ID range as parameter. :param bool is_extended: If True parameters from_id and to_id contains 29-bit CAN-ID. :param int from_id: First CAN-ID which should be received. ...
Is the actual callback function for :meth:`init_hw_connect_control_ex`. :param event: Event (:data:`CbEvent.EVENT_CONNECT`, :data:`CbEvent.EVENT_DISCONNECT` or :data:`CbEvent.EVENT_FATALDISCON`). :param param: Additional parameter depending on the event. - CbEvent.EVENT_...
def _connect_control(self, event, param, arg): """ Is the actual callback function for :meth:`init_hw_connect_control_ex`. :param event: Event (:data:`CbEvent.EVENT_CONNECT`, :data:`CbEvent.EVENT_DISCONNECT` or :data:`CbEvent.EVENT_FATALDISCON`). :param param: Ad...
Is called if a working event occurred. :param int handle: USB-CAN-Handle returned by the function :meth:`init_hardware`. :param int event: Event type. :param int channel: CAN channel (:data:`Channel.CHANNEL_CH0`, :data:`Channel.CHANNEL_CH1` or :data:`Channel.CHANNEL_ANY`). :...
def _callback(self, handle, event, channel, arg): """ Is called if a working event occurred. :param int handle: USB-CAN-Handle returned by the function :meth:`init_hardware`. :param int event: Event type. :param int channel: CAN channel (:data:`Channel.CHANNEL_CH0`, ...
Colors API using schema This example is using marshmallow schemas
def get(self, palette): """ Colors API using schema This example is using marshmallow schemas """ all_colors = { 'cmyk': ['cian', 'magenta', 'yellow', 'black'], 'rgb': ['red', 'green', 'blue'] } if palette == 'all': result = all...
Custom validation function which drops parameter '_id' if present in data
def drop_id_validate(data, schema): """ Custom validation function which drops parameter '_id' if present in data """ jsonschema.validate(data, schema) if data.get('_id') is not None: del data['_id']
Custom validation function which inserts a timestamp for when the validation occurred
def timestamping_validate(data, schema): """ Custom validation function which inserts a timestamp for when the validation occurred """ jsonschema.validate(data, schema) data['timestamp'] = str(time.time())
Custom validation function which inserts an special flag depending on the cat's name
def special_validate(data, schema): """ Custom validation function which inserts an special flag depending on the cat's name """ jsonschema.validate(data, schema) data['special'] = str(data['name'] == 'Garfield').lower()
Custom validation error handler which produces 404 Bad Request response in case validation fails and returns the error
def validation_error_inform_error(err, data, schema): """ Custom validation error handler which produces 404 Bad Request response in case validation fails and returns the error """ abort(Response( json.dumps({'error': str(err), 'data': data, 'schema': schema}), status=HTTPStatus.BAD_...
Custom validation error handler which attempts alternative validation
def validation_error_try_to_accept(err, data, schema): """ Custom validation error handler which attempts alternative validation """ if not isinstance(err, ValidationError): abort(Response(err, status=HTTPStatus.BAD_REQUEST)) alernative_schema = dict(schema) alernative_schema['prope...
Convert Marshmallow schemas to dict definitions Also updates the optional definitions argument with any definitions entries contained within the schema.
def convert_schemas(d, definitions=None): """ Convert Marshmallow schemas to dict definitions Also updates the optional definitions argument with any definitions entries contained within the schema. """ if Schema is None: raise RuntimeError('Please install marshmallow and apispec') ...
Converts APISpec dict to flasgger suitable dict also adds definitions and paths (optional)
def to_flasgger(self, app=None, definitions=None, paths=None): """ Converts APISpec dict to flasgger suitable dict also adds definitions and paths (optional) """ if Schema is None: raise RuntimeError('Please install marshmallow and apispec') return flasgger.u...
If validation=True perform validation
def dispatch_request(self, *args, **kwargs): """ If validation=True perform validation """ if self.validation: specs = {} attrs = flasgger.constants.OPTIONAL_FIELDS + [ 'parameters', 'definitions', 'responses', 'summary', 'descripti...
Update target dictionary with values from the source, recursively. List items will be merged.
def merge_specs(target, source): """ Update target dictionary with values from the source, recursively. List items will be merged. """ for key, value in source.items(): if isinstance(value, dict): node = target.setdefault(key, {}) merge_specs(node, value) eli...
Takes a filename.yml, a dictionary or object and loads swagger specs. :param specs: a filepath, a dictionary or an object :param filetype: yml or yaml (json and py to be implemented) :param endpoint: endpoint to build definition name :param methods: method to build method based specs :param validat...
def swag_from( specs=None, filetype=None, endpoint=None, methods=None, validation=False, schema_id=None, data=None, definition=None, validation_function=None, validation_error_handler=None): """ Takes a filename.yml, a dictionary or object and loads swagger specs. :param specs: a fi...
This method is available to use YAML swagger definitions file or specs (dict or object) to validate data against its jsonschema. example: validate({"item": 1}, 'item_schema', 'defs.yml', root=__file__) validate(request.json, 'User', specs={'definitions': {'User': ...}}) :param data: data t...
def validate( data=None, schema_id=None, filepath=None, root=None, definition=None, specs=None, validation_function=None, validation_error_handler=None): """ This method is available to use YAML swagger definitions file or specs (dict or object) to validate data against its jsonschema. ...
Converts apispec object in to flasgger definitions template :param app: Current app :param spec: apispec.APISpec :param definitions: a list of [Schema, ..] or [('Name', Schema), ..] :param paths: A list of flask views
def apispec_to_template(app, spec, definitions=None, paths=None): """ Converts apispec object in to flasgger definitions template :param app: Current app :param spec: apispec.APISpec :param definitions: a list of [Schema, ..] or [('Name', Schema), ..] :param paths: A list of flask views """ ...
Converts inner OrderedDict to bare dict
def ordered_dict_to_dict(d): """ Converts inner OrderedDict to bare dict """ ret = {} new_d = deepcopy(d) for k, v in new_d.items(): if isinstance(v, OrderedDict): v = dict(v) if isinstance(v, dict): v = ordered_dict_to_dict(v) ret[k] = v retur...
*nix to python module path
def pathify(basenames, examples_dir="examples/"): # pragma: no cover """*nix to python module path""" example = examples_dir.replace("/", ".") return [example + basename for basename in basenames]
All example modules
def get_examples(examples_dir="examples/"): # pragma: no cover """All example modules""" all_files = os.listdir(examples_dir) python_files = [f for f in all_files if is_python_file(f)] basenames = [remove_suffix(f) for f in python_files] modules = [import_module(module) for module in pathify(basena...
If `file:` is provided import the file.
def get_path_from_doc(full_doc): """ If `file:` is provided import the file. """ swag_path = full_doc.replace('file:', '').strip() swag_type = swag_path.split('.')[-1] return swag_path, swag_type
Load specs from YAML file
def load_from_file(swag_path, swag_type='yml', root_path=None): """ Load specs from YAML file """ if swag_type not in ('yaml', 'yml'): raise AttributeError("Currently only yaml or yml supported") # TODO: support JSON try: enc = detect_by_bom(swag_path) with codecs.op...
Gets swag data for method/view docstring
def parse_docstring(obj, process_doc, endpoint=None, verb=None): """ Gets swag data for method/view docstring """ first_line, other_lines, swag = None, None, None full_doc = None swag_path = getattr(obj, 'swag_path', None) swag_type = getattr(obj, 'swag_type', 'yml') swag_paths = getatt...
Get file path for object and returns its dirname
def get_root_path(obj): """ Get file path for object and returns its dirname """ try: filename = os.path.abspath(obj.__globals__['__file__']) except (KeyError, AttributeError): if getattr(obj, '__wrapped__', None): # decorator package has been used in view ret...
Gets swag data from docstring for class based definitions
def parse_definition_docstring(obj, process_doc): """ Gets swag data from docstring for class based definitions """ doc_lines, swag = None, None full_doc = None swag_path = getattr(obj, 'swag_path', None) swag_type = getattr(obj, 'swag_type', 'yml') if swag_path is not None: fu...
Supports `import: otherfile.yml` in docstring specs
def parse_imports(full_doc, root_path=None): """ Supports `import: otherfile.yml` in docstring specs """ regex = re.compile('import: "(.*)"') import_prop = regex.search(full_doc) if import_prop: start = import_prop.start() spaces_num = start - full_doc.rfind('\n', 0, start) - 1 ...
Since we couldn't be bothered to register models elsewhere our definitions need to be extracted from the parameters. We require an 'id' field for the schema to be correctly added to the definitions list.
def extract_definitions(alist, level=None, endpoint=None, verb=None, prefix_ids=False): """ Since we couldn't be bothered to register models elsewhere our definitions need to be extracted from the parameters. We require an 'id' field for the schema to be correctly added to th...
Return True if dispatch_request is swaggable
def has_valid_dispatch_view_docs(endpoint): """ Return True if dispatch_request is swaggable """ klass = endpoint.__dict__.get('view_class', None) return klass and hasattr(klass, 'dispatch_request') \ and hasattr(endpoint, 'methods') \ and getattr(klass, 'dispatch_request').__doc__
Return True if obj is MethodView
def is_valid_method_view(endpoint): """ Return True if obj is MethodView """ klass = endpoint.__dict__.get('view_class', None) try: return issubclass(klass, MethodView) except TypeError: return False
Identify vendor extension fields and extract them into a new dictionary. Examples: >>> get_vendor_extension_fields({'test': 1}) {} >>> get_vendor_extension_fields({'test': 1, 'x-test': 2}) {'x-test': 2}
def get_vendor_extension_fields(mapping): """ Identify vendor extension fields and extract them into a new dictionary. Examples: >>> get_vendor_extension_fields({'test': 1}) {} >>> get_vendor_extension_fields({'test': 1, 'x-test': 2}) {'x-test': 2} """ return {k: v fo...
User authenticate method. --- description: Authenticate user with supplied credentials. parameters: - name: username in: formData type: string required: true - name: password in: formData type: string required: true responses: 200: ...
def login(): """ User authenticate method. --- description: Authenticate user with supplied credentials. parameters: - name: username in: formData type: string required: true - name: password in: formData type: string required: true res...
The data under /apidocs json or Swagger UI
def get(self): """ The data under /apidocs json or Swagger UI """ base_endpoint = self.config.get('endpoint', 'flasgger') specs = [ { "url": url_for(".".join((base_endpoint, spec['endpoint']))), "title": spec.get('title', 'API S...
Initialize the app with Swagger plugin
def init_app(self, app, decorators=None): """ Initialize the app with Swagger plugin """ self.decorators = decorators or self.decorators self.app = app self.load_config(app) # self.load_apispec(app) if self.template_file is not None: self.temp...
Returns all werkzeug rules
def get_url_mappings(self, rule_filter=None): """ Returns all werkzeug rules """ rule_filter = rule_filter or (lambda rule: True) app_rules = [ rule for rule in current_app.url_map.iter_rules() if rule_filter(rule) ] return app_rules