Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • cs/ds/alarm-handler
  • francesco.tripaldi/alarm-handler
2 results
Show changes
Showing
with 2631 additions and 759 deletions
/*
* formula_grammar.h
*
* $Author: graziano $
*
* $Revision: 1.5 $
*
* $Log: formula_grammar.h,v $
*
*
* copyleft: Sincrotrone Trieste S.C.p.A. di interesse nazionale
* Strada Statale 14 - km 163,5 in AREA Science Park
* 34012 Basovizza, Trieste ITALY
......@@ -15,6 +8,7 @@
#ifndef FORMULA_GRAMMAR_H_
#define FORMULA_GRAMMAR_H_
#include <boost/version.hpp>
//#define BOOST_SPIRIT_NO_TREE_NODE_COLLAPSING //test trying to have node also if formula of type (ev/ev/ev/ev) 27/02/2008
......@@ -24,23 +18,25 @@
#endif
#endif
#if BOOST_VERSION < 103600
#if BOOST_VERSION < 103600
#include <boost/spirit/core.hpp>
#include <boost/spirit/tree/ast.hpp>
//for ast parse trees (in tree_formula)
#include <boost/spirit/symbols/symbols.hpp> //for symbol table
using namespace boost::spirit;
#else
#include <boost/spirit/include/classic_core.hpp>
#include <boost/spirit/include/classic_ast.hpp>
using namespace boost::spirit::classic;
//for ast parse trees (in tree_formula)
#include <boost/spirit/include/classic_symbols.hpp> //for symbol table
using namespace boost::spirit::classic;
#endif
//for ast parse trees (in tree_formula)
//#include <boost/spirit/symbols/symbols.hpp> //for symbol table
using namespace std;
#ifdef _ACCESS_NODE_D
/*typedef char const* iterator_t;
typedef node_val_data_factory<unsigned int> factory_t;
typedef tree_match<iterator_t, factory_t> parse_tree_match_t;
......@@ -60,7 +56,7 @@ static void Assign_Stat (tree_node_t & node, const iterator_t & begin, const ite
node.value.value(stat_tmp);
}*/
unsigned int stat_tmp;
static unsigned int stat_tmp;
struct Save_Stat
{
void operator () (unsigned int val) const
......@@ -77,9 +73,33 @@ struct Assign_Stat
}
};
#endif //_ACCESS_NODE_D
//TODO: duplicated from alarm.h
enum _AlarmStateEnum {
_NORM,
_UNACK,
_ACKED,
_RTNUN,
_SHLVD,
_DSUPR,
_OOSRV,
_ERROR
} ;
static vector<string> quality_labels = {"ATTR_VALID","ATTR_INVALID","ATTR_ALARM","ATTR_CHANGING","ATTR_WARNING"};
struct formula_grammar : public grammar<formula_grammar>
{
/*formula_t &m_formula;
symbols<unsigned int> sym_grp;
formula_grammar(formula_t &f) \
: m_formula(f)
{
}*/
static const int val_rID = 1;
static const int val_hID = 2;
static const int val_stID = 3;
......@@ -96,9 +116,24 @@ struct formula_grammar : public grammar<formula_grammar>
static const int expr_atomID = 14;
static const int shift_exprID = 15;
static const int unary_exprID = 16;
static const int val_stringID = 17; //TODO: OK ?
static const int func_dualID = 18;
static const int logical_expr_parenID = 19;
static const int cond_exprID = 20;
static const int exprID = 21;
static const int nonempty_exprID = 22;
static const int val_qualityID = 23;
static const int val_alarm_enum_stID = 24;
static const int propertyID = 25;
static const int index_rangeID = 26;
static const int index_listID = 27;
symbols<unsigned int> tango_states;
symbols<unsigned int> tango_states;
symbols<unsigned int> attr_quality;
symbols<unsigned int> alarm_enum_states;
formula_grammar()
{
tango_states.add("ON", (unsigned int)Tango::ON);
......@@ -115,6 +150,22 @@ struct formula_grammar : public grammar<formula_grammar>
tango_states.add("ALARM", (unsigned int)Tango::ALARM);
tango_states.add("DISABLE", (unsigned int)Tango::DISABLE);
tango_states.add("UNKNOWN", (unsigned int)Tango::UNKNOWN);
attr_quality.add("ATTR_VALID", (unsigned int)Tango::ATTR_VALID);
attr_quality.add("ATTR_INVALID", (unsigned int)Tango::ATTR_INVALID);
attr_quality.add("ATTR_ALARM", (unsigned int)Tango::ATTR_ALARM);
attr_quality.add("ATTR_CHANGING", (unsigned int)Tango::ATTR_CHANGING);
attr_quality.add("ATTR_WARNING", (unsigned int)Tango::ATTR_WARNING);
alarm_enum_states.add("NORM", (unsigned int)_NORM);
alarm_enum_states.add("UNACK", (unsigned int)_UNACK);
alarm_enum_states.add("ACKED", (unsigned int)_ACKED);
alarm_enum_states.add("RTNUN", (unsigned int)_RTNUN);
alarm_enum_states.add("SHLVD", (unsigned int)_SHLVD);
alarm_enum_states.add("DSUPR", (unsigned int)_DSUPR);
alarm_enum_states.add("OOSRV", (unsigned int)_OOSRV);
alarm_enum_states.add("ERROR", (unsigned int)_ERROR);
}
template <typename ScannerT>
......@@ -139,7 +190,10 @@ struct formula_grammar : public grammar<formula_grammar>
definition(formula_grammar const& self)
{
symbol
= (alnum_p | '.' | '_' | '-' | '+') //any alpha numeric char plus '.', '_', '-', '+'
= (alnum_p | '.' | '_' | '-' | '+') //any alpha numeric char plus '.', '_', '-'
;
symbol_attr
= (alnum_p | '_' | '.') - str_p(".normal") - str_p(".alarm") - str_p(".quality") //any alpha numeric char plus '_', '.' for attribute names
;
//------------------------------ALARM NAME--------------------------------------
name
......@@ -151,13 +205,27 @@ struct formula_grammar : public grammar<formula_grammar>
lexeme_d[ //needed to ignore "space_p" (skip white spaces) evaluating name
!("tango://" >> (+symbol) >> ':' >> uint_p >> "/") //eventually match FQDN
>> (+symbol) >> '/' >> (+symbol)
>> '/' >> (+symbol) >> '/' >> (+symbol)
>> '/' >> (+symbol) >> '/' >> (+symbol_attr)
]
]
// = repeat_p(3)[(+symbol) >> ch_p('/')] >> (+symbol)
;
;
index_range
=
( uint_p >> !(discard_node_d[ch_p('-')] >> uint_p)) // n or n-m
;
index_list
= (index_range >> *(discard_node_d[ch_p(',')] >> index_range)) // n-m,k,s-t,..
;
index
= inner_node_d[ch_p('[') >> uint_p >> ch_p(']')]
= discard_node_d[ch_p('[')] >>
(str_p("-1") | index_list) >>
discard_node_d[ch_p(']')]
;
property
= str_p(".quality")
| str_p(".alarm")
| str_p(".normal")
;
//------------------------------FORMULA--------------------------------------
val_r
......@@ -176,21 +244,52 @@ struct formula_grammar : public grammar<formula_grammar>
;
val_st
=
#ifndef _ACCESS_NODE_D
token_node_d[self.tango_states] //match only group defined in sym_grp symbol table
#else
//access_node_d[self.tango_states[&Save_Stat]][&Assign_Stat] //save Tango::state value in node
access_node_d[self.tango_states[Save_Stat()]][Assign_Stat()] //save Tango::state value in node
#endif //_ACCESS_NODE_D
;
val_quality
=
//access_node_d[self.attr_quality[&Save_Stat]][&Assign_Stat] //save Tango::state value in node
access_node_d[self.attr_quality[Save_Stat()]][Assign_Stat()] //save Tango::state value in node
;
val_alarm_enum_st
=
//access_node_d[self.alarm_enum_states[&Save_Stat]][&Assign_Stat] //save Tango::state value in node
access_node_d[self.alarm_enum_states[Save_Stat()]][Assign_Stat()] //save Tango::state value in node
;
val_string
#if BOOST_VERSION < 103600
= token_node_d[
#else
= reduced_node_d[
#endif
lexeme_d[ //to conserve white spaces
ch_p('\'')
>> (+(anychar_p - '\'')) //one ore more char except '"'
>> '\''
]
]
// = repeat_p(3)[(+symbol) >> ch_p('/')] >> (+symbol)
;
event_
= name
>> !(index)
>> ( *(index)//0 or more indexex
>> !(property) //followed by 0 or 1 property
)
;
top = logical_expr
;
/*top = ternary_if;
ternary_if
= logical_expr_paren
>> !(root_node_d[str_p("?")] >> logical_expr_paren >> discard_node_d[ch_p(':')] >> logical_expr_paren)
;*/
cond_expr = logical_expr >> *(root_node_d[ch_p('?')] >> cond_expr >> discard_node_d[ch_p(':')] >> cond_expr);
/*top = logical_expr
;*/
logical_expr
= bitwise_expr
......@@ -235,36 +334,67 @@ struct formula_grammar : public grammar<formula_grammar>
)
;
mult_expr
= expr_atom
>> *( (root_node_d[ch_p('*')] >> expr_atom)
| (root_node_d[ch_p('/')] >> expr_atom)
= unary_expr
>> *( (root_node_d[ch_p('*')] >> unary_expr)
| (root_node_d[ch_p('/')] >> unary_expr)
)
;
function
= root_node_d[str_p("abs")] >> (inner_node_d[ch_p('(') >> logical_expr >> ')'])
;
unary_expr
= ( (root_node_d[ch_p('+')] >> expr_atom)
= ( expr_atom
| function
| function_dual
| (root_node_d[ch_p('+')] >> expr_atom)
| (root_node_d[ch_p('-')] >> expr_atom)
| (root_node_d[ch_p('!')] >> expr_atom)
// | (root_node_d[ch_p('~')] >> expr_atom) //TODO
)
;
function
= ( root_node_d[str_p("abs")] >> (discard_node_d[ch_p('(')] >> cond_expr >> discard_node_d[ch_p(')')]) //TODO: ? not expr_atom ?
| root_node_d[str_p("cos")] >> (discard_node_d[ch_p('(')] >> cond_expr >> discard_node_d[ch_p(')')]) //TODO: ? not expr_atom ?
| root_node_d[str_p("sin")] >> (discard_node_d[ch_p('(')] >> cond_expr >> discard_node_d[ch_p(')')]) //TODO: ? not expr_atom ?
| root_node_d[str_p("quality")] >> (discard_node_d[ch_p('(')] >> cond_expr >> discard_node_d[ch_p(')')]) //TODO: ? not expr_atom ?
| root_node_d[str_p("AND")] >> (discard_node_d[ch_p('(')] >> cond_expr >> discard_node_d[ch_p(')')]) //TODO: ? not expr_atom ?
| root_node_d[str_p("OR")] >> (discard_node_d[ch_p('(')] >> cond_expr >> discard_node_d[ch_p(')')]) //TODO: ? not expr_atom ?
)
;
function_dual
= ( (root_node_d[str_p("max")] >> (discard_node_d[ch_p('(')] >> cond_expr >> discard_node_d[ch_p(',')] >> cond_expr >> discard_node_d[ch_p(')')]))
//| (root_node_d[str_p("max")] >> (inner_node_d[ch_p('(') >> discard_node_d[ch_p('(')] >> logical_expr >> discard_node_d[ch_p(')')] >> discard_node_d[ch_p(',')] >> discard_node_d[ch_p('(')] >> logical_expr >> discard_node_d[ch_p(')')] >> ')']))
| (root_node_d[str_p("min")] >> (discard_node_d[ch_p('(')] >> cond_expr >> discard_node_d[ch_p(',')] >> cond_expr >> discard_node_d[ch_p(')')]))
//| (root_node_d[str_p("min")] >> (inner_node_d[ch_p('(') >> discard_node_d[ch_p('(')] >> logical_expr >> discard_node_d[ch_p(')')] >> discard_node_d[ch_p(',')] >> discard_node_d[ch_p('(')] >> logical_expr >> discard_node_d[ch_p(')')] >> ')']))
| (root_node_d[str_p("pow")] >> (discard_node_d[ch_p('(')] >> cond_expr >> discard_node_d[ch_p(',')] >> cond_expr >> discard_node_d[ch_p(')')]))
)
//= *( (root_node_d[str_p("max")] >> (inner_node_d[ch_p('(') >> logical_expr_paren >> discard_node_d[ch_p(',')] >> logical_expr_paren >> ')']))
// | (root_node_d[str_p("min")] >> (inner_node_d[ch_p('(') >> logical_expr_paren >> discard_node_d[ch_p(',')] >> logical_expr_paren >> ')']))
//| (root_node_d[str_p("min")] >> (discard_node_d[ch_p('(')] >> logical_expr_paren >> discard_node_d[ch_p(',')] >> logical_expr_paren >> discard_node_d[ch_p(',')]))
//| (root_node_d[str_p("min")] >> (ch_p('(') >> expr_atom >> ch_p(',') >> expr_atom >> ch_p(',')))
//)
;
non_empty_expression = cond_expr;
top = non_empty_expression | epsilon_p;
// top = non_empty_expression;
expr_atom
= //val_h | val_r
= //val_h | val_r
event_
| unary_expr
| val_h | val_r | val_st
| function
//| (inner_node_d[ch_p('(') >> logical_expr >> ')'])
| (discard_node_d[ch_p('(')] >> logical_expr >> discard_node_d[ch_p(')')])
| unary_expr
| val_h | val_r | val_st | val_quality | val_alarm_enum_st | val_string
//| (inner_node_d[ch_p('(') >> non_empty_expression >> ')'])
| (discard_node_d[ch_p('(')] >> non_empty_expression >> discard_node_d[ch_p(')')])
;
/*logical_expr_paren
= (discard_node_d[ch_p('(')] >> logical_expr >> discard_node_d[ch_p(')')])
| logical_expr
;*/
}
rule<ScannerT> top;
//rule<ScannerT> symbol;
rule<typename lexeme_scanner<ScannerT>::type> symbol; //neede to use lexeme_d in rule name
rule<typename lexeme_scanner<ScannerT>::type> symbol; //needed to use lexeme_d in rule name
rule<typename lexeme_scanner<ScannerT>::type> symbol_attr; //needed to use lexeme_d in rule name
rule<ScannerT, parser_context<>, parser_tag<val_rID> > val_r;
rule<ScannerT, parser_context<>, parser_tag<val_hID> > val_h;
rule<ScannerT, parser_context<>, parser_tag<val_stID> > val_st;
......@@ -280,7 +410,19 @@ struct formula_grammar : public grammar<formula_grammar>
rule<ScannerT, parser_context<>, parser_tag<expr_atomID> > expr_atom;
rule<ScannerT, parser_context<>, parser_tag<funcID> > function;
rule<ScannerT, parser_context<>, parser_tag<nameID> > name;
rule<ScannerT, parser_context<>, parser_tag<index_rangeID> > index_range;
rule<ScannerT, parser_context<>, parser_tag<index_listID> > index_list;
rule<ScannerT, parser_context<>, parser_tag<indexID> > index;
rule<ScannerT, parser_context<>, parser_tag<val_stringID> > val_string;
rule<ScannerT, parser_context<>, parser_tag<func_dualID> > function_dual;
rule<ScannerT, parser_context<>, parser_tag<logical_expr_parenID> > logical_expr_paren;
rule<ScannerT, parser_context<>, parser_tag<cond_exprID> > cond_expr;
rule<ScannerT, parser_context<>, parser_tag<nonempty_exprID> > non_empty_expression;
rule<ScannerT, parser_context<>, parser_tag<exprID> > expression;
rule<ScannerT, parser_context<>, parser_tag<val_qualityID> > val_quality;
rule<ScannerT, parser_context<>, parser_tag<val_alarm_enum_stID> > val_alarm_enum_st;
rule<ScannerT, parser_context<>, parser_tag<propertyID> > property;
rule<ScannerT> const&
start() const { return top; }
......
/*
* log_thread.cpp
*
* $Author: graziano $
*
* $Revision: 1.7 $
*
* $Log: log_thread.cpp,v $
*
*
* copyleft: Sincrotrone Trieste S.C.p.A. di interesse nazionale
* Strada Statale 14 - km 163,5 in AREA Science Park
* 34012 Basovizza, Trieste ITALY
*/
#include "log_thread.h"
//#define _DEBUG_LOG_THREAD 0
//#define _DEBUG_LOG_THREAD 1
static const char __FILE__rev[] = __FILE__ " $Revision: 1.7 $";
/*
* log_thread::log_thread()
*/
log_thread::log_thread(string dbhost, string dbuser, string dbpw, string dbname, int dbport, string instance_name/*, Alarm_ns::Alarm *p*/)/*: Tango::LogAdapter(p)*/
{
//p_Alarm = p;
m_dbhost = dbhost;
m_dbuser = dbuser;
m_dbpw = dbpw;
m_dbname = dbname;
m_dbport = dbport;
m_instance_name = instance_name;
//cout << __FILE__rev << endl;
ostringstream err;
if(!mysql_init(&log_db))
{
err << "mysql_init failed for log DB" << ends;
throw err.str();
}
my_bool my_auto_reconnect=1;
if(mysql_options(&log_db,MYSQL_OPT_RECONNECT,&my_auto_reconnect) !=0)
{
err << "mysql auto reconnection error for log DB: " << mysql_error(&log_db) << ends;;
throw err.str();
}
if(!mysql_real_connect(&log_db, m_dbhost.c_str(), m_dbuser.c_str(), m_dbpw.c_str(), m_dbname.c_str(), m_dbport, NULL, 0))
{
err << "mysql_real_connect failed for log DB" << ends;
throw err.str();
}
}
/*
* log_thread::~log_thread()
*/
log_thread::~log_thread()
{
//p_Alarm = NULL;
mysql_close(&log_db);
}
/*
* log_thread::run()
*/
void log_thread::run(void *)
{
while (true) {
/*
* pop_front() will wait() on condition variable
*/
try
{
alm_log_t a = al_list.pop_front();
if ((a.name == LOG_THREAD_EXIT) && \
(a.time_s == LOG_THREAD_EXIT_TIME))
break;
write_db(a);
}
catch(omni_thread_fatal& ex)
{
ostringstream err;
err << "omni_thread_fatal exception running log thread, err=" << ex.error << ends;
//WARN_STREAM << "alarm_thread::run(): " << err.str() << endl;
printf("log_thread::run(): %s", err.str().c_str());
}
catch(Tango::DevFailed& ex)
{
ostringstream err;
err << "exception running log thread: '" << ex.errors[0].desc << "'" << ends;
//WARN_STREAM << "alarm_thread::run(): " << err.str() << endl;
printf("log_thread::run(): %s", err.str().c_str());
Tango::Except::print_exception(ex);
}
catch(...)
{
//WARN_STREAM << "alarm_thread::run(): catched unknown exception!!" << endl;
printf("log_thread::run(): catched unknown exception!!");
}
}
} /* alarm_thread::run() */
void log_thread::log_alarm_db(alm_log_t& a)
{
al_list.push_back(a);
}
void log_thread::write_db(alm_log_t& a)
{
ostringstream query_str;
ostringstream err_msg;
char *values_escaped = new char [2 * a.values.length() + 1];
char *name_escaped = new char [2 * a.name.length() + 1];
char *formula_escaped = new char [2 * a.formula.length() + 1];
char *grp_escaped = new char [2 * a.grp.length() + 1];
char *msg_escaped = new char [2 * a.msg.length() + 1];
char *level_escaped = new char [2 * a.level.length() + 1];
char *action_escaped = new char [2 * a.action.length() + 1];
char *instance_escaped = new char [2 * m_instance_name.length() + 1];
mysql_real_escape_string(&log_db, values_escaped, a.values.c_str(), a.values.length());
mysql_real_escape_string(&log_db, name_escaped, a.name.c_str(), a.name.length());
mysql_real_escape_string(&log_db, formula_escaped, a.formula.c_str(), a.formula.length());
mysql_real_escape_string(&log_db, grp_escaped, a.grp.c_str(), a.grp.length());
mysql_real_escape_string(&log_db, msg_escaped, a.msg.c_str(), a.msg.length());
mysql_real_escape_string(&log_db, level_escaped, a.level.c_str(), a.level.length());
mysql_real_escape_string(&log_db, action_escaped, a.action.c_str(), a.action.length());
mysql_real_escape_string(&log_db, instance_escaped, m_instance_name.c_str(), m_instance_name.length());
char *tmp_name_escaped;
ostringstream tmp_names;
for(vector<string>::iterator it=a.alm_list.begin(); it!=a.alm_list.end(); it++)
{
tmp_name_escaped = new char [2 * it->length() + 1];
mysql_real_escape_string(&log_db, tmp_name_escaped, it->c_str(), it->length());
tmp_names << " AND " << DESC_COL_NAME << "!='" << tmp_name_escaped << "'";
delete [] tmp_name_escaped;
}
switch (a.type_log)
{
case TYPE_LOG_STATUS:
//example:
//INSERT INTO alarms
// (time_sec, time_usec, status, ack, id_description, attr_values)
// SELECT 1234567890, 123456, 'ALARM', 'NACK', id_description, 'ev/ev/ev/ev2=1.;' //take id_description
// FROM description //from description
// WHERE name='al/al/al/al' AND active=1 AND instance='alarm_1'; //where this alarm is active
if((a.status.size() == 0) || (a.ack.size() == 0) || (strlen(name_escaped) == 0))
{
err_msg << "log_thread::write_db(): ERROR some mandatory values adding alarm status are empty: status=" <<
a.status << " ack=" << a.ack << " name=" << name_escaped << ends;
break;
}
query_str <<
"INSERT INTO " << m_dbname << "." << STAT_TABLE_NAME <<
" (" << STAT_COL_TIME_S << "," << STAT_COL_TIME_U << "," <<
STAT_COL_STATUS << "," << STAT_COL_ACK << "," <<
STAT_COL_DESC_ID << "," << STAT_COL_VALUES <<
") SELECT " << a.time_s << "," << a.time_us << ",'" <<
a.status << "','" << a.ack << "'," <<
DESC_COL_ID << ",'" << values_escaped << "'" <<
" FROM " << DESC_TABLE_NAME <<
" WHERE " << DESC_COL_NAME << "='" << name_escaped << "'" <<
" AND " << DESC_COL_ACTIVE << "=" << ALARM_ACTIVE <<
" AND " << DESC_COL_INSTANCE << "='" << instance_escaped << "'" <<
ends;
break;
case TYPE_LOG_DESC_ADD:
//example:
//INSERT INTO description
// (name, active, time_sec, formula, time_threashold, level, grp, msg, action, instance)
// SELECT 'al/al/al/al', 'alarm_1', 1, 1234567890, '(ev/ev/ev/evn < 1.2)', 'log', 'gr_none', 'msg'
// FROM description
// WHERE name='al/al/al/al' AND active=1 AND instance='alarm_1' //look if exists an alarm with the same name and active
// HAVING count(*) = 0; //insert only if it does not exist
if((strlen(name_escaped) == 0) || (strlen(instance_escaped) == 0) || (strlen(formula_escaped) == 0) || (strlen(level_escaped) == 0) ||
(strlen(grp_escaped) == 0) || (strlen(msg_escaped) == 0))
{
err_msg << "log_thread::write_db(): ERROR some mandatory values adding alarm description are empty: name=" <<
name_escaped << " instance=" << instance_escaped << " formula=" << formula_escaped << " level=" << level_escaped << " grp=" << grp_escaped <<
" msg=" << msg_escaped << ends;
break;
}
query_str <<
"INSERT INTO " << m_dbname << "." << DESC_TABLE_NAME <<
" (" << DESC_COL_NAME << "," << DESC_COL_ACTIVE << "," <<
DESC_COL_TIME_S << "," << DESC_COL_FORMULA << "," <<
DESC_COL_TIME_THRESHOLD << "," << DESC_COL_LEVEL << "," <<
DESC_COL_GRP << "," << DESC_COL_MSG << "," <<
DESC_COL_ACTION << "," << DESC_COL_INSTANCE << "," <<
DESC_COL_SILENT_TIME <<
") SELECT '" << name_escaped << "'," << ALARM_ACTIVE << "," <<
a.time_s << ",'" << formula_escaped << "','" <<
a.time_threshold << "','" << level_escaped << "','" <<
grp_escaped << "','" << msg_escaped << "','" <<
action_escaped << "','" <<instance_escaped << "','" <<
a.silent_time << "'" <<
" FROM " << DESC_TABLE_NAME <<
" WHERE " << DESC_COL_NAME << "='" << name_escaped << "'" <<
" AND " << DESC_COL_ACTIVE << "=" << ALARM_ACTIVE <<
" AND " << DESC_COL_INSTANCE << "='" << instance_escaped << "'" <<
" HAVING COUNT(*) = 0" <<
ends;
break;
case TYPE_LOG_DESC_DIS:
//example:
//UPDATE description
// SET active=0 //set active to 0
// WHERE name='al/al/al/al' AND active=1 AND instance='alarm_1'; //in alarm specified that is active
if(strlen(name_escaped) == 0 || strlen(instance_escaped) == 0)
{
err_msg << "log_thread::write_db(): ERROR some mandatory values setting non-active alarm are empty: name=" <<
name_escaped << " instance=" << instance_escaped << ends;
break;
}
query_str <<
"UPDATE " << m_dbname << "." << DESC_TABLE_NAME <<
" SET " << DESC_COL_ACTIVE << "=" << ALARM_REMOVED <<
" WHERE " << DESC_COL_NAME << "='" << name_escaped << "'" <<
" AND " << DESC_COL_ACTIVE << "=" << ALARM_ACTIVE <<
" AND " << DESC_COL_INSTANCE << "='" << instance_escaped << "'" <<
ends;
break;
case TYPE_LOG_DESC_REM:
//example:
//DELETE FROM description
// WHERE name='al/al/al/al' AND active=1 AND instance='alarm_1'; //in alarm specified that is active
if(strlen(name_escaped) == 0 || strlen(instance_escaped) == 0)
{
err_msg << "log_thread::write_db(): ERROR some mandatory values removing alarm are empty: name=" <<
name_escaped << " instance=" << instance_escaped<< ends;
break;
}
query_str <<
"DELETE FROM " << m_dbname << "." << DESC_TABLE_NAME <<
" WHERE " << DESC_COL_NAME << "='" << name_escaped << "'" <<
" AND " << DESC_COL_ACTIVE << "=" << ALARM_ACTIVE <<
" AND " << DESC_COL_INSTANCE << "='" << instance_escaped << "'" <<
ends;
break;
case TYPE_LOG_DESC_SYNC:
//example:
//UPDATE description
// SET active=0
// WHERE name='al/al/al/al' //disable this alarm
// AND active=1 //if it is active and
// AND instance='alarm_1' //for this alarm instance and
// AND (formula!='(ev/ev/ev/ev > 1)' //or formula is changed
// OR time_threashold!=5 //or time_threshold is changed
// OR level!='log' //or level is changed
// OR grp!='gr_none' //or grp is changed
// OR msg!='message'); //or msg is changed
// OR action!='act/act/act/act'); //or action is changed
query_str <<
"UPDATE " << m_dbname << "." << DESC_TABLE_NAME <<
" SET " << DESC_COL_ACTIVE << "=" << ALARM_REMOVED <<
" WHERE " << DESC_COL_NAME << "='" << name_escaped << "'" <<
" AND " << DESC_COL_ACTIVE << "=" << ALARM_ACTIVE <<
" AND " << DESC_COL_INSTANCE << "='" << instance_escaped << "'" <<
" AND (" << DESC_COL_FORMULA << "!='" << formula_escaped << "'" <<
" OR " << DESC_COL_TIME_THRESHOLD << "!='" << a.time_threshold << "'" <<
" OR " << DESC_COL_LEVEL << "!='" << level_escaped << "'" <<
" OR " << DESC_COL_GRP << "!='" << grp_escaped << "'" <<
" OR " << DESC_COL_MSG << "!='" << msg_escaped << "'" <<
" OR " << DESC_COL_ACTION << "!='" << action_escaped << "'" <<
")" <<
ends;
break;
case TYPE_LOG_DESC_UPD_OLD:
//example:
//UPDATE description
// SET active=0
// WHERE name!='al1/al1/al1/al1' //disable every alarm not in this list
// AND name !='al2/al2/al2/al2'
// AND name !=...
// AND active=1 //if it is active
// AND instance='alarm_1'
query_str <<
"UPDATE " << m_dbname << "." << DESC_TABLE_NAME <<
" SET " << DESC_COL_ACTIVE << "=" << ALARM_REMOVED <<
" WHERE " << DESC_COL_ACTIVE << "=" << ALARM_ACTIVE <<
" AND " << DESC_COL_INSTANCE << "='" << instance_escaped << "'" <<
tmp_names.str() <<
ends;
break;
case TYPE_LOG_DESC_UPDATE:
//example:
//UPDATE description
// SET time_sec=1234567890, time_threashold=1, level='log', grp='gr_none', msg='msg'
// WHERE name='al1/al1/al1/al1' //
// AND active=1 //
// AND instance='alarm_1'
query_str <<
"UPDATE " << m_dbname << "." << DESC_TABLE_NAME <<
" SET " << DESC_COL_TIME_S << "=" << a.time_s <<
" , " << DESC_COL_TIME_THRESHOLD << "=" << a.time_threshold <<
" , " << DESC_COL_LEVEL << "='" << level_escaped << "'" <<
" , " << DESC_COL_GRP << "='" << grp_escaped << "'" <<
" , " << DESC_COL_MSG << "='" << msg_escaped << "'" <<
" , " << DESC_COL_ACTION << "='" << action_escaped << "'" <<
" , " << DESC_COL_SILENT_TIME << "='" << a.silent_time << "'" <<
" WHERE " << DESC_COL_NAME << "='" << name_escaped << "'" <<
" AND " << DESC_COL_ACTIVE << "=" << ALARM_ACTIVE <<
" AND " << DESC_COL_INSTANCE << "='" << instance_escaped << "'" <<
ends;
break;
}
delete [] values_escaped;
delete [] name_escaped;
delete [] formula_escaped;
delete [] grp_escaped;
delete [] msg_escaped;
delete [] level_escaped;
delete [] action_escaped;
delete [] instance_escaped;
if(err_msg.str().size() != 0)
{
cout << err_msg.str();
return;
}
if(mysql_query(&log_db, query_str.str().c_str()))
{
err_msg << " log_thread::write_db(): ERROR in query=" << query_str.str() << endl;
//cout << err_msg.str();
//throw err_msg.str();
}
if(err_msg.str().size() != 0)
{
cout << gettime().tv_sec << err_msg.str();
return;
}
int num_rows = mysql_affected_rows(&log_db);
#ifdef _DEBUG_LOG_THREAD
cout << gettime().tv_sec << " log_thread::write_db(): Affected rows=" << num_rows << " in query=" << query_str.str() << endl;
#else
if(((a.type_log == TYPE_LOG_STATUS) || (a.type_log == TYPE_LOG_DESC_DIS)) && (num_rows != 1))
cout << gettime().tv_sec << " log_thread::write_db(): Error num_rows=" << num_rows << " in query=" << query_str.str() << endl;
#endif
}
void log_thread::get_alarm_list(vector<string> &al_list)
{
ostringstream query_str;
ostringstream err_msg;
MYSQL_RES *res;
MYSQL_ROW row;
char *instance_escaped = new char [2 * m_instance_name.length() + 1];
mysql_real_escape_string(&log_db, instance_escaped, m_instance_name.c_str(), m_instance_name.length());
// unsigned int num_fields;
// unsigned int i;
//example:
//SELECT description
// CONCAT('\t',name,'\t',formula,
// '\t',IFNULL(time_threshold,0),'\t',level,
// '\t',grp,'\t','\"',IFNULL(msg,''),'\"',
// '\t',IFNULL(action,''))
// FROM alarm.description
// WHERE active=1
// AND instance='alarm_1'
query_str <<
"SELECT" <<
" CONCAT('\t', " << DESC_COL_NAME << ",'\t'," << DESC_COL_FORMULA <<
",'\t'," << "IFNULL(" << DESC_COL_TIME_THRESHOLD << ",0)" << ",'\t'," << DESC_COL_LEVEL <<
",'\t'," << "IFNULL(" << DESC_COL_SILENT_TIME << ",-1)" <<
",'\t'," << DESC_COL_GRP << ",'\t','\"'," << "IFNULL(" << DESC_COL_MSG << ",'')" <<
",'\"','\t'," << "IFNULL(" << DESC_COL_ACTION << ",';')" << ")" <<
" FROM " << m_dbname << "." << DESC_TABLE_NAME <<
" WHERE " << DESC_COL_ACTIVE << "=" << ALARM_ACTIVE <<
" AND " << DESC_COL_INSTANCE << "='" << instance_escaped << "'" <<
ends;
delete [] instance_escaped;
if(mysql_query(&log_db, query_str.str().c_str()))
{
err_msg << "log_thread::get_alarm_list(): ERROR in query=" << query_str.str() << endl;
//cout << err_msg.str();
throw err_msg.str();
}
//#define _DEBUG_LOG_THREAD 1
#ifdef _DEBUG_LOG_THREAD
else
cout << gettime().tv_sec << " log_thread::get_alarm_list(): Success with query=" << query_str.str() << endl;
#endif //_DEBUG_LOG_THREAD
res = mysql_use_result(&log_db);
if(res == NULL)
{
if(*mysql_error(&log_db))
err_msg << "log_thread::get_alarm_list(): ERROR while retrieving result, err=" << mysql_error(&log_db) << endl;
else
err_msg << "log_thread::get_alarm_list(): ERROR while retrieving result" << endl;
//cout << err_msg.str();
throw err_msg.str();
}
//num_fields = mysql_num_fields(res);
while ((row = mysql_fetch_row(res)))
{
al_list.push_back(row[0]);
#ifdef _DEBUG_LOG_THREAD
cout << gettime().tv_sec << " log_thread::get_alarm_list(): Retrieved line: " << row[0] << endl;
#endif //_DEBUG_LOG_THREAD
}
mysql_free_result(res);
}
/*
* alarm_list class methods
*/
void alarm_list::push_back(alm_log_t& a)
{
this->lock();
try{
l_alarm.push_back(a);
empty.signal();
}
catch(omni_thread_fatal& ex)
{
ostringstream err;
err << "omni_thread_fatal exception signaling omni_condition, err=" << ex.error << ends;
//WARN_STREAM << "alarm_list::push_back(): " << err.str() << endl;
printf("alarm_list::push_back(): %s", err.str().c_str());
}
catch(Tango::DevFailed& ex)
{
ostringstream err;
err << "exception signaling omni_condition: '" << ex.errors[0].desc << "'" << ends;
//WARN_STREAM << "alarm_list::push_back(): " << err.str() << endl;
printf("alarm_list::push_back: %s", err.str().c_str());
Tango::Except::print_exception(ex);
}
catch(...)
{
//WARN_STREAM << "alarm_list::push_back(): catched unknown exception!!" << endl;
printf("alarm_list::push_back(): catched unknown exception signaling omni_condition!!");
}
this->unlock();
}
const alm_log_t alarm_list::pop_front(void)
{
this->lock();
//omni_mutex_lock l((omni_mutex)this); //call automatically unlock on destructor and on exception
try{
while (l_alarm.empty() == true)
empty.wait(); //wait release mutex while is waiting, then reacquire when signaled
}
catch(omni_thread_fatal& ex)
{
ostringstream err;
err << "omni_thread_fatal exception waiting on omni_condition, err=" << ex.error << ends;
//WARN_STREAM << "alarm_list::pop_front(): " << err.str() << endl;
printf("alarm_list::pop_front(): %s", err.str().c_str());
alm_log_t a;
this->unlock();
sleep(1);
return(a);
}
catch(Tango::DevFailed& ex)
{
ostringstream err;
err << "exception waiting on omni_condition: '" << ex.errors[0].desc << "'" << ends;
//WARN_STREAM << "alarm_list::pop_front(): " << err.str() << endl;
printf("alarm_list::pop_front: %s", err.str().c_str());
Tango::Except::print_exception(ex);
alm_log_t a;
this->unlock();
sleep(1);
return(a);
}
catch(...)
{
//WARN_STREAM << "alarm_list::pop_front(): catched unknown exception!!" << endl;
printf("alarm_list::pop_front(): catched unknown exception waiting on omni_condition!!");
alm_log_t a;
this->unlock();
sleep(1);
return(a);
}
/*const*/ alm_log_t a;
a = *(l_alarm.begin());
l_alarm.pop_front();
this->unlock();
return(a);
}
void alarm_list::clear(void)
{
//this->lock();
l_alarm.clear();
//this->unlock();
}
list<alm_log_t> alarm_list::show(void)
{
list<alm_log_t> al;
this->lock();
al = l_alarm;
this->unlock();
return(al);
}
/*
* log_thread.h
*
* $Author: graziano $
*
* $Revision: 1.4 $
*
* $Log: log_thread.h,v $
*
*
* copyleft: Sincrotrone Trieste S.C.p.A. di interesse nazionale
* Strada Statale 14 - km 163,5 in AREA Science Park
* 34012 Basovizza, Trieste ITALY
*/
#ifndef LOG_THREAD_H
#define LOG_THREAD_H
#include <omnithread.h>
#include <tango.h>
#include <Alarm.h>
#include <mysql.h>
#define LOG_THREAD_EXIT "log_thread_exit"
#define LOG_THREAD_EXIT_TIME 1
//############# DB ############
//#define LOG_DB_NAME "alarm"
//######## ALARM_DESC ########
#define DESC_TABLE_NAME "description"
#define DESC_COL_ID "id_description"
#define DESC_COL_NAME "name"
#define DESC_COL_INSTANCE "instance"
#define DESC_COL_ACTIVE "active"
#define DESC_COL_TIME_S "time_sec"
#define DESC_COL_FORMULA "formula"
#define DESC_COL_SILENT_TIME "silent_time"
#define DESC_COL_TIME_THRESHOLD "time_threshold"
#define DESC_COL_LEVEL "level"
#define DESC_COL_GRP "grp"
#define DESC_COL_MSG "msg"
#define DESC_COL_ACTION "action"
//######## ALARM_STATUS #######
#define STAT_TABLE_NAME "alarms"
#define STAT_COL_ID "id_alarms"
#define STAT_COL_TIME_S "time_sec"
#define STAT_COL_TIME_U "time_usec"
#define STAT_COL_STATUS "status"
#define STAT_COL_ACK "ack"
#define STAT_COL_DESC_ID DESC_COL_ID
#define STAT_COL_VALUES "attr_values"
#define TYPE_LOG_STATUS 1
#define TYPE_LOG_DESC_ADD 2
#define TYPE_LOG_DESC_DIS 3
#define TYPE_LOG_DESC_REM 4
#define TYPE_LOG_DESC_SYNC 5
#define TYPE_LOG_DESC_UPD_OLD 6
#define TYPE_LOG_DESC_UPDATE 7
#define ALARM_ACTIVE 1
#define ALARM_REMOVED 0
typedef struct {
unsigned int type_log;
unsigned int time_s;
unsigned int time_us;
unsigned int time_threshold;
int silent_time;
string name;
string status;
string ack;
string level;
string grp;
string msg;
string formula;
string action;
string values;
vector<string> alm_list;
} alm_log_t;
/*
* here Alarm insert data to log, log_thread process data
* and store in db
*/
class alarm_list : public omni_mutex {
public:
alarm_list(void): full(this), empty(this) {}
~alarm_list(void) {}
void push_back(alm_log_t& a);
const alm_log_t pop_front(void);
void clear(void);
list<alm_log_t> show(void);
protected:
list<alm_log_t> l_alarm;
private:
omni_condition full,
empty;
};
class log_thread : public omni_thread/*, public Tango::LogAdapter*/
{
public:
log_thread(string dbhost, string dbuser, string dbpw, string dbname, int dbport, string instance_name/*, Alarm_ns::Alarm *p*/);
~log_thread();
void log_alarm_db(alm_log_t& a);
void get_alarm_list(vector<string> &al_list);
protected:
void run(void *);
private:
//Alarm_ns::Alarm *p_Alarm;
MYSQL log_db;
alarm_list al_list;
string m_dbhost;
string m_dbuser;
string m_dbpw;
string m_dbname;
int m_dbport;
string m_instance_name;
void write_db(alm_log_t& a);
};
#endif /* LOG_THREAD_H */
/* EOF */
/*----- PROTECTED REGION ID(Alarm::main.cpp) ENABLED START -----*/
static const char *RcsId = "$Id: $";
/*----- PROTECTED REGION ID(AlarmHandler::main.cpp) ENABLED START -----*/
//=============================================================================
//
// file : main.cpp
//
// description : C++ source for the Alarm device server main.
// description : C++ source for the AlarmHandler device server main.
// The main rule is to initialise (and create) the Tango
// system and to create the DServerClass singleton.
// The main should be the same for every Tango device server.
//
// project : alarm
// project : Elettra alarm handler device server
//
// This file is part of Tango device class.
//
......@@ -26,38 +25,40 @@ static const char *RcsId = "$Id: $";
// You should have received a copy of the GNU General Public License
// along with Tango. If not, see <http://www.gnu.org/licenses/>.
//
// $Author: $
//
// $Revision: $
// $Date: $
//
// $HeadURL: $
//
//=============================================================================
// This file is generated by POGO
// (Program Obviously used to Generate tango Object)
//=============================================================================
#include <tango/tango.h>
// Check if crash reporting is used.
#if defined(ENABLE_CRASH_REPORT)
# include <crashreporting/crash_report.h>
#else
# define DECLARE_CRASH_HANDLER
# define INSTALL_CRASH_HANDLER
#endif
DECLARE_CRASH_HANDLER;
#include <tango.h>
#ifndef TANGO_LOG
#define TANGO_LOG cout
#endif
int main(int argc,char *argv[])
{
Tango::Util *tg;
using std::endl;
using std::bad_alloc;
INSTALL_CRASH_HANDLER
try
{
// Initialise the device server
//----------------------------------------
tg = Tango::Util::init(argc,argv);
Tango::Util *tg = Tango::Util::init(argc,argv);
/*
* serialize all calls
* BY_DEVICE, BY_CLASS, BY_PROCESS
*/
//tg->set_serial_model(Tango::BY_PROCESS);
// Create the device server singleton
// which will create everything
//----------------------------------------
......@@ -65,24 +66,23 @@ int main(int argc,char *argv[])
// Run the endless loop
//----------------------------------------
cout << "Ready to accept request" << endl;
TANGO_LOG << "Ready to accept request" << endl;
tg->server_run();
}
catch (bad_alloc)
catch (bad_alloc &)
{
cout << "Can't allocate memory to store device object !!!" << endl;
cout << "Exiting" << endl;
TANGO_LOG << "Can't allocate memory to store device object !!!" << endl;
TANGO_LOG << "Exiting" << endl;
}
catch (CORBA::Exception &e)
{
Tango::Except::print_exception(e);
cout << "Received a CORBA_Exception" << endl;
cout << "Exiting" << endl;
TANGO_LOG << "Received a CORBA_Exception" << endl;
TANGO_LOG << "Exiting" << endl;
}
tg->server_cleanup();
Tango::Util::instance()->server_cleanup();
return(0);
}
/*----- PROTECTED REGION END -----*/ // Alarm::main.cpp
/*----- PROTECTED REGION END -----*/ // AlarmHandler::main.cpp
/*
* update-thread.cpp
*
* $Author: claudio $
*
* $Revision: 1.2 $
*
* $Log: update-thread.cpp,v $
* Revision 1.2 2013-03-06 10:38:43 claudio
* commented out debug print statements
*
* Revision 1.1 2008-11-10 10:54:09 graziano
* thread for update of alarms with time threshold > 0
*
*
*
*
* copyleft: Sincrotrone Trieste S.C.p.A. di interesse nazionale
* Strada Statale 14 - km 163,5 in AREA Science Park
* 34012 Basovizza, Trieste ITALY
*/
#include "update-thread.h"
......@@ -26,9 +8,9 @@ static const char __FILE__rev[] = __FILE__ " $Revision: 1.2 $";
/*
* alarm_thread::alarm_thread()
*/
update_thread::update_thread(Alarm_ns::Alarm *p) : p_Alarm(p)
update_thread::update_thread(AlarmHandler_ns::AlarmHandler *p) : p_Alarm(p),Tango::LogAdapter(p)
{
//cout << __FILE__rev << endl;
//TANGO_LOG << __FILE__rev << endl;
}
/*
......@@ -36,6 +18,7 @@ update_thread::update_thread(Alarm_ns::Alarm *p) : p_Alarm(p)
*/
update_thread::~update_thread()
{
DEBUG_STREAM << __func__ << "update_thread::~update_thread(): entering!" << endl;
p_Alarm = NULL;
}
......@@ -44,6 +27,7 @@ update_thread::~update_thread()
*/
void update_thread::run(void *)
{
DEBUG_STREAM << __func__ << "update_thread::run(): entering!" << endl;
//printf("update_thread::run(): running...\n");
unsigned int pausasec, pausanano;
pausasec=1;
......@@ -52,14 +36,23 @@ void update_thread::run(void *)
while (!p_Alarm->abortflag) {
try
{
omni_thread::sleep(pausasec,pausanano);
p_Alarm->timer_update();
//omni_thread::sleep(pausasec,pausanano);
abort_sleep(pausasec+(double)pausanano/1000000000);
if(!p_Alarm->abortflag)
p_Alarm->timer_update();
//printf("update_thread::run(): TIMER!!\n");
}
catch(...)
{
printf("update_thread::run(): catched unknown exception!!\n");
INFO_STREAM << "update_thread::run(): catched unknown exception!!";
}
}
//cout << "update_thread::run(): exiting!" << endl;
DEBUG_STREAM << "update_thread::run(): exiting!" << endl;
} /* update_thread::run() */
void update_thread::abort_sleep(double time)
{
omni_mutex_lock sync(*this);
long time_millis = (long)(time*1000);
int res = wait(time_millis);
}
/*
* alarm-thread.h
*
* $Author: graziano $
*
* $Revision: 1.1 $
*
* $Log: update-thread.h,v $
* Revision 1.1 2008-11-10 10:54:09 graziano
* thread for update of alarms with time threshold > 0
*
*
*
*
* copyleft: Sincrotrone Trieste S.C.p.A. di interesse nazionale
* Strada Statale 14 - km 163,5 in AREA Science Park
* 34012 Basovizza, Trieste ITALY
* update-thread.h
*/
#ifndef UPDATE_THREAD_H
#define UPDATE_THREAD_H
#include <omnithread.h>
#include <tango.h>
#include <Alarm.h>
#include <tango/tango.h>
#include <AlarmHandler.h>
class update_thread : public omni_thread {
class update_thread : public omni_thread, public Tango::TangoMonitor, public Tango::LogAdapter {
public:
update_thread(Alarm_ns::Alarm *p);
update_thread(AlarmHandler_ns::AlarmHandler *p);
~update_thread();
protected:
void run(void *);
private:
Alarm_ns::Alarm *p_Alarm;
void abort_sleep(double time);
AlarmHandler_ns::AlarmHandler *p_Alarm;
};
#endif /* UPDATE_THREAD_H */
......
cmake_minimum_required(VERSION 3.2)
project(test NONE)
include(ExternalProject)
ExternalProject_Add(testdevice
SOURCE_DIR ${CMAKE_SOURCE_DIR}/test/testdevice
# PREFIX ${CMAKE_BINARY_DIR}
CMAKE_ARGS "-DCMAKE_INSTALL_PREFIX=${CMAKE_BINARY_DIR}"
# INSTALL_DIR ${CMAKE_BINARY_DIR}
# BINARY_DIR ${CMAKE_BINARY_DIR}
# STEP_TARGETS build
# EXCLUDE_FROM_ALL TRUE
)
ExternalProject_Get_property(testdevice SOURCE_DIR)
message("Source dir of testdevice = ${SOURCE_DIR}")
ExternalProject_Get_property(testdevice INSTALL_DIR)
message("Install dir of testdevice = ${INSTALL_DIR}")
ExternalProject_Get_property(testdevice BINARY_DIR)
message("Binary dir of testdevice = ${BINARY_DIR}")
ExternalProject_Get_property(testdevice CMAKE_ARGS)
message("CMqke args for testdevice = ${CMAKE_ARGS}")
#ExternalProject_Get_property(testdevice PREFIX)
#message("Prefix dir of testdevice = ${PREFIX}")
{
"_version": 1,
"_source": "ConfigInjectorDiag.xls",
"_title": "hdbpp mysql innodb test",
"_date": "2020-07-07 14:45:04",
"servers": {
"alarm-handler-srv/01": {
"AlarmHandler": {
"alarm/handler/01": {
"properties": {
},
"attribute_properties": {
}
}
}
},
"testdevice-srv/01": {
"TestDevice": {
"alarm/test/01": {
"properties": {
"Attr_config": [
"condition:bool:0:0.0"
]
},
"attribute_properties": {
}
}
}
}
},
"classes": {
"AlarmHandler": {
"properties": {
"GroupNames": ["gr_none","gr_test"],
"StatisticsTimeWindow": ["60"],
"SubscribeRetryPeriod": ["30"]
}
},
"TestDevice": {
"properties": {
}
}
}
}
#!/usr/bin/python
#
import sys,re
#import PyTango
from PyTango import *
import time
import string
if __name__ == "__main__":
Device = False
Conf = False
File = False
conflist = []
#PrepareState = False
for arg in sys.argv:
word = '([a-z0-9._\-\*]*)'
wordpath = '([a-z0-9._\-\*/]*)'
m = re.compile("--device=" + word + "/{0,1}" + word + "/{0,1}" + word).match(arg.lower())
if m is not None:
#print m.groups()
domain = m.groups()[0]
family = m.groups()[1]
member = m.groups()[2]
if domain == '':
domain = '*'
if family == '':
family = '*'
if member == '':
member = '*'
Device = True
#formula = '([a-z0-9._,\*,\-,\|,\/,\",\s,\t]*)'
formula = '(.*)'
m = re.compile("--conf=" + formula).match(arg)
if m is not None:
#print m.groups()
alarm_rule = m.groups()[0]
Conf = True
#m = re.compile("--prepare_state").match(arg.lower())
#if m is not None:
# PrepareState = True
m = re.compile("--file=" + wordpath).match(arg)
if m is not None:
#print m.groups()
file_name = m.groups()[0]
File = True
tagchars = '([a-zA-Z0-9._-]*)'
tag=''
if Device:
if Conf or File:
dev_name = domain + '/' + family + '/' + member
try:
dev = DeviceProxy(dev_name)
except (DevFailed,ConnectionFailed,EventSystemFailed) as e:
print ('ERROR connecting proxy(',dev_name,'): ',e[0].desc)
sys.exit(-1)
if Conf:
m = re.compile("tag=" + tagchars + ";(.*)").match(alarm_rule)
if m is not None:
try:
tag = m.groups()[0]
conflist = dev.command_inout('SearchAlarm',tag)
except (DevFailed,ConnectionFailed,EventSystemFailed) as e:
print (' ---> ERROR: ', e[0].desc)
sys.exit(1)
for co in conflist:
if co == alarm_rule:
print ('Found matching alarm: ', co)
sys.exit(0)
print ('Not found conf for alarm ', tag)
sys.exit(1)
elif File:
for line in open(file_name):
line = line[0:-1]
m = re.compile("tag=" + tagchars + ";(.*)").match(line)
conf_found = False
if m is not None:
try:
tag = m.groups()[0]
conflist = dev.command_inout('SearchAlarm',tag)
except (DevFailed,ConnectionFailed,EventSystemFailed) as e:
print (' ---> ERROR: ', e[0].desc)
sys.exit(1)
for co in conflist:
if co == alarm_rule:
conf_found = True
if not conf_found:
print ('Not found conf for alarm ', tag)
sys.exit(1)
sys.exit(0)
if len(sys.argv) < 3:
print ('Usage:', sys.argv[0], ' --device=alarm_device --conf=alarm_rule | --file=filename')
print ()
print ('Examples:')
print ('\tcheck one alarm_rule in alarm/handler/01:', sys.argv[0], '--device=alarm/handler/01 --conf=\"tag=test0;formula=(alarm/test/01/condition == 1);on_delay=0;off_delay=0;priority=high;shlvd_time=0;group=gr_test;message=Test alarm;url=;on_command=;off_command=;enabled=1\"')
print ('\tcheck alarm rules from filename in alarm/handler/01:', sys.argv[0], '--device=alarm/handler/01 --file=alarms.txt')
sys.exit(-1)
# EOF
#!/usr/bin/python
#
import sys,re
#import PyTango
from PyTango import *
import time
import string
if __name__ == "__main__":
Device = False
Conf = False
File = False
#PrepareState = False
for arg in sys.argv:
word = '([a-z0-9._\-\*]*)'
wordpath = '([a-z0-9._\-\*/]*)'
m = re.compile("--device=" + word + "/{0,1}" + word + "/{0,1}" + word).match(arg.lower())
if m is not None:
domain = m.groups()[0]
family = m.groups()[1]
member = m.groups()[2]
if domain == '':
domain = '*'
if family == '':
family = '*'
if member == '':
member = '*'
Device = True
#formula = '([a-z0-9._,\*,\-,\|,\/,\",\s,\t]*)'
formula = '(.*)'
m = re.compile("--conf=" + formula).match(arg)
if m is not None:
alarm_rule = m.groups()[0]
Conf = True
#m = re.compile("--prepare_state").match(arg.lower())
#if m is not None:
# PrepareState = True
m = re.compile("--file=" + wordpath).match(arg)
if m is not None:
file_name = m.groups()[0]
File = True
if Device:
if Conf or File:
dev_name = domain + '/' + family + '/' + member
try:
dev = DeviceProxy(dev_name)
except (DevFailed,ConnectionFailed,EventSystemFailed) as e:
print ('ERROR connecting proxy(',dev_name,'): ',e[0].desc)
sys.exit(-1)
if Conf:
print ('Loading: ', alarm_rule)
try:
dev.command_inout('Load',alarm_rule)
print ('.............OK!')
except (DevFailed,ConnectionFailed,EventSystemFailed) as e:
print ('...........ERROR!')
print (' ---> ERROR: ', e[0].desc)
continue
sys.exit(0)
elif File:
for line in open(file_name):
line = line[0:-1]
try:
dev.command_inout('Load',line)
time.sleep(0.1)
except (DevFailed,ConnectionFailed,EventSystemFailed) as e:
print (' ---> ERROR: ', e[0].desc)
time.sleep(2)
sys.exit(1)
sys.exit(0)
#dev = DeviceProxy("alarm/alarm/1")
#dev.command_inout('Load', sys.argv[1])
if len(sys.argv) < 3:
print ('Usage:', sys.argv[0], ' --device=alarm_device --conf=alarm_rule | --file=filename')
print ()
print ('Examples:')
print ('\tload one alarm_rule in alarm/handler/01:', sys.argv[0], '--device=alarm/handler/01 --conf=\"tag=test0;formula=(alarm/test/01/condition == 1);on_delay=0;off_delay=0;priority=high;shlvd_time=0;group=gr_test;message=Test alarm;url=;on_command=;off_command=;enabled=1\"')
print ('\tload alarm rules from filename in alarm/handler/01:', sys.argv[0], '--device=alarm/handler/01 --file=alarms.txt')
sys.exit(-1)
# EOF
# Functions and Pre-build -----------------------------------
# Stop messy in source builds
set(CMAKE_DISABLE_IN_SOURCE_BUILD ON)
set(CMAKE_DISABLE_SOURCE_CHANGES OFF)
if ( ${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_BINARY_DIR} )
message( FATAL_ERROR "In-source builds not allowed. Please make a new directory (called a build directory) and run CMake from there. You may need to remove CMakeCache.txt." )
endif()
# Start Build Config -----------------------------------
cmake_minimum_required(VERSION 3.8)
set(CMAKE_SKIP_RPATH true)
set(CMAKE_VERBOSE_MAKEFILE ON)
set(CMAKE_COLOR_MAKEFILE ON)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
# Output name for the final binary
set(DEV_NAME "testdevice-srv")
# Versioning
set(VERSION_MAJOR "1")
set(VERSION_MINOR "0")
set(VERSION_PATCH "0")
set(VERSION_METADATA "")
set(VERSION_STRING ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH})
# Add any include paths from the command line
list(APPEND INCLUDE_PATHS ${CMAKE_INCLUDE_PATH})
list(APPEND INCLUDE_PATHS ${CMAKE_SOURCE_DIR})
list(APPEND LIBRARY_PATHS ${CMAKE_LIBRARY_PATH})
# Start the project
project(testdevice VERSION ${VERSION_STRING} LANGUAGES CXX)
# Build options
# arch install definitions
include(GNUInstallDirs)
message(STATUS "Searching for libraries...")
# Variable to contain a list of all the libs we depend on
set(AH_LIBRARIES)
# allow pkg-config to search the CMAKE_PREFIX_PATH
set(PKG_CONFIG_USE_CMAKE_PREFIX_PATH ON)
list(APPEND CMAKE_PREFIX_PATH "/usr")
# Find Dependencies -----------------------------------
# Find tango if it has not already been found. Returns an interface library
# called TangoInterfaceLibrary
set(CMAKE_MODULE_PATH "${CMAKE_MODULE_PATH};${CMAKE_CURRENT_SOURCE_DIR}/cmake")
find_package(Tango)
# Source -----------------------------------
add_subdirectory(src)
# Build Targets -----------------------------------
# Executable --------
add_executable(testdevice ${SRC_FILES})
target_link_libraries(testdevice
PRIVATE
TangoInterfaceLibrary
)
target_include_directories(testdevice
PRIVATE
$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/src>
${INCLUDE_PATHS}
"${PROJECT_BINARY_DIR}"
)
if(NOT (CMAKE_CXX_COMPILER_ID STREQUAL "AppleClang" OR CMAKE_CXX_COMPILER_ID STREQUAL "Clang"))
set_target_properties(testdevice
PROPERTIES
OUTPUT_NAME ${DEV_NAME}
LINK_FLAGS "-Wl,--no-undefined"
CXX_STANDARD 17)
else()
set_target_properties(testdevice
PROPERTIES
OUTPUT_NAME ${DEV_NAME}
LINK_FLAGS ""
CXX_STANDARD 17)
endif()
target_compile_options(testdevice
PRIVATE "$<$<CONFIG:DEBUG>:-g>")
# Install Config -----------------------------------
install(
TARGETS testdevice
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR})
message(STATUS "Configured testdevice project")
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
GCCMAJOR := $(shell ${CXX} -dumpversion | cut -d"." -f1)
GCCMINOR := $(shell ${CXX} -dumpversion | cut -d"." -f2)
MACHINE := $(shell ${CXX} -dumpmachine)
TANGO_DIR := /usr/local/tango-9.3.4
OMNIORB_DIR := /usr/local/omniorb-4.2.3
ZMQ_DIR := /usr/local/zeromq-4.0.8
RUNTIME_DIR := /runtime
TANGO_INC := ${TANGO_DIR}/include/tango
LOG4TANGO_INC := ${TANGO_DIR}/include
OMNIORB_INC := ${OMNIORB_DIR}/include
ZMQ_INC := ${ZMQ_DIR}/include
RUNTIME_INC := ${RUNTIME_DIR}/include
TANGO_LIB = ${TANGO_DIR}/lib
OMNIORB_LIB = ${OMNIORB_DIR}/lib
ZMQ_LIB = ${ZMQ_DIR}/lib
RUNTIME_LIB = ${RUNTIME_DIR}/lib
ifeq ($(SDKTARGETSYSROOT),)
ifeq ($(GCCMAJOR),4)
ifeq ($(shell test $(GCCMINOR) -lt 4; echo $$?),0)
CXXFLAGS += -std=gnu++98
else
CXXFLAGS += -std=c++0x
endif
else
CXXFLAGS += -std=c++11
endif
INC_DIR = -I${TANGO_INC} -I${LOG4TANGO_INC} -I${OMNIORB_INC} -I${ZMQ_INC} -I${RUNTIME_INC}
LIB_DIR = -L${TANGO_LIB} -L${OMNIORB_LIB} -L${ZMQ_LIB} -L${RUNTIME_LIB} -L/usr/local/lib
else
CXXFLAGS += -std=gnu++11
INC_DIR = -I${SDKTARGETSYSROOT}/usr/include/tango
endif
#-----------------------------------------
# Default make entry
#-----------------------------------------
default: release
release debug: bin/$(NAME_SRV)
all: default
#-----------------------------------------
# Set CXXFLAGS and LDFLAGS
#-----------------------------------------
CXXFLAGS += -D__linux__ -D__OSVERSION__=2 -Wall -pedantic \
-Wno-non-virtual-dtor -Wno-long-long -DOMNI_UNLOADABLE_STUBS \
$(INC_DIR) -Isrc
ifeq ($(GCCMAJOR),4)
CXXFLAGS += -Wextra
endif
ifeq ($(GCCMAJOR),5)
CXXFLAGS += -Wextra
endif
LDFLAGS += $(LIB_DIR) -ltango -lomniORB4 -lomniDynamic4 \
-lCOS4 -lomnithread -lzmq
#-----------------------------------------
# Set dependencies
#-----------------------------------------
SRC_FILES += $(wildcard src/*.cpp)
OBJ_FILES += $(addprefix obj/,$(notdir $(SRC_FILES:.cpp=.o)))
obj/%.o: $(SRC_FILES:%.cpp)
$(CXX) $(CXXFLAGS) -c -o $@ $<
.nse_depinfo: $(SRC_FILES)
@$(CXX) $(CXXFLAGS) -M -MM $^ | sed 's/\(.*\)\.o/obj\/\1.o/g' > $@
-include .nse_depinfo
#-----------------------------------------
# Main make entries
#-----------------------------------------
bin/$(NAME_SRV): bin obj $(OBJ_FILES)
$(CXX) $(CXXFLAGS) $(OBJ_FILES) -o bin/$(NAME_SRV) $(LDFLAGS)
clean:
@rm -fr obj/ bin/ core* .nse_depinfo src/*~
bin obj:
@ test -d $@ || mkdir $@
#-----------------------------------------
# Target specific options
#-----------------------------------------
release: CXXFLAGS += -O2 -DNDEBUG
release: LDFLAGS += -s
debug: CXXFLAGS += -ggdb3
.PHONY: clean
NAME_SRV = testdevice-srv
CXXFLAGS =
LDFLAGS =
include ./Make-9.3.4.in
# Project Name
testdevice
## Description
Tango device server for storing and distributing a number of variables as device attributes.
## Installation
See your institue guidelines for deploying and configuring a Tango device server.
## Usage
The server is dynamically configured by means of dedicated Methods. The configuration and values are stored in the Tango Database and restored at server restart.
A typical usage is to store and distribute the results of measurments or simulations to a number of differet clients.
## History
## Credits
Elettra-Sincrotrone Trieste S.C.p.A. di interesse nazionale
Strada Statale 14 - km 163,5 in AREA Science Park
34149 Basovizza, Trieste ITALY
## License
GPL 3
include(CMakeParseArguments)
function(find_libraries)
# Parse the parameters
set(MULTIVALUEARGS LIBRARIES SEARCH_PATHS)
cmake_parse_arguments(FIND_LIBRARIES "" "" "${MULTIVALUEARGS}" ${ARGN})
# Clear the found libraries
unset(FOUND_LIBRARIES PARENT_SCOPE)
foreach(LIB ${FIND_LIBRARIES_LIBRARIES})
# try the user provided paths first
find_library(FOUND_LIB_${LIB} ${LIB} PATHS ${FIND_LIBRARIES_SEARCH_PATHS} NO_DEFAULT_PATH)
# if we could not find it, drop to the system paths
if(NOT FOUND_LIB_${LIB})
find_library(FOUND_LIB_${LIB} ${LIB})
endif(NOT FOUND_LIB_${LIB})
if(FOUND_LIB_${LIB})
message(STATUS "Found " ${LIB} " at: " ${FOUND_LIB_${LIB}})
list(APPEND FOUND_LIBRARIES ${FOUND_LIB_${LIB}})
else()
message(FATAL "Could not find " ${LIB})
endif(FOUND_LIB_${LIB})
endforeach(LIB ${LIBRARIES})
set(FOUND_LIBRARIES ${FOUND_LIBRARIES} PARENT_SCOPE)
endfunction(find_libraries)
\ No newline at end of file
if(NOT TARGET TangoInterfaceLibrary)
# Ensure pkg-config is installed
find_package(PkgConfig REQUIRED)
# Now search for the tango.pc file, this is a required dependency
message(STATUS "Search for TANGO package config...")
pkg_search_module(TANGO REQUIRED tango>=9.2.5)
message(STATUS "Found tango version ${TANGO_VERSION} at ${TANGO_PREFIX}")
include(FindLibraries)
find_libraries(LIBRARIES ${TANGO_LIBRARIES} SEARCH_PATHS ${TANGO_LIBRARY_DIRS})
# Create an interface library to represent the tango linkage
add_library(TangoInterfaceLibrary INTERFACE)
set_target_properties(TangoInterfaceLibrary
PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES "${TANGO_INCLUDE_DIRS}"
INTERFACE_LINK_LIBRARIES "${FOUND_LIBRARIES}"
INTERFACE_COMPILE_OPTIONS "${TANGO_CFLAGS}")
message(STATUS "Configured Tango Interface for TANGO version ${TANGO_VERSION}")
endif(NOT TARGET TangoInterfaceLibrary)
\ No newline at end of file
cmake_minimum_required(VERSION 3.2)
# source files
set(SRC_FILES ${SRC_FILES}
${CMAKE_CURRENT_SOURCE_DIR}/TestDevice.cpp
${CMAKE_CURRENT_SOURCE_DIR}/TestDeviceClass.cpp
${CMAKE_CURRENT_SOURCE_DIR}/TestDeviceStateMachine.cpp
${CMAKE_CURRENT_SOURCE_DIR}/ClassFactory.cpp
${CMAKE_CURRENT_SOURCE_DIR}/main.cpp
PARENT_SCOPE)
/*----- PROTECTED REGION ID(TestDevice::ClassFactory.cpp) ENABLED START -----*/
//=============================================================================
//
// file : ClassFactory.cpp
//
// description : C++ source for the class_factory method of the DServer
// device class. This method is responsible for the creation of
// all class singleton for a device server. It is called
// at device server startup.
//
// $Author: graziano $
//
//
//=============================================================================
// This file is generated by POGO
// (Program Obviously used to Generate tango Object)
//=============================================================================
#include <tango/tango.h>
#include <TestDeviceClass.h>
// Add class header files if needed
/**
* Create TestDevice Class singleton and store it in DServer object.
*/
void Tango::DServer::class_factory()
{
// Add method class init if needed
add_class(TestDevice_ns::TestDeviceClass::init("TestDevice"));
}
/*----- PROTECTED REGION END -----*/
/*----- PROTECTED REGION ID(TestDevice.cpp) ENABLED START -----*/
//=============================================================================
//
// file : TestDevice.cpp
//
// description : C++ source for the TestDevice and its commands.
// The class is derived from Device. It represents the
// CORBA servant object which will be accessed from the
// network. All commands which can be executed on the
// TestDevice are implemented in this file.
//
// $Author: graziano $
//
//
//=============================================================================
// This file is generated by POGO
// (Program Obviously used to Generate tango Object)
//=============================================================================
#include <TestDevice.h>
#include <TestDeviceClass.h>
#include <math.h>
#include <iomanip>
#include <limits>
/*----- PROTECTED REGION END -----*/
/**
* TestDevice class description:
*
*/
//================================================================
//
// The following table gives the correspondence
// between command and method names.
//
// Command name | Method name
//----------------------------------------------------------------
// State | Inherited (no method)
// Status | Inherited (no method)
//================================================================
namespace TestDevice_ns
{
/*----- PROTECTED REGION ID(TestDevice::namespace_starting) ENABLED START -----*/
// static initializations
/*----- PROTECTED REGION END -----*/ // TestDevice::namespace_starting
//--------------------------------------------------------
/**
* Method : TestDevice::TestDevice()
* Description : Constructors for a Tango device
* implementing the class TestDevice
*/
//--------------------------------------------------------
TestDevice::TestDevice(Tango::DeviceClass *cl, string &s)
: TANGO_BASE_CLASS(cl, s.c_str())
{
/*----- PROTECTED REGION ID(TestDevice::constructor_1) ENABLED START -----*/
init_device();
/*----- PROTECTED REGION END -----*/ // TestDevice::constructor_1
}
//--------------------------------------------------------
TestDevice::TestDevice(Tango::DeviceClass *cl, const char *s)
: TANGO_BASE_CLASS(cl, s)
{
/*----- PROTECTED REGION ID(TestDevice::constructor_2) ENABLED START -----*/
init_device();
/*----- PROTECTED REGION END -----*/ // TestDevice::constructor_2
}
//--------------------------------------------------------
TestDevice::TestDevice(Tango::DeviceClass *cl, const char *s, const char *d)
: TANGO_BASE_CLASS(cl, s, d)
{
/*----- PROTECTED REGION ID(TestDevice::constructor_3) ENABLED START -----*/
init_device();
/*----- PROTECTED REGION END -----*/ // TestDevice::constructor_3
}
//--------------------------------------------------------
/**
* Method : TestDevice::delete_device()()
* Description : will be called at device destruction or at init command
*/
//--------------------------------------------------------
void TestDevice::delete_device()
{
/*----- PROTECTED REGION ID(TestDevice::delete_device) ENABLED START -----*/
// Delete device allocated objects
save_configuration();
map<std::string,map_data_t>::iterator it;
for(it = attr_data_map.begin(); it != attr_data_map.end(); it++)
{
if(it->second.type == Tango::DEV_DOUBLE)
delete [] (Tango::DevDouble *) it->second.value;
else if(it->second.type == Tango::DEV_LONG)
delete [] (Tango::DevLong *) it->second.value;
else if(it->second.type == Tango::DEV_BOOLEAN)
delete [] (Tango::DevBoolean *) it->second.value;
else if(it->second.type == Tango::DEV_STRING)
delete [] (char *) it->second.value; //TODO: !!!
}
/*----- PROTECTED REGION END -----*/ // TestDevice::delete_device
delete[] attr_ScalarDyn_read;
delete[] attr_Ref_read;
delete[] attr_Values_read;
}
//--------------------------------------------------------
/**
* Method : TestDevice::init_device()
* Description : // will be called at device initialization.
*/
//--------------------------------------------------------
void TestDevice::init_device()
{
DEBUG_STREAM << "TestDevice::init_device() create device " << device_name << endl;
/*----- PROTECTED REGION ID(TestDevice::init_device_before) ENABLED START -----*/
// Initialization before get_device_property() call
dlastDB = 0.0;
waitingDB = false;
/*----- PROTECTED REGION END -----*/ // TestDevice::init_device_before
// Get the device properties (if any) from database
get_device_property();
attr_ScalarDyn_read = new Tango::DevString[1];
attr_Ref_read = new Tango::DevDouble[1024];
attr_Values_read = new Tango::DevString[1024];
/*----- PROTECTED REGION ID(TestDevice::init_device) ENABLED START -----*/
for (int i = 0; i < 1024; i++)
{
//ref_ptr[i] = ref_array[i];
attr_Values_read[i] = ref_array[i];
}
// Initialize device
gettimeofday(&last_read, NULL);
set_state(Tango::ON);
/*----- PROTECTED REGION END -----*/ // TestDevice::init_device
}
//--------------------------------------------------------
/**
* Method : TestDevice::get_device_property()
* Description : // Add your own code to initialize
*/
//--------------------------------------------------------
void TestDevice::get_device_property()
{
/*----- PROTECTED REGION ID(TestDevice::get_device_property_before) ENABLED START -----*/
// Initialize property data members
/*----- PROTECTED REGION END -----*/ // TestDevice::get_device_property_before
// Read device properties from database.
Tango::DbData dev_prop;
dev_prop.push_back(Tango::DbDatum("Attr_config"));
dev_prop.push_back(Tango::DbDatum("MinSaveDBPeriod"));
// is there at least one property to be read ?
if (dev_prop.size()>0)
{
// Call database and extract values
if (Tango::Util::instance()->_UseDb==true)
get_db_device()->get_property(dev_prop);
// get instance on TestDeviceClass to get class property
Tango::DbDatum def_prop, cl_prop;
TestDeviceClass *ds_class =
(static_cast<TestDeviceClass *>(get_device_class()));
int i = -1;
// Try to initialize Attr_config from class property
cl_prop = ds_class->get_class_property(dev_prop[++i].name);
if (cl_prop.is_empty()==false) cl_prop >> attr_config;
else {
// Try to initialize Attr_config from default device value
def_prop = ds_class->get_default_device_property(dev_prop[i].name);
if (def_prop.is_empty()==false) def_prop >> attr_config;
}
// And try to extract Attr_config value from database
if (dev_prop[i].is_empty()==false) dev_prop[i] >> attr_config;
// Try to initialize MinSaveDBPeriod from class property
cl_prop = ds_class->get_class_property(dev_prop[++i].name);
if (cl_prop.is_empty()==false) cl_prop >> minSaveDBPeriod;
else {
// Try to initialize MinSaveDBPeriod from default device value
def_prop = ds_class->get_default_device_property(dev_prop[i].name);
if (def_prop.is_empty()==false) def_prop >> minSaveDBPeriod;
}
// And try to extract MinSaveDBPeriod value from database
if (dev_prop[i].is_empty()==false) dev_prop[i] >> minSaveDBPeriod;
}
/*----- PROTECTED REGION ID(TestDevice::get_device_property_after) ENABLED START -----*/
// Check device property data members init
/*----- PROTECTED REGION END -----*/ // TestDevice::get_device_property_after
}
//--------------------------------------------------------
/**
* Method : TestDevice::always_executed_hook()
* Description : method always executed before any command is executed
*/
//--------------------------------------------------------
void TestDevice::always_executed_hook()
{
//INFO_STREAM << "TestDevice::always_executed_hook() " << device_name << endl;
/*----- PROTECTED REGION ID(TestDevice::always_executed_hook) ENABLED START -----*/
// code always executed before all requests
/*----- PROTECTED REGION END -----*/ // TestDevice::always_executed_hook
}
//--------------------------------------------------------
/**
* Method : TestDevice::read_attr_hardware()
* Description : Hardware acquisition for attributes.
*/
//--------------------------------------------------------
void TestDevice::read_attr_hardware(vector<long> &attr_list)
{
//DEBUG_STREAM << "TestDevice::read_attr_hardware(vector<long> &attr_list) entering... " << endl;
/*----- PROTECTED REGION ID(TestDevice::read_attr_hardware) ENABLED START -----*/
// Add your own code
if(waitingDB)
{
timeval now;
gettimeofday(&now, NULL);
double dnow=now.tv_sec + (double)now.tv_usec/1000000.0;
if(dnow - dlastDB > minSaveDBPeriod)
{
save_configuration();
dlastDB = dnow;
waitingDB = false;
}
}
/*----- PROTECTED REGION END -----*/ // TestDevice::read_attr_hardware
}
//--------------------------------------------------------
/**
* Read ScalarDyn attribute
* Description:
*
* Data type: Tango::DevDouble
* Attr type: Scalar
*/
//--------------------------------------------------------
void TestDevice::read_ScalarDyn(Tango::Attribute &attr)
{
//DEBUG_STREAM << "TestDevice::read_ScalarDyn(Tango::Attribute &attr) entering... " << endl;
/*----- PROTECTED REGION ID(TestDevice::read_ScalarDyn) ENABLED START -----*/
map<std::string,map_data_t>::iterator it = attr_data_map.find(attr.get_name());
if(it == attr_data_map.end())
Tango::Except::throw_exception((const char*) "Exception reading attribute",
(const char*) "Attribute Not Found", __FUNCTION__, Tango::ERR);
if(it->second.type == Tango::DEV_DOUBLE)
{
attr.set_value_date_quality((Tango::DevDouble *) it->second.value,it->second.ts,Tango::ATTR_VALID, 1, 0, false);
}
else if(it->second.type == Tango::DEV_LONG)
{
attr.set_value_date_quality((Tango::DevLong *) it->second.value,it->second.ts,Tango::ATTR_VALID, 1, 0, false);
}
else if(it->second.type == Tango::DEV_BOOLEAN)
{
attr.set_value_date_quality((Tango::DevBoolean *) it->second.value,it->second.ts,Tango::ATTR_VALID, 1, 0, false);
}
else if(it->second.type == Tango::DEV_STRING)
{
*attr_ScalarDyn_read = (char *) it->second.value;
attr.set_value_date_quality(attr_ScalarDyn_read,it->second.ts,Tango::ATTR_VALID, 1, 0, false);
//attr.set_value_date_quality((Tango::DevString *) it->second.value,it->second.ts,Tango::ATTR_VALID, 1, 0, false);
}
/*----- PROTECTED REGION END -----*/ // TestDevice::read_ScalarDyn
}
//+----------------------------------------------------------------------------
//
// method : TestDevice::write_ScalarDyn
//
// description : Write ScalarDyn attribute values to hardware.
//
//-----------------------------------------------------------------------------
void TestDevice::write_ScalarDyn(Tango::WAttribute &attr)
{
DEBUG_STREAM << "TestDevice::write_ScalarDyn(Tango::WAttribute &attr) entering... "<< endl;
/*----- PROTECTED REGION ID(TestDevice::write_ScalarDyn) ENABLED START -----*/
map<std::string,map_data_t>::iterator it = attr_data_map.find(attr.get_name());
if(it == attr_data_map.end())
Tango::Except::throw_exception((const char*) "Exception reading attribute",
(const char*) "Attribute Not Found", __FUNCTION__, Tango::ERR);
gettimeofday(&(it->second.ts), NULL);
if(it->second.type == Tango::DEV_DOUBLE)
{
Tango::DevDouble w_val;
attr.get_write_value(w_val);
*(Tango::DevDouble *) it->second.value = w_val;
try{
push_change_event(attr.get_name(),(Tango::DevDouble *)(it->second.value),/*NULL,Tango::ATTR_VALID,*/ 1/*size*/, 0, false);
push_archive_event(attr.get_name(),(Tango::DevDouble *)(it->second.value),/*NULL,Tango::ATTR_VALID,*/ 1/*size*/, 0, false);
}catch(...){}
}
else if(it->second.type == Tango::DEV_LONG)
{
Tango::DevLong w_val;
attr.get_write_value(w_val);
*(Tango::DevLong *) it->second.value = w_val;
try{
push_change_event(attr.get_name(),(Tango::DevLong *)(it->second.value),/*NULL,Tango::ATTR_VALID,*/ 1/*size*/, 0, false);
push_archive_event(attr.get_name(),(Tango::DevLong *)(it->second.value),/*NULL,Tango::ATTR_VALID,*/ 1/*size*/, 0, false);
}catch(...){}
}
else if(it->second.type == Tango::DEV_BOOLEAN)
{
Tango::DevBoolean w_val;
attr.get_write_value(w_val);
*(Tango::DevBoolean *) it->second.value = w_val;
try{
push_change_event(attr.get_name(),(Tango::DevBoolean *)(it->second.value),/*NULL,Tango::ATTR_VALID,*/ 1/*size*/, 0, false);
push_archive_event(attr.get_name(),(Tango::DevBoolean *)(it->second.value),/*NULL,Tango::ATTR_VALID,*/ 1/*size*/, 0, false);
}catch(...){}
}
else if(it->second.type == Tango::DEV_STRING)
{
Tango::DevString w_val;
attr.get_write_value(w_val);
memset((char *) it->second.value, 0, 1024);
strncpy((char *) it->second.value,w_val, 1023);
//try{
// push_change_event(attr.get_name(),(Tango::DevString *)(it->second.value),/*NULL,Tango::ATTR_VALID,*/ 1/*size*/, 0, false);
// push_archive_event(attr.get_name(),(Tango::DevString *)(it->second.value),/*NULL,Tango::ATTR_VALID,*/ 1/*size*/, 0, false);
//}catch(...){}
}
timeval now;
gettimeofday(&now, NULL);
double dnow=now.tv_sec + (double)now.tv_usec/1000000.0;
if(dnow - dlastDB > minSaveDBPeriod)
{
save_configuration();
dlastDB = dnow;
waitingDB = false;
}
else
{
waitingDB = true;
}
/*----- PROTECTED REGION END -----*/ // TestDevice::write_ScalarDyn
}
//--------------------------------------------------------
/**
* Read SpectrumDyn attribute
* Description:
*
* Data type: Tango::DevDouble
* Attr type: Spectrum
*/
//--------------------------------------------------------
void TestDevice::read_SpectrumDyn(Tango::Attribute &attr)
{
//DEBUG_STREAM << "TestDevice::read_SpectrumDyn(Tango::Attribute &attr) entering... " << endl;
/*----- PROTECTED REGION ID(TestDevice::read_SpectrumDyn) ENABLED START -----*/
map<std::string,map_data_t>::iterator it = attr_data_map.find(attr.get_name());
if(it == attr_data_map.end())
Tango::Except::throw_exception((const char*) "Exception reading attribute",
(const char*) "Attribute Not Found", __FUNCTION__, Tango::ERR);
if(it->second.type == Tango::DEV_DOUBLE)
{
attr.set_value_date_quality((Tango::DevDouble *) it->second.value,it->second.ts,Tango::ATTR_VALID, it->second.size1, 0, false);
}
else if(it->second.type == Tango::DEV_LONG)
{
attr.set_value_date_quality((Tango::DevLong *) it->second.value,it->second.ts,Tango::ATTR_VALID, it->second.size1, 0, false);
}
else if(it->second.type == Tango::DEV_BOOLEAN)
{
attr.set_value_date_quality((Tango::DevBoolean *) it->second.value,it->second.ts,Tango::ATTR_VALID, it->second.size1, 0, false);
}
else if(it->second.type == Tango::DEV_STRING)
{
//NOT SUPPORTED
}
/*----- PROTECTED REGION END -----*/ // TestDevice::read_SpectrumDyn
}
//+----------------------------------------------------------------------------
//
// method : TestDevice::write_SpectrumDyn
//
// description : Write SpectrumDyn attribute values to hardware.
//
//-----------------------------------------------------------------------------
void TestDevice::write_SpectrumDyn(Tango::WAttribute &attr)
{
DEBUG_STREAM << "TestDevice::write_SpectrumDyn(Tango::WAttribute &attr) entering... "<< endl;
/*----- PROTECTED REGION ID(TestDevice::write_SpectrumDyn) ENABLED START -----*/
map<std::string,map_data_t>::iterator it = attr_data_map.find(attr.get_name());
if(it == attr_data_map.end())
Tango::Except::throw_exception((const char*) "Exception reading attribute",
(const char*) "Attribute Not Found", __FUNCTION__, Tango::ERR);
gettimeofday(&(it->second.ts), NULL);
size_t value_size = attr.get_write_value_length();
it->second.size1 = value_size > MAX_SPECTRUM_SIZE ? MAX_SPECTRUM_SIZE : value_size;
if(it->second.type == Tango::DEV_DOUBLE)
{
const Tango::DevDouble * w_val;
attr.get_write_value(w_val);
for(size_t ind=0; ind < it->second.size1; ind++)
{
((Tango::DevDouble *) it->second.value)[ind] = w_val[ind];
}
try{
push_change_event(attr.get_name(),(Tango::DevDouble *)(it->second.value),/*NULL,Tango::ATTR_VALID,*/ it->second.size1, 0, false);
push_archive_event(attr.get_name(),(Tango::DevDouble *)(it->second.value),/*NULL,Tango::ATTR_VALID,*/ it->second.size1, 0, false);
}catch(...){}
}
else if(it->second.type == Tango::DEV_LONG)
{
const Tango::DevLong * w_val;
attr.get_write_value(w_val);
for(size_t ind=0; ind < it->second.size1; ind++)
{
((Tango::DevLong *) it->second.value)[ind] = w_val[ind];
}
try{
push_change_event(attr.get_name(),(Tango::DevLong *)(it->second.value),/*NULL,Tango::ATTR_VALID,*/ it->second.size1, 0, false);
push_archive_event(attr.get_name(),(Tango::DevLong *)(it->second.value),/*NULL,Tango::ATTR_VALID,*/ it->second.size1, 0, false);
}catch(...){}
}
else if(it->second.type == Tango::DEV_BOOLEAN)
{
const Tango::DevBoolean * w_val;
attr.get_write_value(w_val);
for(size_t ind=0; ind<it->second.size1; ind++)
{
((Tango::DevBoolean *) it->second.value)[ind] = w_val[ind];
}
try{
push_change_event(attr.get_name(),(Tango::DevBoolean *)(it->second.value),/*NULL,Tango::ATTR_VALID,*/ it->second.size1, 0, false);
push_archive_event(attr.get_name(),(Tango::DevBoolean *)(it->second.value),/*NULL,Tango::ATTR_VALID,*/ it->second.size1, 0, false);
}catch(...){}
}
else if(it->second.type == Tango::DEV_STRING)
{
//NOT SUPPORTED
}
timeval now;
gettimeofday(&now, NULL);
double dnow=now.tv_sec + (double)now.tv_usec/1000000.0;
if(dnow - dlastDB > minSaveDBPeriod)
{
save_configuration();
dlastDB = dnow;
waitingDB = false;
}
else
{
waitingDB = true;
}
/*----- PROTECTED REGION END -----*/ // TestDevice::write_SpectrumDyn
}
//--------------------------------------------------------
/**
* Read Ref attribute
* Description:
*
* Data type: Tango::DevString
* Attr type: Scalar
*/
//--------------------------------------------------------
void TestDevice::read_Ref(Tango::Attribute &attr)
{
//DEBUG_STREAM << "TestDevice::read_Ref(Tango::Attribute &attr) entering... " << endl;
/*----- PROTECTED REGION ID(TestDevice::read_Ref) ENABLED START -----*/
map<std::string,map_data_t>::iterator it;
int i=0;
for(it = attr_data_map.begin(), i=0; it != attr_data_map.end() && i<1024; it++)
{
if(it->second.type == Tango::DEV_DOUBLE)
attr_Ref_read[i++] = *((Tango::DevDouble *) it->second.value);
}
attr.set_value(attr_Ref_read, i);
/*----- PROTECTED REGION END -----*/ // TestDevice::read_Ref
}
//+----------------------------------------------------------------------------
//
// method : TestDevice::write_Ref
//
// description : Write Ref attribute values to hardware.
//
//-----------------------------------------------------------------------------
void TestDevice::write_Ref(Tango::WAttribute &attr)
{
DEBUG_STREAM << "TestDevice::write_Ref(Tango::Attribute &attr) entering... " << endl;
// Retrieve write value
const Tango::DevDouble *w_val;
attr.get_write_value(w_val);
/*----- PROTECTED REGION ID(TestDevice::write_Ref) ENABLED START -----*/
int size_ref = attr.get_write_value_length();
size_ref = size_ref<1024 ? size_ref : 1024;
double tmp;
int i=0;
attr.get_write_value(tmp);
for(map<std::string,map_data_t>::iterator it=attr_data_map.begin(); it != attr_data_map.end() && i<size_ref; it++)
{
if(it->second.type == Tango::DEV_DOUBLE)
{
gettimeofday(&(it->second.ts), NULL);
*(Tango::DevDouble *) it->second.value = w_val[i++];
try {
push_change_event(it->first,(Tango::DevDouble *)(it->second.value),/*NULL,Tango::ATTR_VALID,*/ 1/*size*/, 0, false);
push_archive_event(it->first,(Tango::DevDouble *)(it->second.value),/*NULL,Tango::ATTR_VALID,*/ 1/*size*/, 0, false);
}catch(...){}
}
}
timeval now;
gettimeofday(&now, NULL);
double dnow=now.tv_sec + (double)now.tv_usec/1000000.0;
if(dnow - dlastDB > minSaveDBPeriod)
{
save_configuration();
dlastDB = dnow;
waitingDB = false;
}
else
{
waitingDB = true;
}
/*----- PROTECTED REGION END -----*/// TestDevice::write_Ref
}
//--------------------------------------------------------
/**
* Read Values attribute
* Description:
*
* Data type: Tango::DevString
* Attr type: Scalar
*/
//--------------------------------------------------------
void TestDevice::read_Values(Tango::Attribute &attr)
{
//DEBUG_STREAM << "TestDevice::read_Values(Tango::Attribute &attr) entering... " << endl;
/*----- PROTECTED REGION ID(TestDevice::read_Values) ENABLED START -----*/
map<std::string,map_data_t>::iterator it;
int i;
for(it = attr_data_map.begin(), i=0; it != attr_data_map.end() && i<1024; it++, i++)
{
stringstream val;
if(it->second.type == Tango::DEV_DOUBLE)
{
for(size_t ind=0; ind<it->second.size1; ind++)
{
val << std::setprecision(std::numeric_limits<Tango::DevDouble>::digits10+2) << ((Tango::DevDouble *) it->second.value)[ind];
if(ind < it->second.size1-1)
val << ",";
}
sprintf(ref_array[i], "%s=%s", it->first.c_str(), val.str().c_str());
}
else if(it->second.type == Tango::DEV_LONG)
{
for(size_t ind=0; ind<it->second.size1; ind++)
{
val << std::setprecision(std::numeric_limits<Tango::DevLong>::digits10+2) << ((Tango::DevLong *) it->second.value)[ind];
if(ind < it->second.size1-1)
val << ",";
}
sprintf(ref_array[i], "%s=%s", it->first.c_str(), val.str().c_str());
}
else if(it->second.type == Tango::DEV_BOOLEAN)
{
for(size_t ind=0; ind<it->second.size1; ind++)
{
val << (((Tango::DevBoolean *) it->second.value)[ind] ? "true" : "false");
if(ind < it->second.size1-1)
val << ",";
}
sprintf(ref_array[i], "%s=%s", it->first.c_str(), val.str().c_str());
}
else if(it->second.type == Tango::DEV_STRING)
{
sprintf(ref_array[i], "%s=%s", it->first.c_str(), ((char *) it->second.value));
}
}
attr.set_value(attr_Values_read, i);
/*----- PROTECTED REGION END -----*/ // TestDevice::read_Values
}
//+----------------------------------------------------------------------------
//
// method : TestDevice::write_Ref
//
// description : Write Ref attribute values to hardware.
//
//-----------------------------------------------------------------------------
void TestDevice::write_Values(Tango::WAttribute &attr)
{
DEBUG_STREAM << "TestDevice::write_Values(Tango::Attribute &attr) entering... " << endl;
// Retrieve write value
const Tango::ConstDevString *w_val;
attr.get_write_value(w_val);
/*----- PROTECTED REGION ID(TestDevice::write_Values) ENABLED START -----*/
int size_ref = attr.get_write_value_length();
size_ref = size_ref<1024 ? size_ref : 1024;
double tmp;
int i=0;
attr.get_write_value(tmp);
for(i=0; i<size_ref; i++)
{
vector<string> results;
string_explode(w_val[i], "=", &results);
if(results.size() == 2)
{
map<std::string,map_data_t>::iterator it = attr_data_map.find(results[0]);
if(it == attr_data_map.end())
continue;
/*Tango::Except::throw_exception((const char*) "Exception writing attribute",
string("Attribute '") + string(results[0]) + string("' not found"), __FUNCTION__, Tango::ERR);*/
gettimeofday(&(it->second.ts), NULL);
vector<string> values;
string_explode(results[1], ",", &values);
if(it->second.type == Tango::DEV_BOOLEAN)
{
size_t ind=0;
for(vector<string>::iterator val=values.begin(); val != values.end() && ind<it->second.size1; val++)
{
if(*val == "true")
((Tango::DevBoolean *) it->second.value)[ind++] = true;
else if(*val == "false")
((Tango::DevBoolean *) it->second.value)[ind++] = false;
else
((Tango::DevBoolean *) it->second.value)[ind++] = atoi(val->c_str());
}
try {
set_write_value((Tango::DevBoolean *) it->second.value, results[0], it->second.size1);
push_change_event(it->first,(Tango::DevBoolean *)(it->second.value),/*NULL,Tango::ATTR_VALID,*/ it->second.size1/*size*/, 0, false);
push_archive_event(it->first,(Tango::DevBoolean *)(it->second.value),/*NULL,Tango::ATTR_VALID,*/ it->second.size1/*size*/, 0, false);
}catch(...){}
}
else if(it->second.type == Tango::DEV_LONG)
{
size_t ind=0;
for(vector<string>::iterator val=values.begin(); val != values.end() && ind<it->second.size1; val++)
{
((Tango::DevLong *) it->second.value)[ind++] = atoi(results[1].c_str());
}
try {
set_write_value((Tango::DevLong *) it->second.value, results[0], it->second.size1);
push_change_event(it->first,(Tango::DevLong *)(it->second.value),/*NULL,Tango::ATTR_VALID,*/ 1/*size*/, 0, false);
push_archive_event(it->first,(Tango::DevLong *)(it->second.value),/*NULL,Tango::ATTR_VALID,*/ 1/*size*/, 0, false);
}catch(...){}
}
else if(it->second.type == Tango::DEV_DOUBLE)
{
size_t ind=0;
for(vector<string>::iterator val=values.begin(); val != values.end() && ind<it->second.size1; val++)
{
((Tango::DevDouble *) it->second.value)[ind++] = atof(results[1].c_str());
}
try {
set_write_value((Tango::DevDouble *) it->second.value, results[0], it->second.size1);
push_change_event(it->first,(Tango::DevDouble *)(it->second.value),/*NULL,Tango::ATTR_VALID,*/ 1/*size*/, 0, false);
push_archive_event(it->first,(Tango::DevDouble *)(it->second.value),/*NULL,Tango::ATTR_VALID,*/ 1/*size*/, 0, false);
}catch(...){}
}
else if(it->second.type == Tango::DEV_STRING)
{
memset((char *) it->second.value, 0, 1024);
strncpy((char *) it->second.value,results[1].c_str(), 1023);
Tango::DevString str_ptr = (char *) it->second.value;
set_write_value((Tango::DevString ) str_ptr, results[0]);
}
}
}
timeval now;
gettimeofday(&now, NULL);
double dnow=now.tv_sec + (double)now.tv_usec/1000000.0;
if(dnow - dlastDB > minSaveDBPeriod)
{
save_configuration();
dlastDB = dnow;
waitingDB = false;
}
else
{
waitingDB = true;
}
//and now push events
/*----- PROTECTED REGION END -----*/// TestDevice::write_Ref
}
//--------------------------------------------------------
/**
* Method : TestDevice::TestDeviceClass::add_dynamic_attributes()
* Description : Create the dynamic attributes if any
* for specified device.
*/
//--------------------------------------------------------
void TestDevice::add_dynamic_attributes()
{
/*----- PROTECTED REGION ID(TestDevice::Class::add_dynamic_attributes) ENABLED START -----*/
// Add your own code to create and add dynamic attributes if any
DEBUG_STREAM << __FUNCTION__ << " entering...";
if (attr_config.empty() == false)
{
for(vector<string>::iterator it = attr_config.begin();it != attr_config.end(); it++)
{
vector<string> results;
string_explode(*it, ":", &results);
try
{
create_dynamic_attribute(results);
} catch(Tango::DevFailed &e)
{
INFO_STREAM << __FUNCTION__ << " Error reading creating attribute='" << e.errors[0].desc << "'";
}
}
}
/*----- PROTECTED REGION END -----*/ // TestDevice::Class::add_dynamic_attributes
}
//========================================================
// Command execution methods
//========================================================
//--------------------------------------------------------
/**
* Execute the WriteAttrname command:
* Description: Delete all Double attributes and create new ones.
*
* @param argin List of double attributes to write.
* @returns
*/
//--------------------------------------------------------
void TestDevice::write_attrname(const Tango::DevVarDoubleStringArray *argin)
{
DEBUG_STREAM << "TestDevice::write_attrname() - " << device_name << endl;
/*----- PROTECTED REGION ID(TestDevice::write_attrname) ENABLED START -----*/
// Add your own code
// POGO has generated a method core with argout allocation.
// If you would like to use a static reference without copying,
// See "TANGO Device Server Programmer's Manual"
// (chapter : Writing a TANGO DS / Exchanging data)
//------------------------------------------------------------
// Add your own code to control device here
double tmp;
int lens, lend, lenmin;
string name;
int i=0;
lens = argin->svalue.length();
lend = argin->dvalue.length();
lenmin = (lens <= lend) ? lens : lend;
for(i=0; i<lenmin; i++)
{
name = string(argin->svalue[i]);
tmp = argin->dvalue[i];
map<std::string,map_data_t>::iterator it = attr_data_map.find(name);
if(it == attr_data_map.end())
Tango::Except::throw_exception((const char*) "Exception writing attribute", string("Attribute '") + name
+ string("' not found"), __FUNCTION__, Tango::ERR);
if(it->second.type != Tango::DEV_DOUBLE)
{
Tango::Except::throw_exception((const char*) "Exception writing attribute", string("Attribute '") + name
+ string("' is not of type double"), __FUNCTION__, Tango::ERR);
}
else
{
gettimeofday(&(it->second.ts), NULL);
*(Tango::DevDouble *) it->second.value = tmp;
try {
push_change_event(it->first,(Tango::DevDouble *)(it->second.value),/*NULL,Tango::ATTR_VALID,*/ 1/*size*/, 0, false);
push_archive_event(it->first,(Tango::DevDouble *)(it->second.value),/*NULL,Tango::ATTR_VALID,*/ 1/*size*/, 0, false);
}catch(...){}
timeval now;
gettimeofday(&now, NULL);
double dnow=now.tv_sec + (double)now.tv_usec/1000000.0;
if(dnow - dlastDB > minSaveDBPeriod)
{
save_configuration();
dlastDB = dnow;
waitingDB = false;
}
else
{
waitingDB = true;
}
}
}
/*----- PROTECTED REGION END -----*/// TestDevice::write_attrname
return;
}
//--------------------------------------------------------
/**
* Execute the ReadAttrname command:
* Description: Delete all Double attributes and create new ones.
*
* @param argin List of new double attributes.
* @returns
*/
//--------------------------------------------------------
Tango::DevVarDoubleArray * TestDevice::read_attrname(const Tango::DevVarStringArray *argin)
{
Tango::DevVarDoubleArray *argout;
DEBUG_STREAM << "TestDevice::read_attrname() - " << device_name << endl;
/*----- PROTECTED REGION ID(TestDevice::read_attrname) ENABLED START -----*/
// Add your own code
// POGO has generated a method core with argout allocation.
// If you would like to use a static reference without copying,
// See "TANGO Device Server Programmer's Manual"
// (chapter : Writing a TANGO DS / Exchanging data)
//------------------------------------------------------------
// Add your own code to control device here
argout = new Tango::DevVarDoubleArray();
vector<string> attributes;
attributes << (*argin);
double *tmp = new double[attributes.size()];
string name;
unsigned int index = 0;
for(vector<string>::iterator its = attributes.begin(); its != attributes.end(); its++)
{
name = *its;
map<std::string, map_data_t>::iterator it = attr_data_map.find(name);
if(it == attr_data_map.end())
{
delete [] tmp;
Tango::Except::throw_exception((const char*) "Exception reading attribute", string("Attribute '") + name
+ string("' not found"), __FUNCTION__, Tango::ERR);
}
if(it->second.type == Tango::DEV_DOUBLE)
{
tmp[index++] = *((Tango::DevDouble *) it->second.value);
}
else
{
delete [] tmp;
Tango::Except::throw_exception((const char*) "Exception reading attribute", string("Attribute '") + name
+ string("' is not of type double"), __FUNCTION__, Tango::ERR);
}
}
//if found all names
if(index == attributes.size())
{
argout->length(index);
for(unsigned int i=0; i<index; i++)
(*argout)[i] = tmp[i];
}
delete [] tmp;
/*----- PROTECTED REGION END -----*/// TestDevice::read_attrname
return argout;
}
//--------------------------------------------------------
/**
* Execute the Config command:
* Description: Delete all Double attributes and create new ones.
*
* @param argin List of new double attributes.
* @returns
*/
//--------------------------------------------------------
void TestDevice::config(const Tango::DevVarStringArray *argin)
{
DEBUG_STREAM << "TestDevice::config() - " << device_name << endl;
/*----- PROTECTED REGION ID(TestDevice::config) ENABLED START -----*/
// Add your own code
// POGO has generated a method core with argout allocation.
// If you would like to use a static reference without copying,
// See "TANGO Device Server Programmer's Manual"
// (chapter : Writing a TANGO DS / Exchanging data)
//------------------------------------------------------------
// Add your own code to control device here
vector<string> attributes;
attributes << (*argin);
#if 1
//TODO: verify memory leak
for(unsigned int i = 0; i < this->get_device_attr()->get_attr_nb(); i++)
{
string attr_name = get_device_attr()->get_attr_by_ind(i).get_name();
if((attr_name != "State") && (attr_name != "Status") && (attr_name != "Ref") && (attr_name != "Values"))
{
DEBUG_STREAM << "TestDevice::config: i=" << i << " removing attribute: "
<< attr_name << endl;
//TODO: update_idx=Flag set to true if the attributes object index
// used to retrieve the corresponding Attr object has to be
// updated (because one Attr object has been removed)
this->get_device_attr()->remove_attribute(attr_name, /*update_idx*/true);
i--;
}
}
#else
erase_dynamic_attributes() //TODO
#endif
map<std::string,map_data_t>::iterator it;
for(it = attr_data_map.begin(); it != attr_data_map.end(); it++)
{
if(it->second.type == Tango::DEV_DOUBLE)
delete [] (Tango::DevDouble *) it->second.value;
else if(it->second.type == Tango::DEV_LONG)
delete [] (Tango::DevLong *) it->second.value;
else if(it->second.type == Tango::DEV_BOOLEAN)
delete [] (Tango::DevBoolean *) it->second.value;
else if(it->second.type == Tango::DEV_STRING)
delete [] (char *) it->second.value;
}
try
{
attr_data_map.clear();
DEBUG_STREAM << "TestDevice::config: attr_data_map cleared !" << endl;
} catch(...)
{
WARN_STREAM << "TestDevice::delete_device: Could not clear attr_data_map !" << endl;
}
numAttr = attributes.size();
for(int j = 0; j < numAttr; j++)
{
Tango::Attr *cspec;
char attrname[256];
Tango::UserDefaultAttrProp attrprop;
sprintf(attrname, "%s", attributes[j].c_str());
cspec = new ScalarDynAttrib(attrname, Tango::DEV_DOUBLE);
/*sprintf(strtmp,"Dynamic Attribute %s reading channel %d ",attrname,num_ch);
if(unit != "")
{
attrprop.set_unit(unit.c_str());
attrprop.set_standard_unit("1.0");
attrprop.set_display_unit(unit.c_str());
}
attrprop.set_format("%.9g");
attrprop.set_description(strtmp);*/
cspec->set_default_properties(attrprop);
add_attribute(cspec);
struct timeval curr_time;
//gettimeofday(&curr_time,NULL);
curr_time.tv_sec = 0;
double *value = new double();
map_data_t tmp;
tmp.value = value;
tmp.size1 = 1;
tmp.size2 = 0;
tmp.max1 = 1;
tmp.max2 = 1;
tmp.type = Tango::DEV_DOUBLE;
tmp.ts = curr_time;
attr_data_map.insert(make_pair(attrname, tmp));
}
save_configuration();
/*----- PROTECTED REGION END -----*/// TestDevice::config
return;
}
//--------------------------------------------------------
/**
* Execute the Add command:
* Description: Create new attributes.
*
* @param argin List of new attributes.
* @returns
*/
//--------------------------------------------------------
void TestDevice::add(const Tango::DevVarStringArray *argin)
{
DEBUG_STREAM << "TestDevice::add() - " << device_name << endl;
/*----- PROTECTED REGION ID(TestDevice::add) ENABLED START -----*/
// Add your own code
// POGO has generated a method core with argout allocation.
// If you would like to use a static reference without copying,
// See "TANGO Device Server Programmer's Manual"
// (chapter : Writing a TANGO DS / Exchanging data)
//------------------------------------------------------------
// Add your own code to control device here
vector<string> attributes;
attributes << (*argin);
for(vector<string>::iterator it = attributes.begin();it != attributes.end(); it++)
{
DEBUG_STREAM << __func__ << ": adding '" << *it << "'";
vector<string> results;
string_explode(*it, ":", &results);
create_dynamic_attribute(results);
}
save_configuration();
/*----- PROTECTED REGION END -----*/// TestDevice::add
return;
}
//--------------------------------------------------------
/**
* Execute the AddDouble command:
* Description: Create new attributes.
*
* @param argin List of new attributes.
* @returns
*/
//--------------------------------------------------------
void TestDevice::add_double(const Tango::DevVarStringArray *argin)
{
DEBUG_STREAM << "TestDevice::add_double() - " << device_name << endl;
/*----- PROTECTED REGION ID(TestDevice::add_double) ENABLED START -----*/
// Add your own code
// POGO has generated a method core with argout allocation.
// If you would like to use a static reference without copying,
// See "TANGO Device Server Programmer's Manual"
// (chapter : Writing a TANGO DS / Exchanging data)
//------------------------------------------------------------
// Add your own code to control device here
vector<string> attributes;
attributes << (*argin);
for(vector<string>::iterator it = attributes.begin();it != attributes.end(); it++)
{
vector<string> results;
results.push_back(*it);
results.push_back("double");
results.push_back("0");
results.push_back("0");
create_dynamic_attribute(results);
}
save_configuration();
/*----- PROTECTED REGION END -----*/// TestDevice::add_double
return;
}
//--------------------------------------------------------
/**
* Execute the AddLong command:
* Description: Create new attributes.
*
* @param argin List of new attributes.
* @returns
*/
//--------------------------------------------------------
void TestDevice::add_long(const Tango::DevVarStringArray *argin)
{
DEBUG_STREAM << "TestDevice::add_long() - " << device_name << endl;
/*----- PROTECTED REGION ID(TestDevice::add_long) ENABLED START -----*/
// Add your own code
// POGO has generated a method core with argout allocation.
// If you would like to use a static reference without copying,
// See "TANGO Device Server Programmer's Manual"
// (chapter : Writing a TANGO DS / Exchanging data)
//------------------------------------------------------------
// Add your own code to control device here
vector<string> attributes;
attributes << (*argin);
for(vector<string>::iterator it = attributes.begin();it != attributes.end(); it++)
{
vector<string> results;
results.push_back(*it);
results.push_back("long");
results.push_back("0");
results.push_back("0");
create_dynamic_attribute(results);
}
save_configuration();
/*----- PROTECTED REGION END -----*/// TestDevice::add_long
return;
}
//--------------------------------------------------------
/**
* Execute the AddBool command:
* Description: Create new attributes.
*
* @param argin List of new attributes.
* @returns
*/
//--------------------------------------------------------
void TestDevice::add_bool(const Tango::DevVarStringArray *argin)
{
DEBUG_STREAM << "TestDevice::add_bool() - " << device_name << endl;
/*----- PROTECTED REGION ID(TestDevice::add_bool) ENABLED START -----*/
// Add your own code
// POGO has generated a method core with argout allocation.
// If you would like to use a static reference without copying,
// See "TANGO Device Server Programmer's Manual"
// (chapter : Writing a TANGO DS / Exchanging data)
//------------------------------------------------------------
// Add your own code to control device here
vector<string> attributes;
attributes << (*argin);
for(vector<string>::iterator it = attributes.begin();it != attributes.end(); it++)
{
vector<string> results;
results.push_back(*it);
results.push_back("bool");
results.push_back("0");
results.push_back("0");
create_dynamic_attribute(results);
}
save_configuration();
/*----- PROTECTED REGION END -----*/// TestDevice::add_bool
return;
}
//--------------------------------------------------------
/**
* Execute the AddString command:
* Description: Create new attributes.
*
* @param argin List of new attributes.
* @returns
*/
//--------------------------------------------------------
void TestDevice::add_string(const Tango::DevVarStringArray *argin)
{
DEBUG_STREAM << "TestDevice::add_string() - " << device_name << endl;
/*----- PROTECTED REGION ID(TestDevice::add_string) ENABLED START -----*/
// Add your own code
// POGO has generated a method core with argout allocation.
// If you would like to use a static reference without copying,
// See "TANGO Device Server Programmer's Manual"
// (chapter : Writing a TANGO DS / Exchanging data)
//------------------------------------------------------------
// Add your own code to control device here
vector<string> attributes;
attributes << (*argin);
for(vector<string>::iterator it = attributes.begin();it != attributes.end(); it++)
{
vector<string> results;
results.push_back(*it);
results.push_back("string");
results.push_back("0");
results.push_back("0");
create_dynamic_attribute(results);
}
save_configuration();
/*----- PROTECTED REGION END -----*/// TestDevice::add_string
return;
}
//--------------------------------------------------------
/**
* Execute the Remove command:
* Description: Remove attributes.
*
* @param argin List of attributes.
* @returns
*/
//--------------------------------------------------------
void TestDevice::remove(const Tango::DevVarStringArray *argin)
{
DEBUG_STREAM << "TestDevice::remove() - " << device_name << endl;
/*----- PROTECTED REGION ID(TestDevice::remove) ENABLED START -----*/
// Add your own code
// POGO has generated a method core with argout allocation.
// If you would like to use a static reference without copying,
// See "TANGO Device Server Programmer's Manual"
// (chapter : Writing a TANGO DS / Exchanging data)
//------------------------------------------------------------
// Add your own code to control device here
vector<string> attributes;
attributes << (*argin);
//TODO: verify memory leak
for(vector<string>::iterator it = attributes.begin(); it != attributes.end(); it++)
{
if((*it != "State") && (*it != "Status") && (*it != "Ref"))
{
map<std::string,map_data_t>::iterator it_attr = attr_data_map.find(*it);
if(it_attr == attr_data_map.end())
{
Tango::Except::throw_exception((const char*) "Exception removing attribute", string("Attribute '")
+ string(*it) + string("' not found"), __FUNCTION__, Tango::ERR);
}
DEBUG_STREAM << __FUNCTION__ << ": removing attribute: " << *it;
//TODO: update_idx=Flag set to true if the attributes object index
// used to retrieve the corresponding Attr object has to be
// updated (because one Attr object has been removed)
this->get_device_attr()->remove_attribute(*it, /*update_idx*/true);
try
{
if(it_attr->second.type == Tango::DEV_DOUBLE)
delete [] (Tango::DevDouble *) it_attr->second.value;
else if(it_attr->second.type == Tango::DEV_LONG)
delete [] (Tango::DevLong *) it_attr->second.value;
else if(it_attr->second.type == Tango::DEV_BOOLEAN)
delete [] (Tango::DevBoolean *) it_attr->second.value;
else if(it_attr->second.type == Tango::DEV_STRING)
delete [] (char *) it_attr->second.value;
attr_data_map.erase(/**it*/it_attr);
DEBUG_STREAM << __FUNCTION__ << ": " << *it << " removed from attr_data_map";
} catch(...)
{
WARN_STREAM << __FUNCTION__ << ": ERROR removing " << *it << " from attr_data_map";
}
save_configuration();
}
}
/*----- PROTECTED REGION END -----*/// TestDevice::remove
return;
}
/*----- PROTECTED REGION ID(TestDevice::namespace_ending) ENABLED START -----*/
// Additional Methods
//+------------------------------------------------------------------
/*
* method: TestDevice::create_dynamic_attribute
* Create and configure an attribute
*/
//+------------------------------------------------------------------
void TestDevice::create_dynamic_attribute(vector<string> config)
{
if(config.size() == 3 || config.size() == 4)
{
Tango::Attr *attr;
char attrname[256];
Tango::UserDefaultAttrProp attrprop;
struct timeval attr_time;
if(config.size() == 4)
{
vector<string> timestamp;
string_explode(config[3], ".", &timestamp);
if(timestamp.size() == 2)
{
attr_time.tv_sec = atoi(timestamp[0].c_str());
attr_time.tv_usec = atoi(timestamp[1].c_str());
if(attr_time.tv_sec == 0)
gettimeofday(&attr_time,NULL);
}
else
{
gettimeofday(&attr_time,NULL);
}
}
else
{
gettimeofday(&attr_time,NULL);
}
strcpy(attrname, config[0].c_str());
if(attr_data_map.find(attrname) != attr_data_map.end())
Tango::Except::throw_exception((const char*) "Exception creating attribute",
string("Attribute '") + string(attrname) + string("' already existing"), __FUNCTION__, Tango::ERR);
vector<string> values;
string_explode(config[2], ",", &values);
map_data_t tmp;
tmp.size1 = (values.size() > MAX_SPECTRUM_SIZE) ? MAX_SPECTRUM_SIZE : values.size();
tmp.size2 = 0;
tmp.max1 = 1;
tmp.max2 = 1;
tmp.ts = attr_time;
size_t value_size = (tmp.size1 > 1) ? MAX_SPECTRUM_SIZE : 1;
if(config[1] == "bool")
{
tmp.type = Tango::DEV_BOOLEAN;
Tango::DevBoolean *value = new Tango::DevBoolean[value_size];
size_t ind=0;
for(vector<string>::iterator val=values.begin(); val != values.end() && ind < tmp.size1; val++)
{
if(*val == "true")
value[ind++] = true;
else if(*val == "false")
value[ind++] = false;
else
value[ind++] = atoi(val->c_str());
}
tmp.value = value;
}
else if(config[1] == "long")
{
tmp.type = Tango::DEV_LONG;
Tango::DevLong *value = new Tango::DevLong[value_size];
size_t ind=0;
for(vector<string>::iterator val=values.begin(); val != values.end() && ind < tmp.size1; val++)
{
value[ind++] = atoi(val->c_str());
}
tmp.value = value;
}
else if(config[1] == "double")
{
tmp.type = Tango::DEV_DOUBLE;
Tango::DevDouble *value = new Tango::DevDouble[value_size];
size_t ind=0;
for(vector<string>::iterator val=values.begin(); val != values.end() && ind < tmp.size1; val++)
{
value[ind++] = atof(val->c_str());
}
tmp.value = value;
}
else if(config[1] == "string")
{
tmp.size1 = 1;
tmp.type = Tango::DEV_STRING;
char *value = new char[1024];
memset(value, 0, 1024);
strncpy(value, config[2].c_str(), 1023);
tmp.value = value;
}
if(tmp.size1 == 1)
attr = new ScalarDynAttrib(attrname, tmp.type);
else
attr = new SpectrumDynAttrib(attrname, tmp.type, MAX_SPECTRUM_SIZE);
/*sprintf(strtmp,"Dynamic Attribute %s reading channel %d ",attrname,num_ch);
if(unit != "")
{
attrprop.set_unit(unit.c_str());
attrprop.set_standard_unit("1.0");
attrprop.set_display_unit(unit.c_str());
}
attrprop.set_format("%.9g");
attrprop.set_description(strtmp);*/
attr->set_default_properties(attrprop);
add_attribute(attr);
set_change_event(attrname, true, false);
set_archive_event(attrname, true, false);
attr_data_map.insert(make_pair(attrname, tmp));
try
{
if(config[1] == "bool")
{
set_write_value(((Tango::DevBoolean *)tmp.value), attrname, tmp.size1);
}
else if(config[1] == "long")
{
set_write_value(((Tango::DevLong *)tmp.value), attrname, tmp.size1);
}
else if(config[1] == "double")
{
set_write_value(((Tango::DevDouble *)tmp.value), attrname, tmp.size1);
}
else if(config[1] == "string")
{
Tango::DevString str_ptr = (char *)tmp.value;
set_write_value((Tango::DevString)str_ptr, attrname);
}
} catch(Tango::DevFailed &e)
{
INFO_STREAM << __FUNCTION__ << " error seting write value=" << e.errors[0].desc;
}
}
}
//+------------------------------------------------------------------
/*
* method: TestDevice::string_explode
* Explode a string
*/
//+------------------------------------------------------------------
void TestDevice::string_explode(string str, string separator, vector<string>* results)
{
size_t found;
found = str.find_first_of(separator);
while(found != string::npos) {
if(found > 0) {
results->push_back(str.substr(0,found));
}
str = str.substr(found+1);
found = str.find_first_of(separator);
}
if(str.length() > 0) {
results->push_back(str);
}
}
//+------------------------------------------------------------------
/*
* method: TestDevice::save_configuration
* Save configuration on DB
*/
//+------------------------------------------------------------------
void TestDevice::save_configuration()
{
Tango::Database *db = new Tango::Database();
try
{
db->set_timeout_millis(10000); //10 s timeout
vector<string> configuration;
char conf_str[256];
map<std::string,map_data_t>::iterator it;
for(it = attr_data_map.begin(); it != attr_data_map.end(); it++)
{
double ts = (double)(it->second.ts.tv_sec) + ((double)it->second.ts.tv_usec)/1000000.0;
if(it->second.size1 == 1)
{
if(it->second.type == Tango::DEV_DOUBLE)
sprintf(conf_str, "%s:double:%.16e:%f", it->first.c_str(), *((Tango::DevDouble *) it->second.value), ts);
else if(it->second.type == Tango::DEV_LONG)
sprintf(conf_str, "%s:long:%d:%f", it->first.c_str(), *((Tango::DevLong *) it->second.value), ts);
else if(it->second.type == Tango::DEV_BOOLEAN)
sprintf(conf_str, "%s:bool:%d:%f", it->first.c_str(), *((Tango::DevBoolean *) it->second.value), ts);
else if(it->second.type == Tango::DEV_STRING)
sprintf(conf_str, "%s:string:%s:%f", it->first.c_str(), ((char *) it->second.value), ts);
}
else if(it->second.size1 > 1)
{
stringstream val;
if(it->second.type == Tango::DEV_DOUBLE)
{
for(size_t i=0; i<it->second.size1; i++)
{
val << std::setprecision(std::numeric_limits<double>::digits10+2) << ((Tango::DevDouble *) it->second.value)[i];
if(i < it->second.size1-1)
val << ",";
}
sprintf(conf_str, "%s:double:%s:%f", it->first.c_str(), val.str().c_str(), ts);
}
else if(it->second.type == Tango::DEV_LONG)
{
for(size_t i=0; i<it->second.size1; i++)
{
val << std::setprecision(std::numeric_limits<Tango::DevLong>::digits10+2) << ((Tango::DevLong *) it->second.value)[i];
if(i < it->second.size1-1)
val << ",";
}
sprintf(conf_str, "%s:long:%s:%f", it->first.c_str(), val.str().c_str(), ts);
}
else if(it->second.type == Tango::DEV_BOOLEAN)
{
for(size_t i=0; i<it->second.size1; i++)
{
val << std::setprecision(std::numeric_limits<Tango::DevBoolean>::digits10+2) << ((Tango::DevBoolean *) it->second.value)[i];
if(i < it->second.size1-1)
val << ",";
}
sprintf(conf_str, "%s:bool:%s:%f", it->first.c_str(), val.str().c_str(), ts);
}
else if(it->second.type == Tango::DEV_STRING)
{
//NOT SUPPORTED
}
}
configuration.push_back(conf_str);
DEBUG_STREAM << __FUNCTION__ << " saving " << conf_str;
}
Tango::DbDatum config("Attr_config");
Tango::DbData db_data_put;
config << configuration;
db_data_put.push_back(config);
db->put_device_property(get_name(), db_data_put);
//get_db_device()->put_property(db_data_put);
if(get_state()!=Tango::ON)
set_state(Tango::ON);
} catch(Tango::DevFailed &e)
{
INFO_STREAM << __FUNCTION__ << " error saving properties=" << e.errors[0].desc;
set_state(Tango::FAULT);
}
delete db;
}
long TestDevice::create_dynamic_command(const char* cmd_name, Tango::CmdArgType type_in, Tango::CmdArgType type_out, long size_in, long size_out)
{
std::vector< Tango::Command* >& command_list = get_device_class()->get_command_list();
command_list.push_back(new CmdClass(cmd_name,
type_in, type_out,
"LV argin",
"LV argout",
Tango::OPERATOR,
size_in,
this));
return 0;
}
template <typename Attr_type> void TestDevice::set_write_value(Attr_type *value, string attrname, long x)
{
Tango::WAttribute& wattr = get_device_attr()->get_w_attr_by_name(attrname.c_str());
if(x == 1)
wattr.set_write_value(*value);
else
wattr.set_write_value(value, x);
}
void TestDevice::set_write_value(Tango::DevString value, string attrname)
{
Tango::WAttribute& wattr = get_device_attr()->get_w_attr_by_name(attrname.c_str());
wattr.set_write_value(value);
}
/***************************************************************************
CmdClass class
***************************************************************************/
CORBA::Any *CmdClass::execute(Tango::DeviceImpl *device,const CORBA::Any &in_any)
{
TANGO_LOG << "CmdClass::" << get_name() << ": entering..." << endl;
//const Tango::DevVarLongArray *argin;
//extract(in_any, argin);
return new CORBA::Any();
}
/*bool TestDevice::is_LVCmd_allowed(const CORBA::Any &any)
{
// End of Generated Code
// Re-Start of Generated Code
return true;
}*/
/*----- PROTECTED REGION END -----*/ // TestDevice::namespace_ending
} // namespace