UniSet 2.32.1
MBConfig.h
1/*
2 * Copyright (c) 2020 Pavel Vainerman.
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU Lesser General Public License as
6 * published by the Free Software Foundation, version 2.1.
7 *
8 * This program is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Lesser Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16// -----------------------------------------------------------------------------
17#ifndef _MBConfig_H_
18#define _MBConfig_H_
19// -----------------------------------------------------------------------------
20#include <ostream>
21#include <string>
22#include <map>
23#include <unordered_map>
24#include <memory>
25#include "IONotifyController.h"
26#include "Calibration.h"
27#include "DelayTimer.h"
28#include "SMInterface.h"
29#include "SharedMemory.h"
30#include "IOBase.h"
31#include "VTypes.h"
32#include "MTR.h"
33#include "RTUStorage.h"
34#include "modbus/ModbusClient.h"
35#include "Configuration.h"
36// -------------------------------------------------------------------------
37namespace uniset
38{
39 // -----------------------------------------------------------------------------
42 {
43 public:
44 MBConfig(const std::shared_ptr<uniset::Configuration>& conf
45 , xmlNode* cnode
46 , std::shared_ptr<SMInterface> _shm );
47
48 ~MBConfig();
49
59 friend std::ostream& operator<<( std::ostream& os, const ExchangeMode& em );
60
68
69
70 friend std::string to_string( const SafeMode& m );
71 friend std::ostream& operator<<( std::ostream& os, const SafeMode& m );
72
80
81 static DeviceType getDeviceType( const std::string& dtype ) noexcept;
82 friend std::ostream& operator<<( std::ostream& os, const DeviceType& dt );
83
84 struct RTUDevice;
85 struct RegInfo;
86
87 struct RSProperty:
88 public IOBase
89 {
90 int8_t nbit = { -1 };
91 VTypes::VType vType = { VTypes::vtUnknown };
92 uint16_t rnum = { 1 };
93 uint8_t nbyte = { 0 };
94 uint16_t mask = { 0 };
95 uint8_t offset = { 0 };
97 RSProperty() {}
98
99 // т.к. IOBase содержит rwmutex с запрещённым конструктором копирования
100 // приходится здесь тоже объявлять разрешенными только операции "перемещения"
101 RSProperty( const RSProperty& r ) = delete;
102 RSProperty& operator=(const RSProperty& r) = delete;
103 RSProperty( RSProperty&& r ) = default;
104 RSProperty& operator=(RSProperty&& r) = default;
105
106 std::shared_ptr<RegInfo> reg;
107 };
108
109 friend std::ostream& operator<<( std::ostream& os, const RSProperty& p );
110
111 typedef std::list<RSProperty> PList;
112
113 typedef std::map<ModbusRTU::RegID, std::shared_ptr<RegInfo>> RegMap;
114 struct RegInfo
115 {
116 // т.к. RSProperty содержит rwmutex с запрещённым конструктором копирования
117 // приходится здесь тоже объявлять разрешенными только операции "перемещения"
118 RegInfo( const RegInfo& r ) = delete;
119 RegInfo& operator=(const RegInfo& r) = delete;
120 RegInfo( RegInfo&& r ) = default;
121 RegInfo& operator=(RegInfo&& r) = default;
122 RegInfo() = default;
123
124 ModbusRTU::ModbusData mbval = { 0 };
125 inline bool setMBVal(ModbusRTU::ModbusData nv)
126 {
127 if( mbval != nv )
128 mbval_changed = true;
129
130 mbval = nv;
131 return mbval_changed;
132 }
133 ModbusRTU::ModbusData mbreg = { 0 };
134 ModbusRTU::SlaveFunctionCode mbfunc = { ModbusRTU::fnUnknown };
135 PList slst;
136 ModbusRTU::RegID regID = { 0 };
137
138 std::shared_ptr<RTUDevice> dev;
139
140 // only for RTU188
141 RTUStorage::RTUJack rtuJack = { RTUStorage::nUnknown };
142 int rtuChan = { 0 };
143
144 // only for MTR
145 MTR::MTRType mtrType = { MTR::mtUnknown };
147 // optimization
148 size_t q_num = { 0 };
149 size_t q_count = { 1 };
151 RegMap::iterator rit;
152
153 // начальная инициализация для "записываемых" регистров
154 // Механизм:
155 // Если tcp_preinit="1", то сперва будет сделано чтение значения из устройства.
156 // при этом флаг mb_init=false пока не пройдёт успешной инициализации
157 // Если tcp_preinit="0", то флаг mb_init сразу выставляется в true.
158 bool mb_initOK = { false };
160 // Флаг sm_init означает, что писать в устройство нельзя, т.к. значение в "карте регистров"
161 // ещё не инициализировано из SM
162 bool sm_initOK = { false };
164 // Флаг mbval_changed == true означает, что значение датчика для регистра на запись изменилось и нужно
165 // записать его в устройство.
166 // При старте по-умолчанию первый запрос отправляется, если для конкретного датчика не выставлен
167 // тег "init_mbval_changed=0".
168 // Также можно указать "init_mbval_changed=0" в глобальной секции для процесса обмена или параметром
169 // "--prefix-init-mbval-changed 0" командной строки. Тогда все регистры будут инициализировать mbval_changed
170 // этим значением, если не указать тег для датчика.
171 bool mbval_changed = { true };
172 };
173
174 friend std::ostream& operator<<( std::ostream& os, const RegInfo& r );
175 friend std::ostream& operator<<( std::ostream& os, const RegInfo* r );
176
178 {
179 ModbusRTU::ModbusAddr mbaddr = { 0 };
180 std::unordered_map<size_t, std::shared_ptr<RegMap>> pollmap;
181
184 // resp - respond..(контроль наличия связи)
186 IOController::IOStateList::iterator resp_it;
187 DelayTimer resp_Delay; // таймер для формирования задержки на отпускание (пропадание связи)
188 PassiveTimer resp_ptInit; // таймер для формирования задержки на инициализацию связи (задержка на выставление датчика связи после запуска)
189 bool resp_state = { false };
190 bool resp_invert = { false };
191 bool resp_force = { false };
192 Trigger trInitOK; // триггер для "инициализации"
193 std::atomic<size_t> numreply = { 0 }; // количество успешных запросов..
194 std::atomic<size_t> prev_numreply = { 0 };
195
196 //
197 bool ask_every_reg = { false };
199 // режим работы
201 IOController::IOStateList::iterator mode_it;
202 long mode = { emNone }; // режим работы с устройством (см. ExchangeMode)
203
204 // safe mode
205 long safeMode = { safeNone };
207 IOController::IOStateList::iterator safemode_it;
208 long safemode_value = { 1 };
209
210 // return TRUE if state changed
211 bool checkRespond( std::shared_ptr<DebugStream>& log );
212
213 // специфические поля для RS
214 ComPort::Speed speed = { ComPort::ComSpeed38400 };
215 std::shared_ptr<RTUStorage> rtu188;
216 ComPort::Parity parity = { ComPort::NoParity };
217 ComPort::CharacterSize csize = { ComPort::CSize8 };
218 ComPort::StopBits stopBits = { ComPort::OneBit };
219
220 std::string getShortInfo() const;
221 };
222
223 friend std::ostream& operator<<( std::ostream& os, RTUDevice& d );
224
225 typedef std::unordered_map<ModbusRTU::ModbusAddr, std::shared_ptr<RTUDevice>> RTUDeviceMap;
226
227 friend std::ostream& operator<<( std::ostream& os, RTUDeviceMap& d );
228 static void printMap(RTUDeviceMap& d);
229
230 typedef std::list<IOBase> ThresholdList;
231
233 {
234 InitRegInfo():
235 dev(0), mbreg(0),
236 mbfunc(ModbusRTU::fnUnknown),
237 initOK(false)
238 {}
239 RSProperty p;
240 std::shared_ptr<RTUDevice> dev;
241 ModbusRTU::ModbusData mbreg;
242 ModbusRTU::SlaveFunctionCode mbfunc;
243 bool initOK;
244 std::shared_ptr<RegInfo> ri;
245 };
246 typedef std::list<InitRegInfo> InitList;
247
248 static void rtuQueryOptimization( RTUDeviceMap& m, size_t maxQueryCount );
249 static void rtuQueryOptimizationForDevice( const std::shared_ptr<RTUDevice>& d, size_t maxQueryCount );
250 static void rtuQueryOptimizationForRegMap( const std::shared_ptr<RegMap>& regmap, size_t maxQueryCount );
251
252 // т.к. пороговые датчики не связаны напрямую с обменом, создаём для них отдельный список
253 // и отдельно его проверяем потом
254 ThresholdList thrlist;
255 RTUDeviceMap devices;
256 InitList initRegList;
258 void loadConfig( const std::shared_ptr<uniset::UniXML>& xml, UniXML::iterator sensorsSection );
259 void initDeviceList( const std::shared_ptr<UniXML>& xml );
260 bool initItem( UniXML::iterator& it );
261
262 std::string s_field;
263 std::string s_fvalue;
264
265 // определение timeout для соединения
266 timeout_t recv_timeout = { 500 }; // msec
267 timeout_t default_timeout = { 5000 }; // msec
268 timeout_t aftersend_pause = { 0 };
269 timeout_t polltime = { 100 };
270 timeout_t sleepPause_msec = { 10 };
271
272 size_t maxQueryCount = { ModbusRTU::MAXDATALEN };
273 xmlNode* cnode = { 0 };
274 std::shared_ptr<DebugStream> mblog;
275 std::string myname;
276 std::string prefix;
277 std::string prop_prefix;
278 std::string defaultMBtype;
279 std::string defaultMBaddr;
280 bool mbregFromID = { false };
281 bool defaultMBinitOK = { false }; // флаг определяющий нужно ли ждать "первого обмена" или при запуске сохранять в SM значение default.
282 bool noQueryOptimization = { false };
283 std::shared_ptr<uniset::Configuration> conf;
284 std::shared_ptr<SMInterface> shm;
285
286 void cloneParams( const std::shared_ptr<MBConfig>& conf );
287 std::string getShortInfo() const;
288
289 static const size_t changeOnlyWrite = { 65535 };
290 bool init_mbval_changed = { true };
292 bool checkDuplicationRegID( const ModbusRTU::RegID id, const std::shared_ptr<RTUDevice>& dev, const std::shared_ptr<RegMap>& rmap ) const;
294 protected:
295
296 bool initSMValue( ModbusRTU::ModbusData* data, int count, RSProperty* p );
297
298 void readConfiguration(const std::shared_ptr<uniset::UniXML>& xml, UniXML::iterator sensorsSection );
299 void initOffsetList();
300
301 std::shared_ptr<RTUDevice> addDev( RTUDeviceMap& dmap, ModbusRTU::ModbusAddr a, UniXML::iterator& it );
302 std::shared_ptr<RegInfo> addReg(std::shared_ptr<RegMap>& devices, ModbusRTU::RegID id, ModbusRTU::ModbusData r, UniXML::iterator& it, std::shared_ptr<RTUDevice> dev );
303 RSProperty* addProp( PList& plist, RSProperty&& p );
304
305 bool initMTRitem(UniXML::iterator& it, std::shared_ptr<RegInfo>& p );
306 bool initRTU188item(UniXML::iterator& it, std::shared_ptr<RegInfo>& p );
307 bool initRSProperty( RSProperty& p, UniXML::iterator& it );
308 bool initRegInfo(std::shared_ptr<RegInfo>& r, UniXML::iterator& it, std::shared_ptr<RTUDevice>& dev );
309 bool initRTUDevice( std::shared_ptr<RTUDevice>& d, UniXML::iterator& it );
310 bool initDeviceInfo( RTUDeviceMap& m, ModbusRTU::ModbusAddr a, UniXML::iterator& it );
311 };
312 // --------------------------------------------------------------------------
313} // end of namespace uniset
314// -----------------------------------------------------------------------------
315namespace std
316{
317 std::string to_string( const uniset::MBConfig::PList& p );
318}
319#endif // _MBConfig_H_
320// -----------------------------------------------------------------------------
Definition DelayTimer.h:30
Definition MBConfig.h:42
bool initItem(UniXML::iterator &it)
Definition MBConfig.cc:603
std::string prop_prefix
Definition MBConfig.h:277
bool checkDuplicationRegID(const ModbusRTU::RegID id, const std::shared_ptr< RTUDevice > &dev, const std::shared_ptr< RegMap > &rmap) const
Definition MBConfig.cc:1237
SafeMode
Definition MBConfig.h:63
@ safeResetIfNotRespond
Definition MBConfig.h:65
@ safeExternalControl
Definition MBConfig.h:66
@ safeNone
Definition MBConfig.h:64
static const size_t changeOnlyWrite
Definition MBConfig.h:289
DeviceType
Definition MBConfig.h:74
@ dtRTU188
Definition MBConfig.h:78
@ dtUnknown
Definition MBConfig.h:75
@ dtRTU
Definition MBConfig.h:76
@ dtMTR
Definition MBConfig.h:77
size_t maxQueryCount
Definition MBConfig.h:272
bool init_mbval_changed
Definition MBConfig.h:290
timeout_t polltime
Definition MBConfig.h:269
InitList initRegList
Definition MBConfig.h:256
ExchangeMode
Definition MBConfig.h:52
@ emNone
Definition MBConfig.h:53
@ emSkipExchange
Definition MBConfig.h:57
@ emReadOnly
Definition MBConfig.h:55
@ emSkipSaveToSM
Definition MBConfig.h:56
@ emWriteOnly
Definition MBConfig.h:54
Пассивный таймер
Definition PassiveTimer.h:94
Definition UniXML.h:44
STL namespace.
Definition Calibration.h:27
const ObjectId DefaultObjectId
Definition UniSetTypes.h:71
long ObjectId
Definition UniSetTypes_i.idl:30
Definition IOBase.h:35
Definition MBConfig.h:233
Definition MBConfig.h:89
VTypes::VType vType
Definition MBConfig.h:91
uint8_t offset
Definition MBConfig.h:95
int8_t nbit
Definition MBConfig.h:90
uint8_t nbyte
Definition MBConfig.h:93
uint16_t mask
Definition MBConfig.h:94
uint16_t rnum
Definition MBConfig.h:92
Definition MBConfig.h:178
uniset::ObjectId safemode_id
Definition MBConfig.h:206
long safeMode
Definition MBConfig.h:205
DeviceType dtype
Definition MBConfig.h:182
ModbusRTU::ModbusAddr mbaddr
Definition MBConfig.h:179
bool ask_every_reg
Definition MBConfig.h:197
Definition MBConfig.h:115
size_t q_count
Definition MBConfig.h:149
ModbusRTU::ModbusData mbreg
Definition MBConfig.h:133
ModbusRTU::SlaveFunctionCode mbfunc
Definition MBConfig.h:134
MTR::MTRType mtrType
Definition MBConfig.h:145
bool mb_initOK
Definition MBConfig.h:158
size_t q_num
Definition MBConfig.h:148
bool mbval_changed
Definition MBConfig.h:171
bool sm_initOK
Definition MBConfig.h:162