AnalyzerConfiguratorTemplate.h 24.6 KB
Newer Older
Alessio Netti's avatar
Alessio Netti committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//
// Created by Netti, Alessio on 10.12.18.
//

#ifndef PROJECT_ANALYZERCONFIGURATORTEMPLATE_H
#define PROJECT_ANALYZERCONFIGURATORTEMPLATE_H

#include <map>
#include <set>

#include <boost/foreach.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/info_parser.hpp>
#include "AnalyzerTemplate.h"
#include "AnalyzerConfiguratorInterface.h"
17
#include "sensorbase.h"
Alessio Netti's avatar
Alessio Netti committed
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

#include <iostream>
#include <sstream>
#include <iomanip>

#define CFG_VAL	boost::property_tree::iptree&

/**
 * Template that implements a standard AnalyzerConfiguratorInterface.
 *
 * Users should employ this template whenever possible, and create their own configurators only when strictly
 * necessary.
 */
template <class Analyzer, class SBase = SensorBase>
class AnalyzerConfiguratorTemplate : public AnalyzerConfiguratorInterface {

    // Verifying the types of input classes
    static_assert(std::is_base_of<SensorBase, SBase>::value, "SBase must derive from SensorBase!");
    static_assert(std::is_base_of<AnalyzerInterface, Analyzer>::value, "Analyzer must derive from AnalyzerInterface!");

protected:

    // For readability
    using A_Ptr = std::shared_ptr<Analyzer>;

    // Some wildcard characters
    const char COMMA = ',';
    const char OPEN_SQBRKET = '[';
    const char CLOSE_SQBRKET = ']';
    const char DASH = '-';

    // Keywords used to identify input and output sensor blocks
    const string INPUT_BLOCK = "input";
    const string OUTPUT_BLOCK = "output";
52
53
    const string ALL_CLAUSE = "all";
    const string ALL_REC_CLAUSE = "all-recursive";
Alessio Netti's avatar
Alessio Netti committed
54
    
Alessio Netti's avatar
Alessio Netti committed
55
56
57
58
59
60
public:

    /**
    * @brief            Class constructor
    */
    AnalyzerConfiguratorTemplate() :
61
            _queryEngine(QueryEngine::getInstance()),
Alessio Netti's avatar
Alessio Netti committed
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
            _analyzerName("INVALID"),
            _baseName("INVALID"),
            _cfgPath(""),
            _mqttPrefix(""),
            _cacheInterval(900000) {}

    /**
    * @brief            Copy constructor is not available
    */
    AnalyzerConfiguratorTemplate(const AnalyzerConfiguratorTemplate&) = delete;

    /**
    * @brief            Assignment operator is not available
    */
    AnalyzerConfiguratorTemplate& operator=(const AnalyzerConfiguratorTemplate&) = delete;

    /**
    * @brief            Class destructor
    */
    virtual ~AnalyzerConfiguratorTemplate() {
        for (auto ta : _templateAnalyzers)
            delete ta.second;
Alessio Netti's avatar
Alessio Netti committed
84
85
        for (auto ts : _templateSensors)
            delete ts.second;
Alessio Netti's avatar
Alessio Netti committed
86
        _templateAnalyzers.clear();
Alessio Netti's avatar
Alessio Netti committed
87
88
        _templateSensors.clear();
        _templateProtoInputs.clear();
Alessio Netti's avatar
Alessio Netti committed
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
        _analyzerInterfaces.clear();
        _analyzers.clear();
    }

    /**
    * @brief                    Sets default global settings for analyzers
    *
    *                           This method should be called once after constructing a configurator and before reading
    *                           the configuration, so that it has access to the default global settings (which can
    *                           be overridden.
    *
    * @param pluginSettings	    struct with global default settings for the plugins.
    */
    virtual void setGlobalSettings(const pluginSettings_t& pluginSettings) final {
        _mqttPrefix = pluginSettings.mqttPrefix;
        _cacheInterval = pluginSettings.cacheInterval;
    }

107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
    /**
    * @brief                    Print configuration as read in.
    *
    * @param ll                 Logging level to log with
    */
    void printConfig(LOG_LEVEL ll) final {
        LOG_VAR(ll) << "    General: ";
        LOG_VAR(ll) << "          MQTT-Prefix:    " << (_mqttPrefix != "" ? _mqttPrefix : "DEFAULT");
        LOG_VAR(ll) << "          Cache interval: " << _cacheInterval << " ms";

        //prints plugin specific configurator attributes and entities if present
        printConfiguratorConfig(ll);

        LOG_VAR(ll) << "    Analyzers: ";
        for(auto a : _analyzers) {
            LOG_VAR(ll) << "        Analyzer: " << a->getName();
            a->printConfig(ll);
        }
    }

Alessio Netti's avatar
Alessio Netti committed
127
128
129
130
131
132
133
134
135
136
137
138
    /**
    * @brief            Read a config file and instantiate analyzers accordingly
    *
    *                   This method supplies standard algorithms to instantiate analyzers and parse units from config
    *                   files accordingly. It should be overridden only if strictly necessary, which generally should
    *                   not happen.
    *
    * @param cfgPath    Path to the config file
    * @return	        True if successful, false otherwise
    */
    bool readConfig(std::string cfgPath) {
        _cfgPath = cfgPath;
Alessio Netti's avatar
Alessio Netti committed
139
        _unitGen.setNavigator(_queryEngine.getNavigator());
Alessio Netti's avatar
Alessio Netti committed
140
141
142
143
144
145
146
147
148
149
150
151
152
153

        boost::property_tree::iptree cfg;
        boost::property_tree::read_info(cfgPath, cfg);

        // Read global variables (if present overwrite those from global.conf)
        readGlobal(cfg);

        // Reading analyzers and template analyzers
        BOOST_FOREACH(boost::property_tree::iptree::value_type &val, cfg) {
            // In this block templates are parsed and read
            if (boost::iequals(val.first, "template_" + _analyzerName)) {
                LOG(debug) << "Template " << _analyzerName << " \"" << val.second.data() << "\"";
                if (!val.second.empty()) {
                    Analyzer* an = new Analyzer(val.second.data());
154
                    an->setTemplate(true);
Alessio Netti's avatar
Alessio Netti committed
155
                    if (!readAnalyzer(*an, val.second)) {
Alessio Netti's avatar
Alessio Netti committed
156
157
158
159
                        LOG(warning) << "Template " << _analyzerName << " \"" << val.second.data() << "\" has bad values! Ignoring...";
                        delete an;
                    }
                }
Alessio Netti's avatar
Alessio Netti committed
160
161
162
163
164
165
166
167
168
169
170
            // Sensor templates are read
            } else if (boost::iequals(val.first, "template_" + _baseName)) {
                LOG(debug) << "Template " << _baseName << " \"" << val.second.data() << "\"";
                if (!val.second.empty()) {
                    SBase* base = new SBase(val.second.data());
                    if (!readSensorBase(*base, val.second, true)) {
                        LOG(warning) << "Template " << _baseName << " \"" << val.second.data() << "\" has bad values! Ignoring...";
                        delete base;
                    }
                }
            // Here we read and instantiate analyzers
Alessio Netti's avatar
Alessio Netti committed
171
172
173
174
175
176
177
178
179
180
181
182
            } else if (boost::iequals(val.first, _analyzerName)) {
                LOG(debug) << _analyzerName << " \"" << val.second.data() << "\"";
                if (!val.second.empty()) {
                    A_Ptr an = std::make_shared<Analyzer>(val.second.data());
                    if (readAnalyzer(*an, val.second)) {
                        // If the analyzer must be duplicated for each compute unit, we copy-construct identical
                        // instances that have different unit IDs
                        unsigned numUnits = an->getUnits().size();
                        if(an->getDuplicate() && numUnits>1) {
                            for(unsigned int i=0; i < numUnits; i++) {
                                A_Ptr anCopy = std::make_shared<Analyzer>(*an);
                                anCopy->setUnitID(i);
183
                                anCopy->collapseUnits();
Alessio Netti's avatar
Alessio Netti committed
184
185
186
187
188
189
190
191
                                storeAnalyzer(anCopy);
                            }
                        } else
                            storeAnalyzer(an);
                    } else {
                        LOG(warning) << _analyzerName << " \"" << val.second.data() << "\" has bad values! Ignoring...";
                    }
                }
192
193
194
            } else if( !boost::iequals(val.first, "global") ) {
                LOG(error) << "\"" << val.first << "\": unknown construct!";
                return false;
Alessio Netti's avatar
Alessio Netti committed
195
196
197
198
199
200
            }
        }
        return true;
    }

    /**
Alessio Netti's avatar
Alessio Netti committed
201
    * @brief            Clears the plugin configuration
Alessio Netti's avatar
Alessio Netti committed
202
    *
Alessio Netti's avatar
Alessio Netti committed
203
204
    *                   This will stop any analyzers that have been created, destroy them and return the plugin to
    *                   its uninitialized state.
Alessio Netti's avatar
Alessio Netti committed
205
206
    *
    */
Alessio Netti's avatar
Alessio Netti committed
207
    void clearConfig() final {
Alessio Netti's avatar
Alessio Netti committed
208
209
210
211
212
213
214
215
        // Stop all analyzers
        for(auto a : _analyzers)
            a->stop();

        // Wait for all analyzers to finish
        for(auto a : _analyzers)
            a->wait();

Alessio Netti's avatar
Alessio Netti committed
216
        // First of all, delete all template analyzers and sensors
Alessio Netti's avatar
Alessio Netti committed
217
218
        for (auto ta : _templateAnalyzers)
            delete ta.second;
Alessio Netti's avatar
Alessio Netti committed
219
220
        for (auto ts : _templateSensors)
            delete ts.second;
Alessio Netti's avatar
Alessio Netti committed
221
222
223
224
225

        // Clear all analyzers
        _analyzerInterfaces.clear();
        _analyzers.clear();
        _templateAnalyzers.clear();
Alessio Netti's avatar
Alessio Netti committed
226
227
        _templateSensors.clear();
        _templateProtoInputs.clear();
Alessio Netti's avatar
Alessio Netti committed
228
229
230
231
232
233
234
235
236
237
238
239
    }

    /**
    * @brief            Clear all instantiated analyzers and read the configuration again
    *
    *                   This will stop any analyzers that have been created, destroy them and finally create new ones
    *                   from a new configuration read pass.
    *
    * @return	        True if successful, false otherwise
    */
    bool reReadConfig() final {
        clearConfig();
Alessio Netti's avatar
Alessio Netti committed
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275

        // Reading the configuration once again
        return readConfig(_cfgPath);
    }

    /**
    * @brief                   Return all instantiated analyzers
    *
    * @return	               Vector containing pointers to all analyzer interfaces of this plugin
    */
    std::vector<AnalyzerPtr>& getAnalyzers() final {
        return _analyzerInterfaces;
    }

protected:

    /**
    * @brief           Reads any derived analyzer attributes
    *
    *                  Pure virtual interface method, responsible for reading plugin-specific analyzer attributes.
    *
    * @param an		   The analyzer for which derived attributes must be set
    * @param config	   A Boost property (sub-)tree containing the config attributes
    */
    virtual void analyzer(Analyzer& an, CFG_VAL config) = 0;

    /**
    * @brief           Reads any derived sensor attributes
    *
    *                  Pure virtual interface method, responsible for reading plugin-specific sensor attributes.
    *
    * @param s		   The sensor for which derived attributes must be set
    * @param config	   A Boost property (sub-)tree containing the config attributes
    */
    virtual void sensorBase(SBase& s, CFG_VAL config) = 0;

276
277
278
279
280
281
    /**
    * @brief           Performs additional checks on instantiated units
    *
    *                  Pure virtual interface method, responsible for performing user-specified checks on units.
    *
    * @param u		   The unit that has been created
Alessio Netti's avatar
Alessio Netti committed
282
    * @return          True if the unit is valid, False otherwise
283
    */
Alessio Netti's avatar
Alessio Netti committed
284
    virtual bool unit(UnitTemplate<SBase>& u) = 0;
285

Alessio Netti's avatar
Alessio Netti committed
286
287
288
289
290
291
292
293
294
    /**
    * @brief           Reads additional global attributes on top of the default ones
    *
    *                  Virtual interface method, responsible for reading plugin-specific global attributes.
    *
    * @param config	   A Boost property (sub-)tree containing the global values
    */
    virtual void global(CFG_VAL config) {}

295
296
297
298
299
300
301
302
    /**
    * @brief            Print information about configurable configurator attributes.
    *
    *                   This method is virtual and can be overridden on a per-plugin basis.
    *
    * @param ll         Severity level to log with
    */
    virtual void printConfiguratorConfig(LOG_LEVEL ll) {
Alessio Netti's avatar
Alessio Netti committed
303
        LOG_VAR(ll) << "          No other plugin-specific general parameters defined";
304
    }
Alessio Netti's avatar
Alessio Netti committed
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328

    /**
    * @brief                   Store an analyzer in the internal vectors
    *
    * @param an                Shared pointer to a AnalyzerInterface object
    */
    void storeAnalyzer(A_Ptr an) {
        _analyzers.push_back(an);
        _analyzerInterfaces.push_back(an);
    }

    /**
    * @brief                   Reads a single analyzer configuration block
    *
    *                          Non-virtual interface method for class-internal use only. This will configure an
    *                          Analyzer object, and instantiate all units associated to it. All derived attributes
    *                          and additional configuration must be performed in the analyzer() virtual method.
    *
    * @param an	               The analyzer that must be configured
    * @param config	           A boost property (sub-)tree containing the analyzer values
    * @return	               True if successful, false otherwise
    */
    bool readAnalyzer(Analyzer& an, CFG_VAL config) {
        // Vectors containing "prototype" inputs and outputs to be modified with the actual compute units
Alessio Netti's avatar
Alessio Netti committed
329
        std::vector<shared_ptr<SBase>> protoInputs, protoOutputs;
330
        inputMode_t inputMode = SELECTIVE;
Alessio Netti's avatar
Alessio Netti committed
331
332
333
334
335
336
337
338
        // Check for the existence of a template definition to initialize the analyzer
        boost::optional<boost::property_tree::iptree&> def = config.get_child_optional("default");
        if(def) {
            LOG(debug) << "  Using \"" << def.get().data() << "\" as default.";
            auto it = _templateAnalyzers.find(def.get().data());
            if(it != _templateAnalyzers.end()) {
                an = *(it->second);
                an.setName(config.data());
339
                an.setTemplate(false);
Alessio Netti's avatar
Alessio Netti committed
340
341
                // Analyzers instantiated from templates DO NOT share the same units and output sensors. 
                // This would lead to too much naming ambiguity and is generally just not needed
Alessio Netti's avatar
Alessio Netti committed
342
                an.clearUnits();
Alessio Netti's avatar
Alessio Netti committed
343
344
345
                // The input sensors defined in the template are on the other hand preserved; this is meant as a 
                // workaround to shorten certain configurations 
                protoInputs = _templateProtoInputs[def.get().data()];
Alessio Netti's avatar
Alessio Netti committed
346
347
348
349
350
351
352
353
354
355
356
357
358
359
            } else {
                LOG(warning) << "Template " << _analyzerName << "\"" << def.get().data() << "\" not found! Using standard values.";
            }
        }
        // Reading attributes associated to AnalyzerInterface
        BOOST_FOREACH(boost::property_tree::iptree::value_type &val, config)
        {
            if (boost::iequals(val.first, "interval")) {
                an.setInterval(stoull(val.second.data()));
            } else if (boost::iequals(val.first, "minValues")) {
                an.setMinValues(stoull(val.second.data()));
            } else if (boost::iequals(val.first, "mqttPart")) {
                an.setMqttPart(val.second.data());
            } else if (boost::iequals(val.first, "sync")) {
Alessio Netti's avatar
Alessio Netti committed
360
                an.setSync(to_bool(val.second.data()));
Alessio Netti's avatar
Alessio Netti committed
361
362
            } else if (boost::iequals(val.first, "delay")) {
                an.setDelayInterval(stoull(val.second.data()) / 1000);
Alessio Netti's avatar
Alessio Netti committed
363
            } else if (boost::iequals(val.first, "duplicate")) {
Alessio Netti's avatar
Alessio Netti committed
364
                an.setDuplicate(to_bool(val.second.data()));
Alessio Netti's avatar
Alessio Netti committed
365
            } else if (boost::iequals(val.first, "streaming")) {
Alessio Netti's avatar
Alessio Netti committed
366
                an.setStreaming(to_bool(val.second.data()));
Alessio Netti's avatar
Alessio Netti committed
367
368
            } else if (boost::iequals(val.first, INPUT_BLOCK) || boost::iequals(val.first, OUTPUT_BLOCK)) {
                // Instantiating all sensors contained within the "input" or "output" block
369
                BOOST_FOREACH(boost::property_tree::iptree::value_type &valInner, val.second)
Alessio Netti's avatar
Alessio Netti committed
370
371
                {
                    if (boost::iequals(valInner.first, _baseName)) {
372
373
                        LOG(debug) << "    I/O " << _baseName << " " << valInner.second.data();
                        SBase sensor = SBase(valInner.second.data());
Alessio Netti's avatar
Alessio Netti committed
374
                        if (readSensorBase(sensor, valInner.second, false)) {
Alessio Netti's avatar
Alessio Netti committed
375
376
                            shared_ptr<SBase> sensorPtr = make_shared<SBase>(sensor);
                            val.first==INPUT_BLOCK ? protoInputs.push_back(sensorPtr) : protoOutputs.push_back(sensorPtr);
Alessio Netti's avatar
Alessio Netti committed
377
378
379
                        } else {
                            LOG(warning) << "I/O " << _baseName << " " << an.getName() << "::" << sensor.getName() << " could not be read! Omitting";
                        }
380
381
382
383
384
385
386
                        // An "all" or "all-recursive" statement in the input block causes all sensors related to the specific
                        // unit to be picked
                    } else if (boost::iequals(val.first, INPUT_BLOCK) && (boost::iequals(valInner.first, ALL_CLAUSE) || boost::iequals(valInner.first, ALL_REC_CLAUSE))) {
                        inputMode = boost::iequals(valInner.first, ALL_CLAUSE) ? ALL : ALL_RECURSIVE;
                    } else {
                        LOG(error) << "\"" << valInner.first << "\": unknown I/O construct!";
                        return false;
Alessio Netti's avatar
Alessio Netti committed
387
388
389
390
391
392
393
394
                    }
                }
            }
        }

        // Reading all derived attributes, if any
        analyzer(an, config);

Alessio Netti's avatar
Alessio Netti committed
395
396
        // Instantiating units and returning the result
        if(!an.getTemplate()) {
Alessio Netti's avatar
Alessio Netti committed
397
            vector <shared_ptr<UnitTemplate<SBase>>> *units = NULL;
Alessio Netti's avatar
Alessio Netti committed
398
            try {
Alessio Netti's avatar
Alessio Netti committed
399
400
401
                units = _unitGen.generateUnits(protoInputs, protoOutputs, inputMode, 
                        MQTTChecker::formatTopic(_mqttPrefix) + MQTTChecker::formatTopic(an.getMqttPart()), 
                        !an.getStreaming());
Alessio Netti's avatar
Alessio Netti committed
402
403
            }
            catch (const std::exception &e) {
Alessio Netti's avatar
Alessio Netti committed
404
405
                LOG(error) << _analyzerName << " " << an.getName() << ": Error when creating units: " << e.what();
                delete units;
Alessio Netti's avatar
Alessio Netti committed
406
407
408
409
                return false;
            }

            for (auto &u: *units) {
Alessio Netti's avatar
Alessio Netti committed
410
                if(!constructSensorTopics(*u, an)) {
Alessio Netti's avatar
Alessio Netti committed
411
412
413
414
                    an.clearUnits();
                    delete units;
                    return false;
                }
Alessio Netti's avatar
Alessio Netti committed
415
416
                if (an.getStreaming()) {
                    if (!unit(*u)) {
417
                        LOG(error) << "    Unit " << u->getName() << " did not pass the final check!";
Alessio Netti's avatar
Alessio Netti committed
418
419
420
                        an.clearUnits();
                        delete units;
                        return false;
421
422
                    } else {
                        LOG(debug) << "    Unit " << u->getName() << " generated.";
Alessio Netti's avatar
Alessio Netti committed
423
                        an.addUnit(u);
424
                    }
Alessio Netti's avatar
Alessio Netti committed
425
426
                } else {
                    if (unit(*u)) {
Alessio Netti's avatar
Alessio Netti committed
427
                        an.addToOndemandCache(u);
428
                        LOG(debug) << "    Template unit for on-demand operation " + u->getName() + " generated.";
Alessio Netti's avatar
Alessio Netti committed
429
430
431
432
433
434
435
                    } else {
                        LOG(error) << "    Template unit " << u->getName() << " did not pass the final check!";
                        an.clearUnits();
                        delete units;
                        return false;
                    }
                }
Alessio Netti's avatar
Alessio Netti committed
436
            }
Alessio Netti's avatar
Alessio Netti committed
437
            delete units;
Alessio Netti's avatar
Alessio Netti committed
438
439
440
441
442
443
444
445
        } else {
            // If the analyzer is a template, we add it to the related map
            auto ret = _templateAnalyzers.insert(std::pair<std::string, Analyzer*>(an.getName(), &an));
            if(!ret.second) {
                LOG(warning) << "Template " << _analyzerName << " " << an.getName() << " already exists! Omitting...";
                return false;
            }
            _templateProtoInputs.insert(std::pair<std::string, std::vector<shared_ptr<SBase>>>(an.getName(), protoInputs));
Alessio Netti's avatar
Alessio Netti committed
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
        }
        return true;
    }

    /**
    * @brief                   Reads a single sensor configuration block
    *
    *                          Non-virtual interface method for class-internal use only. This will configure a
    *                          sensor object. All derived attributes and additional configuration must be performed
    *                          in the sensorBase() virtual method.
    *
    * @param sBase	           The sensor that must be configured
    * @param config	           A boost property (sub-)tree containing the sensor values
    * @return	               True if successful, false otherwise
    */
Alessio Netti's avatar
Alessio Netti committed
461
    bool readSensorBase(SBase& sBase, CFG_VAL config, bool isTemplate=false) {
Alessio Netti's avatar
Alessio Netti committed
462
        sBase.setCacheInterval(_cacheInterval);
Alessio Netti's avatar
Alessio Netti committed
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
        if (!isTemplate) {
            // Copying parameters from the template (if defined)
            boost::optional<boost::property_tree::iptree&> def = config.get_child_optional("default");
            if(def) {
                LOG(debug) << "  Using \"" << def.get().data() << "\" as default.";
                auto it = _templateSensors.find(def.get().data());
                if(it != _templateSensors.end()) {
                    sBase = *(it->second);
                    sBase.setName(config.data());
                } else {
                    LOG(warning) << "Template " << _baseName << "\" " << def.get().data() << "\" not found! Using standard values.";
                }
            }
        }
        // Reading other sensor parameters
Alessio Netti's avatar
Alessio Netti committed
478
479
480
        BOOST_FOREACH(boost::property_tree::iptree::value_type &val, config) {
            if (boost::iequals(val.first, "mqttsuffix")) {
                sBase.setMqtt(val.second.data());
481
            } else if (boost::iequals(val.first, "skipConstVal")) {
Alessio Netti's avatar
Alessio Netti committed
482
                sBase.setSkipConstVal(to_bool(val.second.data()));
483
            } else if (boost::iequals(val.first, "delta")) {
Alessio Netti's avatar
Alessio Netti committed
484
                sBase.setDelta(to_bool(val.second.data()));
485
            } else if (boost::iequals(val.first, "sink")) {
Alessio Netti's avatar
Alessio Netti committed
486
                sBase.setSinkPath(val.second.data());
487
            } else if (boost::iequals(val.first, "subSampling")) {
Alessio Netti's avatar
Alessio Netti committed
488
                sBase.setSubsampling(std::stoul(val.second.data()));
Alessio Netti's avatar
Alessio Netti committed
489
490
491
            }
        }
        sensorBase(sBase, config);
Alessio Netti's avatar
Alessio Netti committed
492
493
494
495
496
497
498
499
500
        
        if(isTemplate) {
            auto ret = _templateSensors.insert(std::pair<std::string, SBase*>(sBase.getName(), &sBase));
            if(!ret.second) {
                LOG(warning) << "Template " << _baseName << " " << sBase.getName() << " already exists! Omitting...";
                return false;
            }
        }
        
Alessio Netti's avatar
Alessio Netti committed
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
        return true;
    }

    /**
    * @brief                   Reads the global configuration block
    *
    *                          Non-virtual interface method for class-internal use only. This will read the "global"
    *                          configuration block in a file, overwriting any default settings on a per-plugin base.
    *                          Any derived or additional attributes must be added through the global() virtual method.
    *
    * @param config	           A Boost property (sub-)tree containing the global block
    * @return	               True if successful, false otherwise
    */
    bool readGlobal(CFG_VAL config) {
        boost::optional<boost::property_tree::iptree&> globalVals = config.get_child_optional("global");
        if (globalVals) {
            BOOST_FOREACH(boost::property_tree::iptree::value_type &global, config.get_child("global")) {
                if (boost::iequals(global.first, "mqttprefix")) {
                    _mqttPrefix = global.second.data();
                    if (_mqttPrefix[_mqttPrefix.length()-1] != '/') {
                        _mqttPrefix.append("/");
                    }
                    LOG(debug) << "  Using own MQTT-Prefix " << _mqttPrefix;
                } else if (boost::iequals(global.first, "cacheInterval")) {
                    _cacheInterval = stoul(global.second.data());
                    LOG(debug) << "  Using own caching interval " << _cacheInterval << " [s]";
                    _cacheInterval *= 1000;
Alessio Netti's avatar
Alessio Netti committed
528
                } 
Alessio Netti's avatar
Alessio Netti committed
529
530
531
532
533
534
            }
            global(config.get_child("global"));
        }
        return true;
    }

Alessio Netti's avatar
Alessio Netti committed
535
    /**
Alessio Netti's avatar
Alessio Netti committed
536
    * @brief                   Adjusts the topics and names of the sensors
Alessio Netti's avatar
Alessio Netti committed
537
    *
Alessio Netti's avatar
Alessio Netti committed
538
    *                          Names are set according to the corresponding topic.
Alessio Netti's avatar
Alessio Netti committed
539
540
    *
    * @return                  true if successful, false otherwise
Alessio Netti's avatar
Alessio Netti committed
541
    */
Alessio Netti's avatar
Alessio Netti committed
542
    bool constructSensorTopics(UnitTemplate<SBase>& u, Analyzer& an) {
Alessio Netti's avatar
Alessio Netti committed
543
544
        std::string name;
        // Performing name construction
Alessio Netti's avatar
Alessio Netti committed
545
546
        for(auto& s: u.getOutputs())
            s->setName(s->getMqtt());
Alessio Netti's avatar
Alessio Netti committed
547
        return true;
Alessio Netti's avatar
Alessio Netti committed
548
549
    }

Alessio Netti's avatar
Alessio Netti committed
550
    // Instance of a QueryEngine object
551
    QueryEngine&     _queryEngine;
Alessio Netti's avatar
Alessio Netti committed
552
553
    // UnitGenerator object used to create units
    UnitGenerator<SBase>    _unitGen;
Alessio Netti's avatar
Alessio Netti committed
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571

    // Keyword used to identify analyzer blocks in config files
    std::string		_analyzerName;
    // Keyword used to identify sensors in config files
    std::string     _baseName;

    // Path of the configuration file that must be used
    std::string 	_cfgPath;
    // Default MQTT prefix to be used when creating output sensors
    std::string		_mqttPrefix;
    // Interval in seconds for the cache of each sensor
    unsigned int	_cacheInterval;
    // The vector of analyzers, in the form of pointers to AnalyzerInterface objects
    std::vector<AnalyzerPtr> 	_analyzerInterfaces;
    // Like the above, but containing the analyzers in their actual types
    std::vector<A_Ptr>		_analyzers;
    // Map of the template analyzers that were defined in the config file - used for easy retrieval and instantiation
    std::map<std::string, Analyzer*> _templateAnalyzers;
Alessio Netti's avatar
Alessio Netti committed
572
573
574
575
    // Map of the template sensors that were defined
    std::map<std::string, SBase*> _templateSensors;
    // Map of the protoinputs belonging to template analyzers
    std::map<std::string, std::vector<shared_ptr<SBase>>> _templateProtoInputs;
Alessio Netti's avatar
Alessio Netti committed
576
577
578
};

#endif //PROJECT_ANALYZERCONFIGURATORTEMPLATE_H