停止用Python脚本控制NAO机器人触摸他的头

2024-10-02 12:33:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我的问题如下。我在Python中有一个脚本被执行,这样机器人在执行停止之前不会停止执行各种操作,但是出于安全原因(万一机器人疯了,想要杀死我们所有人),我需要添加这个指令,以防按下它头部的触摸传感器来停止它。在

我读了一些关于ALTouch模块的文章,它可以生成TouchChanged()模块,但它作用于所有的传感器(包括运动),而不仅仅是头部的触摸传感器。在

欢迎任何想法或相关文件。在

以下是我的一些代码:

class SoundProcessingModule(object):

    def __init__( self, app):

        ttsProxy.say("Touch my head at any moment to stop me")

        super(SoundProcessingModule, self).__init__()
        app.start()
        session = app.session

        self.audio_service = session.service("ALAudioDevice")
        self.isProcessingDone = False
        self.nbOfFramesToProcess = 100
        self.framesCount=0
        self.micFront = []
        self.module_name = "SoundProcessingModule"

    def startProcessing(self):
        self.audio_service.setClientPreferences(self.module_name, 16000, 3, 0)
        self.audio_service.subscribe(self.module_name)

        while self.isProcessingDone == False:
            time.sleep(1)

        self.audio_service.unsubscribe(self.module_name)

    def processRemote(self, nbOfChannels, nbOfSamplesByChannel, timeStamp, inputBuffer):
        #ReadyToDance
        postureProxy.goToPosture("StandInit", 0.5)

        self.framesCount = self.framesCount + 1
        if (self.framesCount <= self.nbOfFramesToProcess):
            print(self.framesCount)
            self.micFront=self.convertStr2SignedInt(inputBuffer)
            rmsMicFront = self.calcRMSLevel(self.micFront)
            print ("Nivel RMS del microfono frontal = " + str(rmsMicFront))
            rmsArray.insert(self.framesCount-1,rmsMicFront)

            #-40 y -30
            if promedio >= -40 and promedio <= -30 :
                #Some dance moves    

            #-29 y -20
            elif promedio >= -29 and promedio <= -20:
                #Some dance moves

            #-19 y -11
            elif promedio >= -19 and promedio <= -11:
                #Some dance moves

        else :
            self.isProcessingDone=True
            #Plot RMS signal
            plt.plot(rmsArray)
            plt.ylabel('RMS')
            plt.xlabel('Frames')
            plt.text(np.argmin(rmsArray), np.min(rmsArray) - 0.1, u'Mínimo', fontsize=10, horizontalalignment='center',
                     verticalalignment='center')  
            plt.text(np.argmax(rmsArray), np.max(rmsArray) + 0.1, u'Máximo', fontsize=10, horizontalalignment='center',
                     verticalalignment='center')  
            print("")
            print ("El promedio total del sonido es: " + str(np.mean(rmsArray)))
            print("El maximo total del sonido es: " + str(np.max(rmsArray)))
            print("El minimo total del sonido es: " + str(np.min(rmsArray)))
            plt.show()
            postureProxy.goToPosture("Sit", 1.0)

    def calcRMSLevel(self,data) :
        rms = 20 * np.log10( np.sqrt( np.sum( np.power(data,2) / len(data)  )))
        return rms

    def convertStr2SignedInt(self, data) :
        signedData=[]
        ind=0;
        for i in range (0,len(data)/2) :
            signedData.append(data[ind]+data[ind+1]*256)
            ind=ind+2

        for i in range (0,len(signedData)) :
            if signedData[i]>=32768 :
                signedData[i]=signedData[i]-65536

        for i in range (0,len(signedData)) :
            signedData[i]=signedData[i]/32768.0

        return signedData


def StiffnessOn(proxy):
    # We use the "Body" name to signify the collection of all joints
    pNames = "Body"
    pStiffnessLists = 1.0
    pTimeLists = 1.0
    proxy.stiffnessInterpolation(pNames, pStiffnessLists, pTimeLists)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    #Es necesario estar al pendiente de la IP del robot para moficarla
    parser.add_argument("--ip", type=str, default="nao.local",
                        help="Robot IP address. On robot or Local Naoqi: use '127.0.0.1'.")
    parser.add_argument("--port", type=int, default=9559,
                        help="Naoqi port number")

    args = parser.parse_args()
        # Inicializamos proxys.
    try:
        proxy = ALProxy("ALMotion", "nao.local", 9559)
    except Exception, e:
        print "Could not create proxy to ALMotion"
        print "Error was: ", e

    try:
        postureProxy = ALProxy("ALRobotPosture", "nao.local", 9559)
    except Exception, e:
        print "Could not create proxy to ALRobotPosture"
        print "Error was: ", e

    try:
        ttsProxy = ALProxy("ALTextToSpeech" , "nao.local", 9559)
    except Exception, e:
        print "Could not create proxy to ALTextToSpeech"
        print "Error was: ", e

    try:
        memory = ALProxy("ALMemory" , "nao.local", 9559)
    except Exception, e:
        print "Could not create proxy to ALMemory"
        print "Error was: ", e

    try:
        connection_url = "tcp://" + args.ip + ":" + str(args.port)
        app = qi.Application(["SoundProcessingModule", "--qi-url=" + connection_url])
    except RuntimeError:
        print ("Can't connect to Naoqi at ip \"" + args.ip + "\" on port " + str(args.port) +".\n"
               "Please check your script arguments. Run with -h option for help.")
        sys.exit(1)

    MySoundProcessingModule = SoundProcessingModule(app)
    app.session.registerService("SoundProcessingModule", MySoundProcessingModule)
    MySoundProcessingModule.startProcessing()

机器人根据前麦克风捕捉到的RMS电平跳舞,但我需要在任何时候当头部传感器(或任何传感器)被触碰时停止它。在


Tags: tonameselfappdatadefnpproxy
1条回答
网友
1楼 · 发布于 2024-10-02 12:33:13

不必订阅TouchChanged,您只可以通过3个事件订阅头部(对于3个触觉按钮):

  • 正面触碰
  • 中间触碰
  • 后部触碰

当触摸开始时,它们将以值1升高,当触摸结束时,值为0。所以你需要过滤,并且只在值为1时停止你的舞蹈。在

相关问题 更多 >

    热门问题