-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmodbus_south.cpp
1917 lines (1852 loc) · 50.3 KB
/
modbus_south.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Fledge south service modbus plugin
*
* Copyright (c) 2019 OSIsoft, LLC
*
* Released under the Apache 2.0 Licence
*
* Author: Mark Riddoch
*/
#include <modbus_south.h>
#include <reading.h>
#include <logger.h>
#include <math.h>
#include <string.h>
#include <modbus/modbus-version.h>
#include "rapidjson/error/error.h"
#include "rapidjson/error/en.h"
#define INSTRUMENT_IO 0 // Enabl instrusmentation of IO and mutex
#define INSTIO_THRESHOLD 5
#if INSTRUMENT_IO
static const char *mutexHolders[] = { "None", "Config", "Read", "Write", "Destructor" };
static enum {
HolderNone = 0, HolderConfig, HolderRead, HolderWrite, HolderDestructor
} mutexHolder;
#endif
/**
* Set debug mode in the underlying modbus context. Set to
* 1 to enable debug or zero to disable it.
*
* Note, this debug will appear on standard output.
*/
#define DEBUG 0
using namespace std;
/**
* Constructor for the modbus interface, in this case it is a shell
* that is awaiting configuration.
*
* The actual modbus connection can only be created once we have
* configuration data.
*/
Modbus::Modbus() : m_modbus(0), m_tcp(false), m_port(0), m_device(""),
m_baud(0), m_bits(0), m_stopBits(0), m_parity('E'), m_errcount(0),
m_timeout(0.5), m_connectCount(0), m_disconnectCount(0),m_recreate(false)
{
}
/**
* Destructor for the modbus interface
*/
Modbus::~Modbus()
{
m_configMutex.lock();
#if INSTRUMENT_IO
mutexHolder = HolderDestructor;
#endif
removeMap();
modbus_free(m_modbus);
m_configMutex.unlock();
}
/**
* Populate the Modbus plugin shell with a connection to a real modbus device.
*
* If a connection already exists then we are called as part of reconfiguration
* and we should tear down that previous modbus context.
*/
void Modbus:: createModbus()
{
if (m_modbus)
{
modbus_free(m_modbus);
}
if (m_tcp)
{
char port[40];
snprintf(port, sizeof(port), "%d", m_port);
if ((m_modbus = modbus_new_tcp_pi(m_address.c_str(), port)) == NULL)
{
throw runtime_error(("%s", modbus_strerror(errno)));
}
struct timeval response_timeout;
response_timeout.tv_sec = floor(m_timeout);
response_timeout.tv_usec = (m_timeout - floor(m_timeout)) * 1000000;
Logger::getLogger()->debug("Set request timeout to %d seconds, %d uSeconds",
response_timeout.tv_sec, response_timeout.tv_usec);
#if LIBMODBUS_VERSION_MINOR == 0
modbus_set_response_timeout(m_modbus, &response_timeout);
#else
modbus_set_response_timeout(m_modbus, response_timeout.tv_sec, response_timeout.tv_usec);
#endif
}
else
{
if ((m_modbus = modbus_new_rtu(m_device.c_str(), m_baud, m_parity, m_bits, m_stopBits)) == NULL)
{
throw runtime_error(("%s", modbus_strerror(errno)));
}
}
#if DEBUG
modbus_set_debug(m_modbus, true);
#endif
errno = 0;
m_connectCount++;
if (modbus_connect(m_modbus) == -1)
{
Logger::getLogger()->error("Failed to connect to Modbus %s server %s, %s", (m_tcp ? "TCP" : "RTU"),
(m_tcp ? m_address.c_str() : m_device.c_str()), modbus_strerror(errno));
m_connected = false;
}
else
{
Logger::getLogger()->info("Modbus %s connected to %s", (m_tcp ? "TCP" : "RTU"), (m_tcp ? m_address.c_str() : m_device.c_str()));
m_connected = true;
}
}
/**
* Configure the modbus plugin. This may be either called to do initial
* configuration or as a result of a reconfiguration. Hence it must hold
* the mutex to prevent data being ingested mid configuration and also
* clear out any existing configuration to prevent memory leaks.
*
* Since the configuration may result in changing the server the plugin
* communicates with or the type of connection, the configure routine looks
* for changes that might require the underlying modbus context to be
* recreated. However it avoids recreating it when i is not required to
* do so.
*
* @param config The configuration category
*/
void Modbus::configure(ConfigCategory *config)
{
string device, address;
Logger *log = Logger::getLogger();
m_configMutex.lock();
try {
#if INSTRUMENT_IO
mutexHolder = HolderConfig;
#endif
if (config->itemExists("protocol"))
{
string proto = config->getValue("protocol");
if (!proto.compare("TCP"))
{
if (!m_tcp)
{
m_recreate = true;
m_tcp = true;
}
if (config->itemExists("address"))
{
address = config->getValue("address");
if (address.compare(m_address))
{
m_address = address;
m_recreate = true;
}
if (! address.empty()) // Not empty
{
unsigned short port = 502;
if (config->itemExists("port"))
{
string value = config->getValue("port");
int port = (unsigned short)atoi(value.c_str());
if (m_port != port)
{
m_port = port;
m_recreate = true;
}
}
}
}
if (config->itemExists("timeout"))
{
m_timeout = strtod(config->getValue("timeout").c_str(), NULL);
}
}
else if (!proto.compare("RTU"))
{
if (m_tcp)
{
m_recreate = true;
m_tcp = false;
}
if (config->itemExists("device"))
{
device = config->getValue("device");
int baud = 9600;
char parity = 'N';
int bits = 8;
int stopBits = 1;
if (config->itemExists("baud"))
{
string value = config->getValue("baud");
baud = atoi(value.c_str());
}
if (config->itemExists("parity"))
{
string value = config->getValue("parity");
if (value.compare("even") == 0)
{
parity = 'E';
}
else if (value.compare("odd") == 0)
{
parity = 'O';
}
else if (value.compare("none") == 0)
{
parity = 'N';
}
}
if (config->itemExists("bits"))
{
string value = config->getValue("bits");
bits = atoi(value.c_str());
}
if (config->itemExists("stopBits"))
{
string value = config->getValue("stopBits");
stopBits = atoi(value.c_str());
}
if (m_device.compare(device) != 0)
{
m_device = device;
m_recreate = true;
}
if (m_baud != baud)
{
m_baud = baud;
m_recreate = true;
}
if (m_parity != parity)
{
m_parity = parity;
m_recreate = true;
}
if (m_bits != bits)
{
m_bits = bits;
m_recreate = true;
}
if (m_stopBits != stopBits)
{
m_stopBits = stopBits;
m_recreate = true;
}
}
}
else
{
Logger::getLogger()->fatal("Modbus must specify either RTU or TCP as protocol");
}
}
else
{
Logger::getLogger()->fatal("Modbus missing protocol specification");
throw runtime_error("Unable to determine modbus protocol");
}
if (config->itemExists("slave"))
{
setDefaultSlave(atoi(config->getValue("slave").c_str()));
}
if (config->itemExists("asset"))
{
setAssetName(config->getValue("asset"));
}
else
{
setAssetName("modbus");
}
string control = config->getValue("control");
if (control.compare("None") == 0)
{
m_control = NoControlMap;
}
else if (control.compare("Use Register Map") == 0)
{
m_control = UseRegisterMap;
}
else if (control.compare("Use Control Map") == 0)
{
m_control = UseControlMap;
}
/*
* Remove any previous map
*/
removeMap();
// Now process the Modbus regster map
string map = config->getValue("map");
rapidjson::Document doc;
doc.Parse(map.c_str());
if (!doc.HasParseError())
{
if (doc.HasMember("values") && doc["values"].IsArray())
{
int errorCount = 0;
const rapidjson::Value& values = doc["values"];
for (rapidjson::Value::ConstValueIterator itr = values.Begin();
itr != values.End(); ++itr)
{
int rCount = 0;
int slaveID = getDefaultSlave();
float scale = 1.0;
float offset = 0.0;
string name = "";
string assetName = "";
if (itr->HasMember("name"))
{
if ((*itr)["name"].IsString())
{
name = (*itr)["name"].GetString();
}
else
{
log->error("The value of name in the modbus map should be a string");
errorCount++;
}
}
else
{
log->error("Each item in the modbus map must have a name property");
errorCount++;
continue;
}
if (itr->HasMember("slave"))
{
if (! (*itr)["slave"].IsInt())
{
log->error("The value of slave for item '%s' in the modbus map should be an integer", name.c_str());
errorCount++;
}
else
{
slaveID = (*itr)["slave"].GetInt();
}
}
if (itr->HasMember("assetName"))
{
if ((*itr)["assetName"].IsString())
{
assetName = (*itr)["assetName"].GetString();
}
else
{
log->error("The value of assetName for item '%s' in the modbus map should be a string", name.c_str());
errorCount++;
}
}
if (itr->HasMember("scale"))
{
if (! (*itr)["scale"].IsNumber())
{
log->error("The value of scale for item '%s' in the modbus map should be a floating point number", name.c_str());
errorCount++;
}
else
{
scale = (*itr)["scale"].GetFloat();
}
}
if (itr->HasMember("offset"))
{
if (! (*itr)["offset"].IsNumber())
{
log->error("The value of offset for item '%s' in the modbus map should be a floating point number", name.c_str());
errorCount++;
}
else
{
offset = (*itr)["offset"].GetFloat();
}
}
if (itr->HasMember("coil"))
{
rCount++;
if (! (*itr)["coil"].IsNumber())
{
log->error("The value of coil for item '%s' in the modbus map should be a number", name.c_str());
errorCount++;
}
else
{
int coil = (*itr)["coil"].GetInt();
addToMap(slaveID, new ModbusCoil(slaveID, createRegisterMap(assetName, name, coil, scale, offset)));
}
}
if (itr->HasMember("input"))
{
rCount++;
if ((*itr)["input"].IsInt())
{
int input = (*itr)["input"].GetInt();
addToMap(slaveID, new ModbusInputBits(slaveID, createRegisterMap(assetName, name, input, scale, offset)));
}
else
{
log->error("The value of input for item '%s' in the modbus map must be either an integer", name.c_str());
errorCount++;
}
}
if (itr->HasMember("register"))
{
rCount++;
if ((*itr)["register"].IsInt())
{
int regNo = (*itr)["register"].GetInt();
addToMap(slaveID, new ModbusRegister(slaveID, createRegisterMap(assetName, name, regNo, scale, offset)));
}
else if ((*itr)["register"].IsArray())
{
vector<unsigned int> words;
for (rapidjson::Value::ConstValueIterator itr2 = (*itr)["register"].Begin();
itr2 != (*itr)["register"].End(); ++itr2)
{
if (itr2->IsInt())
{
words.push_back(itr2->GetInt());
}
else
{
log->error("The register array for item '%s' in the modbus map contain integer values", name.c_str());
errorCount++;
}
}
addToMap(slaveID, new ModbusRegister(slaveID, createRegisterMap(assetName, name, words, scale, offset)));
}
else
{
log->error("The value of register for item '%s' in the modbus map must be either an integer or an array", name.c_str());
errorCount++;
}
}
if (itr->HasMember("inputRegister"))
{
rCount++;
if ((*itr)["inputRegister"].IsInt())
{
int regNo = (*itr)["inputRegister"].GetInt();
addToMap(slaveID, new ModbusInputRegister(slaveID, createRegisterMap(assetName, name, regNo, scale, offset)));
}
else if ((*itr)["inputRegister"].IsArray())
{
vector<unsigned int> words;
for (rapidjson::Value::ConstValueIterator itr2 = (*itr)["inputRegister"].Begin();
itr2 != (*itr)["inputRegister"].End(); ++itr2)
{
if (itr2->IsInt())
{
words.push_back(itr2->GetInt());
}
else
{
log->error("The value of inputRegister for item '%s' in the modbus map must be either an integer or an array", name.c_str());
errorCount++;
}
}
addToMap(slaveID, new ModbusInputRegister(slaveID, createRegisterMap(assetName, name, words, scale, offset)));
}
else
{
log->error("The value of inputRegister for item '%s' in the modbus map must be either an integer or an array", name.c_str());
errorCount++;
}
}
// Now deal with flags for the item we have just added
if (itr->HasMember("type"))
{
if ((*itr)["type"].IsString())
{
string type = (*itr)["type"].GetString();
if (type.compare("float") == 0)
{
m_lastItem->setFlag(ITEM_TYPE_FLOAT);
}
else
{
log->error("The type property '%s' of the item '%s' in the modbus map is not supported", type.c_str(), name.c_str());
errorCount++;
}
}
else
{
log->error("The type property of the item '%s' in the modbus map must be a string", name.c_str());
errorCount++;
}
}
if (itr->HasMember("swap"))
{
if ((*itr)["swap"].IsString())
{
string swap = (*itr)["swap"].GetString();
if (swap.compare("bytes") == 0)
{
m_lastItem->setFlag(ITEM_SWAP_BYTES);
}
else if (swap.compare("words") == 0)
{
m_lastItem->setFlag(ITEM_SWAP_WORDS);
}
else if (swap.compare("both") == 0)
{
m_lastItem->setFlag(ITEM_SWAP_BYTES|ITEM_SWAP_WORDS);
}
else
{
log->error("The swap property '%s' of item '%s' in the modbus map must be one of bytes, words or both", swap.c_str(), name.c_str());
errorCount++;
}
}
else
{
log->error("The swap property of the item '%s' in the modbus map must be a string", name.c_str());
errorCount++;
}
}
if (rCount == 0)
{
log->error("Item '%s' in the modbus map must have one of coil, input, register or inputRegister properties", name.c_str());
errorCount++;
}
else if (rCount > 1)
{
log->error("Item '%s' in the modbus map must only have one of coil, input, register or inputRegister properties", name.c_str());
errorCount++;
}
}
if (errorCount)
{
log->error("%d errors encountered in the modbus map", errorCount);
}
}
if (doc.HasMember("coils") && doc["coils"].IsObject())
{
for (rapidjson::Value::ConstMemberIterator itr = doc["coils"].MemberBegin();
itr != doc["coils"].MemberEnd(); ++itr)
{
addToMap(new ModbusCoil(m_defaultSlave, createRegisterMap(itr->name.GetString(), itr->value.GetUint())));
}
}
if (doc.HasMember("inputs") && doc["inputs"].IsObject())
{
for (rapidjson::Value::ConstMemberIterator itr = doc["inputs"].MemberBegin();
itr != doc["inputs"].MemberEnd(); ++itr)
{
addToMap(new ModbusInputBits(m_defaultSlave, createRegisterMap(itr->name.GetString(), itr->value.GetUint())));
}
}
if (doc.HasMember("registers") && doc["registers"].IsObject())
{
for (rapidjson::Value::ConstMemberIterator itr = doc["registers"].MemberBegin();
itr != doc["registers"].MemberEnd(); ++itr)
{
addToMap(new ModbusRegister(m_defaultSlave, createRegisterMap(itr->name.GetString(), itr->value.GetUint())));
}
}
if (doc.HasMember("inputRegisters") && doc["inputRegisters"].IsObject())
{
for (rapidjson::Value::ConstMemberIterator itr = doc["inputRegisters"].MemberBegin();
itr != doc["inputRegisters"].MemberEnd(); ++itr)
{
addToMap(new ModbusInputRegister(m_defaultSlave, createRegisterMap(itr->name.GetString(), itr->value.GetUint())));
}
}
}
else
{
log->error("Parse error in modbus map, the map must be a valid JSON object. %s",
GetParseError_En(doc.GetParseError()));
}
// Now process the Modbus control map if there is one
if (m_control == UseControlMap)
{
string map = config->getValue("controlmap");
rapidjson::Document doc;
doc.Parse(map.c_str());
if (!doc.HasParseError())
{
if (doc.HasMember("values") && doc["values"].IsArray())
{
int errorCount = 0;
const rapidjson::Value& values = doc["values"];
for (rapidjson::Value::ConstValueIterator itr = values.Begin();
itr != values.End(); ++itr)
{
ModbusEntity *entity = createEntity(*itr);
string name = entity->getMap()->m_name;
m_writeMap.insert(pair<string, Modbus::ModbusEntity *>(name, entity));
}
}
}
else
{
log->error("Parse error in control modbus map, the map must be a valid JSON object. %s",
GetParseError_En(doc.GetParseError()));
}
}
string read_method = config->getValue("readMethod");
if (read_method.compare("Object Read") == 0)
{
m_readMethod = ModbusReadMethod::Object;
} else if (read_method.compare("Single Register Read") == 0)
{
m_readMethod = ModbusReadMethod::SingleRegister;
} else {
m_readMethod = ModbusReadMethod::EfficientBlock;
optimise();
}
} catch (...) {
m_configMutex.unlock();
throw;
}
m_configMutex.unlock();
}
/**
* Create a ModbusEntity from the values in the JSON configuration
* item for that entity
*
* @param item The set of key/value pairs for the item
* @return The new ModbusEntity or null on error
*/
Modbus::ModbusEntity *Modbus::createEntity(const rapidjson::Value& item)
{
int rCount = 0;
int slaveID = getDefaultSlave();
float scale = 1.0;
float offset = 0.0;
string name = "";
string assetName = "";
ModbusEntity *rval = NULL;
Logger *log = Logger::getLogger();
int errorCount = 0;
if (item.HasMember("slave"))
{
if (! item["slave"].IsInt())
{
log->error("The value of slave in the modbus map should be an integer");
errorCount++;
}
else
{
slaveID = item["slave"].GetInt();
}
}
if (item.HasMember("name"))
{
if (item["name"].IsString())
{
name = item["name"].GetString();
}
else
{
log->error("The value of name in the modbus map should be a string");
errorCount++;
}
}
else
{
log->error("Each item in the modbus map must have a name property");
errorCount++;
return rval;
}
if (item.HasMember("assetName"))
{
if (item["assetName"].IsString())
{
assetName = item["assetName"].GetString();
}
else
{
log->error("The value of assetName in the %s modbus map should be a string", name.c_str());
errorCount++;
}
}
if (item.HasMember("scale"))
{
if (! item["scale"].IsNumber())
{
log->error("The value of scale in the %s modbus map should be a floating point number", name.c_str());
errorCount++;
}
else
{
scale = item["scale"].GetFloat();
}
}
if (item.HasMember("offset"))
{
if (! item["offset"].IsNumber())
{
log->error("The value of offset in the %s modbus map should be a floating point number", name.c_str());
errorCount++;
}
else
{
offset = item["offset"].GetFloat();
}
}
if (item.HasMember("coil"))
{
rCount++;
if (! item["coil"].IsNumber())
{
log->error("The value of coil in the %s modbus map should be a number", name.c_str());
errorCount++;
}
else
{
int coil = item["coil"].GetInt();
rval = new ModbusCoil(slaveID, createRegisterMap(assetName, name, coil, scale, offset));
}
}
if (item.HasMember("input"))
{
rCount++;
if (item["input"].IsInt())
{
int input = item["input"].GetInt();
rval = new ModbusInputBits(slaveID, createRegisterMap(assetName, name, input, scale, offset));
}
else
{
log->error("The input item in the %s modbus map must be either an integer", name.c_str());
errorCount++;
}
}
if (item.HasMember("register"))
{
rCount++;
if (item["register"].IsInt())
{
int regNo = item["register"].GetInt();
rval = new ModbusRegister(slaveID, createRegisterMap(assetName, name, regNo, scale, offset));
}
else if (item["register"].IsArray())
{
vector<unsigned int> words;
for (rapidjson::Value::ConstValueIterator item2 = item["register"].Begin();
item2 != item["register"].End(); ++item2)
{
if (item2->IsInt())
{
words.push_back(item2->GetInt());
}
else
{
log->error("The modbus map %s register array must contain integer values", name.c_str());
errorCount++;
}
}
rval = new ModbusRegister(slaveID, createRegisterMap(assetName, name, words, scale, offset));
}
else
{
log->error("The input item in the %s modbus map must be either an integer or an array", name.c_str());
errorCount++;
}
}
if (item.HasMember("inputRegister"))
{
rCount++;
if (item["inputRegister"].IsInt())
{
int regNo = item["inputRegister"].GetInt();
rval = new ModbusInputRegister(slaveID, createRegisterMap(assetName, name, regNo, scale, offset));
}
else if (item["inputRegister"].IsArray())
{
vector<unsigned int> words;
for (rapidjson::Value::ConstValueIterator item2 = item["inputRegister"].Begin();
item2 != item["inputRegister"].End(); ++item2)
{
if (item2->IsInt())
{
words.push_back(item2->GetInt());
}
else
{
log->error("The %s modbus map input register array must contain integer values", name.c_str());
errorCount++;
}
}
rval = new ModbusInputRegister(slaveID, createRegisterMap(assetName, name, words, scale, offset));
}
else
{
log->error("The input item in the %s modbus map must be either an integer or an array", name.c_str());
errorCount++;
}
}
// Now deal with flags for the item we have just added
if (item.HasMember("type"))
{
if (item["type"].IsString())
{
string type = item["type"].GetString();
if (type.compare("float") == 0)
{
m_lastItem->setFlag(ITEM_TYPE_FLOAT);
}
}
else
{
log->error("The type property of %s must be a string", name.c_str());
}
}
if (item.HasMember("swap"))
{
if (item["swap"].IsString())
{
string swap = item["swap"].GetString();
if (swap.compare("bytes") == 0)
{
m_lastItem->setFlag(ITEM_SWAP_BYTES);
}
else if (swap.compare("words") == 0)
{
m_lastItem->setFlag(ITEM_SWAP_WORDS);
}
else if (swap.compare("both") == 0)
{
m_lastItem->setFlag(ITEM_SWAP_BYTES|ITEM_SWAP_WORDS);
}
else
{
log->error("The swap property of %s must be one of bytes, words or both", name.c_str());
}
}
else
{
log->error("The swap property of %s must be a string", name.c_str());
}
}
if (rCount == 0)
{
log->error("%s in map must have one of coil, input, register or inputRegister properties", name.c_str());
errorCount++;
}
else if (rCount > 1)
{
log->error("%s in map must only have one of coil, input, register or inputRegister properties", name.c_str());
errorCount++;
}
return rval;
}
/**
* Set the slave ID of the modbus node we are interacting with
*
* @param slave The modbus slave ID
*/
void Modbus::setSlave(int slave)
{
modbus_set_slave(m_modbus, slave);
}
/**
* Create a modbus register map entry for a single of register
*
* @param value The datapoint names for this value
* @param registerNo The register number
*/
Modbus::RegisterMap *
Modbus::createRegisterMap(const string& value, const unsigned int registerNo)
{
m_lastItem = new Modbus::RegisterMap(value, registerNo, 1.0, 0.0);
return m_lastItem;
}
/**
* Create a modbus register map entry for a single of register
*
* @param value The datapoint names for this value
* @param registerNo The register number
* @param scale A scale factor to apply to this value
* @param offset An offset to add to this value
*/
Modbus::RegisterMap *
Modbus::createRegisterMap(const string& value, const unsigned int registerNo, double scale, double offset)
{
m_lastItem = new Modbus::RegisterMap(value, registerNo, scale, offset);
return m_lastItem;
}
/**
* Create a modbus register map entry for a single of register
*
* @param assetName The asset name to assign this entry
* @param value The datapoint names for this value
* @param registerNo The register number
* @param scale A scale factor to apply to this value
* @param offset An offset to add to this value
*/
Modbus::RegisterMap *
Modbus::createRegisterMap(const string& assetName, const string& value, const unsigned int registerNo, double scale, double offset)
{
m_lastItem = new Modbus::RegisterMap(assetName, value, registerNo, scale, offset);
return m_lastItem;
}
/**
* Create a modbus register map entry for a set of registers
*
* @param assetName The asset name to assign this entry
* @param value The datapoint names for this value
* @param registers The set of registers to combine for this value
* @param scale A scale factor to apply to this value
* @param offset An offset to add to this value
*/
Modbus::RegisterMap *
Modbus::createRegisterMap(const string& assetName, const string& value, const std::vector<unsigned int> registers, double scale, double offset)
{
m_lastItem = new Modbus::RegisterMap(assetName, value, registers, scale, offset);
return m_lastItem;
}
/**
* Add a entity to the modbus map
*
* @param entity The modbus register/coil entity and the data associated with it
*/
void
Modbus::addToMap(ModbusEntity *entity)
{
addToMap(m_defaultSlave, entity);
}
/**
* Add a entity to the modbus map
*
* @param slave The modbus slave ID
* @param entity The modbus register/coil entity and the data associated with it
*/
void
Modbus::addToMap(int slave, ModbusEntity *entity)
{
ModbusCacheManager *manager = ModbusCacheManager::getModbusCacheManager();
RegisterMap *map = entity->getMap();
if (map->m_isVector)
{
for (int i = 0; i < map->m_registers.size(); i++)
{
manager->registerItem(slave, entity->getSource(), map->m_registers[i]);
}
}
else
{
manager->registerItem(slave, entity->getSource(), map->m_registerNo);
}
if (m_map.find(slave) != m_map.end())
{
m_map[slave].push_back(entity);
}
else
{
vector<Modbus::ModbusEntity *> empty;
m_map.insert(pair<int, vector<Modbus::ModbusEntity *> >(slave, empty));
m_map[slave].push_back(entity);
}
if (m_control == UseRegisterMap)
{
string name = map->m_name;
m_writeMap.insert(pair<string, Modbus::ModbusEntity *>(name, entity));
}
}
/**
* Clear down the modbus map and remove all of the objects related to the map
*/
void
Modbus::removeMap()
{
for (auto it = m_map.begin(); it != m_map.end(); it++)
{
for (int i = 0; i < it->second.size(); i++)
{
delete it->second[i];
}
it->second.clear();