4
votes

I have a python script, which will start cherrypy webserver when run in the terminal. In the script, i use pyserial by importing serial, then i open up the port /dev/ttyAMA0 and i can send any serial commands.

 @cherrypy.expose
 def login (self, **data):
    passcode = data.get("passcode", None)
    print "logging in using passcode %s"%passcode ,type(passcode)

    import serial
    import time
    #open connection
    serialport=serial.Serial ("/dev/ttyAMA0", 9600, timeout=0.5)
    #write in user sign in code
    serialport.write("\x03LI%s\x0D"%passcode)
    #get reply 
    reply=serialport.readlines(1)
    print reply, type(reply)

However, since there is an Ethernet port and i can send the serial command to that similar device using Netcat, how can i let this script to send commands through the ethernet port instead of the serial port? What should i change?

sorry but i'm really clueless on how to do this. i've searched through google and i can't find answers. :(

2
socat is your friend ;)hek2mgl
thanks! it's almost the same as netcat. but how to use either one of them? :syvonnezoe
It's not the same as netcat, although they are related. You could probably connect to a local TCP socket in python, but redirect the byte stream to a serial device using socat. python would not even recognize this. But of course there will be true python solutions as well. Note that I'm not a python expert, but once we did it at work the socat way :) That's why I left the comment.hek2mgl
BTW: There is a dedicated raspberry py stack exchange: raspberrypi.stackexchange.comClay

2 Answers

2
votes

What about using the socat command? Using the following command line you can make /dev/ttyAMA0 accessible via eth 127.0.0.1:5555:

socat PTY,link=/dev/ttyAMA0 TCP:127.0.0.1:5555
0
votes

A Python based approach to the problem is to use the pyserial's built-in network ports functionality (which is based on the RFC2217 standard).

In your server (where the serial device is attached) you run a network serial server - you can use the serial port bridge example e.g:

% python /usr/share/doc/python-serial/examples/rfc2217_server.py -p 7000 /dev/ttyAMA0

And in your client python code you attach to it using a rfc2217 style url with the newer serial_for_url (as mentioned in the howto) e.g:

serial.serial_for_url('rfc2217://yourservername:7000')