def _connect_services(self):
        """Connect to all services required by ALTactileGesture"""
        self.services_connected = qi.Promise()
        services_connected_fut = self.services_connected.future()

        def get_services():
            """Attempt to get all services"""
            try:
                self.memory = self.session.service('ALMemory')
                self.prefs = self.session.service('ALPreferenceManager')
                self.logger.info('got references to all services')
                self.services_connected.setValue(True)
            except RuntimeError as e:
                self.logger.warning('missing service:\n {}'.format(e))

        get_services_task = qi.PeriodicTask()
        get_services_task.setCallback(get_services)
        get_services_task.setUsPeriod(int(2 * 1000000))  # check every 2s
        get_services_task.start(True)

        try:
            services_connected_fut.value(30 * 1000)  # timeout = 30s
            get_services_task.stop()
        except RuntimeError:
            get_services_task.stop()
            self.logger.info('Failed to reach all services after 30 seconds')
            raise RuntimeError
    def _search_gestures(self):
        """
        Compare inputted sequence to all gestures to find match

        Algorithm:
        1. async call _check_sequence on for all gestures
           (i.e. gestures that match the current hold status and are not unset custom gestures)
              -> _check_sequence() will fullfill promise with the gesture if matched; else None
        2. Build list of all futures whose value is a matched sequence
        3. Return the gesture whose match is the closest the sequence prototype
           it matched (i.e. smallest difference)
        """
        futures = []
        las = len(self.active_sequence)
        # For every sequence; start check asynchronously
        for gesture in self.all_gestures:
            if gesture.hold == self.active_hold:
                p = qi.Promise()
                futures.append(p.future())
                qi. async (self._check_sequence, self.active_sequence, las,
                           gesture, p)
        # Walks through futures list; waits on each promise to be fullfiled
        vf = (f.value() for f in futures if f.value()[0])
        # Returns gesture corresponding to min diff value in vf above
        # If vf is empty, returns (None, 0)
        return reduce(lambda x, y: min((x, y), key=op.itemgetter(1)), vf,
                      next(vf, (None, 0)))[0]
    def _connect_services(self):
        """
        Connect to all services required by BarcodeReader.
        """
        self.logger.info('Connecting services...')
        self.services_connected = qi.Promise()
        services_connected_fut = self.services_connected.future()

        def get_services():
            """Attempt to get all services"""
            try:
                self.mem = self.session.service('ALMemory')
                self.vid = self.session.service("ALVideoDevice")
                self.logger.info('All services are now connected')
                self.services_connected.setValue(True)
            except RuntimeError as e:
                self.logger.warning('Missing service:\n {}'.format(e))

        get_services_task = qi.PeriodicTask()
        get_services_task.setCallback(get_services)
        get_services_task.setUsPeriod(int(2 * 1000000))  # check every 2s
        get_services_task.start(True)
        try:
            services_connected_fut.value(30 * 1000)  # timeout = 30s
            get_services_task.stop()
        except RuntimeError:
            get_services_task.stop()
            self.logger.error('Failed to reach all services after 30 seconds.')
            raise RuntimeError
    def connect_services(self):
        # connect all services required by your module
        # done in async way over 30s,
        # so it works even if other services are not yet ready when you start your module
        # this is required when the service is autorun as it may start before other modules...
        self.logger.info('Connecting services...')
        self.services_connected = qi.Promise()
        services_connected_fut = self.services_connected.future()

        def get_services():
            try:
                self.memory = self.session.service('ALMemory')
                self.dialog = self.session.service('ALDialog')
                # connect other services if needed...
                self.logger.info('All services are now connected')
                self.services_connected.setValue(True)
            except RuntimeError as e:
                self.logger.warning(
                    'Still missing some service:\n {}'.format(e))

        get_services_task = qi.PeriodicTask()
        get_services_task.setCallback(get_services)
        get_services_task.setUsPeriod(int(2 * 1000000))  # check every 2s
        get_services_task.start(True)
        try:
            services_connected_fut.value(30 * 1000)  # timeout = 30s
            get_services_task.stop()
        except RuntimeError:
            get_services_task.stop()
            self.logger.error('Failed to reach all services after 30 seconds')
            raise RuntimeError
 def bind_retfutint(self):
     p = qi.Promise("(i)")
     t = threading.Thread(target=setValue, args=(
         p,
         42,
     ))
     t.start()
     return p.future()
Exemple #6
0
def test_future_strand():
    obj = Stranded(30)

    prom = qi.Promise()
    for i in range(30):
        prom.future().addCallback(obj.cb)
    prom.setValue(None)

    obj.end.future().value()
 def _waitForTabletReconnection(self, t):
     """ Wait for the ALTabletService reconnection for x secunds
         Parameters:
             t (int) - the time to wait the reconnection in sec
     """
     self.logger.info(
         "ALTabletService not found, wait %ss for reconnection ..." % t)
     self.promiseWaitingTabletReconnection = qi.Promise()
     qi. async (self._cancelWaitForTabletReconnection, delay=t * 1000000)
     self.promiseWaitingTabletReconnection.future().wait()
     self.promiseWaitingTabletReconnection = None
 def retfutmap(self):
     p = qi.Promise()
     t = threading.Thread(target=setValue,
                          args=(
                              p,
                              {
                                  'titi': 'toto',
                                  "foo": "bar"
                              },
                          ))
     t.start()
     return p.future()
Exemple #9
0
 def run(self):
     self.logger.info("run")
     self.init_variables()
     self.check_variables()
     self.promise = qi.Promise(self._cancel)
     self.reason = None
     self.signal_id = self.move_failed_subscriber.signal.connect(
         self._on_move_failed)
     self.robot_position_begin = almath.Pose2D(
         self.ALMotion.getRobotPosition(True))
     self.task.start(True)
     return self.promise.future()
    def __init__(self, application):
        self.application = application
        self.session = application.session
        self.service_name = self.__class__.__name__

        # Getting a logger. Logs will be in /var/log/naoqi/servicemanager/{application id}.{service name}
        self.logger = qi.Logger(self.service_name)

        self.logger.info("Initializing...")

        self.handDetect = False

        def awaitServiceStartup(p):

            try:
                self.motion = self.session.service("ALMotion")
                self.posture = self.session.service("ALRobotPosture")
                self.speech = self.session.service("ALTextToSpeech")
                self.memory = self.session.service("ALMemory")

                self.speakingMovement = self.session.service(
                    "ALSpeakingMovement")
                self.listeningMovement = self.session.service(
                    "ALListeningMovement")
                self.backgroundMovement = self.session.service(
                    "ALBackgroundMovement")
            except RuntimeError:
                self.logger.info("Services not found")
                return

            self.logger.info("Services found")
            p.setValue("SERVICES_READY")

        p = qi.Promise()
        f = p.future()

        pt = qi.PeriodicTask()
        pt.setCallback(functools.partial(awaitServiceStartup, p))
        pt.setUsPeriod(2000000)
        pt.start(True)

        if f.value(30000) == "SERVICES_READY":
            self.service_id = self.session.registerService(
                self.service_name, self)
            self.logger.info("Initialized!")
        else:
            self.logger.info("Initialization failed!")

        pt.stop()
def show_prompt():
    """
    This example uses the executeJS method.
    To Test ALTabletService, you need to run the script ON the robot.
    """
    global exit
    global file
    # Get the service ALTabletService.
    try:
        # Javascript script for displaying a prompt
        # ALTabletBinding is a javascript binding inject in the web page displayed on the tablet
        script = """
            var name = prompt("Write down your email to receive our SMILE-Newsletter ", "*****@*****.**");
            ALTabletBinding.raiseEvent(name)
        """

        # Don't forget to disconnect the signal at the end
        signalID = 0

        # function called when the signal onJSEvent is triggered
        # by the javascript function ALTabletBinding.raiseEvent(name)
        print('Defining callback')

        def callback(event):
            global exit
            if not str(event) == '*****@*****.**':
                if event:
                    print(event)
                    file.write(str(event) + '\n')
                tts.say('Thank you')
            exit.set()

        promise = qi.Promise()

        print('Connecting callback')
        # attach the callback function to onJSEvent signal
        signalID = tabletService.onJSEvent.connect(callback)

        # inject and execute the javascript in the current web page displayed
        print('Executing script')
        tabletService.executeJS(script)

        exit.clear()
        exit.wait()

    except Exception, e:
        print "Error was:", e
        file.close()
def main(session):
    """
    This example uses the executeJS method.
    To Test ALTabletService, you need to run the script ON the robot.
    """
    # Get the service ALTabletService.
    tabletService = session.service("ALTabletService")

    try:
        # Display a local web page located in boot-config/html folder
        # The ip of the robot from the tablet is 198.18.0.1
        tabletService.showWebview(
            "http://198.18.0.1/apps/boot-config/preloading_dialog.html")

        time.sleep(3)

        # Javascript script for displaying a prompt
        # ALTabletBinding is a javascript binding inject in the web page displayed on the tablet
        script = """
            var name = prompt("Please enter your name", "Harry Pepper");
            ALTabletBinding.raiseEvent(name)
        """

        # Don't forget to disconnect the signal at the end
        signalID = 0

        # function called when the signal onJSEvent is triggered
        # by the javascript function ALTabletBinding.raiseEvent(name)
        def callback(event):
            print "your name is:", event
            promise.setValue(True)

        promise = qi.Promise()

        # attach the callback function to onJSEvent signal
        signalID = tabletService.onJSEvent.connect(callback)

        # inject and execute the javascript in the current web page displayed
        tabletService.executeJS(script)

        try:
            promise.future().hasValue(30000)
        except RuntimeError:
            raise RuntimeError('Timeout: no signal triggered')

    except Exception, e:
        print "Error was:", e
Exemple #13
0
def test_future_partials_strand():
    obj = Stranded(50)

    prom = qi.Promise()
    for i in range(10):
        prom.future().addCallback(obj.cb)
    for i in range(10):
        prom.future().addCallback(partial(obj.cbn, 1))
    for i in range(10):
        prom.future().addCallback(partial(partial(obj.cbn, 1), 2))
    for i in range(10):
        prom.future().addCallback(partial(partial(Stranded.cbn, obj, 1), 2))
    for i in range(10):
        prom.future().addCallback(partial(Stranded.cbn, obj, 1))
    prom.setValue(None)

    obj.end.future().value()
def test_return_empty_object(session_to_process_service_endpoint):
    service_name, service_session = session_to_process_service_endpoint
    log = logging.getLogger("test_return_empty_object")
    obj = service_session.service(service_name)
    prom = qi.Promise()

    def callback(obj):
        try:
            log.info("object is valid: {}.".format(obj.isValid()))
            prom.setValue(not obj.isValid())
        except Exception as err:
            prom.setError(str(err))
        except:
            prom.setError("Unknown exception.")

    obj.signal.connect(callback)
    obj.resetObject()
    obj.emit()
    assert prom.future().value()
Exemple #15
0
        def wrapper(self, *args, **kwds):
            promise = qi.Promise(_cancel)
            future = promise.future()
            queued_tmstp = time.time()

            def runner():
                if not promise.future().isCanceled():
                    try:
                        exec_tmstp = time.time()
                        if expire_delay != -1 and exec_tmstp - queued_tmstp > expire_delay:
                            logger.info("Expired %s%s, do not exec" %
                                        (method.__name__, args))
                            promise.setError(
                                "Could not exec method, it expired")
                            return
                        res = method(self, *args, **kwds)
                        if not promise.future().isCanceled():
                            promise.setValue(res)
                    except Exception, e:
                        logger.error(traceback.format_exc())
                        if not promise.future().isCanceled():
                            promise.setError(str(e))
Exemple #16
0
def test_all_strand():
    obj = Stranded(81)

    sig = qi.Signal("m")
    prop = qi.Property("m")
    prom = qi.Promise()
    per = qi.PeriodicTask()
    per.setCallback(partial(obj.cb, None))
    per.setUsPeriod(10000)
    for i in range(20):
        prom.future().addCallback(obj.cb)
    for i in range(20):
        sig.connect(obj.cb)
    for i in range(20):
        prop.connect(obj.cb)
    per.start(True)
    sig(None)
    prop.setValue(42)
    prom.setValue(None)
    for i in range(20):
        qi. async (partial(obj.cb, None))

    obj.end.future().value()
    per.stop()
Exemple #17
0
    def wait_for(self, event, subscribe=False):
        """Block until a certain event is raised, and returns it's value.

        If you pass subscribe=True, ALMemory.subscribeToEvent will be called
        (sometimes necessary for side effects, i.e. WordRecognized).

        This will block a thread so you should avoid doing this too often!
        """
        if self.wait_promise:
            # there was already a wait in progress, cancel it!
            self.wait_promise.setCanceled()
        self.wait_promise = qi.Promise()
        if subscribe:
            connection_id = self.subscribe(event, "EVENTHELPER",
                                           self._on_wait_event)
        elif "." in event:  # it's a signal
            connection_id = self.connect(event, self._on_wait_signal)
        else:
            connection_id = self.connect(event, self._on_wait_event)
        try:
            result = self.wait_promise.future().value()
        finally:
            self.disconnect(event, connection_id)
        return result
Exemple #18
0
    def connect_services(self, timeout):
        """Connect to all services required.
        :param timeout: time in seconds after wich acquiring services is
                        abandonned."""
        self.services_connected = qi.Promise()
        services_connected_fut = self.services_connected.future()
        timeout = int(max([1, timeout]) * 1000)
        period = int(min([2, timeout / 2]) * 1000000)

        self.logger.info('Timeout: {} ms'.format(timeout))
        self.logger.info('Period: {} us'.format(period))

        get_services_task = qi.PeriodicTask()
        get_services_task.setCallback(self.get_services)
        get_services_task.setUsPeriod(period)
        get_services_task.start(True)

        try:
            services_connected_fut.value(timeout)
            get_services_task.stop()
        except RuntimeError:
            get_services_task.stop()
            raise RuntimeError(
                'Failed to reach all services after {} ms'.format(timeout))
Exemple #19
0
 def fut(self):
     p = qi.Promise()
     #p.setValue(42)
     threading.Thread(target=makeIt, args=[p]).start()
     return p.future()
Exemple #20
0
 def __init__(self):
     self.running = True
     self.promise = qi.Promise()
     self.future = self.promise.future()
     self._exception = ""
     self.lock = threading.Lock()
Exemple #21
0
 def __dialog_reinit_promise(self):
     if self.__dialog_promise is not None and not self.__dialog_promise.future(
     ).isFinished():
         self.__dialog_promise.setCanceled()
     self.__dialog_promise = qi.Promise()
Exemple #22
0
 def __init__(self, max):
     self.calling = False
     self.counter = 0
     self.max = max
     self.end = qi.Promise()