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
Дмитрий

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

  • Result:60points,
  • Rating points-1
Дмитрий

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

  • Result:92points,
  • Rating points8
d
  • dsfs
  • April 26, 2024, 4:56 a.m.

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

  • Result:80points,
  • Rating points4
Last comments
k
kmssrFeb. 8, 2024, 6:43 p.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, 10:30 a.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, 8:38 a.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. 18, 2023, 9:01 p.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
George13May 7, 2024, 12:27 a.m.
добавить qlineseries в функции в функции: "GPlotter::addSeries(QString title, QVector &arr)" я вызываю метод setChart(...), я в конструктор передал адрес на QChartView элемент
BlinCT
BlinCTMay 5, 2024, 5:46 a.m.
Написать свой GraphsView Всем привет. В Qt есть давольно старый обьект дял работы с графиками ChartsView и есть в 6.7 новый но очень сырой и со слабым функционалом GraphsView. По этой причине я хочу написать х…
PS
Peter SonMay 3, 2024, 5:57 p.m.
Best Indian Food Restaurant In Cincinnati OH Ready to embark on a gastronomic journey like no other? Join us at App india restaurant and discover why we're renowned as the Best Indian Food Restaurant In Cincinnati OH . Whether y…
Evgenii Legotckoi
Evgenii LegotckoiMay 2, 2024, 2:07 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Добрый день. По моему мнению - да, но то, что будет касаться вызовов к функционалу Андроида, может создать огромные трудности.
IscanderChe
IscanderCheApril 30, 2024, 4:22 a.m.
Во Flask рендер шаблона не передаётся в браузер Доброе утро! Имеется вот такой шаблон: <!doctype html><html> <head> <title>{{ title }}</title> <link rel="stylesheet" href="{{ url_…

Follow us in social networks