开发者

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

开发者 https://www.devze.com 2023-02-08 07:18 出处:网络
I can connect to an energy-meter (Baudrate 300!) and the logfile with 228 lines comes slowly in. line = ser.readline(eol=\'!\')

I can connect to an energy-meter (Baudrate 300!) and the logfile with 228 lines comes slowly in.

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. 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.

What am I missing? First I thought, the script is to fast for the slo开发者_运维百科w 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. The readline function is not an iterable, so you cannot loop over its values. 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)
0

精彩评论

暂无评论...
验证码 换一张
取 消