#!/usr/bin/env python3
import subprocess
from time import sleep

import pychromecast
from py_irsend import irsend

CHROMECAST_NAME = 'Bedroom TV'
TV = 'Sanyo_TV'
STATUS_PIN = 18

pychromecast.IGNORE_CEC.append('*')
CHROMECAST = None

VOLUME_INCREMENT = 12


def send_button(button, times=1):
    for i in range(times):
        irsend.send_once(TV, [button])
    print(f'Hit {button} (x{times})')


def toggle_power():
    # Not entirely sure why, but need to hold the button for a bit
    send_button('KEY_POWER', 4)


def get_chromecast(name):
    chromecast = next((cc
        for cc in pychromecast.get_chromecasts()
        if cc.device.friendly_name == name), None)
    chromecast.wait()
    return chromecast


def configure_status():
    subprocess.run(f'gpio -g mode {STATUS_PIN} up'.split())


def is_on():
    status = subprocess.run(f'gpio -g read {STATUS_PIN}'.split(),
                            capture_output=True)
    txt = status.stdout.decode().strip()
    return not int(txt)


def is_correct_state():
    return is_on() != CHROMECAST.is_idle


def volume_up(increment):
    send_button('KEY_VOLUMEUP', increment)


def volume_down(increment):
    send_button('KEY_VOLUMEDOWN', increment)


if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser(description='''Controls a TV based on a Chromecast's state.''')
    parser.add_argument('--verbose', '-v', action='count')
    args = parser.parse_args()

    CHROMECAST = get_chromecast(CHROMECAST_NAME)
    last_state = CHROMECAST.is_idle
    states = [True] * 10

    configure_status()

    print('Polling Idle State')
    state_index = 0
    while True:
        # Switch on derivative (~1s)
        state = CHROMECAST.is_idle
        if state != last_state:
            last_state = state
            toggle_power()

        # Switch if states don't match for 10 cycles (~10s)
        state_index = (state_index + 1) % 10
        states[state_index] = is_correct_state()
        if args.verbose:
            if args.verbose >= 2:
                print(f'Idle: {state} State {states[state_index]} {state_index}')
            print('State Register: ' + ''.join('1' if state else '0' for state in states))
        if True not in states:
            print('Correcting State')
            toggle_power()
            states = [True] * 10
            continue

        # Handle Volume (~1s)
        for i in range(10):
            volume = CHROMECAST.status.volume_level
            if volume > 0.96:
                volume_down(6)
                CHROMECAST.set_volume(.5)
            elif volume >= 0.90:
                CHROMECAST.set_volume(.5)
                volume_up(VOLUME_INCREMENT)
            elif volume <= 0.10:
                volume_down(VOLUME_INCREMENT)
                CHROMECAST.set_volume(.5)
            sleep(0.1)

de955505a1ee5acd48ba79cbec3798898b0ee0fe
<mask token>


def send_button(button, times=1):
    for i in range(times):
        irsend.send_once(TV, [button])
    print(f'Hit {button} (x{times})')


<mask token>


def get_chromecast(name):
    chromecast = next((cc for cc in pychromecast.get_chromecasts() if cc.
        device.friendly_name == name), None)
    chromecast.wait()
    return chromecast


def configure_status():
    subprocess.run(f'gpio -g mode {STATUS_PIN} up'.split())


def is_on():
    status = subprocess.run(f'gpio -g read {STATUS_PIN}'.split(),
        capture_output=True)
    txt = status.stdout.decode().strip()
    return not int(txt)


def is_correct_state():
    return is_on() != CHROMECAST.is_idle


<mask token>


def volume_down(increment):
    send_button('KEY_VOLUMEDOWN', increment)


<mask token>

<mask token>


def send_button(button, times=1):
    for i in range(times):
        irsend.send_once(TV, [button])
    print(f'Hit {button} (x{times})')


def toggle_power():
    send_button('KEY_POWER', 4)


def get_chromecast(name):
    chromecast = next((cc for cc in pychromecast.get_chromecasts() if cc.
        device.friendly_name == name), None)
    chromecast.wait()
    return chromecast


def configure_status():
    subprocess.run(f'gpio -g mode {STATUS_PIN} up'.split())


def is_on():
    status = subprocess.run(f'gpio -g read {STATUS_PIN}'.split(),
        capture_output=True)
    txt = status.stdout.decode().strip()
    return not int(txt)


def is_correct_state():
    return is_on() != CHROMECAST.is_idle


def volume_up(increment):
    send_button('KEY_VOLUMEUP', increment)


def volume_down(increment):
    send_button('KEY_VOLUMEDOWN', increment)


<mask token>

<mask token>
pychromecast.IGNORE_CEC.append('*')
<mask token>


def send_button(button, times=1):
    for i in range(times):
        irsend.send_once(TV, [button])
    print(f'Hit {button} (x{times})')


def toggle_power():
    send_button('KEY_POWER', 4)


def get_chromecast(name):
    chromecast = next((cc for cc in pychromecast.get_chromecasts() if cc.
        device.friendly_name == name), None)
    chromecast.wait()
    return chromecast


def configure_status():
    subprocess.run(f'gpio -g mode {STATUS_PIN} up'.split())


def is_on():
    status = subprocess.run(f'gpio -g read {STATUS_PIN}'.split(),
        capture_output=True)
    txt = status.stdout.decode().strip()
    return not int(txt)


def is_correct_state():
    return is_on() != CHROMECAST.is_idle


def volume_up(increment):
    send_button('KEY_VOLUMEUP', increment)


def volume_down(increment):
    send_button('KEY_VOLUMEDOWN', increment)


if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description=
        "Controls a TV based on a Chromecast's state.")
    parser.add_argument('--verbose', '-v', action='count')
    args = parser.parse_args()
    CHROMECAST = get_chromecast(CHROMECAST_NAME)
    last_state = CHROMECAST.is_idle
    states = [True] * 10
    configure_status()
    print('Polling Idle State')
    state_index = 0
    while True:
        state = CHROMECAST.is_idle
        if state != last_state:
            last_state = state
            toggle_power()
        state_index = (state_index + 1) % 10
        states[state_index] = is_correct_state()
        if args.verbose:
            if args.verbose >= 2:
                print(
                    f'Idle: {state} State {states[state_index]} {state_index}')
            print('State Register: ' + ''.join('1' if state else '0' for
                state in states))
        if True not in states:
            print('Correcting State')
            toggle_power()
            states = [True] * 10
            continue
        for i in range(10):
            volume = CHROMECAST.status.volume_level
            if volume > 0.96:
                volume_down(6)
                CHROMECAST.set_volume(0.5)
            elif volume >= 0.9:
                CHROMECAST.set_volume(0.5)
                volume_up(VOLUME_INCREMENT)
            elif volume <= 0.1:
                volume_down(VOLUME_INCREMENT)
                CHROMECAST.set_volume(0.5)
            sleep(0.1)

import subprocess
from time import sleep
import pychromecast
from py_irsend import irsend
CHROMECAST_NAME = 'Bedroom TV'
TV = 'Sanyo_TV'
STATUS_PIN = 18
pychromecast.IGNORE_CEC.append('*')
CHROMECAST = None
VOLUME_INCREMENT = 12


def send_button(button, times=1):
    for i in range(times):
        irsend.send_once(TV, [button])
    print(f'Hit {button} (x{times})')


def toggle_power():
    send_button('KEY_POWER', 4)


def get_chromecast(name):
    chromecast = next((cc for cc in pychromecast.get_chromecasts() if cc.
        device.friendly_name == name), None)
    chromecast.wait()
    return chromecast


def configure_status():
    subprocess.run(f'gpio -g mode {STATUS_PIN} up'.split())


def is_on():
    status = subprocess.run(f'gpio -g read {STATUS_PIN}'.split(),
        capture_output=True)
    txt = status.stdout.decode().strip()
    return not int(txt)


def is_correct_state():
    return is_on() != CHROMECAST.is_idle


def volume_up(increment):
    send_button('KEY_VOLUMEUP', increment)


def volume_down(increment):
    send_button('KEY_VOLUMEDOWN', increment)


if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description=
        "Controls a TV based on a Chromecast's state.")
    parser.add_argument('--verbose', '-v', action='count')
    args = parser.parse_args()
    CHROMECAST = get_chromecast(CHROMECAST_NAME)
    last_state = CHROMECAST.is_idle
    states = [True] * 10
    configure_status()
    print('Polling Idle State')
    state_index = 0
    while True:
        state = CHROMECAST.is_idle
        if state != last_state:
            last_state = state
            toggle_power()
        state_index = (state_index + 1) % 10
        states[state_index] = is_correct_state()
        if args.verbose:
            if args.verbose >= 2:
                print(
                    f'Idle: {state} State {states[state_index]} {state_index}')
            print('State Register: ' + ''.join('1' if state else '0' for
                state in states))
        if True not in states:
            print('Correcting State')
            toggle_power()
            states = [True] * 10
            continue
        for i in range(10):
            volume = CHROMECAST.status.volume_level
            if volume > 0.96:
                volume_down(6)
                CHROMECAST.set_volume(0.5)
            elif volume >= 0.9:
                CHROMECAST.set_volume(0.5)
                volume_up(VOLUME_INCREMENT)
            elif volume <= 0.1:
                volume_down(VOLUME_INCREMENT)
                CHROMECAST.set_volume(0.5)
            sleep(0.1)

#!/usr/bin/env python3
import subprocess
from time import sleep

import pychromecast
from py_irsend import irsend

CHROMECAST_NAME = 'Bedroom TV'
TV = 'Sanyo_TV'
STATUS_PIN = 18

pychromecast.IGNORE_CEC.append('*')
CHROMECAST = None

VOLUME_INCREMENT = 12


def send_button(button, times=1):
    for i in range(times):
        irsend.send_once(TV, [button])
    print(f'Hit {button} (x{times})')


def toggle_power():
    # Not entirely sure why, but need to hold the button for a bit
    send_button('KEY_POWER', 4)


def get_chromecast(name):
    chromecast = next((cc
        for cc in pychromecast.get_chromecasts()
        if cc.device.friendly_name == name), None)
    chromecast.wait()
    return chromecast


def configure_status():
    subprocess.run(f'gpio -g mode {STATUS_PIN} up'.split())


def is_on():
    status = subprocess.run(f'gpio -g read {STATUS_PIN}'.split(),
                            capture_output=True)
    txt = status.stdout.decode().strip()
    return not int(txt)


def is_correct_state():
    return is_on() != CHROMECAST.is_idle


def volume_up(increment):
    send_button('KEY_VOLUMEUP', increment)


def volume_down(increment):
    send_button('KEY_VOLUMEDOWN', increment)


if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser(description='''Controls a TV based on a Chromecast's state.''')
    parser.add_argument('--verbose', '-v', action='count')
    args = parser.parse_args()

    CHROMECAST = get_chromecast(CHROMECAST_NAME)
    last_state = CHROMECAST.is_idle
    states = [True] * 10

    configure_status()

    print('Polling Idle State')
    state_index = 0
    while True:
        # Switch on derivative (~1s)
        state = CHROMECAST.is_idle
        if state != last_state:
            last_state = state
            toggle_power()

        # Switch if states don't match for 10 cycles (~10s)
        state_index = (state_index + 1) % 10
        states[state_index] = is_correct_state()
        if args.verbose:
            if args.verbose >= 2:
                print(f'Idle: {state} State {states[state_index]} {state_index}')
            print('State Register: ' + ''.join('1' if state else '0' for state in states))
        if True not in states:
            print('Correcting State')
            toggle_power()
            states = [True] * 10
            continue

        # Handle Volume (~1s)
        for i in range(10):
            volume = CHROMECAST.status.volume_level
            if volume > 0.96:
                volume_down(6)
                CHROMECAST.set_volume(.5)
            elif volume >= 0.90:
                CHROMECAST.set_volume(.5)
                volume_up(VOLUME_INCREMENT)
            elif volume <= 0.10:
                volume_down(VOLUME_INCREMENT)
                CHROMECAST.set_volume(.5)
            sleep(0.1)
