File: devapi.h

package info (click to toggle)
tango 9.2.5a%2Bdfsg1-2
  • links: PTS, VCS
  • area: main
  • in suites: buster, stretch
  • size: 21,624 kB
  • ctags: 11,597
  • sloc: cpp: 135,480; sh: 21,772; makefile: 1,103; ansic: 1,083; java: 215; python: 55
file content (1008 lines) | stat: -rw-r--r-- 28,657 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
//=====================================================================================================================
//
// devapi.h - include file for TANGO device api
//
//
// Copyright (C) :      2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015
//						European Synchrotron Radiation Facility
//                      BP 220, Grenoble 38043
//                      FRANCE
//
// This file is part of Tango.
//
// Tango is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Tango is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License along with Tango.
// If not, see <http://www.gnu.org/licenses/>.
//
// $Revision: 28018 $
//
//====================================================================================================================

#ifndef _DEVAPI_H
#define _DEVAPI_H

#include <tango.h>
#include <tango_const.h>
#include <apiexcept.h>
#include <cbthread.h>
#include <lockthread.h>
#include <readers_writers_lock.h>

#include <bitset>

using namespace std;

namespace Tango
{

/** @defgroup Client Client classes */

//
// forward declarations
//

class DeviceData;
class DeviceAttribute;
class DbDevice;
class DbAttribute;
class DbDatum;
class DbDevImportInfo;
class Database;
class AsynReq;
class NotifdEventConsumer;
class ZmqEventConsumer;
class CallBack;
class AttributeProxy;
class TangoMonitor;

//
// Some typedef
//

typedef vector<DbDatum> DbData;

typedef union
{
	TangoSys_Pid	LockerPid;
	unsigned long	UUID[4];
}LockerId;

struct LockerInfo
{
	LockerLanguage	ll;
	LockerId		li;
	string			locker_host;
	string			locker_class;
};

struct LockingThread
{
	TangoMonitor	*mon;
	LockThCmd		*shared;
	LockThread		*l_thread;
};

/**
 * Base structure for command information
 *
 * @headerfile tango.h
 */
#ifdef GEN_DOC
typedef struct DevCommandInfo
#else
typedef struct _DevCommandInfo
#endif
{
	string 		cmd_name;           ///< The command name
	long 		cmd_tag;            ///< The command tag
	long 		in_type;            ///< Input parameter data type
	long 		out_type;           ///< Output parameter data type
	string 		in_type_desc;       ///< Input parameter description
	string 		out_type_desc;      ///< Ouptput parameter description

///@privatesection
	bool operator==(const _DevCommandInfo &);
}DevCommandInfo;


struct AttributeDimension
{
	long dim_x;
	long dim_y;
};

/**
 * Command information data extension
 *
 * @headerfile tango.h
 * @ingroup Client
 */
#ifdef GEN_DOC
typedef struct CommandInfo : public DevCommandInfo
#else
typedef struct _CommandInfo : public DevCommandInfo
#endif
{
	Tango::DispLevel disp_level;    ///< The command display level

/// @privatesection
	friend ostream &operator<<(ostream &,_CommandInfo &);
	bool operator==(const _CommandInfo &);
}CommandInfo;

/**
 * A vector of CommandInfo structure
 *
 * @headerfile tango.h
 * @ingroup Client
 */
typedef vector<CommandInfo> CommandInfoList;

struct _DeviceInfo
{
	string 	dev_class;
	string 	server_id;
	string 	server_host;
	long 	server_version;
	string 	doc_url;
	string 	dev_type;
};

typedef _DeviceInfo DeviceInfo;

/**
 * Base structure for Attribute configuration
 *
 * @headerfile tango.h
 */
#ifdef GEN_DOC
typedef struct DeviceAttributeConfig
#else
typedef struct _DeviceAttributeConfig
#endif
{
	string 			name;               ///< Name
	AttrWriteType 	writable;           ///< Writable type (Read, Write,...)
	AttrDataFormat 	data_format;        ///< Data format (Scalar, Spectrum,...)
	int 			data_type;          ///< Data type
	int 			max_dim_x;          ///< Max dim X
	int 			max_dim_y;          ///< Max dim Y
	string 			description;        ///< Description
	string 			label;              ///< Label
	string 			unit;               ///< Unit
	string 			standard_unit;      ///< Standard unit
	string 			display_unit;       ///< Display unit
	string 			format;             ///< Format
	string 			min_value;          ///< Min value
	string 			max_value;          ///< Max value
	string 			min_alarm;          ///< Min alarm
	string 			max_alarm;          ///< Max alarm
	string 			writable_attr_name; ///< Writable att. name
	vector<string> 	extensions;         ///< For future extensions

/// @privatesection
	bool operator==(const _DeviceAttributeConfig &);
}DeviceAttributeConfig;

/**
 * Attribute configuration data extension
 *
 * @headerfile tango.h
 * @ingroup Client
 */
#ifdef GEN_DOC
typedef struct AttributeInfo : public DeviceAttributeConfig
#else
typedef struct _AttributeInfo : public DeviceAttributeConfig
#endif
{
	Tango::DispLevel disp_level;        ///< Display level

/// @privatesection
	friend ostream &operator<<(ostream &,_AttributeInfo &);
	bool operator==(const _AttributeInfo &);
}AttributeInfo;

/**
 * Attribute alarms configuration
 *
 * @headerfile tango.h
 * @ingroup Client
 */
#ifdef GEN_DOC
typedef struct AttributeAlarmInfo
#else
typedef struct _AttributeAlarmInfo
#endif
{
	string			min_alarm;      ///< Min alarm level
	string			max_alarm;      ///< max alarm level
	string 			min_warning;    ///< Min warning level
	string			max_warning;    ///< Max warning level
	string			delta_t;        ///< Delta t RDS
	string			delta_val;      ///< Delta val RDS
	vector<string>	extensions;     ///< Future extensions

/// @privatesection
	bool operator==(const _AttributeAlarmInfo &);
}AttributeAlarmInfo;

/**
 * Attribute change event configuration
 *
 * @headerfile tango.h
 * @ingroup Client
 */
#ifdef GEN_DOC
typedef struct ChangeEventInfo
#else
typedef struct _ChangeEventInfo
#endif
{
	string			rel_change;     ///< Relative change threshold
	string			abs_change;     ///< Absolute change threshold
	vector<string>	extensions;     ///< Future extensions
}ChangeEventInfo;

/**
 * Attribute periodic event configuration
 *
 * @headerfile tango.h
 * @ingroup Client
 */
#ifdef GEN_DOC
typedef struct PeriodicEventInfo
#else
typedef struct _PeriodicEventInfo
#endif
{
	string			period;         ///< Event period
	vector<string>	extensions;     ///< Future extensions
}PeriodicEventInfo;

/**
 * Attribute archive event configuration
 *
 * @headerfile tango.h
 * @ingroup Client
 */
#ifdef GEN_DOC
typedef struct ArchiveEventInfo
#else
typedef struct _ArchiveEventInfo
#endif
{
	string			archive_rel_change;     ///< Archive relative change threshold
	string			archive_abs_change;     ///< Archive abosolute change threshold
	string			archive_period;         ///< Archive event period
	vector<string>	extensions;             ///< Future exetnsions
}ArchiveEventInfo;

/**
 * Attribute event configuration
 *
 * @headerfile tango.h
 * @ingroup Client
 */
#ifdef GEN_DOC
typedef struct AttributeEventInfo
#else
typedef struct _AttributeEventInfo
#endif
{
	ChangeEventInfo		ch_event;       ///< Attribute change event info
	PeriodicEventInfo	per_event;      ///< Attribute periodic event info
	ArchiveEventInfo	arch_event;     ///< Attribute archive event info

/// @privatesection
	bool operator==(const _AttributeEventInfo &);
}AttributeEventInfo;

/**
 * Possible memorized attribute type
 *
 * @ingroup Client
 * @headerfile tango.h
 */
typedef enum _AttrMemorizedType
{
	NOT_KNOWN,        		///< Device too old to  get this info
	NONE,      				///< The attribute is not memorized
	MEMORIZED,      		///< Memorized attribute
	MEMORIZED_WRITE_INIT	///< Memorized attribute with memorized value writen at initialization
}AttrMemorizedType;


/**
 * Extended attribute configuration data
 *
 * @headerfile tango.h
 * @ingroup Client
 */
#ifdef GEN_DOC
typedef struct AttributeInfoEx: public AttributeInfo
#else
typedef struct _AttributeInfoEx : public AttributeInfo
#endif
{
	string				root_attr_name;		///< Root attribute name (in case of forwarded attribute)
	AttrMemorizedType	memorized;			///< The attribute memorization type
	vector<string>		enum_labels;		///< Enumerated attribute labels
	AttributeAlarmInfo 	alarms;             ///< The attribute alarms
	AttributeEventInfo	events;             ///< The attribute events configuration
	vector<string>		sys_extensions;     ///< Future extensions

/// @privatesection
	_AttributeInfoEx & operator=(const AttributeConfig_2 *);
	_AttributeInfoEx & operator=(const AttributeConfig_3 *);
	_AttributeInfoEx & operator=(const AttributeConfig_5 *);

	friend ostream &operator<<(ostream &,_AttributeInfoEx &);
	bool operator==(const _AttributeInfoEx &);
}AttributeInfoEx;

typedef vector<AttributeInfo> AttributeInfoList;

/**
 * vector of AttributeInfoEx structure
 *
 * @headerfile tango.h
 * @ingroup Client
 */
typedef vector<AttributeInfoEx> AttributeInfoListEx;

/**
 * Base structure for pipe information
 *
 * @headerfile tango.h
 */
#ifdef GEN_DOC
typedef struct PipeInfo
#else
typedef struct _PipeInfo
#endif
{
	string 					name;          		///< Pipe name
	string					description;		///< Pipe description
	string 					label;       		///< Pipe label
	Tango::DispLevel 		disp_level;        	///< Display level
	Tango::PipeWriteType 	writable;           ///< Writable type (Read, Read-Write)
	vector<string> 			extensions;         ///< For future extensions

///@privatesection
	friend ostream &operator<<(ostream &,_PipeInfo &);
//	bool operator==(const _PipeInfo &);
}PipeInfo;

// TODO: Pipe -> Change the type for writable to replace PIPE_READ, PIPE_READ_WRITE by READ, READ_WRITE (IDL limitation)

typedef vector<PipeInfo> PipeInfoList;

//
// Can't use CALLBACK (without _) in the following enum because it's a
// pre-defined type on Windows....
//

/**
 * Possible asynchronous request type
 *
 * @ingroup Client
 * @headerfile tango.h
 */
enum asyn_req_type
{
	POLLING,        ///< Polling mode request
	CALL_BACK,      ///< Callback mode request
	ALL_ASYNCH      ///< All request
};

/**
 * Possible callback mode
 *
 * @ingroup Client
 * @headerfile tango.h
 */
enum cb_sub_model
{
	PUSH_CALLBACK,  ///< Callback push model
	PULL_CALLBACK   ///< Callback pull model
};

//
// Some define
//

#define 	CONNECTION_OK		1
#define 	CONNECTION_NOTOK	0

#define		PROT_SEP			"://"
#define		TACO_PROTOCOL		"taco"
#define		TANGO_PROTOCOL		"tango"

#define		MODIFIER			'#'
#define		DBASE_YES			"dbase=yes"
#define		DBASE_NO			"dbase=no"
#define		MODIFIER_DBASE_NO	"#dbase=no"

#define		HOST_SEP			':'
#define		PORT_SEP			'/'
#define		DEV_NAME_FIELD_SEP	'/'
#define		RES_SEP				"->"
#define		DEVICE_SEP			'/'

#define		FROM_IOR			"IOR"
#define		NOT_USED			"Unused"


/****************************************************************************************
 * 																						*
 * 					The ApiUtil class													*
 * 					-----------------													*
 * 																						*
 ***************************************************************************************/

#include "ApiUtil.h"


/****************************************************************************************
 * 																						*
 * 					The DeviceData class												*
 * 					--------------------												*
 * 																						*
 ***************************************************************************************/


#include "DeviceData.h"

/****************************************************************************************
 * 																						*
 * 					The DevicePipe class												*
 * 					--------------------												*
 * 																						*
 ***************************************************************************************/


#include "DevicePipe.h"

/****************************************************************************************
 * 																						*
 * 					The DeviceAttribute class											*
 * 					-------------------------											*
 * 																						*
 ***************************************************************************************/


#include "DeviceAttribute.h"


/****************************************************************************************
 * 																						*
 * 					The xxxDataHistory classes											*
 * 					--------------------------											*
 * 																						*
 ***************************************************************************************/

/**
 * Fundamental type for receiving data from device command polling buffers
 *
 * This is the fundamental type for receiving data from device command polling buffers. This class inherits
 * from the Tango::DeviceData class. One instance of this class is created for each command result history.
 * Within this class, you find the command result data or the exception parameters, a flag indicating if the
 * command has failed when it was invoked by the device server polling thread and the date when the command
 * was executed. For history calls, it is not possible to returns command error as exception. See chapter
 * on Advanced Features in the
 * <a href=http://www.esrf.eu/computing/cs/tango/tango_doc/kernel_doc/ds_prog/index.html target=new>Tango book</a>
 * for all details regarding device polling.
 *
 * $Author: taurel $
 * $Revision: 28018 $
 *
 * @headerfile tango.h
 * @ingroup Client
 */
class DeviceDataHistory: public DeviceData
{

public :
///@privatesection
//
// constructor methods
//

	DeviceDataHistory();
	DeviceDataHistory(int, int *,DevCmdHistoryList *);
	DeviceDataHistory(const DeviceDataHistory &);
	DeviceDataHistory & operator=(const DeviceDataHistory &);
#ifdef HAS_RVALUE
	DeviceDataHistory(DeviceDataHistory &&);
	DeviceDataHistory &operator=(DeviceDataHistory &&);
#endif

	~DeviceDataHistory();

///@publicsection
/**
 * Check if the record was a failure
 *
 * Returns a boolean set to true if the record in the polling buffer was a failure
 *
 * @return A boolean set to true if the record was a failure
 */
	bool has_failed() {return fail;}
/**
 * Get record polling date
 *
 * Returns the date when the device server polling thread has executed the command.
 *
 * @return The record polling date
 */
	TimeVal &get_date() {return time;}
/**
 * Get record error stack
 *
 * Return the error stack recorded by the device server polling thread in case of the command failed when it
 * was invoked.
 *
 * @return The record error stack
 */
	const DevErrorList &get_err_stack() {return err.in();}
/**
 * Print a DeviceDataHistory instance
 *
 * Is an utility function to easily print the contents of a DeviceDataHistory object. This function knows all
 * types which could be inserted in a DeviceDataHistory object and print them accordingly. It also prints date
 * and error stack in case the command returned an error.
 * @code
 * DeviceProxy *dev = new DeviceProxy(“...”);
 * int hist_depth = 4;
 * vector<DeviceDataHistory> *hist;
 *
 * hist = dev->command_history(“MyCommand”,hist_depth);
 *
 * for (int i = 0;i < hist_depth;i++)
 * {
 *    cout << (*hist)[i] << endl;
 * }
 * delete hist;
 * @endcode
 *
 * @param [in] str The printing stream
 * @param [in] ddh The instance to be printed
 */
	friend ostream &operator<<(ostream &str,DeviceDataHistory &ddh);

///@privatesection
// Three following methods for compatibility with older release

	bool failed() {return fail;}
	void failed(bool val) {fail = val;}
	void set_date(TimeVal &tv) {time = tv;}
	TimeVal &date() {return time;}
	const DevErrorList &errors() {return err.in();}
	void errors(DevErrorList_var &del) {err = del;}

protected:
///@privatesection
	bool 				fail;
	TimeVal 			time;
	DevErrorList_var 	err;

	DevCmdHistoryList 	*seq_ptr;
	int 				*ref_ctr_ptr;

private:
    class DeviceDataHistoryExt
    {
    public:
        DeviceDataHistoryExt() {};
    };

#ifdef HAS_UNIQUE_PTR
    unique_ptr<DeviceDataHistoryExt>    ext_hist;
#else
	DeviceDataHistoryExt	            *ext_hist;		// Class extension
#endif
};

typedef vector<DeviceDataHistory> DeviceDataHistoryList;

/**
 * Fundamental type for receiving data from device attribute polling buffers
 *
 * This is the fundamental type for receiving data from device attribute polling buffers. This class inherits
 * from the Tango::DeviceAttribute class. One instance of this class is created for each attribute result history.
 * Within this class, you find the attribute result data or the exception parameters and a flag indicating if the
 * attribute has failed when it was invoked by the device server polling thread. For history calls, it is not
 * possible to returns attribute error as exception. See chapter on Advanced Features in the
 * <a href=http://www.esrf.eu/computing/cs/tango/tango_doc/kernel_doc/ds_prog/index.html target=new>Tango book</a> for all details regarding
 * device polling.
 *
 * $Author: taurel $
 * $Revision: 28018 $
 *
 * @headerfile tango.h
 * @ingroup Client
 */
class DeviceAttributeHistory: public DeviceAttribute
{

public :
///@privatesection
//
// constructor methods
//

	DeviceAttributeHistory();
	DeviceAttributeHistory(int, DevAttrHistoryList_var &);
	DeviceAttributeHistory(int, DevAttrHistoryList_3_var &);
	DeviceAttributeHistory(const DeviceAttributeHistory &);
	DeviceAttributeHistory & operator=(const DeviceAttributeHistory &);
#ifdef HAS_RVALUE
	DeviceAttributeHistory(DeviceAttributeHistory &&);
	DeviceAttributeHistory &operator=(DeviceAttributeHistory &&);
#endif

	~DeviceAttributeHistory();
///@publicsection
/**
 * Check if the record was a failure
 *
 * Returns a boolean set to true if the record in the polling buffer was a failure
 *
 * @return A boolean set to true if the record was a failure
 */
	bool has_failed() {return fail;}
/**
 * Print a DeviceAttributeHistory instance
 *
 * Is an utility function to easily print the contents of a DeviceAttributeHistory object. This function knows
 * all types which could be inserted in a DeviceAttributeHistory object and print them accordingly. It also
 * in case the attribute returned an error.
 * @code
 * DeviceProxy *dev = new DeviceProxy(“...”);
 * int hist_depth = 4;
 * vector<DeviceAttributeHistory> *hist;

 * hist = dev->attribute_history(“MyAttribute”,hist_depth);

 * for (int i = 0;i < hist_depth;i++)
 * {
 *    cout << (*hist)[i] << endl;
 * }
 * delete hist;
 * @endcode
 *
 * @param [in] str The printing stream
 * @param [in] dah The instance to be printed
 */
 	friend ostream &operator<<(ostream &str,DeviceAttributeHistory &dah);

///@privatesection
// Three following methods for compatibility with older release

	bool failed() {return fail;}
	void failed(bool val) {fail = val;}
	TimeVal &date() {return time;}
//	const DevErrorList &errors() {return err;}

protected:
///@privatesection
	bool 				fail;
	char 				compatibility_padding[16];

private:
    class DeviceAttributeHistoryExt
    {
    public:
        DeviceAttributeHistoryExt() {};
    };

#ifdef HAS_UNIQUE_PTR
    unique_ptr<DeviceAttributeHistoryExt>   ext_hist;
#else
	DeviceAttributeHistoryExt	            *ext_hist;	// Class extension
#endif
};


/****************************************************************************************
 * 																						*
 * 					The Connection class												*
 * 					--------------------												*
 * 																						*
 ***************************************************************************************/

#include "Connection.h"

/****************************************************************************************
 * 																						*
 * 					The DeviceProxy class												*
 * 					--------------------												*
 * 																						*
 ***************************************************************************************/

#include "DeviceProxy.h"

/****************************************************************************************
 * 																						*
 * 					The AttributeProxy class											*
 * 					--------------------												*
 * 																						*
 ***************************************************************************************/

#include "AttributeProxy.h"

/****************************************************************************************
 * 																						*
 * 					The DummyDeviceProxy class											*
 * 					--------------------												*
 * 																						*
 ***************************************************************************************/

class DummyDeviceProxy: public Tango::Connection
{
public:
	DummyDeviceProxy():Tango::Connection(true) {};

	virtual string get_corba_name(bool) {string str;return str;}
	virtual string build_corba_name() {string str;return str;}
	virtual int get_lock_ctr() {return 0;}
	virtual void set_lock_ctr(int) {};

	virtual string dev_name() {string str;return str;}

	int get_env_var(const char *cc,string &str_ref) {return Tango::Connection::get_env_var(cc,str_ref);}
};



///
///					Some inline methods
///					-------------------
///

inline ApiUtil *ApiUtil::instance()
{
	omni_mutex_lock lo(inst_mutex);

	if (_instance == NULL)
		_instance = new ApiUtil();
	return _instance;
}

inline long Connection::add_asyn_request(CORBA::Request_ptr req,TgRequest::ReqType req_type)
{
	omni_mutex_lock guard(asyn_mutex);
	long id = ApiUtil::instance()->get_pasyn_table()->store_request(req,req_type);
	pasyn_ctr++;
	return id;
}

inline void Connection::remove_asyn_request(long id)
{
	omni_mutex_lock guard(asyn_mutex);

	ApiUtil::instance()->get_pasyn_table()->remove_request(id);
	pasyn_ctr--;
}

inline void Connection::add_asyn_cb_request(CORBA::Request_ptr req,CallBack *cb,Connection *con,TgRequest::ReqType req_type)
{
	omni_mutex_lock guard(asyn_mutex);
	ApiUtil::instance()->get_pasyn_table()->store_request(req,cb,con,req_type);
	pasyn_cb_ctr++;
}

inline void Connection::remove_asyn_cb_request(Connection *con,CORBA::Request_ptr req)
{
	omni_mutex_lock guard(asyn_mutex);
	ApiUtil::instance()->get_pasyn_table()->remove_request(con,req);
	pasyn_cb_ctr--;
}

inline long Connection::get_pasyn_cb_ctr()
{
	long ret;
	asyn_mutex.lock();
	ret = pasyn_cb_ctr;
	asyn_mutex.unlock();
	return ret;
}

inline void Connection::dec_asynch_counter(asyn_req_type ty)
{
	omni_mutex_lock guard(asyn_mutex);
	if (ty==POLLING)
		pasyn_ctr--;
	else if (ty==CALL_BACK)
		pasyn_cb_ctr--;
}

inline void DeviceProxy::check_connect_adm_device()
{
	omni_mutex_lock guard(adm_dev_mutex);
	if (adm_device == NULL)
		connect_to_adm_device();
}

//
// For Tango 8 ZMQ event system
//

inline int DeviceProxy::subscribe_event (const string &attr_name, EventType event, CallBack *callback)
{
    vector<string> filt;
	return subscribe_event (attr_name,event,callback,filt,false);
}

inline int DeviceProxy::subscribe_event (const string &attr_name, EventType event,
                                 CallBack *callback,bool stateless)
{
    vector<string> filt;
    return subscribe_event(attr_name,event,callback,filt,stateless);
}

inline int DeviceProxy::subscribe_event (const string &attr_name, EventType event,
                                 int event_queue_size,bool stateless)
{
    vector<string> filt;
    return subscribe_event(attr_name,event,event_queue_size,filt,stateless);
}

///
///					Some macros
///					-----------
///

#define READ_ATT_EXCEPT(NAME_CHAR,OBJ) \
		catch (Tango::ConnectionFailed &e) \
		{ \
			TangoSys_OMemStream desc; \
			desc << "Failed to read_attribute on device " << device_name; \
			desc << ", attribute " << NAME_CHAR << ends; \
			ApiConnExcept::re_throw_exception(e,(const char*)"API_AttributeFailed", \
                        	desc.str(), (const char*)"DeviceProxy::read_attribute()"); \
		} \
		catch (Tango::DevFailed &e) \
		{ \
			TangoSys_OMemStream desc; \
			desc << "Failed to read_attribute on device " << device_name; \
			desc << ", attribute " << NAME_CHAR << ends; \
			Except::re_throw_exception(e,(const char*)"API_AttributeFailed", \
                        	desc.str(), (const char*)"DeviceProxy::read_attribute()"); \
		} \
		catch (CORBA::TRANSIENT &trans) \
		{ \
			TRANSIENT_NOT_EXIST_EXCEPT(trans,"DeviceProxy","read_attribute",OBJ); \
		} \
		catch (CORBA::OBJECT_NOT_EXIST &one) \
		{ \
			if (one.minor() == omni::OBJECT_NOT_EXIST_NoMatch || one.minor() == 0) \
			{ \
				TRANSIENT_NOT_EXIST_EXCEPT(one,"DeviceProxy","read_attribute",OBJ); \
			} \
			else \
			{ \
				set_connection_state(CONNECTION_NOTOK); \
				TangoSys_OMemStream desc; \
				desc << "Failed to read_attribute on device " << device_name << ends; \
				ApiCommExcept::re_throw_exception(one, \
							      (const char*)"API_CommunicationFailed", \
                        				      desc.str(), \
							      (const char*)"DeviceProxy::read_attribute()"); \
			} \
		} \
		catch (CORBA::COMM_FAILURE &comm) \
		{ \
			if (comm.minor() == omni::COMM_FAILURE_WaitingForReply) \
			{ \
				TRANSIENT_NOT_EXIST_EXCEPT(comm,"DeviceProxy","read_attribute",OBJ); \
			} \
			else \
			{ \
				set_connection_state(CONNECTION_NOTOK); \
				TangoSys_OMemStream desc; \
				desc << "Failed to read_attribute on device " << device_name << ends; \
				ApiCommExcept::re_throw_exception(comm, \
							      (const char*)"API_CommunicationFailed", \
                        				      desc.str(), \
							      (const char*)"DeviceProxy::read_attribute()"); \
			} \
		} \
		catch (CORBA::SystemException &ce) \
        { \
			set_connection_state(CONNECTION_NOTOK); \
			TangoSys_OMemStream desc; \
			desc << "Failed to read_attribute on device " << device_name << ends; \
			ApiCommExcept::re_throw_exception(ce, \
						      (const char*)"API_CommunicationFailed", \
                        			      desc.str(), \
						      (const char*)"DeviceProxy::read_attribute()"); \
		}


#define	COPY_BASE_CONFIG(A,B) \
	A[i].name = B[i].name; \
	A[i].writable = B[i].writable; \
	A[i].data_format = B[i].data_format; \
	A[i].data_type = B[i].data_type; \
	A[i].max_dim_x = B[i].max_dim_x; \
	A[i].max_dim_y = B[i].max_dim_y; \
	A[i].description = B[i].description; \
	A[i].label = B[i].label; \
	A[i].unit = B[i].unit; \
	A[i].standard_unit = B[i].standard_unit; \
	A[i].display_unit = B[i].display_unit; \
	A[i].format = B[i].format; \
	A[i].min_value = B[i].min_value; \
	A[i].max_value = B[i].max_value; \
	A[i].writable_attr_name = B[i].writable_attr_name; \
	A[i].extensions.resize(B[i].extensions.length()); \
	for (size_t j=0; j<B[i].extensions.length(); j++) \
	{ \
		A[i].extensions[j] = B[i].extensions[j]; \
	}


#define	COPY_ALARM_CONFIG(A,B) \
	A[i].alarms.min_alarm = B[i].att_alarm.min_alarm; \
	A[i].alarms.max_alarm = B[i].att_alarm.max_alarm; \
	A[i].alarms.min_warning = B[i].att_alarm.min_warning; \
	A[i].alarms.max_warning = B[i].att_alarm.max_warning; \
	A[i].alarms.delta_t = B[i].att_alarm.delta_t; \
	A[i].alarms.delta_val = B[i].att_alarm.delta_val; \
	A[i].alarms.extensions.resize(B[i].att_alarm.extensions.length()); \
	for (size_t j=0; j<B[i].att_alarm.extensions.length(); j++) \
	{ \
		A[i].alarms.extensions[j] = B[i].att_alarm.extensions[j]; \
	}


#define	COPY_EVENT_CONFIG(A,B) \
	A[i].events.ch_event.rel_change = B[i].event_prop.ch_event.rel_change; \
	A[i].events.ch_event.abs_change = B[i].event_prop.ch_event.abs_change; \
	A[i].events.ch_event.extensions.resize(B[i].event_prop.ch_event.extensions.length()); \
	for (size_t j=0; j<B[i].event_prop.ch_event.extensions.length(); j++) \
	{ \
		A[i].events.ch_event.extensions[j] = B[i].event_prop.ch_event.extensions[j]; \
	} \
\
	A[i].events.per_event.period = B[i].event_prop.per_event.period; \
	A[i].events.per_event.extensions.resize(B[i].event_prop.per_event.extensions.length()); \
	for (size_t j=0; j<B[i].event_prop.per_event.extensions.length(); j++) \
	{ \
		A[i].events.per_event.extensions[j] = B[i].event_prop.per_event.extensions[j]; \
	} \
\
	A[i].events.arch_event.archive_rel_change = B[i].event_prop.arch_event.rel_change; \
	A[i].events.arch_event.archive_abs_change = B[i].event_prop.arch_event.abs_change; \
	A[i].events.arch_event.archive_period = B[i].event_prop.arch_event.period; \
	A[i].events.arch_event.extensions.resize(B[i].event_prop.arch_event.extensions.length()); \
	for (size_t j=0; j<B[i].event_prop.arch_event.extensions.length(); j++) \
	{ \
		A[i].events.arch_event.extensions[j] = B[i].event_prop.arch_event.extensions[j]; \
	}


///
/// 				Small utility classes
///					---------------------


class AutoConnectTimeout
{
public:
	AutoConnectTimeout(unsigned int to) {omniORB::setClientConnectTimeout((CORBA::ULong)to);}
	~AutoConnectTimeout() {omniORB::setClientConnectTimeout(NARROW_CLNT_TIMEOUT);}
};

} // End of Tango namespace

#endif /* _DEVAPI_H */