示例#1
0
def main():
    """ Entry point of qiservice
    """
    app = qi.Application(sys.argv, raw=True)


    parser = argparse.ArgumentParser(description='Inspect qi module')
    parser.add_argument('--module', '-m', help='module name')
    parser.add_argument("--list", "-l", action="store_true", default=False, help="list all available modules")
    args = parser.parse_args()

    if args.list:
        print "modules:"
        for m in qi.listModules():
            print m
        return 0

    if args.list:
        print "modules:"
        for m in qi.listModules():
            print m
        return 0


    print "module:", args.module
    print "prefixes:", qi.path.sdkPrefixes()

    mod = qi.module(args.module)
    for o in mod.objects():
        print "object:", o
    for f in mod.functions():
        print "func  :", f
    for c in mod.constants():
        print "const :", c
示例#2
0
 def __init__(self):
     import qi
     mod = qi.module("tokenmanager")
     self._cli = mod.createObject("OAuth")
     self.access_token = self._cli.getAccessToken()
     if not is_token_valid(self.access_token):
         self.refresh()
     self._init_handlers()
    def __init__(self, session):
        """ Helper to configure the network from a QRCode

            Properties:
                status : the current status of the module. Can be
                        Ready : the module is initialized.
                        WaitingForQRCode : The module is scanning for a QRCode.
                        QRCodeDetected : The module has detected a QRCode.
                        Connecting : The module is trying to connect to the network.
                        Connected : The network is connected.
                        Error : Something goes wrong.
        """
        self.session = session

        #logger
        self.logger = qi.logging.Logger("naoqi.core.ALQRCodeWifiConfigurator")
        self.module = qi.module("qicore")
        self.logManager = self.session.service("LogManager")
        self.provider = self.module.createObject("LogProvider",
                                                 self.logManager)
        self.providerId = self.logManager.addProvider(self.provider)

        # init variables
        self.connectingToHiddenNetwork = False  # Setup wifi variable
        self.waitingForConnection = False
        self.cnonce = random.randint(
            1000, 9999
        )  # TODO: figure out if we want to use Head Id or what; for now Nonce is used nowhere in the process
        self.attemptedHiddenNetworks = None
        self.hiddenNetworkFailureReasons = None
        self.cam = 0
        self.status = qi.Signal("(s)")

        self.albarcodereader = self._get_service("ALBarcodeReader")
        if self.albarcodereader is None:
            self.logger.error("ALBarcodeReader is not available")
            return

        self.alconnectionmanager = self._get_service("ALConnectionManager")
        if self.alconnectionmanager is None:
            self.logger.error("ALConnectionManager is not available")
            return

        self.alvideodevice = self._get_service("ALVideoDevice")
        if self.alvideodevice is None:
            self.logger.error("ALVideoDevice is not available")
            return

        self.almemory = self._get_service("ALMemory")
        self.alaudioplayer = self._get_service("ALAudioPlayer")

        self.status(ALQRCodeWifiConfigurator.STATUS_READY)
示例#4
0
class SBRAppLauncher(object):
    """Communicates with the tablet and installs the native android app
    launcher.
    """
    def __init__(self, session):
        currPath = os.path.dirname(os.path.realpath(__file__))
        subprocess.call(["chmod", "+x", currPath + "/adb"])
        pathToLink = "/home/nao/.local/share/PackageManager/apps/applauncher"
        try:
            os.symlink(currPath, pathToLink)
        except OSError, e:
            if e.errno == errno.EEXIST:
                os.remove(pathToLink)
                os.symlink(currPath, pathToLink)
        self.session = session
        self.name = 'jp.softbank.rb.rald'
        self.version = '2.1.4'
        self._activityRequestedByUser = qi.Signal('(s)')
        self.touch_expr_obj = None
        self.target_behavior = str()
        self.services_connected = None
        self.log_prefix = 'ApplicationLauncher'
        self.custom_launcher = str()
        try:
            qicore = qi.module("qicore")
            log_manager = self.session.service("LogManager")
            provider = qicore.createObject("LogProvider", log_manager)
            log_manager.addProvider(provider)
            self.logger = qi.Logger(self.log_prefix)
        except (RuntimeError, AttributeError):
            pass

        # Wait for all services to be available
        self.connect_services(90)
        self.mem.declareEvent('ALRALManagerModule/onTouchDown')
        self.alife.userRequestableActivitiesViolations.connect(
            self.on_permissions_changed)
        self.tts.languageTTS.connect(self.on_language_changed)
        self.packman.onPackageRemoved2.connect(
            self.on_package_custom_launcher_removed)

        tablet = self.get_tablet_service()
        self.change_applauncher()
        self.startService()
        try:
            tablet.onTouchDown.connect(self.onTabletTouched)
        except (AttributeError, RuntimeError) as err:
            self.logger.warning(
                'Problem connecting the tablet touched event: {}'.format(err))
示例#5
0
def get_logger(session, app_id):
    """Returns a qi logger object."""
    logger = qi.logging.Logger(app_id)
    try:
        qicore = qi.module("qicore")
        log_manager = session.service("LogManager")
        provider = qicore.createObject("LogProvider", log_manager)
        log_manager.addProvider(provider)
    except RuntimeError:
        # no qicore, we're not running on a robot, it doesn't matter
        pass
    except AttributeError:
        # old version of NAOqi - logging will probably not work.
        pass
    return logger
示例#6
0
def get_logger(session, app_id):
    """Returns a qi logger object."""
    logger = qi.logging.Logger(app_id)
    try:
        qicore = qi.module("qicore")
        log_manager = session.service("LogManager")
        provider = qicore.createObject("LogProvider", log_manager)
        log_manager.addProvider(provider)
    except RuntimeError:
        # no qicore, we're not running on a robot, it doesn't matter
        pass
    except AttributeError:
        # old version of NAOqi - logging will probably not work.
        pass
    return logger
示例#7
0
def test_module():
    mod = qi.module("moduletest")

    cat = mod.createObject("Cat", "truc")
    assert cat.meow(3) == 'meow'

    mouse = mod.createObject("Mouse")
    assert mouse.squeak() == 18

    session = qi.Session()
    session.listenStandalone('tcp://localhost:0')
    cat = mod.createObject("Cat", session)
    assert cat.meow(3) == 'meow'

    assert cat.cloneMe().meow(3) == 'meow'

    assert mod.call("lol") == 3
示例#8
0
def test_module():
    mod = qi.module("moduletest")

    cat = mod.createObject("Cat", "truc")
    assert cat.meow(3) == 'meow'

    mouse = mod.createObject("Mouse")
    assert mouse.squeak() == 18

    session = qi.Session()
    session.listenStandalone('tcp://localhost:0')
    cat = mod.createObject("Cat", session)
    assert cat.meow(3) == 'meow'

    assert cat.cloneMe().meow(3) == 'meow'

    assert mod.call("lol") == 3
示例#9
0
def main():
    """ Entry point of qiservice
    """
    app = qi.Application(sys.argv, raw=True)

    parser = argparse.ArgumentParser(description='Inspect qi module')
    parser.add_argument('--module', '-m', help='module name')
    parser.add_argument("--list",
                        "-l",
                        action="store_true",
                        default=False,
                        help="list all available modules")
    args = parser.parse_args()

    if args.list:
        print "modules:"
        for m in qi.listModules():
            print m
        return 0

    if args.list:
        print "modules:"
        for m in qi.listModules():
            print m
        return 0

    print "module:", args.module
    print "prefixes:", qi.path.sdkPrefixes()

    mod = qi.module(args.module)
    for o in mod.objects():
        print "object:", o
    for f in mod.functions():
        print "func  :", f
    for c in mod.constants():
        print "const :", c
示例#10
0
def test_module_undef():
    mod = qi.module("moduletest")

    with pytest.raises(AttributeError):
        mod.createObject("LOL")
示例#11
0
import os
import qi


app = qi.Application()
qicore = qi.module('qicore')

log = qi.Logger("qicore.file.example.AliceServices.ImageStore")

class ImageStore:
  def __init__(self):
    self.file_registry = dict()
    self.counter = 0

  def __del__(self):
    for name, path in self.file_registry.iteritems():
       os.remove(path)

  # Store a copy of the image file and associate it with the provided name.
  def store_image(self, image_file, name):
    # Note that ideally this would be implemented in an asynchronous way,
    # but for simplicity we will do it synchronously.

    log.info("Storing '{0}' file ...".format(name))

    # First, make a local copy in a temporary files directory:
    temp_file_path = self._generate_temporary_file_path()

    # This call will block until the end because it returns a FutureSync.
    qicore.copyToLocal(image_file, temp_file_path)
示例#12
0
#!/usr/bin/env python
import sys
import time
import qi
import qi.path
import qi.logging
from ctypes import *

if __name__ == "__main__":
    app = qi.ApplicationSession(sys.argv)
    app.start()

    mod = qi.module("qicore")
    logmanager = app.session.service("LogManager")

    # Create a provider
    provider = mod.createObject("LogProvider", logmanager)
    # Add the provider to LogManager
    id = logmanager.addProvider(provider)

    # log!!!!!
    mylogger = qi.Logger("myfoo.bar")
    mylogger.fatal("fatal log")
    mylogger.error("error log")
    mylogger.warning("warning log")
    mylogger.info("info log")
    mylogger.verbose("verbose log")

    # since LogManager hold a "proxy" to the client object
    # we need to explicitly destroy the remote provider to call
    # the destructor
示例#13
0
        buff64 = base64.b64encode(buff)
        full = "data:image/png;base64," + buff64
        # show app
        self.memory.raiseEvent(self.events["metricalMap"],
                               [mpp, size, map[3], full])

    def getOccupancyMapParams(self):
        return [
            self.occMap.size, self.occMap.metersPerPixel,
            self.occMap.originOffset.toVector()
        ]


if __name__ == "__main__":
    app = qi.Application(sys.argv)
    app.start()
    session = app.session

    #get the logs
    mod = qi.module("qicore")
    provider = mod.initializeLogging(app.session)

    # don't forget to check that the services you use are ready!
    for required_service in ["ALMemory", "ALNavigation", "ALTabletService"]:
        future = session.waitForService(required_service)
        if future is not None:
            future.wait()
    my_service = ExplorationManager(session)
    register_id = session.registerService("ExplorationManager", my_service)
    app.run()
示例#14
0
def test_module_undef():
    mod = qi.module("moduletest")

    with pytest.raises(AttributeError):
        mod.createObject("LOL")
示例#15
0
    def __init__(self, session):
        """ ALBootConfig is a service to handle the boot of the robot

        """
        self.session = session
        self.finishing = False
        self.movement_deactivated = False
        self.is_online = False
        self.apkStarted = False
        self.aboutToReboot = False
        self.isGmsTablet = False

        #logger
        self.logger = qi.logging.Logger(ALBootConfig.APP_IDENTIFIER)
        self.module = qi.module("qicore")
        self.logManager = self.session.service("LogManager")
        self.provider = self.module.createObject("LogProvider",
                                                 self.logManager)
        self.providerId = self.logManager.addProvider(self.provider)

        #subsribe to itself to put log in file
        self.listener = self.logManager.createListener()
        self.listener.clearFilters()
        self.listener.addFilter("ALMemory", qi.logging.SILENT)
        self.listener.addFilter("ALMotion", qi.logging.SILENT)
        self.listener.onLogMessage.connect(self._onLogMessage)

        if os.path.exists(ALBootConfig.LOG_FILE):
            os.remove(ALBootConfig.LOG_FILE)

        logging.basicConfig(filename=ALBootConfig.LOG_FILE,
                            level=logging.DEBUG,
                            format='%(asctime)s %(message)s')

        self.logger.info("Starting ...")

        #services
        self.serviceDirectory = self._get_service("ServiceDirectory")
        if not self.serviceDirectory:
            self.logger.error(
                "ServiceDirectory not found, finishing boot config .....")
            return self.finish()

        self.altabletservice = self._get_service("ALTabletService")

        self.alconnectionmanager = self._get_service("ALConnectionManager")
        self.alrobotmodel = self._get_service("ALRobotModel")
        self.almemory = self._get_service("ALMemory")
        self.packagemanager = self._get_service("PackageManager")
        self.albehaviormanager = self._get_service("ALBehaviorManager")
        self.alpreferencemanager = self._get_service("ALPreferenceManager")
        self.almotion = self._get_service("ALMotion")
        self.alautonomousmove = self._get_service("ALAutonomousMoves")
        self.alstore = self._get_service("ALStore")

        self.alautonomouslife = self._get_service("ALAutonomousLife")
        if self.alautonomouslife:
            self.alautonomouslife._forbidStopCommands(
                True, )  # deactivate the stop app
            self.alautonomouslife.setSafeguardEnabled("RobotPushed", False)
            self.alautonomouslife.setSafeguardEnabled("RobotFell", False)
            self.alautonomouslife.setSafeguardEnabled("RobotMoved", False)
            self.alautonomouslife.setSafeguardEnabled("CriticalDiagnosis",
                                                      False)
            self.alautonomouslife.setSafeguardEnabled("CriticalTemperature",
                                                      False)

        # subscribe to events/signals
        self.serviceSignal = self.serviceDirectory.serviceAdded.connect(
            self._handleServiceAdded)
        self.serviceSignalR = self.serviceDirectory.serviceRemoved.connect(
            self._handleServiceRemoved)

        self.firstLaunch = self._check_and_set_first_launch()

        if self.alrobotmodel._getRobotType() != 1:
            self.logger.info(
                "The robot is not a Pepper, skip interactive config ....")
            return self.finish()

        self.hasStarted = False
        if self.altabletservice:
            self._check_is_gms_tablet()
            self.hasStarted = True
            self.robotIp = self.altabletservice.robotIp()
            self.altabletservice.onApkInstalled.connect(self._onApkInstalled)
            self.startbootconfig()
        else:
            state = self._get_state()
            if (state == ALBootConfig.WIZARDSTATE_SYSTEM_UPDATING
                    or state == ALBootConfig.WIZARDSTATE_SYSTEM_UPDATED
                ) and self._isBCApkRunning():
                self.logger.info(
                    "Finishing system update with ALTabletService missing")
                self.hasStarted = True
                self.apkStarted = True
                self.runInit()
                self._finishUpdate()
            elif state == ALBootConfig.WIZARDSTATE_SYSTEM_UPDATING_WITH_OTA:
                self.logger.info(
                    "Finishing system and tablet update with ALTabletService missing"
                )
                if self.almotion:
                    try:
                        self.almotion.wakeUp()
                    except Exception as e:
                        self.logger.error("Error playing wake up: %s " % e)
                if not self.movement_deactivated and self.albehaviormanager:
                    try:
                        self.albehaviormanager.startBehavior(
                            "boot-config/animations/inviteTablet")
                    except Exception as e:
                        self.logger.error("Error playing animation: %s" % e)
                guessTimeForTabletUpdate = 20  # TODO value ?
                self._waitForTabletReconnection(guessTimeForTabletUpdate * 60)
                if not self.altabletservice:
                    self.logger.info(
                        "ALTabletService missing, finishing boot-config.")
                    self.finish()
            else:
                self._waitForTabletReconnection(8 * 60)
                if not self.altabletservice:
                    self.logger.info(
                        "ALTabletService missing, finishing boot-config.")
                    self.finish()
示例#16
0
            else:
                raise Exception("No markers with IDs %s found" % params["ids"])

        d = time.time() - t
        self.logger.info("_detect_markers done %s" % d)
        return p6Ds


if __name__ == "__main__":
    application = qi.Application()
    application.start()

    logger = qi.getLogger(PACKAGE_UID)
    # mandatory to broadcast logs
    try:
        qicore_module = qi.module("qicore")
        log_provider = qicore_module.initializeLogging(application.session)
    except Exception as e:
        logger.warning("qicore module not found, logs won't be broadcasted")

    # instanciate, register & start the application
    try:
        lock_application = True
        logger.info("instanciation...")
        instance = Main(application, logger)
        logger.info("instanciation done, registration...")
        application.session.registerService(SERVICE_NAME, instance)
        logger.info("registration done")
    except Exception as e:
        logger.error("instanciation or registration finished with error: %s" %
                     e)