【问题标题】:Having trouble opening serial port, or reading from serial port with pyserial无法打开串口,或使用 pyserial 从串口读取
【发布时间】:2017-03-22 17:28:59
【问题描述】:

背景:当 PXE 获得 IP 地址时,我正在尝试自动重启服务器。这是为了重现问题,重现的唯一方法是每次重新启动时在完全相同的时间冷启动它。我已经厌倦了手动执行此操作,到目前为止,我已经在此脚本和故障排除上花费了大约 10 个小时。..

我正在尝试从服务器上的串行控制台读取行,同时查找某个字符串,然后发出重新启动命令。

现在,我可以让这个脚本回显串行控制台上的内容的唯一方法是关闭服务器电源,启动 minicom,打开服务器电源,当文本启动时,我可以退出 minicom 而无需重置,然后启动我的脚本。

第一次运行时,脚本运行良好,甚至最后的 iLO 命令也正常运行,然后它重新启动 while 循环,但我不再从控制台获得任何输出。

看来我要么没有正确打开串口,但我打印了get_settings,波特率、停止位等都是正确的。

我已经从许多不同的地方搜索并使用了 sn-ps 的代码来破解这个脚本,我真的很沮丧,因为我不能让它自己工作。

[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 停止工作..不确定哪个..

标签: python linux python-2.7 serial-port pyserial


【解决方案1】:

它可能会节省一些与串行端口中的其他线路有关的东西:DTR、DSR 等。它们的使用经常不一致,并且它们经常用于其他目的而不是它们的预期用途。

也许 minicom 使用 DTR 来初始化连接。尝试在序列号open之后添加这个。

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

【讨论】:

    猜你喜欢
    • 2017-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-13
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    相关资源
    最近更新 更多