Add smarttv.py

This commit is contained in:
Sthope 2024-03-17 13:32:44 +01:00
parent a444faf445
commit 811e75f2bb

87
smarttv.py Normal file
View File

@ -0,0 +1,87 @@
import serial
import time
import sys
SERIAL_PORT = '/dev/ttyUSB0'
BAUD_RATE = 19200
SMARTTV_HELP = b'?\r'
SMARTTV_ON = b'on\r'
SMARTTV_OFF = b'off\r'
SMARTTV_GET_MUTE = b'get mute\r'
SMARTTV_MUTE = b'set mute=on\r'
SMARTTV_UNMUTE = b'set mute=off\r'
SMARTTV_GET_STATE = b'get powerstate\r'
SMARTTV_GET_VOLUME = b'get volume\r'
SMARTTV_SET_VOLUME = b'set volume=%d\r'
SMARTTV_GET_POWERSTATE = b'get powerstate\r'
SMARTTV_GET_INPUT = b'get input\r'
SMARTTV_SET_INPUT_HDMI = b'set input=hdmi1\r'
SMARTTV_SET_INPUT_OPS= b'set input=ops/hdmi2\r'
def send_command(command):
with serial.Serial(SERIAL_PORT, BAUD_RATE, timeout=1) as ser:
ser.write(command)
time.sleep(0.1)
reply = ser.read(100)
return reply.decode('utf-8')
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python3 smarttv.py [power_on|power_off|get_volume|set_volume=volume]")
sys.exit(1)
command = sys.argv[1]
if command == "help":
print(send_command(SMARTTV_HELP))
elif command == "power_on":
print(send_command(SMARTTV_ON))
elif command == "power_off":
print(send_command(SMARTTV_OFF))
elif command == "get_state":
print(send_command(SMARTTV_GET_STATE))
elif command == "get_volume":
print(send_command(SMARTTV_GET_VOLUME))
elif command == "set_volume":
if len(sys.argv) != 3:
print("Usage: python3 smarttv.py set_volume volume")
sys.exit(1)
volume = int(sys.argv[2])
if not 0 <= volume <= 100:
print("Volume must be between 0 and 100")
sys.exit(1)
volume_command = SMARTTV_SET_VOLUME % volume
print(send_command(volume_command))
elif command == "get_mute":
print(send_command(SMARTTV_GET_MUTE))
elif command == "mute":
print(send_command(SMARTTV_MUTE))
elif command == "unmute":
print(send_command(SMARTTV_UNMUTE))
elif command == "get_powerstate":
print(send_command(SMARTTV_GET_POWERSTATE))
elif command == "get_input":
print(send_command(SMARTTV_GET_INPUT))
elif command == "set_input_hdmi":
print(send_command(SMARTTV_SET_INPUT_HDMI))
elif command == "set_input_ops":
print(send_command(SMARTTV_SET_INPUT_OPS))
else:
print("Invalid command. Usage: python3 smarttv.py [power_on|power_off|get_volume|set_volume=volume]")
sys.exit(1)