Qt Cloud Messaging API available for embedded systems

Problems with cloud messaging for embedded devices inspired the Kaltiot & SnowGrains teams to create a cross-platform Qt API that makes it easy to send messages from embedded devices. The API is called Qt Cloud Messaging API and is built with flexibility and extensibility in mind.


We also decided to target other areas of Qt and make the API easily extensible for any service provider, not just embeddable ones. This allows developers to use the same API to develop mobile and desktop applications.

Currently, there are a huge number of push message providers for mobile and web development. However, industries such as automation, automotive, robotics and other embedded devices do not really have this type of service providers. The need is growing at a rapid pace as embedded and IoT devices send more and more messages from owner devices, auto service providers, telemetry, the cloud, and more.

The Qt Cloud Messaging API is easy to learn and use.

Let's take a look at how to use the Android Embedded and Mobile APIs. We have integrated the Kaltiot Smart IoT SDK and the Firebase C++ SDK into the backend, and with the help of the Qt Cloud Messaging API we can easily build, for example, a chat application on top of it.

How to use the Qt Cloud Messaging API for embedded devices:

First, clone the qtcloudmessaging repository: git clone https://codereview.qt-project.org/qt/qtcloudmessaging

Service Provider

Prerequisites:

  • Obtain the Kaltiot SDK for your embedded device (e.g. Linux or Raspberry Pi SDK) from https://console.torqhub.io
  • Get an API key to send channels and/or create a server implementation
  • Add the following line to the application's .pro file: QT += cloudmessagingembeddedkaltiot
  • Define the KALTIOT_SDK path to your application.pro
  • Add following include to main.cpp
#include <QtCloudMessaging>
 
#include <QtCloudMessagingEmbeddedKaltiot>
  • Add the following QtCloudMessaging configurations to main.cpp
// Создайте экземпляр CloudMessaging библиотеки
QCloudMessaging *pushServices = new QCloudMessaging();

// Добавить поставщика для встраиваемых систем Kaltiot
QCloudMessagingEmbeddedKaltiotProvider *kaltiotPushService = new QCloudMessagingEmbeddedKaltiotProvider()

// Параметры инициализации, основанные на поставщике, предоставляются с помощью QVariantMap
QVariantMap provider_params;
provider_params[“API_KEY”] = “Your API key from the Kaltiot console for server communication”;
// Создание имени поставщика, которое может быть использовано через ваше приложение.
pushServices->registerProvider(“KaltiotService”, kaltiotPushService, provider_params);

QVariantMap client_params;
client_params[“address”] = “IOTSensor1”;
client_params[“version”] = “1.0”;
client_params[“customer_id”] = “Kaltiot”;

// Создание каналов по умолчанию для прослушивания
QVariantList channels;
channels.append(“weather_broadcast_channel”);
client_params[“channels”] = channels;

// Подключение клиента IoT-датчика к системе
pushServices->connectClient(“KaltiotService”, “IOTSensor1”, client_params);

//! Автоматически подписаться на прослушивание еще одного канала, например, WindInfo.
pushServices->subsribeToChannel(“WindInfo”, ” KaltiotService “, ” IOTSensor1″);
  • Provide cloud messaging context with QML in main.cpp
//! Предоставление контекста QML 
engine.rootContext()->setContextProperty(“pushServices”, pushServices);

QML part:

in main.qml to catch messages coming from the Kaltiot service.

To get a message in QML:

  • Receiving messages
Connections{
target : pushServices
onMessageReceived:{

      //! Message is received as string and needs parsing to JSON

console.log(message)
}
}
  • Sending messages
//! Отправка широковещательного сообщения, например, от метеостанции:
//! Структура сообщения для встраиваемых устройств проста:
//! определить полезную нагрузку json:
//! {
//!   “payload_type”:”STRING”,
//!   “payload”: encodeURI(JSON.stringify(payload))
//! }
//! Полезная нагрузка - это ваше приложение. Например:
var payload =
{
  msgType:”NEW_WEATHER_INFO”,
  city: “Oulu”,
  forecast: “full sunlight for whole next week”
}

//! Капсулируйте полезную нагрузку для сообщения и отправляйте ее через API QtCloudMessaging:
var payload_array = [{“payload_type”:”STRING”,”payload”: encodeURI(JSON.stringify(payload))}]

pushServices.sendMessage(JSON.stringify(data), ”KaltiotService”, ”IOTSensor1”, ””, ”weather_broadcast_channel”);

Using Qt Cloud Messaging API for Android/iOS mobile development with Google's Firebase service provider

Prerequisites:

  • Create a new project in Google Firebase Console: https://firebase.google.com/
  • Download Google Firebase C++ SDK and add Firebase Android Gradle config file:
    DISTFILES += \android/google-services.json
  • Add the following line to the application's .pro file: QT += cloudmessagingfirebase
    Define Google Firebase path in application.pro file with GOOGLE_FIREBASE_SDK
  • Add the following include to your main.cpp file
#include <QtCloudMessaging>

#include <QtCloudMessagingFirebase>
  • Add the following QtCloudMessaging setting to main.cpp:
// Создайте экземпляр CloudMessaging библиотеки

QCloudMessaging *pushServices = new QCloudMessaging();

QCloudMessagingFirebaseProvider *firebaseService = new QCloudMessagingFirebaseProvider();

QVariantMap provider_params;

// Ключ API сервера не рекомендуется хранить внутри кода приложения из соображений безопасности.
// Но если вы это делаете или если вы выполняете реализацию сервера с помощью C++ и Qt, убедитесь, что он находится внутри скомпилированного файла C.
// SERVER_API_KEY необходимо иметь возможность отправлять сообщения темы с клиента без сервера приложений Firebase.

provider_params[“SERVER_API_KEY”] = “Get your SERVER API KEY from the google firebase console”;

// Регистрация компонента службы firebase Google.
pushServices->registerProvider(“GoogleFireBase”, firebaseService, provider_params);

/*! Для мобильного устройства необходим подключенный клиент.
\param Service name “GoogleFireBase”
\param Client identifier name to be used inside the application
\param Parameters for the client. No params for firebase client.
*/

pushServices->connectClient(“GoogleFireBase”, “MobileClient”, QVariantMap());

//! Автоматически подписаться на прослушивание одной темы
pushServices->subsribeToChannel(“ChatRoom”, “GoogleFireBase”, “MobileClient”);
  • Provide cloud messaging context with QML in main.cpp
//! Предоставление контекста QML
engine.rootContext()->setContextProperty(“pushServices”, pushServices);

QML part:

in main.qml catch messages coming from google firebase

  • Receiving messages:
Connections{
target : pushServices
onMessageReceived:{
//! Сообщение принимается как строка и требует синтаксического анализа для JSON

console.log(message)
}
}
  • Sending messages:
//! Для firebase структура сообщения должна иметь данные как целое сообщение.
//! Уведомления отображаются в центре уведомлений Android/iOS.
function sendMessage(notification_titile, notification_msg, msg){
var data = { “data”:{
“message”: {“text”:msg } },
“notification” : {
“body” : notification_msg,
“title” : notification_titile
}
}

//! Дайте идентификатор поставщика данных и поставщика услуг, а также имя клиента, определенное в коде C++.

pushServices.sendMessage(JSON.stringify(data),”GoogleFireBase”,”MobileClient”,””,”ChatRoom”);
}

You can play around with the Firebase Qt Cloud Messaging API + from the sample https://github.com/snowgrains/qtcloudmessaging-examples

The Qt Cloud Messaging API provides a cross-platform API that allows us to include new providers and keep the development API the same.

The Qt Cloud Messaging API is designed to be easily accessible to any service provider. Take a look at it https://codereview.qt-project.org/qt/qtcloudmessaging and make your own contribution to the backend in the community.

Kaltiot has been developing and maintaining IoT cloud services since 2008. She is trusted by Microsoft. 10M messages pass through Kaltiot every hour.

SnowGrains provides complete software solutions.

Article written by: Ari Salmi | Tuesday, January 2, 2018

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

ИИ
  • April 3, 2019, 7:36 a.m.

https://blog.qt.io/blog/2018/01/02/qt-cloud-messaging-api-available-embedded-systems/
Пытался по этому мануалу все сделать, ошибка возникла на 2 шаге, QT += cloudmessagingfirebase
Project ERROR: Unknown module(s) in QT: cloudmessagingfirebase
Как лечить это?

zloi
  • June 3, 2019, 9:59 a.m.

У меня тоже такая проблема возникла, никак не могу найти решение. Может подскажет кто?

A
  • Aug. 17, 2020, 12:39 a.m.

Тема так и не развилась?
Очень хочется попробовать сконнектить qt-десктоп с андройдом через firebase.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
B

C++ - Test 002. Constants

  • Result:16points,
  • Rating points-10
B

C++ - Test 001. The first program and data types

  • Result:46points,
  • Rating points-6
FL

C++ - Test 006. Enumerations

  • Result:80points,
  • Rating points4
Last comments
k
kmssrFeb. 9, 2024, 5:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 9:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 7:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 8:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
AC
Alexandru CodreanuJan. 19, 2024, 10:57 p.m.
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…
BlinCT
BlinCTDec. 27, 2023, 7:57 p.m.
Растягивать Image на парент по высоте Ну и само собою дял включения scrollbar надо чтобы был Flickable. Так что выходит как то так Flickable{ id: root anchors.fill: parent clip: true property url linkFile p…
Дмитрий
ДмитрийJan. 10, 2024, 3:18 p.m.
Qt Creator загружает всю оперативную память Проблема решена. Удалось разобраться с помощью утилиты strace. Запустил ее: strace ./qtcreator Начал выводиться весь лог работы креатора. В один момент он начал считывать фай…
Evgenii Legotckoi
Evgenii LegotckoiDec. 12, 2023, 5:48 p.m.
Побуквенное сравнение двух строк Добрый день. Там случайно не высылается этот сигнал textChanged ещё и при форматировани текста? Если решиать в лоб, то можно просто отключать сигнал/слотовое соединение внутри слота и …

Follow us in social networks