Wrapper to send posted scene command and get response
335848
def scene_command(self, command):
        """"""
        self.logger.info("scene_command: Group %s Command %s", self.group_id, command)
        command_url = self.hub.hub_url + '/0?' + command + self.group_id + "=I=0"
        return self.hub.post_direct_command(command_url)
1095838
def sendcmd(self, cmd='AT', timeout=1.0):
        """"""
        import time
        if self.write(cmd):
            while self.get_response() == '' and timeout > 0:
                time.sleep(0.1)
                timeout -= 0.1
        return self.get_lines()
363657
function sendCommand(bleObj, cmd, callback)
{
	var bleBuffer = new ble.charArray(bufferLength);
	bleObj.writeData(cmd, cmd.length);

	// wait up to 1 second
	if (bleObj.dataAvailable(1000))
    {
		bleObj.readData(bleBuffer, bufferLength);
		var bleData = "";
		// read only the number of characters
		// specified by myGPSSensor.readData
		for (var x = 0; x < bufferLength; x++)
		{
			if (bleBuffer.getitem(x) == '\0')
				break;
			else
				bleData += bleBuffer.getitem(x);
		}
		console.log(bleData);
    }
	else
		console.log("Timed out waiting for response");
	if (callback)
		callback();
}
836259
def _handle_POST(self, env, start_response):
        
        input = env['wsgi.input']
        data = input.read( int(env['CONTENT_LENGTH']) )
        mimeType = "text/xml"
        if self.encoding is not None:
            mimeType = 'text/xml; charset="%s"' % self.encoding

        request = None
        resource = self.delegate or self
        chain = self.factory.newInstance()
        try:
            pyobj = chain.processRequest(data, request=request, resource=resource)
        except Exception, ex:
            start_response("500 ERROR", [('Content-Type',mimeType)])
            return [fault.FaultFromException(ex, False, sys.exc_info()[2]).AsSOAP()]

        try:
            soap = chain.processResponse(pyobj, request=request, resource=resource)
        except Exception, ex:
            start_response("500 ERROR", [('Content-Type',mimeType)])
            return [fault.FaultFromException(ex, False, sys.exc_info()[2]).AsSOAP()]
        
        start_response("200 OK", [('Content-Type',mimeType)])
        return [soap]
848760
def _send_command(self, cmd_class, command, payload, timeout=3.0):
        

        if len(payload) > 60:
            return ValueError("Attempting to send a BGAPI packet with length > 60 is not allowed", actual_length=len(payload), command=command, command_class=cmd_class)

        header = bytearray(4)
        header[0] = 0
        header[1] = len(payload)
        header[2] = cmd_class
        header[3] = command

        packet = header + bytearray(payload)
        self._stream.write(bytes(packet))

        #Every command has a response so wait for the response here
        response = self._receive_packet(timeout)
        return response
302062
def scene_on(self):
        """"""
        user_data = Userdata({'d1': self._group,
                              'd2': 0x00,
                              'd3': 0x00,
                              'd4': 0x11,
                              'd5': 0xff,
                              'd6': 0x00})
        self._set_sent_property(DIMMABLE_KEYPAD_SCENE_ON_LEVEL, 0xff)
        cmd = ExtendedSend(self._address,
                           COMMAND_EXTENDED_TRIGGER_ALL_LINK_0X30_0X00,
                           user_data)
        cmd.set_checksum()
        _LOGGER.debug('Calling scene_on and sending response to '
                      '_received_scene_triggered')
        self._send_method(cmd, self._received_scene_triggered)
649918
def recv(self):
        """"""
        try:
            items = self.poller.poll(self.timeout)
        except KeyboardInterrupt:
            return  # interrupted

        if items:
            # if we got a reply, process it
            msg = self.client.recv_multipart()
            self.close()
            if self.verbose:
                logging.info("I: received reply:")
                dump(msg)

            # Don't try to handle errors, just assert noisily
            assert len(msg) >= 4

            #first drop will be drop (cause empty)
            header = msg.pop(0)
            header = msg.pop(0)
            assert MDP.C_CLIENT == header

            #this one contains servicename
            #TODO: exploit this
            header = msg.pop(0)

            return msg
        else:
            logging.warn("W: permanent error, abandoning request")
1360875
async def on_message(message):
    

    # Simplify message info
    server = message.server
    author = message.author
    channel = message.channel
    content = message.content

    data = datatools.get_data()

    if not data["discord"]["servers"][server.id][_data.modulename]["activated"]:
        return

    # Only reply to server messages and don't reply to myself
    if server is not None and author != channel.server.me:
        # Commands section
        prefix = data["discord"]["servers"][server.id]["prefix"]
        if content.startswith(prefix):
            # Parse message
            package = content.split(" ")
            command = package[0][len(prefix):]
            args = package[1:]
            arg = ' '.join(args)

            # Commands
            if command == 'hex':
                await client.send_typing(channel)

                # Parse message
                hex_strs = api_hexconvert.convert_hex_value(arg)
                # Create embed UI
                if len(hex_strs) > 0:
                    for hex_str in hex_strs:
                        image_url = convert_hex_to_url(hex_str)
                        embed = ui_embed.success(channel, image_url, hex_str)
                        await embed.send()
                else:
                    embed = ui_embed.fail_api(channel)
                    await embed.send()
        else:
            # Parse message
            hex_strs = api_hexconvert.convert_hex_value(content)
            # Create embed UI
            if len(hex_strs) > 0:
                for hex_str in hex_strs:
                    await client.send_typing(channel)
                    image_url = convert_hex_to_url(hex_str)
                    embed = ui_embed.success(channel, image_url, hex_str)
                    await embed.send()
305418
def cmd(send, msg, args):
    
    parser = arguments.ArgParser(args['config'])
    parser.add_argument('blogname', action=arguments.TumblrParser)
    group = parser.add_mutually_exclusive_group()
    group.add_argument('--submit', nargs='*')
    group.add_argument('--random', action='store_true')
    try:
        cmdargs = parser.parse_args(msg)
    except arguments.ArgumentException as e:
        send(str(e))
        return

    if cmdargs.random:
        apikey = args['config']['api']['tumblrconsumerkey']
        # First, get the number of posts
        response = get('https://api.tumblr.com/v2/blog/%s/posts' % cmdargs.blogname, params={'api_key': apikey, 'type': 'text'}).json()
        postcount = response['response']['total_posts']
        if postcount <= 1:
            send("No text posts found.")
            return
        # No random post functionality and we can only get 20 posts per API call, so pick a random offset to get the random post
        offset = randint(0, postcount - 1)
        response = get('https://api.tumblr.com/v2/blog/%s/posts' % cmdargs.blogname,
                       params={
                           'api_key': apikey,
                           'offset': offset,
                           'limit': 1,
                           'type': 'text',
                           'filter': 'text'
                       }).json()
        entry = response['response']['posts'][0]['body']
        # Account for possibility of multiple lines
        lines = entry.splitlines()
        for line in lines:
            send(line)

    elif cmdargs.submit:
        if not cmdargs.submit:
            send('Post what?')
            return
        if isinstance(cmdargs.submit, list):
            cmdargs.submit = ' '.join(cmdargs.submit)
        if args['is_admin']:
            send(post_tumblr(args['config'], cmdargs.blogname, cmdargs.submit)[0])
        else:
            row = Tumblrs(post=cmdargs.submit, submitter=args['nick'], nick=args['nick'], blogname=cmdargs.blogname)
            args['db'].add(row)
            args['db'].flush()
            send("New Tumblr Post: %s -- %s, Submitted by %s" % (cmdargs.submit, cmdargs.blogname, args['nick']),
                 target=args['config']['core']['ctrlchan'])
            send("Issue submitted for approval.", target=args['nick'])
    else:
        send("Did not get an argument (choices are --random, --submit)")
964876
def do_POST(self, request, response):
        # pylint: disable=C0103
        
        # Get the request JSON content
        data = jsonrpclib.loads(to_str(request.read_data()))

        # Convert from Jabsorb
        data = jabsorb.from_jabsorb(data)

        # Dispatch
        try:
            result = self._unmarshaled_dispatch(data, self._simple_dispatch)
        except NoMulticallResult:
            # No result (never happens, but who knows...)
            result = None

        if result is not None:
            # Convert result to Jabsorb
            if "result" in result:
                result["result"] = jabsorb.to_jabsorb(result["result"])

            # Store JSON
            result = jsonrpclib.jdumps(result)
        else:
            # It was a notification
            result = ""

        # Send the result
        response.send_content(200, result, "application/json-rpc")
1083826
async def send_command(self, command):
        """"""
        _LOGGER.debug("Sending command to projector %s", command)
        if self.__checkLock():
            return False
        self.__setLock(command)
        response = await self.send_request(
            timeout=self.__get_timeout(command),
            params=EPSON_KEY_COMMANDS[command],
            type='directsend',
            command=command)
        return response
650318
def send_command_return_multilines(self, obj, command, *arguments):
        
        return self._perform_command('{}/{}'.format(self.session_url, obj.ref), command,
                                     OperReturnType.multiline_output, *arguments).json()
606551
def poll_command_reponse(self):
        
        if self._command.response is not Empty:
            _logger.debug("Sending response %s", self._command.response)
            self.rpc.send(_pack(self._command.response))
            self._command = None
1122364
def sendCommand(self, command):
        
        command_data = [ord(x) for x in buffer(command)]
        self.hid.write(command_data)
        response_data = ''.join(chr(x) for x in self.hid.read(64))
        response = command.RESPONSE.from_buffer_copy(response_data)
        if response.status != 0:
            raise CommandException(response.status)
        return response
812261
def __reply(self, reply, args, kwargs):
        
        binding = self.method.binding.input
        msg = binding.get_message(self.method, args, kwargs)
        log.debug('inject (simulated) send message:\n%s', msg)
        binding = self.method.binding.output
        return self.succeeded(binding, reply)
258052
def _execute_command(self, create_command, tag_info, mode, dic={}):
        
        xml = self._create_dynamic_xml(
            create_command, tag_info, mode, dic)
        d = self._request_ilo(xml)
        data = self._parse_output(d)
        LOG.debug(self._("Received response data: %s"), data)
        return data
509878
def recv(self, message, ref, pos):
        

        # Get action
        action = message.get('action', None)

        # Show the message we got
        if action != 'pingdog':
            self.debug("{} - Receive: {} (ref:{}) - {}".format(pos.name.encode('ascii', 'ignore'), message, ref, pos.uuid), color="cyan")

        # Check the action that it is requesting
        if action == 'get_config':
            # Get all the hardware connected to this POS
            answer = {}
            answer['action'] = 'config'
            answer['commit'] = pos.commit
            answer['hardware'] = []
            for hw in pos.hardwares.filter(enable=True):
                # Prepare to send back the config
                answer['hardware'].append({'kind': hw.kind, 'config': hw.get_config(), 'uuid': hw.uuid.hex})
            self.debug(u"{} - Send: {} - {}".format(pos.name.encode('ascii', 'ignore'), answer, pos.uuid), color='green')
            self.send(answer, ref, pos)
        elif action == 'subscribe':
            # Get UUID
            uid = message.get('uuid', None)
            # Check if we got a valid UUID
            if uid:
                uid = uuid.UUID(uid)
                poshw = POSHardware.objects.filter(uuid=uid).first()
                if poshw:
                    if poshw.enable:
                        # Suscribe this websocket to group
                        self.debug("{} - Subscribed to '{}' - {}".format(pos.name.encode('ascii', 'ignore'), uid.hex, pos.uuid), color="purple")
                        Group(uid.hex).add(self.message.reply_channel)
                        self.send({'action': 'subscribed', 'uuid': uid.hex, 'key': poshw.key}, ref, pos)
                    else:
                        self.send_error("You cannot subscribe to a disabled Hardware!", ref, pos)
                else:
                    self.send_error("You cannot subscribe to a Hardware that is not available, UUID not found!", ref, pos)
            else:
                self.send_error("You have tried to subscribe to a UUID but didn't specify any or is invalid", ref, pos)
        elif action == 'msg':
            uid = message.get('uuid', None)
            msg = message.get('msg', None)
            if uid:
                origin = POSHardware.objects.filter(uuid=uuid.UUID(uid)).first()
                if origin:
                    self.debug("{} - Got a message from {}: {} (ref:{}) - {}".format(pos.name.encode('ascii', 'ignore'), origin.uuid, msg, ref, pos.uuid), color='purple')
                    origin.recv(msg)
                else:
                    self.debug("{} - Got a message from UNKNOWN {}: {} (ref:{}) - {}".format(pos.name.encode('ascii', 'ignore'), uid, msg, ref, pos.uuid), color='purple')
            else:
                self.debug("{} - Got a message from NO-UUID: {} (ref:{}) - {}".format(pos.name.encode('ascii', 'ignore'), msg, ref, pos.uuid), color='purple')
        elif action == 'ping':
            super(POSConsumer, self).send({'message': json.dumps({'action': 'pong', 'ref': ref})})
        elif action == 'pong':
            self.debug("{} - Got PONG {} (ref:{}) - {}".format(pos.name.encode('ascii', 'ignore'), message.get('ref', '-'), ref, pos.uuid), color='white')
        elif action == 'pingdog':
            super(POSConsumer, self).send({'message': json.dumps({'action': 'pongdog', 'ref': ref})})
        elif action == 'error':
            uid = message.get('uuid', None)
            msg = message.get('error', 'No error')
            if uid:
                self.error("{} - Got an error from {}: {} (UUID:{}) (ref:{}) - {}".format(pos.name.encode('ascii', 'ignore'), pos.uuid, msg, uid, ref, pos.uuid))
            else:
                self.error("{} - Got an error from {}: {}) (ref:{}) - {}".format(pos.name.encode('ascii', 'ignore'), pos.uuid, msg, ref, pos.uuid))
            log = POSLog()
            log.pos = pos
            if uid:
                poshw = POSHardware.objects.filter(uuid=uid).first()
                if poshw:
                    log.poshw = poshw
                    log.uuid = poshw.uuid
            else:
                log.uuid = pos.uuid
            log.log = message.get('error', None)
            log.save()
        else:
            # Unknown action
            self.send_error("Unknown action '{}'".format(action), ref, pos)