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

wirenboard / wb-mqtt-serial / 689

26 Aug 2025 01:28PM UTC coverage: 73.031% (-0.08%) from 73.114%
689

push

github

web-flow
Add protocol parameter to device/Probe RPC (#988)

  * Add protocol to Modbus TCP port information in ports/Load RPC
  * Add protocol parameter to device/Probe RPC
  * Set TCP_NODELAY for TCP ports
  * Handle TCP port closing by remote

6605 of 9406 branches covered (70.22%)

28 of 59 new or added lines in 11 files covered. (47.46%)

68 existing lines in 3 files now uncovered.

12554 of 17190 relevant lines covered (73.03%)

372.2 hits per line

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

87.73
/src/serial_config.cpp
1
#include "serial_config.h"
2
#include "file_utils.h"
3
#include "log.h"
4

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

14
#include "tcp_port.h"
15
#include "tcp_port_settings.h"
16

17
#include "serial_port.h"
18
#include "serial_port_settings.h"
19

20
#include "config_merge_template.h"
21
#include "config_schema_generator.h"
22

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

44
#define LOG(logger) ::logger.Log() << "[serial config] "
45

46
using namespace std;
47
using namespace WBMQTT::JSON;
48

49
namespace
50
{
51
    const char* DefaultProtocol = "modbus";
52

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

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

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

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

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

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

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

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

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

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

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

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

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

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

179
    std::optional<std::chrono::milliseconds> GetReadRateLimit(const Json::Value& data)
1,459✔
180
    {
181
        std::chrono::milliseconds res(-1);
1,459✔
182
        try {
183
            Get(data, "poll_interval", res);
1,459✔
184
        } catch (...) { // poll_interval is deprecated, so ignore it, if it has wrong format
×
185
        }
186
        Get(data, "read_rate_limit_ms", res);
1,459✔
187
        if (res < 0ms) {
1,459✔
188
            return std::nullopt;
1,447✔
189
        }
190
        return std::make_optional(res);
12✔
191
    }
192

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

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

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

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

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

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

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

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

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

305
            auto read_rate_limit_ms = GetReadRateLimit(channel_data);
28✔
306
            auto read_period = GetReadPeriod(channel_data);
28✔
307

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

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

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

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

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

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

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

403
        Get(channel_data, "units", channel->Units);
981✔
404

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

409
        deviceWithChannels.Channels.push_back(channel);
981✔
410
    }
411

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

586
        Get(port_data, "baud_rate", settings.BaudRate);
17✔
587

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

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

594
        PPort port = std::make_shared<TSerialPort>(settings);
17✔
595

596
        rpcConfig->AddSerialPort(settings);
17✔
597

598
        return port;
34✔
599
    }
600

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

605
        PPort port = std::make_shared<TTcpPort>(settings);
4✔
606

607
        rpcConfig->AddTCPPort(settings);
4✔
608

609
        return port;
8✔
610
    }
611

NEW
612
    PPort OpenModbusTcpPort(const Json::Value& port_data, PRPCConfig rpcConfig)
×
613
    {
NEW
614
        TTcpPortSettings settings(port_data["address"].asString(), port_data["port"].asUInt());
×
615

NEW
616
        PPort port = std::make_shared<TTcpPort>(settings);
×
617

NEW
618
        rpcConfig->AddModbusTCPPort(settings);
×
619

NEW
620
        return port;
×
621
    }
622

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

634
        auto port_config = make_shared<TPortConfig>();
188✔
635

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

639
        auto port_type = port_data.get("port_type", "serial").asString();
193✔
640

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

644
        std::tie(port_config->Port, port_config->IsModbusTcp) = portFactory(port_data, rpcConfig);
94✔
645

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

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

654
        handlerConfig->AddPortConfig(port_config);
89✔
655
    }
656
}
657

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

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

673
std::pair<PPort, bool> DefaultPortFactory(const Json::Value& port_data, PRPCConfig rpcConfig)
21✔
674
{
675
    auto port_type = port_data.get("port_type", "serial").asString();
63✔
676
    if (port_type == "serial") {
21✔
677
        return {OpenSerialPort(port_data, rpcConfig), false};
17✔
678
    }
679
    if (port_type == "tcp") {
4✔
680
        return {OpenTcpPort(port_data, rpcConfig), false};
4✔
681
    }
682
    if (port_type == "modbus tcp") {
×
NEW
683
        return {OpenModbusTcpPort(port_data, rpcConfig), true};
×
684
    }
685
    throw TConfigParserException("invalid port_type: '" + port_type + "'");
×
686
}
687

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

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

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

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

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

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

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

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

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

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

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

773
    return handlerConfig;
152✔
774
}
775

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

898
void AppendParams(Json::Value& dst, const Json::Value& src)
19✔
899
{
900
    for (auto it = src.begin(); it != src.end(); ++it) {
1,007✔
901
        dst[it.name()] = *it;
988✔
902
    }
903
}
19✔
904

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

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

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

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

947
void TSerialDeviceFactory::RegisterProtocol(PProtocol protocol, IDeviceFactory* deviceFactory)
3,486✔
948
{
949
    TDeviceProtocolParams params = {protocol, std::shared_ptr<IDeviceFactory>(deviceFactory)};
3,486✔
950
    Protocols.insert(std::make_pair(protocol->GetName(), params));
3,486✔
951
}
3,486✔
952

953
TDeviceProtocolParams TSerialDeviceFactory::GetProtocolParams(const std::string& protocolName) const
433✔
954
{
955
    auto it = Protocols.find(protocolName);
433✔
956
    if (it == Protocols.end()) {
433✔
957
        throw TSerialDeviceException("unknown protocol: " + protocolName);
×
958
    }
959
    return it->second;
866✔
960
}
961

962
PProtocol TSerialDeviceFactory::GetProtocol(const std::string& protocolName) const
151✔
963
{
964
    return GetProtocolParams(protocolName).protocol;
151✔
965
}
966

967
const std::string& TSerialDeviceFactory::GetCommonDeviceSchemaRef(const std::string& protocolName) const
61✔
968
{
969
    return GetProtocolParams(protocolName).factory->GetCommonDeviceSchemaRef();
61✔
970
}
971

972
const std::string& TSerialDeviceFactory::GetCustomChannelSchemaRef(const std::string& protocolName) const
37✔
973
{
974
    return GetProtocolParams(protocolName).factory->GetCustomChannelSchemaRef();
37✔
975
}
976

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

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

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

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

1024
    return deviceWithChannels;
362✔
1025
}
1026

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

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

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

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

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

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

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

1059
    if (dev.isMember("slave_id")) {
182✔
1060
        if (dev["slave_id"].isString())
182✔
1061
            res->SlaveId = dev["slave_id"].asString();
104✔
1062
        else // legacy
1063
            res->SlaveId = std::to_string(dev["slave_id"].asInt());
78✔
1064
    }
1065

1066
    LoadCommonDeviceParameters(*res, dev);
182✔
1067

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

1072
    return res;
182✔
1073
}
1074

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1217
TUint32RegisterAddressFactory::TUint32RegisterAddressFactory(size_t bytesPerRegister)
2,766✔
1218
    : BaseRegisterAddress(0),
1219
      BytesPerRegister(bytesPerRegister)
2,766✔
1220
{}
2,766✔
1221

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

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

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

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

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

1272
bool HasNoEmptyProperty(const Json::Value& regCfg, const std::string& propertyName)
2,184✔
1273
{
1274
    return regCfg.isMember(propertyName) &&
3,277✔
1275
           !(regCfg[propertyName].isString() && regCfg[propertyName].asString().empty());
3,277✔
1276
}
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