Kodi Community Forum

Full Version: Python loop command until serial response includes string
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a Py script that controls my TV. I have posted about this before but didn't get much so I am trying a little different approach.

This is the ON command.
Code:
import time, serial
ser = serial.Serial(port='/dev/ttyUSB0', baudrate=9600, timeout=1)
ser.write("\x08\x22\x00\x00\x00\x02\xd4")
data = ser.read(24)
print data.encode('hex')
time.sleep(2)
ser.close()

This works but occasinaly the TV dosent respond and I have to try again. Maybe two or three times. Once the TV does respond it sends data back.

This is what it should send:
Code:
030cf100

But sometimes I get:
Code:
030cf1030cf100
or
ada103010001a6030cf100

When I get extra data the 030cf100 is still there. So what I want is to do a loop, maybe setting the response as a variable until that response has the string 030cf100 in it somewhere.

Can anyone help me with this?
I came up with this but it still continues even if it gets the exact string. Thoughts?

Code:
import time, serial
ser = serial.Serial(port='/dev/ttyUSB0', baudrate=9600, timeout=1)
data=""
string="030cf100"
while 1 == 1:
        if string in data:
                print "found it"
                Break
                ser.close()
        else:
                ser.write("\x08\x22\x00\x00\x00\x01\xd5")
                data = ser.read(24)
                resp=data.encode('hex')
                print resp
                time.sleep(1)
print "finished"
untested, but something like this should work:

Code:
import time, serial

def send_command(cmd):
        ser = serial.Serial(port='/dev/ttyUSB0', baudrate=9600, timeout=1)
        ser.write(cmd)
        return ser.read(24)

while (send_command("\x08\x22\x00\x00\x00\x01\xd5") != "030cf100"):
        time.sleep(1)

print "finished"
ser.close()