[mythtv-users] using mythtv as clockradio

Hika van den Hoven hikavdh at gmail.com
Thu Jan 21 21:51:09 UTC 2016


This should be it! Next embedding it in my WOL script and...

#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import argparse, socket, sys, traceback, time, requests

def read_commandline():
    parser = argparse.ArgumentParser(description='Start LiveTV on the (optionaly) given channel.')

    parser.add_argument('-b', '--backend', type=str, required=True,
        metavar='<hostname>', default=None, dest = 'backend',
        help='backendend dns hostname/ip-address')

    parser.add_argument('-P', '--back_port', type=int, required=False,
        metavar='<portnr>', default=6544, dest = 'back_port',
        help='the backend api portnumber, default is 6544')

    parser.add_argument('-f', '--frontend', type=str, required=False,
        metavar='<hostname>', default=socket.gethostname(), dest = 'frontend',
        help='frontend dns hostname/ip-address, defaults to the local hostname')

    parser.add_argument('-p', '--front_port', type=int, required=False,
        metavar='<portnr>', default=6547, dest = 'front_port',
        help='the frontend api portnumber, default is 6547')

    parser.add_argument('-c', '--channel', type=int, required=False,
        metavar='<channelnr>', default=None, dest = 'channel',
        help='the tv/radio channel to tune to')

    try:
        return parser.parse_args()

    except:
        return

def post_api(url, postdata=None):
    try:
        headers = {'User-Agent':'0.27 Python Services API Client',
                            'Accept': 'application/json'}
        url_request = requests.post(url, headers = headers, data = postdata)
        return url_request.json()

    except requests.ConnectionError:
        sys.stderr.write('The host is not available!\n')

    except:
        sys.stderr.write('An unexpected error has occured:\n')
        sys.stderr.write(traceback.format_exc())

def check_hostname(args):
    url = 'http://%s:%s/Myth/GetHosts' % (args.backend, args.back_port)
    host_list = post_api(url)['StringList']
    if host_list == None:
        return(False)

    for h in host_list:
        if h.lower() == args.frontend.lower():
            args.frontend = h
            return(True)

    else:
        sys.stderr.write('The given Frontend: %s is not known!\n' % args.frontend)
        return(False)

def get_setting(args, key):
    url = 'http://%s:%s/Myth/GetSetting' % (args.backend, args.back_port)
    postdata ={'HostName': args.frontend,'Key': key}
    reply = post_api(url, postdata)
    if reply != None:
        return reply['SettingList']['Settings'][key]

def put_setting(args, key, value):
    url = 'http://%s:%s/Myth/PutSetting' % (args.backend, args.back_port)
    postdata ={'HostName': args.frontend,'Key': key, 'Value': value}
    reply = post_api(url, postdata)
    if reply == None:
        return False

    return(reply['bool'] == 'true')

def get_frontend_state(args):
    url = 'http://%s:%s/Frontend/GetStatus' % (args.frontend, args.front_port)
    reply = post_api(url)
    if reply != None:
        return reply['FrontendStatus']['State']['state']

def send_action(args, api_call):
    url = 'http://%s:%s/Frontend/SendAction' % (args.frontend, args.front_port)
    postdata ={'Action': api_call}
    return (post_api(url, postdata)['bool'] == 'true')

def main():
    try:
        # get the commandline parameters
        args = read_commandline()
        if args == None:
            return(0)

        # Check if the given frontend name is known
        f not check_hostname(args):
            return(2)

        # Check if WatchTVGuide is set
        watch_tv_guide = get_setting(args, 'WatchTVGuide')
        if watch_tv_guide == None:
            sys.stderr.write('Invalid Frontend Name: %s\n' % args.frontend)
            return(2)

        # Try to unset it
        send_select = False
        if watch_tv_guide == '1':
            if not put_setting(args, 'WatchTVGuide', '0'):
                send_select = True

            time.sleep(1)

        # Check if the frontend is available and not busy
        if get_frontend_state(args) != 'idle':
            sys.stderr.write('The Frontend %s is busy or otherwise unavailable\n' % args.frontend)
            return(2)

        # Start Live TV
        if not send_action(args, 'Live TV'):
            sys.stderr.write('The Frontend %s returned False on starting Live TV:\n' % args.frontend)

        # If unsetting WatchTVGuide failed, leave the Guide
        if send_select:
            time.sleep(2)
            send_action(args.host, args.port, 'SELECT')
            time.sleep(1)

        # If a channel was specified, change to that channel
        if args.channel != None:
            time.sleep(1)
            ch = str(args.channel)
            for chn in ch:
                send_action(args, chn)

            send_action(args, 'SELECT')

        # If previously WatchingLiveTV was unset, wait till LiveTV stops to unset it
        if watch_tv_guide == '1':
            while get_frontend_state(args) == 'WatchingLiveTV':
                time.sleep(2)

            time.sleep(2)
            put_setting(args, 'WatchTVGuide', '1')

    except:
        sys.stderr.write('An unexpected error has occured:\n')
        sys.stderr.write(traceback.format_exc())
        return(99)

    # and return success
    return(0)
# end main()

# allow this to be a module
if __name__ == '__main__':
    sys.exit(main())




More information about the mythtv-users mailing list