def __init__(self): """Client key will be displayed on the TV when you accept the connection for the first time. Store the dict value as an env variable and use it as below. Using TV's ip makes the initial response much quicker but it looks for the TVs in ip range if an ip is not found.""" store = {'client_key': client_key} try: self.client = WebOSClient(ip_address) self.client.connect() except gaierror: sys.stdout.write( f"\rThe TV's IP has either changed or unreachable. Scanning your IP range.." ) self.client = WebOSClient.discover()[0] self.client.connect() except (TimeoutError, BrokenPipeError): sys.stdout.write( '\rOperation timed out. The TV might be turned off.') for status in self.client.register(store): if status == WebOSClient.REGISTERED and not TV._init_status: sys.stdout.write('\rConnected to the TV.') elif status == WebOSClient.PROMPTED: sys.stdout.write( '\rPlease accept the connection request on your TV.') # sys.stdout.write(f'\r{store}') # get the client key dict during the first run and store as in line #18 self.system = SystemControl(self.client) self.system.notify("Jarvis is controlling the TV now." ) if not TV._init_status else None self.media = MediaControl(self.client) self.app = ApplicationControl(self.client) self.source_control = SourceControl(self.client) TV._init_status = True
def __init__(self): webos_store = {'auth': {}} try: webos_store = pickle.load(open("webos.auth", "rb")) except: print("Cant load webos auth, registering new one.") pass if not 'host' in webos_store: print("Searching tv...") webos_client = WebOSClient.discover()[0] else: print("Connecting to tv at {}".format(webos_store['host'])) webos_client = WebOSClient(webos_store['host']) webos_client.connect() for status in webos_client.register(webos_store['auth']): if status == WebOSClient.PROMPTED: print("Please accept the connect on the TV!") elif status == WebOSClient.REGISTERED: print("Webos connection successful!") webos_store['host'] = webos_client.host pickle.dump(webos_store, open("webos.auth", "wb")) self.webos_system = SystemControl(webos_client) self.webos_media = MediaControl(webos_client) self.webos_inp = InputControl(webos_client) self.webos_inp.connect_input() self.notify("Skipper connected")
def _discover(self) -> Tuple[Dict[str, HostType], List[HostType]]: """ Discover devices connected to the network, both existing and new. These are then separated, based on whether they exist in the user config, and returned :return: A dict of existing host IP addresses (indexed by their name) and a list of new hosts. """ clients = WebOSClient.discover() discovered_hosts = [c.host for c in clients] return self._separate_new_hosts(discovered_hosts)
def test_discovery(self): def mock_discover(*args, **kwargs): return ["host1", "host2"] backup = pywebostv.connection.discover pywebostv.connection.discover = mock_discover expected = ["ws://{}:3000/".format(x) for x in ["host1", "host2"]] assert [x.url for x in WebOSClient.discover()] == expected pywebostv.connection.discover = backup
def discover(self): """ Discover existing smart TV on the LAN and create config file """ try: while True: print(".", end="") a = WebOSClient.discover() if a: for res in a: print(f"\n{res.host} found") break except KeyboardInterrupt: print("\nLong enough..")
def scan(self): new_clients = {} for client in WebOSClient.discover(): logger.info("Found an LG Web OS TV at: %s", client.url) mac = get_mac_address(client.host) if mac not in self.discovered_clients: webos_tv = WebOSTV(self.service, mac, client) new_clients[mac] = webos_tv webos_tv.start() for key in set(self.discovered_clients.keys()) - set(new_clients): self.discovered_clients.pop(key) self.discovered_clients.update(new_clients)
def main(): parser = ArgumentParser(description='LG WebOS CLI wrapper', formatter_class=RawTextHelpFormatter) parser.add_argument('method', type=str, help=format_controls_help(controls_subsystems)) parser.add_argument('method_args', metavar='arguments', nargs='*', help='Method arguments ([arg])') args = parser.parse_args(None if sys.argv[1:] else ['-h']) if args.method == 'power_on': # TODO figure out how to enumerate network interfaces and find broadcast ip addr (netifaces?) send_magic_packet(ConnectionCache.read_mac(), ip_address='192.168.15.255') sys.exit() addr = ConnectionCache.read_addr() if not addr: clients = { str(index): client for index, client in enumerate(WebOSClient.discover(), 1) } entered = None while entered is None or entered not in clients.keys(): entered = input('\n'.join([ *[') '.join([i, c.host]) for i, c in clients.items()], '(q to quit)\n', ])) if entered == 'q': sys.exit() client = clients.get(entered) else: client = WebOSClient(addr) client.connect() store = CredStorage.load(client.host) for status in client.register(store): if status == WebOSClient.PROMPTED: print('Please accept the connection on the TV') ConnectionCache.write(client) if status == WebOSClient.REGISTERED: CredStorage.persist(client.host, store) if args.method not in controls: parser.print_help() sys.exit() stdout.write(str(call(client, args.method, args.method_args)))
def init(wakeup=True): if not os.path.exists(STORE): store = {} else: with open(STORE) as fh: store = json.load(fh) if "ipaddr" in store: client = WebOSClient(store["ipaddr"]) else: clients = WebOSClient.discover() client = clients[0] try: client.connect() except OSError: if wakeup and "macaddr" in store: print("Starting TV") send_magic_packet(store["macaddr"]) time.sleep(10) return init(False) print("TV is off", file=sys.stderr) sys.exit(1) for status in client.register(store): if status == WebOSClient.PROMPTED: print("Please accept the connect on the TV!") elif status == WebOSClient.REGISTERED: pass store["ipaddr"] = client.host macaddr = get_macaddr(store["ipaddr"]) if macaddr: store["macaddr"] = macaddr with open(STORE, "w") as out: json.dump(store, out) return client
def conn_attempt(): global board, connection_status, tvClient, tvInputControl, tvMediaControl print('Attempting to connect') connection_status = 1 board.led.state = Led.PULSE_QUICK board.button._pressed_callback = None client_list = WebOSClient.discover() if len(client_list) != 1: play_wav('errorsound.wav') print('connection failed: more than 1 tv found') connection_status = 0 board.led.state = Led.OFF return tvClient = client_list[0] try: tvClient.connect() for status in tvClient.register(store): if status == WebOSClient.PROMPTED: play_wav('ding.wav') print('See TV prompt and press yes') elif status == WebOSClient.REGISTERED: play_wav('ding.wav') print('Successful connection') board.led.state = Led.ON connection_status = 2 tvInputControl = InputControl(tvClient) tvInputControl.connect_input() tvMediaControl = MediaControl(tvClient) except Exception: play_wav('errorsound.wav') print('connection failed: you probably pressed no on the prompt') connection_status = 0 board.led.state = Led.OFF return
def discover(self): devices = WebOSClient.discover() for device in devices: print(device.host)