From a26c877c33c9ce9e547dbd5088c1f54a78c13651 Mon Sep 17 00:00:00 2001
From: Alessio Igor Bogani <alessio.bogani@elettra.eu>
Date: Wed, 7 Feb 2024 12:51:42 +0100
Subject: [PATCH] Consolidate checks for timeout

---
 src/Serial2.cpp | 43 +++++++++----------------------------------
 src/Serial2.h   |  2 ++
 2 files changed, 11 insertions(+), 34 deletions(-)

diff --git a/src/Serial2.cpp b/src/Serial2.cpp
index f4157e3..4c6c4da 100644
--- a/src/Serial2.cpp
+++ b/src/Serial2.cpp
@@ -358,9 +358,7 @@ void Serial2::get_device_property()
 	{
 		multiplexing = SLEEP;
 		DEBUG_STREAM << "Using sleep IO multiplexing type" << endl;
-	}
-	else
-	{
+	} else {
 		multiplexing = SELECT;
 		DEBUG_STREAM << "Using select IO multiplexing type" << endl;
 	}
@@ -418,9 +416,16 @@ void Serial2::always_executed_hook()
 	{
 		set_state(Tango::FAULT);
 		set_status(init_error);
+		return;
 	}
-	else
+
+	tout.tv_sec = timeout / 1000;
+	tout.tv_usec = timeout % 1000 * 1000;
+	if ( ! timerisset( &tout ) )
 	{
+		set_state(Tango::FAULT);
+		set_status("Invalid timeout");
+	} else {
 		check_connection( );
 	}
 
@@ -531,16 +536,6 @@ void Serial2::write(const Tango::DevVarCharArray *argin)
 	/*----- PROTECTED REGION ID(Serial2::write) ENABLED START -----*/
 	check_init();
 	
-	timeval tout;
-	tout.tv_sec = timeout / 1000;
-	tout.tv_usec = timeout % 1000 * 1000;
-	if ( ! timerisset( &tout ) )
-	{
-		Tango::Except::throw_exception( "",
-				"Invalid timeout",
-				"Serial2::write()");
-	}
-
 	char *argin_data = new char[ argin->length() ];
 	for( unsigned int i=0; i<argin->length(); ++i )
 	{
@@ -649,16 +644,6 @@ Tango::DevVarCharArray *Serial2::read(Tango::DevLong argin)
 	/*----- PROTECTED REGION ID(Serial2::read) ENABLED START -----*/
 	check_init();
 
-	timeval tout;
-	tout.tv_sec = timeout / 1000;
-	tout.tv_usec = timeout % 1000 * 1000;
-	if ( ! timerisset( &tout ) )
-	{
-		Tango::Except::throw_exception( "",
-				"Invalid timeout",
-				"Serial2::read()");
-	}
-
 	if (argin < 0)
 	{
 		Tango::Except::throw_exception("",
@@ -704,16 +689,6 @@ Tango::DevVarCharArray *Serial2::read_until(const Tango::DevVarCharArray *argin)
 	/*----- PROTECTED REGION ID(Serial2::read_until) ENABLED START -----*/
 	check_init();
 
-	timeval tout;
-	tout.tv_sec = timeout / 1000;
-	tout.tv_usec = timeout % 1000 * 1000;
-	if ( ! timerisset( &tout ) )
-	{
-		Tango::Except::throw_exception( "",
-				"Invalid timeout",
-				"Serial2::read_until()");
-	}
-
 	if (argin->length() != 1)
 	{
 		Tango::Except::throw_exception("",
diff --git a/src/Serial2.h b/src/Serial2.h
index 4c90319..39e3f08 100644
--- a/src/Serial2.h
+++ b/src/Serial2.h
@@ -91,6 +91,8 @@ class Serial2 : public TANGO_BASE_CLASS
 
 	enum { SLEEP, SELECT } multiplexing;
 
+	timeval tout;
+
 /*----- PROTECTED REGION END -----*/	//	Serial2::Data Members
 
 //	Device property data members
-- 
GitLab