Saturday, March 03, 2007

Send key presses to mythfrontend telnet control

Here is a simple python script that simplifies controlling mythfrontend over a network. It simply captures key presses and sends them to mythfrontend using the telnet interface 'key ...' command.



#!/usr/bin/python
#
# Send control keys to mythfrontend. Remember to enable network control
# in the mythfrontend settings.
#
# Ben Anhalt 03/03/07
#

import curses
import curses.wrapper
import curses.ascii
import telnetlib
import sys



key_map = {ord('\\') : 'backslash',
curses.KEY_BACKSPACE : 'backspace',
ord('[') : 'bracketleft',
ord(']') : 'bracketright',
ord(':') : 'colon',
curses.KEY_DOWN : 'down',
ord('\n') : 'enter',
ord('=') : 'equal',
curses.ascii.ESC : 'escape',
curses.KEY_F1 : 'f1',
curses.KEY_F10 : 'f10',
curses.KEY_F11 : 'f11',
curses.KEY_F12 : 'f12',
curses.KEY_F2 : 'f2',
curses.KEY_F3 : 'f3',
curses.KEY_F4 : 'f4',
curses.KEY_F5 : 'f5',
curses.KEY_F6 : 'f6',
curses.KEY_F7 : 'f7',
curses.KEY_F8 : 'f8',
curses.KEY_F9 : 'f9',
ord('>') : 'greater',
curses.KEY_LEFT : 'left',
ord('<') : 'less',
curses.KEY_NPAGE : 'pagedown',
curses.KEY_PPAGE : 'pageup',
curses.KEY_RIGHT : 'right',
ord(';') : 'semicolon',
ord('/') : 'slash',
ord(' ') : 'space',
curses.KEY_UP : 'up'}

def main(stdscr, tn):
stdscr.scrollok(1)

while 1:
c = stdscr.getch()

if c == ord('q'):
break

try:
send = 'key ' + key_map[c] + '\n'

except KeyError:
if curses.ascii.isalnum(c):
send = 'key ' + chr(c) + '\n'
else:
send = '\n'

tn.write(send)
stdscr.addstr('Sent: ' + send)

#recv = tn.read_some()
#stdscr.addstr('Recv: ' + recv)



try:
host = sys.argv[1]
except IndexError:
print """Usage: %s HOST [PORT]
HOST - Address of host running mythfrontend.
PORT - Mythfrontend control port.""" % sys.argv[0]

sys.exit()

port = 6546
if len(sys.argv) > 2:
port = int(sys.argv[2])


tn = telnetlib.Telnet(host, port)
tn.read_until('#')

curses.wrapper(main, tn)

tn.close()

No comments: