• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

wirenboard / wb-mqtt-serial / 6

13 Jan 2026 06:31AM UTC coverage: 76.817% (+4.0%) from 72.836%
6

Pull #1049

github

8b2ffc
Ilia1S
Remove fw from groups
Pull Request #1049: WB-MR templates: Add delays

6873 of 9161 branches covered (75.02%)

12966 of 16879 relevant lines covered (76.82%)

830.18 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

87.83
/src/serial_config.cpp
1
#include "serial_config.h"
2
#include "file_utils.h"
3
#include "json_common.h"
4
#include "log.h"
5

6
#include <cstdlib>
7
#include <dirent.h>
8
#include <fstream>
9
#include <memory>
10
#include <set>
11
#include <stdexcept>
12
#include <string>
13
#include <sys/sysinfo.h>
14

15
#include "port/tcp_port.h"
16
#include "port/tcp_port_settings.h"
17

18
#include "port/serial_port.h"
19
#include "port/serial_port_settings.h"
20

21
#include "config_merge_template.h"
22
#include "config_schema_generator.h"
23
#include "old_serial_config.h"
24

25
#include "devices/curtains/a_ok_device.h"
26
#include "devices/curtains/dooya_device.h"
27
#include "devices/curtains/somfy_sdn_device.h"
28
#include "devices/curtains/windeco_device.h"
29
#include "devices/dlms_device.h"
30
#include "devices/energomera_ce_device.h"
31
#include "devices/energomera_iec_device.h"
32
#include "devices/energomera_iec_mode_c_device.h"
33
#include "devices/iec_mode_c_device.h"
34
#include "devices/ivtm_device.h"
35
#include "devices/lls_device.h"
36
#include "devices/mercury200_device.h"
37
#include "devices/mercury230_device.h"
38
#include "devices/milur_device.h"
39
#include "devices/modbus_device.h"
40
#include "devices/modbus_io_device.h"
41
#include "devices/neva_device.h"
42
#include "devices/pulsar_device.h"
43
#include "devices/s2k_device.h"
44
#include "devices/uniel_device.h"
45

46
#define LOG(logger) ::logger.Log() << "[serial config] "
47

48
using namespace std;
49
using namespace WBMQTT::JSON;
50

51
namespace
52
{
53
    const char* DefaultProtocol = "modbus";
54

55
    template<class T> T Read(const Json::Value& root, const std::string& key, const T& defaultValue)
14,104✔
56
    {
57
        T value;
5,060✔
58
        if (Get(root, key, value)) {
14,104✔
59
            return value;
2,284✔
60
        }
61
        return defaultValue;
11,820✔
62
    }
63

64
    int GetIntFromString(const std::string& value, const std::string& errorPrefix)
67✔
65
    {
66
        try {
67
            // use std::stoul to parse negative hex value string without sign (greater than 0x7fffffff)
68
            return static_cast<int>(std::stoul(value, 0, 0));
67✔
69
        } catch (const std::logic_error&) {
×
70
            throw TConfigParserException(errorPrefix + ": plain integer or '0x..' hex string expected instead of '" +
×
71
                                         value + "'");
×
72
        }
73
    }
74

75
    double ToDouble(const Json::Value& v, const std::string& title)
99✔
76
    {
77
        if (v.isNumeric())
99✔
78
            return v.asDouble();
62✔
79
        if (!v.isString()) {
37✔
80
            throw TConfigParserException(title + ": number or '0x..' hex string expected");
×
81
        }
82
        return GetIntFromString(v.asString(), title);
37✔
83
    }
84

85
    uint64_t ToUint64(const Json::Value& v, const string& title)
1,382✔
86
    {
87
        if (v.isUInt()) {
1,382✔
88
            return v.asUInt64();
909✔
89
        }
90

91
        if (v.isInt()) {
473✔
92
            auto val = v.asInt64();
×
93
            if (val >= 0) {
×
94
                return val;
×
95
            }
96
        }
97

98
        if (v.isString()) {
473✔
99
            auto val = v.asString();
473✔
100
            if (val.find("-") == std::string::npos) {
473✔
101
                // don't try to parse strings containing munus sign
102
                try {
103
                    return stoull(val, /*pos= */ 0, /*base= */ 0);
473✔
104
                } catch (const logic_error& e) {
×
105
                }
106
            }
107
        }
108

109
        throw TConfigParserException(
×
110
            title + ": 64-bit plain unsigned integer or '0x..' hex string expected instead of '" + v.asString() + "'");
×
111
    }
112

113
    double GetDouble(const Json::Value& obj, const std::string& key)
99✔
114
    {
115
        return ToDouble(obj[key], key);
99✔
116
    }
117

118
    uint64_t GetUint64(const Json::Value& obj, const std::string& key)
1,125✔
119
    {
120
        return ToUint64(obj[key], key);
1,125✔
121
    }
122

123
    std::string GetIntegerString(const Json::Value& obj, const std::string& key)
117✔
124
    {
125
        auto v = obj[key];
234✔
126
        if (v.isInt()) {
117✔
127
            return std::to_string(v.asInt64());
79✔
128
        }
129

130
        auto val = v.asString();
76✔
131
        try {
132
            return std::to_string(stoll(val, /*pos= */ 0, /*base= */ 0));
38✔
133
        } catch (const logic_error& e) {
×
134
            throw TConfigParserException(key + ": 64-bit plain integer or '0x..' hex string expected instead of '" +
×
135
                                         val + "': " + e.what());
×
136
        }
137
    }
138

139
    bool IsSerialNumberChannel(const Json::Value& channel_data)
983✔
140
    {
141
        const std::vector<std::string> serialNames{"Serial", "serial_number", "Serial NO"};
5,898✔
142
        return serialNames.end() !=
1,966✔
143
               std::find(serialNames.begin(), serialNames.end(), channel_data.get("name", std::string()).asString());
2,949✔
144
    }
145

146
    bool ReadChannelsReadonlyProperty(const Json::Value& register_data,
2,312✔
147
                                      const std::string& key,
148
                                      bool templateReadonly,
149
                                      const std::string& override_error_message_prefix,
150
                                      const std::string& register_type)
151
    {
152
        if (!register_data.isMember(key)) {
2,312✔
153
            return templateReadonly;
2,295✔
154
        }
155
        auto& val = register_data[key];
17✔
156
        if (!val.isConvertibleTo(Json::booleanValue)) {
17✔
157
            return templateReadonly;
×
158
        }
159
        bool readonly = val.asBool();
17✔
160
        if (templateReadonly && !readonly) {
17✔
161
            LOG(Warn) << override_error_message_prefix << " unable to make register of type \"" << register_type
2✔
162
                      << "\" writable";
1✔
163
            return true;
1✔
164
        }
165
        return readonly;
16✔
166
    }
167

168
    const TRegisterType& GetRegisterType(const Json::Value& itemData, const TRegisterTypeMap& typeMap)
1,156✔
169
    {
170
        if (itemData.isMember("reg_type")) {
1,156✔
171
            std::string type = itemData["reg_type"].asString();
1,089✔
172
            try {
173
                return typeMap.Find(type);
1,089✔
174
            } catch (...) {
×
175
                throw TConfigParserException("invalid register type: " + type);
×
176
            }
177
        }
178
        return typeMap.GetDefaultType();
67✔
179
    }
180

181
    std::optional<std::chrono::milliseconds> GetReadRateLimit(const Json::Value& data)
1,459✔
182
    {
183
        std::chrono::milliseconds res(-1);
1,459✔
184
        Get(data, "read_rate_limit_ms", res);
1,459✔
185
        if (res < 0ms) {
1,459✔
186
            return std::nullopt;
1,447✔
187
        }
188
        return std::make_optional(res);
12✔
189
    }
190

191
    std::optional<std::chrono::milliseconds> GetReadPeriod(const Json::Value& data)
1,184✔
192
    {
193
        std::chrono::milliseconds res(-1);
1,184✔
194
        Get(data, "read_period_ms", res);
1,184✔
195
        if (res < 0ms) {
1,184✔
196
            return std::nullopt;
1,162✔
197
        }
198
        return std::make_optional(res);
22✔
199
    }
200

201
    struct TLoadingContext
202
    {
203
        // Full path to loaded item composed from device and channels names
204
        std::string name_prefix;
205

206
        // MQTT topic prefix. It could be different from name_prefix
207
        std::string mqtt_prefix;
208
        const IDeviceFactory& factory;
209
        const IRegisterAddress& device_base_address;
210
        size_t stride = 0;
211
        TTitleTranslations translated_name_prefixes;
212
        const Json::Value* translations = nullptr;
213

214
        TLoadingContext(const IDeviceFactory& f, const IRegisterAddress& base_address)
189✔
215
            : factory(f),
189✔
216
              device_base_address(base_address)
189✔
217
        {}
189✔
218
    };
219

220
    TTitleTranslations Translate(const std::string& name, bool idIsDefined, const TLoadingContext& context)
991✔
221
    {
222
        TTitleTranslations res;
991✔
223
        if (context.translations) {
991✔
224
            // Find translation for the name. Iterate through languages
225
            for (auto it = context.translations->begin(); it != context.translations->end(); ++it) {
152✔
226
                auto lang = it.name();
15✔
227
                auto translatedName = (*it)[name];
15✔
228
                if (!translatedName.isNull()) {
15✔
229
                    // Find prefix translated to the language or english translated prefix
230
                    auto prefixIt = context.translated_name_prefixes.find(lang);
6✔
231
                    if (prefixIt == context.translated_name_prefixes.end()) {
6✔
232
                        if (lang != "en") {
4✔
233
                            prefixIt = context.translated_name_prefixes.find("en");
4✔
234
                        }
235
                    }
236
                    // Take translation of prefix and add translated name
237
                    if (prefixIt != context.translated_name_prefixes.end()) {
6✔
238
                        res[lang] = prefixIt->second + " " + translatedName.asString();
3✔
239
                        continue;
3✔
240
                    }
241
                    // There isn't translated prefix
242
                    // Take MQTT id prefix if any and add translated name
243
                    if (context.mqtt_prefix.empty()) {
3✔
244
                        res[lang] = translatedName.asString();
2✔
245
                    } else {
246
                        res[lang] = context.mqtt_prefix + " " + translatedName.asString();
1✔
247
                    }
248
                }
249
            }
250

251
            for (const auto& it: context.translated_name_prefixes) {
148✔
252
                // There are translatied prefixes, but no translation for the name.
253
                // Take translated prefix and add the name as is
254
                if (!res.count(it.first)) {
11✔
255
                    res[it.first] = it.second + " " + name;
9✔
256
                }
257
            }
258

259
            // Name is different from MQTT id and there isn't english translated prefix
260
            // Take MQTT ID prefix if any and add the name as is
261
            if (!res.count("en") && idIsDefined) {
274✔
262
                if (context.mqtt_prefix.empty()) {
3✔
263
                    res["en"] = name;
1✔
264
                } else {
265
                    res["en"] = context.mqtt_prefix + " " + name;
2✔
266
                }
267
            }
268
            return res;
137✔
269
        }
270

271
        // No translations for names at all.
272
        // Just compose english name if it is different from MQTT id
273
        auto trIt = context.translated_name_prefixes.find("en");
854✔
274
        if (trIt != context.translated_name_prefixes.end()) {
854✔
275
            res["en"] = trIt->second + name;
×
276
        } else {
277
            if (idIsDefined) {
854✔
278
                res["en"] = name;
4✔
279
            }
280
        }
281
        return res;
854✔
282
    }
283

284
    void LoadSimpleChannel(TSerialDeviceWithChannels& deviceWithChannels,
981✔
285
                           const Json::Value& channel_data,
286
                           const TLoadingContext& context,
287
                           const TRegisterTypeMap& typeMap)
288
    {
289
        std::string mqtt_channel_name(channel_data["name"].asString());
981✔
290
        bool idIsDefined = false;
981✔
291
        if (channel_data.isMember("id")) {
981✔
292
            mqtt_channel_name = channel_data["id"].asString();
3✔
293
            idIsDefined = true;
3✔
294
        }
295
        if (!context.mqtt_prefix.empty()) {
981✔
296
            mqtt_channel_name = context.mqtt_prefix + " " + mqtt_channel_name;
8✔
297
        }
298
        auto errorMsgPrefix = "Channel \"" + mqtt_channel_name + "\"";
981✔
299
        std::string default_type_str;
981✔
300
        std::vector<PRegister> registers;
981✔
301
        if (channel_data.isMember("consists_of")) {
981✔
302

303
            auto read_rate_limit_ms = GetReadRateLimit(channel_data);
28✔
304
            auto read_period = GetReadPeriod(channel_data);
28✔
305

306
            const Json::Value& reg_data = channel_data["consists_of"];
28✔
307
            for (Json::ArrayIndex i = 0; i < reg_data.size(); ++i) {
112✔
308
                auto reg = LoadRegisterConfig(reg_data[i],
309
                                              typeMap,
310
                                              errorMsgPrefix,
311
                                              context.factory,
312
                                              context.device_base_address,
313
                                              context.stride);
168✔
314
                reg.RegisterConfig->ReadRateLimit = read_rate_limit_ms;
84✔
315
                reg.RegisterConfig->ReadPeriod = read_period;
84✔
316
                registers.push_back(deviceWithChannels.Device->AddRegister(reg.RegisterConfig));
84✔
317
                if (!i)
84✔
318
                    default_type_str = reg.DefaultControlType;
28✔
319
                else if (registers[i]->GetConfig()->AccessType != registers[0]->GetConfig()->AccessType)
56✔
320
                    throw TConfigParserException(("can't mix read-only, write-only and writable registers "
×
321
                                                  "in one channel -- ") +
×
322
                                                 deviceWithChannels.Device->DeviceConfig()->DeviceType);
×
323
            }
324
        } else {
325
            try {
326
                auto reg = LoadRegisterConfig(channel_data,
327
                                              typeMap,
328
                                              errorMsgPrefix,
329
                                              context.factory,
330
                                              context.device_base_address,
331
                                              context.stride);
953✔
332
                default_type_str = reg.DefaultControlType;
953✔
333
                registers.push_back(deviceWithChannels.Device->AddRegister(reg.RegisterConfig));
953✔
334
            } catch (const std::exception& e) {
×
335
                LOG(Warn) << deviceWithChannels.Device->ToString() << " channel \"" + mqtt_channel_name
×
336
                          << "\" is ignored: " << e.what();
×
337
                return;
×
338
            }
339
        }
340

341
        std::string type_str(Read(channel_data, "type", default_type_str));
2,943✔
342
        if (type_str == "wo-switch" || type_str == "pushbutton") {
981✔
343
            if (type_str == "wo-switch") {
×
344
                type_str = "switch";
×
345
            }
346
            for (auto& reg: registers) {
×
347
                reg->GetConfig()->AccessType = TRegisterConfig::EAccessType::WRITE_ONLY;
×
348
            }
349
        }
350

351
        int order = deviceWithChannels.Channels.size() + 1;
981✔
352
        PDeviceChannelConfig channel(
353
            new TDeviceChannelConfig(type_str,
354
                                     deviceWithChannels.Device->DeviceConfig()->Id,
981✔
355
                                     order,
356
                                     (registers[0]->GetConfig()->AccessType == TRegisterConfig::EAccessType::READ_ONLY),
1,962✔
357
                                     mqtt_channel_name,
358
                                     registers));
1,962✔
359

360
        for (const auto& it: Translate(channel_data["name"].asString(), idIsDefined, context)) {
994✔
361
            channel->SetTitle(it.second, it.first);
13✔
362
        }
363

364
        if (channel_data.isMember("enum") && channel_data.isMember("enum_titles")) {
981✔
365
            const auto& enumValues = channel_data["enum"];
2✔
366
            const auto& enumTitles = channel_data["enum_titles"];
2✔
367
            if (enumValues.size() == enumTitles.size()) {
2✔
368
                for (Json::ArrayIndex i = 0; i < enumValues.size(); ++i) {
6✔
369
                    channel->SetEnumTitles(enumValues[i].asString(),
12✔
370
                                           Translate(enumTitles[i].asString(), true, context));
8✔
371
                }
372
            } else {
373
                LOG(Warn) << errorMsgPrefix << ": enum and enum_titles should have the same size -- "
×
374
                          << deviceWithChannels.Device->DeviceConfig()->DeviceType;
×
375
            }
376
        }
377

378
        if (channel_data.isMember("max")) {
981✔
379
            channel->Max = GetDouble(channel_data, "max");
98✔
380
        }
381
        if (channel_data.isMember("min")) {
981✔
382
            channel->Min = GetDouble(channel_data, "min");
1✔
383
        }
384
        if (channel_data.isMember("on_value")) {
981✔
385
            if (registers.size() != 1)
59✔
386
                throw TConfigParserException("on_value is allowed only for single-valued controls -- " +
×
387
                                             deviceWithChannels.Device->DeviceConfig()->DeviceType);
×
388
            channel->OnValue = GetIntegerString(channel_data, "on_value");
59✔
389
        }
390
        if (channel_data.isMember("off_value")) {
981✔
391
            if (registers.size() != 1)
58✔
392
                throw TConfigParserException("off_value is allowed only for single-valued controls -- " +
×
393
                                             deviceWithChannels.Device->DeviceConfig()->DeviceType);
×
394
            channel->OffValue = GetIntegerString(channel_data, "off_value");
58✔
395
        }
396

397
        if (registers.size() == 1) {
981✔
398
            channel->Precision = registers[0]->GetConfig()->RoundTo;
953✔
399
        }
400

401
        Get(channel_data, "units", channel->Units);
981✔
402

403
        if (IsSerialNumberChannel(channel_data) && registers.size()) {
981✔
404
            deviceWithChannels.Device->SetSnRegister(registers[0]->GetConfig());
2✔
405
        }
406

407
        deviceWithChannels.Channels.push_back(channel);
981✔
408
    }
409

410
    void LoadChannel(TSerialDeviceWithChannels& deviceWithChannels,
411
                     const Json::Value& channel_data,
412
                     const TLoadingContext& context,
413
                     const TRegisterTypeMap& typeMap);
414

415
    void LoadSetupItems(TSerialDevice& device,
416
                        const Json::Value& item_data,
417
                        const TRegisterTypeMap& typeMap,
418
                        const TLoadingContext& context);
419

420
    void LoadSubdeviceChannel(TSerialDeviceWithChannels& deviceWithChannels,
7✔
421
                              const Json::Value& channel_data,
422
                              const TLoadingContext& context,
423
                              const TRegisterTypeMap& typeMap)
424
    {
425
        uint32_t shift = 0;
7✔
426
        if (channel_data.isMember("shift")) {
7✔
427
            shift = static_cast<uint32_t>(GetUint64(channel_data, "shift"));
7✔
428
        }
429
        std::unique_ptr<IRegisterAddress> baseAddress(context.device_base_address.CalcNewAddress(shift, 0, 0, 0));
14✔
430

431
        TLoadingContext newContext(context.factory, *baseAddress);
14✔
432
        newContext.translations = context.translations;
7✔
433
        auto name = channel_data["name"].asString();
14✔
434
        newContext.name_prefix = name;
7✔
435
        if (!context.name_prefix.empty()) {
7✔
436
            newContext.name_prefix = context.name_prefix + " " + newContext.name_prefix;
4✔
437
        }
438

439
        newContext.mqtt_prefix = name;
7✔
440
        bool idIsDefined = false;
7✔
441
        if (channel_data.isMember("id")) {
7✔
442
            newContext.mqtt_prefix = channel_data["id"].asString();
3✔
443
            idIsDefined = true;
3✔
444
        }
445

446
        // Empty id is used if we don't want to add channel name to resulting MQTT topic name
447
        // This case we also don't add translation to resulting translated channel name
448
        if (!(idIsDefined && newContext.mqtt_prefix.empty())) {
7✔
449
            newContext.translated_name_prefixes = Translate(name, idIsDefined, context);
6✔
450
        }
451

452
        if (!context.mqtt_prefix.empty()) {
7✔
453
            if (newContext.mqtt_prefix.empty()) {
2✔
454
                newContext.mqtt_prefix = context.mqtt_prefix;
×
455
            } else {
456
                newContext.mqtt_prefix = context.mqtt_prefix + " " + newContext.mqtt_prefix;
2✔
457
            }
458
        }
459

460
        newContext.stride = Read(channel_data, "stride", 0);
7✔
461
        LoadSetupItems(*deviceWithChannels.Device, channel_data, typeMap, newContext);
7✔
462

463
        if (channel_data.isMember("channels")) {
6✔
464
            for (const auto& ch: channel_data["channels"]) {
20✔
465
                LoadChannel(deviceWithChannels, ch, newContext, typeMap);
14✔
466
            }
467
        }
468
    }
6✔
469

470
    void LoadChannel(TSerialDeviceWithChannels& deviceWithChannels,
990✔
471
                     const Json::Value& channel_data,
472
                     const TLoadingContext& context,
473
                     const TRegisterTypeMap& typeMap)
474
    {
475
        if (channel_data.isMember("enabled") && !channel_data["enabled"].asBool()) {
990✔
476
            if (IsSerialNumberChannel(channel_data)) {
2✔
477
                deviceWithChannels.Device->SetSnRegister(LoadRegisterConfig(channel_data,
×
478
                                                                            typeMap,
479
                                                                            std::string(),
×
480
                                                                            context.factory,
481
                                                                            context.device_base_address,
482
                                                                            context.stride)
×
483
                                                             .RegisterConfig);
×
484
            }
485
            return;
2✔
486
        }
487
        if (channel_data.isMember("device_type")) {
988✔
488
            LoadSubdeviceChannel(deviceWithChannels, channel_data, context, typeMap);
7✔
489
        } else {
490
            LoadSimpleChannel(deviceWithChannels, channel_data, context, typeMap);
981✔
491
        }
492
        if (deviceWithChannels.Device->IsSporadicOnly() && !channel_data["sporadic"].asBool()) {
987✔
493
            deviceWithChannels.Device->SetSporadicOnly(false);
182✔
494
        }
495
    }
496

497
    void LoadSetupItem(TSerialDevice& device,
102✔
498
                       const Json::Value& item_data,
499
                       const TRegisterTypeMap& typeMap,
500
                       const TLoadingContext& context)
501
    {
502
        std::string name(Read(item_data, "title", std::string("<unnamed>")));
408✔
503
        if (!context.name_prefix.empty()) {
102✔
504
            name = context.name_prefix + " " + name;
13✔
505
        }
506
        auto reg = LoadRegisterConfig(item_data,
507
                                      typeMap,
508
                                      "Setup item \"" + name + "\"",
204✔
509
                                      context.factory,
510
                                      context.device_base_address,
511
                                      context.stride);
204✔
512
        const auto& valueItem = item_data["value"];
102✔
513
        // libjsoncpp uses format "%.17g" in asString() and outputs strings with additional small numbers
514
        auto value = valueItem.isDouble() ? WBMQTT::StringFormat("%.15g", valueItem.asDouble()) : valueItem.asString();
103✔
515
        device.AddSetupItem(PDeviceSetupItemConfig(
101✔
516
            new TDeviceSetupItemConfig(name, reg.RegisterConfig, value, item_data["id"].asString())));
206✔
517
    }
101✔
518

519
    void LoadSetupItems(TSerialDevice& device,
189✔
520
                        const Json::Value& device_data,
521
                        const TRegisterTypeMap& typeMap,
522
                        const TLoadingContext& context)
523
    {
524
        if (device_data.isMember("setup")) {
189✔
525
            for (const auto& setupItem: device_data["setup"])
151✔
526
                LoadSetupItem(device, setupItem, typeMap, context);
102✔
527
        }
528
    }
188✔
529

530
    void LoadCommonDeviceParameters(TDeviceConfig& device_config, const Json::Value& device_data, bool isWBDevice)
182✔
531
    {
532
        if (device_data.isMember("password")) {
182✔
533
            device_config.Password.clear();
2✔
534
            for (const auto& passwordItem: device_data["password"]) {
11✔
535
                device_config.Password.push_back(static_cast<uint8_t>(ToUint64(passwordItem, "password item")));
9✔
536
            }
537
        }
538

539
        if (device_data.isMember("delay_ms")) {
182✔
540
            LOG(Warn) << "\"delay_ms\" is not supported, use \"frame_timeout_ms\" instead";
×
541
        }
542

543
        if (isWBDevice || device_data["enable_wb_continuous_read"].asBool()) {
182✔
544
            device_config.MaxWriteRegisters = Modbus::MAX_WRITE_REGISTERS;
2✔
545
        }
546

547
        Get(device_data, "frame_timeout_ms", device_config.FrameTimeout);
182✔
548
        if (device_config.FrameTimeout.count() < 0) {
182✔
549
            device_config.FrameTimeout = DefaultFrameTimeout;
×
550
        }
551
        Get(device_data, "response_timeout_ms", device_config.ResponseTimeout);
182✔
552
        Get(device_data, "device_timeout_ms", device_config.DeviceTimeout);
182✔
553
        Get(device_data, "device_max_fail_cycles", device_config.DeviceMaxFailCycles);
182✔
554
        Get(device_data, "max_write_fail_time_s", device_config.MaxWriteFailTime);
182✔
555
        Get(device_data, "max_reg_hole", device_config.MaxRegHole);
182✔
556
        Get(device_data, "max_bit_hole", device_config.MaxBitHole);
182✔
557
        Get(device_data, "max_read_registers", device_config.MaxReadRegisters);
182✔
558
        Get(device_data, "min_read_registers", device_config.MinReadRegisters);
182✔
559
        Get(device_data, "max_write_registers", device_config.MaxWriteRegisters);
182✔
560
        Get(device_data, "guard_interval_us", device_config.RequestDelay);
182✔
561
        Get(device_data, "stride", device_config.Stride);
182✔
562
        Get(device_data, "shift", device_config.Shift);
182✔
563
        Get(device_data, "access_level", device_config.AccessLevel);
182✔
564
        Get(device_data, "min_request_interval", device_config.MinRequestInterval);
182✔
565
    }
182✔
566

567
    void LoadDevice(PPortConfig port_config,
184✔
568
                    const Json::Value& device_data,
569
                    const std::string& default_id,
570
                    TTemplateMap& templates,
571
                    TSerialDeviceFactory& deviceFactory)
572
    {
573
        if (device_data.isMember("enabled") && !device_data["enabled"].asBool())
184✔
574
            return;
×
575

576
        TSerialDeviceFactory::TCreateDeviceParams params;
189✔
577
        params.Defaults.Id = default_id;
184✔
578
        params.Defaults.RequestDelay = port_config->RequestDelay;
184✔
579
        params.Defaults.ReadRateLimit = port_config->ReadRateLimit;
184✔
580
        params.IsModbusTcp = port_config->Port->IsModbusTcp();
184✔
581
        port_config->AddDevice(deviceFactory.CreateDevice(device_data, params, templates));
186✔
582
    }
583

584
    PFeaturePort OpenSerialPort(const Json::Value& port_data, PRPCConfig rpcConfig)
17✔
585
    {
586
        TSerialPortSettings settings(port_data["path"].asString());
34✔
587

588
        Get(port_data, "baud_rate", settings.BaudRate);
17✔
589

590
        if (port_data.isMember("parity"))
17✔
591
            settings.Parity = port_data["parity"].asCString()[0];
10✔
592

593
        Get(port_data, "data_bits", settings.DataBits);
17✔
594
        Get(port_data, "stop_bits", settings.StopBits);
17✔
595

596
        auto port = std::make_shared<TSerialPort>(settings);
17✔
597

598
        rpcConfig->AddSerialPort(settings);
17✔
599

600
        return std::make_shared<TFeaturePort>(port, false);
51✔
601
    }
602

603
    PFeaturePort OpenTcpPort(const Json::Value& port_data, PRPCConfig rpcConfig)
4✔
604
    {
605
        TTcpPortSettings settings(port_data["address"].asString(), port_data["port"].asUInt());
8✔
606

607
        auto port = std::make_shared<TTcpPort>(settings);
4✔
608

609
        rpcConfig->AddTCPPort(settings);
4✔
610

611
        return std::make_shared<TFeaturePort>(port, false);
12✔
612
    }
613

614
    PFeaturePort OpenModbusTcpPort(const Json::Value& port_data, PRPCConfig rpcConfig)
×
615
    {
616
        TTcpPortSettings settings(port_data["address"].asString(), port_data["port"].asUInt());
×
617

618
        auto port = std::make_shared<TTcpPort>(settings);
×
619

620
        rpcConfig->AddModbusTCPPort(settings);
×
621

622
        return std::make_shared<TFeaturePort>(port, true, port_data["connected_to_mge"].asBool());
×
623
    }
624

625
    void LoadPort(PHandlerConfig handlerConfig,
94✔
626
                  const Json::Value& port_data,
627
                  const std::string& id_prefix,
628
                  TTemplateMap& templates,
629
                  PRPCConfig rpcConfig,
630
                  TSerialDeviceFactory& deviceFactory,
631
                  TPortFactoryFn portFactory)
632
    {
633
        if (port_data.isMember("enabled") && !port_data["enabled"].asBool())
94✔
634
            return;
×
635

636
        auto port_config = make_shared<TPortConfig>();
188✔
637

638
        Get(port_data, "guard_interval_us", port_config->RequestDelay);
94✔
639
        port_config->ReadRateLimit = GetReadRateLimit(port_data);
94✔
640

641
        auto port_type = port_data.get("port_type", "serial").asString();
193✔
642

643
        Get(port_data, "connection_timeout_ms", port_config->OpenCloseSettings.MaxFailTime);
94✔
644
        Get(port_data, "connection_max_fail_cycles", port_config->OpenCloseSettings.ConnectionMaxFailCycles);
94✔
645

646
        port_config->Port = portFactory(port_data, rpcConfig);
94✔
647

648
        std::chrono::milliseconds responseTimeout = RESPONSE_TIMEOUT_NOT_SET;
94✔
649
        Get(port_data, "response_timeout_ms", responseTimeout);
94✔
650
        port_config->Port->SetMinimalResponseTimeout(responseTimeout);
94✔
651

652
        const Json::Value& array = port_data["devices"];
94✔
653
        for (Json::Value::ArrayIndex index = 0; index < array.size(); ++index)
273✔
654
            LoadDevice(port_config, array[index], id_prefix + std::to_string(index), templates, deviceFactory);
199✔
655

656
        handlerConfig->AddPortConfig(port_config);
89✔
657
    }
658
}
659

660
std::string DecorateIfNotEmpty(const std::string& prefix, const std::string& str, const std::string& postfix)
72✔
661
{
662
    if (str.empty()) {
72✔
663
        return std::string();
×
664
    }
665
    return prefix + str + postfix;
144✔
666
}
667

668
void SetIfExists(Json::Value& dst, const std::string& dstKey, const Json::Value& src, const std::string& srcKey)
144✔
669
{
670
    if (src.isMember(srcKey)) {
144✔
671
        dst[dstKey] = src[srcKey];
44✔
672
    }
673
}
144✔
674

675
PFeaturePort DefaultPortFactory(const Json::Value& port_data, PRPCConfig rpcConfig)
21✔
676
{
677
    auto port_type = port_data.get("port_type", "serial").asString();
63✔
678
    if (port_type == "serial") {
21✔
679
        return OpenSerialPort(port_data, rpcConfig);
17✔
680
    }
681
    if (port_type == "tcp") {
4✔
682
        return OpenTcpPort(port_data, rpcConfig);
4✔
683
    }
684
    if (port_type == "modbus tcp") {
×
685
        return OpenModbusTcpPort(port_data, rpcConfig);
×
686
    }
687
    throw TConfigParserException("invalid port_type: '" + port_type + "'");
×
688
}
689

690
Json::Value LoadConfigTemplatesSchema(const std::string& templateSchemaFileName, const Json::Value& commonDeviceSchema)
19✔
691
{
692
    Json::Value schema = WBMQTT::JSON::Parse(templateSchemaFileName);
19✔
693
    AppendParams(schema["definitions"], commonDeviceSchema["definitions"]);
19✔
694
    return schema;
19✔
695
}
696

697
void AddRegisterType(Json::Value& configSchema, const std::string& registerType)
19✔
698
{
699
    configSchema["definitions"]["reg_type"]["enum"].append(registerType);
19✔
700
}
19✔
701

702
void CheckDuplicatePorts(const THandlerConfig& handlerConfig)
77✔
703
{
704
    std::unordered_set<std::string> paths;
154✔
705
    for (const auto& port: handlerConfig.PortConfigs) {
166✔
706
        if (!paths.insert(port->Port->GetDescription(false)).second) {
89✔
707
            throw TConfigParserException("Duplicate port: " + port->Port->GetDescription(false));
×
708
        }
709
    }
710
}
77✔
711

712
void CheckDuplicateDeviceIds(const THandlerConfig& handlerConfig)
77✔
713
{
714
    std::unordered_set<std::string> ids;
154✔
715
    for (const auto& port: handlerConfig.PortConfigs) {
164✔
716
        for (const auto& device: port->Devices) {
263✔
717
            if (!ids.insert(device->Device->DeviceConfig()->Id).second) {
176✔
718
                throw TConfigParserException(
1✔
719
                    "Duplicate MQTT device id: " + device->Device->DeviceConfig()->Id +
2✔
720
                    ", set device MQTT ID explicitly to fix (see https://wb.wiki/serial-id-collision)");
3✔
721
            }
722
        }
723
    }
724
}
76✔
725

726
PHandlerConfig LoadConfig(const std::string& configFileName,
90✔
727
                          TSerialDeviceFactory& deviceFactory,
728
                          const Json::Value& commonDeviceSchema,
729
                          TTemplateMap& templates,
730
                          PRPCConfig rpcConfig,
731
                          const Json::Value& portsSchema,
732
                          TProtocolConfedSchemasMap& protocolSchemas,
733
                          TPortFactoryFn portFactory)
734
{
735
    PHandlerConfig handlerConfig(new THandlerConfig);
90✔
736
    Json::Value Root(Parse(configFileName));
180✔
737
    FixOldConfigFormat(Root, templates);
90✔
738

739
    try {
740
        ValidateConfig(Root, deviceFactory, commonDeviceSchema, portsSchema, templates, protocolSchemas);
90✔
741
    } catch (const std::runtime_error& e) {
16✔
742
        throw std::runtime_error("File: " + configFileName + " error: " + e.what());
8✔
743
    }
744

745
    // wb6 - single core - max 100 registers per second
746
    // wb7 - 4 cores - max 800 registers per second
747
    handlerConfig->LowPriorityRegistersRateLimit = (1 == get_nprocs_conf()) ? 100 : 800;
82✔
748
    Get(Root, "rate_limit", handlerConfig->LowPriorityRegistersRateLimit);
82✔
749

750
    Get(Root, "debug", handlerConfig->Debug);
82✔
751

752
    auto maxUnchangedInterval = DefaultMaxUnchangedInterval;
82✔
753
    Get(Root, "max_unchanged_interval", maxUnchangedInterval);
82✔
754
    if (maxUnchangedInterval.count() > 0 && maxUnchangedInterval < MaxUnchangedIntervalLowLimit) {
82✔
755
        LOG(Warn) << "\"max_unchanged_interval\" is set to " << MaxUnchangedIntervalLowLimit.count() << " instead of "
×
756
                  << maxUnchangedInterval.count();
×
757
        maxUnchangedInterval = MaxUnchangedIntervalLowLimit;
×
758
    }
759
    handlerConfig->PublishParameters.Set(maxUnchangedInterval.count());
82✔
760

761
    const Json::Value& array = Root["ports"];
82✔
762
    for (Json::Value::ArrayIndex index = 0; index < array.size(); ++index) {
171✔
763
        // old default prefix for compat
764
        LoadPort(handlerConfig,
188✔
765
                 array[index],
766
                 "wb-modbus-" + std::to_string(index) + "-",
203✔
767
                 templates,
768
                 rpcConfig,
769
                 deviceFactory,
770
                 portFactory);
391✔
771
    }
772

773
    CheckDuplicatePorts(*handlerConfig);
77✔
774
    CheckDuplicateDeviceIds(*handlerConfig);
77✔
775

776
    return handlerConfig;
152✔
777
}
778

779
void TPortConfig::AddDevice(PSerialDeviceWithChannels device)
181✔
780
{
781
    // try to find duplicate of this device
782
    for (auto dev: Devices) {
406✔
783
        if (dev->Device->Protocol() == device->Device->Protocol()) {
225✔
784
            if (dev->Device->Protocol()->IsSameSlaveId(dev->Device->DeviceConfig()->SlaveId,
672✔
785
                                                       device->Device->DeviceConfig()->SlaveId))
448✔
786
            {
787
                stringstream ss;
4✔
788
                ss << "id \"" << device->Device->DeviceConfig()->SlaveId << "\" of device \""
2✔
789
                   << device->Device->DeviceConfig()->Name
4✔
790
                   << "\" is already set to device \"" + device->Device->DeviceConfig()->Name + "\"";
6✔
791
                throw TConfigParserException(ss.str());
2✔
792
            }
793
        }
794
    }
795

796
    Devices.push_back(device);
179✔
797
}
179✔
798

799
TDeviceChannelConfig::TDeviceChannelConfig(const std::string& type,
981✔
800
                                           const std::string& deviceId,
801
                                           int order,
802
                                           bool readOnly,
803
                                           const std::string& mqttId,
804
                                           const std::vector<PRegister>& regs)
981✔
805
    : MqttId(mqttId),
806
      Type(type),
807
      DeviceId(deviceId),
808
      Order(order),
809
      ReadOnly(readOnly),
810
      Registers(regs)
981✔
811
{}
981✔
812

813
const std::string& TDeviceChannelConfig::GetName() const
64✔
814
{
815
    auto it = Titles.find("en");
64✔
816
    if (it != Titles.end()) {
64✔
817
        return it->second;
5✔
818
    }
819
    return MqttId;
59✔
820
}
821

822
const TTitleTranslations& TDeviceChannelConfig::GetTitles() const
528✔
823
{
824
    return Titles;
528✔
825
}
826

827
void TDeviceChannelConfig::SetTitle(const std::string& name, const std::string& lang)
13✔
828
{
829
    if (!lang.empty()) {
13✔
830
        Titles[lang] = name;
13✔
831
    }
832
}
13✔
833

834
const std::map<std::string, TTitleTranslations>& TDeviceChannelConfig::GetEnumTitles() const
466✔
835
{
836
    return EnumTitles;
466✔
837
}
838

839
void TDeviceChannelConfig::SetEnumTitles(const std::string& value, const TTitleTranslations& titles)
4✔
840
{
841
    if (!value.empty()) {
4✔
842
        EnumTitles[value] = titles;
4✔
843
    }
844
}
4✔
845

846
TDeviceSetupItemConfig::TDeviceSetupItemConfig(const std::string& name,
108✔
847
                                               PRegisterConfig reg,
848
                                               const std::string& value,
849
                                               const std::string& parameterId)
108✔
850
    : Name(name),
851
      RegisterConfig(reg),
852
      Value(value),
853
      ParameterId(parameterId)
113✔
854
{
855
    try {
856
        RawValue = ConvertToRawValue(*reg, Value);
108✔
857
    } catch (const std::exception& e) {
2✔
858
        throw TConfigParserException("\"" + name + "\" bad value \"" + value + "\"");
1✔
859
    }
860
}
107✔
861

862
const std::string& TDeviceSetupItemConfig::GetName() const
107✔
863
{
864
    return Name;
107✔
865
}
866

867
const std::string& TDeviceSetupItemConfig::GetValue() const
105✔
868
{
869
    return Value;
105✔
870
}
871

872
const std::string& TDeviceSetupItemConfig::GetParameterId() const
105✔
873
{
874
    return ParameterId;
105✔
875
}
876

877
TRegisterValue TDeviceSetupItemConfig::GetRawValue() const
107✔
878
{
879
    return RawValue;
107✔
880
}
881

882
PRegisterConfig TDeviceSetupItemConfig::GetRegisterConfig() const
212✔
883
{
884
    return RegisterConfig;
212✔
885
}
886

887
void THandlerConfig::AddPortConfig(PPortConfig portConfig)
89✔
888
{
889
    PortConfigs.push_back(portConfig);
89✔
890
}
89✔
891

892
TConfigParserException::TConfigParserException(const std::string& message)
6✔
893
    : std::runtime_error("Error parsing config file: " + message)
6✔
894
{}
6✔
895

896
bool IsSubdeviceChannel(const Json::Value& channelSchema)
×
897
{
898
    return (channelSchema.isMember("oneOf") || channelSchema.isMember("device_type"));
×
899
}
900

901
std::string GetProtocolName(const Json::Value& deviceDescription)
38✔
902
{
903
    std::string p;
38✔
904
    Get(deviceDescription, "protocol", p);
38✔
905
    if (p.empty()) {
38✔
906
        p = DefaultProtocol;
27✔
907
    }
908
    return p;
38✔
909
}
910

911
void LoadChannels(TSerialDeviceWithChannels& deviceWithChannels,
182✔
912
                  const Json::Value& deviceData,
913
                  const std::optional<std::chrono::milliseconds>& defaultReadRateLimit,
914
                  const TRegisterTypeMap& typeMap,
915
                  const TLoadingContext& context)
916
{
917
    if (deviceData.isMember("channels")) {
182✔
918
        for (const auto& channel_data: deviceData["channels"]) {
1,157✔
919
            LoadChannel(deviceWithChannels, channel_data, context, typeMap);
976✔
920
        }
921
    }
922

923
    if (deviceWithChannels.Channels.empty()) {
181✔
924
        LOG(Warn) << "device " << deviceWithChannels.Device->DeviceConfig()->Name << " has no channels";
×
925
    } else if (deviceWithChannels.Device->IsSporadicOnly()) {
181✔
926
        LOG(Debug) << "device " << deviceWithChannels.Device->DeviceConfig()->Name
×
927
                   << " has only sporadic channels enabled";
×
928
    }
929

930
    auto readRateLimit = GetReadRateLimit(deviceData);
181✔
931
    if (!readRateLimit) {
181✔
932
        readRateLimit = defaultReadRateLimit;
177✔
933
    }
934
    for (auto channel: deviceWithChannels.Channels) {
1,161✔
935
        for (auto reg: channel->Registers) {
2,016✔
936
            if (!reg->GetConfig()->ReadRateLimit) {
1,036✔
937
                reg->GetConfig()->ReadRateLimit = readRateLimit;
1,032✔
938
            }
939
        }
940
    }
941
}
181✔
942

943
void TSerialDeviceFactory::RegisterProtocol(PProtocol protocol, IDeviceFactory* deviceFactory)
3,488✔
944
{
945
    TDeviceProtocolParams params = {protocol, std::shared_ptr<IDeviceFactory>(deviceFactory)};
3,488✔
946
    Protocols.insert(std::make_pair(protocol->GetName(), params));
3,488✔
947
}
3,488✔
948

949
TDeviceProtocolParams TSerialDeviceFactory::GetProtocolParams(const std::string& protocolName) const
434✔
950
{
951
    auto it = Protocols.find(protocolName);
434✔
952
    if (it == Protocols.end()) {
434✔
953
        throw TSerialDeviceException("unknown protocol: " + protocolName);
×
954
    }
955
    return it->second;
868✔
956
}
957

958
PProtocol TSerialDeviceFactory::GetProtocol(const std::string& protocolName) const
152✔
959
{
960
    return GetProtocolParams(protocolName).protocol;
152✔
961
}
962

963
const std::string& TSerialDeviceFactory::GetCommonDeviceSchemaRef(const std::string& protocolName) const
61✔
964
{
965
    return GetProtocolParams(protocolName).factory->GetCommonDeviceSchemaRef();
61✔
966
}
967

968
const std::string& TSerialDeviceFactory::GetCustomChannelSchemaRef(const std::string& protocolName) const
37✔
969
{
970
    return GetProtocolParams(protocolName).factory->GetCustomChannelSchemaRef();
37✔
971
}
972

973
std::vector<std::string> TSerialDeviceFactory::GetProtocolNames() const
1✔
974
{
975
    std::vector<std::string> res;
1✔
976
    for (const auto& bucket: Protocols) {
25✔
977
        res.emplace_back(bucket.first);
24✔
978
    }
979
    return res;
1✔
980
}
981

982
PSerialDeviceWithChannels TSerialDeviceFactory::CreateDevice(const Json::Value& deviceConfigJson,
184✔
983
                                                             const TCreateDeviceParams& params,
984
                                                             TTemplateMap& templates)
985
{
986
    TDeviceConfigLoadParams loadParams;
368✔
987
    loadParams.Defaults = params.Defaults;
184✔
988
    const auto* cfg = &deviceConfigJson;
184✔
989
    unique_ptr<Json::Value> mergedConfig;
184✔
990
    auto isWBDevice = false;
184✔
991
    if (deviceConfigJson.isMember("device_type")) {
184✔
992
        auto deviceType = deviceConfigJson["device_type"].asString();
60✔
993
        auto deviceTemplate = templates.GetTemplate(deviceType);
32✔
994
        loadParams.DeviceTemplateTitle = deviceTemplate->GetTitle();
30✔
995
        mergedConfig = std::make_unique<Json::Value>(
28✔
996
            MergeDeviceConfigWithTemplate(deviceConfigJson, deviceType, deviceTemplate->GetTemplate()));
58✔
997
        cfg = mergedConfig.get();
28✔
998
        loadParams.Translations = &deviceTemplate->GetTemplate()["translations"];
28✔
999
        isWBDevice = !deviceTemplate->GetHardware().empty();
28✔
1000
    }
1001
    std::string protocolName = DefaultProtocol;
364✔
1002
    Get(*cfg, "protocol", protocolName);
182✔
1003

1004
    if (params.IsModbusTcp) {
182✔
1005
        if (!GetProtocol(protocolName)->IsModbus()) {
×
1006
            throw TSerialDeviceException("Protocol \"" + protocolName + "\" is not compatible with Modbus TCP");
×
1007
        }
1008
        protocolName += "-tcp";
×
1009
    }
1010

1011
    TDeviceProtocolParams protocolParams = GetProtocolParams(protocolName);
364✔
1012
    auto deviceConfig = LoadDeviceConfig(*cfg, protocolParams.protocol, loadParams, isWBDevice);
364✔
1013
    auto deviceWithChannels = std::make_shared<TSerialDeviceWithChannels>();
182✔
1014
    deviceWithChannels->Device = protocolParams.factory->CreateDevice(*cfg, deviceConfig, protocolParams.protocol);
182✔
1015
    TLoadingContext context(*protocolParams.factory,
182✔
1016
                            protocolParams.factory->GetRegisterAddressFactory().GetBaseRegisterAddress());
364✔
1017
    context.translations = loadParams.Translations;
182✔
1018
    auto regTypes = protocolParams.protocol->GetRegTypes();
364✔
1019
    LoadSetupItems(*deviceWithChannels->Device, *cfg, *regTypes, context);
182✔
1020
    LoadChannels(*deviceWithChannels, *cfg, params.Defaults.ReadRateLimit, *regTypes, context);
182✔
1021

1022
    return deviceWithChannels;
362✔
1023
}
1024

1025
IDeviceFactory::IDeviceFactory(std::unique_ptr<IRegisterAddressFactory> registerAddressFactory,
3,488✔
1026
                               const std::string& commonDeviceSchemaRef,
1027
                               const std::string& customChannelSchemaRef)
3,488✔
1028
    : CommonDeviceSchemaRef(commonDeviceSchemaRef),
1029
      CustomChannelSchemaRef(customChannelSchemaRef),
1030
      RegisterAddressFactory(std::move(registerAddressFactory))
3,488✔
1031
{}
3,488✔
1032

1033
const std::string& IDeviceFactory::GetCommonDeviceSchemaRef() const
61✔
1034
{
1035
    return CommonDeviceSchemaRef;
61✔
1036
}
1037

1038
const std::string& IDeviceFactory::GetCustomChannelSchemaRef() const
37✔
1039
{
1040
    return CustomChannelSchemaRef;
37✔
1041
}
1042

1043
const IRegisterAddressFactory& IDeviceFactory::GetRegisterAddressFactory() const
1,355✔
1044
{
1045
    return *RegisterAddressFactory;
1,355✔
1046
}
1047

1048
PDeviceConfig LoadDeviceConfig(const Json::Value& dev,
182✔
1049
                               PProtocol protocol,
1050
                               const TDeviceConfigLoadParams& parameters,
1051
                               bool isWBDevice)
1052
{
1053
    auto res = std::make_shared<TDeviceConfig>();
182✔
1054

1055
    Get(dev, "device_type", res->DeviceType);
182✔
1056

1057
    res->Id = Read(dev, "id", parameters.Defaults.Id);
182✔
1058
    Get(dev, "name", res->Name);
182✔
1059

1060
    if (dev.isMember("slave_id")) {
182✔
1061
        res->SlaveId = dev["slave_id"].asString();
182✔
1062
    }
1063

1064
    LoadCommonDeviceParameters(*res, dev, isWBDevice);
182✔
1065

1066
    if (res->RequestDelay.count() == 0) {
182✔
1067
        res->RequestDelay = parameters.Defaults.RequestDelay;
173✔
1068
    }
1069

1070
    return res;
182✔
1071
}
1072

1073
TLoadRegisterConfigResult LoadRegisterConfig(const Json::Value& registerData,
1,156✔
1074
                                             const TRegisterTypeMap& typeMap,
1075
                                             const std::string& readonlyOverrideErrorMessagePrefix,
1076
                                             const IDeviceFactory& factory,
1077
                                             const IRegisterAddress& deviceBaseAddress,
1078
                                             size_t stride)
1079
{
1080
    TLoadRegisterConfigResult res;
1,156✔
1081
    TRegisterType regType = GetRegisterType(registerData, typeMap);
2,312✔
1082
    res.DefaultControlType = regType.DefaultControlType.empty() ? "text" : regType.DefaultControlType;
1,156✔
1083

1084
    if (registerData.isMember("format")) {
1,156✔
1085
        regType.DefaultFormat = RegisterFormatFromName(registerData["format"].asString());
595✔
1086
    }
1087

1088
    if (registerData.isMember("word_order")) {
1,156✔
1089
        regType.DefaultWordOrder = WordOrderFromName(registerData["word_order"].asString());
21✔
1090
    }
1091

1092
    if (registerData.isMember("byte_order")) {
1,156✔
1093
        regType.DefaultByteOrder = ByteOrderFromName(registerData["byte_order"].asString());
20✔
1094
    }
1095

1096
    double scale = Read(registerData, "scale", 1.0); // TBD: check for zero, too
1,156✔
1097
    double offset = Read(registerData, "offset", 0.0);
1,156✔
1098
    double round_to = Read(registerData, "round_to", 0.0);
1,156✔
1099
    TRegisterConfig::TSporadicMode sporadicMode = TRegisterConfig::TSporadicMode::DISABLED;
1,156✔
1100
    if (Read(registerData, "sporadic", false)) {
1,156✔
1101
        sporadicMode = TRegisterConfig::TSporadicMode::ONLY_EVENTS;
1✔
1102
    }
1103
    if (Read(registerData, "semi-sporadic", false)) {
1,156✔
1104
        sporadicMode = TRegisterConfig::TSporadicMode::EVENTS_AND_POLLING;
×
1105
    }
1106

1107
    bool readonly = ReadChannelsReadonlyProperty(registerData,
1,156✔
1108
                                                 "readonly",
1109
                                                 regType.ReadOnly,
1110
                                                 readonlyOverrideErrorMessagePrefix,
1111
                                                 regType.Name);
2,312✔
1112
    // For compatibility with old configs
1113
    readonly = ReadChannelsReadonlyProperty(registerData,
1,156✔
1114
                                            "channel_readonly",
1115
                                            readonly,
1116
                                            readonlyOverrideErrorMessagePrefix,
1117
                                            regType.Name);
2,312✔
1118

1119
    auto registerDesc =
1120
        factory.GetRegisterAddressFactory().LoadRegisterAddress(registerData,
1,156✔
1121
                                                                deviceBaseAddress,
1122
                                                                stride,
1123
                                                                RegisterFormatByteWidth(regType.DefaultFormat));
2,312✔
1124

1125
    if ((regType.DefaultFormat == RegisterFormat::String || regType.DefaultFormat == RegisterFormat::String8) &&
1,156✔
1126
        registerDesc.DataWidth == 0)
8✔
1127
    {
1128
        throw TConfigParserException(readonlyOverrideErrorMessagePrefix +
×
1129
                                     ": String size is not set for register string format");
×
1130
    }
1131

1132
    res.RegisterConfig = TRegisterConfig::Create(regType.Index,
1,156✔
1133
                                                 registerDesc,
1134
                                                 regType.DefaultFormat,
1135
                                                 scale,
1136
                                                 offset,
1137
                                                 round_to,
1138
                                                 sporadicMode,
1139
                                                 readonly,
1140
                                                 regType.Name,
1141
                                                 regType.DefaultWordOrder,
1142
                                                 regType.DefaultByteOrder);
1,156✔
1143

1144
    if (registerData.isMember("error_value")) {
1,156✔
1145
        res.RegisterConfig->ErrorValue = TRegisterValue{ToUint64(registerData["error_value"], "error_value")};
238✔
1146
    }
1147

1148
    if (registerData.isMember("unsupported_value")) {
1,156✔
1149
        res.RegisterConfig->UnsupportedValue =
10✔
1150
            TRegisterValue{ToUint64(registerData["unsupported_value"], "unsupported_value")};
20✔
1151
    }
1152

1153
    res.RegisterConfig->ReadRateLimit = GetReadRateLimit(registerData);
1,156✔
1154
    res.RegisterConfig->ReadPeriod = GetReadPeriod(registerData);
1,156✔
1155
    return res;
2,312✔
1156
}
1157

1158
void RegisterProtocols(TSerialDeviceFactory& deviceFactory)
144✔
1159
{
1160
    TEnergomeraIecWithFastReadDevice::Register(deviceFactory);
144✔
1161
    TEnergomeraIecModeCDevice::Register(deviceFactory);
144✔
1162
    TIVTMDevice::Register(deviceFactory);
144✔
1163
    TLLSDevice::Register(deviceFactory);
144✔
1164
    TMercury200Device::Register(deviceFactory);
144✔
1165
    TMercury230Device::Register(deviceFactory);
144✔
1166
    TMilurDevice::Register(deviceFactory);
144✔
1167
    TModbusDevice::Register(deviceFactory);
144✔
1168
    TModbusIODevice::Register(deviceFactory);
144✔
1169
    TNevaDevice::Register(deviceFactory);
144✔
1170
    TPulsarDevice::Register(deviceFactory);
144✔
1171
    TS2KDevice::Register(deviceFactory);
144✔
1172
    TUnielDevice::Register(deviceFactory);
144✔
1173
    TDlmsDevice::Register(deviceFactory);
144✔
1174
    Dooya::TDevice::Register(deviceFactory);
144✔
1175
    WinDeco::TDevice::Register(deviceFactory);
144✔
1176
    Somfy::TDevice::Register(deviceFactory);
144✔
1177
    Aok::TDevice::Register(deviceFactory);
144✔
1178
    TIecModeCDevice::Register(deviceFactory);
144✔
1179
    TEnergomeraCeDevice::Register(deviceFactory);
144✔
1180
}
144✔
1181

1182
TRegisterBitsAddress LoadRegisterBitsAddress(const Json::Value& register_data, const std::string& jsonPropertyName)
1,148✔
1183
{
1184
    TRegisterBitsAddress res;
1,148✔
1185
    const auto& addressValue = register_data[jsonPropertyName];
1,148✔
1186
    if (addressValue.isString()) {
1,148✔
1187
        const auto& addressStr = addressValue.asString();
496✔
1188
        auto pos1 = addressStr.find(':');
248✔
1189
        if (pos1 == string::npos) {
248✔
1190
            res.Address = static_cast<uint32_t>(GetUint64(register_data, jsonPropertyName));
218✔
1191
        } else {
1192
            res.Address = GetIntFromString(addressStr.substr(0, pos1), jsonPropertyName);
30✔
1193
            auto pos2 = addressStr.find(':', pos1 + 1);
30✔
1194
            auto bitOffset = stoul(addressStr.substr(pos1 + 1, pos2));
30✔
1195
            if (bitOffset > 255) {
30✔
1196
                throw TConfigParserException(
×
1197
                    "address parsing failed: bit shift must be in range [0, 255] (address string: '" + addressStr +
×
1198
                    "')");
×
1199
            }
1200
            res.BitOffset = bitOffset;
30✔
1201
            if (pos2 != string::npos) {
30✔
1202
                res.BitWidth = stoul(addressStr.substr(pos2 + 1));
30✔
1203
            }
1204
        }
1205
    } else {
1206
        res.Address = static_cast<uint32_t>(GetUint64(register_data, jsonPropertyName));
900✔
1207
    }
1208

1209
    if (register_data.isMember("string_data_size")) {
1,148✔
1210
        res.BitWidth = register_data["string_data_size"].asUInt() * sizeof(char) * 8;
8✔
1211
    }
1212
    return res;
1,148✔
1213
}
1214

1215
TUint32RegisterAddressFactory::TUint32RegisterAddressFactory(size_t bytesPerRegister)
2,768✔
1216
    : BaseRegisterAddress(0),
1217
      BytesPerRegister(bytesPerRegister)
2,768✔
1218
{}
2,768✔
1219

1220
TRegisterDesc TUint32RegisterAddressFactory::LoadRegisterAddress(const Json::Value& regCfg,
1,092✔
1221
                                                                 const IRegisterAddress& deviceBaseAddress,
1222
                                                                 uint32_t stride,
1223
                                                                 uint32_t registerByteWidth) const
1224
{
1225
    TRegisterDesc res;
1,092✔
1226

1227
    if (HasNoEmptyProperty(regCfg, SerialConfig::ADDRESS_PROPERTY_NAME)) {
1,092✔
1228
        auto addr = LoadRegisterBitsAddress(regCfg, SerialConfig::ADDRESS_PROPERTY_NAME);
1,092✔
1229
        res.DataOffset = addr.BitOffset;
1,092✔
1230
        res.DataWidth = addr.BitWidth;
1,092✔
1231
        res.Address = std::shared_ptr<IRegisterAddress>(
1,092✔
1232
            deviceBaseAddress.CalcNewAddress(addr.Address, stride, registerByteWidth, BytesPerRegister));
1,092✔
1233
        res.WriteAddress = res.Address;
1,092✔
1234
    }
1235
    if (HasNoEmptyProperty(regCfg, SerialConfig::WRITE_ADDRESS_PROPERTY_NAME)) {
1,092✔
1236
        auto writeAddress = LoadRegisterBitsAddress(regCfg, SerialConfig::WRITE_ADDRESS_PROPERTY_NAME);
1✔
1237
        res.WriteAddress = std::shared_ptr<IRegisterAddress>(
1✔
1238
            deviceBaseAddress.CalcNewAddress(writeAddress.Address, stride, registerByteWidth, BytesPerRegister));
1✔
1239
    }
1240
    return res;
1,092✔
1241
}
1242

1243
const IRegisterAddress& TUint32RegisterAddressFactory::GetBaseRegisterAddress() const
194✔
1244
{
1245
    return BaseRegisterAddress;
194✔
1246
}
1247

1248
TRegisterDesc TStringRegisterAddressFactory::LoadRegisterAddress(const Json::Value& regCfg,
×
1249
                                                                 const IRegisterAddress& deviceBaseAddress,
1250
                                                                 uint32_t stride,
1251
                                                                 uint32_t registerByteWidth) const
1252
{
1253
    TRegisterDesc res;
×
1254
    if (HasNoEmptyProperty(regCfg, SerialConfig::ADDRESS_PROPERTY_NAME)) {
×
1255
        res.Address = std::make_shared<TStringRegisterAddress>(regCfg[SerialConfig::ADDRESS_PROPERTY_NAME].asString());
×
1256
        res.WriteAddress = res.Address;
×
1257
    }
1258
    if (HasNoEmptyProperty(regCfg, SerialConfig::WRITE_ADDRESS_PROPERTY_NAME)) {
×
1259
        res.WriteAddress =
1260
            std::make_shared<TStringRegisterAddress>(regCfg[SerialConfig::WRITE_ADDRESS_PROPERTY_NAME].asString());
×
1261
    }
1262
    return res;
×
1263
}
1264

1265
const IRegisterAddress& TStringRegisterAddressFactory::GetBaseRegisterAddress() const
4✔
1266
{
1267
    return BaseRegisterAddress;
4✔
1268
}
1269

1270
bool HasNoEmptyProperty(const Json::Value& regCfg, const std::string& propertyName)
2,184✔
1271
{
1272
    return regCfg.isMember(propertyName) &&
3,277✔
1273
           !(regCfg[propertyName].isString() && regCfg[propertyName].asString().empty());
3,277✔
1274
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc