QCanBusDevice Class | Qt Serial Bus | Qt 6.10.3
Description: The QCanBusDevice class is the interface class for CAN bus.

- Qt 6.10
- Qt Serial Bus
- C++ Classes
- QCanBusDevice
- Qt 6.10.3 Reference Documentation

# QCanBusDevice Class

The QCanBusDevice class is the interface class for CAN bus. More...

Header: | `#include <QCanBusDevice>`
CMake: | `find_package(Qt6 REQUIRED COMPONENTS SerialBus)` `target_link_libraries(mytarget PRIVATE Qt6::SerialBus)`
qmake: | `QT += serialbus`
Inherits: | QObject

- List of all members, including inherited members

## Public Types

struct | Filter
enum | CanBusDeviceState { UnconnectedState, ConnectingState, ConnectedState, ClosingState }
enum | CanBusError { NoError, ReadError, WriteError, ConnectionError, ConfigurationError, …, TimeoutError }
enum class | CanBusStatus { Unknown, Good, Warning, Error, BusOff }
enum | ConfigurationKey { RawFilterKey, ErrorFilterKey, LoopbackKey, ReceiveOwnKey, BitRateKey, …, UserKey }
enum | Direction { Input, Output, AllDirections }
flags | Directions

## Public Functions

| QCanBusDevice(QObject *parent = nullptr)
virtual QCanBusDevice::CanBusStatus | busStatus()
void | clear(QCanBusDevice::Directions direction = Direction::AllDirections)
QList<QCanBusDevice::ConfigurationKey> | configurationKeys() const
QVariant | configurationParameter(QCanBusDevice::ConfigurationKey key) const
bool | connectDevice()
`(since 6.2)` virtual QCanBusDeviceInfo | deviceInfo() const
void | disconnectDevice()
QCanBusDevice::CanBusError | error() const
QString | errorString() const
qint64 | framesAvailable() const
qint64 | framesToWrite() const
virtual bool | hasBusStatus() const
virtual QString | interpretErrorFrame(const QCanBusFrame &frame) = 0
QList<QCanBusFrame> | readAllFrames()
QCanBusFrame | readFrame()
virtual void | resetController()
virtual void | setConfigurationParameter(QCanBusDevice::ConfigurationKey key, const QVariant &value)
QCanBusDevice::CanBusDeviceState | state() const
virtual bool | waitForFramesReceived(int msecs)
virtual bool | waitForFramesWritten(int msecs)
virtual bool | writeFrame(const QCanBusFrame &frame) = 0

## Signals

void | errorOccurred(QCanBusDevice::CanBusError)
void | framesReceived()
void | framesWritten(qint64 framesCount)
void | stateChanged(QCanBusDevice::CanBusDeviceState state)

## Protected Functions

void | clearError()
virtual void | close() = 0
QCanBusFrame | dequeueOutgoingFrame()
void | enqueueOutgoingFrame(const QCanBusFrame &newFrame)
void | enqueueReceivedFrames(const QList<QCanBusFrame> &newFrames)
bool | hasOutgoingFrames() const
virtual bool | open() = 0
void | setError(const QString &errorText, QCanBusDevice::CanBusError errorId)
void | setState(QCanBusDevice::CanBusDeviceState newState)

## Detailed Description

QCanBusDevice communicates with a CAN plugin providing users with a convenient API. The CAN plugin must be specified during the object creation.

## Member Type Documentation

### enum QCanBusDevice::CanBusDeviceState

This enum describes all possible device states.

Constant | Value | Description
--- | --- | ---
`QCanBusDevice::UnconnectedState` | `0` | The device is disconnected.
`QCanBusDevice::ConnectingState` | `1` | The device is being connected.
`QCanBusDevice::ConnectedState` | `2` | The device is connected to the CAN bus.
`QCanBusDevice::ClosingState` | `3` | The device is being closed.

### enum QCanBusDevice::CanBusError

This enum describes all the possible error conditions.

Constant | Value | Description
--- | --- | ---
`QCanBusDevice::NoError` | `0` | No errors have occurred.
`QCanBusDevice::ReadError` | `1` | An error occurred during a read operation.
`QCanBusDevice::WriteError` | `2` | An error occurred during a write operation.
`QCanBusDevice::ConnectionError` | `3` | An error occurred when attempting to open the plugin.
`QCanBusDevice::ConfigurationError` | `4` | An error occurred when attempting to set a configuration parameter.
`QCanBusDevice::UnknownError` | `5` | An unknown error occurred.
`QCanBusDevice::OperationError` | `6` | An operation was attempted while the device was in a state that did not permit it. This enum was introduced in Qt 5.14.
`QCanBusDevice::TimeoutError` | `7` | An timeout occurred while waiting for frames written or received. This enum was introduced in Qt 5.14.

### enum class QCanBusDevice::CanBusStatus

This enum describes possible CAN bus status values.

Constant | Value | Description
--- | --- | ---
`QCanBusDevice::CanBusStatus::Unknown` | `0` | The CAN bus status is unknown (e.g. not supported by the CAN plugin).
`QCanBusDevice::CanBusStatus::Good` | `1` | The CAN controller is fully operational
`QCanBusDevice::CanBusStatus::Warning` | `2` | The CAN controller is in warning status
`QCanBusDevice::CanBusStatus::Error` | `3` | The CAN controller is in error status (no longer sending CAN frames)
`QCanBusDevice::CanBusStatus::BusOff` | `4` | The CAN controller is in bus off status (disconnected from the CAN bus)

### enum QCanBusDevice::ConfigurationKey

This enum describes the possible configuration options for the CAN bus connection.

Constant | Value | Description
--- | --- | ---
`QCanBusDevice::RawFilterKey` | `0` | This configuration determines the type of CAN bus frames that the current device accepts. The expected value is `QList<QCanBusDevice::Filter>`. Passing an empty list clears all previously set filters including default filters. For more details see QCanBusDevice::Filter.
`QCanBusDevice::ErrorFilterKey` | `1` | This key defines the type of error that should be forwarded via the current connection. The associated value should be of type QCanBusFrame::FrameErrors.
`QCanBusDevice::LoopbackKey` | `2` | This key defines whether the CAN bus device should operate in loopback mode. Loopback means, whenever a CAN frame is transmitted on the CAN bus, a local echo of this frame is sent to all applications connected to this CAN device. The expected value for this key is `bool`.
`QCanBusDevice::ReceiveOwnKey` | `3` | This key defines whether this CAN device receives its own send frames. This can be used to check if the transmission was successful. The expected value for this key is `bool`.
`QCanBusDevice::BitRateKey` | `4` | This key defines the CAN bitrate in bits per second. With CAN FD, the payload can be transmitted at a higher data bitrate, if QCanBusFrame::hasBitrateSwitch() is set. In this case, `QCanBusDevice::BitRateKey` is only used for the CAN ID arbitration phase. See also `QCanBusDevice::DataBitRateKey`
`QCanBusDevice::CanFdKey` | `5` | This key defines whether sending and receiving of CAN FD frames should be enabled. The expected value for this key is `bool`.
`QCanBusDevice::DataBitRateKey` | `6` | This key defines the CAN FD payload bitrate in bits per second. CAN FD allows to transmit the payload of frames with QCanBusFrame::hasBitrateSwitch() flag at a higher data bitrate, after the arbitration phase at the nominal bitrate is finished. This enum value was introduced in Qt 5.9. See also `QCanBusDevice::BitRateKey`
`QCanBusDevice::ProtocolKey` | `7` | This key allows to specify another protocol. For now, this parameter can only be set and used in the SocketCAN plugin. This enum value was introduced in Qt 5.14.
`QCanBusDevice::UserKey` | `30` | This key defines the range where custom keys start. Its most common purpose is to permit platform-specific configuration options.

See also configurationParameter().

### enum QCanBusDevice::Direction
flags QCanBusDevice::Directions

This enum describes possible data transmission directions.

Constant | Value | Description
--- | --- | ---
`QCanBusDevice::Input` | `1` | Input direction.
`QCanBusDevice::Output` | `2` | Output direction.
`QCanBusDevice::AllDirections` | `Input | Output` | Both directions, input and output.

The Directions type is a typedef for QFlags<Direction>. It stores an OR combination of Direction values.

## Member Function Documentation

### `[explicit]` QCanBusDevice::QCanBusDevice(QObject *parent = nullptr)

Constructs a serial bus device with the specified parent.

### `[virtual]` QCanBusDevice::CanBusStatus QCanBusDevice::busStatus()

Returns the current CAN bus status. If the status cannot be requested, QCanBusDevice::UnknownStatus is returned.

Note: This function may not be implemented in all CAN plugins. Please refer to the plugins help pages for more information. The function hasBusStatus() can be used at runtime to check if the used CAN plugin has support for requesting the CAN bus status.

See also hasBusStatus() and resetController().

### void QCanBusDevice::clear(QCanBusDevice::Directions direction = Direction::AllDirections)

Clears the devices input or output buffers, depending on direction.

This function only operates on QCanBusDevice buffers. Frames that are already written to the CAN driver or CAN hardware layer, or that are not yet read from these layers, are not cleared by this function.

Note: Clearing the output buffers is only possible for buffered devices.

See also framesAvailable(), readFrame(), framesToWrite(), and writeFrame().

### `[protected]` void QCanBusDevice::clearError()

Clears the error id and the human readable description of the last device error.

CAN bus implementations must use this function to update the device's error state.

See also error(), errorOccurred(), and setError().

### `[pure virtual protected]` void QCanBusDevice::close()

This function is responsible for closing the CAN bus connection. The implementation must ensure that the instance's state() is set to QCanBusDevice::UnconnectedState.

This function's most important task is to close the socket to the CAN device and to call QCanBusDevice::setState().

See also disconnectDevice().

### QList<QCanBusDevice::ConfigurationKey> QCanBusDevice::configurationKeys() const

Returns the list of keys used by the CAN bus connection.

The meaning of the keys is equivalent to ConfigurationKey. If a key is not explicitly mentioned, the platform's default setting for the relevant key is used.

### QVariant QCanBusDevice::configurationParameter(QCanBusDevice::ConfigurationKey key) const

Returns the current value assigned to the ConfigurationKey key; otherwise an invalid QVariant.

See also setConfigurationParameter() and configurationKeys().

### bool QCanBusDevice::connectDevice()

Connects the device to the CAN bus. Returns `true` on success; otherwise `false`.

This function calls open() as part of its implementation.

See also disconnectDevice().

### `[protected]` QCanBusFrame QCanBusDevice::dequeueOutgoingFrame()

Returns the next QCanBusFrame from the internal list of outgoing frames; otherwise returns an invalid QCanBusFrame. The returned frame is removed from the internal list.

### `[virtual, since 6.2]` QCanBusDeviceInfo QCanBusDevice::deviceInfo() const

Returns a QCanBusDeviceInfo for the current QCanBusDevice. If the function is not implemented by a sub-class of QCanBusDevice, a default constructed object is returned.

This function was introduced in Qt 6.2.

### void QCanBusDevice::disconnectDevice()

Disconnects the device from the CAN bus.

This function calls close() as part of its implementation.

Note: This function should only be called, if connectDevice() returned `true`.

See also connectDevice().

### `[protected]` void QCanBusDevice::enqueueOutgoingFrame(const QCanBusFrame &newFrame)

Appends newFrame to the internal list of outgoing frames which can be accessed by writeFrame().

Subclasses must call this function when they write a new frame.

### `[protected]` void QCanBusDevice::enqueueReceivedFrames(const QList<QCanBusFrame> &newFrames)

Appends newFrames to the internal list of frames which can be accessed using readFrame() and emits the framesReceived() signal.

Subclasses must call this function when they receive frames.

### QCanBusDevice::CanBusError QCanBusDevice::error() const

Returns the last error that has occurred. The error value is always set to last error that occurred and it is never reset.

See also setError() and errorString().

### `[signal]` void QCanBusDevice::errorOccurred(QCanBusDevice::CanBusError)

This signal is emitted when an error occurs.

### QString QCanBusDevice::errorString() const

Returns a human-readable description of the last device error that occurred.

See also error().

### qint64 QCanBusDevice::framesAvailable() const

Returns the number of available frames. If no frames are available, this function returns 0.

See also clear(), readFrame(), and readAllFrames().

### `[signal]` void QCanBusDevice::framesReceived()

This signal is emitted when one or more frames have been received. The frames should be read using readFrame() and framesAvailable().

### qint64 QCanBusDevice::framesToWrite() const

For buffered devices, this function returns the number of frames waiting to be written. For unbuffered devices, this function always returns zero.

Note: There may be additional buffering in the CAN driver and CAN hardware layer. Therefore, if this function returns zero, that does not mean all CAN frames are already written to the CAN bus.

See also clear() and writeFrame().

### `[signal]` void QCanBusDevice::framesWritten(qint64 framesCount)

This signal is emitted every time a payload of frames has been written to the CAN bus. The framesCount argument is set to the number of frames that were written in this payload.

### `[virtual]` bool QCanBusDevice::hasBusStatus() const

Return true, if the CAN plugin supports requesting the CAN bus status.

See also busStatus().

### `[protected]` bool QCanBusDevice::hasOutgoingFrames() const

Returns `true` if the internal list of outgoing frames is not empty; otherwise returns `false`.

### `[pure virtual]` QString QCanBusDevice::interpretErrorFrame(const QCanBusFrame &frame)

Interprets frame as error frame and returns a human readable description of the error.

If frame is not an error frame, the returned string is empty.

### `[pure virtual protected]` bool QCanBusDevice::open()

This function is called by connectDevice(). Subclasses must provide an implementation which returns `true` if the CAN bus connection could be established; otherwise `false`. The QCanBusDevice implementation ensures upon entry of this function that the device's state() is set to QCanBusDevice::ConnectingState already.

The implementation must ensure that upon success the instance's state() is set to QCanBusDevice::ConnectedState; otherwise QCanBusDevice::UnconnectedState. setState() must be used to set the new device state.

The custom implementation is responsible for opening the socket, instanciation of a potentially required QSocketNotifier and the application of custom and default QCanBusDevice::configurationParameter().

See also connectDevice().

### QList<QCanBusFrame> QCanBusDevice::readAllFrames()

Returns all QCanBusFrames from the queue; otherwise returns an empty QList. The returned frames are removed from the queue.

The queue operates according to the FIFO principle.

See also clear(), framesAvailable(), and readFrame().

### QCanBusFrame QCanBusDevice::readFrame()

Returns the next QCanBusFrame from the queue; otherwise returns an empty QCanBusFrame. The returned frame is removed from the queue.

The queue operates according to the FIFO principle.

See also clear(), framesAvailable(), and readAllFrames().

### `[virtual]` void QCanBusDevice::resetController()

Performs a CAN controller reset to release the CAN controller from bus off state, if possible.

Note: CAN controller resets disturb the running communication and may take up to one second to complete. Only call this function to recover from bus errors.

Note: This function may not be implemented in all CAN plugins. Please refer to the plugins help pages for more information.

See also busStatus().

### `[virtual]` void QCanBusDevice::setConfigurationParameter(QCanBusDevice::ConfigurationKey key, const QVariant &value)

Sets the configuration parameter key for the CAN bus connection to value. The potential keys are represented by ConfigurationKey.

A parameter can be unset by setting an invalid QVariant. Unsetting a parameter implies that the configuration is reset to its default setting.

Note: In most cases, configuration changes only take effect after a reconnect.

See also configurationParameter().

### `[protected]` void QCanBusDevice::setError(const QString &errorText, QCanBusDevice::CanBusError errorId)

Sets the human readable description of the last device error to errorText. errorId categorizes the type of error.

CAN bus implementations must use this function to update the device's error state.

See also error(), errorOccurred(), and clearError().

### `[protected]` void QCanBusDevice::setState(QCanBusDevice::CanBusDeviceState newState)

Sets the state of the device to newState. CAN bus implementations must use this function to update the device state.

See also state().

### QCanBusDevice::CanBusDeviceState QCanBusDevice::state() const

Returns the current state of the device.

See also setState() and stateChanged().

### `[signal]` void QCanBusDevice::stateChanged(QCanBusDevice::CanBusDeviceState state)

This signal is emitted every time the state of the device changes. The new state is represented by state.

See also setState() and state().

### `[virtual]` bool QCanBusDevice::waitForFramesReceived(int msecs)

Blocks until new frames are available for reading and the framesReceived() signal has been emitted, or until msecs milliseconds have passed. If msecs is `-1`, this function will not time out.

Returns `true` if new frames are available for reading and the framesReceived() signal is emitted; otherwise returns `false` (if the operation timed out or if an error occurred).

Note: This function will start a local event loop. This may lead to scenarios whereby other application slots may be called while the execution of this function scope is blocking. To avoid problems, the signals for this class should not be connected to slots. Similarly this function must never be called in response to the framesReceived() or errorOccurred() signals.

See also waitForFramesWritten().

### `[virtual]` bool QCanBusDevice::waitForFramesWritten(int msecs)

For buffered devices, this function waits until all buffered frames have been written to the device and the framesWritten() signal has been emitted, or until msecs milliseconds have passed. If msecs is -1, this function will not time out. For unbuffered devices, it returns immediately with `false` as writeFrame() does not require a write buffer.

Returns `true` if the framesWritten() signal is emitted; otherwise returns `false` (i.e. if the operation timed out, or if an error occurred).

Note: This function will start a local event loop. This may lead to scenarios whereby other application slots may be called while the execution of this function scope is blocking. To avoid problems, the signals for this class should not be connected to slots. Similarly this function must never be called in response to the framesWritten() or errorOccurred() signals.

See also waitForFramesReceived().

### `[pure virtual]` bool QCanBusDevice::writeFrame(const QCanBusFrame &frame)

Writes frame to the CAN bus and returns `true` on success; otherwise `false`.

On some platforms, the frame may be put into a queue and the return value may only indicate a successful insertion into the queue. The actual frame will be send later on. Therefore the framesWritten() signal is the final confirmation that the frame has been handed off to the transport layer. If an error occurs the errorOccurred() is emitted.

As per CAN bus specification, frames of type remote transfer request (RTR) do not have a payload, but a length from 0 to 8 (including). This length indicates the expected response payload length from the remote party. Therefore when sending a RTR frame using this function it may still be required to set an arbitrary payload on frame. The length of the arbitrary payload is what is set as size expectation for the RTR frame.

See also QCanBusFrame::setPayload().