Search code examples
pythonpython-3.xxml-rpcpyserial

Python Make serial output accessible to other scripts


I currently have a script that gets a feed from a serial device.

feed.py

from serial import Serial
ser = Serial('COM27', 9600, timeout=5)

def scrape():
    while True:
        raw = ser.readline()
        raw = raw.decode('utf-8')
        if raw == "":
            pass
        else:
            print(raw)
    #print (raw.decode('utf-8'))
scrape()

What I would like to do now is access that feed from other python scripts. I did try using SimpleXMLRPCServer but could not get the output

feed.py

from serial import Serial
from xmlrpc.server import SimpleXMLRPCServer
ser = Serial('COM27', 9600, timeout=5)

def scrape():
    while True:
        raw = ser.readline()
        raw = raw.decode('utf-8')
        if raw == "":
            pass
        else:
            print(raw)
try:
    server = SimpleXMLRPCServer(("localhost", 8000), allow_none=True)
    server.register_function(scrape)
    server.serve_forever()

except Exception as e:
    print(e)

listener.py

import xmlrpc.client

feed = xmlrpc.client.ServerProxy('http://localhost:8000')

print(feed.scrape())

I got no output from the listener scrpit


Solution

  • When a function is registered then it is expected that the function returns an information, not just print it, so that is the reason for the failure of your logic.

    In this case it is better to register the Serial object:

    feed.py

    from serial import Serial
    from xmlrpc.server import SimpleXMLRPCServer
    
    ser = Serial("COM27", 9600, timeout=5)
    
    try:
        server = SimpleXMLRPCServer(("localhost", 8000), allow_none=True)
        server.register_instance(ser)
        server.serve_forever()
    
    except Exception as e:
        print(e)
    

    listener.py

    import xmlrpc.client
    
    ser = xmlrpc.client.ServerProxy("http://localhost:8000")
    
    while True:
        raw = ser.readline()
        if raw:
            print(raw)