ser.inWaiting() always returns 0 when reading a virtual port

孤者浪人 提交于 2020-01-06 02:22:46

问题


I'm having difficulties getting pyserial to play nicely with a virtual port. I know this is an area which a few others have written about, but I couldn't find anything which solved my problem in those answers. Forgive me if I'm just being dense, and the solution exists ready-made elsewhere.

This is what I'm trying to achieve: I want to set up a virtual port, to which I can write data in one .py file, and from which I can then read data in another .py file. This is for the purposes of development and testing; I don't always have access to the device around which my current project is built.

This is my code so far:

dummy_serial.py

import os, pty, serial, time

master, slave = pty.openpty()
m_name = os.ttyname(master)
s_name = os.ttyname(slave)

# This tells us which ports "openpty" has happened to choose.
print("master: "+m_name)
print("slave: "+s_name)

ser = serial.Serial(s_name, 9600)

message = "Hello, world!"
encoded = message.encode("ascii")

while True:
  ser.write(encoded)
  time.sleep(1)

reader.py

import serial, time

# The port will change, depending on what port "openpty" (in the other file)
# happens to choose.
ser = serial.Serial("/dev/pts/1", 9600)

while True:
  time.sleep(1)
  incoming_bytes = ser.inWaiting()
  # This print statement gives us an idea of what's going on.
  print(incoming_bytes)
  if incoming_bytes != 0:
    data = ser.read(incoming_bytes)
    print(data)

At present, dummy_serial.py seems to run okay. However, reader.py just keeps saying that there are no bytes waiting to be read, and hence reads no data.

What I would like:

  • An explanation of why ser.inWaiting() keeps returning 0, and a solution which makes ser.read(x) actually spit out "Hello, world!"
  • Or an explanation of why what I'm trying to do is fundamentally silly, and a better means of creating a writeable/readable virtual port.

来源:https://stackoverflow.com/questions/57753616/ser-inwaiting-always-returns-0-when-reading-a-virtual-port

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!