@@ -99,8 +99,11 @@ class VisaDriver(InstrumentDriver):
9999 """Base driver for VISA-compatible instruments (GPIB, USB, serial).
100100
101101 Provides connect/disconnect/query/write with automatic retry.
102+ Supports auto-reconnect on communication failure.
102103 """
103104
105+ auto_reconnect : bool = True
106+
104107 def connect (self ) -> None :
105108 import pyvisa
106109
@@ -126,15 +129,58 @@ def reset(self) -> None:
126129 self .write ("*RST" )
127130
128131 @retry (max_attempts = 3 , delay = 0.5 )
129- def query (self , command : str ) -> str :
130- """Send a query and return the response. Auto-retries on failure ."""
132+ def _query_inner (self , command : str ) -> str :
133+ """Inner query with retry. Called by query() ."""
131134 return self ._instrument .query (command ).strip ()
132135
136+ def query (self , command : str ) -> str :
137+ """Send a query and return the response.
138+
139+ Auto-retries on failure. If retries are exhausted and
140+ auto_reconnect is enabled, attempts to reconnect and retry once.
141+ """
142+ try :
143+ return self ._query_inner (command )
144+ except Exception :
145+ if not self .auto_reconnect :
146+ raise
147+ logger .info ("Retries exhausted for query, attempting reconnect to %s" , self .resource )
148+ self .disconnect ()
149+ self .connect ()
150+ return self ._instrument .query (command ).strip ()
151+
133152 @retry (max_attempts = 3 , delay = 0.5 )
134- def write (self , command : str ) -> None :
135- """Send a command. Auto-retries on failure ."""
153+ def _write_inner (self , command : str ) -> None :
154+ """Inner write with retry. Called by write() ."""
136155 self ._instrument .write (command )
137156
157+ def write (self , command : str ) -> None :
158+ """Send a command.
159+
160+ Auto-retries on failure. If retries are exhausted and
161+ auto_reconnect is enabled, attempts to reconnect and retry once.
162+ """
163+ try :
164+ self ._write_inner (command )
165+ except Exception :
166+ if not self .auto_reconnect :
167+ raise
168+ logger .info ("Retries exhausted for write, attempting reconnect to %s" , self .resource )
169+ self .disconnect ()
170+ self .connect ()
171+ self ._instrument .write (command )
172+
173+ def is_connected (self ) -> bool :
174+ """Test if instrument is still responding."""
175+ if not self ._connected or not self ._instrument :
176+ return False
177+ try :
178+ self ._instrument .query ("*IDN?" )
179+ return True
180+ except Exception :
181+ self ._connected = False
182+ return False
183+
138184 def read_float (self , command : str ) -> float :
139185 """Query and parse as float."""
140186 return float (self .query (command ))
0 commit comments