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
г
  • ги
  • April 24, 2024, 3:51 a.m.

C++ - Test 005. Structures and Classes

  • Result:41points,
  • Rating points-8
l
  • laei
  • April 23, 2024, 9:19 p.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:10points,
  • Rating points-10
l
  • laei
  • April 23, 2024, 9:17 p.m.

C++ - Тест 003. Условия и циклы

  • Result:50points,
  • Rating points-4
Last comments
k
kmssrFeb. 9, 2024, 7: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, 11: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, 9: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, 10: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
G
GarApril 22, 2024, 5:46 p.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 7:45 p.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 6:41 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 2:35 p.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 4:47 p.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks