#!/usr/bin/env python2
import subprocess
import time
from requests.exceptions import ConnectionError
from kodijson import Kodi	# sudo pip install kodi-json

def monitor_state():
    mon_state = subprocess.check_output(['/usr/bin/tvservice',  '-s'])
    return mon_state.split(' ')[1] in ['0xa', '0x12000a', '0x40002']


def kodi_state():
        try:
            kodi = Kodi("http://tv:8080/jsonrpc")
            ap = kodi.Player.GetActivePlayers()
            return len(ap['result']) > 0
        except ConnectionError:             # This is a dirty trick, if kodi is not yet ready to answer requests
            return False


prev_state = None
while True:
    # second count
    curr_state = kodi_state()
    # check if there is a change in the screen state
    if curr_state != prev_state:
        if curr_state is True:
            subprocess.check_output(['sispmctl', '-o', '1'])
        else:
            subprocess.check_output(['sispmctl', '-f', '1'])
    prev_state = curr_state
    time.sleep(1.)
