Wednesday, 2 August 2023

How to fix this python telnet code to send a command to a device a second time?

Under windows 10 and using python 3.10.11 I am trying to run a command on a telnet-connected device twice. The problem is that only the first time it works and the second time the command is only half(?) transmitted to the device?

First, here is the complete code:

import time
import telnetlib

def read(session, timeout=1):
    received = b""
    t0 = time.time()
    while time.time() - t0 < timeout:
        data = session.read_very_eager()
        if data:
            received += data
            t0 = time.time()
    return received.decode()

def write_and_read(session, command):
    time.sleep(1)
    session.write(command.encode() + b"\r\n")
    time.sleep(1)
    reply = read(session)
    print(reply)


session = telnetlib.Telnet("192.168.200.10", 9000, 20)
command = "$SENSOR,STATUS,192.168.200.53"

write_and_read(session, command)
write_and_read(session, command)

As you see the same command ("$SENSOR,STATUS,192.168.200.53") is executed twice. But only the first time it works and I get the expected output.

The output I get is

Requesting radar report from 192.168.200.53...
Failed to query sensor. Is the IP correct? Is the sensor powered?

$SENSOR,STATUS,192.168

The first two lines is the correct response from the device. And the fourth line shows what I get when the command is executed again.

I tried already different sleeps, different reads, different timing, nothing. The second command just does not get through (?). It varies however in the response I get. Thhey can be

$SENSOR,STATUS,192.168
$SENSOR,STATUS,192.168.2
$SENSOR,STATUS,192.168.

etc. It is always some random number of characters missing.

Is there any that issue can be fixed? Might that be related to windows 10? A colleague with the same device using windows 11 does not get this issue at all...

Here is the complete communication when I use a slightly altered code as follows:

def write_and_read(session, command, a, b):
    time.sleep(a)
    to_write = command.encode() + b"\r\n"
    print("WRITE: ", to_write)
    session.write(to_write)
    time.sleep(b)
    reply = session.read_until(b"\n")
    print("READ: ", reply)
    reply = session.read_until(b"\n")
    print("READ: ", reply)
    return reply

command = "$SENSOR,STATUS,192.168.200.53"

with telnetlib.Telnet("192.168.200.10", 9000, 10) as session:
    write_and_read(session, command, 0, 2)
    write_and_read(session, command, 0, 2)
    session.close()

then the output is

WRITE:  b'$SENSOR,STATUS,192.168.200.53\r\n'
READ:  b'\x1b[0GRequesting radar report from 192.168.200.53...\r\n'
READ:  b'Failed to query sensor. Is the IP correct? Is the sensor powered?\r\n'
WRITE:  b'$SENSOR,STATUS,192.168.200.53\r\n'

and then it blocks indefinitely.



from How to fix this python telnet code to send a command to a device a second time?

No comments:

Post a Comment