def discover_roku(): """ Search LAN for available Roku devices. Returns a Roku object. """ print("Searching for Roku devices within LAN ...") rokus = Roku.discover() if not rokus: print("Unable to discover Roku devices. " + "Try again, or manually specify the IP address with " + "\'roku <ipaddr>\' (e.g. roku 192.168.1.130)") return None print("Found the following Roku devices:") for i, r in enumerate(rokus): print("[" + str(i+1) + "] " + str(r.host) + ":" + str(r.port)) print("") if len(rokus) == 1: print("Selecting Roku 1 by default") return rokus[0] else: print("Multiple Rokus found. Select the index of the Roku to control:") while True: try: query = "Select (1 to " + str(len(rokus)) + ") > " sel = int(raw_input(query)) - 1 if sel >= len(rokus): raise ValueError else: break except ValueError: print("Invalid selection") return rokus[sel]
def __init__(self, host): """Initialize the Roku device.""" from roku import Roku self.roku = Roku(host) self.ip_address = host self.channels = [] self.current_app = None self._device_info = {}
def scan_for_rokus(hass): """Scan for devices and present a notification of the ones found.""" from roku import Roku, RokuException rokus = Roku.discover() devices = [] for roku in rokus: try: r_info = roku.device_info except RokuException: # skip non-roku device continue devices.append('Name: {0}<br />Host: {1}<br />'.format( r_info.userdevicename if r_info.userdevicename else "{} {}".format(r_info.modelname, r_info.sernum), roku.host)) if not devices: devices = ['No device(s) found'] hass.components.persistent_notification.create( 'The following devices were found:<br /><br />' + '<br /><br />'.join(devices), title=NOTIFICATION_SCAN_TITLE, notification_id=NOTIFICATION_SCAN_ID)
def roku(bot, event, *args): try: # https://pypi.python.org/pypi/roku/1.0 admins_list = bot.get_config_suboption(event.conv_id, 'admins') or [] if event.user_id.chat_id in admins_list: ip = bot.user_memory_get(event.user.id_.chat_id, 'roku') if ip is None: rokuControl = Roku.discover(timeout=10)[0] bot.user_memory_set(event.user.id_.chat_id, 'roku', rokuControl.host) ip = rokuControl.host rokuControl = Roku(ip) command = {'up' : rokuControl.up, 'down' : rokuControl.down, 'left' : rokuControl.left, 'right' : rokuControl.right, 'select' : rokuControl.select, 'home' : rokuControl.home, 'back' : rokuControl.back, 'play' : rokuControl.play } arg = args[0] if arg in command: command[args[0].lower()]() else: rokuControl[arg].launch() return else: html_text = "You can't control my roku, you so crazy" except: html_text = "Unable to control the roku right now" logger.exception(html_text) yield from bot.coro_send_message(event.conv_id, html_text)
from os import system import time system('clear') from roku import Roku system('clear') ip = input('Please input the IP of the roku: ') roku = Roku('' + ip) while time.time: roku.home() print('Done.') #time.sleep(1)
def roku_url(): """Return the roku url using SSDP discovery.""" rok = Roku.discover(timeout=5) if len(rok) > 0: return 'http://{}:{}'.format(rok[0].host, rok[0].port)
#!/usr/bin/env python from roku import Roku retour = '' discovered = Roku.discover() for roku in discovered: retour += roku + ';' print retour[:-1]
class MainWindow(tk.Frame): def __init__(self, master, *args, **kwargs): super().__init__(master, *args, **kwargs) self.master = master settings = self.master.settings font = settings['font'] text = settings['colors']['text'] light = settings['colors']['light'] dark = settings['colors']['dark'] power = settings['colors']['power'] app = settings['colors']['app'] size = 20 flat = { 'relief': 'solid', 'bd': 1, 'activebackground': '#ffffff', 'activeforeground': '#ffffff' } font = {**flat, 'font': [font, size], 'fg': text, 'bg': dark} arrow = {**flat, 'font': [font, size], 'fg': text, 'bg': light} app = {**flat, 'font': [font, size], 'fg': text, 'bg': app} power = {**flat, 'font': [font, 30], 'fg': text, 'bg': power} def set_active_bg(f): f['activebackground'] = f['bg'] [set_active_bg(f) for f in [font, arrow, app, power]] self.roku = Roku('192.168.1.144') self.master.title('Roku Remote') self.pack(fill=tk.BOTH, expand=True) config_grids(self, rows=[1, 1, 1, 1, 1, 1], columns=[1, 1, 1, 1]) self.restart_flag = False self.back_button = tk.Button(self, **font, text=u'\u2B60', command=self.roku.back) self.back_button.grid(row=0, column=1, sticky='nsew') self.up_button = tk.Button(self, **arrow, text=u'\u2B9D', command=self.roku.up) self.up_button.grid(row=0, column=2, sticky='nsew') self.home_button = tk.Button(self, **font, text=u'\u2302', command=self.roku.home) self.home_button.grid(row=0, column=3, sticky='nsew') self.left_button = tk.Button(self, **arrow, text=u'\u2B9C', command=self.roku.left) self.left_button.grid(row=1, column=1, sticky='nsew') self.select_button = tk.Button(self, **arrow, text='OK', command=self.roku.select) self.select_button.grid(row=1, column=2, sticky='nsew') self.right_button = tk.Button(self, **arrow, text=u'\u2B9E', command=self.roku.right) self.right_button.grid(row=1, column=3, sticky='nsew') self.replay_button = tk.Button(self, **font, text=u'\u27F2', command=self.roku.replay) self.replay_button.grid(row=2, column=1, sticky='nsew') self.down_button = tk.Button(self, **arrow, text=u'\u2B9F', command=self.roku.down) self.down_button.grid(row=2, column=2, sticky='nsew') self.options_button = tk.Button(self, **font, text=u'\u273C', command=self.roku.info) self.options_button.grid(row=2, column=3, sticky='nsew') self.rewind_button = tk.Button(self, **font, text=u'\u23EA', command=self.roku.reverse) self.rewind_button.grid(row=3, column=1, sticky='nsew') self.pause_play_button = tk.Button(self, **font, text=u'\u25B6\u2758\u2758', command=self.roku.play) self.pause_play_button.grid(row=3, column=2, sticky='nsew') self.fast_forward_button = tk.Button(self, **font, text=u'\u23E9', command=self.roku.forward) self.fast_forward_button.grid(row=3, column=3, sticky='nsew') self.volume_mute_button = tk.Button(self, **font, text='MUTE', command=self.roku.volume_mute, width=20) self.volume_mute_button.grid(row=4, column=1, sticky='nsew') self.volume_down_button = tk.Button(self, **font, text='VOL-', command=self.roku.volume_down, width=20) self.volume_down_button.grid(row=4, column=2, sticky='nsew') self.volume_up_button = tk.Button(self, **font, text='VOL+', command=self.roku.volume_up, width=20) self.volume_up_button.grid(row=4, column=3, sticky='nsew') self.search_button = tk.Button(self, **font, text=u'\u2315', command=self.roku.search, width=20) self.search_button.grid(row=5, column=0, sticky='nsew') self.search_var = tk.StringVar() self.previous_text = '' self.search_var.trace('w', self.send_text) self.search_frame = tk.Frame(self, bg='#000000', bd=1) #self.search_frame.grid(row=5, column=1, columnspan=2, sticky='nsew') config_grids(self.search_frame) self.build_search_input() self.backspace_button = tk.Button(self, **font, text='DEL', command=self.roku.backspace) self.backspace_button.grid(row=5, column=3, sticky='nsew') self.power_button = tk.Button(self, **power, text=u'\u23FB', command=self.roku.power) self.power_button.grid(row=0, column=0, rowspan=2, sticky='nsew') self.computer_button = tk.Button( self, **app, text='PC', command=lambda: self.launch_app('computer')) self.computer_button.grid(row=2, column=0, sticky='nsew') self.plex_button = tk.Button(self, **app, text='PLEX', command=lambda: self.launch_app('plex')) self.plex_button.grid(row=3, column=0, sticky='nsew') self.ps4_button = tk.Button( self, **app, text='PS4', command=lambda: self.launch_app('playstation')) self.ps4_button.grid(row=4, column=0, sticky='nsew') self.menu_bar = Menubar(self) self.master.config(menu=self.menu_bar) self.bindings = [ ('<KeyPress>', self.key_press), ('<Left>', self.roku.left), ('<Right>', self.roku.right), ('<Up>', self.roku.up), ('<Down>', lambda *args: click_button(self.down_button)), ('<Return>', self.roku.select), ('-', self.roku.volume_down), ('+', self.roku.volume_up), ('=', self.roku.volume_up), ('<space>', self.roku.play), ('<BackSpace>', self.roku.back), ] self.bound = False self.master.bind('<FocusIn>', self.set_bindings) self.master.bind('<FocusOut>', self.set_bindings) self.master.geometry(get_geometry(settings)) def get_geometry(self): if all([(key in self.master.settings) for key in ['win_x', 'win_y']]): self.master.geometry('{}x{}+{}+{}'.format( self.master.settings['win_w'], self.master.settings['win_h'], self.master.settings['win_x'], self.master.settings['win_y'])) else: self.master.geometry('{}x{}'.format(settings['win_w'], settings['win_h'])) def send_text(self, *args): text = self.search_var.get() diff = len(self.previous_text) - len(text) if diff < 0: new_text = text[diff] self.roku.literal(new_text) if diff > 0: for i in range(diff): self.roku.backspace() self.previous_text = text def build_search_input(self, *args): font = self.master.settings['font'] ENTRY = {'font': [font, 14], 'fg': '#201d3d', 'bg': '#fcfbfd'} if hasattr(self, 'search_input'): self.search_input.destroy() self.search_input = tk.Entry(self, **ENTRY, bd=10, relief='flat', textvariable=self.search_var) self.search_input.grid(row=5, column=1, columnspan=2, padx=1, pady=1, sticky='nsew') self.search_input.bind('<Escape>', self.build_search_input) def launch_app(self, ident): app = next((a for a in self.roku.apps if ident in a.name.lower()), None) if app: app.launch() def key_press(self, *args): print(args) def set_bindings(self, event): if not self.bound: self.bind_keys(event) else: self.unbind_keys(event) def bind_keys(self, event): for key, func in self.bindings: self.master.bind(key, func) self.bound = True def unbind_keys(self, event): if str(event.widget) == '.!mainwindow.!entry' and self.bound: for key, func in self.bindings: self.master.unbind(key) self.bound = False
from roku import Roku import time ip = "10.0.0.164" # ip = Roku.discover() # ip = str(ip[0]).split(':')[1].replace(' ',"") roku = Roku(ip) # print(str(Roku.discover()[0]).split(':')[1].replace(' ', "")) hulu = False netflix = False def next_episode(): if hulu: roku.down() time.sleep(1) roku.play() # roku.enter() hulu = True tv = True def pause(): if tv: roku.select()
def main(self): # Banner print('==========================================================') print('Discovering Rokus') num_rokus = 0 my_rokus = {} rokus = {} for x in range(0, 2): rokus = Roku.discover(10, 1) if len(rokus) > 0: break else: print('No Rokus discovered on network. Exiting program.') quit() my_apps_xml = '' print(rokus) for device in rokus: device = parse("<Roku: {}:{}>", str(device)) device_ip = device[0] device_port = device[1] baseurl = 'http://' + device_ip + ':' + device_port url = baseurl + '/query/device-info' print(url) try: response = urllib.request.urlopen(str(url)) content = response.read() except urllib.error.HTTPError as e: print(('HTTPError = ' + str(e.code))) continue except urllib.error.URLError as e: print(('URLError = ' + str(e.reason))) continue except httplib.HTTPException as e: print('HTTPException') continue # find the names of the rokus device_tree = etree.XML(content) device_name = device_tree.find('user-device-name') my_rokus[device_name.text] = baseurl # find the apps installed on the first roku found if my_apps_xml == '': try: response = urllib.request.urlopen(baseurl + '/query/apps') my_apps_xml = response.read() except urllib.error.HTTPError as e: print(('HTTPError = ' + str(e.code))) continue except urllib.error.URLError as e: print(('URLError = ' + str(e.reason))) continue except httplib.HTTPException as e: print('HTTPException') continue # write the rokus to a file for use by the roku_trigger script with open("my-rokus.txt", "wb") as myFile: pickle.dump(my_rokus, myFile) # write the apps list xml to a file for use by the roku_trigger script with open("roku-apps.xml", "wb") as myFile: myFile.write(my_apps_xml) print('Saving the following Rokus and the apps installed on them') print(my_rokus)
text='Connect', bg='#E0EEEE', font=('arial', 12, 'normal'), command=connectDevice).place(x=284, y=115) Label(selector, text='Roku IP:', bg='#8A2BE2', font=('arial', 10, 'normal')).place(x=44, y=125) selector.mainloop() print("Connecting...") ###################################################################################### try: roku = Roku(userInput) # Channel shortcuts sling = roku['Sling TV'] netflix = roku['Netflix'] amazon = roku['Prime Video'] nbc = roku['NBC News'] hbo = roku['HBO Max'] # Keybindings keyboard.add_hotkey(72, lambda: roku.up()) keyboard.add_hotkey(75, lambda: roku.left()) keyboard.add_hotkey(77, lambda: roku.right()) keyboard.add_hotkey(80, lambda: roku.down()) keyboard.add_hotkey(14, lambda: roku.backspace()) keyboard.add_hotkey(28, lambda: rokuSubmitText())
def setUp(self): self.roku = Roku('127.0.0.1') self.yt = YouTubeKeyboardController(self.roku, 'A')
getkey = _Getch() if __name__ == '__main__': os.system('cls' if os.name == 'nt' else 'clear') print """ Welcome to Rokudo, your command-line Roku remote. Supported commands: - Arrow keys to navigate - Enter to select - Backspace to go back Enter can also be used to pause/play """ print "Finding Roku on local network..." rokus = Roku.discover(timeout=10) if len(rokus) == 0: print "Couldn't find any Rokus :(. Buy one and try again." exit(0) print "Found at least one Roku. Using the first." roku = rokus[0] done = False while not done: try: key = getkey() if key == 27: done = True # arrow keys elif key == 1080:
def discover(): rokus = Roku.discover() hosts = list(map(lambda r: r.host, rokus)) return make_response(jsonify(hosts), 200)
from flask import Flask, request, url_for, jsonify, render_template, redirect import logging import os from todo import Todo from roku import Roku from hue import Hue app = Flask(__name__) todo = Todo(db='todo.db') tv = Roku(ip=os.environ['roku_ip']) light = Hue(ip=os.environ['hue_ip'], username=os.environ['hue_username']) @app.route('/', methods=['GET', 'POST']) def index(): tasks = todo.get() lights = light.get() if request.method == 'POST' and 'addtask' in request.form: try: task = request.form['addtask'] todo.post(task) tasks = todo.get() app.logger.info("Home: Added todo: " + str(task)) return render_template("index.html", tasks=tasks, lights=lights) except: app.logger.error("Home: Failed to add todo: " + str(task)) if request.method == 'POST' and 'deletetask' in request.form: try:
from roku import Roku rokuls = Roku.discover(timeout=10); print(rokuls); ip = input('IP: '); roku = Roku(ip); rokuapps = roku.apps; print(r[rokuapps]);
# https://github.com/jcarbaugh/python-roku import numpy import sys import time from roku import Roku roku = Roku('192.168.1.214') delay = .200 youtube_search_alpha = [ ['A', 'B', 'C', 'D', 'E', 'F', 'G', '{backspace}'], ['H', 'I', 'J', 'K', 'L', 'M', 'N', '{num}'], ['O', 'P', 'Q', 'R', 'S', 'T', 'U'], ['V', 'W', 'X', 'Y', 'Z', '-', "'"], [' ', '{clear}', '{search}'], ] youtube_search_num = [ ['1', '2', '3', '&', '#', '(', ')', '{backspace}'], ['4', '5', '6', '@', '!', '?', ':', '{alpha}'], ['7', '8', '9', '0', '.', '_', '"'], [' ', '{clear}', '{search}'], ] def youtube_search_character(char): loc = next( ((i, alpha.index(char)) for i, alpha in enumerate(youtube_search_alpha) if char in alpha), None) if loc is None:
from roku import Roku rokuls = Roku.discover(timeout=10) print(rokuls) ip = input('IP: ') roku = Roku(ip) while True: remoteinput = input( 'Remote Input (i.e. down, up, left, right, back, home, ok, open, text): ' ) if remoteinput == 'down': roku.down() elif remoteinput == 'up': roku.up() elif remoteinput == 'left': roku.left() elif remoteinput == 'right': roku.right() elif remoteinput == 'back': roku.back() elif remoteinput == 'home': roku.home() elif remoteinput == 'ok': roku.select() elif remoteinput == 'open': appinput = input('APP (i.e. YouTube): ') apptolaunch = roku[appinput] apptolaunch.launch() elif remoteinput == 'text':
from roku import Roku import threading import time roku = Roku('192.168.0.132') def Change_to_ABC(): '''Switches display to the mode entered as an argument. Works for PC and TV mode.''' def Callback(): print('Switching to ABC') youtube = roku['YouTube TV'] youtube.launch() time.sleep(10) roku.right() time.sleep(1) for _ in range(2): roku.down() time.sleep(.5) roku.enter() if 'YouTube TV' in str(roku.active_app): print('Success') else: input('Roku Failed to switch to ABC on Youtube TV.') ABC = threading.Thread(target=Callback) ABC.start() def Check_If_Youtube_TV(obj): '''Set Scene Function.
def __init__(self, host): """Initialize the Roku device.""" from roku import Roku self.roku = Roku(host) self.update()
from roku import Roku from roku import RokuException import RPi.GPIO as GPIO import time PIN1 = 3 PIN2 = 18 PIN3 = 25 PIN4 = 16 # Connecting to Roku roku = 0 rList = Roku.discover() for r in rList: # On my personal network there are two Roku devices listed by the SSDP crawl; One of them is the remote # the remote uses port 80, so we can filter it out with nothing more than the port here. if r.port == 8060: roku = r if roku == 0: # using systemD to handle upkeep, simpler than doing my own loop and probably more resource efficient raise Exception('No valid Rokus found on network') GPIO.setmode(GPIO.BCM) # Buttons setup, using an internal pull up resistor to simplify the physical circuit I have to build GPIO.setup(PIN1, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(PIN2, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(PIN3, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(PIN4, GPIO.IN, pull_up_down=GPIO.PUD_UP) while True: button1 = GPIO.input(PIN1)
def __init__(self): self.roku = Roku(secrets.rokuIP)
from roku import Roku #connect to roku with your IP, you can get this from your roku in settings network about section. IP = "ENTER YOUR IP HERE" roku = Roku(IP) #check all the apps you have donwloadedApps = roku.apps #keywords it looks for _keywordOpenApp = ["open", "launch"] _keywordMovement = ["w", "a", "s", "d", "up", "left", "right", "down"] _keywordFuncs = ["back", "enter", "play", "backspace", "forward", "search"] _keywordActive = ["active"] _keywordHelp = ["?", "help", "cmds"] #opens an app passed with params ex: "open netflix" def openApp(app): for apps in donwloadedApps: if app == str(apps.name).lower(): appToLaunch = roku[apps.name] appToLaunch.launch() #some basic remote movments includes just the cardinal directions def basicMovement(movementChoice): if movementChoice in ["w", "up"]: cmd = "up" elif movementChoice in ["a", "left"]: cmd = "left" elif movementChoice in ["s", "down"]:
class RokuDevice(MediaPlayerDevice): """Representation of a Roku device on the network.""" # pylint: disable=abstract-method # pylint: disable=too-many-public-methods def __init__(self, host): """Initialize the Roku device.""" from roku import Roku self.roku = Roku(host) self.update() def update(self): """Retrieve latest state.""" import requests.exceptions try: self.roku_name = "roku_" + self.roku.device_info.sernum self.ip_address = self.roku.host self.channels = self.get_source_list() if self.roku.current_app is not None: self.current_app = self.roku.current_app else: self.current_app = None except requests.exceptions.ConnectionError: self.current_app = None def get_source_list(self): """Get the list of applications to be used as sources.""" return ["Home"] + sorted(channel.name for channel in self.roku.apps) @property def should_poll(self): """Device should be polled.""" return True @property def name(self): """Return the name of the device.""" return self.roku_name @property def state(self): """Return the state of the device.""" if self.current_app is None: return STATE_UNKNOWN if self.current_app.name in ["Power Saver", "Default screensaver"]: return STATE_IDLE elif self.current_app.name == "Roku": return STATE_HOME elif self.current_app.name is not None: return STATE_PLAYING return STATE_UNKNOWN @property def supported_media_commands(self): """Flag of media commands that are supported.""" return SUPPORT_ROKU @property def media_content_type(self): """Content type of current playing media.""" if self.current_app is None: return None elif self.current_app.name == "Power Saver": return None elif self.current_app.name == "Roku": return None else: return MEDIA_TYPE_VIDEO @property def media_image_url(self): """Image url of current playing media.""" if self.current_app is None: return None elif self.current_app.name == "Roku": return None elif self.current_app.name == "Power Saver": return None elif self.current_app.id is None: return None return 'http://{0}:{1}/query/icon/{2}'.format(self.ip_address, DEFAULT_PORT, self.current_app.id) @property def app_name(self): """Name of the current running app.""" if self.current_app is not None: return self.current_app.name @property def app_id(self): """Return the ID of the current running app.""" if self.current_app is not None: return self.current_app.id @property def source(self): """Return the current input source.""" if self.current_app is not None: return self.current_app.name @property def source_list(self): """List of available input sources.""" return self.channels def media_play_pause(self): """Send play/pause command.""" if self.current_app is not None: self.roku.play() def media_previous_track(self): """Send previous track command.""" if self.current_app is not None: self.roku.reverse() def media_next_track(self): """Send next track command.""" if self.current_app is not None: self.roku.forward() def mute_volume(self, mute): """Mute the volume.""" if self.current_app is not None: self.roku.volume_mute() def volume_up(self): """Volume up media player.""" if self.current_app is not None: self.roku.volume_up() def volume_down(self): """Volume down media player.""" if self.current_app is not None: self.roku.volume_down() def select_source(self, source): """Select input source.""" if self.current_app is not None: if source == "Home": self.roku.home() else: channel = self.roku[source] channel.launch()
from Tkinter import * from roku import Roku roku = Roku.discover(timeout=5)[0] apps = roku.apps text = None def main(): window = Tk() # window.geometry("800x600") window.title("Pyku Controller") build_tk_window(window) mainloop() def build_tk_window(window): text_box = Entry(window, textvariable=text) text_box.pack() enter_button = Button(window, text="enter", command=lambda: enter_search(text_box)) enter_button.pack() home_button = Button(window, text="home", command=home) home_button.pack()
#!/usr/bin/env python3 from roku import Roku import ssdp import os import curses screen = curses.initscr() curses.noecho() curses.cbreak() screen.keypad(True) roku = Roku('192.168.11.103') netflix = roku['Netflix'] plex = roku['Plex'] primevideo = roku['Prime Video'] try: while True: char = screen.getch() if char == ord('q'): break elif char == curses.KEY_RIGHT: roku.right() elif char == curses.KEY_LEFT: roku.left() elif char == curses.KEY_UP: roku.up() elif char == curses.KEY_DOWN: roku.down() elif char == curses.KEY_BACKSPACE:
def scan_devices(self): print(Roku.discover(timeout=30))
def main(): # Locate the roku device printing("Finding roku device ...") rokus = Roku.discover() printing("Done finding roku device ...") # IF no devices found ... if len(rokus) == 0: print("No rokus found") sys.exit(-1) # Otherwise, get the ip and port of the device else: roku_ip_address = rokus[0].host roku_port = rokus[0].port # Setup API object to make requests to the roku device print("Connecting ...") roku = Roku(host=roku_ip_address, port=roku_port) print("Done connecting ...") # Find youtube app print("Finding youtube app ...") youtube_app = [a for a in roku.apps if 'youtube' in a.name.lower()][0] print("Done finding youtube app ...") # Wait for the app to start print("Starting youtube app ...") APP_LAUNCH_TIMEOUT = 15 youtube_app.launch() time.sleep(APP_LAUNCH_TIMEOUT) print("Done starting youtube app ...") # Series of remote clicks to get to youtube Watch Later playlist # TODO: sleeps may not be needed roku.left() time.sleep(1) roku.left() time.sleep(1) roku.down() time.sleep(1) roku.down() time.sleep(1) roku.right() time.sleep(1) roku.down() time.sleep(1) roku.down() time.sleep(1) roku.right() time.sleep(1) roku.select()
def __init__(self, master, *args, **kwargs): super().__init__(master, *args, **kwargs) self.master = master settings = self.master.settings font = settings['font'] text = settings['colors']['text'] light = settings['colors']['light'] dark = settings['colors']['dark'] power = settings['colors']['power'] app = settings['colors']['app'] size = 20 flat = { 'relief': 'solid', 'bd': 1, 'activebackground': '#ffffff', 'activeforeground': '#ffffff' } font = {**flat, 'font': [font, size], 'fg': text, 'bg': dark} arrow = {**flat, 'font': [font, size], 'fg': text, 'bg': light} app = {**flat, 'font': [font, size], 'fg': text, 'bg': app} power = {**flat, 'font': [font, 30], 'fg': text, 'bg': power} def set_active_bg(f): f['activebackground'] = f['bg'] [set_active_bg(f) for f in [font, arrow, app, power]] self.roku = Roku('192.168.1.144') self.master.title('Roku Remote') self.pack(fill=tk.BOTH, expand=True) config_grids(self, rows=[1, 1, 1, 1, 1, 1], columns=[1, 1, 1, 1]) self.restart_flag = False self.back_button = tk.Button(self, **font, text=u'\u2B60', command=self.roku.back) self.back_button.grid(row=0, column=1, sticky='nsew') self.up_button = tk.Button(self, **arrow, text=u'\u2B9D', command=self.roku.up) self.up_button.grid(row=0, column=2, sticky='nsew') self.home_button = tk.Button(self, **font, text=u'\u2302', command=self.roku.home) self.home_button.grid(row=0, column=3, sticky='nsew') self.left_button = tk.Button(self, **arrow, text=u'\u2B9C', command=self.roku.left) self.left_button.grid(row=1, column=1, sticky='nsew') self.select_button = tk.Button(self, **arrow, text='OK', command=self.roku.select) self.select_button.grid(row=1, column=2, sticky='nsew') self.right_button = tk.Button(self, **arrow, text=u'\u2B9E', command=self.roku.right) self.right_button.grid(row=1, column=3, sticky='nsew') self.replay_button = tk.Button(self, **font, text=u'\u27F2', command=self.roku.replay) self.replay_button.grid(row=2, column=1, sticky='nsew') self.down_button = tk.Button(self, **arrow, text=u'\u2B9F', command=self.roku.down) self.down_button.grid(row=2, column=2, sticky='nsew') self.options_button = tk.Button(self, **font, text=u'\u273C', command=self.roku.info) self.options_button.grid(row=2, column=3, sticky='nsew') self.rewind_button = tk.Button(self, **font, text=u'\u23EA', command=self.roku.reverse) self.rewind_button.grid(row=3, column=1, sticky='nsew') self.pause_play_button = tk.Button(self, **font, text=u'\u25B6\u2758\u2758', command=self.roku.play) self.pause_play_button.grid(row=3, column=2, sticky='nsew') self.fast_forward_button = tk.Button(self, **font, text=u'\u23E9', command=self.roku.forward) self.fast_forward_button.grid(row=3, column=3, sticky='nsew') self.volume_mute_button = tk.Button(self, **font, text='MUTE', command=self.roku.volume_mute, width=20) self.volume_mute_button.grid(row=4, column=1, sticky='nsew') self.volume_down_button = tk.Button(self, **font, text='VOL-', command=self.roku.volume_down, width=20) self.volume_down_button.grid(row=4, column=2, sticky='nsew') self.volume_up_button = tk.Button(self, **font, text='VOL+', command=self.roku.volume_up, width=20) self.volume_up_button.grid(row=4, column=3, sticky='nsew') self.search_button = tk.Button(self, **font, text=u'\u2315', command=self.roku.search, width=20) self.search_button.grid(row=5, column=0, sticky='nsew') self.search_var = tk.StringVar() self.previous_text = '' self.search_var.trace('w', self.send_text) self.search_frame = tk.Frame(self, bg='#000000', bd=1) #self.search_frame.grid(row=5, column=1, columnspan=2, sticky='nsew') config_grids(self.search_frame) self.build_search_input() self.backspace_button = tk.Button(self, **font, text='DEL', command=self.roku.backspace) self.backspace_button.grid(row=5, column=3, sticky='nsew') self.power_button = tk.Button(self, **power, text=u'\u23FB', command=self.roku.power) self.power_button.grid(row=0, column=0, rowspan=2, sticky='nsew') self.computer_button = tk.Button( self, **app, text='PC', command=lambda: self.launch_app('computer')) self.computer_button.grid(row=2, column=0, sticky='nsew') self.plex_button = tk.Button(self, **app, text='PLEX', command=lambda: self.launch_app('plex')) self.plex_button.grid(row=3, column=0, sticky='nsew') self.ps4_button = tk.Button( self, **app, text='PS4', command=lambda: self.launch_app('playstation')) self.ps4_button.grid(row=4, column=0, sticky='nsew') self.menu_bar = Menubar(self) self.master.config(menu=self.menu_bar) self.bindings = [ ('<KeyPress>', self.key_press), ('<Left>', self.roku.left), ('<Right>', self.roku.right), ('<Up>', self.roku.up), ('<Down>', lambda *args: click_button(self.down_button)), ('<Return>', self.roku.select), ('-', self.roku.volume_down), ('+', self.roku.volume_up), ('=', self.roku.volume_up), ('<space>', self.roku.play), ('<BackSpace>', self.roku.back), ] self.bound = False self.master.bind('<FocusIn>', self.set_bindings) self.master.bind('<FocusOut>', self.set_bindings) self.master.geometry(get_geometry(settings))
def __init__(self, host): """Initialize the Roku device.""" self.roku = Roku(host) self._device_info = {}
from roku import Roku rokuls = Roku.discover(timeout=10) print(rokuls) ip = input('IP: ') roku = Roku(ip) while True: roku.down() roku.down() roku.down() roku.down() roku.up() roku.up() roku.left() roku.left() roku.right() roku.right() roku.right()
def roku_command(remote_command): delay = 1 #connect to roku #enter your rokus ip address to test roku = Roku('192.168.0.110') #remote command is place holder for list of commands from remote to dashboard #remote_command=['triangle'] #if circle shape is registered on remote than launch the most recent episode of a users favorite show. #In this case Silicon Valley. for i in remote_command: if i == 'circle': for light in lights: light.brightness = 254 light.xy = [.1, .1] hbo = roku["HBO GO"] hbo.launch() sleep(6 * delay) roku.down() sleep(delay) roku.right() sleep(delay) roku.right() sleep(delay) roku.select() sleep(3 * delay) roku.select() sleep(2 * delay) roku.select() sleep(delay) # roku.up() # sleep(delay) # roku.left() # sleep(delay) # roku.down() # sleep(delay) # roku.left() # sleep(delay) # roku.select() # sleep(2*delay) # roku.right() # sleep(delay) # roku.select() # sleep(2*delay) # roku.select() # sleep(2*delay) for light in lights: light.brightness = 100 if i == "left_swipe": #move cursor left roku.left() if i == "up_swipe": roku.up() if i == "down_swipe": roku.down() if i == "right_swipe": #move curser right roku.right() if i == "triangle": print "test" b.set_light([2, 3], 'on', True) # Prints if light 1 is on or not b.get_light(2, 'on') # Set brightness of lamp 1 to max b.set_light(2, 'bri', 254) # Set brightness of lamp 2 to 50% b.set_light(3, 'bri', 254) for light in lights: light.brightness = 254 light.xy = [.9, .7] #enter search commands roku.search() if i == "square": roku.info() if i == 'quad_diagonal_1': b.set_light(1, 'on', False) return True
class RokuDevice(MediaPlayerDevice): """Representation of a Roku device on the network.""" def __init__(self, host): """Initialize the Roku device.""" from roku import Roku self.roku = Roku(host) self.ip_address = host self.channels = [] self.current_app = None self._device_info = {} def update(self): """Retrieve latest state.""" try: self._device_info = self.roku.device_info self.ip_address = self.roku.host self.channels = self.get_source_list() if self.roku.current_app is not None: self.current_app = self.roku.current_app else: self.current_app = None except (requests.exceptions.ConnectionError, requests.exceptions.ReadTimeout): pass def get_source_list(self): """Get the list of applications to be used as sources.""" return ["Home"] + sorted(channel.name for channel in self.roku.apps) @property def should_poll(self): """Device should be polled.""" return True @property def name(self): """Return the name of the device.""" if self._device_info.userdevicename: return self._device_info.userdevicename return "Roku {}".format(self._device_info.sernum) @property def state(self): """Return the state of the device.""" if self.current_app is None: return STATE_UNKNOWN if (self.current_app.name == "Power Saver" or self.current_app.is_screensaver): return STATE_IDLE if self.current_app.name == "Roku": return STATE_HOME if self.current_app.name is not None: return STATE_PLAYING return STATE_UNKNOWN @property def supported_features(self): """Flag media player features that are supported.""" return SUPPORT_ROKU @property def unique_id(self): """Return a unique, HASS-friendly identifier for this entity.""" return self._device_info.sernum @property def media_content_type(self): """Content type of current playing media.""" if self.current_app is None: return None if self.current_app.name == "Power Saver": return None if self.current_app.name == "Roku": return None return MEDIA_TYPE_MOVIE @property def media_image_url(self): """Image url of current playing media.""" if self.current_app is None: return None if self.current_app.name == "Roku": return None if self.current_app.name == "Power Saver": return None if self.current_app.id is None: return None return 'http://{0}:{1}/query/icon/{2}'.format(self.ip_address, DEFAULT_PORT, self.current_app.id) @property def app_name(self): """Name of the current running app.""" if self.current_app is not None: return self.current_app.name @property def app_id(self): """Return the ID of the current running app.""" if self.current_app is not None: return self.current_app.id @property def source(self): """Return the current input source.""" if self.current_app is not None: return self.current_app.name @property def source_list(self): """List of available input sources.""" return self.channels def media_play_pause(self): """Send play/pause command.""" if self.current_app is not None: self.roku.play() def media_previous_track(self): """Send previous track command.""" if self.current_app is not None: self.roku.reverse() def media_next_track(self): """Send next track command.""" if self.current_app is not None: self.roku.forward() def mute_volume(self, mute): """Mute the volume.""" if self.current_app is not None: self.roku.volume_mute() def volume_up(self): """Volume up media player.""" if self.current_app is not None: self.roku.volume_up() def volume_down(self): """Volume down media player.""" if self.current_app is not None: self.roku.volume_down() def select_source(self, source): """Select input source.""" if self.current_app is not None: if source == "Home": self.roku.home() else: channel = self.roku[source] channel.launch()
result = channel.launch() return result def volumemute(): result=roku.volumemute() return result actions = {"back" : back, "backspace" : backspace, "down" : down, "enter" : enter, "forward" : forward, "home" : home, "info" : info, "left" : left, "literal" : literal, "play" : play, "replay" : replay, "reverse" : reverse, "right" : right, "search" : search, "select" : select, "up" : up, "volumeup" : volumeup, "volumedown" : volumedown, "volumemute" : volumemute, "channel" : channel } roku = Roku(sys.argv[1]) actions[sys.argv[2]]()
class RokuDevice(MediaPlayerDevice): """Representation of a Roku device on the network.""" def __init__(self, host): """Initialize the Roku device.""" from roku import Roku self.roku = Roku(host) self.ip_address = host self.channels = [] self.current_app = None self._device_info = {} self.update() def update(self): """Retrieve latest state.""" import requests.exceptions try: self._device_info = self.roku.device_info self.ip_address = self.roku.host self.channels = self.get_source_list() if self.roku.current_app is not None: self.current_app = self.roku.current_app else: self.current_app = None except (requests.exceptions.ConnectionError, requests.exceptions.ReadTimeout): pass def get_source_list(self): """Get the list of applications to be used as sources.""" return ["Home"] + sorted(channel.name for channel in self.roku.apps) @property def should_poll(self): """Device should be polled.""" return True @property def name(self): """Return the name of the device.""" if self._device_info.userdevicename: return self._device_info.userdevicename return "Roku {}".format(self._device_info.sernum) @property def state(self): """Return the state of the device.""" if self.current_app is None: return STATE_UNKNOWN if (self.current_app.name == "Power Saver" or self.current_app.is_screensaver): return STATE_IDLE if self.current_app.name == "Roku": return STATE_HOME if self.current_app.name is not None: return STATE_PLAYING return STATE_UNKNOWN @property def supported_features(self): """Flag media player features that are supported.""" return SUPPORT_ROKU @property def unique_id(self): """Return a unique, HASS-friendly identifier for this entity.""" return self._device_info.sernum @property def media_content_type(self): """Content type of current playing media.""" if self.current_app is None: return None if self.current_app.name == "Power Saver": return None if self.current_app.name == "Roku": return None return MEDIA_TYPE_MOVIE @property def media_image_url(self): """Image url of current playing media.""" if self.current_app is None: return None if self.current_app.name == "Roku": return None if self.current_app.name == "Power Saver": return None if self.current_app.id is None: return None return 'http://{0}:{1}/query/icon/{2}'.format( self.ip_address, DEFAULT_PORT, self.current_app.id) @property def app_name(self): """Name of the current running app.""" if self.current_app is not None: return self.current_app.name @property def app_id(self): """Return the ID of the current running app.""" if self.current_app is not None: return self.current_app.id @property def source(self): """Return the current input source.""" if self.current_app is not None: return self.current_app.name @property def source_list(self): """List of available input sources.""" return self.channels def media_play_pause(self): """Send play/pause command.""" if self.current_app is not None: self.roku.play() def media_previous_track(self): """Send previous track command.""" if self.current_app is not None: self.roku.reverse() def media_next_track(self): """Send next track command.""" if self.current_app is not None: self.roku.forward() def mute_volume(self, mute): """Mute the volume.""" if self.current_app is not None: self.roku.volume_mute() def volume_up(self): """Volume up media player.""" if self.current_app is not None: self.roku.volume_up() def volume_down(self): """Volume down media player.""" if self.current_app is not None: self.roku.volume_down() def select_source(self, source): """Select input source.""" if self.current_app is not None: if source == "Home": self.roku.home() else: channel = self.roku[source] channel.launch()
#!/usr/bin/env python ''' Roku remote application ''' from Tkinter import * from roku import Roku from PIL import ImageTk from PIL import Image # place the Roku's IP address here roku = Roku('192.168.1.1') class Application(Frame): def home(self): roku.home() def right(self): roku.right() def left(self): roku.left() def up(self): roku.up() def down(self): roku.down() def back(self): roku.back()