无法打开串口,或使用pyserial从串口读取数据时遇到问题

3
背景:我正在尝试自动重启服务器,当PXE获取IP地址时。这是为了重现一个问题,而唯一的方法是在每次重新启动时在确切的时间冷启动它。我已经厌倦了手动操作,到目前为止已经花费了大约10个小时来编写和故障排除此脚本。
我正在尝试从服务器的串行控制台读取行,同时寻找特定的字符串,然后发出重启命令。
现在,我能够让这个脚本回显串行控制台上的内容的唯一方法是关闭服务器电源,启动minicom,开启服务器电源,等到文本开始,然后可以退出minicom而不进行重置,然后启动我的脚本。
第一次运行时,脚本正常工作,甚至最后的iLO命令也可以工作,然后它重新启动while循环,但是之后我就再也没有从控制台得到任何输出了。
似乎我要么没有正确打开串口,但我打印get_settings和波特率、停止位等都是正确的。
我已经搜索并从许多不同的地方使用代码片段来拼凑这个脚本,但真的很沮丧,因为我不能让它自己工作。
[root@localhost ~]# python2 bootorder.py 
{'parity': 'N', 'baudrate': 115200, 'bytesize': 8, 'xonxoff': False, 'rtscts': False, 'timeout': None, 'inter_byte_timeout': None, 'stopbits': 1, 'dsrdtr': False, 'write_timeout': None}

如您在上方所见,当我运行它时,串行端口设置被打印出来,与minicom和服务器端的串行控制台匹配。

那么,minicom是如何打开端口的,而我在脚本中没有做到呢?我已经从许多网站上参考了例子,有时确实可以工作,只是我无法弄清楚如何让它自己工作。

这是我的脚本:

#!/usr/bin/python

import io
import hpilo
import os
import sys
import time
import serial
from datetime import datetime

outfile='/tmp/bootordercount.txt'
# configure the serial connections (the parameters differs on the device you    are connecting to)
port = '/dev/ttyS0'
ser = serial.Serial(port,115200,timeout=None)
cycles = 1

if ser.isOpen(): ser.close()
ser.open()

if ser.isOpen():

    try:
#        ser.flushInput() #flush input buffer, discarding all its contents
#        ser.flushOutput()#flush output buffer, aborting current output 
                 #and discard all that is in buffer
    print(ser.get_settings())
    with open(outfile, 'a') as f:

       while ser.isOpen():
           line = ser.readline()
           print line
           if "CLIENT IP:" in line: 
                print "Client string seen!"
                ilo = hpilo.Ilo('10.0.8.203', 'administrator', 'password') #configure ilo function
                ilo.cold_boot_server() #cold boot the server
                print cycles
   #            f.write(datetime.utcnow().isoformat() + '\t' + cycles + '\n')
   #            f.flush()
                cycles += 1

    except Exception, e1:
        print "error communicating...: " + str(e1)
        ser.close()

感谢您的贡献和帮助!

我认为readline部分是正确的,因为它可以正确地通过一次循环,但在循环之后,我就无法从串口获取数据,或者readline停止工作了。不确定是哪个问题。 - John Julian
1个回答

1

这可能与串口中的其他线路有关:DTR、DSR等。它们的使用通常不一致,而且经常被用于与其预期用途不同的目的。

也许minicom使用DTR来初始化连接。在串口open后尝试添加此内容。

s.setDTR(False)
sleep(0.025)
s.setDTR(True)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接