PySerial Benq projector communication

21 Views Asked by At

I am trying to write small script in Python3 to starting up and set up source in my benq projector that will be started from my Home Assistant server connected to projector via USB to serial connector.

I have coded that script:

import serial
ser = serial.Serial('/dev/ttyUSB0', baudrate=115200, bytesize=8, timeout=none, parity=PARITY_NONE, stopbits=STOPBITS_ONE, xonxoff=False, rtscts=False)

for i in range(1,20):
    ser.write("*pow=?#\r\n")
    sleep (1)
    ans = ser.readline()
    if ans == "ON"
    
    for j in range(1,3):
        ser.write("*sour=?#\r\n")
        sleep (1)
        ans = ser.readline()
        if ans == HDMI2:
            exit
        else
            ser.write("*sour=HDMI2#\r\n")
            sleep (1)
    
    else
        sleep (3)

ser.flush()
ser.close()

Basically what I want to achieve is script asking projector via serial command *pow=?# that the projector is turned on. Projector can return OFF or ON. For first answer script should wait 3 sec and ask again. Once script read ON from projector, 2nd query should start asking for current source ( command *sour=?# ). Answer can be HDMI, HDMI2 or HDMI3. Because projector remember last source selected, I do not want to spam port and not touch source if correct one is already selected.

Alternatively last section could be a bit altered and whole code could be like that:

import serial
ser = serial.Serial('/dev/ttyUSB0', baudrate=115200, bytesize=8, timeout=none, parity=PARITY_NONE, stopbits=STOPBITS_ONE, xonxoff=False, rtscts=False)

for i in range(1,20):
    ser.write("*pow=?#\r\n")
    sleep (1)
    ans = ser.readline()
    if ans == "ON"
       ser.write("*sour=HDMI2#\r\n")
        sleep (1)
        ans = ser.readline()
        if ans == HDMI2:
            exit
        else
            ser.write("*sour=HDMI2#\r\n")
            sleep (1)
    
    else
        sleep (3)

ser.flush()
ser.close()

Not sure that my understanding is correct. Could anyone look into my code to checkup is it correct?

0

There are 0 best solutions below