Esempio n. 1
0
def Initialize(port, functionMap={}, asyncHandler=None):
    '''
    
    Initializes BlackBoard with the corresponding parameters.
    
    :param int port: The port through which BlackBoard will communicate with this module.
    :param dictionary functionMap: A dictionary containing **key:value** pairs, where the *key* is the name of a command received (a string),
        and the *value* is either a tuple containing a function as a first element and a boolean as a second element, or a function.
        The function in both cases is the function that is going to execute the specified command and receives on object of type :class:`Command` (See :ref:`Creating a command handler <creating_a_command_handler>`).
        The boolean value indicates whether the execution of that command should be synchronous (on the same thread) or asynchronous,
        usually synchronous execution is preferred for fast commands that can answer almost immediately and asynchronous for commands that might take a little time.
        When the value is only a function, by default the execution is synchronous. *functionMap* can also contain an entry with a string containing only an asterisk,
        meaning that would be the handler in case no other handler is found for a specific command.
        
        .. note::

            Notice that although functionMap can include a wildcard handler and this might seem like the module could answer
            anything, BlackBoard will only send commands that are registered under this module's configuration.
        
    :param function asyncHandler: A function that would handle the response of commands when sent with the method :func:`Send`
        instead of using :func:`SendAndWait`. This means the execution of a program that sends a command could continue
        and an asynchronous handler would handle the response when one is received.

        .. note::
    
            Notice that the asyncHandler functionality could also be achieved using a :class:`ParallelSender` object,
            but it has other implications.
    
    '''
    global _executors, _connMan, _parser, _p, _initialized, _ready

    _executors = {
        'busy': (lambda x: Response('busy'), False),
        'ready': (_isReady, False),
        'alive': (lambda x: Response('alive', True), False)
    }

    for m in functionMap:
        if isinstance(functionMap[m], types.FunctionType):
            _executors[m] = (functionMap[m], False)
        elif isinstance(functionMap[m], tuple):
            _executors[m] = functionMap[m]
        else:
            print 'Element in function map is not a function nor a correct tuple: ' + repr(
                functionMap[m])

    _connMan = ConnectionManager(port)
    _parser = CommandParser(asyncHandler)

    _p = threading.Thread(target=_MainThread)
    _p.daemon = True

    _initialized = True
Esempio n. 2
0
    def Parse(cls, s):
        r = Response.Parse(s)
        if not (r and r.name == 'read_var'):
            return r

        var = SharedVar(r)

        m = SharedVar._rx.match(var.params)

        if not m:
            print 'read_var received but failed to parse:'
            print var.params
            return None

        var.svType = m.group('type') + ('[]' if m.group('array') else '')
        var.size = -1 if not m.group('size') else int(m.group('size'))
        var.varName = m.group('name')
        var.data = m.group('data')

        var.report = m.group('report')
        var.subscription = m.group('subscription')
        var.writer = m.group('writer')

        var.isNotification = not not var.report

        var.data = SharedVar._ProcessReadVar(var)

        return var
Esempio n. 3
0
def _Execute(func, command):
    try:
        response = func(command)
    except Exception as e:
        print "Function '" + str(func) + "' crashed."
        print 'ERROR: ' + str(e)
        response = Response.FromCommandObject(command, False, command.params)

    if not isinstance(response, Response):
        print "Function '" + str(func) + "' did not return a Response object."
        response = Response.FromCommandObject(command, False, command.params)

    resp = Response.FromCommandObject(command, response.successful,
                                      response.params)

    Send(resp)
Esempio n. 4
0
    def send_image_request(self, request):
        camera_op = "CAMERA" in request.command  # Indicates if a camera image was requested
        data_out = str(
            request.__dict__
        )  #pickle.dumps(request, protocol=2)    # Explicitly requests Python2 protocol

        while not self.connect_to_proxy():  # Open connection
            time.sleep(1)  # In case server is offline, continues to try

        self.socket.send(data_out)
        # Now wait for response
        try:
            if camera_op:  # If it's an image, incrementally receive all the data chunks
                data_in = b''
                while True:
                    block = self.socket.recv(4096)
                    if block:
                        data_in += block
                    else:
                        break
            else:
                data_in = self.socket.recv(4096)
            self.connection_close()  # Close the connection
            response = data_in

        except EOFError:
            response = Response(False, "Reception error")
        return response
Esempio n. 5
0
 def get_camera_image(self):
     img = self.nao.get_camera_image()
     print(type(img))
     retval, buff = cv.imencode(".jpg", img)
     print(type(buff))
     data = base64.b64encode(buff)
     print(type(data))
     return Response(True, data)
Esempio n. 6
0
 def api_request(self, method, path, params=[], data=""):
     try:
         self.connection.send_message(
             Request(method, path, params, data).encode())
         sresp = self.connection.receive_message()
         # Check if client cliosing connection
         if sresp.type == CLOSE_MESSAGE:
             if self.onclose_callback != None:
                 self.onclose_callback()
             return None
         resp = Response()
         resp.decode(sresp.data)
         return resp
     except socket.error:
         if self.onclose_callback != None:
             self.onclose_callback()
         return None
Esempio n. 7
0
def _isReady(c):
    global _ready, _readyLock

    _readyLock.acquire()
    ready = _ready
    _readyLock.release()

    return Response('ready', ready)
Esempio n. 8
0
 def add_post(self, request):
     user = request.user
     # user = endpoints.get_current_user()
     # user = handlers.BaseRequestHandler.current_user()
     if user is None:
         raise endpoints.UnauthorizedException('Invalid token.')
     resp = services.ApiUtils.add_post(user, request.title, request.quote,
                                       request.user_anonymous,
                                       request.provider, request.url,
                                       request.image)
     return Response(success=resp)
Esempio n. 9
0
 def add_comment(self, request):
     author = request.author
     # user = endpoints.get_current_user()
     # user = handlers.BaseRequestHandler.current_user()
     resp = services.ApiUtils.add_comment(
         user=author,
         quoteid=request.post_id,
         text=request.text,
         provider=request.provider,
         user_anon=request.author_anonymous)
     return Response(success=resp)
Esempio n. 10
0
 def _sendAck(self):
     ack = Response(typeMessage=MessageType.ACK,
                    messageId=self._messageId,
                    token=self._token)
     ack.setCode(ResponseCode.EMPTY)
     self._sock.sendto(ack.getHeader() + ack.getTokenBytes(),
                       (self._ip, self._port))
Esempio n. 11
0
    async def read(self,
                   websocket: websockets.WebSocketClientProtocol) -> None:
        """Asynchronously reads responses from the OBS websocket."""

        try:
            while True:
                msg = await websocket.recv()
                data = json.loads(msg)
                if self.debug:
                    print(data)
                self.responses.append(Response(data, self.obs))
        except asyncio.CancelledError:
            return
Esempio n. 12
0
    def _parsingThread(self):

        while True:

            data = BB._incomingMessages.get()

            el = SharedVar.Parse(data)
            if el and el.isNotification:
                handler = None
                BB._subscriptionHandlersLock.acquire()
                if el.varName in BB._subscriptionHandlers:
                    handler = BB._subscriptionHandlers[el.varName]
                BB._subscriptionHandlersLock.release()

                if not handler:
                    print 'ERROR: No handler for shared variable: ' + el.varName
                    continue

                try:
                    handler(el)
                except:
                    print 'Handler for shared var: "' + el.varName + '" crashed.'

                continue
            if not el:
                el = Response.Parse(data)
                if el:
                    print "Something that wasn't supposed to happen happened"
            if el:
                BB._commandsLock.acquire()
                if el in BB._sentCommands:
                    BB._responsesLock.acquire()
                    BB._receivedResponses[el] = el
                    BB._responsesLock.release()
                elif self._asyncHandler:
                    self._asyncHandler(el)
                else:
                    print 'Response without awaiting command: ' + repr(el)
                BB._commandsLock.release()
                continue
            el = Command.Parse(data)
            if el:
                BB._receivedCommands.put(el)
                continue

            print 'Invalid message received: ' + data + '_len(' + str(
                len(data)) + ')'
Esempio n. 13
0
    def route_request(self, request):

        if request.command == "PING":
            response = 5
        elif request.command == "CAMERA":
            response = self.get_camera_image()
        elif request.command == "LED":
            response = self.set_led_color(request.parameters)
        elif request.command == "LISTEN":
            response = self.listen_for_words(request.parameters)
        elif request.command == "STAND":
            response = self.standup()
        elif request.command == "SIT":
            response = self.sitdown()
        elif request.command == "SAY":
            response = self.say(request.parameters)
        elif request.command == "CLOSE":
            response = Server.close()
        else:
            # Command not recognized
            response = Response(False, "Invalid command code")
        return response
Esempio n. 14
0
	def run (self):
		while not self.stopped():
			# Wait for message
			msg = self.wsconnection.receive_message()

			# Check if client cliosing connection
			if msg.type == CLOSE_MESSAGE:
				self.stop()
				self.server.remove_client(self)
				return

			# Hendle message
			request = Request()
			resp = None
			if not request.decode(msg.data):
				resp = Response (400)
			else:
				if request.path in self.server.paths:
					data = self.server.paths[request.path](request.data)
					resp = Response (200, data)
				else:
					resp = Response (404)
			sresp = resp.encode()
			self.wsconnection.send_message(sresp)
Esempio n. 15
0
 def standup(self):
     self.nao.standup()
     return Response(True, None)
Esempio n. 16
0
 def ping(self):
     return Response(True, t.time())
Esempio n. 17
0
 def close(self):
     self.close_request = True
     return Response(True, None)
Esempio n. 18
0
 def set_led_color(self, *params):
     self.nao.set_led_color(params[0], params[1])
     return Response(True, None)
Esempio n. 19
0
 def say(self, words):
     self.nao.say(words)
     return Response(True, None)
Esempio n. 20
0
 def sitdown(self):
     self.nao.sitdown()
     return Response(True, None)
Esempio n. 21
0
 def listen_for_words(self, vocabulary):
     return Response(True, self.nao.listen_for_words(vocabulary))