UniSet @VERSION@
IOController.h
1/*
2 * Copyright (c) 2015 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// --------------------------------------------------------------------------
21// --------------------------------------------------------------------------
22#ifndef IOController_H_
23#define IOController_H_
24//---------------------------------------------------------------------------
25#include <unordered_map>
26#include <list>
27#include <limits>
28#include <sigc++/sigc++.h>
29#include "IOController_i.hh"
30#include "UniSetTypes.h"
31#include "UniSetManager.h"
32#include "Configuration.h"
33#include "Mutex.h"
34#include "DBServer.h"
35#include "AccessMask.h"
36#include "AccessConfig.h"
37//---------------------------------------------------------------------------
38namespace uniset
39{
50 public UniSetManager,
51 public POA_IOController_i
52 {
53 public:
54
55 IOController( const std::string& name, const std::string& section );
57 virtual ~IOController();
58
59 void setDBServer( const std::shared_ptr<uniset::DBServer>& dbserver );
60
61 virtual uniset::ObjectType getType() override
62 {
63 return uniset::ObjectType("IOController");
64 }
65
66 virtual uniset::SimpleInfo* getInfo( const char* userparam = "" ) override;
67
68 // ----------------------------------------------------------------
69 // Публичный (IDL) интерфейс IOController_i
70 // ----------------------------------------------------------------
71
72 virtual CORBA::Long getValue( uniset::ObjectId sid, uniset::ObjectId sup_id ) override;
73
74 virtual void setValue( uniset::ObjectId sid, CORBA::Long value,
75 uniset::ObjectId sup_id = uniset::DefaultObjectId ) override;
76 virtual void setUndefinedState( uniset::ObjectId sid,
77 CORBA::Boolean undefined,
78 uniset::ObjectId sup_id = uniset::DefaultObjectId ) override;
79
80 virtual void freezeValue( uniset::ObjectId sid,
81 CORBA::Boolean set,
82 CORBA::Long value,
83 uniset::ObjectId sup_id = uniset::DefaultObjectId ) override;
84
85 virtual IOController_i::SensorInfoSeq* getSensorSeq( const uniset::IDSeq& lst, uniset::ObjectId sup_id ) override;
86 virtual uniset::IDSeq* setOutputSeq( const IOController_i::OutSeq& lst, uniset::ObjectId sup_id ) override;
87
88 // ----------------------------------------------------------------
89 virtual UniversalIO::IOType getIOType( uniset::ObjectId sid ) override;
90
91 virtual IOController_i::SensorInfoSeq* getSensorsMap( uniset::ObjectId sup_id ) override;
92 virtual IOController_i::SensorIOInfo getSensorIOInfo( uniset::ObjectId sid, uniset::ObjectId sup_id ) override;
93
94 virtual CORBA::Long getRawValue( uniset::ObjectId sid, uniset::ObjectId sup_id ) override;
95 virtual void calibrate( uniset::ObjectId sid,
97 uniset::ObjectId adminId ) override;
98
99 IOController_i::CalibrateInfo getCalibrateInfo( const uniset::ObjectId sid, const uniset::ObjectId consumer_id ) override;
100
101 inline IOController_i::SensorInfo SensorInfo( const uniset::ObjectId sid,
102 const uniset::ObjectId node = uniset::uniset_conf()->getLocalNode())
103 {
105 si.id = sid;
106 si.node = node;
107 return si;
108 };
109
110 uniset::Message::Priority getPriority( const uniset::ObjectId id, const uniset::ObjectId consumer_id );
111
112 virtual IOController_i::ShortIOInfo getTimeChange( const uniset::ObjectId id, const uniset::ObjectId consumer_id ) override;
113
114 virtual IOController_i::ShortMapSeq* getSensors( const uniset::ObjectId consumer_id ) override;
115
116#ifndef DISABLE_REST_API
117 // HTTP API (IHttpRequest)
118 virtual Poco::JSON::Object::Ptr httpHelp( const Poco::URI::QueryParameters& p ) override;
119 virtual Poco::JSON::Object::Ptr httpRequest( const UHttp::HttpRequestContext& ctx ) override;
120#endif
121
122 public:
123
124 // предварительное объявление..
125 struct USensorInfo;
126 typedef std::unordered_map<uniset::ObjectId, std::shared_ptr<USensorInfo>> IOStateList;
127
128 static const long not_specified_value = { std::numeric_limits<long>::max() };
129
130 // ================== Доступные сигналы =================
136 typedef sigc::signal<void, std::shared_ptr<USensorInfo>&, IOController*> ChangeSignal;
137 typedef sigc::signal<void, std::shared_ptr<USensorInfo>&, IOController*> ChangeUndefinedStateSignal;
138
139 // signal по изменению определённого датчика
140 ChangeSignal signal_change_value( uniset::ObjectId sid );
141
142 // signal по изменению любого датчика
143 ChangeSignal signal_change_value();
144
145 // сигналы по изменению флага "неопределённое состояние" (обрыв датчика например)
146 ChangeUndefinedStateSignal signal_change_undefined_state( uniset::ObjectId sid );
147 ChangeUndefinedStateSignal signal_change_undefined_state();
148 // -----------------------------------------------------------------------------------------
149 // полнейшее нарушение инкапсуляции
150 // но пока, это попытка оптимизировать работу с IOController через указатель.
151 // Т.е. работая с датчиками через итераторы..
152#if 1
153 inline IOStateList::iterator ioBegin()
154 {
155 return ioList.begin();
156 }
157 inline IOStateList::iterator ioEnd()
158 {
159 return ioList.end();
160 }
161 inline IOStateList::iterator find( uniset::ObjectId k )
162 {
163 return ioList.find(k);
164 }
165#endif
166 inline int ioCount() const noexcept
167 {
168 return ioList.size();
169 }
170
171 protected:
172
173 // доступ к элементам через итератор
174 // return итоговое значение
175 virtual long localSetValueIt( IOStateList::iterator& it, const uniset::ObjectId sid,
176 CORBA::Long value, uniset::ObjectId sup_id );
177
178 virtual long localGetValue( IOStateList::iterator& it, const uniset::ObjectId sid, uniset::ObjectId sup_id );
179
184 virtual void localSetUndefinedState( IOStateList::iterator& it, bool undefined,
185 const uniset::ObjectId sid );
186
187 virtual void localFreezeValueIt( IOController::IOStateList::iterator& li,
189 CORBA::Boolean set,
190 CORBA::Long value,
191 uniset::ObjectId sup_id );
192
193 virtual void localFreezeValue( std::shared_ptr<USensorInfo>& usi,
194 CORBA::Boolean set,
195 CORBA::Long value,
196 uniset::ObjectId sup_id );
197
198
199 // -- работа через указатель ---
200 virtual long localSetValue( std::shared_ptr<USensorInfo>& usi, CORBA::Long value, uniset::ObjectId sup_id );
201 long localGetValue( std::shared_ptr<USensorInfo>& usi, const uniset::ObjectId consumer_id ) ;
202
203#ifndef DISABLE_REST_API
204 // http API
205 virtual Poco::JSON::Object::Ptr request_get( const std::string& req, const Poco::URI::QueryParameters& p );
206 virtual Poco::JSON::Object::Ptr request_set( const std::string& req, const Poco::URI::QueryParameters& p );
207 virtual Poco::JSON::Object::Ptr request_freeze( const std::string& req, const Poco::URI::QueryParameters& p, bool set );
208 virtual Poco::JSON::Object::Ptr request_sensors( const std::string& req, const Poco::URI::QueryParameters& p );
209 void getSensorInfo( Poco::JSON::Array::Ptr& jdata, std::shared_ptr<USensorInfo>& s, uniset::ObjectId consumer_id, bool shortInfo = false );
210 bool disabledHttpSetApi = { false };
211 bool disabledHttpFreezeApi = { false };
212 bool disableHttpAccessControl = { false };
213#endif
214
215 // переопределяем для добавления вызова регистрации датчиков
216 virtual bool deactivateObject() override;
217 virtual bool activateObject() override;
218
220 virtual void activateInit();
221
223 virtual void sensorsRegistration() {};
225 virtual void sensorsUnregistration();
226
227 typedef sigc::signal<void, std::shared_ptr<USensorInfo>&, IOController*> InitSignal;
228
229 // signal по изменению определённого датчика
230 InitSignal signal_init();
231
233 void ioRegistration(std::shared_ptr<USensorInfo>& usi );
234
236 void ioUnRegistration( const uniset::ObjectId sid );
237
239 void reloadACLConfig( uniset::ACLMap& amap, uniset::ACLInfoMap& iomap );
240
241 // ------------------------------
243 SensorIOInfo(long v, UniversalIO::IOType t, const IOController_i::SensorInfo& si,
244 uniset::Message::Priority p = uniset::Message::Medium,
245 long defval = 0, IOController_i::CalibrateInfo* ci = 0,
248 {
250 ai.si = si;
251 ai.type = t;
252 ai.value = v;
253 ai.priority = p;
254 ai.default_val = defval;
255 ai.real_value = v;
256 ai.blocked = false;
257 ai.supplier = sup_id;
258 ai.depend_sid = depend_sid;
259
260 if( ci != 0 )
261 ai.ci = *ci;
262 else
263 {
264 ai.ci.minRaw = 0;
265 ai.ci.maxRaw = 0;
266 ai.ci.minCal = 0;
267 ai.ci.maxCal = 0;
268 ai.ci.precision = 0;
269 }
270
271 return ai;
272 };
273
275 virtual void logging( uniset::SensorMessage& sm );
276
278 virtual void dumpToDB();
279
280 IOController();
281
282 // доступ к списку c изменением только для своих
283 IOStateList::iterator myioBegin();
284 IOStateList::iterator myioEnd();
285 IOStateList::iterator myiofind( uniset::ObjectId id );
286
287 void initIOList( const IOStateList&& l );
288
289 typedef std::function<void(std::shared_ptr<USensorInfo>&)> UFunction;
290 // функция работает с mutex
291 void for_iolist( UFunction f );
292
293 void setDefaultAccessMask( uniset::AccessMask m );
294
295 private:
296 friend class NCRestorer;
297 friend class SMInterface;
298
299 std::mutex siganyMutex;
300 ChangeSignal sigAnyChange;
301
302 std::mutex siganyundefMutex;
303 ChangeSignal sigAnyUndefChange;
304 InitSignal sigInit;
305
306 IOStateList ioList;
307 uniset::uniset_rwmutex ioMutex;
309 bool isPingDBServer; // флаг связи с DBServer-ом
311 std::shared_ptr<uniset::DBServer> dbserver = { nullptr };
312
313 std::mutex loggingMutex;
315 uniset::AccessMask defaultAccessMask = { uniset::AccessRW };
316
317 public:
318
319 struct UThresholdInfo;
320 typedef std::list<std::shared_ptr<UThresholdInfo>> ThresholdExtList;
321
324 {
325 USensorInfo( const USensorInfo& ) = delete;
326 const USensorInfo& operator=(const USensorInfo& ) = delete;
327 USensorInfo( USensorInfo&& ) = default;
328 USensorInfo& operator=(USensorInfo&& ) = default;
329
330 USensorInfo();
331 virtual ~USensorInfo() {}
332
336
338 const USensorInfo& operator=(const IOController_i::SensorIOInfo& r);
340
341 // Дополнительные (вспомогательные поля)
344 // userdata (универсальный, но небезопасный способ расширения информации связанной с датчиком)
345 static const size_t MaxUserData = 4;
346 void* userdata[MaxUserData] = { nullptr, nullptr, nullptr, nullptr };
349 void* getUserData( size_t index );
350 void setUserData( size_t index, void* data );
351
352 // сигнал для реализации механизма зависимостей..
353 // (все зависимые датчики подключаются к нему (см. NCRestorer::init_depends_signals)
354 uniset::uniset_rwmutex changeMutex;
355 ChangeSignal sigChange;
356
357 uniset::uniset_rwmutex undefMutex;
358 ChangeUndefinedStateSignal sigUndefChange;
359
360 long d_value = { 1 };
361 long d_off_value = { 0 };
362 std::shared_ptr<USensorInfo> d_usi; // shared_ptr на датчик от которого зависит этот.
363
364 // список пороговых датчиков для данного
366 ThresholdExtList thresholds;
367
368 size_t nchanges = { 0 }; // количество изменений датчика
369
370 long undef_value = { not_specified_value }; // значение для "неопределённого состояния датчика"
371 long frozen_value = { 0 };
372
373 bool readonly = { false }; // readonly датчик (deprecated, use permissions)
374
375 std::string aclName = { "" };
376 uniset::ACLPtr acl = { nullptr };
377 uniset::AccessMask checkMask(uniset::ObjectId, const AccessMask& defaultMask) const;
378
379 // функция обработки информации об изменении состояния датчика, от которого зависит данный
380 void checkDepend( std::shared_ptr<USensorInfo>& d_usi, IOController* );
381
382 void init( const IOController_i::SensorIOInfo& s );
383
384 inline IOController_i::SensorIOInfo makeSensorIOInfo()
385 {
388 return s;
389 }
390
391 inline uniset::SensorMessage makeSensorMessage( bool with_lock = false )
392 {
394 sm.id = si.id;
395 sm.node = si.node; // uniset_conf()->getLocalNode()?
396 sm.sensor_type = type;
397 sm.priority = (uniset::Message::Priority)priority;
398
399 // лочим только изменяемые поля
400 if( with_lock )
401 {
403 sm.value = value;
404 sm.sm_tv.tv_sec = tv_sec;
405 sm.sm_tv.tv_nsec = tv_nsec;
406 sm.ci = ci;
407 sm.supplier = supplier;
408 sm.undefined = undefined;
409 }
410 else
411 {
412 sm.value = value;
413 sm.sm_tv.tv_sec = tv_sec;
414 sm.sm_tv.tv_nsec = tv_nsec;
415 sm.ci = ci;
416 sm.supplier = supplier;
417 sm.undefined = undefined;
418 }
419
420 return sm;
421 }
422 };
423
427 {
428 UThresholdInfo( uniset::ThresholdId tid, CORBA::Long low, CORBA::Long hi, bool inv,
430 sid(_sid),
431 invert(inv)
432 {
433 id = tid;
434 hilimit = hi;
435 lowlimit = low;
437 }
438
441
443 IOController::IOStateList::iterator sit;
444
446 bool invert;
447
448 inline bool operator== ( const ThresholdInfo& r ) const
449 {
450 return ((id == r.id) &&
451 (hilimit == r.hilimit) &&
452 (lowlimit == r.lowlimit) &&
453 (invert == r.invert) );
454 }
455
456 UThresholdInfo( const UThresholdInfo& ) = delete;
457 UThresholdInfo& operator=( const UThresholdInfo& ) = delete;
458 UThresholdInfo( UThresholdInfo&& ) = default;
459 UThresholdInfo& operator=(UThresholdInfo&& ) = default;
460 };
461 };
462 // -------------------------------------------------------------------------
463} // end of uniset namespace
464// --------------------------------------------------------------------------
465#endif
466// --------------------------------------------------------------------------
Definition AccessMask.h:29
Definition IOController.h:52
virtual void dumpToDB()
сохранение состояния всех датчиков в БД
Definition IOController.cc:598
virtual void sensorsUnregistration()
Definition IOController.cc:87
bool disabledHttpFreezeApi
Definition IOController.h:211
bool disabledHttpSetApi
Definition IOController.h:210
virtual void activateInit()
Definition IOController.cc:108
virtual bool deactivateObject() override
Definition IOController.cc:81
virtual void sensorsRegistration()
Definition IOController.h:223
virtual bool activateObject() override
Definition IOController.cc:70
void ioUnRegistration(const uniset::ObjectId sid)
Definition IOController.cc:552
virtual void localSetUndefinedState(IOStateList::iterator &it, bool undefined, const uniset::ObjectId sid)
Definition IOController.cc:201
bool disableHttpAccessControl
Definition IOController.h:212
void reloadACLConfig(uniset::ACLMap &amap, uniset::ACLInfoMap &iomap)
Definition IOController.cc:1049
void ioRegistration(std::shared_ptr< USensorInfo > &usi)
Definition IOController.cc:514
sigc::signal< void, std::shared_ptr< USensorInfo > &, IOController * > ChangeSignal
Definition IOController.h:136
virtual void logging(uniset::SensorMessage &sm)
сохранение информации об изменении состояния датчика
Definition IOController.cc:562
Definition MessageType.h:127
Definition UniSetManager.h:60
Definition Mutex.h:85
Definition Mutex.h:32
@ NormalThreshold
Definition IOController_i.idl:211
Definition AccessConfig.h:30
string< SizeOfObjectType > ObjectType
Definition UniSetTypes_i.idl:33
long ThresholdId
Definition UniSetTypes_i.idl:31
sequence< ObjectId > IDSeq
Definition UniSetTypes_i.idl:89
const ObjectId DefaultObjectId
Definition UniSetTypes.h:71
std::shared_ptr< Configuration > uniset_conf() noexcept
Definition Configuration.cc:106
long ObjectId
Definition UniSetTypes_i.idl:30
Definition IOController_i.idl:89
Definition IOController_i.idl:103
uniset::ObjectId supplier
Definition IOController_i.idl:116
unsigned long tv_sec
Definition IOController_i.idl:114
boolean undefined
Definition IOController_i.idl:105
CalibrateInfo ci
Definition IOController_i.idl:113
UniversalIO::IOType type
Definition IOController_i.idl:109
long priority
Definition IOController_i.idl:110
unsigned long tv_nsec
Definition IOController_i.idl:115
long value
Definition IOController_i.idl:104
Definition IOController_i.idl:64
uniset::ObjectId node
Definition IOController_i.idl:66
uniset::ObjectId id
Definition IOController_i.idl:65
Definition IOController_i.idl:150
Definition IOController_i.idl:216
long lowlimit
Definition IOController_i.idl:219
long hilimit
Definition IOController_i.idl:218
Definition IOController.h:324
void * userdata[MaxUserData]
Definition IOController.h:346
uniset::uniset_rwmutex userdata_lock
Definition IOController.h:347
long d_off_value
Definition IOController.h:361
long d_value
Definition IOController.h:360
uniset::uniset_rwmutex val_lock
Definition IOController.h:342
Definition IOController.h:427
IOController::IOStateList::iterator sit
Definition IOController.h:443
uniset::ObjectId sid
Definition IOController.h:440
bool invert
Definition IOController.h:446
Definition UniSetTypes_i.idl:65
Definition UHttpRequestHandler.h:87