Drop the telnetlib dependency from the attenuator telnet client (#1091)
diff --git a/mobly/controllers/attenuator_lib/telnet_scpi_client.py b/mobly/controllers/attenuator_lib/telnet_scpi_client.py
index b43f9e7..2487dab 100644
--- a/mobly/controllers/attenuator_lib/telnet_scpi_client.py
+++ b/mobly/controllers/attenuator_lib/telnet_scpi_client.py
@@ -11,16 +11,32 @@
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
-"""
-Helper module for common telnet capability to communicate with
-AttenuatorDevice(s).
+"""Client for instruments that take SCPI commands over a telnet connection.
 
 User code shouldn't need to directly access this class.
 """
 
-import telnetlib
+import logging
+import re
+import select
+import socket
+import time
+
 from mobly.controllers import attenuator
 
+_CONNECT_TIMEOUT_SEC = 10
+_PROMPT_TIMEOUT_SEC = 2
+_RESPONSE_TIMEOUT_SEC = 5
+
+# Telnet protocol bytes, see RFC 854.
+_IAC = b"\xff"
+_DONT = b"\xfe"
+_DO = b"\xfd"
+_WONT = b"\xfc"
+_WILL = b"\xfb"
+_SB = b"\xfa"
+_SE = b"\xf0"
+
 
 def _ascii_string(uc_string):
   return str(uc_string).encode("ASCII")
@@ -33,7 +49,11 @@
   """
 
   def __init__(self, tx_cmd_separator="\n", rx_cmd_separator="\n", prompt=""):
-    self._tn = None
+    self._sock = None
+    # Bytes received but not yet checked for telnet commands.
+    self._raw = b""
+    # Text received from the instrument but not yet consumed.
+    self._text = b""
     self.tx_cmd_separator = tx_cmd_separator
     self.rx_cmd_separator = rx_cmd_separator
     self.prompt = prompt
@@ -41,39 +61,76 @@
     self.port = None
 
   def open(self, host, port=23):
-    if self._tn:
-      self._tn.close()
+    self.close()
     self.host = host
     self.port = port
-    self._tn = telnetlib.Telnet()
-    self._tn.open(host, port, 10)
+    self._sock = socket.create_connection((host, port), _CONNECT_TIMEOUT_SEC)
 
   @property
   def is_open(self):
-    return bool(self._tn)
+    return bool(self._sock)
 
   def close(self):
-    if self._tn:
-      self._tn.close()
-      self._tn = None
+    if self._sock:
+      self._sock.close()
+      self._sock = None
+    self._raw = b""
+    self._text = b""
 
   def cmd(self, cmd_str, wait_ret=True):
+    """Sends a command to the instrument.
+
+    If the command fails because the connection is broken or the instrument
+    does not answer, reconnects and sends the command one more time.
+
+    Args:
+      cmd_str: The command to send, without the command separator.
+      wait_ret: Whether to wait for a response.
+
+    Returns:
+      The response without separators and prompt, or None if `wait_ret` is
+      False.
+
+    Raises:
+      attenuator.Error: The connection is not open or the command failed.
+    """
     if not isinstance(cmd_str, str):
       raise TypeError("Invalid command string", cmd_str)
     if not self.is_open:
       raise attenuator.Error("Telnet connection not open for commands")
 
-    cmd_str.strip(self.tx_cmd_separator)
-    self._tn.read_until(_ascii_string(self.prompt), 2)
-    self._tn.write(_ascii_string(cmd_str + self.tx_cmd_separator))
+    cmd_str = cmd_str.strip(self.tx_cmd_separator)
+    try:
+      return self._cmd(cmd_str, wait_ret)
+    except (OSError, attenuator.Error) as e:
+      logging.warning(
+          "Command %r to %s:%s failed, reconnecting: %s",
+          cmd_str,
+          self.host,
+          self.port,
+          e,
+      )
+    try:
+      self.open(self.host, self.port)
+      return self._cmd(cmd_str, wait_ret)
+    except OSError as e:
+      raise attenuator.Error(
+          f"Command {cmd_str!r} to {self.host}:{self.port} failed: {e}"
+      ) from e
+
+  def _cmd(self, cmd_str, wait_ret):
+    if self.prompt:
+      prompt = re.compile(re.escape(_ascii_string(self.prompt)))
+      if self._read_until(prompt, _PROMPT_TIMEOUT_SEC) is None:
+        # Whatever arrived instead of the prompt is not part of the response.
+        self._text = b""
+    self._sock.sendall(_ascii_string(cmd_str + self.tx_cmd_separator))
     if wait_ret is False:
       return None
 
-    match_idx, match_val, ret_text = self._tn.expect(
-        [_ascii_string(r"\S+" + self.rx_cmd_separator)], 1
-    )
-
-    if match_idx == -1:
+    response = re.compile(_ascii_string(r"\S+" + self.rx_cmd_separator))
+    ret_text = self._read_until(response, _RESPONSE_TIMEOUT_SEC)
+    if ret_text is None:
       raise attenuator.Error("Telnet command failed to return valid data")
 
     ret_text = ret_text.decode()
@@ -82,3 +139,70 @@
     )
 
     return ret_text
+
+  def _read_until(self, pattern, timeout):
+    """Consumes received text through the first match of a pattern.
+
+    Args:
+      pattern: Compiled bytes pattern to look for.
+      timeout: Seconds to wait for the pattern to show up.
+
+    Returns:
+      The text up to and including the match, or None if the pattern did not
+      show up in time.
+
+    Raises:
+      ConnectionError: The instrument closed the connection.
+    """
+    deadline = time.monotonic() + timeout
+    while True:
+      match = pattern.search(self._text)
+      if match:
+        text = self._text[: match.end()]
+        self._text = self._text[match.end() :]
+        return text
+      remaining = deadline - time.monotonic()
+      if (
+          remaining <= 0
+          or not select.select([self._sock], [], [], remaining)[0]
+      ):
+        return None
+      data = self._sock.recv(4096)
+      if not data:
+        raise ConnectionError("Connection closed by the instrument.")
+      self._raw += data
+      self._process_raw()
+
+  def _process_raw(self):
+    """Moves text out of the raw bytes and answers telnet commands.
+
+    Every option the instrument tries to negotiate is refused. A command that
+    is only partially received stays in the raw bytes until the rest arrives.
+    """
+    while self._raw:
+      text, iac, rest = self._raw.partition(_IAC)
+      # NUL and XON carry no data in a telnet stream.
+      self._text += text.replace(b"\x00", b"").replace(b"\x11", b"")
+      if not iac:
+        self._raw = b""
+        return
+      self._raw = iac + rest
+      command = rest[:1]
+      if not command:
+        return
+      if command in (_DO, _DONT, _WILL, _WONT):
+        option = rest[1:2]
+        if not option:
+          return
+        refusal = _WONT if command in (_DO, _DONT) else _DONT
+        self._sock.sendall(_IAC + refusal + option)
+        self._raw = rest[2:]
+      elif command == _SB:
+        _, end, rest = rest.partition(_IAC + _SE)
+        if not end:
+          return
+        self._raw = rest
+      else:
+        if command == _IAC:
+          self._text += _IAC
+        self._raw = rest[1:]
diff --git a/tests/mobly/controllers/attenuator_lib/__init__.py b/tests/mobly/controllers/attenuator_lib/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/tests/mobly/controllers/attenuator_lib/__init__.py
diff --git a/tests/mobly/controllers/attenuator_lib/telnet_scpi_client_test.py b/tests/mobly/controllers/attenuator_lib/telnet_scpi_client_test.py
new file mode 100644
index 0000000..41e085b
--- /dev/null
+++ b/tests/mobly/controllers/attenuator_lib/telnet_scpi_client_test.py
@@ -0,0 +1,220 @@
+# Copyright 2026 Google Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Unit tests for mobly.controllers.attenuator_lib.telnet_scpi_client."""
+
+import socket
+import threading
+import unittest
+from unittest import mock
+
+from mobly.controllers import attenuator
+from mobly.controllers.attenuator_lib import telnet_scpi_client
+
+
+class _FakeInstrument:
+  """A telnet server on localhost that serves one behavior per connection.
+
+  Each behavior is a function that takes the accepted connection. Whatever the
+  client sends on a connection is recorded in `received` once the behavior
+  returns.
+  """
+
+  def __init__(self, *behaviors):
+    self.received = []
+    self._behaviors = behaviors
+    self._server = socket.create_server(('localhost', 0))
+    self.port = self._server.getsockname()[1]
+    self._thread = threading.Thread(target=self._serve, daemon=True)
+    self._thread.start()
+
+  def _serve(self):
+    for behavior in self._behaviors:
+      try:
+        conn, _ = self._server.accept()
+      except OSError:
+        return
+      with conn:
+        self.received.append(behavior(conn))
+
+  def stop_listening(self):
+    self._server.close()
+
+  def stop(self):
+    self.stop_listening()
+    self._thread.join()
+
+
+def _answer(response, greeting=b''):
+  """Sends a greeting, then answers one command with a response."""
+
+  def behavior(conn):
+    conn.sendall(greeting)
+    received = conn.recv(1024)
+    conn.sendall(response)
+    # Collect anything else the client sends until it disconnects.
+    while data := conn.recv(1024):
+      received += data
+    return received
+
+  return behavior
+
+
+def _hang_up(conn):
+  """Closes the connection as soon as a command arrives."""
+  return conn.recv(1024)
+
+
+def _stay_silent(conn):
+  """Never answers; returns when the client disconnects."""
+  received = b''
+  while data := conn.recv(1024):
+    received += data
+  return received
+
+
+class TelnetScpiClientTest(unittest.TestCase):
+
+  def _start(self, *behaviors):
+    instrument = _FakeInstrument(*behaviors)
+    client = telnet_scpi_client.TelnetScpiClient(
+        tx_cmd_separator='\r\n', rx_cmd_separator='\r\n'
+    )
+    client.open('localhost', instrument.port)
+
+    def stop():
+      client.close()
+      instrument.stop()
+
+    self.addCleanup(stop)
+    return instrument, client
+
+  def test_cmd_returns_response(self):
+    instrument, client = self._start(_answer(b'MN=RCDAT-6000-90\r\n'))
+
+    self.assertEqual(client.cmd('MN?'), 'MN=RCDAT-6000-90')
+
+    client.close()
+    instrument.stop()
+    self.assertEqual(instrument.received, [b'MN?\r\n'])
+
+  def test_cmd_strips_separator_from_command(self):
+    instrument, client = self._start(_answer(b'1\r\n'))
+
+    client.cmd('CHAN:1:SETATT:10\r\n')
+
+    client.close()
+    instrument.stop()
+    self.assertEqual(instrument.received, [b'CHAN:1:SETATT:10\r\n'])
+
+  def test_cmd_response_split_across_packets(self):
+    def behavior(conn):
+      received = conn.recv(1024)
+      conn.sendall(b'12')
+      conn.sendall(b'.5\r')
+      conn.sendall(b'\n')
+      return received
+
+    _, client = self._start(behavior)
+
+    self.assertEqual(client.cmd(':ATT?'), '12.5')
+
+  def test_cmd_without_waiting_for_response(self):
+    instrument, client = self._start(_stay_silent)
+
+    self.assertIsNone(client.cmd('CHAN:1:SETATT:10', wait_ret=False))
+
+    client.close()
+    instrument.stop()
+    self.assertEqual(instrument.received, [b'CHAN:1:SETATT:10\r\n'])
+
+  def test_cmd_refuses_telnet_option_negotiation(self):
+    # IAC DO ECHO, IAC WILL SUPPRESS-GO-AHEAD, and a subnegotiation.
+    greeting = b'\xff\xfd\x01\xff\xfb\x03\xff\xfa\x18\x01\xff\xf0'
+    instrument, client = self._start(_answer(b'10.0\r\n', greeting=greeting))
+
+    self.assertEqual(client.cmd(':ATT?'), '10.0')
+
+    client.close()
+    instrument.stop()
+    # IAC WONT ECHO and IAC DONT SUPPRESS-GO-AHEAD follow the command.
+    self.assertEqual(
+        instrument.received, [b':ATT?\r\n\xff\xfc\x01\xff\xfe\x03']
+    )
+
+  def test_cmd_drops_nul_bytes(self):
+    _, client = self._start(_answer(b'\x0010.0\r\x00\n'))
+
+    self.assertEqual(client.cmd(':ATT?'), '10.0')
+
+  def test_cmd_waits_for_prompt(self):
+    instrument = _FakeInstrument(_answer(b'10.0\n> ', greeting=b'> '))
+    self.addCleanup(instrument.stop)
+    client = telnet_scpi_client.TelnetScpiClient(prompt='> ')
+    client.open('localhost', instrument.port)
+    self.addCleanup(client.close)
+
+    self.assertEqual(client.cmd(':ATT?'), '10.0')
+
+  def test_cmd_reconnects_when_connection_is_closed(self):
+    instrument, client = self._start(_hang_up, _answer(b'10.0\r\n'))
+
+    self.assertEqual(client.cmd(':ATT?'), '10.0')
+
+    client.close()
+    instrument.stop()
+    self.assertEqual(instrument.received, [b':ATT?\r\n', b':ATT?\r\n'])
+
+  @mock.patch.object(telnet_scpi_client, '_RESPONSE_TIMEOUT_SEC', 0.05)
+  def test_cmd_reconnects_when_no_response(self):
+    instrument, client = self._start(_stay_silent, _answer(b'10.0\r\n'))
+
+    self.assertEqual(client.cmd(':ATT?'), '10.0')
+
+    client.close()
+    instrument.stop()
+    self.assertEqual(instrument.received, [b':ATT?\r\n', b':ATT?\r\n'])
+
+  @mock.patch.object(telnet_scpi_client, '_RESPONSE_TIMEOUT_SEC', 0.05)
+  def test_cmd_raises_when_no_response_after_reconnect(self):
+    _, client = self._start(_stay_silent, _stay_silent)
+
+    with self.assertRaisesRegex(
+        attenuator.Error, 'Telnet command failed to return valid data'
+    ):
+      client.cmd(':ATT?')
+
+  def test_cmd_raises_when_reconnect_fails(self):
+    instrument, client = self._start(_hang_up)
+    instrument.stop_listening()
+
+    with self.assertRaisesRegex(attenuator.Error, "Command ':ATT\\?' to"):
+      client.cmd(':ATT?')
+
+    self.assertFalse(client.is_open)
+
+  def test_cmd_raises_when_not_open(self):
+    client = telnet_scpi_client.TelnetScpiClient()
+
+    with self.assertRaisesRegex(attenuator.Error, 'not open'):
+      client.cmd(':ATT?')
+
+  def test_cmd_rejects_non_string_command(self):
+    client = telnet_scpi_client.TelnetScpiClient()
+
+    with self.assertRaises(TypeError):
+      client.cmd(b':ATT?')
+
+
+if __name__ == '__main__':
+  unittest.main()