Send a key command to the TV.
189150
def send_key(self, key):
        """"""
        if isinstance(key, Keys):
            key = key.value
        params = '<X_KeyEvent>{}</X_KeyEvent>'.format(key)
        self.soap_request(URL_CONTROL_NRC, URN_REMOTE_CONTROL,
                          'X_SendKey', params)
1072541
def send_keyevents(self, keyevent: int) -> None:
        ''''''
        self._execute('-s', self.device_sn, 'shell',
                      'input', 'keyevent', str(keyevent))
1320282
def __send_command(self, command, args=[]):
        ''''''
        self.ws.send(json.dumps({"op": command, "args": args}))
737704
function send_command(command, cb) {
        var cmd = commands[command.toUpperCase()];
        if(parseInt(cmd)) {
            post('/roap/api/command', `<?xml version='1.0' encoding='utf-8'?><command><name>HandleKeyInput</name><value>${cmd}</value></command>`, (body) => {
                try {
                    var doc = new dom().parseFromString(body);
                    if(cb) cb(xpath.select('//ROAPErrorDetail/text()', doc).toString() == 'OK')
                } catch(error) {
                    log(`error send_command:  ${error.message}`)
                    if(cb) cb(false)
                }
            });
        }
    }
226088
def onKeyInCommandEntry(self, event):
        ''''''
        if event.char == '\r':
            self.onSendCommand()
            self.canvas.focus_set()
655963
def key_press(keys):
        """"""
        return lambda e: e.key if e.type == pygame.KEYDOWN \
            and e.key in keys else EventConsumerInfo.DONT_CARE
619069
def send_command(command)
      SerialPort.open(self.device_path, 9600, 8, 1) do |port|
        # flush anything existing on the port
        port.flush
        flush_read_buffer(port)

        byte_string = command.to_bytes.pack('C*')

        begin
          while byte_string && byte_string.length != 0
            count = port.write_nonblock(byte_string)
            byte_string = byte_string[count,-1]

            port.flush
          end
        rescue IO::WaitWritable
          if IO.select([], [port], [], 5)
            retry
          else
            raise IOError, "Timeout writing command to #{self.device_path}"
          end
        end

        # wait for expected confirmation signals
        got_eot = false
        got_soh = false
        loop do
          begin
            c = port.read_nonblock(1)

            case c
              when "\x04"
                if ! got_eot
                  got_eot = true
                else
                  raise IOError, "Got EOT reply twice from #{self.device_path}"
                end
              when "\x01"
                if got_eot
                  if ! got_soh
                    got_soh = true

                    break
                  else
                    raise IOError, "Got SOH twice from #{self.device_path}"
                  end
                else
                  raise IOError, "Got SOH before EOT from #{self.device_path}"
                end
            end
          rescue IO::WaitReadable
            if IO.select([port], [], [], 3)
              retry
            else
              raise IOError, "Timeout waiting for command reply from #{self.device_path}.  EOT:#{got_eot} SOH:#{got_soh}"
            end
          end
        end
      end

      self
    end
727427
async def cli_handler(loop):
    """"""
    parser = argparse.ArgumentParser()

    parser.add_argument('command', nargs='+',
                        help='commands, help, ...')
    parser.add_argument('--name', help='apple tv name',
                        dest='name', default='Apple TV')
    parser.add_argument('--address', help='device ip address or hostname',
                        dest='address', default=None)
    parser.add_argument('--protocol', action=TransformProtocol,
                        help='protocol to use (values: dmap, mrp)',
                        dest='protocol', default=None)
    parser.add_argument('--port', help='port when connecting',
                        dest='port', type=_in_range(0, 65535),
                        default=0)
    parser.add_argument('-t', '--scan-timeout', help='timeout when scanning',
                        dest='scan_timeout', type=_in_range(1, 100),
                        metavar='TIMEOUT', default=3)
    parser.add_argument('--version', action='version',
                        help='version of atvremote and pyatv',
                        version='%(prog)s {0}'.format(const.__version__))

    pairing = parser.add_argument_group('pairing')
    pairing.add_argument('--remote-name', help='remote pairing name',
                         dest='remote_name', default='pyatv')
    pairing.add_argument('-p', '--pin', help='pairing pin code',
                         dest='pin_code', metavar='PIN', default=1234,
                         type=_in_range(0, 9999, allow_none=True))
    pairing.add_argument('--pairing-guid',
                         help='pairing guid (16 chars hex)',
                         dest='pairing_guid', default=None)

    parser.add_argument('-a', '--autodiscover', action='store_true',
                        help='automatically find a device',
                        dest='autodiscover', default=False)
    parser.add_argument('--device_credentials', help='credentials to device',
                        dest='device_credentials', default=None)

    airplay = parser.add_argument_group('airplay')
    airplay.add_argument('--airplay_credentials',
                         help='credentials for airplay',
                         dest='airplay_credentials', default=None)

    debug = parser.add_argument_group('debugging')
    debug.add_argument('-v', '--verbose', help='increase output verbosity',
                       action='store_true', dest='verbose')
    debug.add_argument('--debug', help='print debug information',
                       action='store_true', dest='debug')

    args = parser.parse_args()
    loglevel = logging.WARNING
    if args.verbose:
        loglevel = logging.INFO
    if args.debug:
        loglevel = logging.DEBUG

    logging.basicConfig(level=loglevel,
                        format='%(levelname)s: %(message)s')
    logging.getLogger('requests').setLevel(logging.WARNING)

    cmds = retrieve_commands(GlobalCommands)

    if args.command[0] in cmds:
        glob_cmds = GlobalCommands(args, loop)
        return (await _exec_command(
            glob_cmds, args.command[0], print_result=False))
    if args.autodiscover:
        if not await _autodiscover_device(args, loop):
            return 1

        return await _handle_commands(args, loop)
    if args.address:
        return await _handle_commands(args, loop)

    logging.error('To autodiscover an Apple TV, add -a')

    return 1
221986
function (self, cmd, channel, data, cb) {
		if (typeof(cb) != "function") {
			cb = false;
		}

		if (typeof(channel) == "number") {
			channel = channel.toString();
		}

		if (typeof(channel) != "string" || !/[0-9]+-[0-9]+/.test(channel)) {
			self.log("Invalid channel");
			return cb && cb(new Error("Invalid channel"));
		}

		if (typeof(data) != "string") {
			data = self.datObJectToXml(data);
		}

		if (typeof(data) != "string") {
			self.log("Invalid data");
			return cb && cb(new Error("Invalid data"));
		}

		self.sendCommand("CG " + channel + " " + cmd + " 1 \"" + data + "\"", cb);
	}
1290605
def _send_command(self, command):
        
        if self.status is None or self.status.media_session_id is None:
            self.logger.warning(
                "%s command requested but no session is active.",
                command[MESSAGE_TYPE])
            return

        command['mediaSessionId'] = self.status.media_session_id

        self.send_message(command, inc_session_id=True)
884884
def KeyPress(self, key, n=1, delay=0):
        
        self._delay(delay)
        cmd = Command("KeyPress", 'KeyPress "%s", %s' % (key, n))
        self.add(cmd)
1085270
def command(self, command, raw=False, timeout_ms=None):
    """"""
    return ''.join(self.streaming_command(command, raw, timeout_ms))
1366781
def send(self, cmd, timeout, wait_for_string, password):
        """"""
        return self.target_device.send(cmd, timeout=timeout, wait_for_string=wait_for_string, password=password)
634989
def send_keysequence_window_up(self, window, keysequence, delay=12000):
        """"""
        _libxdo.xdo_send_keysequence_window_up(
            self._xdo, window, keysequence, ctypes.c_ulong(delay))
250505
async def help(self):
        """"""
        if len(self.args.command) != 2:
            print('Which command do you want help with?', file=sys.stderr)
            return 1

        iface = [interface.RemoteControl,
                 interface.Metadata,
                 interface.Playing,
                 interface.AirPlay,
                 self.__class__,
                 DeviceCommands]
        for cmd in iface:
            for key, value in cmd.__dict__.items():
                if key.startswith('_') or key != self.args.command[1]:
                    continue

                if inspect.isfunction(value):
                    signature = inspect.signature(value)
                else:
                    signature = ' (property)'

                print('COMMAND:\n>> {0}{1}\n\nHELP:\n{2}'.format(
                    key, signature, inspect.getdoc(value)))
        return 0
921137
def send_command(self, *args, **kwargs):
        
        if len(args) >= 1:
            command_string = args[0]
        else:
            command_string = kwargs["command_string"]

        # If changeto in command, look for '#' to determine command is done
        if "changeto" in command_string:
            if len(args) <= 1:
                expect_string = kwargs.get("expect_string", "#")
                kwargs["expect_string"] = expect_string
        output = super(CiscoAsaSSH, self).send_command(*args, **kwargs)

        if "changeto" in command_string:
            self.set_base_prompt()

        return output
605920
def send(cfg, **kwargs):
    """"""
    for name, value in kwargs.items():
        setattr(cfg, name, value)
    with cfg.timing.add("import", which="cmd_send"):
        from . import cmd_send

    return go(cmd_send.send, cfg)