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

wirenboard / wb-mqtt-serial / 714

31 Oct 2025 05:56AM UTC coverage: 76.986% (+3.6%) from 73.348%
714

push

github

web-flow
Allow using domain names in RPC requests (#1010)

6860 of 9092 branches covered (75.45%)

12949 of 16820 relevant lines covered (76.99%)

750.66 hits per line

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

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

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

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

580
    PFeaturePort OpenSerialPort(const Json::Value& port_data, PRPCConfig rpcConfig)
17✔
581
    {
582
        TSerialPortSettings settings(port_data["path"].asString());
34✔
583

584
        Get(port_data, "baud_rate", settings.BaudRate);
17✔
585

586
        if (port_data.isMember("parity"))
17✔
587
            settings.Parity = port_data["parity"].asCString()[0];
10✔
588

589
        Get(port_data, "data_bits", settings.DataBits);
17✔
590
        Get(port_data, "stop_bits", settings.StopBits);
17✔
591

592
        auto port = std::make_shared<TSerialPort>(settings);
17✔
593

594
        rpcConfig->AddSerialPort(settings);
17✔
595

596
        return std::make_shared<TFeaturePort>(port, false);
51✔
597
    }
598

599
    PFeaturePort OpenTcpPort(const Json::Value& port_data, PRPCConfig rpcConfig)
4✔
600
    {
601
        TTcpPortSettings settings(port_data["address"].asString(), port_data["port"].asUInt());
8✔
602

603
        auto port = std::make_shared<TTcpPort>(settings);
4✔
604

605
        rpcConfig->AddTCPPort(settings);
4✔
606

607
        return std::make_shared<TFeaturePort>(port, false);
12✔
608
    }
609

610
    PFeaturePort OpenModbusTcpPort(const Json::Value& port_data, PRPCConfig rpcConfig)
×
611
    {
612
        TTcpPortSettings settings(port_data["address"].asString(), port_data["port"].asUInt());
×
613

614
        auto port = std::make_shared<TTcpPort>(settings);
×
615

616
        rpcConfig->AddModbusTCPPort(settings);
×
617

618
        return std::make_shared<TFeaturePort>(port, true);
×
619
    }
620

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

632
        auto port_config = make_shared<TPortConfig>();
188✔
633

634
        Get(port_data, "guard_interval_us", port_config->RequestDelay);
94✔
635
        port_config->ReadRateLimit = GetReadRateLimit(port_data);
94✔
636

637
        auto port_type = port_data.get("port_type", "serial").asString();
193✔
638

639
        Get(port_data, "connection_timeout_ms", port_config->OpenCloseSettings.MaxFailTime);
94✔
640
        Get(port_data, "connection_max_fail_cycles", port_config->OpenCloseSettings.ConnectionMaxFailCycles);
94✔
641

642
        port_config->Port = portFactory(port_data, rpcConfig);
94✔
643

644
        std::chrono::milliseconds responseTimeout = RESPONSE_TIMEOUT_NOT_SET;
94✔
645
        Get(port_data, "response_timeout_ms", responseTimeout);
94✔
646
        port_config->Port->SetMinimalResponseTimeout(responseTimeout);
94✔
647

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

652
        handlerConfig->AddPortConfig(port_config);
89✔
653
    }
654
}
655

656
std::string DecorateIfNotEmpty(const std::string& prefix, const std::string& str, const std::string& postfix)
72✔
657
{
658
    if (str.empty()) {
72✔
659
        return std::string();
×
660
    }
661
    return prefix + str + postfix;
144✔
662
}
663

664
void SetIfExists(Json::Value& dst, const std::string& dstKey, const Json::Value& src, const std::string& srcKey)
144✔
665
{
666
    if (src.isMember(srcKey)) {
144✔
667
        dst[dstKey] = src[srcKey];
44✔
668
    }
669
}
144✔
670

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

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

693
void AddRegisterType(Json::Value& configSchema, const std::string& registerType)
19✔
694
{
695
    configSchema["definitions"]["reg_type"]["enum"].append(registerType);
19✔
696
}
19✔
697

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

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

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

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

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

746
    Get(Root, "debug", handlerConfig->Debug);
82✔
747

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

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

769
    CheckDuplicatePorts(*handlerConfig);
77✔
770
    CheckDuplicateDeviceIds(*handlerConfig);
77✔
771

772
    return handlerConfig;
152✔
773
}
774

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

792
    Devices.push_back(device);
179✔
793
}
179✔
794

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

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

818
const TTitleTranslations& TDeviceChannelConfig::GetTitles() const
528✔
819
{
820
    return Titles;
528✔
821
}
822

823
void TDeviceChannelConfig::SetTitle(const std::string& name, const std::string& lang)
13✔
824
{
825
    if (!lang.empty()) {
13✔
826
        Titles[lang] = name;
13✔
827
    }
828
}
13✔
829

830
const std::map<std::string, TTitleTranslations>& TDeviceChannelConfig::GetEnumTitles() const
466✔
831
{
832
    return EnumTitles;
466✔
833
}
834

835
void TDeviceChannelConfig::SetEnumTitles(const std::string& value, const TTitleTranslations& titles)
4✔
836
{
837
    if (!value.empty()) {
4✔
838
        EnumTitles[value] = titles;
4✔
839
    }
840
}
4✔
841

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

858
const std::string& TDeviceSetupItemConfig::GetName() const
107✔
859
{
860
    return Name;
107✔
861
}
862

863
const std::string& TDeviceSetupItemConfig::GetValue() const
105✔
864
{
865
    return Value;
105✔
866
}
867

868
const std::string& TDeviceSetupItemConfig::GetParameterId() const
105✔
869
{
870
    return ParameterId;
105✔
871
}
872

873
TRegisterValue TDeviceSetupItemConfig::GetRawValue() const
107✔
874
{
875
    return RawValue;
107✔
876
}
877

878
PRegisterConfig TDeviceSetupItemConfig::GetRegisterConfig() const
212✔
879
{
880
    return RegisterConfig;
212✔
881
}
882

883
void THandlerConfig::AddPortConfig(PPortConfig portConfig)
89✔
884
{
885
    PortConfigs.push_back(portConfig);
89✔
886
}
89✔
887

888
TConfigParserException::TConfigParserException(const std::string& message)
6✔
889
    : std::runtime_error("Error parsing config file: " + message)
6✔
890
{}
6✔
891

892
bool IsSubdeviceChannel(const Json::Value& channelSchema)
×
893
{
894
    return (channelSchema.isMember("oneOf") || channelSchema.isMember("device_type"));
×
895
}
896

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

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

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

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

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

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

954
PProtocol TSerialDeviceFactory::GetProtocol(const std::string& protocolName) const
152✔
955
{
956
    return GetProtocolParams(protocolName).protocol;
152✔
957
}
958

959
const std::string& TSerialDeviceFactory::GetCommonDeviceSchemaRef(const std::string& protocolName) const
61✔
960
{
961
    return GetProtocolParams(protocolName).factory->GetCommonDeviceSchemaRef();
61✔
962
}
963

964
const std::string& TSerialDeviceFactory::GetCustomChannelSchemaRef(const std::string& protocolName) const
37✔
965
{
966
    return GetProtocolParams(protocolName).factory->GetCustomChannelSchemaRef();
37✔
967
}
968

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

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

998
    if (params.IsModbusTcp) {
182✔
999
        if (!GetProtocol(protocolName)->IsModbus()) {
×
1000
            throw TSerialDeviceException("Protocol \"" + protocolName + "\" is not compatible with Modbus TCP");
×
1001
        }
1002
        protocolName += "-tcp";
×
1003
    }
1004

1005
    TDeviceProtocolParams protocolParams = GetProtocolParams(protocolName);
364✔
1006
    auto deviceConfig = LoadDeviceConfig(*cfg, protocolParams.protocol, loadParams);
364✔
1007
    auto deviceWithChannels = std::make_shared<TSerialDeviceWithChannels>();
182✔
1008
    deviceWithChannels->Device = protocolParams.factory->CreateDevice(*cfg, deviceConfig, protocolParams.protocol);
182✔
1009
    TLoadingContext context(*protocolParams.factory,
182✔
1010
                            protocolParams.factory->GetRegisterAddressFactory().GetBaseRegisterAddress());
364✔
1011
    context.translations = loadParams.Translations;
182✔
1012
    auto regTypes = protocolParams.protocol->GetRegTypes();
364✔
1013
    LoadSetupItems(*deviceWithChannels->Device, *cfg, *regTypes, context);
182✔
1014
    LoadChannels(*deviceWithChannels, *cfg, params.Defaults.ReadRateLimit, *regTypes, context);
182✔
1015

1016
    return deviceWithChannels;
362✔
1017
}
1018

1019
IDeviceFactory::IDeviceFactory(std::unique_ptr<IRegisterAddressFactory> registerAddressFactory,
3,488✔
1020
                               const std::string& commonDeviceSchemaRef,
1021
                               const std::string& customChannelSchemaRef)
3,488✔
1022
    : CommonDeviceSchemaRef(commonDeviceSchemaRef),
1023
      CustomChannelSchemaRef(customChannelSchemaRef),
1024
      RegisterAddressFactory(std::move(registerAddressFactory))
3,488✔
1025
{}
3,488✔
1026

1027
const std::string& IDeviceFactory::GetCommonDeviceSchemaRef() const
61✔
1028
{
1029
    return CommonDeviceSchemaRef;
61✔
1030
}
1031

1032
const std::string& IDeviceFactory::GetCustomChannelSchemaRef() const
37✔
1033
{
1034
    return CustomChannelSchemaRef;
37✔
1035
}
1036

1037
const IRegisterAddressFactory& IDeviceFactory::GetRegisterAddressFactory() const
1,355✔
1038
{
1039
    return *RegisterAddressFactory;
1,355✔
1040
}
1041

1042
PDeviceConfig LoadDeviceConfig(const Json::Value& dev, PProtocol protocol, const TDeviceConfigLoadParams& parameters)
182✔
1043
{
1044
    auto res = std::make_shared<TDeviceConfig>();
182✔
1045

1046
    Get(dev, "device_type", res->DeviceType);
182✔
1047

1048
    res->Id = Read(dev, "id", parameters.Defaults.Id);
182✔
1049
    Get(dev, "name", res->Name);
182✔
1050

1051
    if (dev.isMember("slave_id")) {
182✔
1052
        res->SlaveId = dev["slave_id"].asString();
182✔
1053
    }
1054

1055
    LoadCommonDeviceParameters(*res, dev);
182✔
1056

1057
    if (res->RequestDelay.count() == 0) {
182✔
1058
        res->RequestDelay = parameters.Defaults.RequestDelay;
173✔
1059
    }
1060

1061
    return res;
182✔
1062
}
1063

1064
TLoadRegisterConfigResult LoadRegisterConfig(const Json::Value& registerData,
1,156✔
1065
                                             const TRegisterTypeMap& typeMap,
1066
                                             const std::string& readonlyOverrideErrorMessagePrefix,
1067
                                             const IDeviceFactory& factory,
1068
                                             const IRegisterAddress& deviceBaseAddress,
1069
                                             size_t stride)
1070
{
1071
    TLoadRegisterConfigResult res;
1,156✔
1072
    TRegisterType regType = GetRegisterType(registerData, typeMap);
2,312✔
1073
    res.DefaultControlType = regType.DefaultControlType.empty() ? "text" : regType.DefaultControlType;
1,156✔
1074

1075
    if (registerData.isMember("format")) {
1,156✔
1076
        regType.DefaultFormat = RegisterFormatFromName(registerData["format"].asString());
595✔
1077
    }
1078

1079
    if (registerData.isMember("word_order")) {
1,156✔
1080
        regType.DefaultWordOrder = WordOrderFromName(registerData["word_order"].asString());
21✔
1081
    }
1082

1083
    if (registerData.isMember("byte_order")) {
1,156✔
1084
        regType.DefaultByteOrder = ByteOrderFromName(registerData["byte_order"].asString());
20✔
1085
    }
1086

1087
    double scale = Read(registerData, "scale", 1.0); // TBD: check for zero, too
1,156✔
1088
    double offset = Read(registerData, "offset", 0.0);
1,156✔
1089
    double round_to = Read(registerData, "round_to", 0.0);
1,156✔
1090
    TRegisterConfig::TSporadicMode sporadicMode = TRegisterConfig::TSporadicMode::DISABLED;
1,156✔
1091
    if (Read(registerData, "sporadic", false)) {
1,156✔
1092
        sporadicMode = TRegisterConfig::TSporadicMode::ONLY_EVENTS;
1✔
1093
    }
1094
    if (Read(registerData, "semi-sporadic", false)) {
1,156✔
1095
        sporadicMode = TRegisterConfig::TSporadicMode::EVENTS_AND_POLLING;
×
1096
    }
1097

1098
    bool readonly = ReadChannelsReadonlyProperty(registerData,
1,156✔
1099
                                                 "readonly",
1100
                                                 regType.ReadOnly,
1101
                                                 readonlyOverrideErrorMessagePrefix,
1102
                                                 regType.Name);
2,312✔
1103
    // For compatibility with old configs
1104
    readonly = ReadChannelsReadonlyProperty(registerData,
1,156✔
1105
                                            "channel_readonly",
1106
                                            readonly,
1107
                                            readonlyOverrideErrorMessagePrefix,
1108
                                            regType.Name);
2,312✔
1109

1110
    auto registerDesc =
1111
        factory.GetRegisterAddressFactory().LoadRegisterAddress(registerData,
1,156✔
1112
                                                                deviceBaseAddress,
1113
                                                                stride,
1114
                                                                RegisterFormatByteWidth(regType.DefaultFormat));
2,312✔
1115

1116
    if ((regType.DefaultFormat == RegisterFormat::String || regType.DefaultFormat == RegisterFormat::String8) &&
1,156✔
1117
        registerDesc.DataWidth == 0)
8✔
1118
    {
1119
        throw TConfigParserException(readonlyOverrideErrorMessagePrefix +
×
1120
                                     ": String size is not set for register string format");
×
1121
    }
1122

1123
    res.RegisterConfig = TRegisterConfig::Create(regType.Index,
1,156✔
1124
                                                 registerDesc,
1125
                                                 regType.DefaultFormat,
1126
                                                 scale,
1127
                                                 offset,
1128
                                                 round_to,
1129
                                                 sporadicMode,
1130
                                                 readonly,
1131
                                                 regType.Name,
1132
                                                 regType.DefaultWordOrder,
1133
                                                 regType.DefaultByteOrder);
1,156✔
1134

1135
    if (registerData.isMember("error_value")) {
1,156✔
1136
        res.RegisterConfig->ErrorValue = TRegisterValue{ToUint64(registerData["error_value"], "error_value")};
238✔
1137
    }
1138

1139
    if (registerData.isMember("unsupported_value")) {
1,156✔
1140
        res.RegisterConfig->UnsupportedValue =
10✔
1141
            TRegisterValue{ToUint64(registerData["unsupported_value"], "unsupported_value")};
20✔
1142
    }
1143

1144
    res.RegisterConfig->ReadRateLimit = GetReadRateLimit(registerData);
1,156✔
1145
    res.RegisterConfig->ReadPeriod = GetReadPeriod(registerData);
1,156✔
1146
    return res;
2,312✔
1147
}
1148

1149
void RegisterProtocols(TSerialDeviceFactory& deviceFactory)
144✔
1150
{
1151
    TEnergomeraIecWithFastReadDevice::Register(deviceFactory);
144✔
1152
    TEnergomeraIecModeCDevice::Register(deviceFactory);
144✔
1153
    TIVTMDevice::Register(deviceFactory);
144✔
1154
    TLLSDevice::Register(deviceFactory);
144✔
1155
    TMercury200Device::Register(deviceFactory);
144✔
1156
    TMercury230Device::Register(deviceFactory);
144✔
1157
    TMilurDevice::Register(deviceFactory);
144✔
1158
    TModbusDevice::Register(deviceFactory);
144✔
1159
    TModbusIODevice::Register(deviceFactory);
144✔
1160
    TNevaDevice::Register(deviceFactory);
144✔
1161
    TPulsarDevice::Register(deviceFactory);
144✔
1162
    TS2KDevice::Register(deviceFactory);
144✔
1163
    TUnielDevice::Register(deviceFactory);
144✔
1164
    TDlmsDevice::Register(deviceFactory);
144✔
1165
    Dooya::TDevice::Register(deviceFactory);
144✔
1166
    WinDeco::TDevice::Register(deviceFactory);
144✔
1167
    Somfy::TDevice::Register(deviceFactory);
144✔
1168
    Aok::TDevice::Register(deviceFactory);
144✔
1169
    TIecModeCDevice::Register(deviceFactory);
144✔
1170
    TEnergomeraCeDevice::Register(deviceFactory);
144✔
1171
}
144✔
1172

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

1200
    if (register_data.isMember("string_data_size")) {
1,148✔
1201
        res.BitWidth = register_data["string_data_size"].asUInt() * sizeof(char) * 8;
8✔
1202
    }
1203
    return res;
1,148✔
1204
}
1205

1206
TUint32RegisterAddressFactory::TUint32RegisterAddressFactory(size_t bytesPerRegister)
2,768✔
1207
    : BaseRegisterAddress(0),
1208
      BytesPerRegister(bytesPerRegister)
2,768✔
1209
{}
2,768✔
1210

1211
TRegisterDesc TUint32RegisterAddressFactory::LoadRegisterAddress(const Json::Value& regCfg,
1,092✔
1212
                                                                 const IRegisterAddress& deviceBaseAddress,
1213
                                                                 uint32_t stride,
1214
                                                                 uint32_t registerByteWidth) const
1215
{
1216
    TRegisterDesc res;
1,092✔
1217

1218
    if (HasNoEmptyProperty(regCfg, SerialConfig::ADDRESS_PROPERTY_NAME)) {
1,092✔
1219
        auto addr = LoadRegisterBitsAddress(regCfg, SerialConfig::ADDRESS_PROPERTY_NAME);
1,092✔
1220
        res.DataOffset = addr.BitOffset;
1,092✔
1221
        res.DataWidth = addr.BitWidth;
1,092✔
1222
        res.Address = std::shared_ptr<IRegisterAddress>(
1,092✔
1223
            deviceBaseAddress.CalcNewAddress(addr.Address, stride, registerByteWidth, BytesPerRegister));
1,092✔
1224
        res.WriteAddress = res.Address;
1,092✔
1225
    }
1226
    if (HasNoEmptyProperty(regCfg, SerialConfig::WRITE_ADDRESS_PROPERTY_NAME)) {
1,092✔
1227
        auto writeAddress = LoadRegisterBitsAddress(regCfg, SerialConfig::WRITE_ADDRESS_PROPERTY_NAME);
1✔
1228
        res.WriteAddress = std::shared_ptr<IRegisterAddress>(
1✔
1229
            deviceBaseAddress.CalcNewAddress(writeAddress.Address, stride, registerByteWidth, BytesPerRegister));
1✔
1230
    }
1231
    return res;
1,092✔
1232
}
1233

1234
const IRegisterAddress& TUint32RegisterAddressFactory::GetBaseRegisterAddress() const
194✔
1235
{
1236
    return BaseRegisterAddress;
194✔
1237
}
1238

1239
TRegisterDesc TStringRegisterAddressFactory::LoadRegisterAddress(const Json::Value& regCfg,
×
1240
                                                                 const IRegisterAddress& deviceBaseAddress,
1241
                                                                 uint32_t stride,
1242
                                                                 uint32_t registerByteWidth) const
1243
{
1244
    TRegisterDesc res;
×
1245
    if (HasNoEmptyProperty(regCfg, SerialConfig::ADDRESS_PROPERTY_NAME)) {
×
1246
        res.Address = std::make_shared<TStringRegisterAddress>(regCfg[SerialConfig::ADDRESS_PROPERTY_NAME].asString());
×
1247
        res.WriteAddress = res.Address;
×
1248
    }
1249
    if (HasNoEmptyProperty(regCfg, SerialConfig::WRITE_ADDRESS_PROPERTY_NAME)) {
×
1250
        res.WriteAddress =
1251
            std::make_shared<TStringRegisterAddress>(regCfg[SerialConfig::WRITE_ADDRESS_PROPERTY_NAME].asString());
×
1252
    }
1253
    return res;
×
1254
}
1255

1256
const IRegisterAddress& TStringRegisterAddressFactory::GetBaseRegisterAddress() const
4✔
1257
{
1258
    return BaseRegisterAddress;
4✔
1259
}
1260

1261
bool HasNoEmptyProperty(const Json::Value& regCfg, const std::string& propertyName)
2,184✔
1262
{
1263
    return regCfg.isMember(propertyName) &&
3,277✔
1264
           !(regCfg[propertyName].isString() && regCfg[propertyName].asString().empty());
3,277✔
1265
}
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