#!/bin/env python

import os
import sys
import time

# https://github.com/suan/libLGTV_serial
sys.path.append(os.path.join(os.path.dirname(__file__), 'libLGTV_serial'))

# https://github.com/pyserial/pyserial
sys.path.append(os.path.join(os.path.dirname(__file__), 'serial'))

import serial as lib_serial
from libLGTV_serial import LGTV

model = '42PN4500' # actually
model = '42LC7DC' # lol whatever, library supports this one

serial_port = '/dev/ttyUSB0'

def definitely_send(command, timeout=None):
    """Send command to TV in a persistent way."""
    timeout = time.time() + (timeout or 300)
    while True:
        tv = LGTV(model, serial_port)
        try:
            result = tv.send(command)
            if result:
                print("ok")
            else:
                sys.stdout.write('.')
        except lib_serial.serialutil.SerialException:
            sys.stdout.write('X')
        if result or time.time() > timeout:
            break
        time.sleep(.5)

if __name__ == '__main__':
    definitely_send(sys.argv[1])