Skip to content
Snippets Groups Projects
Alarm.cpp 134 KiB
Newer Older
/*----- PROTECTED REGION ID(Alarm.cpp) ENABLED START -----*/
static const char *RcsId = "$Id:  $";
//=============================================================================
//
// file :        Alarm.cpp
//
// description : C++ source for the Alarm class 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
//               Alarm are implemented in this file.
//
// project :     alarm
//
// This file is part of Tango device class.
// 
// Tango is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// Tango is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// 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.h>
#include <Alarm.h>
#include <AlarmClass.h>
#include <ctype.h>		//for tolower

#include "alarm-thread.h"
#include "alarm_grammar.h"
#include "log_thread.h"
#include "update-thread.h"

//#define _DUMP_TREE_XML
#ifdef _DUMP_TREE_XML
#if BOOST_VERSION  < 103600
#include <boost/spirit/iterator/fixed_size_queue.hpp>

#include <boost/spirit/core.hpp>
#include <boost/spirit/tree/ast.hpp>
#include <boost/spirit/tree/tree_to_xml.hpp>

using namespace boost::spirit;
#else
#include <boost/spirit/include/classic_fixed_size_queue.hpp>

#include <boost/spirit/include/classic_core.hpp>
#include <boost/spirit/include/classic_ast.hpp>
#include <boost/spirit/include/classic_tree_to_xml.hpp>

using namespace boost::spirit::classic;
#endif
#include <iostream>
#include <stack>
#include <functional>
#include <string>
#include <cassert>
#endif 		//_DUMP_TREE_XML
#include <sstream>

std::map<parser_id, std::string> rule_names;  //only for log messages

int Alarm_ns::Alarm::instanceCounter = 0;

#ifndef ALARM_BUILDTIME
#define ALARM_BUILDTIME    __DATE__ " "  __TIME__ " boost=" BOOST_LIB_VERSION
#endif

const char version_string[] = "$Build: @buildID@ " ALARM_BUILDTIME " $";
static const char __FILE__rev[] = __FILE__ " $Revision: 1.29 $";

/*----- PROTECTED REGION END -----*/	//	Alarm.cpp

/**
 *  Alarm class description:
 *    Elettra alarm device server
 */

//================================================================
//  The following table gives the correspondence
//  between command and method names.
//
//  Command name  |  Method name
//================================================================
//  State         |  Inherited (no method)
//  Status        |  Inherited (no method)
//  Ack           |  ack
//  Load          |  load
//  Remove        |  remove
//  Configured    |  configured
//  StopNew       |  stop_new
//  Silence       |  silence
//  Modify        |  modify
//================================================================

//================================================================
//  Attributes managed is:
//================================================================
//  alarm  |  Tango::DevString	Spectrum  ( max = 1024)
//================================================================

namespace Alarm_ns
{
/*----- PROTECTED REGION ID(Alarm::namespace_starting) ENABLED START -----*/

//	static initializations

/*----- PROTECTED REGION END -----*/	//	Alarm::namespace_starting

//--------------------------------------------------------
/**
 *	Method      : Alarm::Alarm()
 *	Description : Constructors for a Tango device
 *                implementing the classAlarm
 */
//--------------------------------------------------------
Alarm::Alarm(Tango::DeviceClass *cl, string &s)
 : TANGO_BASE_CLASS(cl, s.c_str())
{
	/*----- PROTECTED REGION ID(Alarm::constructor_1) ENABLED START -----*/
	init_device();
	
	/*----- PROTECTED REGION END -----*/	//	Alarm::constructor_1
}
//--------------------------------------------------------
Alarm::Alarm(Tango::DeviceClass *cl, const char *s)
 : TANGO_BASE_CLASS(cl, s)
{
	/*----- PROTECTED REGION ID(Alarm::constructor_2) ENABLED START -----*/
	init_device();
	
	/*----- PROTECTED REGION END -----*/	//	Alarm::constructor_2
}
//--------------------------------------------------------
Alarm::Alarm(Tango::DeviceClass *cl, const char *s, const char *d)
 : TANGO_BASE_CLASS(cl, s, d)
{
	/*----- PROTECTED REGION ID(Alarm::constructor_3) ENABLED START -----*/
	init_device();
	
	/*----- PROTECTED REGION END -----*/	//	Alarm::constructor_3
}

//--------------------------------------------------------
/**
 *	Method      : Alarm::delete_device()
 *	Description : will be called at device destruction or at init command
 */
//--------------------------------------------------------
void Alarm::delete_device()
{
	DEBUG_STREAM << "Alarm::delete_device() " << device_name << endl;
	/*----- PROTECTED REGION ID(Alarm::delete_device) ENABLED START -----*/
	
	//	Delete device allocated objects
	//	Delete device's allocated object
	/*
	 * unsubscribe events and release memory
	 */
	DEBUG_STREAM << "Alarm::delete_device(): entering..." << endl;
	abortflag = true;
	DEBUG_STREAM << "Alarm::delete_device(): after abortflag=true..." << endl;
	try {
		events->unsubscribe_events();
	} catch (string& err) {
		ERROR_STREAM << err << endl;
	}
	DEBUG_STREAM << "Alarm::delete_device(): events unsubscribed!" << endl;
	/*
	 * kill alarm thread
	 */
	bei_t e;
	e.ev_name = ALARM_THREAD_EXIT;
	e.value.push_back(ALARM_THREAD_EXIT_VALUE);
	e.value.push_back(ALARM_THREAD_EXIT_VALUE);
	evlist.push_back(e);
#ifdef _RW_LOCK
	alarms.del_rwlock();
#endif
	alarms.stop_logdb();
	alarms.stop_cmdthread();
	sleep(1);		//wait for alarm_thread and log_thread to exit
	//delete almloop;
	DEBUG_STREAM << "Alarm::delete_device(): stopped alarm and log threads!" << endl;
	
	
	//delete proxy for actions
	for(alarm_container_t::iterator i = alarms.v_alarm.begin(); i!=alarms.v_alarm.end(); i++)
	{
		if(i->second.dp_a)
			delete i->second.dp_a;
		i->second.dp_a = NULL;
		if(i->second.dp_n)
			delete i->second.dp_n;
		i->second.dp_n = NULL;
	}	
	/*
	 * clear all data structures
	 */
	alarms.v_alarm.clear();
	events->v_event.clear();
	evlist.clear();
/*	for (int i = ds_num - 1; i >= 0; i--) {
		CORBA::string_free(ds[i]);
	}*/
	ds_num = 0;
	/*
	 * store current "alarmed" table status
	 */
	vector<string> vs;	
	for (vector<alarm_t>::iterator i = alarmed.begin(); \
			 i != alarmed.end(); i++) {
		vs.push_back(i->alm2str());
	}
	Tango::DbDatum as("AlarmStatus");
	Tango::DbData	data_del;
	data_del.push_back(as);
	//get_db_device()->delete_property(data_del);	
	as << vs;
	Tango::DbData	data_put;
	data_put.push_back(as);
#ifndef _USE_ELETTRA_DB_RW
	Tango::Database *db = new Tango::Database();
#else	
	//salvataggio proprietà usando host_rw e port_rw per connettersi al database
	Tango::Database *db;
	if(host_rw != "")
		db = new Tango::Database(host_rw,port_rw);
	else
		db = new Tango::Database();
#endif
	try {

		db->put_device_property(get_name(), data_put);
	}
	catch(Tango::DevFailed &e)
	{
		ERROR_STREAM << __FUNCTION__<< " error saving properties='" << e.errors[0].desc << "'";
	} 
	delete db;
	
	/*
	 * clear storage
	 */
	alarmed.clear();
	delete alarmedlock;
	delete internallock;
	delete dslock;
	delete events;
	DEBUG_STREAM << "Alarm::delete_device(): saved AlarmStatus in properties!!" << endl;
	//Tango::leavefunc();

	/*----- PROTECTED REGION END -----*/	//	Alarm::delete_device
}

//--------------------------------------------------------
/**
 *	Method      : Alarm::init_device()
 *	Description : will be called at device initialization.
 */
//--------------------------------------------------------
void Alarm::init_device()
{
	DEBUG_STREAM << "Alarm::init_device() create device " << device_name << endl;
	/*----- PROTECTED REGION ID(Alarm::init_device_before) ENABLED START -----*/
	
	//	Initialization before get_device_property() call
	int dbPortint=0;	
	abortflag = false;	
	instanceCounter++;
	events = new event_table(this);
	thread = new SubscribeThread(this);
	//because of static map<string, unsigned int> grp_str and of exception while subscribing
	//more than one time the same event in the same executable, control the number of instances
	if(instanceCounter > 1)		
	{
		ERROR_STREAM << "More than one instance in the same executable of Alarm Server is not allowed!!" << endl;
		cout << "ERROR: second instance of Alarm Server, exiting..." << endl;
		exit(-1);
	}	//-------------------------------------------	
	errThreshold = 0;
	alarmedlock = new(ReadersWritersLock);
	internallock = new(ReadersWritersLock);
	dslock = new(ReadersWritersLock);

	/*----- PROTECTED REGION END -----*/	//	Alarm::init_device_before
	

	//	Get the device properties from database
	get_device_property();
	
	/*----- PROTECTED REGION ID(Alarm::init_device) ENABLED START -----*/
	
	//	Initialize device
	thread->period = subscribeRetryPeriod;
	
#ifdef _USE_ELETTRA_DB_RW
	host_rw = "";
	Tango::Database *db = new Tango::Database();
	try
	{
		Tango::DbData db_data;
		db_data.push_back((Tango::DbDatum("Host")));
		db_data.push_back((Tango::DbDatum("Port")));
		db->get_property("Database",db_data);
 
		db_data[0] >> host_rw;
		db_data[1] >> port_rw;
	}catch(Tango::DevFailed &e)
	{
		ERROR_STREAM << __FUNCTION__ << " Error reading Database property='" << e.errors[0].desc << "'";
	}
	string server = "alarm-srv/test";
	Tango::DbServerInfo info = db->get_server_info(server);
	INFO_STREAM << " INFO: host=" << info.host;

	delete db;
#endif
	
	dbPortint = atoi(dbPort.c_str());
	if(dbHost.empty() || dbUser.empty() || dbPasswd.empty() || dbName.empty() || (dbPortint == 0) || instanceName.empty())
	{
		ERROR_STREAM << "Alarm::init_device(): not all necessary properties are defined: DbHost="<<dbHost<<
			" DbUser="<<dbUser<<" DbPasswd="<<dbPasswd<<" DbName="<<dbName<<" DbPort="<<dbPortint<<" InstanceName="<<instanceName<< endl;
		cout << "Error: not all necessary properties are defined. Exiting..." << endl;
		exit(-2);
	}	
	ds_num = 0;				//initialize number of lines returned by read_alarm
	internal_counter = 0;

	/*Tango::DbData db_data;
	db_data.push_back(Tango::DbDatum("alarm"));
	get_db_device()->get_attribute_property(db_data);*/
	/*
	 * connect to log database
	 */	
#ifdef _RW_LOCK
	alarms.new_rwlock();
#endif
	try {
		if((!dbHost.empty()) && (!dbUser.empty()) && (!dbPasswd.empty()) && (!dbName.empty()) && (dbPortint != 0) )
			//logloop = new log_thread(dbhost, dbuser, dbpw, dbname, dbportint,this);
			alarms.init_logdb(dbHost, dbUser, dbPasswd, dbName, dbPortint, instanceName);
	} catch(string & e)
	{
		ERROR_STREAM << "Alarm::init_device(): " << e << endl;
		cout << "Error: " << e << ". Exiting..." << endl;
		exit(-3);
	}
	
	try {
		alarms.init_cmdthread();
	} catch(...)
	{
		WARN_STREAM << "Alarm::init_device(): error creating cmd thread" << endl;
	}	
	
	rule_names[formula_grammar::val_rID] = "ValReal";
	rule_names[formula_grammar::val_hID] = "ValHex";
	rule_names[formula_grammar::val_stID] = "ValStatus";
	rule_names[formula_grammar::event_ID] = "EventFather";
	rule_names[formula_grammar::nameID] = "EventName";
	rule_names[formula_grammar::indexID] = "EventIndex";
	rule_names[formula_grammar::funcID] = "Function";
	rule_names[formula_grammar::logical_exprID] = "LogicalE";
	rule_names[formula_grammar::bitwise_exprID] = "BitwiseE";
	rule_names[formula_grammar::equality_exprID] = "EqualityE";
	rule_names[formula_grammar::compare_exprID] = "CompareE";
	rule_names[formula_grammar::add_exprID] = "AddE";
	rule_names[formula_grammar::mult_exprID] = "MultE";
	rule_names[formula_grammar::expr_atomID] = "AtomicE";
	rule_names[formula_grammar::shift_exprID] = "ShiftE";
	rule_names[formula_grammar::unary_exprID] = "UnaryE";    	
	
	/*
	 * get device attribute properties and initialize internal
	 * data structures
	 */
//	short n_prop;
	string expr;
	string pr_name;
	vector<string> tmp_alm_vec;
/*	db_data[0] >> n_prop;
	INFO_STREAM << "Number alarm to load = " << n_prop << endl;
	for (int i = 1; i <= n_prop; i++) 
	{
		pr_name = db_data[i].name;
		db_data[i] >> expr;
		DEBUG_STREAM << "	-> attr property: " << pr_name << " = " << expr << endl;
    	size_t pos = pr_name.find('_');
    	int count_ = 1;
    	while(pos != string::npos) 	//TODO: better this control
    	{
      		pos = pr_name.find('_', pos+1);
      		count_++;
      		if((count_ == 3) && (pos != string::npos))	//if at least 3 _ in the attr property name, expr is OK  	//TODO: better this control
      		{
				tmp_alm_vec.push_back(expr);
				break;      		
      		}	
    	}
	}*/
	try {
		alarms.get_alarm_list_db(tmp_alm_vec);
	} catch(string & e)
	{
		ERROR_STREAM << "Alarm::init_device(): " << e << endl;
		cout << "Error: " << e << ". Exiting..." << endl;
		exit(-4);
	}		
	
	
	/*
	 * store the alarms into alarm table vector
	 */
	map< string,vector<string> > alarm_event;	//map alarm->vector event popolated by parser
	vector<string> evn;	 						//vector with all event (possibly duplicated) popolated by parser
	vector<string> temp_evn;	
	vector<string> tmp_alm_name_lst; 						
	//alarms.init(tmp_alm_vec, evn, alarm_event);
	alarm_t tmp_alm;
	evn.clear();
	for(vector<string>::iterator it_al = tmp_alm_vec.begin(); it_al!= tmp_alm_vec.end(); it_al++)
	{
		tmp_alm.clear();
		temp_evn.clear();
		try {		
			load_alarm(*it_al, tmp_alm, temp_evn);
			add_alarm(tmp_alm);
			tmp_alm_name_lst.push_back(tmp_alm.name);
		} catch(Tango::DevFailed& e)
		{
			ostringstream err;
			err << "error loading alarm=" << tmp_alm.name << " , " << e.errors[0].desc << ends;
			WARN_STREAM << "Alarm::init_device(): " << err.str() << endl;
			set_internal_alarm(INTERNAL_ERROR, gettime(), err.str());
			continue;
		} catch (string& err) {
			ostringstream err_out;
			err_out << "error loading alarm=" << tmp_alm.name << " , " << err << ends;
			WARN_STREAM << "Alarm::init_device(): " << err_out.str() << endl;
			set_internal_alarm(INTERNAL_ERROR, gettime(), err_out.str());
			continue;
		}
		//eliminate duplicated event
		if (temp_evn.empty() == false) 
		{		
			sort(temp_evn.begin(), temp_evn.end());
			vector<string>::iterator new_end = \
				unique(temp_evn.begin(), temp_evn.end());
			while (temp_evn.end() != new_end) 
				temp_evn.pop_back();
		}
		alarm_event.insert(make_pair(tmp_alm.name,temp_evn));
		evn.insert(evn.end(),temp_evn.begin(),temp_evn.end());
/*		alarms.log_alarm_db(TYPE_LOG_DESC_SYNC, gettime(), tmp_alm.name, "", "", 		//remove if alarm with the same name exist but is changed
			tmp_alm.formula, tmp_alm.grp2str(), tmp_alm.lev, tmp_alm.msg);		
		alarms.log_alarm_db(TYPE_LOG_DESC_ADD, gettime(), tmp_alm.name, "", "", 		//add new alarm if there is not already one active with the same name
			tmp_alm.formula, tmp_alm.grp2str(), tmp_alm.lev, tmp_alm.msg);*/		
	}
/*	alarms.log_alarm_db(TYPE_LOG_DESC_UPD_OLD, gettime(), "", "", "", 		//set as not active all alarms not present in this list
		"", "", "", "", tmp_alm_name_lst);*/		
	DEBUG_STREAM << "alarms table size = " << alarms.size() << endl;
	
	vector<string> al_table_string;
	alarms.show(al_table_string);
	for(vector<string>::iterator str_it=al_table_string.begin(); str_it!=al_table_string.end(); str_it++)
		DEBUG_STREAM << (*str_it) << endl;

	/*
	 * check 'stored' alarms against current alarm table for consistency
	 */
	vector<string> to_remove_from_stored;
	if (stored.empty() == false) {
		for (vector<alarm_t>::iterator i = stored.begin(); \
			 	 i != stored.end(); i++) {
			alarm_container_t::iterator found = alarms.v_alarm.find(i->name);
			if (found == alarms.v_alarm.end()) {

				to_remove_from_stored.push_back(i->name);
				//stored.erase(i);
			}
		}
	}
	for(vector<string>::iterator k=to_remove_from_stored.begin(); k != to_remove_from_stored.end(); k++)
	{
		vector<alarm_t>::iterator rmv = find(stored.begin(),stored.end(),*k);
		if(rmv != stored.end())
		{
			ERROR_STREAM << "init_device(): alarm '" << *k \
							 << "' NOT found in alarm table! " \
			 	 			 << "Removing from 'stored' alarms" << endl;			
			stored.erase(rmv);
		}
		else
			WARN_STREAM << "init_device(): alarm " << *k << " not found while removing from stored !!!" << endl;
	}
	/*
	 * update "alarm" table with "stored" alarms
	 */
	alarms.stored(stored);
	/*
	 * update "alarmed" table with "stored" alarms
	 */ 
	if (stored.empty() == false) {
		alarmedlock->writerIn();
		for (vector<alarm_t>::iterator i = stored.begin(); \
			 	 i != stored.end(); i++) {
			alarmed.push_back(*i);
		}
		alarmedlock->writerOut();
	}

	for(alarm_container_t::iterator i = alarms.v_alarm.begin(); \
		i!=alarms.v_alarm.end(); i++)
	{
		if(i->second.cmd_name_a.length() > 0)
		{
			try {
				i->second.dp_a = new Tango::DeviceProxy(i->second.cmd_dp_a);
				i->second.dp_a->ping();
				Tango::CommandInfo info = i->second.dp_a->command_query(i->second.cmd_action_a);
				if((info.in_type != Tango::DEV_STRING) && (info.in_type != Tango::DEV_VOID))
				{
					ostringstream err;
					err << i->second.name << ": error, command " << i->second.cmd_name_a << " does not accept a Tango::DevString or a Tango::DevVoid as input value" << ends;
					ERROR_STREAM << "Alarm::init_device(): " << err.str() << endl;
					set_internal_alarm(INTERNAL_ERROR, gettime(), err.str());
				}
				else
				{				
					if(info.in_type == Tango::DEV_STRING)
						i->second.send_arg_a = true;
					else
						i->second.send_arg_a = false;				
					DEBUG_STREAM << "Alarm::init_device(): " << i->second.name << ": successfully connected to proxy=" << i->second.cmd_dp_a << " for action=" << i->second.cmd_action_a << endl;
				}
			} catch(Tango::DevFailed& e)
			{
				ostringstream err;
				err << i->second.name << ": error connecting to device proxy=" << i->second.cmd_dp_a << ", err=" << e.errors[0].desc << ends;
				WARN_STREAM << "Alarm::init_device(): " << err.str() << endl;
				set_internal_alarm(INTERNAL_ERROR, gettime(), err.str());
				i->second.dp_a = NULL;
			}						
		}
		if(i->second.cmd_name_n.length() > 0)
		{
			try {
				i->second.dp_n = new Tango::DeviceProxy(i->second.cmd_dp_n);
				i->second.dp_n->ping();
				Tango::CommandInfo info = i->second.dp_n->command_query(i->second.cmd_action_n);
				if((info.in_type != Tango::DEV_STRING) && (info.in_type != Tango::DEV_VOID))
				{
					ostringstream err;
					err << i->second.name << ": error, command " << i->second.cmd_name_n << " does not accept a Tango::DevString or a Tango::DevVoid as input value" << ends;
					ERROR_STREAM << "Alarm::init_device(): " << err.str() << endl;
					set_internal_alarm(INTERNAL_ERROR, gettime(), err.str());
				}
				else
				{				
					if(info.in_type == Tango::DEV_STRING)
						i->second.send_arg_n = true;
					else
						i->second.send_arg_n = false;
					DEBUG_STREAM << "Alarm::init_device(): " << i->second.name << ": successfully connected to proxy=" << i->second.cmd_dp_n << " for action=" << i->second.cmd_action_n << endl;
				}
			} catch(Tango::DevFailed& e)
			{
				ostringstream err;
				err << i->second.name << ": error connecting to device proxy=" << i->second.cmd_dp_n << ", err=" << e.errors[0].desc << ends;
				WARN_STREAM << "Alarm::init_device(): " << err.str() << endl;
				set_internal_alarm(INTERNAL_ERROR, gettime(), err.str());
				i->second.dp_n = NULL;
			}						
		}		
	}
		
	alarms.startup_complete = gettime();			//enable actions execution in 10 seconds
	
	//TODO:ecb.init(&evlist);
	for(map<string, vector<string> >::iterator al_ev_it=alarm_event.begin(); \
		al_ev_it!=alarm_event.end(); al_ev_it++)
	{
		alarm_container_t::iterator i = alarms.v_alarm.find(al_ev_it->first);
		if(i != alarms.v_alarm.end())
		{		
				//add_event(i->second, al_ev_it->second);
				//TODO:subscribe_event(i->second, ecb, al_ev_it->second);
				for (vector<string>::iterator j = al_ev_it->second.begin(); j != al_ev_it->second.end(); j++)
				{
					vector<event>::iterator k = \
							find(events->v_event.begin(), events->v_event.end(), *j);
					if (k == events->v_event.end())	//if not already present
					{
						string name=*j;
						vector<string> context;//TODO
						events->add(name, context);
					}
				}
				add_event(i->second, al_ev_it->second);//moved after events->add
				for (vector<string>::iterator j = al_ev_it->second.begin(); j != al_ev_it->second.end(); j++)
				{
					vector<event>::iterator k = \
							find(events->v_event.begin(), events->v_event.end(), *j);
					if (k == events->v_event.end())	//if not already present
					{
						string name=*j;
						events->start(name);
					}
				}
			} catch (string& err) {
				WARN_STREAM << "Alarm::init_device(): " << err << endl;				
				for(vector<string>::iterator j=al_ev_it->second.begin(); j!=al_ev_it->second.end(); j++)
				{
					DEBUG_STREAM << "Alarm::init_device(): Removing alarm=" << i->second.name << " from event=" << *j << endl;
					vector<event>::iterator k = \
						find(events->v_event.begin(), events->v_event.end(), *j);
					if (k != events->v_event.end())
					{
						k->pop_alarm(i->second.name);		//remove alarm/formula just added to event
						DEBUG_STREAM << "Alarm::init_device(): Removed!!!! alarm=" << i->second.name << " from event=" << *j << endl;						
						if(k->m_alarm.empty())
						{
							events->v_event.erase(k);	//remove event just added to event_table
							DEBUG_STREAM << "Alarm::init_device(): event=" << *j << " no more used, REMOVED!!!" << endl;
						}
					}
				}			
				set_internal_alarm(INTERNAL_ERROR, gettime(), err);
			}
#else
			try {
				add_event(i->second, al_ev_it->second);
			} catch (string& err) {
				WARN_STREAM << "Alarm::init_device(): " << err << endl;
				set_internal_alarm(INTERNAL_ERROR, gettime(), err);
			}
			try {
				subscribe_event(i->second, ecb, al_ev_it->second);
			} catch (string& err) {
				WARN_STREAM << "Alarm::init_device(): " << err << endl;
				set_internal_alarm(INTERNAL_ERROR, gettime(), err);
			}			
#endif
		}
	}
	
#if 0
	//now subscribe all events
	for (vector<string>::iterator j = evn.begin(); j != evn.end(); j++)
	{
		vector<event>::iterator k = \
				find(events->v_event.begin(), events->v_event.end(), *j);
		if (k != events->v_event.end())
		{

		}
	}
#endif


	/*
	 * update event table with fresh-subscribed event[s] data
	 */
	 
	list<bei_t> el;
	el = evlist.show();

	try {
		for (list<bei_t>::iterator j = el.begin(); j != el.end(); j++) 
		{
			//cout << "name = " << j->name << "\ttype = " << j->type << endl;
			events->update_events(*j);
		}
	}
	catch (string& err)
	{
		WARN_STREAM << "init_device(): error updating events = " << err << endl;
	}
	set_change_event("alarm",true,false);
	/*
	 * create alarm processing thread
	 */

	//almloop = new alarm_thread::alarm_thread(/*this*/);
	almloop = new alarm_thread(this);
	almloop->start();
	
	updateloop = new update_thread(this);
	updateloop->start();

	thread->start();

	events->start_all();
	
  	set_state(Tango::RUNNING);
	set_status("Alarm server is running");	

	//

//	for (int i=0; i< MAX_ALARMS ; i++) ds[i]=0;
//	ds_num = 0;
	for (int i=0; i< MAX_ALARMS ; i++)
		ds[i]=(char *) (dss[i]);

	/*----- PROTECTED REGION END -----*/	//	Alarm::init_device
}

//--------------------------------------------------------
/**
 *	Method      : Alarm::get_device_property()
 *	Description : Read database to initialize property data members.
 */
//--------------------------------------------------------
void Alarm::get_device_property()
{
	/*----- PROTECTED REGION ID(Alarm::get_device_property_before) ENABLED START -----*/
	
	//	Initialize property data members
	

	/*----- PROTECTED REGION END -----*/	//	Alarm::get_device_property_before


	//	Read device properties from database.
	Tango::DbData	dev_prop;
	dev_prop.push_back(Tango::DbDatum("AlarmStatus"));
	dev_prop.push_back(Tango::DbDatum("GroupNames"));
	dev_prop.push_back(Tango::DbDatum("ErrThreshold"));
	dev_prop.push_back(Tango::DbDatum("DbHost"));
	dev_prop.push_back(Tango::DbDatum("DbUser"));
	dev_prop.push_back(Tango::DbDatum("DbPasswd"));
	dev_prop.push_back(Tango::DbDatum("DbName"));
	dev_prop.push_back(Tango::DbDatum("DbPort"));
	dev_prop.push_back(Tango::DbDatum("InstanceName"));
	dev_prop.push_back(Tango::DbDatum("SubscribeRetryPeriod"));

	//	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 AlarmClass to get class property
		Tango::DbDatum	def_prop, cl_prop;
		AlarmClass	*ds_class =
			(static_cast<AlarmClass *>(get_device_class()));
		int	i = -1;

		//	Try to initialize AlarmStatus from class property
		cl_prop = ds_class->get_class_property(dev_prop[++i].name);
		if (cl_prop.is_empty()==false)	cl_prop  >>  alarmStatus;
		else {
			//	Try to initialize AlarmStatus from default device value
			def_prop = ds_class->get_default_device_property(dev_prop[i].name);
			if (def_prop.is_empty()==false)	def_prop  >>  alarmStatus;
		}
		//	And try to extract AlarmStatus value from database
		if (dev_prop[i].is_empty()==false)	dev_prop[i]  >>  alarmStatus;

		//	Try to initialize GroupNames from class property
		cl_prop = ds_class->get_class_property(dev_prop[++i].name);
		if (cl_prop.is_empty()==false)	cl_prop  >>  groupNames;
		else {
			//	Try to initialize GroupNames from default device value
			def_prop = ds_class->get_default_device_property(dev_prop[i].name);
			if (def_prop.is_empty()==false)	def_prop  >>  groupNames;
		}
		//	And try to extract GroupNames value from database
		if (dev_prop[i].is_empty()==false)	dev_prop[i]  >>  groupNames;

		//	Try to initialize ErrThreshold from class property
		cl_prop = ds_class->get_class_property(dev_prop[++i].name);
		if (cl_prop.is_empty()==false)	cl_prop  >>  errThreshold;
		else {
			//	Try to initialize ErrThreshold from default device value
			def_prop = ds_class->get_default_device_property(dev_prop[i].name);
			if (def_prop.is_empty()==false)	def_prop  >>  errThreshold;
		}
		//	And try to extract ErrThreshold value from database
		if (dev_prop[i].is_empty()==false)	dev_prop[i]  >>  errThreshold;

		//	Try to initialize DbHost from class property
		cl_prop = ds_class->get_class_property(dev_prop[++i].name);
		if (cl_prop.is_empty()==false)	cl_prop  >>  dbHost;
		else {
			//	Try to initialize DbHost from default device value
			def_prop = ds_class->get_default_device_property(dev_prop[i].name);
			if (def_prop.is_empty()==false)	def_prop  >>  dbHost;
		}
		//	And try to extract DbHost value from database
		if (dev_prop[i].is_empty()==false)	dev_prop[i]  >>  dbHost;

		//	Try to initialize DbUser from class property
		cl_prop = ds_class->get_class_property(dev_prop[++i].name);
		if (cl_prop.is_empty()==false)	cl_prop  >>  dbUser;
		else {
			//	Try to initialize DbUser from default device value
			def_prop = ds_class->get_default_device_property(dev_prop[i].name);
			if (def_prop.is_empty()==false)	def_prop  >>  dbUser;
		}
		//	And try to extract DbUser value from database
		if (dev_prop[i].is_empty()==false)	dev_prop[i]  >>  dbUser;

		//	Try to initialize DbPasswd from class property
		cl_prop = ds_class->get_class_property(dev_prop[++i].name);
		if (cl_prop.is_empty()==false)	cl_prop  >>  dbPasswd;
		else {
			//	Try to initialize DbPasswd from default device value
			def_prop = ds_class->get_default_device_property(dev_prop[i].name);
			if (def_prop.is_empty()==false)	def_prop  >>  dbPasswd;
		}
		//	And try to extract DbPasswd value from database
		if (dev_prop[i].is_empty()==false)	dev_prop[i]  >>  dbPasswd;

		//	Try to initialize DbName from class property
		cl_prop = ds_class->get_class_property(dev_prop[++i].name);
		if (cl_prop.is_empty()==false)	cl_prop  >>  dbName;
		else {
			//	Try to initialize DbName from default device value
			def_prop = ds_class->get_default_device_property(dev_prop[i].name);
			if (def_prop.is_empty()==false)	def_prop  >>  dbName;
		}
		//	And try to extract DbName value from database
		if (dev_prop[i].is_empty()==false)	dev_prop[i]  >>  dbName;

		//	Try to initialize DbPort from class property
		cl_prop = ds_class->get_class_property(dev_prop[++i].name);
		if (cl_prop.is_empty()==false)	cl_prop  >>  dbPort;
		else {
			//	Try to initialize DbPort from default device value
			def_prop = ds_class->get_default_device_property(dev_prop[i].name);
			if (def_prop.is_empty()==false)	def_prop  >>  dbPort;
		}
		//	And try to extract DbPort value from database
		if (dev_prop[i].is_empty()==false)	dev_prop[i]  >>  dbPort;

		//	Try to initialize InstanceName from class property
		cl_prop = ds_class->get_class_property(dev_prop[++i].name);
		if (cl_prop.is_empty()==false)	cl_prop  >>  instanceName;
		else {
			//	Try to initialize InstanceName from default device value
			def_prop = ds_class->get_default_device_property(dev_prop[i].name);
			if (def_prop.is_empty()==false)	def_prop  >>  instanceName;
		}
		//	And try to extract InstanceName value from database
		if (dev_prop[i].is_empty()==false)	dev_prop[i]  >>  instanceName;

		//	Try to initialize SubscribeRetryPeriod from class property
		cl_prop = ds_class->get_class_property(dev_prop[++i].name);
		if (cl_prop.is_empty()==false)	cl_prop  >>  subscribeRetryPeriod;
		else {
			//	Try to initialize SubscribeRetryPeriod from default device value
			def_prop = ds_class->get_default_device_property(dev_prop[i].name);
			if (def_prop.is_empty()==false)	def_prop  >>  subscribeRetryPeriod;
		}
		//	And try to extract SubscribeRetryPeriod value from database
		if (dev_prop[i].is_empty()==false)	dev_prop[i]  >>  subscribeRetryPeriod;

	}

	/*----- PROTECTED REGION ID(Alarm::get_device_property_after) ENABLED START -----*/
	
	//	Check device property data members init
	/*
	 * initialize groups
	 */	
	alarm_t tmp_alm;						
	tmp_alm.init_static_map(groupNames); 
	
	/*
	 * retrive last saved alarms status
	 */
	if (alarmStatus.empty() == false) {
		for (vector<string>::iterator i = alarmStatus.begin(); \
			 	 i != alarmStatus.end(); i++) {
			/*
			 * test for string length; data[1].is_empty() will return false
			 * when empty string eventually initialized with jive!!!!!!
			 */
			if (i->length() != 0) {
				alarm_t tmp_alm;
				tmp_alm.str2alm(*i);
				tmp_alm.is_new = /*(tmp_alm.stat == S_ALARM) ? 1 :*/ 0; //don't beep at startup on old alarms
				stored.push_back(tmp_alm);
			}
		}
	}
	DEBUG_STREAM << "saved alarms table:" << endl;
	if (stored.empty() == false) {
		for (vector<alarm_t>::iterator a = stored.begin(); \
			 	 a != stored.end(); a++) {
			DEBUG_STREAM << "\t" << a->alm2str() << endl;
		}
	}

	/*----- PROTECTED REGION END -----*/	//	Alarm::get_device_property_after
}

//--------------------------------------------------------
/**
 *	Method      : Alarm::always_executed_hook()
 *	Description : method always executed before any command is executed
 */
//--------------------------------------------------------
void Alarm::always_executed_hook()
{
	DEBUG_STREAM << "Alarm::always_executed_hook()  " << device_name << endl;
	/*----- PROTECTED REGION ID(Alarm::always_executed_hook) ENABLED START -----*/
	
	//	code always executed before all requests
	

	/*----- PROTECTED REGION END -----*/	//	Alarm::always_executed_hook
}

//--------------------------------------------------------
/**
 *	Method      : Alarm::read_attr_hardware()
 *	Description : Hardware acquisition for attributes
 */
//--------------------------------------------------------
void Alarm::read_attr_hardware(TANGO_UNUSED(vector<long> &attr_list))
{
	DEBUG_STREAM << "Alarm::read_attr_hardware(vector<long> &attr_list) entering... " << endl;
	/*----- PROTECTED REGION ID(Alarm::read_attr_hardware) ENABLED START -----*/
	
	//	Add your own code
	//DEBUG_STREAM << "In read_attr_hardware for " << attr_list.size() << " attribute(s)" << endl;
	
	//	Add your own code here
	//---------------------------------

	/*----- PROTECTED REGION END -----*/	//	Alarm::read_attr_hardware
}

//--------------------------------------------------------
/**
 *	Read attribute alarm related method
 *	Description: 
 *
 *	Data type:	Tango::DevString
 *	Attr type:	Spectrum max = 1024
 */
//--------------------------------------------------------
void Alarm::read_alarm(Tango::Attribute &attr)
{
	DEBUG_STREAM << "Alarm::read_alarm(Tango::Attribute &attr) entering... " << endl;
	/*----- PROTECTED REGION ID(Alarm::read_alarm) ENABLED START -----*/
	// Add your own code here
#if 0
	alarm_container_t::iterator ai;
	vector<alarm_t>::iterator aid;
	for (ai = alarms.v_alarm.begin(); ai != alarms.v_alarm.end(); ai++) {
		if (ai->second.stat == S_ALARM) {
			/*
			 * alarm status is S_ALARM
			 */
			aid = find(alarmed.begin(), alarmed.end(),ai->second.name);
			if (aid != alarmed.end()) {
				/*
				 * found, change stat only if switching from
				 * S_NORMAL to S_ALARM status
				 */
				//cout << "read_attr(): S_ALARM: found: " << aid->name << endl;
				if (aid->stat == S_NORMAL) {
					aid->stat = S_ALARM;
					aid->ack = NOT_ACK;
					aid->ts = ai->second.ts;
					aid->msg = ai->second.msg;
				}
				aid->grp = ai->second.grp;
				aid->lev = ai->second.lev;				
				aid->is_new = ai->second.is_new;			//copy is_new state
				//ai->second.is_new = 0;						//and set state as not more new //12-06-08: StopNew command set it to 0
				aid->counter = ai->second.counter;
				aid->ack = ai->second.ack;					//if already acknowledged but has arrived new alarm ack is reset
				aid->silenced = ai->second.silenced;		//update silenced from alarm table (maybe not necessary)
				aid->silent_time = ai->second.silent_time;	//if already alarmed and not saved correctly in properties needed to update
			} else {
				/*
				 * not found: new "alarmed" item
				 */
				DEBUG_STREAM << "read_attr(): S_ALARM: pushing new alarm: " \
						 				 << ai->second.name << "\t" << ai->second.stat << endl;
				alarmed.push_back(ai->second);
				//ai->second.is_new = 0;						//set state as not more new		//12-06-08: StopNew command set it to 0
			}
		} else if (ai->second.stat == S_NORMAL) {
			/*
			 * alarm status is S_NORMAL
			 */
			aid = find(alarmed.begin(), alarmed.end(), ai->second.name);
			if (aid != alarmed.end()) {
				/*
				 * found, as it should;
				 * switching from S_ALARM to S_NORMAL
				 */
				aid->stat = S_NORMAL;
				aid->ts = ai->second.ts;
				//aid->msg = " ";						/* no message again */
				aid->msg =ai->second.msg;
				aid->grp = ai->second.grp;
				aid->lev = ai->second.lev;
				aid->counter = ai->second.counter;
				aid->ack = ai->second.ack;					//if already acknowledged but has arrived new alarm ack is reset				
				aid->is_new = ai->second.is_new;			//copy is_new state
				aid->silenced = ai->second.silenced;		//update silenced from alarm table (maybe not necessary)
				aid->silent_time = ai->second.silent_time;	//if already alarmed and not saved correctly in properties needed to update
				//ai->second.is_new = 0;						//and set state as not more new		//12-06-08: StopNew command set it to 0
				if (aid->ack == ACK) {
					if (aid->done) {
						/*
					 	 * if already ACKnowledged and visualized
					 	 * remove from "alarmed" list
					 	 */
						DEBUG_STREAM << "read_attr(): S_NORMAL: " << aid->name \
								 				 << " ACKnowledged: removing" << endl;
						alarmed.erase(aid);
					} else {
						aid->done = true;
					}
				}	 /* if */
			}  /* if */
		}  /* if else if */
	}  /* for */
	
	vector<string> tmp_alarm_table;
	string is_new;
	ostringstream os1;		
	/*os1.clear();
	os1 << header << "\t" << alarmed.size() << ends;*/
	//tmp_alarm_table.push_back(os1.str());
	if (alarmed.empty() == false) {
		for (aid = alarmed.begin(); aid != alarmed.end(); aid++) {
			if(aid->silenced > 0)
			{
				Tango::TimeVal now = gettime();
				double dnow = now.tv_sec + ((double)now.tv_usec) / 1000000;
				double dsilent = aid->ts_time_silenced.tv_sec + ((double)aid->ts_time_silenced.tv_usec) / 1000000;
				double dminutes = (dnow - dsilent)/60;
				//silenced already calculated in alarm_table::update, but here updated for panel also if state not changed:
				//to see minutes countdown
				if(dminutes < aid->silent_time)
					aid->silenced = aid->silent_time - floor(dminutes);
				else
					aid->silenced = 0;
			}
			ostringstream os;
			os.clear();
			is_new.clear();
			is_new = (aid->is_new && aid->silenced <= 0) ? "NEW" : " ";
			os << aid->ts.tv_sec << "\t" << aid->ts.tv_usec << "\t" \
			 	 << aid->name << "\t" << aid->stat << "\t" << aid->ack \
				 << "\t" << aid->counter << "\t" << aid->lev << "\t" << aid->silenced << "\t" << aid->grp2str() << "\t" << aid->msg << "\t" << is_new << ends;
			tmp_alarm_table.push_back(os.str());
		}
	}		
	if (internal.empty() == false) {
		for (aid = internal.begin(); aid != internal.end(); aid++) {
			
/*			size_t index;
			int count = 1;
			index = aid->stat.find("*");
			if((index != std::string::npos) && (index+1 != std::string::npos))
			{
				
				size_t last = aid->stat.size();
				string str_count= aid->stat.substr(index+1, last - index+1);      
				count = strtol(str_count.c_str(), 0,10); 
			}	
			//do not show internal alarms that have a molteplicity less then errThreshold
			if((aid->msg.find()) && (count < errThreshold))
				continue;*/			
			
			ostringstream os;
			os.clear();
			os << aid->ts.tv_sec << "\t" << aid->ts.tv_usec << "\t" \
			 	 << aid->name << "\t" << aid->stat << "\t" << aid->ack \
				 << "\t" << aid->counter << "\t" << aid->lev << "\t"<< -1/*silenced*/ <<"\t" << aid->grp2str() << "\t" << aid->msg << "\t "<< ends; //TODO: silenced for internal errors?
			tmp_alarm_table.push_back(os.str());
		}
	}
	int i;
	for (i = ds_num - 1; i >= 0; i--) {
		CORBA::string_free(ds[i]);
	}
	ds_num = tmp_alarm_table.size();
	if(ds_num > MAX_ALARMS)
		ds_num = MAX_ALARMS;		
	for (i = 0; i < ds_num; i++) {
		ds[i] = CORBA::string_dup(tmp_alarm_table[i].c_str());
	}
	if(ds_num == 0)
	{
		ostringstream os1;
		ds_num++;
		os1.clear();
		os1 << 0 << "\t" << 0 << "\t" << 0 << "\t" << 0 << "\t" << 0 << "\t" << 0 << "\t" << 0 << "\t" << -1 << "\t" << 0 << "\t" << 0 << "\t "<< ends;
		ds[0] = CORBA::string_dup(os1.str().c_str());
	}
#else
	//bool changed;
	//prepare_alarm_attr(changed);//moved in do_alarm;
#endif
	if(ds_num == 0)
	{
		attr.set_value_date_quality(ds,0/*gettime()*/,Tango::ATTR_WARNING, ds_num, 0, false);
	}
	else
		attr.set_value(ds, ds_num, 0, false);

	/*----- PROTECTED REGION END -----*/	//	Alarm::read_alarm
}

//--------------------------------------------------------
/**
 *	Read attribute AlarmState related method
 *	Description: 
 *
 *	Data type:	Tango::DevBoolean
 *	Attr type:	Scalar
 */
//--------------------------------------------------------
void Alarm::read_AlarmState(Tango::Attribute &attr)
{
	DEBUG_STREAM << "Alarm::read_AlarmState(Tango::Attribute &attr) entering... " << endl;
	Tango::DevBoolean	*att_value = get_AlarmState_data_ptr(attr.get_name());
	/*----- PROTECTED REGION ID(Alarm::read_AlarmState) ENABLED START -----*/
	string reason("");
	string desc("");
	string origin("");
	int quality = Tango::ATTR_VALID;
#ifndef _RW_LOCK
	alarms.lock();
#else
	alarms.vlock->readerIn();
#endif
	alarm_container_t::iterator it;
	for(it = alarms.v_alarm.begin(); it != alarms.v_alarm.end(); it++)
	{
		if(it->second.attr_name == attr.get_name())
		{

			break;
		}
	}
	if(it != alarms.v_alarm.end())
	{
		reason = it->second.ex_reason;
		desc = it->second.ex_desc;
		origin = it->second.ex_origin;
		quality = it->second.quality;
	}
	DEBUG_STREAM << "Alarm::read_AlarmState: " << attr.get_name() << " desc=" << desc << endl;
#ifndef _RW_LOCK
	alarms.unlock();
#else
	alarms.vlock->readerOut();
#endif
	if(desc.length() > 0)
	{
		Tango::Except::throw_exception(
				reason,
				desc,
				origin, Tango::ERR);
	}
	//	Set the attribute value
	if(quality != Tango::ATTR_VALID)
	{
		timeval now;
		gettimeofday(&now, NULL);
		attr.set_value_date_quality(att_value, now/*TODO timestamp*/, (Tango::AttrQuality)quality);
	}
	else
	{
		attr.set_value(att_value);
	}
	
	/*----- PROTECTED REGION END -----*/	//	Alarm::read_AlarmState
}
//--------------------------------------------------------
/**
 *	Method      : Alarm::add_dynamic_attributes()
 *	Description : Create the dynamic attributes if any
 *                for specified device.
 */
//--------------------------------------------------------
void Alarm::add_dynamic_attributes()
{
	//	Example to add dynamic attribute:
	//	Copy inside the following protected area to create instance(s) at startup.
	//	add_AlarmState_dynamic_attribute("MyAlarmStateAttribute");
	
	/*----- PROTECTED REGION ID(Alarm::add_dynamic_attributes) ENABLED START -----*/
	
	//	Add your own code to create and add dynamic attributes if any
#ifndef _RW_LOCK
	alarms.lock();
#else
	alarms.vlock->readerIn();
#endif
	if (alarms.v_alarm.empty() == false)
	{
		for (alarm_container_t::iterator i = alarms.v_alarm.begin(); \
			i != alarms.v_alarm.end(); i++)
		{
			add_AlarmState_dynamic_attribute(i->second.attr_name);
			Tango::DevBoolean *attr_value = get_AlarmState_data_ptr(i->second.attr_name);
			i->second.attr_value = attr_value;
		}
	}
#ifndef _RW_LOCK
	alarms.unlock();
#else
	alarms.vlock->readerOut();
#endif

	
	/*----- PROTECTED REGION END -----*/	//	Alarm::add_dynamic_attributes
}

//--------------------------------------------------------
/**
 *	Command Ack related method
 *	Description: Alarm acknowledge
 *
 *	@param argin String array containing the alarms to be acknowledged
 */
//--------------------------------------------------------
void Alarm::ack(const Tango::DevVarStringArray *argin)
{
	DEBUG_STREAM << "Alarm::Ack()  - " << device_name << endl;
	/*----- PROTECTED REGION ID(Alarm::ack) ENABLED START -----*/
	
	//	Add your own code
	vector<string> str;
	str << (*argin);
	vector<string>::iterator si;
	
	for (si = str.begin(); si != str.end(); si++) {
#ifndef _RW_LOCK
		alarms.lock();
#else
		alarms.vlock->readerIn();
#endif
		alarmedlock->readerIn();
		vector<alarm_t>::iterator found = \
		find(alarmed.begin(), alarmed.end(), *si);
		if (found != alarmed.end()) 
		{
			alarm_container_t::iterator i = alarms.v_alarm.find(*si);
			if(i != alarms.v_alarm.end())
			{
				//update alarm ack in alarm table
				i->second.ack = ACK;
				//update alarm status from alarm table
				found->stat = i->second.stat;
			}
			if(found->ack == NOT_ACK)
			{
				alarms.log_alarm_db(TYPE_LOG_STATUS, gettime(), found->name, found->stat, ACK, 
						"", 0, "", "", "", "", -1);
			}
			found->ack = ACK;		
		} else {
			internallock->readerIn();
			found = find(internal.begin(), internal.end(), *si);
			if (found != internal.end()) {
				found->ack = ACK;
			} else {
				ostringstream o;
				o << "\"" << *si << "\" not in 'alarmed' or 'internal' table" << endl;
				WARN_STREAM << "Alarm::ack(): " << o.str() << endl;
				internallock->readerOut();
				alarmedlock->readerOut();
#ifndef _RW_LOCK
				alarms.unlock();
#else
				alarms.vlock->readerOut();
#endif
				Tango::Except::throw_exception( \
					(const char*)"Alarm not found!!", \
					o.str(), \
					(const char*)"Alarm::ack()", Tango::ERR);									 
				
			}
			internallock->readerOut();
		}
		alarmedlock->readerOut();
#ifndef _RW_LOCK
		alarms.unlock();
#else
		alarms.vlock->readerOut();
#endif
	}
	/*
	 * remove S_NORMAL status ACKnowledged alarms
	 */
	alarm_t to_be_removed;
	to_be_removed.name = "";
	to_be_removed.formula = "";
	to_be_removed.stat = S_NORMAL;
	to_be_removed.ack = ACK;
	bool go = true;
	while (go) {
		alarmedlock->writerIn();
		vector<alarm_t>::iterator found = \
				find(alarmed.begin(), alarmed.end(), to_be_removed);
		if (found != alarmed.end()) {
			DEBUG_STREAM << "Alarm::ack(): " << found->name \
					 				 << " S_NORMAL and ACK, removing"  << endl;
			alarmed.erase(found);
		} else {
			go = false;
		}
		alarmedlock->writerOut();
	}
	/*
	 * always remove internal ACKnowlwdged alarms as
	 * they'll wont switch to "NORMAL"
	 */
	to_be_removed.name = "";
	to_be_removed.formula = "";
	to_be_removed.stat = S_ALARM;
	to_be_removed.ack = ACK;
	go = true;
	while (go) {
		internallock->writerIn();
		vector<alarm_t>::iterator found = \
				find(internal.begin(), internal.end(), to_be_removed);
		if (found != internal.end()) {
			DEBUG_STREAM << "Alarm::ack(): " << found->name \
					 				 << " ACK, removing"  << endl;
			internal.erase(found);
		} else {
			go = false;
		}
		internallock->writerOut();
	}

	prepare_alarm_attr();
	try
	{
		if(ds_num == 0)
		{
			//attr.set_value_date_quality(ds,0/*gettime()*/,Tango::ATTR_WARNING, ds_num, 0, false);
			struct timeval now;
			gettimeofday(&now,NULL);
			push_change_event("alarm",(char**)ds,now,Tango::ATTR_WARNING, ds_num, 0, false);
		}
		else
			//attr.set_value(ds, ds_num, 0, false);
			push_change_event("alarm",ds, ds_num, 0, false);
	} catch(Tango::DevFailed& e)
	{
		ostringstream err;
		err << "error pushing alarm change event err=" << e.errors[0].desc;
		INFO_STREAM << __func__<<": " << err.str() << endl;
	}

	/*----- PROTECTED REGION END -----*/	//	Alarm::ack
}
//--------------------------------------------------------
/**
 *	Command Load related method
 *	Description: Load a new alarm.
 *
 *	@param argin Alarm entry
 */
//--------------------------------------------------------
void Alarm::load(Tango::DevString argin)
{
	DEBUG_STREAM << "Alarm::Load()  - " << device_name << endl;
	/*----- PROTECTED REGION ID(Alarm::load) ENABLED START -----*/
	
	//	Add your own code
	string s;
	alarm_t alm;
	vector<string> evn;
	
	s = argin;
	//std::transform(s.begin(), s.end(), s.begin(), (int(*)(int))tolower);		//transform to lowercase
	Tango::TimeVal ts = gettime();
	try {
		load_alarm(s, alm, evn);
	} catch(Tango::DevFailed& e)
	{
		ostringstream err;
		err << "error loading alarm=" << alm.name << " , " << e.errors[0].desc << ends;
		WARN_STREAM << "Alarm::load(): " << err.str() << endl;
		Tango::Except::throw_exception( \
				(const char*)"Alarm::load()", \
				err.str(), \
				(const char*)"Alarm::load()", Tango::ERR);	
	}
	
	try {
		add_alarm(alm);
	} catch (string& err) {
		WARN_STREAM << "Alarm::load(): " << err << endl;
		Tango::Except::throw_exception( \
				(const char*)"Alarm::load()", \
				(const char*)err.c_str(), \
				(const char*)"Alarm::load()", Tango::ERR);
	}
	try {
		add_event(alm, evn);
	} catch (string& err) {
		WARN_STREAM << "Alarm::load(): " << err << endl;
#ifndef _RW_LOCK
		alarms.lock();
#else
		alarms.vlock->writerIn();
#endif
		alarm_container_t::iterator i = alarms.v_alarm.find(alm.name);		//look for alarm just added
		if (i != alarms.v_alarm.end())	
			alarms.erase(i);											//and remove from alarm_table
#ifndef _RW_LOCK
		alarms.unlock();
#else
		alarms.vlock->writerOut();
#endif
		Tango::Except::throw_exception( \
				(const char*)"Alarm::load()", \
				(const char*)err.c_str(), \
				(const char*)"Alarm::load()", Tango::ERR);
	}
	string cmd_name_full = alm.cmd_name_a + string(";") + alm.cmd_name_n;
	alarms.log_alarm_db(TYPE_LOG_DESC_ADD, ts, alm.name, "", "", 		//add new alarm on log before subscribe event
			alm.formula, alm.time_threshold, alm.grp2str(), alm.lev, alm.msg, cmd_name_full, alm.silent_time);	//but if it fails remove it from table




	alarm_container_t::iterator i = alarms.v_alarm.find(alm.name);
	if(i != alarms.v_alarm.end())
	{
		try {
			//add_event(i->second, al_ev_it->second);

			for(vector<string>::iterator j = evn.begin(); j != evn.end(); j++)
			{
				vector<event>::iterator k = \
						find(events->v_event.begin(), events->v_event.end(), *j);
				if (k == events->v_event.end())	//if not already present
				{
					string name=*j;
					vector<string> context;//TODO
					events->add(name, context, UPDATE_PROP, false);//throws exception if already present
				}
			}
			add_event(i->second, evn);//moved after events->add
			for(vector<string>::iterator j = evn.begin(); j != evn.end(); j++)
			{
				vector<event>::iterator k = \
						find(events->v_event.begin(), events->v_event.end(), *j);
				if (k != events->v_event.end())	//if already present
				{
					string name=*j;
					events->start(name);//throws exception if not found
				}
			}
		} catch (string& err) {
			WARN_STREAM << "Alarm::"<<__func__<<": string exception=" << err << endl;
			//TODO: handle error
#if 0
			for(vector<string>::iterator j = evn.begin(); j != evn.end(); j++)
			{
				DEBUG_STREAM << "Alarm::"<<__func__<<": Removing alarm=" << i->second.name << " from event=" << *j << endl;
				vector<event>::iterator k = \
					find(events->v_event.begin(), events->v_event.end(), *j);
				if (k != events->v_event.end())
				{
					k->pop_alarm(i->second.name);		//remove alarm/formula just added to event
					DEBUG_STREAM << "Alarm::"<<__func__<<": Removed!!!! alarm=" << i->second.name << " from event=" << *j << endl;
					if(k->m_alarm.empty())
					{
						events->v_event.erase(k);	//remove event just added to event_table
						DEBUG_STREAM << "Alarm::"<<__func__<<": event=" << *j << " no more used, REMOVED!!!" << endl;
					}
				}
			}
			set_internal_alarm(INTERNAL_ERROR, gettime(), err);
#endif
		}
		catch (Tango::DevFailed &e) {
			WARN_STREAM << "Alarm::"<<__func__<<": Tango exception=" << e.errors[0].desc << endl;
		}
	}








#if 0//TODO

		//TODO:subscribe_event(alm, ecb, evn);
		vector<string> contexts;//TODO
		events->add(alm.name, contexts, UPDATE_PROP, false);
	} catch (string& err) {
		WARN_STREAM << "Alarm::load(): " << err << endl;
#ifndef _RW_LOCK
		alarms.lock();
#else
		alarms.vlock->writerIn();
#endif
		alarm_container_t::iterator i = alarms.v_alarm.find(alm.name);		//look for alarm just added
		if (i != alarms.v_alarm.end())	
			alarms.erase(i);											//and remove from alarm_table
#ifndef _RW_LOCK
		alarms.unlock();
#else
		alarms.vlock->writerOut();
#endif
		alarms.log_alarm_db(TYPE_LOG_DESC_REM, ts, alm.name, "", "", 		//remove alarm just added
			"", 0, "", "", "", "", -1);
		Tango::Except::throw_exception( \
				(const char*)"Alarm::load()", \
				(const char*)err.c_str(), \
				(const char*)"Alarm::load()", Tango::ERR);
	}
	
	if(alm.cmd_name_a.length() > 0)
	{
#ifndef _RW_LOCK
		alarms.lock();
#else
		alarms.vlock->readerIn();
#endif
		alarm_container_t::iterator i = alarms.v_alarm.find(alm.name);		//look for alarm just added
		if (i != alarms.v_alarm.end())
		{
			try {
				i->second.dp_a = new Tango::DeviceProxy(i->second.cmd_dp_a);
				i->second.dp_a->ping();
				Tango::CommandInfo info = i->second.dp_a->command_query(i->second.cmd_action_a);
				if(info.in_type != Tango::DEV_STRING)
				{
					ostringstream err;
					err << "Error: command " << i->second.cmd_name_a << " does not accept a Tango::DevString as input value" << ends;
					ERROR_STREAM << "Alarm::load(): " << err.str() << endl;
					set_internal_alarm(INTERNAL_ERROR, gettime(), err.str());					
				}
				else
				{
					if(info.in_type == Tango::DEV_STRING)
						i->second.send_arg_a = true;
					else
						i->second.send_arg_a = false;
					DEBUG_STREAM << "Alarm::load(): successfully connected to proxy=" << i->second.cmd_dp_a << " for action=" << i->second.cmd_action_a << endl;
				}
			} catch(Tango::DevFailed& e)
			{
				ostringstream err;
				err << alm.name << ": error connecting to device proxy=" << i->second.cmd_dp_a << ", err=" << e.errors[0].desc << ends;
				WARN_STREAM << "Alarm::load(): " << err.str() << endl;
				set_internal_alarm(INTERNAL_ERROR, gettime(), err.str());
			}				
		}
#ifndef _RW_LOCK
		alarms.unlock();
#else
		alarms.vlock->readerOut();
#endif
	}
	if(alm.cmd_name_n.length() > 0)
	{
#ifndef _RW_LOCK
		alarms.lock();
#else
		alarms.vlock->readerIn();
#endif
		alarm_container_t::iterator i = alarms.v_alarm.find(alm.name);		//look for alarm just added
		if (i != alarms.v_alarm.end())
		{
			try {
				i->second.dp_n = new Tango::DeviceProxy(i->second.cmd_dp_n);
				i->second.dp_n->ping();
				Tango::CommandInfo info = i->second.dp_n->command_query(i->second.cmd_action_a);
				if(info.in_type != Tango::DEV_STRING)
				{
					ostringstream err;
					err << "Error: command " << i->second.cmd_name_n << " does not accept a Tango::DevString as input value" << ends;
					ERROR_STREAM << "Alarm::load(): " << err.str() << endl;
					set_internal_alarm(INTERNAL_ERROR, gettime(), err.str());						
				}
				else
				{
					if(info.in_type == Tango::DEV_STRING)
						i->second.send_arg_n = true;
					else
						i->second.send_arg_n = false;
					DEBUG_STREAM << "Alarm::load(): successfully connected to proxy=" << i->second.cmd_dp_n << " for action=" << i->second.cmd_action_n << endl;
				}
			} catch(Tango::DevFailed& e)
			{
				ostringstream err;
				err << alm.name << ": error connecting to device proxy=" << i->second.cmd_dp_n << ", err=" << e.errors[0].desc << ends;
				WARN_STREAM << "Alarm::load(): " << err.str() << endl;
				set_internal_alarm(INTERNAL_ERROR, gettime(), err.str());
			}				
		}
#ifndef _RW_LOCK
		alarms.unlock();
#else
		alarms.vlock->readerOut();
#endif
	}	

	//if at least one event was already existing, evaluate formula of just added alarm
	if(alm.to_be_evaluated)							//TODO: remove this evaluation of the formula that is not necessary
	{
		DEBUG_STREAM << "Alarm::load(): Evaluating formula=" << alm.formula << endl;
    		string attr_values;
    		res = eval_formula(alm.formula_tree, attr_values);
          	DEBUG_STREAM << "Parsing succeeded of "<< alm.formula << "; result=" << res.value << " quality=" << res.quality << endl;
        	alarms.update(alm.name, gettime(), res, attr_values, alm.grp2str(), alm.msg, alm.formula);		//pass "now" as timestamp in this case
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049

		} catch(std::out_of_range& e)
		{
			ostringstream o;
			o << alm.name << ": in formula array index out of range!" << ends;
			WARN_STREAM << "Alarm::load(): " << o.str() << endl;
			set_internal_alarm(INTERNAL_ERROR, gettime(), o.str());				
		} catch(string & e)
		{
			ostringstream o;
			o << alm.name << ": in formula err=" << e << ends;
			WARN_STREAM << "Alarm::load(): " << o.str() << endl;
			set_internal_alarm(INTERNAL_ERROR, gettime(), o.str());				
		} catch(Tango::DevFailed& e)
		{
			ostringstream o;
			o << alm.name << "error=" << e.errors[0].desc << ends;
			WARN_STREAM << "Alarm::load(): " << o.str() << endl;
			set_internal_alarm(INTERNAL_ERROR, gettime(), o.str());				
		}
	}

	prepare_alarm_attr();
	try
	{
		if(ds_num == 0)
		{
			//attr.set_value_date_quality(ds,0/*gettime()*/,Tango::ATTR_WARNING, ds_num, 0, false);
			struct timeval now;
			gettimeofday(&now,NULL);
			push_change_event("alarm",(char**)ds,now,Tango::ATTR_WARNING, ds_num, 0, false);
		}
		else
			//attr.set_value(ds, ds_num, 0, false);
			push_change_event("alarm",ds, ds_num, 0, false);
	} catch(Tango::DevFailed& e)
	{
		ostringstream err;
		err << "error pushing alarm change event err=" << e.errors[0].desc;
		INFO_STREAM << __func__<<": " << err.str() << endl;
	}

	/*----- PROTECTED REGION END -----*/	//	Alarm::load
}
//--------------------------------------------------------
/**
 *	Command Remove related method
 *	Description: Remove alarm.
 *
 *	@param argin Alarm name
 */
//--------------------------------------------------------
void Alarm::remove(Tango::DevString argin)
{
	DEBUG_STREAM << "Alarm::Remove()  - " << device_name << endl;
	/*----- PROTECTED REGION ID(Alarm::remove) ENABLED START -----*/
	
	//	Add your own code
	string s, log_alm_name;
	s = argin;
	log_alm_name = argin;
	bool ret = false;
	
	alarmedlock->readerIn();
	vector<alarm_t>::iterator found = find(alarmed.begin(), alarmed.end(), s);
	if (found != alarmed.end()) 
	{
		ostringstream err;
		err << s << " is in ALARM status! Acknowledge it before removing." << ends;
		if((found->stat == S_ALARM) && (found->ack == NOT_ACK))
		{
			alarmedlock->readerOut();
			Tango::Except::throw_exception( \
				(const char*)"Error removing alarm", \
				(const char*)err.str().c_str(), \
				(const char*)"Alarm::remove", Tango::ERR);
		}
	}
	alarmedlock->readerOut();
	try {
		ret = remove_alarm(s);
	} catch (string& err) {
		Tango::Except::throw_exception( \
				(const char*)"Error removing alarm", \
				(const char*)err.c_str(), \
				(const char*)"Alarm::remove", Tango::ERR);
	}
	if (ret) {
		DEBUG_STREAM << "Alarm::remove(): removing alarm '" \
								<< s << "'" << endl;
		while (true) {
			string::size_type i = s.find_first_of("/.");
			if (i == string::npos)
				break;
			s.replace(i, 1, "_");
		}
	}  /* end if */
	alarms.log_alarm_db(TYPE_LOG_DESC_DIS, gettime(), log_alm_name, "", "", 		//set active to 0
			"", 0, "", "", "", "", -1);
	alarmedlock->writerIn();
	found = find(alarmed.begin(), alarmed.end(), s);	//look again because in the meanwhile lock was not acquired
	if (found != alarmed.end()) 
	{
		alarmed.erase(found);		//remove from alarmed table
	}
	alarmedlock->writerOut();

	prepare_alarm_attr();
	try
	{
		if(ds_num == 0)
		{
			//attr.set_value_date_quality(ds,0/*gettime()*/,Tango::ATTR_WARNING, ds_num, 0, false);
			struct timeval now;
			gettimeofday(&now,NULL);
			push_change_event("alarm",(char**)ds,now,Tango::ATTR_WARNING, ds_num, 0, false);
		}
		else
			//attr.set_value(ds, ds_num, 0, false);
			push_change_event("alarm",ds, ds_num, 0, false);
	} catch(Tango::DevFailed& e)
	{
		ostringstream err;
		err << "error pushing alarm change event err=" << e.errors[0].desc;
		INFO_STREAM << __func__<<": " << err.str() << endl;
	}

	/*----- PROTECTED REGION END -----*/	//	Alarm::remove
}
//--------------------------------------------------------
/**
 *	Command Configured related method
 *	Description: Alarms configured
 *
 *	@param argin String containing a filter for output, if empty return all alarms
 *	@returns Alarms configured
 */
//--------------------------------------------------------
Tango::DevVarStringArray *Alarm::configured(Tango::DevString argin)
{
	Tango::DevVarStringArray *argout;
	DEBUG_STREAM << "Alarm::Configured()  - " << device_name << endl;
	/*----- PROTECTED REGION ID(Alarm::configured) 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)
	//------------------------------------------------------------
	argout  = new Tango::DevVarStringArray();
	//argout->length(1);
	//(*argout)[0] = CORBA::string_dup("dummy");
	DEBUG_STREAM << "Alarm::configured(): entering... !" << endl;

	//	Add your own code to control device here

	string filter(argin);
	size_t found;
	vector<string> alarm_filtered;
	ostringstream os1;		
	os1.clear();
	/*os1 << headerConfig << "\t" << alarms.v_alarm.size() << ends;
	alarm_filtered.push_back(os1.str());*/

	alarm_container_t::iterator ai;
#ifndef _RW_LOCK
	alarms.lock();
#else
	alarms.vlock->readerIn();
#endif
	for (ai = alarms.v_alarm.begin(); ai != alarms.v_alarm.end(); ai++) 
	{
		found = 0;
		if(filter.length() != 0)
		{
			found = ai->first.find(filter);
		}
		if((filter.length() == 0) || (found != string::npos))
		{
			ostringstream os;
			os.clear();
			os << ai->second.ts.tv_sec << "\t" << ai->second.name << "\t" << ai->second.formula << "\t" << ai->second.time_threshold << 
			"\t" << ai->second.lev << "\t" << ai->second.silent_time << "\t" << ai->second.grp2str() << "\t" << ai->second.msg << "\t" <<
			ai->second.cmd_name_a << ";" << ai->second.cmd_name_n << ends;
			alarm_filtered.push_back(os.str());
		}
	}  /* for */
#ifndef _RW_LOCK
	alarms.unlock();
#else
	alarms.vlock->readerOut();
#endif
	argout->length(alarm_filtered.size());
	int i = 0;
	for (vector<string>::iterator it= alarm_filtered.begin(); it != alarm_filtered.end(); it++) 
	{
		(*argout)[i] = CORBA::string_dup(it->c_str());
		i++;
	}

	/*----- PROTECTED REGION END -----*/	//	Alarm::configured
	return argout;
}
//--------------------------------------------------------
/**
 *	Command StopNew related method
 *	Description: Remove "NEW" field from alarm string (so alarm panel stop sound)
 *
 */
//--------------------------------------------------------
void Alarm::stop_new()
{
	DEBUG_STREAM << "Alarm::StopNew()  - " << device_name << endl;
	/*----- PROTECTED REGION ID(Alarm::stop_new) ENABLED START -----*/
	
	//	Add your own code
	//12-06-08: StopNew command set is_new to 0
	//	Add your own code to control device here
	alarm_container_t::iterator ai;
#ifndef _RW_LOCK
	alarms.lock();
#else
	alarms.vlock->readerIn();
#endif
	for (ai = alarms.v_alarm.begin(); ai != alarms.v_alarm.end(); ai++) {
		ai->second.is_new = 0;		//set all alarm as no more new
	}
#ifndef _RW_LOCK
	alarms.unlock();
#else
	alarms.vlock->readerOut();
#endif

	prepare_alarm_attr();
	try
	{
		if(ds_num == 0)
		{
			//attr.set_value_date_quality(ds,0/*gettime()*/,Tango::ATTR_WARNING, ds_num, 0, false);
			struct timeval now;
			gettimeofday(&now,NULL);
			push_change_event("alarm",(char**)ds,now,Tango::ATTR_WARNING, ds_num, 0, false);
		}
		else
			//attr.set_value(ds, ds_num, 0, false);
			push_change_event("alarm",ds, ds_num, 0, false);
	} catch(Tango::DevFailed& e)
	{
		ostringstream err;
		err << "error pushing alarm change event err=" << e.errors[0].desc;
		INFO_STREAM << __func__<<": " << err.str() << endl;
	}

	/*----- PROTECTED REGION END -----*/	//	Alarm::stop_new
}
//--------------------------------------------------------
/**
 *	Command Silence related method
 *	Description: Alarm temporarily silence
 *
 *	@param argin String array containing the alarms to be silenced
 */
//--------------------------------------------------------
void Alarm::silence(const Tango::DevVarStringArray *argin)
{
	DEBUG_STREAM << "Alarm::Silence()  - " << device_name << endl;
	/*----- PROTECTED REGION ID(Alarm::silence) ENABLED START -----*/
	
	//	Add your own code
	vector<string> str;
	str << (*argin);
	vector<string>::iterator si;

	for (si = str.begin(); si != str.end(); si++)
	{
#ifndef _RW_LOCK
		alarms.lock();
#else
		alarms.vlock->readerIn();
#endif
		alarm_container_t::iterator i = alarms.v_alarm.find(*si);
		if(i != alarms.v_alarm.end())
		{
			if(i->second.silenced > 0)
			{
				Tango::TimeVal now = gettime();
				double dnow = now.tv_sec + ((double)now.tv_usec) / 1000000;
				double dsilent = i->second.ts_time_silenced.tv_sec + ((double)i->second.ts_time_silenced.tv_usec) / 1000000;
				double dminutes = (dnow - dsilent)/60;
				//silenced already calculated in alarm_table::update, but here updated for panel also if state not changed:
				//to see minutes countdown
				if(dminutes < i->second.silent_time)
					i->second.silenced = i->second.silent_time - floor(dminutes);
				else
					i->second.silenced = 0;
			}
			if(i->second.silenced > 0)
			{
				ostringstream err;
				err << "Alarm " << *si << " already silenced for " << i->second.silenced << " more minutes" << ends;
#ifndef _RW_LOCK
				alarms.unlock();
#else
				alarms.vlock->readerOut();
#endif
				Tango::Except::throw_exception( \
							(const char*)"Alarm already silenced", \
							err.str(), \
							(const char*)"Alarm::silence()", Tango::ERR);
			}
			if(i->second.silent_time <= 0)
			{
				ostringstream err;
				err << "Alarm " << *si << " cannot be silenced" << ends;
#ifndef _RW_LOCK
				alarms.unlock();
#else
				alarms.vlock->readerOut();
#endif
				Tango::Except::throw_exception( \
							(const char*)"Alarm cannot be silenced", \
							err.str(), \
							(const char*)"Alarm::silence()", Tango::ERR);
			}

			//load silent time
			i->second.ts_time_silenced = gettime();
			i->second.silenced = i->second.silent_time;
			//search also in alarmed
			alarmedlock->readerIn();
			vector<alarm_t>::iterator found = \
					find(alarmed.begin(), alarmed.end(), *si);
			if (found != alarmed.end())
			{
				//load silent time from alarm table
				found->silenced = i->second.silent_time;
				found->ts_time_silenced = i->second.ts_time_silenced;
			}
			alarmedlock->readerOut();
		}
		//alarms.unlock();
		if(i == alarms.v_alarm.end())
		{
#ifndef _RW_LOCK
			alarms.unlock();
#else
			alarms.vlock->readerOut();
#endif
			ostringstream err;
			err << "Alarm " << *si << " not found" << ends;
			Tango::Except::throw_exception( \
						(const char*)"Alarm not found!!", \
						err.str(), \
						(const char*)"Alarm::silence()", Tango::ERR);
		}
#ifndef _RW_LOCK
		alarms.unlock();
#else
		alarms.vlock->readerOut();
#endif
	}

	prepare_alarm_attr();
	try
	{
		if(ds_num == 0)
		{
			//attr.set_value_date_quality(ds,0/*gettime()*/,Tango::ATTR_WARNING, ds_num, 0, false);
			struct timeval now;
			gettimeofday(&now,NULL);
			push_change_event("alarm",(char**)ds,now,Tango::ATTR_WARNING, ds_num, 0, false);
		}
		else
			//attr.set_value(ds, ds_num, 0, false);
			push_change_event("alarm",ds, ds_num, 0, false);
	} catch(Tango::DevFailed& e)
	{
		ostringstream err;
		err << "error pushing alarm change event err=" << e.errors[0].desc;
		INFO_STREAM << __func__<<": " << err.str() << endl;
	}

	/*----- PROTECTED REGION END -----*/	//	Alarm::silence
}
//--------------------------------------------------------
/**
 *	Command Modify related method
 *	Description: Modify an existing alarm.
 *
 *	@param argin Alarm entry
 */
//--------------------------------------------------------
void Alarm::modify(Tango::DevString argin)
{
	DEBUG_STREAM << "Alarm::Modify()  - " << device_name << endl;
	/*----- PROTECTED REGION ID(Alarm::modify) ENABLED START -----*/
	DEBUG_STREAM << "Alarm::Modify: " << argin << endl;
	//	Add your own code
	//------------------------------
	//1: parse to get alarm name
	//------------------------------
	string alarm_string(argin);
	alarm_t alm;
	alarm_parse al_gr(alm);    //  Construct Spirit grammar
	alm.name.clear();
	alm.attr_name.clear();
	alm.quality = Tango::ATTR_VALID;
	alm.ex_reason.clear();
	alm.ex_desc.clear();
	alm.ex_origin.clear();
	alm.formula.clear();
	alm.msg.clear();
	alm.lev.clear();
	alm.grp=0;
	alm.to_be_evaluated = false;
	alm.time_threshold = 0;
	alm.silent_time = -1;
	alm.silenced = -1;
	alm.cmd_name_a.clear();
	alm.cmd_dp_a.clear();
	alm.cmd_action_a.clear();
	alm.send_arg_a = false;
	alm.dp_a = NULL;
	alm.cmd_name_n.clear();
	alm.cmd_dp_n.clear();
	alm.cmd_action_n.clear();
	alm.send_arg_n = false;
	alm.dp_n = NULL;

#ifndef _ACCESS_NODE_D
	alm.formula_tree = ast_parse(alarm_string.c_str(), al_gr, space_p);	//parse string s with grammar al_gr, skipping white spaces
#else
	alm.formula_tree =
	//boost::spirit::tree_parse_info< std::string::iterator, factory_t> tmp =
	ast_parse<factory_t>(alarm_string.begin(), alarm_string.end(), al_gr, space_p);	//parse string s with grammar al_gr, skipping white spaces
#endif
	if (alm.formula_tree.full)
	{
    	std::transform(alm.name.begin(), alm.name.end(), alm.name.begin(), (int(*)(int))tolower);		//transform to lowercase
    	//std::transform(alm.formula.begin(), alm.formula.end(), alm.formula.begin(), (int(*)(int))tolower);		//transform to lowercase: incorrect, state has to be written upercase
    	std::transform(alm.lev.begin(), alm.lev.end(), alm.lev.begin(), (int(*)(int))tolower);		//transform to lowercase

    	if(alm.cmd_name_a.length() > 0)
    	{
			const char *c = alm.cmd_name_a.c_str();
			int j = 0;
			while (*c) {
				if (*c == '/')
					j++;
				if (j < 3)
					alm.cmd_dp_a.push_back(*c);
				else if (*c != '/')
					alm.cmd_action_a.push_back(*c);
				c++;
			}
    	}
    	if(alm.cmd_name_n.length() > 0)
    	{
			const char *c = alm.cmd_name_n.c_str();
			int j = 0;
			while (*c) {
				if (*c == '/')
					j++;
				if (j < 3)
					alm.cmd_dp_n.push_back(*c);
				else if (*c != '/')
					alm.cmd_action_n.push_back(*c);
				c++;
			}
    	}

	}
    else
    {
       	ostringstream o;
#ifndef _ACCESS_NODE_D
		o << __func__<<": Parsing Failed, syntax error stopped at " << alm.formula_tree.stop << ends;
#else
		o << __func__<<": Parsing Failed, syntax error stopped at " << string(alm.formula_tree.stop, alarm_string.end()) << ends; //TODO
#endif
       	DEBUG_STREAM << o.str() << endl;
       	Tango::Except::throw_exception( \
				(const char*)"Parsing Failed!", \
				(const char*)o.str().c_str(), \
				(const char*)__func__, Tango::ERR);
    }

	DEBUG_STREAM << "Alarm::Modify: parsing ended: alm name=" << alm.name << endl;
	//------------------------------
	//2: if alarm already exist and
	//   formula is not changed
	//------------------------------
#ifndef _RW_LOCK
	alarms.lock();
#else
	alarms.vlock->writerIn();
#endif
	alarm_container_t::iterator i = alarms.v_alarm.find(alm.name);
	if (i != alarms.v_alarm.end())
	{
		if(i->second.formula == alm.formula)
		{
			Tango::TimeVal ts = gettime();
			string cmd_name_full = alm.cmd_name_a + string(";") + alm.cmd_name_n;

			if ((alm.name.empty() == false) && \
					(alm.formula.empty() == false) && \
					((alm.lev==LEV_LOG)||(alm.lev==LEV_WARNING)|| \
					(alm.lev==LEV_FAULT)||(alm.lev.empty() == true))) {
				i->second.stat = S_NORMAL;
				i->second.ack = ACK;
				i->second.done = false;

				i->second.msg = alm.msg;
				i->second.lev = alm.lev;
				i->second.grp = alm.grp;
				//i->second.to_be_evaluated = alm.to_be_evaluated;
				i->second.time_threshold = alm.time_threshold;
				i->second.silent_time = alm.silent_time;
				i->second.silenced = alm.silenced;
				i->second.cmd_name_a = alm.cmd_name_a;
				i->second.cmd_dp_a = alm.cmd_dp_a;
				i->second.cmd_action_a = alm.cmd_action_a;
				//i->second.send_arg_a = alm.send_arg_a;
				i->second.cmd_name_n = alm.cmd_name_n;
				i->second.cmd_dp_n = alm.cmd_dp_n;
				i->second.cmd_action_n = alm.cmd_action_n;
				//i->second.send_arg_n = alm.send_arg_n;

			} else {
				ostringstream o;
				o << __func__<<": syntax error in '" << alarm_string << "'" << ends;
				WARN_STREAM << o.str() << endl;
#ifndef _RW_LOCK
				alarms.unlock();
#else
				alarms.vlock->writerOut();
#endif
				Tango::Except::throw_exception( \
						(const char*)o.str().c_str(), \
						(const char*)"", \
						(const char*)__func__, Tango::ERR);
			}


			alarms.log_alarm_db(TYPE_LOG_DESC_UPDATE, ts, alm.name, "", "",
					alm.formula, alm.time_threshold, alm.grp2str(), alm.lev, alm.msg, cmd_name_full, alm.silent_time);
Loading full blame...