Quick Secure CoAP Client▲
Quick Secure CoAP Client demonstrates how to create a secure CoAP client and use it in a Qt Quick application.
Qt CoAP does not provide a QML API in its current version. However, you can make the C++ classes of the module available to QML as it is shown in the example.
Running the Example▲
To run the example from Qt Creator, open the Welcome mode and select the example from Examples. For more information, visit Building and Running an Example.
To run the example application, you first need to set up a secure CoAP server. You can run the example with any secure CoAP server supporting one of the pre-shared key (PSK) or certificate authentication modes. For more information about setting up a secure CoAP server, see Setting Up a Secure CoAP Server.
Exposing C++ Classes to QML▲
In this example, you need to expose the QCoapClient class and the QtCoap namespace to QML. To achieve this, create a custom wrapper class and use the special registration macros.
Create the QmlCoapSecureClient class as a wrapper around QCoapClient. This class also holds the selected security mode and security configuration parameters. Use the Q_INVOKABLE macro to expose several methods to QML. Also use the QML_NAMED_ELEMENT macro to register the class in QML as CoapSecureClient.
class
QmlCoapSecureClient : public
QObject
{
Q_OBJECT
QML_NAMED_ELEMENT(CoapSecureClient)
public
:
QmlCoapSecureClient(QObject *
parent =
nullptr
);
~
QmlCoapSecureClient() override
;
Q_INVOKABLE void
setSecurityMode(QtCoap::
SecurityMode mode);
Q_INVOKABLE void
sendGetRequest(const
QString &
amp;host, const
QString &
amp;path, int
port);
Q_INVOKABLE void
setSecurityConfiguration(const
QString &
amp;preSharedKey, const
QString &
amp;identity);
Q_INVOKABLE void
setSecurityConfiguration(const
QString &
amp;localCertificatePath,
const
QString &
amp;caCertificatePath,
const
QString &
amp;privateKeyPath);
Q_INVOKABLE void
disconnect();
Q_SIGNALS
:
void
finished(const
QString &
amp;result);
private
:
QCoapClient *
m_coapClient;
QCoapSecurityConfiguration m_configuration;
QtCoap::
SecurityMode m_securityMode;
}
;
After that, register the QtCoap namespace, so that you can use the enums provided there:
namespace
QCoapForeignNamespace
{
Q_NAMESPACE
QML_FOREIGN_NAMESPACE(QtCoap)
QML_NAMED_ELEMENT(QtCoap)
}
Adjusting Build Files▲
To make the custom types available from QML, update the build system files accordingly.
CMake▲
For a CMake-based build, add the following to the CMakeLists.txt:
qt_add_qml_module(quicksecureclient
URI CoapSecureClientModule
SOURCES
qmlcoapsecureclient.cpp qmlcoapsecureclient.h
QML_FILES
FilePicker.qml
Main.qml
)