示例#1
0
 def getCurrentPosition():
     "get a list of joint name and their current position value in radians ['HeadYaw'=1.0; 'HeadPitch'=1.0;... work even if no stiffness"
     motion = naoqitools.myGetProxy("ALMotion")
     listJointName = motion.getJointNames('Body')
     listJointName.remove("RHipYawPitch")
     # when using dcm: remove this joint
     listJointsDCMValue = []
     # la liste des clés de chaque joint dans la stm
     for strJointName in listJointName:
         listJointsDCMValue.append(
             "Device/SubDeviceList/%s/Position/Sensor/Value" % strJointName)
     # add TorsoX and Y and AccZ
     listJointsDCMValue.append(
         "Device/SubDeviceList/InertialSensor/AngleX/Sensor/Value")
     listJointsDCMValue.append(
         "Device/SubDeviceList/InertialSensor/AngleY/Sensor/Value")
     listJointsDCMValue.append(
         "Device/SubDeviceList/InertialSensor/AccZ/Sensor/Value")
     stm = naoqitools.myGetProxy("ALMemory")
     listJointValue = stm.getListData(listJointsDCMValue)
     dicoConstructed = dict([])
     for i in range(len(listJointName)):
         dicoConstructed[listJointName[i]] = listJointValue[i]
     dicoConstructed['TorsoX'] = listJointValue[len(listJointName)]
     dicoConstructed['TorsoY'] = listJointValue[len(listJointName) + 1]
     dicoConstructed['TorsoAccZ'] = listJointValue[len(listJointName) +
                                                   2] * math.pi / 180
     #    debug.debug( "poselibrary::PoseLibrary::getCurrentPosition: " + stringtools.dictionnaryToString( dicoConstructed ) );
     return dicoConstructed
示例#2
0
def sayAndCacheAndLight( strTextToSay, bJustPrepare = False, bStoreToNonVolatilePath = False, nEyesColor = 0, nUseLang = -1 ):
    "say a cached text with light animation"
    "nEyesColor: 0: white, 1: blue, 2: green; 3: red"
    "nUseLang: if different of -1: speak with a specific languages (useful, when text are already generated: doesn't need to swap languages for nothing!"
    "return the length of the text in seconds, or None if impossible"
    print( "sayAndCacheAndLight( '%s', bJustPrepare: %s, bStoreToNonVolatilePath: %s, nEyesColor: %s, nUseLang: %s )" % ( strTextToSay, str( bJustPrepare ), str( bStoreToNonVolatilePath ), str( nEyesColor ), str( nUseLang ) ) );
    if( not config.bPrecomputeText ):
        print( "sayAndCacheAndLight: disabled by configuration: bPrecomputeText is false" );
        if( bJustPrepare ):
            return None; # do nothing
        tts = naoqitools.myGetProxy( "ALTextToSpeech" );
        tts.say( strTextToSay );
        return None;

    rLength = sayAndCache( strTextToSay, bJustPrepare = True, bStoreToNonVolatilePath = bStoreToNonVolatilePath, nUseLang = nUseLang, bCalledFromSayAndCacheFromLight = True ); # we store it to disk, only if we must do it

    # this two lines are done too in sayAndCache...
    strTextToSay = assumeTextHasDefaultSettings( strTextToSay, nUseLang );
    szFilename = sayAndCache_getFilename( strTextToSay, nUseLang );

    szPathVolatile = pathtools.getVolatilePath();
    rSampleLenSec = 0.05;
#    szPathFilenamePeak = szPathVolatile + szFilename + ("_%5.3f.egy" % rSampleLenSec);
    szPathFilenamePeak = szFilename + ("_%5.3f.egy" % rSampleLenSec);
    szPathFilenamePeakCache = pathtools.getCachePath() + "generatedvoices" + pathtools.getDirectorySeparator() + szPathFilenamePeak;
    szPathFilenamePeak = szPathVolatile + szPathFilenamePeak;
    anLedsColorSequency = [];
    aBufFile = "";
    bFileGenerated = False;
    if( not filetools.isFileExists( szPathFilenamePeak ) ):
        if( filetools.isFileExists( szPathFilenamePeakCache ) ):
            copyFile( szPathFilenamePeakCache, szPathFilenamePeak );
    if( not filetools.isFileExists( szPathFilenamePeak ) ):
        # generate peak file
        timeBegin = time.time();
        print( "sayAndCacheAndLight: generating peak light - begin\n" );
        szPathFilename = szPathVolatile + szFilename + ".raw";
        anLedsColorSequency = [];
        try:
            une = naoqitools.myGetProxy( 'UsageNoiseExtractor' );
            anLedsColorSequency = une.analyseSpeakSound( szPathFilename, int( rSampleLenSec * 1000 ), False );
        except BaseException, err:
            print( "ERR: sayAndCacheAndLight( '%s' ): err: %s" % ( strTextToSay, str( err ) ) );
            print( "ERR: sayAndCacheAndLight => trying old cpp version" );
            anLedsColorSequency = analyseSpeakSound( szPathFilename, rSampleLenSec * 1000 );
        print( "sayAndCacheAndLight: analyseSpeakSound - end - time: %fs\n" % float( time.time() - timeBegin ) );        
#        print( "anLedsColorSequency: %d samples: %s\n" % ( len( anLedsColorSequency ), str( anLedsColorSequency ) ) );
        
        print( "Writing file with %d peak samples (time: %d)\n" % ( len( anLedsColorSequency ), int( time.time() ) ) );
        #         struct.pack_into( "f"*len( anLedsColorSequency ), aBufFile, anLedsColorSequency[:] );
        for peakValue in anLedsColorSequency:
            aBufFile += struct.pack( "f", peakValue );
        try:
            file = open( szPathFilenamePeak, "wb" );
            file.write( aBufFile );
        except RuntimeError, err:
            print( "ERR: sayAndCacheAndLight( '%s' ): err: %s" % ( strTextToSay, str( err ) ) );
示例#3
0
    def launch( self, strPathAndFilenameXar, bWaitEnd = True, strHostName = 'localhost', bForceLoading = False, rTimeOutInSec = 60*60*24*7 ):
        "launch a behavior and return the framemanager id"
        "return [id, return_value]"
        "the id has no use if bWaitEnd is true"
        "the return_value is not set if not bWaitEnd"
        "rTimeOutInSec: on pourrait peut etre mettre un temps plus court par défaut, ca serait mieux pour les tests"
        nSimulatedThreadID = random.randint( 1,10000 );
        self.log( "INF: launch: Launching %s:%s, rTimeOutInSec=%5.3f (thread:%d)" % ( strHostName, strPathAndFilenameXar, rTimeOutInSec, nSimulatedThreadID ) );
        mem = naoqitools.myGetProxy( "ALMemory", strHostName = strHostName );
#        mem.raiseMicroEvent( self.getVarName_SoftCancel( strPathAndFilenameXar ), False ); # on ne le fait pas ici, car des fois on a un stoppe, avant de rentrer dans cette méthode, donc autant le lire ici... par contre on le reinitialisera apres le comportement !         
        if( not bWaitEnd ):
            mem.raiseMicroEvent( self.getVarName_SoftCancel( strPathAndFilenameXar ), False ); # cependant dans ce cas, vu qu'on ne sera pas mis au courant de la fin de ce behavior, on ne pourra pas le remettre a False a la fin, donc il faut le mettre la
        try:
            if( mem.getData( self.getVarName_SoftCancel( strPathAndFilenameXar ) ) == True ):
                self.log( "INF: launch: Launching %s:%s - end (soft canceled before loading)(thread:%d)" % ( strHostName, strPathAndFilenameXar, nSimulatedThreadID ) );
                mem.raiseMicroEvent( self.getVarName_SoftCancel( strPathAndFilenameXar ), False ); # on le réinit pour le prochain lancement
                return [None, None];
        except:
            pass # oui cette variable peut ne pas encore exister!
        nXarID = self.load( strPathAndFilenameXar, strHostName, bForceLoading );
        if( nXarID == -1 ):
            self.log( "ERR: launch: '%s:%s' load failure" % ( strHostName, strPathAndFilenameXar, nSimulatedThreadID ) );
            return -1;
        nNumLoadedXar = self.find( strPathAndFilenameXar, strHostName );
        if( self.aLoadedXar[nNumLoadedXar][3] == True ):
            self.log( "WNG: launch: already launched: '%s:%s' => waiting a little (thread:%d)" % ( strHostName, strPathAndFilenameXar, nSimulatedThreadID ) );
            time.sleep( 1.0 ); # attend une seconde et reteste
            nNumLoadedXar = self.find( strPathAndFilenameXar, strHostName ); # refresh nNumLoadedXar
            if( self.aLoadedXar[nNumLoadedXar][3] == True ):
                self.log( "ERR: launch: already launched: '%s:%s' => skipped (thread:%d)" % ( strHostName, strPathAndFilenameXar, nSimulatedThreadID ) );
                return -1;
        self.aLoadedXar[nNumLoadedXar][3] = True;            
        mem.insertData( self.getVarName_Results( strPathAndFilenameXar ), self.unknown_value );
        mem.insertData( self.getVarName_Cancel( strPathAndFilenameXar ), False );
        try:
            if( mem.getData( self.getVarName_SoftCancel( strPathAndFilenameXar ) ) == True ):
                # on a été interrompu pendant le chargement ou  la connection d'un machin!
                self.log( "INF: launch: Launching %s:%s - end (soft canceled before launching) (thread:%d)" % ( strHostName, strPathAndFilenameXar, nSimulatedThreadID ) );
                mem.raiseMicroEvent( self.getVarName_SoftCancel( strPathAndFilenameXar ), False ); # on le réinit pour le prochain lancement
                self.aLoadedXar[nNumLoadedXar][3] = False;
                return [None, None];
        except:
            pass # oui cette variable peut ne pas encore exister!
            
            
        fm = naoqitools.myGetProxy( "ALFrameManager", strHostName = strHostName );
        try:
            self.log( "DBG: launch: before fm.playBehavior(%s) (thread:%d)" % ( str( nXarID ), nSimulatedThreadID ) );
            fm.playBehavior( nXarID );
            self.log( "DBG: launch: after fm.playBehavior(%s) (thread:%d)" % ( str( nXarID ), nSimulatedThreadID ) );
        except BaseException, err:
            self.log( "ERR: launch: while launching playBehavior on '%s': %s (thread:%d)" % ( strPathAndFilenameXar, err, nSimulatedThreadID ) );
            # self.aLoadedXar[nNumLoadedXar][3] = False; # pas la peine: on va carrément l'invalider!            
            # erasing it for next one!
            self.invalidate( strPathAndFilenameXar, strHostName );
            return [None, None];
示例#4
0
def speechEmo( txt, strEmotion = "Standard", bWaitEnd = True, bPrecompute = False ):
    "talk using a specific emotion"
    "strEmotion, can be 'Standard', 'Happy', 'Sad', 'Loud', 'Proxi' or NAO"
    "Return -1 on error, or the ID of the speaking task"
    print( "speechEmo( '%s', strEmotion = '%s', bPrecompute = %s" % (txt, str( strEmotion ), str( bPrecompute ) ) );
    try:
        tts = naoqitools.myGetProxy( 'ALTextToSpeech' );
        ad = naoqitools.myGetProxy( 'ALAudioDevice' );
    except BaseException, err:
        print( "ERR: abcdk.speech.speechEmo: " + str( err ) );
        return -1;
示例#5
0
def speechEmo(txt, strEmotion="Standard", bWaitEnd=True, bPrecompute=False):
    "talk using a specific emotion"
    "strEmotion, can be 'Standard', 'Happy', 'Sad', 'Loud', 'Proxi' or NAO"
    "Return -1 on error, or the ID of the speaking task"
    print("speechEmo( '%s', strEmotion = '%s', bPrecompute = %s" %
          (txt, str(strEmotion), str(bPrecompute)))
    try:
        tts = naoqitools.myGetProxy('ALTextToSpeech')
        ad = naoqitools.myGetProxy('ALAudioDevice')
    except BaseException, err:
        print("ERR: abcdk.speech.speechEmo: " + str(err))
        return -1
示例#6
0
def setSpeakLanguage( nNumLang = getDefaultSpeakLanguage(), proxyTts = False ):
    "change the tts speak language"
    print( "SetSpeakLanguage to: %d" % nNumLang );
    if( not proxyTts ):
        proxyTts = naoqitools.myGetProxy( "ALTextToSpeech" );
    if( not proxyTts ):
        debug.debug( "ERR: setSpeakLanguage: can't connect to tts" );
        return;

    try:
        if( nNumLang == constants.LANG_FR ):
            proxyTts.loadVoicePreference( "NaoOfficialVoiceFrench" );
        elif ( nNumLang == constants.LANG_EN ):
            proxyTts.loadVoicePreference( "NaoOfficialVoiceEnglish" );
        elif ( nNumLang == constants.LANG_SP ):
            proxyTts.loadVoicePreference( "NaoOfficialVoiceSpanish" );
        elif ( nNumLang == constants.LANG_IT ):
            proxyTts.loadVoicePreference( "NaoOfficialVoiceItalian" );
        elif ( nNumLang == constants.LANG_GE ):
            proxyTts.loadVoicePreference( "NaoOfficialVoiceGerman" );
        elif ( nNumLang == constants.LANG_CH ):
            proxyTts.loadVoicePreference( "NaoOfficialVoiceChinese" );
        elif ( nNumLang == constants.LANG_PO ):
            proxyTts.loadVoicePreference( "NaoOfficialVoicePolish" );
        elif ( nNumLang == constants.LANG_KO ):
            proxyTts.loadVoicePreference( "NaoOfficialVoiceKorean" );            
        else:
            proxyTts.loadVoicePreference( "NaoOfficialVoiceEnglish" );
    except:
        print( "ERR: setSpeakLanguage: loadVoicePreference error" );
示例#7
0
def setBrainVuMeter(nLeftLevel,
                    nRightLevel,
                    rIntensity=1.0,
                    bDontWait=False,
                    bInverseSide=False):
    "use the brain leds as vu meter (left and right separated)"
    "the 0 is in the front of Nao"
    "nXxxLevel in [0,6] => 0: full lightoff; 6 => full litten"
    "bInverseSide: the 0 becomes at bottom of Nao"
    dcm = naoqitools.myGetProxy("DCM")
    rTime = 0.05
    riseTime = dcm.getTime(int(rTime * 1000))
    for i in range(6):
        if (not bInverseSide):
            strDeviceNameR = getBrainLedName(i)
            strDeviceNameL = getBrainLedName(11 - i)
        else:
            strDeviceNameR = getBrainLedName(5 - i)
            strDeviceNameL = getBrainLedName(11 - (5 - i))
        if (i < nLeftLevel):
            rIntL = rIntensity
        else:
            rIntL = 0.
        if (i < nRightLevel):
            rIntR = rIntensity
        else:
            rIntR = 0.
        dcm.set([strDeviceNameL, "Merge", [[float(rIntL), riseTime]]])
        # le float ici est ultra important car sinon venant de chorégraphe 1.0 => 1 (depuis les sliders de params)
        dcm.set([strDeviceNameR, "Merge", [[float(rIntR), riseTime]]])
    if (not bDontWait):
        time.sleep(rTime)
示例#8
0
def getNaoChestName():
    "get the nao name as stored in the rom chest"
    stm = naoqitools.myGetProxy("ALMemory")
    strNum = stm.getData("Device/DeviceList/ChestBoard/BodyNickName")
    if (strNum == 'Nao336' and getNaoNickName() == 'Astroboy'):
        strNum = 'Nao332'
    return strNum
示例#9
0
def getNbrMoveOrder( nThreshold = 0.06 ):
    "compute current joint moving by order"
    mem = naoqitools.myGetProxy( "ALMemory" );
    global global_getNbrMoveOrder_listKeyOrder;
    global global_getNbrMoveOrder_listKeyValue;
    global global_getNbrMoveOrder_listKeyStiffness;
    global global_getNbrMoveOrder_listOrder_prev;

    # first time: generate key list
    if( len( global_getNbrMoveOrder_listKeyOrder ) < 1 ):
        listJointName = getDcmBodyJointName();
        for strJointName in listJointName:
            global_getNbrMoveOrder_listKeyOrder.append( "Device/SubDeviceList/%s/Position/Actuator/Value" % strJointName );
            global_getNbrMoveOrder_listKeyValue.append( "Device/SubDeviceList/%s/Position/Sensor/Value" % strJointName );
            global_getNbrMoveOrder_listKeyStiffness.append( "Device/SubDeviceList/%s/Hardness/Actuator/Value" % strJointName );
            global_getNbrMoveOrder_listOrder_prev = mem.getListData( global_getNbrMoveOrder_listKeyOrder ); # init first time

    # get all values
    arOrder = mem.getListData( global_getNbrMoveOrder_listKeyOrder );
    arValue = mem.getListData( global_getNbrMoveOrder_listKeyValue );
    arStiffness= mem.getListData( global_getNbrMoveOrder_listKeyStiffness );

    nNbr = 0;
    for i in range( len( arOrder ) ):
        # a joint is moving if: pos is different from order, if order changed and if stiffness
        # we can have a big difference between order and value when no stiffness (position is out of range)
        if( ( abs( arOrder[i] - arValue[i] ) > nThreshold or abs( global_getNbrMoveOrder_listOrder_prev[i] - arOrder[i] ) > 0.01 ) and arStiffness[i] > 0.01 ):
            nNbr += 1;
#            debug.debug( "getNbrMoveOrder: difference on %s: order: %f; sensor: %f; stiffness: %f" % ( global_getNbrMoveOrder_listKeyValue[i], arOrder[i], arValue[i], arStiffness[i] ) );
    global_getNbrMoveOrder_listOrder_prev = arOrder;
    return nNbr;
示例#10
0
    def updateImg(self, strMessage, strFilenameImg=None, strLegend=None):
        "add an image and a sentence to a blog"
        "strFilenameImg: if None, take a picture using camera"
        "strLegend: if different of None or strLegend, add a legend below the image"

        if (strFilenameImg == None):
            print("INF: Blog.updateImg: Taking picture...\n")
            camToolBox = naoqitools.myGetProxy("ALVisionToolbox")
            camToolBox.halfPress()
            strFilenameImg = "/home/nao/" + filetools.getFilenameFromTime()
            camToolBox.post.takePictureRegularly(5.0, strFilenameImg, True,
                                                 "jpg", 2)
            # 2=> VGA
            time.sleep(2.2)
            # 1 second is not sufficient !
            camToolBox.stopTPR(strFilenameImg, "jpg")
            strFilenameImg = strFilenameImg + '.jpg'
            # coz takePictureRegularly add '.jpg' automatically
            print("INF: Blog.updateImg: Taking picture, file goes to '%s'\n" %
                  strFilenameImg)
        strExt = os.path.basename(strFilenameImg)
        strExt = strExt.split('.')
        strExt = strExt.pop()
        strFilename = filetools.getFilenameFromTime() + '.' + strExt
        strDest = self.strImgFolderAbs + strFilename
        filetools.copyFile(strFilenameImg, strDest)
        strTxt = "<table cellpadding=2><tr><td>%s<br></td></tr><tr><td><IMG SRC='%s' HEIGHT=192></td></tr>" % (
            strMessage, self.strImgFolderLocal + strFilename)
        if (strLegend != None and strLegend != ""):
            strTxt += "<tr><td><font size=-2><center>- %s -</center></font></td></tr>" % strLegend
        strTxt += "</table>"
        self.updateBlog(strTxt)
示例#11
0
def getHtmlPage( strHtmlAdress, bWaitAnswer = True, rTimeOutForAnswerInSec = 30.0, strSaveAs = None, bTryToUseCpp = True ):
    "return a web page, or "" on error (async or sync method, with optionnal timeout)"
    "Warning: don't put '&' in the html adress !"
    "rTimeOutForAnswerInSec: set to 0 for infinite"
    "strSaveAs: instead of returning a string, just save to a file and return True"
    # this method is ok but doesn't work on adress that doesn't finished with an extension (.ext)
#  req = urllib2.Request( strHtmlAdress );
#  print req.get_full_url();
# handle = urllib2.urlopen( req );
#  res = handle.read();
#  return res;

    # use cpp !
    if( bTryToUseCpp ):
        try:
            usage = naoqitools.myGetProxy( 'UsageTools' );
            # separate hostname and directories
            strHost, strFolder, strPageName = getHostFolderAndFile( strHtmlAdress );
    #        print( "altools.getHtmlPage: L'ADRESSE DU SITE: -%s-%s-%s-:" % (strHost, strFolder, strPageName) );
    #        strHost = strHost[len('http://'):]; # remove http: older version doesn't like it !
            if( strSaveAs != None ):
                if( bWaitAnswer ):
                    bRet = usage.getWebFile( strHost, strFolder + strPageName, strSaveAs, rTimeOutForAnswerInSec );
                    return bRet;
                else:
                    bRet = usage.post.getWebFile( strHost, strFolder + strPageName, strSaveAs, rTimeOutForAnswerInSec );
                    return "";
            strPageContents = usage.getWebPage( strHost, strFolder + strPageName, rTimeOutForAnswerInSec );
            if( strPageContents != "error" or ( rTimeOutForAnswerInSec > 0. and rTimeOutForAnswerInSec < 10.0 ) ): # if we put a short timeout, that's possible to have an empty response!
                return strPageContents; # else, we will use the normal method
            else:
                print( "WRN: getHtmlPage: CPP method error: return empty, trying other method" );
        except BaseException, err:
            print( "WRN: getHtmlPage: CPP method error: %s" % str( err ) );
            pass # use oldies version
示例#12
0
def setBrainVuMeter( nLeftLevel, nRightLevel, rIntensity = 1.0, bDontWait = False, bInverseSide = False ):
    "use the brain leds as vu meter (left and right separated)"
    "the 0 is in the front of Nao"
    "nXxxLevel in [0,6] => 0: full lightoff; 6 => full litten"
    "bInverseSide: the 0 becomes at bottom of Nao"
    dcm = naoqitools.myGetProxy( "DCM" );
    rTime = 0.05
    riseTime = dcm.getTime(int( rTime*1000 ));
    for i in range( 6 ):
        if( not bInverseSide ):
            strDeviceNameR = getBrainLedName( i );
            strDeviceNameL = getBrainLedName( 11-i );
        else:
            strDeviceNameR = getBrainLedName( 5-i );
            strDeviceNameL = getBrainLedName( 11-(5-i) );            
        if( i < nLeftLevel ):
            rIntL = rIntensity;
        else:
            rIntL = 0.;
        if( i < nRightLevel ):
            rIntR = rIntensity;
        else:
            rIntR = 0.;        
        dcm.set( [ strDeviceNameL, "Merge",  [[ float( rIntL ), riseTime ]] ] );         # le float ici est ultra important car sinon venant de chorégraphe 1.0 => 1 (depuis les sliders de params)
        dcm.set( [ strDeviceNameR, "Merge",  [[ float( rIntR ), riseTime ]] ] );
    if( not bDontWait ):
        time.sleep( rTime );
示例#13
0
 def updateImg( self, strMessage, strFilenameImg = None, strLegend = None ):
     "add an image and a sentence to a blog"
     "strFilenameImg: if None, take a picture using camera"
     "strLegend: if different of None or strLegend, add a legend below the image"
     
     if( strFilenameImg == None ):
         print( "INF: Blog.updateImg: Taking picture...\n" );
         camToolBox = naoqitools.myGetProxy( "ALVisionToolbox" );
         camToolBox.halfPress();
         strFilenameImg = "/home/nao/" + filetools.getFilenameFromTime();
         camToolBox.post.takePictureRegularly( 5.0, strFilenameImg, True, "jpg", 2 ); # 2=> VGA
         time.sleep( 2.2 ); # 1 second is not sufficient !
         camToolBox.stopTPR( strFilenameImg, "jpg" );
         strFilenameImg = strFilenameImg + '.jpg'; # coz takePictureRegularly add '.jpg' automatically
         print( "INF: Blog.updateImg: Taking picture, file goes to '%s'\n" % strFilenameImg );
     strExt = os.path.basename( strFilenameImg );
     strExt = strExt.split( '.' );
     strExt = strExt.pop();
     strFilename = filetools.getFilenameFromTime() + '.' + strExt;
     strDest = self.strImgFolderAbs + strFilename;
     filetools.copyFile( strFilenameImg, strDest );
     strTxt = "<table cellpadding=2><tr><td>%s<br></td></tr><tr><td><IMG SRC='%s' HEIGHT=192></td></tr>" % ( strMessage, self.strImgFolderLocal + strFilename );
     if( strLegend != None and strLegend != "" ):
         strTxt += "<tr><td><font size=-2><center>- %s -</center></font></td></tr>" % strLegend;
     strTxt += "</table>";
     self.updateBlog( strTxt );
示例#14
0
 def __init__(self, pstrModuleName, pstrFunctionName="", pstrTaskName=""):
     self.up = naoqitools.myGetProxy("UsageProfiler")
     self.strModuleName = pstrModuleName
     self.strFunctionName = pstrFunctionName
     self.strTaskName = pstrTaskName
     self.up.startMeasure(pstrModuleName, pstrFunctionName, pstrTaskName,
                          -1)
示例#15
0
def sayAndCache_internal( strTextToSay, bJustPrepare, bStoreToNonVolatilePath, bDirectPlay, nUseLang, bWaitEnd, bCalledFromSayAndCacheFromLight, strUseVoice ):
  "generate a text in a file, then read it, next time it will be directly played from that file"
  "bJustPrepare: render the text to a file, but don't play it now"
  "bStoreToNonVolatilePath: copy the generated file to a non volatile path (/usr/generatedvoices)"
  "nUseLang: if different of -1: speak with a specific languages (useful, when text are already generated: doesn't need to swap languages for nothing!"
  "strUseVoice: if different of None or default: use specific voice"
  "return the length of the text in seconds, or None if impossible"
  print( "sayAndCache_internal( '%s', bJustPrepare: %s, bStoreToNonVolatilePath: %s, bDirectPlay: %s, nUseLang: %d, bWaitEnd: %s, bCalledFromSayAndCacheFromLight: %s, strUseVoice: '%s' )" % ( strTextToSay, str( bJustPrepare ), str( bStoreToNonVolatilePath ), str( bDirectPlay ), nUseLang, str( bWaitEnd ), str( bCalledFromSayAndCacheFromLight ), str( strUseVoice ) ) );
  if( not config.bPrecomputeText ):
      print( "sayAndCache: disabled by configuration: bPrecomputeText is false" );
      if( bJustPrepare ):
          return None; # do nothing
      tts = naoqitools.myGetProxy( "ALTextToSpeech" );
      tts.say( strTextToSay );
      return None;
  print( "sayAndCache: FORCING DIRECT_PLAY CAR SINON C'EST BUGGE DANS LA VERSION COURANTE!");  
  bDirectPlay = True;
  
  if( strUseVoice == "default" ):
      strUseVoice = None;
  
  if( config.bRemoveDirectPlay ):
    print( "WRN: DISABLING DIRECT_PLAY SETTINGS for testing/temporary purpose" );
    bDirectPlay = False;  
  
  strTextToSay = assumeTextHasDefaultSettings( strTextToSay, nUseLang );
  szFilename = sayAndCache_getFilename( strTextToSay, nUseLang, strUseVoice );
  
  szPathVolatile = pathtools.getVolatilePath() + "generatedvoices" + pathtools.getDirectorySeparator();
  try:
    os.mkdir( szPathVolatile );
  except BaseException, err:
    pass
示例#16
0
 def getGroupLimits( listGroup, rCoef = 1., bOrderedByMinMax = False ):
   "get list of limits from a group name or a list of group"
   "rCoef: you can reduce the list by a ratio (0.5, will get halt the limits)"    
   "order default: list of min,max,acc for each joint"
   "order bOrderedByMinMax: list of min of each joint, then list of max of each joint..."
   listJoints = PoseLibrary.getListJoints( listGroup );
   listLimits = [];
   if( bOrderedByMinMax ):
       listLimits = [[],[],[]];
   motion = naoqitools.myGetProxy( 'ALMotion' );
   for strJointName in listJoints:
       limitForThisJoint = motion.getLimits( strJointName );
       # gestion 1.7.25 et rétrocompatibilité
       if( len( limitForThisJoint ) > 1 ):
           limitForThisJoint = limitForThisJoint[1];
       limitForThisJoint = limitForThisJoint[0];
       print( "getGroupLimits: %s => %s" % ( strJointName, str( limitForThisJoint ) ) );
       if( not bOrderedByMinMax ):
           limitForThisJoint[0] *= rCoef;
           limitForThisJoint[1] *= rCoef;
           limitForThisJoint[2] *= rCoef;            
           listLimits.append( limitForThisJoint );
       else:
           listLimits[0].append( limitForThisJoint[0]*rCoef );
           listLimits[1].append( limitForThisJoint[1]*rCoef );
           listLimits[2].append( limitForThisJoint[2]*rCoef );
   return listLimits;
示例#17
0
def runBehavior_BM( strBehavior, nTimeOut = 60 ):
    "launch a behavior on Nao, return "" if loading failed, or the 'naoqi' name of the behavior"
    "nTimeOut: temps maximum a attendre en secondes, -1 => pas d'attente (don't wait end)"
    abm = naoqitools.myGetProxy( "ALBehaviorManager" );
    strBeName = getLibraryName( strBehavior );
    
    # comme on ne peut le charger qu'une fois, on doit toujours le stopper avant (ca stoppera un précédent)
    try:
        print( "naolibrary.runBehavior: stopping previously running (%s)" % strBehavior );
        abm.stopBehavior( strBeName );
    except:
        pass # not previously running ... not a big deal
    try:
        print( "naolibrary.runBehavior: unloading previously loaded (%s)" % strBehavior );
        abm.unloadBehavior( self.strBehaviorName );
    except:
        pass # not previously running ... not a big deal
    
    try:
        print( "naolibrary.runBehavior: loading (%s)" % strBehavior );
        abm.loadBehavior( strBeName );
    except:
        print( "naolibrary.runBehavior: can't preload behavior, version >= 1.4.32 (%s) ?" % strBehavior );
    try:
        print( "naolibrary.runBehavior: running (%s)" % strBehavior );
        abm.runBehavior( strBeName );
        rStep = 0.2;
        rTotal = 0;
        while( abm.isBehaviorRunning( strBeName ) or rTotal > nTimeOut ):
            print( "naolibrary.runBehavior: waiting '%s'... %f..." % ( strBehavior, rStep ) );
            time.sleep( rStep );
            rTotal += rStep;
    except BaseException, err:
        debug.logToChoregraphe( "naolibrary.runBehavior: error occurs: " + str( err ) );
        strBeName = "";
示例#18
0
 def getGroupLimits(listGroup, rCoef=1., bOrderedByMinMax=False):
     "get list of limits from a group name or a list of group"
     "rCoef: you can reduce the list by a ratio (0.5, will get halt the limits)"
     "order default: list of min,max,acc for each joint"
     "order bOrderedByMinMax: list of min of each joint, then list of max of each joint..."
     listJoints = PoseLibrary.getListJoints(listGroup)
     listLimits = []
     if (bOrderedByMinMax):
         listLimits = [[], [], []]
     motion = naoqitools.myGetProxy('ALMotion')
     for strJointName in listJoints:
         limitForThisJoint = motion.getLimits(strJointName)
         # gestion 1.7.25 et rétrocompatibilité
         if (len(limitForThisJoint) > 1):
             limitForThisJoint = limitForThisJoint[1]
         limitForThisJoint = limitForThisJoint[0]
         print("getGroupLimits: %s => %s" %
               (strJointName, str(limitForThisJoint)))
         if (not bOrderedByMinMax):
             limitForThisJoint[0] *= rCoef
             limitForThisJoint[1] *= rCoef
             limitForThisJoint[2] *= rCoef
             listLimits.append(limitForThisJoint)
         else:
             listLimits[0].append(limitForThisJoint[0] * rCoef)
             listLimits[1].append(limitForThisJoint[1] * rCoef)
             listLimits[2].append(limitForThisJoint[2] * rCoef)
     return listLimits
def coloriseBox_ActivateOneBox_internal( strPathBoxName, bActivate = True ):
    "add an activation color to a single level box"
    global global_coloriseBox_ActivateOneBox_allBoxState;
    debug( "coloriseBox_ActivateOneBox_internal( '%s', %d )" % ( strPathBoxName, bActivate ) );

    global global_SectionCritique;
    while( global_SectionCritique.testandset() == False ):
        debug( "coloriseBox_ActivateOneBox_internal: locked" );
        time.sleep( 0.05 );

    nIdx = -1;
    for i in range( len( global_coloriseBox_ActivateOneBox_allBoxState ) ):
        if( global_coloriseBox_ActivateOneBox_allBoxState[i][0] == strPathBoxName ):
            nIdx = i;
            break;
    if( nIdx == -1 ):
        # first time
        nIdx = len( global_coloriseBox_ActivateOneBox_allBoxState );
        global_coloriseBox_ActivateOneBox_allBoxState.append( [ strPathBoxName, 0 ] );

    strBoxName = choregrapheBoxPathNameToBoxName( strPathBoxName );
    debug( "coloriseBox_ActivateOneBox_internal: '%s' last => '%s'" % ( strPathBoxName, strBoxName ) );
    if( bActivate ):
        global_coloriseBox_ActivateOneBox_allBoxState[nIdx][1] +=1;
        if( global_coloriseBox_ActivateOneBox_allBoxState[nIdx][1] == 1 ):
            # colorise it!
            controller = naoqitools.myGetProxy( "ALChoregrapheController" );
            try:
                controller.setBoxTitleColor( strBoxName, 0., 0., 1. );
            except BaseException, err:
                debug( "coloriseBox_ActivateOneBox_internal: Exception catched: %s" % err );
示例#20
0
def setSpeakLanguage(nNumLang=getDefaultSpeakLanguage(), proxyTts=False):
    "change the tts speak language"
    print("SetSpeakLanguage to: %d" % nNumLang)
    if (not proxyTts):
        proxyTts = naoqitools.myGetProxy("ALTextToSpeech")
    if (not proxyTts):
        debug("ERR: setSpeakLanguage: can't connect to tts")
        return

    try:
        if (nNumLang == constants.LANG_FR):
            proxyTts.loadVoicePreference("NaoOfficialVoiceFrench")
        elif (nNumLang == constants.LANG_EN):
            proxyTts.loadVoicePreference("NaoOfficialVoiceEnglish")
        elif (nNumLang == constants.LANG_SP):
            proxyTts.loadVoicePreference("NaoOfficialVoiceSpanish")
        elif (nNumLang == constants.LANG_IT):
            proxyTts.loadVoicePreference("NaoOfficialVoiceItalian")
        elif (nNumLang == constants.LANG_GE):
            proxyTts.loadVoicePreference("NaoOfficialVoiceGerman")
        elif (nNumLang == constants.LANG_CH):
            proxyTts.loadVoicePreference("NaoOfficialVoiceChinese")
        elif (nNumLang == constants.LANG_PO):
            proxyTts.loadVoicePreference("NaoOfficialVoicePolish")
        elif (nNumLang == constants.LANG_KO):
            proxyTts.loadVoicePreference("NaoOfficialVoiceKorean")
        else:
            proxyTts.loadVoicePreference("NaoOfficialVoiceEnglish")
    except:
        print("ERR: setSpeakLanguage: loadVoicePreference error")
示例#21
0
def getNaoChestName():
    "get the nao name as stored in the rom chest"
    stm = naoqitools.myGetProxy( "ALMemory" );
    strNum = stm.getData( "Device/DeviceList/ChestBoard/BodyNickName" );
    if( strNum == 'Nao336' and getNaoNickName() == 'Astroboy' ):
        strNum = 'Nao332';    
    return strNum;
示例#22
0
def playSound(strFilename, bWait=True, bDirectPlay=False, nSoundVolume=100):
    "Play a sound, return True if ok"
    "bDirectPlay: play it Now! (could fragilise system and video drivers"
    "nSoundVolume: if bDirectPlay is on, will play the sound with a specific volume (ndev)"

    print(
        "playSound( '%s', bWait = %s, bDirectPlay = %s, nSoundVolume = %d )" %
        (strFilename, str(bWait), str(bDirectPlay), nSoundVolume))

    if (config.bRemoveDirectPlay):
        print(
            "WRN: DISABLING_DIRECTPLAY SETTINGS for testing/temporary purpose")
        bDirectPlay = False

    try:
        # If strFilename has an absolute path, go ahead with this path !
        if strFilename.startswith(pathtools.getDirectorySeparator()):
            strSoundFile = strFilename
        else:
            strSoundFile = pathtools.getApplicationSharedPath(
            ) + "wav/0_work_free/" + strFilename
            if (not filetools.isFileExists(strSoundFile)):
                # then try another path
                strSoundFile = pathtools.getApplicationSharedPath(
                ) + "wav/1_validated/" + strFilename
            if (not filetools.isFileExists(strSoundFile)):
                # and another path
                strSoundFile = pathtools.getApplicationSharedPath(
                ) + "wav/0_work_copyright/" + strFilename
            if (not filetools.isFileExists(strSoundFile)):
                # and another path
                strSoundFile = pathtools.getApplicationSharedPath(
                ) + "wav/" + strFilename
            if (not filetools.isFileExists(strSoundFile)):
                # and another path
                strSoundFile = pathtools.getNaoqiPath(
                ) + "/share/naoqi/wav/" + strFilename
            if (not filetools.isFileExists(strSoundFile)):
                print("ERR: appu.playSound: can't find file '%s'" %
                      strFilename)
                return False

        analyseSound_pause(bWait)
        if (bDirectPlay):
            system.mySystemCall("aplay -q " + strSoundFile, bWait)
        else:
            global_proxyAudioPlayer = naoqitools.myGetProxy("ALAudioPlayer")
            if (global_proxyAudioPlayer == None):
                print(
                    "ERR: sound.playSound: can't find module 'ALAudioPlayer'")
            else:
                if (bWait):
                    global_proxyAudioPlayer.playFile(strSoundFile)
                else:
                    global_proxyAudioPlayer.post.playFile(strSoundFile)
        analyseSound_resume(bWait)
    except BaseException, err:
        debug.debug("playSound: ERR: " + str(err))
        print("errr: " + str(err))
示例#23
0
 def __init__(self, strJointName):
     self.strJointName = strJointName
     self.stm = naoqitools.myGetProxy("ALMemory")
     self.strStmJointNameSensor = "Device/SubDeviceList/" + strJointName + "/Position/Sensor/Value"
     self.strStmJointNameActuator = "Device/SubDeviceList/" + strJointName + "/Position/Actuator/Value"
     self.strStmJointNameStiffness = "Device/SubDeviceList/" + strJointName + "/Hardness/Actuator/Value"
     self.rDiffThreshold = 0.05
     self.reset()
示例#24
0
 def __init__( self, strJointName ):
   self.strJointName = strJointName;
   self.stm = naoqitools.myGetProxy( "ALMemory" );
   self.strStmJointNameSensor = "Device/SubDeviceList/" + strJointName + "/Position/Sensor/Value";
   self.strStmJointNameActuator = "Device/SubDeviceList/" + strJointName + "/Position/Actuator/Value";
   self.strStmJointNameStiffness    = "Device/SubDeviceList/" + strJointName + "/Hardness/Actuator/Value";
   self.rDiffThreshold = 0.05;
   self.reset();
示例#25
0
def analyseSound_resume( bWaitForResume ):
    "resume a previously infinite paused sound analyse"
    if( bWaitForResume ):
        try:
            analyser = naoqitools.myGetProxy( "UsageNoiseExtractor" );
            analyser.inhibitSoundAnalyse( 0 );
        except BaseException, err:
            debug.debug( "analyseSound_resume: ERR: " + str( err ) );
示例#26
0
def analyseSound_resume(bWaitForResume):
    "resume a previously infinite paused sound analyse"
    if (bWaitForResume):
        try:
            analyser = naoqitools.myGetProxy("UsageNoiseExtractor")
            analyser.inhibitSoundAnalyse(0)
        except BaseException, err:
            debug.debug("analyseSound_resume: ERR: " + str(err))
示例#27
0
 def stop( self, strPathAndFilenameXar, strHostName = 'localhost' ):
     "stop a running behavior"
     "return true if the behavior was really running"
     self.log( "INF: stop: Stopping %s:%s" % ( strHostName, strPathAndFilenameXar ) );
     nNumLoadedXar = self.find( strPathAndFilenameXar, strHostName );
     if( nNumLoadedXar == -1 ):
         self.log( "WNG: stop: xar '%s:%s' is not running (perhaps currently loading - in this case, it will be stopped at the end of the loading)" % ( strHostName, strPathAndFilenameXar) );  
         # don't return there !
     try:
         mem = naoqitools.myGetProxy( "ALMemory", strHostName = strHostName );
         mem.raiseMicroEvent( self.getVarName_SoftCancel( strPathAndFilenameXar ), True );
         # pour etre sur on stoppe aussi le comportement (ca rajoute un peu plus de brutalité dans un monde de bug)
         fm = naoqitools.myGetProxy( "ALFrameManager", strHostName = strHostName );
         fm.exitBehavior( self.aLoadedXar[nNumLoadedXar][2] ); # will send a stop # mettre ici deleteBehavior si on veut liberer de la memoire (l'exit est fait dedans)            
     except BaseException, err:
         self.log( "ERR: stop: deleting '%s:%s' failure (already stopped?): err: %s" % ( strHostName, strPathAndFilenameXar, str(err) ) );
         return False;
示例#28
0
 def isFinished( self, strPathAndFilenameXar, strHostName = 'localhost' ):
     mem = naoqitools.myGetProxy( "ALMemory", strHostName = strHostName );
     try:
         valueResults = mem.getData( self.getVarName_Results( strPathAndFilenameXar ) );
         valueCancel = mem.getData( self.getVarName_SoftCancel( strPathAndFilenameXar ) ); # des fois le comportement appellé ne recoit pas que le softcancel a été raisé, donc on n'ajoute ici un test.
     except BaseException, err:
         debug.debug( "WNG: XarLoader.isFinished: return value not found for '%s:%s' (%s) => true" % ( strHostName, strPathAndFilenameXar, err ) );
         return True;
 def importFromALMemory( self, strSpecificIP = "localhost" ):
     "import all variables from a (remote) ALMemory"
     try:
         mem = naoqitools.myGetProxy( "ALMemory", strSpecificIP );
         allVarName = mem.getData( "PersistentMemoryDataManager_all_vars" );
     except BaseException, err:
         debug.debug( "WRN: importFromALMemory: %s" % str( err ) );
         return;
示例#30
0
 def importFromALMemory(self, strSpecificIP="localhost"):
     "import all variables from a (remote) ALMemory"
     try:
         mem = naoqitools.myGetProxy("ALMemory", strSpecificIP)
         allVarName = mem.getData("PersistentMemoryDataManager_all_vars")
     except BaseException, err:
         debug.debug("WRN: importFromALMemory: %s" % str(err))
         return
示例#31
0
def circleLedsEyes( nColor, rTime, nNbrTurn ):
  # launch a leds animation using one color
  leds = naoqitools.myGetProxy( "ALLeds" );
  nNbrSegment = 8;
  for i in range( nNbrSegment*nNbrTurn ):
    leds.post.fadeRGB( "FaceLed%d" % (i%nNbrSegment) , nColor, rTime );
    leds.post.fadeRGB( "FaceLed%d" % (i%nNbrSegment) , 0x000000, rTime*1.25 );
    time.sleep( rTime*0.25 );
  time.sleep( rTime*0.5 ); # wait last time
示例#32
0
 def unloadAll( self ):
     "unload all previously loaded behavior (gain ram, or update of behavior or ...)"
     for behav in self.aLoadedXar:
         self.log( "INF: unloadAll: erasing %s:%s" % ( behav[0], behav[1] ) );
         try: 
             fm = naoqitools.myGetProxy( "ALFrameManager", strHostName = behav[0] );
             fm.exitBehavior( behav[2] );
         except BaseException, err:
             self.log( "ERR: unloadAll: %s!" % ( err ) );
示例#33
0
def setBrainLedsIntensity( rIntensity = 1.0, rTimeMs = 20, bDontWait = False ):
    "light on/off all the brain leds"
    dcm = naoqitools.myGetProxy( "DCM" );
    riseTime = dcm.getTime(rTimeMs);
    for i in range( 12 ):
        strDeviceName = getBrainLedName( i );
        dcm.set( [ strDeviceName, "Merge",  [[ rIntensity, riseTime ]] ] );    
    if( not bDontWait ):
        time.sleep( rTimeMs / 1000. );
示例#34
0
def getMasterVolume():
    "get nao master sound system volume (in %)"
    try:
        ad = naoqitools.myGetProxy( 'ALAudioDevice' );
        nVal = ad.getOutputVolume();
        debug.debug( "getMasterVolume: %d%%" % ( nVal ) );
        return nVal;
    except BaseException, err:
        print( "getMasterVolume: error '%s'" % str( err ) );
示例#35
0
def logToChoregraphe(strText):
    "print logs in the choregraphe debug print (like box.log)"
    import naoqitools
    debug("logToChoregraphe: '%s'" % strText)
    try:
        chor = naoqitools.myGetProxy("ALChoregraphe")
        chor.onPythonPrint(str(strText))
    except:
        pass
示例#36
0
def logToChoregraphe( strText ):
    "print logs in the choregraphe debug print (like box.log)"
    import naoqitools
    debug( "logToChoregraphe: '%s'" % strText );
    try:
        chor = naoqitools.myGetProxy( "ALChoregraphe" );
        chor.onPythonPrint( str( strText ) );
    except:
        pass
示例#37
0
def setBrainLedsIntensity(rIntensity=1.0, rTimeMs=20, bDontWait=False):
    "light on/off all the brain leds"
    dcm = naoqitools.myGetProxy("DCM")
    riseTime = dcm.getTime(rTimeMs)
    for i in range(12):
        strDeviceName = getBrainLedName(i)
        dcm.set([strDeviceName, "Merge", [[rIntensity, riseTime]]])
    if (not bDontWait):
        time.sleep(rTimeMs / 1000.)
示例#38
0
def playMusic( strFilename, bWait ):
  print( "appuPlaySound: avant cnx sur audioplayer (ca lagge?)" );
  #myAP = naoqitools.myGetProxy( "ALAudioPlayer" );
  print( "appuPlaySound: apres cnx sur audioplayer (ca lagge?)" );
  ap = naoqitools.myGetProxy( "ALAudioPlayer" );
  if( bWait ):
    ap.playFile( getApplicationSharedPath() + "/mp3/" + strFilename );
  else:
    ap.post.playFile( getApplicationSharedPath() + "/mp3/" + strFilename );
示例#39
0
def getMasterVolume():
    "get nao master sound system volume (in %)"
    try:
        ad = naoqitools.myGetProxy('ALAudioDevice')
        nVal = ad.getOutputVolume()
        debug.debug("getMasterVolume: %d%%" % (nVal))
        return nVal
    except BaseException, err:
        print("getMasterVolume: error '%s'" % str(err))
示例#40
0
def playMusic(strFilename, bWait):
    print("appuPlaySound: avant cnx sur audioplayer (ca lagge?)")
    #myAP = naoqitools.myGetProxy( "ALAudioPlayer" );
    print("appuPlaySound: apres cnx sur audioplayer (ca lagge?)")
    ap = naoqitools.myGetProxy("ALAudioPlayer")
    if (bWait):
        ap.playFile(getApplicationSharedPath() + "/mp3/" + strFilename)
    else:
        ap.post.playFile(getApplicationSharedPath() + "/mp3/" + strFilename)
示例#41
0
def setOneBrainIntensity( nLedIndex, rIntensity = 1.0, bDontWait = False ):
    "set one led beyond all the brain leds"
    "nLedIndex in [0,11]"
    dcm = naoqitools.myGetProxy( "DCM" );
    rTime = 0.05
    riseTime = dcm.getTime(int( rTime*1000 ));
    strDeviceName = getBrainLedName( nLedIndex );
    dcm.set( [ strDeviceName, "Merge",  [[ float( rIntensity ), riseTime ]] ] );         # le float ici est ultra important car sinon venant de chorégraphe 1.0 => 1 (depuis les sliders de params)
    if( not bDontWait ):
        time.sleep( rTime );
示例#42
0
def getCurrentMasterVolume():
    "get nao master sound system volume (in %)"
    "return 0 on error or problem (not on nao or ...)"
    try:
        ad = naoqitools.myGetProxy('ALAudioDevice')
        nVal = ad.getOutputVolume()
        debug.debug("getCurrentMasterVolume: %d" % (nVal))
        return nVal
    except BaseException, err:
        print("getCurrentMasterVolume: error '%s'" % str(err))
示例#43
0
def circleLedsEyes(nColor, rTime, nNbrTurn):
    # launch a leds animation using one color
    leds = naoqitools.myGetProxy("ALLeds")
    nNbrSegment = 8
    for i in range(nNbrSegment * nNbrTurn):
        leds.post.fadeRGB("FaceLed%d" % (i % nNbrSegment), nColor, rTime)
        leds.post.fadeRGB("FaceLed%d" % (i % nNbrSegment), 0x000000,
                          rTime * 1.25)
        time.sleep(rTime * 0.25)
    time.sleep(rTime * 0.5)
示例#44
0
 def ensureJointIsSoft(self):
     rNewValueHardness = self.stm.getData(self.strStmJointNameStiffness, 0)
     rMin = 0.30
     # below this value, arms couldn't move to the head level.
     if (rNewValueHardness > rMin):
         dcm = naoqitools.myGetProxy("DCM")
         dcm.set([
             "%s/Hardness/Actuator/Value" % self.strJointName, "Merge",
             [[rMin, dcm.getTime(20)]]
         ])
 def exportToALMemory( self ):
     "copy all variable to ALMemory"
     if( len( self.allData ) == 0 ):
         return;
     print( "INF: PersistentMemoryDataManager.exportToALMemory: exporting %d variable(s)" % len( self.allData ) );
     import naoqitools # module already unloaded when called from __del__
     mem = naoqitools.myGetProxy( "ALMemory" );
     if( mem == None ):
         print( "WRN: PersistentMemoryDataManager.exportToALMemory: can't connect to ALMemory" );
         return;
     while( self.mutexListData.testandset() == False ):
         print( "PersistentMemoryDataManager.exportToALMemory: locked" );
         time.sleep( 0.1 );            
     allVarName = [];
     mem = naoqitools.myGetProxy( "ALMemory" );
     for k, v in self.allData.iteritems():
         allVarName.append( v.strName );
         v.exportToALMemory();
     mem.insertData( "PersistentMemoryDataManager_all_vars", allVarName );
     self.mutexListData.unlock();
示例#46
0
def analyseSound_pause(bWaitForResume):
    "pause some running sound analyse"
    "bWaitForResume: True => pause until resume call, False => pause a little times (5sec?)"
    try:
        analyser = naoqitools.myGetProxy("UsageNoiseExtractor")
        nTime = 5
        if (bWaitForResume):
            nTime = -1
        analyser.inhibitSoundAnalyse(nTime)
    except BaseException, err:
        debug.debug("analyseSound_pause: ERR: " + str(err))
示例#47
0
def boxGetFrameNumber(strPathBoxName):
    "Get the frame number of the timeline of a box running in a timeline"
    "return None if the box isn't in a timeline"
    strTimelineName = boxGetParentName(strPathBoxName, 3)
    try:
        mem = naoqitools.myGetProxy("ALMemory")
        nVal = mem.getData(strTimelineName)
        return nVal
    except BaseException, err:
        #        print( "WRN: boxGetFrameNumber: error is: %s" % str( err ) );
        return None
 def increaseParent( self, strPathBoxName ):
     "called from children"
     fm = naoqitools.myGetProxy( "ALFrameManager" );
     nNbrFrame = fm.getMotionLength( strPathBoxName ) * fm.getTimelineFps( strPathBoxName );
     debug.debug( "INF: choregraphetools.FrameNumber.increaseParent( '%s' ), nNbrFrame: %d )" % ( strPathBoxName, nNbrFrame ) );
     strBoxParentName = boxGetParentName( strPathBoxName );
     try:
         self.animations_FrameNumber[strBoxParentName] += nNbrFrame;
     except:
         # not existing => create it
         self.animations_FrameNumber[strBoxParentName] = nNbrFrame;
def boxGetFrameNumber( strPathBoxName ):
    "Get the frame number of the timeline of a box running in a timeline"
    "return None if the box isn't in a timeline"
    strTimelineName = boxGetParentName( strPathBoxName, 3 );
    try:
        mem = naoqitools.myGetProxy( "ALMemory" );
        nVal = mem.getData( strTimelineName );
        return nVal;
    except BaseException, err:
#        print( "WRN: boxGetFrameNumber: error is: %s" % str( err ) );
        return None;
示例#50
0
def analyseSound_pause( bWaitForResume ):
    "pause some running sound analyse"
    "bWaitForResume: True => pause until resume call, False => pause a little times (5sec?)"
    try:
        analyser = naoqitools.myGetProxy( "UsageNoiseExtractor" );
        nTime = 5;
        if( bWaitForResume ):
            nTime = -1;
        analyser.inhibitSoundAnalyse( nTime );
    except BaseException, err:
        debug.debug( "analyseSound_pause: ERR: " + str( err ) );
示例#51
0
def circleLedsEars( rTime, nNbrTurn ):
  # launch a leds animation using one color
  leds = naoqitools.myGetProxy( "ALLeds" );
  nNbrSegment = 10;
  for i in range( nNbrSegment*nNbrTurn ):
    leds.post.fade( "LeftEarLed%d" % (i%nNbrSegment+1) , 1., rTime );
    leds.post.fade( "RightEarLed%d" % (i%nNbrSegment+1) , 1., rTime );
    leds.post.fade( "LeftEarLed%d" % (i%nNbrSegment+1) , 0., rTime*1.25 );
    leds.post.fade( "RightEarLed%d" % (i%nNbrSegment+1) , 0., rTime*1.25 );
    time.sleep( rTime*0.25 );
  time.sleep( rTime*0.5 ); # wait last time
示例#52
0
def setOneBrainIntensity(nLedIndex, rIntensity=1.0, bDontWait=False):
    "set one led beyond all the brain leds"
    "nLedIndex in [0,11]"
    dcm = naoqitools.myGetProxy("DCM")
    rTime = 0.05
    riseTime = dcm.getTime(int(rTime * 1000))
    strDeviceName = getBrainLedName(nLedIndex)
    dcm.set([strDeviceName, "Merge", [[float(rIntensity), riseTime]]])
    # le float ici est ultra important car sinon venant de chorégraphe 1.0 => 1 (depuis les sliders de params)
    if (not bDontWait):
        time.sleep(rTime)
示例#53
0
 def importFromALMemory(self, strName, strSpecificIP="localhost"):
     "read a value from a distant ALMemory on a robot"
     mem = naoqitools.myGetProxy("ALMemory", strSpecificIP)
     while (self.mutex.testandset() == False):
         print("PersistentMemoryData(%s).importFromALMemory: locked" %
               self.strName)
         time.sleep(0.1)
     self.strName = strName
     strKeyname = "behaviordata/" + self.strName
     self.allValue = mem.getData(strKeyname)
     self.mutex.unlock()
     print("self.allValue: " + str(self.allValue))
示例#54
0
 def exportToALMemory(self):
     "write all value of this variable to the ALMemory"
     mem = naoqitools.myGetProxy("ALMemory")
     while (self.mutex.testandset() == False):
         print("PersistentMemoryData(%s).exportToALMemory: locked" %
               self.strName)
         time.sleep(0.1)
     strKeyname = "behaviordata/" + self.strName
     #        print( "INF: PersistentMemoryData.exportToALMemory: exporting value for '%s' (%d value(s))" % ( self.strName, len( self.allValue ) ) );
     if (mem != None):
         mem.insertData(strKeyname, self.allValue)
     self.mutex.unlock()
示例#55
0
def waitBehaviorEnd_BM( strBehavior, nTimeOut = 60 ):
    "Wait until the end of a previously launched behavior"
    "return False if not finished, True if finished"
    "nTimeOut: temps maximum a attendre en secondes, -1 => pas d'attente (don't wait end)" 
    
    abm = naoqitools.myGetProxy( "ALBehaviorManager" );
    rStep = 0.2;
    rTotal = 0;
    while( abm.isBehaviorRunning( strBeName ) or rTotal > nTimeOut ):
        time.sleep( rStep );
        rTotal += rStep;
    return nTotal <= nTimeOut;