MQTTSuite
Loading...
Searching...
No Matches
MqttMapper.cpp
Go to the documentation of this file.
1/*
2 * MQTTSuite - A lightweight MQTT Integration System
3 * Copyright (C) Volker Christian <me@vchrist.at>
4 * 2022, 2023, 2024, 2025, 2026
5 *
6 * This program is free software: you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the Free
8 * Software Foundation, either version 3 of the License, or (at your option)
9 * any later version.
10 *
11 * This program is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
14 * more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20/*
21 * MIT License
22 *
23 * Permission is hereby granted, free of charge, to any person obtaining a copy
24 * of this software and associated documentation files (the "Software"), to deal
25 * in the Software without restriction, including without limitation the rights
26 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
27 * copies of the Software, and to permit persons to whom the Software is
28 * furnished to do so, subject to the following conditions:
29 *
30 * The above copyright notice and this permission notice shall be included in
31 * all copies or substantial portions of the Software.
32 *
33 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
34 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
35 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
36 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
37 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
38 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
39 * THE SOFTWARE.
40 */
41
42#include "MqttMapper.h"
43
45
46#include <core/DynamicLoader.h>
47#include <iot/mqtt/Topic.h>
48
49#ifndef DOXYGEN_SHOULD_SKIP_THIS
50
51#include "nlohmann/json-schema.hpp"
52
53#include <cmath>
54#include <exception>
55
56#ifdef __GNUC__
57#pragma GCC diagnostic push
58#ifdef __has_warning
59#if __has_warning("-Wcovered-switch-default")
60#pragma GCC diagnostic ignored "-Wcovered-switch-default"
61#endif
62#if __has_warning("-Wnrvo")
63#pragma GCC diagnostic ignored "-Wnrvo"
64#endif
65#if __has_warning("-Wsuggest-override")
66#pragma GCC diagnostic ignored "-Wsuggest-override"
67#endif
68#if __has_warning("-Wmissing-noreturn")
69#pragma GCC diagnostic ignored "-Wmissing-noreturn"
70#endif
71#if __has_warning("-Wdeprecated-copy-with-user-provided-dtor")
72#pragma GCC diagnostic ignored "-Wdeprecated-copy-with-user-provided-dtor"
73#endif
74#endif
75#endif
76#include "inja.hpp"
77#ifdef __GNUC_
78#pragma GCC diagnostic pop
79#endif
80
81#include <algorithm>
82#include <log/Logger.h>
83#include <map>
84#include <nlohmann/json.hpp>
85#include <stdexcept>
86#include <vector>
87
88#endif
89
90// IWYU pragma: no_include <nlohmann/detail/iterators/iter_impl.hpp>
91
92namespace mqtt::lib {
93
94#include "mapping-schema.json.h" // definition of 'static const std::string mappingJsonSchemaString;'
95
98
103
105 delete injaEnvironment;
106
107 for (void* pluginHandle : pluginHandles) {
108 core::DynamicLoader::dlClose(pluginHandle);
109 }
110 }
111
112 const std::string& MqttMapper::getSchema() {
114 }
115
116 bool MqttMapper::setMapping(nlohmann::json mappingJson) { // can throw
117 delete injaEnvironment;
118
119 for (void* handle : pluginHandles) {
120 core::DynamicLoader::dlClose(handle);
121 }
122 pluginHandles.clear();
123
125
126 nlohmann::json defaultPatch;
127 try {
128 defaultPatch = validator.validate(mappingJson);
129 } catch (const std::exception& e) {
130 throw std::runtime_error("Validating JSON failed: Mapping JSON = " + mappingJson.dump(4) + "\n" + e.what());
131 }
132
133 nlohmann::json oldMappingJson = this->mappingJson;
134 try {
135 this->mappingJson = mappingJson.patch(defaultPatch);
136 if (mappingJson.empty()) {
138 } else {
139 this->mappingJsonUnpatched = mappingJson;
140 }
141 } catch (const std::exception& e) {
142 throw std::runtime_error("Patching JSON with default patch failed: Default patch = " + defaultPatch.dump(4) + "\n" + e.what());
143 }
144
145 bool mustReconnect = this->mappingJson["connection"] != oldMappingJson["connection"];
146
147 if (mappingJson["mapping"].contains("plugins")) {
148 VLOG(1) << "Loading plugins ...";
149 for (const nlohmann::json& pluginJson : mappingJson["mapping"]["plugins"]) {
150 const std::string plugin = pluginJson;
151
152 void* handle = core::DynamicLoader::dlOpen(plugin);
153
154 if (handle != nullptr) {
155 pluginHandles.push_back(handle);
156
157 VLOG(1) << " Loading plugin: " << plugin << " ...";
158
159 const std::vector<mqtt::lib::Function>* loadedFunctions =
160 static_cast<std::vector<mqtt::lib::Function>*>(core::DynamicLoader::dlSym(handle, "functions"));
161 if (loadedFunctions != nullptr) {
162 VLOG(1) << " Registering inja 'none void callbacks'";
163 for (const mqtt::lib::Function& function : *loadedFunctions) {
164 VLOG(1) << " " << function.name;
165
166 if (function.numArgs >= 0) {
167 injaEnvironment->add_callback(function.name, function.numArgs, function.function);
168 } else {
169 injaEnvironment->add_callback(function.name, function.function);
170 }
171 }
172 VLOG(1) << " Registering inja 'none void callbacks done'";
173 } else {
174 VLOG(1) << " No inja none 'void callbacks found' in plugin " << plugin;
175 }
176
177 const std::vector<mqtt::lib::VoidFunction>* loadedVoidFunctions =
178 static_cast<std::vector<mqtt::lib::VoidFunction>*>(core::DynamicLoader::dlSym(handle, "voidFunctions"));
179 if (loadedVoidFunctions != nullptr) {
180 VLOG(1) << " Registering inja 'void callbacks'";
181 for (const mqtt::lib::VoidFunction& voidFunction : *loadedVoidFunctions) {
182 VLOG(1) << " " << voidFunction.name;
183
184 if (voidFunction.numArgs >= 0) {
185 injaEnvironment->add_void_callback(voidFunction.name, voidFunction.numArgs, voidFunction.function);
186 } else {
187 injaEnvironment->add_void_callback(voidFunction.name, voidFunction.function);
188 }
189 }
190 VLOG(1) << " Registering inja 'void callbacks' done";
191 } else {
192 VLOG(1) << " No inja 'void callbacks' found in plugin " << plugin;
193 }
194
195 VLOG(1) << " Loading plugin done: " << plugin;
196 } else {
197 VLOG(1) << " Error loading plugin: " << plugin;
198 throw std::runtime_error("Error loading plugin '" + plugin + "': " + core::DynamicLoader::dlError());
199 }
200 }
201
202 VLOG(1) << "Loading plugins done";
203 }
204
205 return mustReconnect;
206 }
207
208 const nlohmann::json& MqttMapper::getMapping() const {
210 }
211
212 std::string MqttMapper::getClientId() const {
213 return mappingJson["connection"]["client_id"];
214 }
215
216 uint16_t MqttMapper::getKeepAlive() const {
217 return mappingJson["connection"]["keep_alive"];
218 }
219
221 const nlohmann::json& connectionJson = mappingJson["connection"];
222
223 return std::make_tuple(connectionJson["clean_session"],
224 connectionJson["will_topic"],
225 connectionJson["will_message"],
226 connectionJson["will_qos"],
227 connectionJson["will_retain"],
228 connectionJson["username"],
229 connectionJson["password"]);
230 }
231
233 std::list<iot::mqtt::Topic> topicList;
234
235 extractSubscriptions(mappingJson["mapping"], "", topicList);
236
237 return topicList;
238 }
239
240 MqttMapper::MappedPublishes MqttMapper::getMappings(const iot::mqtt::packets::Publish& publish) {
241 MappedPublishes mappedPublishes;
242 if (mappingJson.contains("mapping") && !mappingJson["mapping"].empty()) {
243 nlohmann::json matchingTopicLevel = findMatchingTopicLevel(mappingJson["mapping"]["topic_level"], publish.getTopic());
244
245 if (!matchingTopicLevel.empty()) {
246 const nlohmann::json& subscription = matchingTopicLevel["subscription"];
247
248 if (subscription.contains("static")) {
249 VLOG(1) << "Topic mapping found for:";
250 VLOG(1) << " Type: static";
251 VLOG(1) << " Topic: " << publish.getTopic();
252 VLOG(1) << " Message: " << publish.getMessage();
253 VLOG(1) << " QoS: " << static_cast<uint16_t>(publish.getQoS());
254 VLOG(1) << " Retain: " << publish.getRetain();
255
256 getStaticMappings(subscription["static"], publish, mappedPublishes);
257 }
258
259 if (subscription.contains("value")) {
260 VLOG(1) << "Topic mapping found for:";
261 VLOG(1) << " Type: value";
262 VLOG(1) << " Topic: " << publish.getTopic();
263 VLOG(1) << " Message: " << publish.getMessage();
264 VLOG(1) << " QoS: " << static_cast<uint16_t>(publish.getQoS());
265 VLOG(1) << " Retain: " << publish.getRetain();
266
267 nlohmann::json json;
268 json["message"] = publish.getMessage();
269
270 getTemplateMappings(subscription["value"], json, publish, mappedPublishes);
271 }
272
273 if (subscription.contains("json")) {
274 VLOG(1) << "Topic mapping found for:";
275 VLOG(1) << " Type: json";
276 VLOG(1) << " Topic: " << publish.getTopic();
277 VLOG(1) << " Message: " << publish.getMessage();
278 VLOG(1) << " QoS: " << static_cast<uint16_t>(publish.getQoS());
279 VLOG(1) << " Retain: " << publish.getRetain();
280
281 try {
282 nlohmann::json json;
283 json["message"] = nlohmann::json::parse(publish.getMessage());
284
285 getTemplateMappings(subscription["json"], json, publish, mappedPublishes);
286 } catch (const nlohmann::json::parse_error& e) {
287 VLOG(1) << " Parsing message into json failed: " << publish.getMessage();
288 VLOG(1) << " What: " << e.what() << '\n'
289 << " Exception Id: " << e.id << '\n'
290 << " Byte position of error: " << e.byte;
291 }
292 }
293 }
294 }
295
296 return mappedPublishes;
297 }
298
299 const nlohmann::json MqttMapper::validate(const nlohmann::json& json) {
300 return validator.validate(json);
301 }
302
304 return validator.validate(json, err);
305 }
306
307 void MqttMapper::extractSubscription(const nlohmann::json& topicLevelJson,
308 const std::string& topic,
309 std::list<iot::mqtt::Topic>& topicList) {
310 const std::string name = topicLevelJson["name"];
311
312 if (topicLevelJson.contains("subscription")) {
313 const uint8_t qoS = topicLevelJson["subscription"]["qos"];
314
315 topicList.emplace_back(topic + ((topic.empty() || topic == "/") && !name.empty() ? "" : "/") + name, qoS);
316 }
317
318 if (topicLevelJson.contains("topic_level")) {
319 extractSubscriptions(topicLevelJson, topic + ((topic.empty() || topic == "/") && !name.empty() ? "" : "/") + name, topicList);
320 }
321 }
322
323 void
324 MqttMapper::extractSubscriptions(const nlohmann::json& mappingJson, const std::string& topic, std::list<iot::mqtt::Topic>& topicList) {
325 if (mappingJson.contains("topic_level")) {
326 const nlohmann::json& topicLevels = mappingJson["topic_level"];
327
328 if (topicLevels.is_object()) {
329 extractSubscription(topicLevels, topic, topicList);
330 } else {
331 for (const nlohmann::json& topicLevel : topicLevels) {
332 extractSubscription(topicLevel, topic, topicList);
333 }
334 }
335 }
336 }
337
338 nlohmann::json MqttMapper::findMatchingTopicLevel(const nlohmann::json& topicLevel, const std::string& topic) const {
339 nlohmann::json foundTopicLevel;
340
341 if (topicLevel.is_object()) {
342 const std::string::size_type slashPosition = topic.find('/');
343 const std::string topicLevelName = topic.substr(0, slashPosition);
344
345 if (topicLevel["name"] == topicLevelName || topicLevel["name"] == "+" || topicLevel["name"] == "#") {
346 if (slashPosition == std::string::npos) {
347 foundTopicLevel = topicLevel;
348 } else if (topicLevel.contains("topic_level")) {
349 foundTopicLevel = findMatchingTopicLevel(topicLevel["topic_level"], topic.substr(slashPosition + 1));
350 }
351 }
352 } else if (topicLevel.is_array()) {
353 for (const nlohmann::json& topicLevelEntry : topicLevel) {
354 foundTopicLevel = findMatchingTopicLevel(topicLevelEntry, topic);
355
356 if (!foundTopicLevel.empty()) {
357 break;
358 }
359 }
360 }
361
362 return foundTopicLevel;
363 }
364
365 void
366 MqttMapper::getMappedTemplate(const nlohmann::json& templateMapping, nlohmann::json& json, MappedPublishes& mappedPublishes) const {
367 const std::string& mappingTemplate = templateMapping["mapping_template"];
368 const std::string& mappedTopic = templateMapping["mapped_topic"];
369
370 try {
371 // Render topic
372 const std::string renderedTopic = injaEnvironment->render(mappedTopic, json);
373 json["mapped_topic"] = renderedTopic;
374
375 VLOG(1) << " Mapped topic template: " << mappedTopic;
376 VLOG(1) << " -> " << renderedTopic;
377
378 try {
379 // Render message
380 const std::string renderedMessage = injaEnvironment->render(mappingTemplate, json);
381 VLOG(1) << " Mapped message template: " << mappingTemplate;
382 VLOG(1) << " -> " << renderedMessage;
383
384 const nlohmann::json& suppressions = templateMapping["suppressions"];
385 const bool retain = templateMapping["retain"];
386
387 if (suppressions.empty() || std::find(suppressions.begin(), suppressions.end(), renderedMessage) == suppressions.end() ||
388 (retain && renderedMessage.empty())) {
389 const uint8_t qoS = templateMapping["qos"];
390 const double delay = templateMapping["delay"];
391
392 VLOG(1) << " Send mapping:" << (delay > 0 ? " delayed" : "");
393 VLOG(1) << " Topic: " << renderedTopic;
394 VLOG(1) << " Message: " << renderedMessage << "";
395 VLOG(1) << " QoS: " << static_cast<int>(qoS);
396 VLOG(1) << " retain: " << retain;
397 VLOG(1) << " Delay: " << delay;
398
399 getMappedMessage(renderedTopic, renderedMessage, qoS, retain, delay, mappedPublishes);
400 } else {
401 VLOG(1) << " Rendered message: '" << renderedMessage << "' in suppression list:";
402 for (const nlohmann::json& item : suppressions) {
403 VLOG(1) << " '" << item.get<std::string>() << "'";
404 }
405 VLOG(1) << " Send mapping: suppressed";
406 }
407 } catch (const inja::InjaError& e) {
408 VLOG(1) << " Message template rendering failed: " << mappingTemplate << " : " << json.dump();
409 VLOG(1) << " What: " << e.what();
410 VLOG(1) << " INJA: " << e.type << ": " << e.message;
411 VLOG(1) << " INJA (line:column):" << e.location.line << ":" << e.location.column;
412 }
413 } catch (const inja::InjaError& e) {
414 VLOG(1) << " Topic template rendering failed: " << mappingTemplate << " : " << json.dump();
415 VLOG(1) << " What: " << e.what();
416 VLOG(1) << " INJA: " << e.type << ": " << e.message;
417 VLOG(1) << " INJA (line:column):" << e.location.line << ":" << e.location.column;
418 }
419 }
420
421 void MqttMapper::getTemplateMappings(const nlohmann::json& templateMapping,
422 nlohmann::json& json,
423 const iot::mqtt::packets::Publish& publish,
424 MappedPublishes& mappedPublishes) const {
425 json["topic"] = publish.getTopic();
426 json["qos"] = publish.getQoS();
427 json["retain"] = publish.getRetain();
428 json["package_identifier"] = publish.getPacketIdentifier();
429
430 try {
431 VLOG(1) << " Render data: " << json.dump();
432
433 if (templateMapping.is_object()) {
434 getMappedTemplate(templateMapping, json, mappedPublishes);
435 } else {
436 for (const nlohmann::json& concreteTemplateMapping : templateMapping) {
437 getMappedTemplate(concreteTemplateMapping, json, mappedPublishes);
438 }
439 }
440 } catch (const nlohmann::json::exception& e) {
441 VLOG(1) << "JSON Exception during Render data:\n" << e.what();
442 }
443 }
444
445 void MqttMapper::getStaticMappings(const nlohmann::json& staticMapping,
446 const iot::mqtt::packets::Publish& publish,
447 MappedPublishes& mappedPublishes) {
448 if (staticMapping.is_object()) {
449 getMappedMessage(staticMapping, publish, mappedPublishes);
450 } else if (staticMapping.is_array()) {
451 for (const nlohmann::json& concreteStaticMapping : staticMapping) {
452 getMappedMessage(concreteStaticMapping, publish, mappedPublishes);
453 }
454 }
455 }
456
458 const std::string& topic, const std::string& message, uint8_t qoS, bool retain, double delay, MappedPublishes& mappedPublishes) {
459 VLOG(1) << " Mapped topic:";
460 VLOG(1) << " -> " << topic;
461 VLOG(1) << " Mapped message:";
462 VLOG(1) << " -> " << message;
463 VLOG(1) << " Send mapping:" << (delay > 0 ? " delayed" : "");
464 VLOG(1) << " Topic: " << topic;
465 VLOG(1) << " Message: " << message;
466 VLOG(1) << " QoS: " << static_cast<int>(qoS);
467 VLOG(1) << " retain: " << retain;
468 VLOG(1) << " Delay: " << delay;
469
470 if (delay < 0.0) {
471 std::get<0>(mappedPublishes).emplace_back(0, topic, message, qoS, false, retain);
472 } else {
473 std::get<1>(mappedPublishes).push_back({delay, iot::mqtt::packets::Publish(0, topic, message, qoS, false, retain)});
474 }
475 }
476
477 void MqttMapper::getMappedMessage(const nlohmann::json& staticMapping,
478 const iot::mqtt::packets::Publish& publish,
479 MappedPublishes& mappedPublishes) {
480 const nlohmann::json& messageMapping = staticMapping["message_mapping"];
481
482 VLOG(1) << " Message mapping: " << messageMapping.dump();
483
484 if (messageMapping.is_object()) {
485 if (messageMapping["message"] == publish.getMessage()) {
486 getMappedMessage(staticMapping["mapped_topic"],
487 messageMapping["mapped_message"],
488 staticMapping["qos"],
489 staticMapping["retain"],
490 staticMapping["delay"],
491 mappedPublishes);
492 } else {
493 VLOG(1) << " no matching mapped message found";
494 }
495 } else {
496 const nlohmann::json::const_iterator matchedMessageMappingIterator =
497 std::find_if(messageMapping.begin(), messageMapping.end(), [&publish](const nlohmann::json& messageMappingCandidat) {
498 return messageMappingCandidat["message"] == publish.getMessage();
499 });
500
501 if (matchedMessageMappingIterator != messageMapping.end()) {
502 getMappedMessage(staticMapping["mapped_topic"],
503 (*matchedMessageMappingIterator)["mapped_message"],
504 staticMapping["qos"],
505 staticMapping["retain"],
506 staticMapping["delay"],
507 mappedPublishes);
508 } else {
509 VLOG(1) << " no matching mapped message found";
510 }
511 }
512 }
513
514} // namespace mqtt::lib
Class for changing the configuration.
Definition inja.hpp:2993
std::string render(std::string_view input, const json &data)
Definition inja.hpp:3093
static void extractSubscription(const nlohmann::json &topicLevelJson, const std::string &topic, std::list< iot::mqtt::Topic > &topicList)
void getTemplateMappings(const nlohmann::json &templateMapping, nlohmann::json &json, const iot::mqtt::packets::Publish &publish, MappedPublishes &mappedPublishes) const
std::string getClientId() const
std::tuple< bool, std::string, std::string, uint8_t, bool, std::string, std::string > ConnectParameter
Definition MqttMapper.h:84
std::list< iot::mqtt::Topic > extractSubscriptions() const
MappedPublishes getMappings(const iot::mqtt::packets::Publish &publish)
nlohmann::json mappingJson
Definition MqttMapper.h:129
uint16_t getKeepAlive() const
bool setMapping(nlohmann::json mappingJson)
static const nlohmann::json validate(const nlohmann::json &json)
ConnectParameter getConnectPayload() const
static const nlohmann::json_schema::json_validator validator
Definition MqttMapper.h:136
std::list< void * > pluginHandles
Definition MqttMapper.h:132
static const nlohmann::json validate(const nlohmann::json &json, nlohmann::json_schema::basic_error_handler &err)
nlohmann::json mappingJsonUnpatched
Definition MqttMapper.h:130
static const std::string mappingJsonSchemaString
Definition MqttMapper.h:138
static void getMappedMessage(const std::string &topic, const std::string &message, uint8_t qoS, bool retain, double delay, MappedPublishes &mappedPublishes)
const nlohmann::json & getMapping() const
void getMappedTemplate(const nlohmann::json &templateMapping, nlohmann::json &json, MappedPublishes &mappedPublishes) const
std::tuple< std::vector< iot::mqtt::packets::Publish >, std::vector< ScheduledPublish > > MappedPublishes
Definition MqttMapper.h:83
inja::Environment * injaEnvironment
Definition MqttMapper.h:134
static void getStaticMappings(const nlohmann::json &staticMapping, const iot::mqtt::packets::Publish &publish, MappedPublishes &mappedPublishes)
static const std::string & getSchema()
static void getMappedMessage(const nlohmann::json &staticMapping, const iot::mqtt::packets::Publish &publish, MappedPublishes &mappedPublishes)
nlohmann::json findMatchingTopicLevel(const nlohmann::json &topicLevel, const std::string &topic) const
json validate(const json &, error_handler &, const json_uri &initial_uri=json_uri("#")) const
void default_string_format_check(const std::string &format, const std::string &value)
const std::string type
Definition inja.hpp:283
const SourceLocation location
Definition inja.hpp:286
const std::string message
Definition inja.hpp:284