Nick C
Nick C

Reputation: 73

Reading live output from telnet connection in python

I have an Arduino set up as a server. In Terminal (I use a Mac), one can connect to it, see the output, and close the connection as follows:

> telnet HOST
Trying 192.168.0.101...
Connected to HOST.
Escape character is '^]'.
0 , 25486 , 0.00 :
1 , 25754 , 0.00 :
2 , 26054 , 0.00 :
3 , 26320 , 0.00 :
4 , 26642 , 0.00 :
5 , 26912 , 0.00 :
6 , 27187 , 0.00 :
7 , 27452 , 0.00 :
8 , 27774 , 0.00 :
0 , 28068 , 2.72 :
1 , 28389 , 2.72 :
2 , 28695 , 2.72 :
3 , 29002 , 2.72 :
4 , 29272 , 2.72 :
5 , 29537 , 2.72 :
6 , 29806 , 2.72 :
7 , 30112 , 2.72 :
8 , 30389 , 2.72 :
^]
telnet> quit
Connection closed.

The data currently streams at around 5 lines per second, without delay. I then tried to recreate this connection in a Python script using telnetlib.

import telnetlib
import time

tn = telnetlib.Telnet(HOST)
tn.set_debuglevel(1)

while True:
    tn_read = tn.read_very_eager()
    time.sleep(1)
    print repr(tn_read)

This script only returns empty strings. I read about there being a timing issue, so I included a manual delay. I have also tried tn.read_until(':') to no avail.

My resulting questions:

  1. Is there any way to pull one line at a time, assuming the incoming stream is continuous and effectively never-ending?
  2. How is this implemented in Python?

Thank you.

EDIT: I've included the void loop for the Arduino code.

void loop(void){
    // Handle any multicast DNS requests
    mdns.update();

    // Handle a connected client.
    Adafruit_CC3000_ClientRef client = senseServer.available();
    if (client) {
        Serial.println("Connected");
    for(int i = 0; i < 9; i ++){ //sets number of channels
        client.print(i);
        client.print(" , ");  
        stamp = millis();  
        client.print(stamp);
        client.print(" , ");
        client.print(R2);
        client.println(" :");
        delay(10);
    }
    e = e + 1;
    R2 = pow(2.718,e);
  }
}

Upvotes: 2

Views: 2844

Answers (1)

James K
James K

Reputation: 3752

Can you work at a lower level, using the socket module?

import socket
s = socket.socket(
    socket.AF_INET, socket.SOCK_STREAM)
s.connect(("192.168.0.101", 23))

while True:
    data = str(s.recv(1024),encoding='utf-8')
    print(data)

Why this should work: It seems that your server is not a full telnet server (requiring a login etc) but a socket that waits for a connection, and then returns data.

Since the server is just a socket, you can connect to it with a simple socket, which is what the above does. I tested this in two ways. First with the Star wars telnet server at towel.blinkenlights.nl, and secondly with a simple python server that waits for a connection and then returns a line of text every second (to simulate your server).

Upvotes: 1

Related Questions