Пример #1
0
def television(args):

    command = args.get("command")

    command = parseCommand(command)

    multiplier = 0
    if ("UP" in command) or ("DOWN" in command) or ("RIGHT" in command) or (
            "LEFT" in command):
        multString = re.search('(\d+)$', command)
        if (multString is not None):
            multString = multString.group(0)
            multiplier = int(multString)
            command = command.replace(multString, "")
            print(multiplier)

    command = decodeCommand(command)

    if lib.is_number(command):
        for i in range(0, len(command)):
            samsungctl.Remote(config.tvconfig).control("KEY_" + command[i])
            print("KEY_" + command[i])
    else:
        if (multiplier > 0):
            for i in range(0, multiplier):
                samsungctl.Remote(config.tvconfig).control(command)
                print(command)
        else:
            samsungctl.Remote(config.tvconfig).control(command)
            print(command)

    return "TV Control OK"
Пример #2
0
def channel(client, userdata, message):
    printmsg(message)
    payload = json.loads(message.payload.decode('utf-8'))
    remote_config = get_config(payload['endpointid'])

    try:
        if payload['operation'] == 'ChangeChannel':
            if 'number' in payload['channel_data']['channel']:
                with samsungctl.Remote(remote_config) as remote:
                    for c in payload['channel_data']['channel']['number']:
                        remote.control("KEY_" + str(c))
                        time.sleep(0.05)
                    remote.control("KEY_ENTER")

            else:
                channel_name = ''
                if 'callSign' in payload['channel_data']['channel']:
                    channel_name = payload['channel_data']['channel'][
                        'callSign']
                elif 'affiliateCallSign' in payload['channel_data']['channel']:
                    channel_name = payload['channel_data']['channel'][
                        'affiliateCallSign']
                elif 'channelMetadata' in payload[
                        'channel_data'] and 'name' in payload['channel_data'][
                            'channelMetadata']:
                    channel_name = payload['channel_data']['channelMetadata'][
                        'name']

                with samsungctl.Remote(remote_config) as remote:
                    res = get_close_matches(
                        channel_name.lower().replace('&', 'and').replace(
                            'the ', '').replace(' channel', ''), tv_channels)
                    if len(res) > 0:
                        chan = tv_listings_dict[res[0]]
                        num = ""
                        if chan[3] != None and tv_dict[
                                payload['endpointid']]['prefer_HD']:
                            num = str(chan[3])
                        else:
                            num = str(chan[2])
                        print(channel_name + ':   closest match - ' + res[0] +
                              '     -  ' + str(num))
                        for c in num:
                            remote.control("KEY_" + str(c))
                            time.sleep(0.05)
                        remote.control("KEY_ENTER")

        elif payload['operation'] == 'SkipChannels':
            steps = payload['channelCount']
            chandown = steps < 0
            steps = abs(steps)

            for i in range(0, steps):
                with samsungctl.Remote(remote_config) as remote:
                    remote.control("KEY_CHDOWN" if chandown else "KEY_CHUP")
                    time.sleep(0.05)  #delay for volume
    except:
        print("Failed to send message to TV")
Пример #3
0
def playback(client, userdata, message):
    printmsg(message)
    payload = json.loads(message.payload.decode('utf-8'))
    remote_config = get_config(payload['endpointid'])

    try:
        if payload['operation'] == 'Pause' or payload['operation'] == 'Stop':
            with samsungctl.Remote(remote_config) as remote:
                remote.control("KEY_PAUSE")
        elif payload['operation'] == 'Play':
            with samsungctl.Remote(remote_config) as remote:
                remote.control("KEY_PLAY")
    except:
        print("Failed to send message to TV")
Пример #4
0
def rewind_little_on():
    with samsungctl.Remote(config) as remote:
        remote.control((keys['enter key']))
        time.sleep(0.5)
        for i in range(5):
            remote.control((keys['left key']))
            time.sleep(0.5)
Пример #5
0
def forward_plenty_on():
    with samsungctl.Remote(config) as remote:
        remote.control((keys['enter key']))
        time.sleep(0.5)
        for i in range(25):
            remote.control((keys['right key']))
            time.sleep(0.5)
Пример #6
0
    def __init__(self, sensorId, sensorName, configPath):
        super().__init__(sensorId, sensorName)
        self.sensorType = "TV"
        self.sensorMetadata = {"bidirectional": False}

        config = samsungctl.Config.load(configPath)
        self.remote = samsungctl.Remote(config)
Пример #7
0
def netflix_on():
    with samsungctl.Remote(config) as remote:
        remote.control((keys['return key']))
        time.sleep(2)
        remote.control((keys['return key']))
        remote.control((keys['smart hub key']))
        time.sleep(10)
        remote.control((keys['enter key']))
Пример #8
0
def change_channel(channel):
    with samsungctl.Remote(config_remote) as remote:
        for digit in channel:
            print "working on", digit
            remote.control("KEY_" + digit)
            time.sleep(0.5)
        remote.control("KEY_ENTER")
        print "The channel was changed to", channel
Пример #9
0
def _tv_remote_action(arg):
    if arg in _remote_key_codes:
        key_code = _remote_key_codes[arg]

        with samsungctl.Remote(config.SAMSUNG) as remote:
            remote.control(key_code)
    else:
        log.e(f"TV: parameter does not exist: {arg}")
Пример #10
0
def power(client, userdata, message):
    printmsg(message)
    payload = json.loads(message.payload.decode('utf-8'))
    remote_config = get_config(payload['endpointid'])
    try:
        if payload['operation'] == 'TurnOn':
            send_magic_packet(payload['endpointid'])
            time.sleep(3)
            with samsungctl.Remote(remote_config) as remote:
                remote.control(
                    "KEY_RETURN"
                )  #get rid of the on menu when you turn the tv on
        elif payload['operation'] == 'TurnOff':
            with samsungctl.Remote(remote_config) as remote:
                remote.control("KEY_POWER")
    except:
        print("Failed to send message to TV")
Пример #11
0
def request_configuration(samsung_config, uuid, hass, add_entities):
    """Request configuration steps from the user."""
    host = samsung_config.host
    name = samsung_config.name

    configurator = hass.components.configurator

    import samsungctl
    event = threading.Event()
    pin = []
    count = 0

    def get_pin():
        global count

        def samsung_configuration_callback(data):
            """Handle the entry of user PIN."""
            pin.append(data.get('pin'))
            event.set()

        if count == 3:
            _LOGGER.error(name + " TV: Pin entry failed")
            return False

        if host in _CONFIGURING:
            count += 1
            configurator.notify_errors(
                _CONFIGURING[host], "Failed to register, please try again.")
            del pin[:]
            event.clear()
        else:
            _CONFIGURING[host] = configurator.request_config(
                name,
                samsung_configuration_callback,
                description='Enter the Pin shown on your Samsung TV.',
                description_image="/static/images/smart-tv.png",
                submit_caption="Confirm",
                fields=[{
                    'id': 'pin',
                    'name': 'Enter the pin',
                    'type': ''
                }])

        event.wait(30)

        if not event.isSet():
            count += 1
            return None

        return pin[0]

    samsung_config.get_pin = get_pin
    try:
        remote = samsungctl.Remote(samsung_config)
        remote.open()
        add_entities([SamsungTVDevice(samsung_config, uuid)])
    except:
        return
Пример #12
0
def speakers_on():
    config = samsungctl.Config.load('/home/pi/speakers_on/samsung.conf')(
        name='samsungctl')

    with samsungctl.Remote(config) as remote:
        for key in keys:
            for i in range(key[1]):
                send_key(remote, key[0], key[2])

    return "on"
Пример #13
0
 def send_keycode(self, keycode):
     '''Standard function for sending keycodes'''
     keycode = "KEY_" + keycode.upper()
     try:
         with samsungctl.Remote(self.config) as remote:
             remote.control(keycode)
     except Exception as e:
         LOGGER.info(str(e))
     finally:
         pass
Пример #14
0
 def write(self, addr, value):
     debug('debugSamsung', self.name, "write", addr, value)
     try:
         if value == 0:
             value = "off"
         keyCmd = keyCmds[value.lower()]
         config["host"] = addr
         samsungctl.Remote(config).control(keyCmd)
     except KeyError:
         log(self.name, addr, "unknown command", value)
Пример #15
0
    def do():
        global count

        try:
            _ = samsungctl.Remote(samsung_config)
            add_entities([SamsungTVDevice(samsung_config)])
        except:
            pass

        hass.components.configurator.request_done(_CONFIGURING.pop(uuid))
Пример #16
0
def press_remote_key(key_pressed):
    Remote = samsungctl.Remote(remoteConfig)
    k = key_pressed.lower()
    if re.match('channel (\d+)', k):
        n = int(re.match('channel (\d+)', 'channel 5').groups()[0])
        k_code = 'KEY_%d' % (n)
    else:
        k_code = RemoteKeyMap[k]

    return Remote.control(k_code)
Пример #17
0
def move(*args):
    with samsungctl.Remote(config) as remote:
        c_row = 0
        c_col = 0
        print(f"começando na linha {c_row}, e na coluna  {c_col} ")
        for tuples in args:
            for item in tuples:
                t_row = item[0]
                t_col = item[1]
                print(
                    f"e tenho que ir para a linha  {t_row}, e  coluna  {t_col} "
                )
                coordinate_row = c_row - t_row
                coordinate_col = c_col - t_col
                print(
                    f" para isso tenho que andar  {coordinate_row} linhas e {coordinate_col}  colunas"
                )
                i = 0
                print(
                    f" descobrindo se vou para cima, para baixo ou se fico...")
                while i < abs(coordinate_row):
                    if coordinate_row < 0:
                        print(f" andando uma casa  para baixo...")
                        remote.control((keys['down key']))
                        time.sleep(0.5)
                        i += 1
                    elif coordinate_row > 0:
                        remote.control((keys['up key']))
                        print(f" andando uma casa para cima...")
                        time.sleep(0.5)
                        i += 1
                    else:
                        print(
                            "ja estou na linha certa vamos para a coluna certa agora..."
                        )
                        i += 1
                i = 0
                print(f" descobrindo se vou para direita ou para esquerda...")
                while i < abs(coordinate_col):
                    if coordinate_col < 0:
                        print(f" andando uma casa para direita...")
                        remote.control((keys['right key']))
                        time.sleep(0.5)
                        i += 1
                    elif coordinate_col > 0:
                        print(f" andando uma casa para esquerda...")
                        remote.control((keys['left key']))
                        time.sleep(0.5)
                        i += 1
                print("não preciso mais mudar de coluna, apertando enter...")
                c_row = t_row
                c_col = t_col
                print(f"agora estou na linha {c_row} e coluna {c_col} ")
                i += 1
                remote.control((keys['enter key']))
Пример #18
0
def tv(keyCode):
    print(f'requesting {keyCode}')
    keyCode = keyCode.upper()
    if keyCode not in validCodes:
        abort(404)

    with samsungctl.Remote(config) as remote:
        remote.control(keyCode)

    print(f'Pressed {keyCode}')
    return jsonify({'keyCode': keyCode, 'status': 'ok'})
Пример #19
0
def send(config, key, wait_time=100.0):
    try:
        with samsungctl.Remote(config) as remote:
            remote.control(key)

        time.sleep(wait_time / 1000.0)
        return True

    except socket.error:
        return False
    except websocket._exceptions.WebSocketConnectionClosedException:
        logging.error('Websocket error! Maybe try sending with legacy (-l)?')
        return False
Пример #20
0
def speaker(client, userdata, message):
    printmsg(message)
    payload = json.loads(message.payload.decode('utf-8'))
    remote_config = get_config(payload['endpointid'])

    try:
        if payload['operation'] == 'SetMute':
            with samsungctl.Remote(remote_config) as remote:
                remote.control("KEY_MUTE")
        elif payload['operation'] == 'AdjustVolume':
            steps = payload['volumeSteps']
            voldown = steps < 0
            steps = abs(steps)

            if steps == 1:
                steps = tvconfig.volume_step_size

            with samsungctl.Remote(remote_config) as remote:
                for i in range(0, steps):
                    remote.control("KEY_VOLDOWN" if voldown else "KEY_VOLUP")
                    time.sleep(0.05)  #delay for volume
    except:
        print("Failed to send message to TV")
Пример #21
0
    def samsung_configuration_callback(data):
        """Handle the entry of user PIN."""
        global count
        pin[0] = data.get('pin')

        try:
            _ = samsungctl.Remote(samsung_config)
            add_entities([SamsungTVDevice(samsung_config)])
        except:
            if samsung_config.uuid in _CONFIGURING:
                count += 1
                configurator.notify_errors(
                    _CONFIGURING[samsung_config.uuid],
                    "Failed to register, please try again.")
Пример #22
0
    def do(self, params):
        config = {
            "name": "melon",
            "description": "Melon",
            "id": "melon",
            "host": params['host'],
            "port": (params['port'] if 'port' in params else 55000),
            "method": (params['method'] if 'method' in params else "legacy"),
            "timeout": 10,
        }

        with samsungctl.Remote(config) as remote:
            remote.control(params['key'])
            time.sleep(0.5)
Пример #23
0
    def send(self, device, args):
        if device['type'] == 'samsung_tv':
            config = {
                "name": "samsungctl",
                "description": "PC",
                "id": "",
                "host": "",
                "port": 8001,
                "method": "websocket",
                "timeout": 0,
            }

            config['host'] = device['address']
            with samsungctl.Remote(config) as remote:
                remote.control(args['key'])
Пример #24
0
    def __sendCommand(self, command):
        try:
            print(self.config)
            with samsungctl.Remote(self.config) as remote:
                for key in command:
                    remote.control(key)

        except exceptions.ConnectionClosed:
            print("Error: Connection closed!")
        except exceptions.AccessDenied:
            print("Error: Access denied!")
        except exceptions.UnknownMethod:
            print("Error: Unknown method '{}'".format(self.config["method"]))
        except socket.timeout:
            print("Error: Timed out!")
        except OSError as e:
            print("Error: %s", e.strerror)
Пример #25
0
    def init_device(self):
        now = time.time()

        if self.remote is None or now - self.last_init >= 60:
            try:
                self.last_init = now
                self.destroy_device()
                if self.config is None:
                    cc = samsungctl.Config.load(self.conffile)
                    cc.log_level = samsungctl.Config.LOG_DEBUG
                    self.config = cc
                self.remote = samsungctl.Remote(self.config)
                if not self.remote.open():
                    self.destroy_device()
            except:  # noqa: E722
                _LOGGER.warning(f"{traceback.format_exc()}")
                self.destroy_device()

        return self.remote
Пример #26
0
def zap_left():
    with samsungctl.Remote(config) as remote:
        for i in range(180):
            time.sleep(2)
            remote.control((keys['left key']))
Пример #27
0
#!/usr/bin/env python3

import samsungctl
import time

config = {
    "name": "samsungctl",
    "description": "PC",
    "id": "",
    "host": "192.168.0.10",
    "port": 55000,
    "method": "legacy",
    "timeout": 0,
}

with samsungctl.Remote(config) as remote:
    for i in range(10):
        remote.control("KEY_MENU")
        time.sleep(0.5)  #!/usr/bin/env python3
'''
KEY_POWEROFF	Power off
KEY_UP	Up
KEY_DOWN	Down
KEY_LEFT	Left
KEY_RIGHT	Right
KEY_CHUP	P Up
KEY_CHDOWN	P Down
KEY_ENTER	Enter
KEY_RETURN	Return
KEY_CH_LIST	Channel List
KEY_MENU	Menu
Пример #28
0
def turn_off():
    with samsungctl.Remote(config) as remote:
        remote.control((keys['poweroff key']))
Пример #29
0
def turn_off_tv():
    with samsungctl.Remote(config_remote) as remote:
        print "The TV is shutting down"
        remote.control("KEY_POWER")
Пример #30
0
def get_out():
    with samsungctl.Remote(config) as remote:
        remote.control((keys['return key']))