Skip to content

Instantly share code, notes, and snippets.

@mattiaslundberg
Created May 30, 2014 13:53
Show Gist options
  • Save mattiaslundberg/42e001dc7b52b614ebbc to your computer and use it in GitHub Desktop.
Save mattiaslundberg/42e001dc7b52b614ebbc to your computer and use it in GitHub Desktop.
Control LG televisions from python
import serial
import re
class LGTV(object):
""" Interface for serial control of LG Televisions """
def __init__(self, port='/dev/ttyUSB0'):
super(LGTV, self).__init__()
self.port = port
self.ser = serial.Serial(port, 9600)
def _run_command(self, c1, c2, set_id, data):
self.ser.write(bytes('%c%c %x %x\n' % (c1, c2, set_id, data), 'utf-8'))
response = self.ser.read(10)
exp = '%c\ %02x\ OK([\da-fA-F]{2})' % (c2, set_id)
match = re.match(exp, response.decode())
if match is None:
raise Exception('Error running command')
return match.group(1)
def is_on(self):
d = self._run_command('k', 'a', 1, 0xFF)
print('Returned %s' % d)
return int(d) == 1
def power_on(self):
self._run_command('k', 'a', 1, 1)
def power_off(self):
self._run_command('k', 'a', 1, 0)
def view_tv(self):
self._run_command('x', 'b', 1, 1 << 4)
def view_dtv(self):
self._run_command('x', 'b', 1, 0)
def view_hdmi(self):
self._run_command('x', 'b', 1, 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment