简体   繁体   English

pyserial 连接有效,但如何使用 ser.readline() 处理输出?

[英]pyserial connection works, but how to handle output with ser.readline()?

I can connect to an energy-meter (Baudrate 300!) and the logfile with 228 lines comes slowly in.我可以连接到一个电表(波特率 300!),228 行的日志文件慢慢进入。

line = ser.readline(eol='!') 
print line

If I use the above code, the complete logfiles is shown.如果我使用上面的代码,则会显示完整的日志文件。 And if I parse separatly saved logfiles with match, it sorts out the right values into sqlite.如果我用 match 解析单独保存的日志文件,它会将正确的值分类到 sqlite。 So both "parts" work separatly.所以这两个“部分”是分开工作的。

But my script is not capable of handing over the output to parse it.但是我的脚本无法移交输出来解析它。 It does'nt throw an error, only that 0 values were given.它不会抛出错误,只给出了 0 个值。

What am I missing?我错过了什么? First I thought, the script is to fast for the slow input (takes over a minute), but the script waits long enough before it is finished.首先我想,脚本是为了慢速输入而加快速度(需要一分钟以上),但是脚本在完成之前等待足够长的时间。

#!/usr/bin/env python
# -*- coding: iso-8859-1 -*- 

import serial
import time
import re
import sqlite3

ser = serial.Serial()
ser.baudrate = 300
ser.port = '/dev/ttyUSB0'     
ser.timeout = 20 
ser.parity = serial.PARITY_EVEN
ser.stopbits = serial.STOPBITS_ONE
ser.bytesize = serial.SEVENBITS

ser.open()
ser.isOpen()

#initiating logfile-output with /?!
time.sleep(2)
ser.write("/?!")
#time.sleep(0.001) 
ser.write("\r\n")       
time.sleep(2)

connection = sqlite3.connect('/var/www/zaehler/test1.db')
cursor = connection.cursor()
extrakt = []

#line = ser.readline(eol='!')
#print line-would work
   
for line in ser.readline(eol='!'):
                match = re.search(r'(0\.0\.0|0\.9\.1|0\.9\.2|1\.6\.1|1\.8\.1)\(([0-9\.]+)', line)
                if match: 
                        version,value = match.groups() 
                        extrakt.append(value)

cursor.execute('INSERT INTO energielog (sernr, time, date, peak, kwh) values (?, ?, ?, ?, ?)', extrakt)

connection.commit()

ser.close()
cursor.close()
connection.close()

I would suggest you use a WHILE loop instead of a FOR loop.我建议您使用 WHILE 循环而不是 FOR 循环。 The readline function is not an iterable, so you cannot loop over its values. readline 函数不是可迭代的,因此您不能循环遍历它的值。 This line does not do what you intended:此行不符合您的预期:

for line in ser.readline(eol='!')

Instead, try this:相反,试试这个:

ss = r'(0\.0\.0|0\.9\.1|0\.9\.2|1\.6\.1|1\.8\.1)\(([0-9\.]+)'

while (True):
    line = ser.readline(eol='!')
    if (len(line) == 0):
        break
    match = re.search(ss, line)
    if match: 
        version,value = match.groups() 
        extrakt.append(value)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM