You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从Flask服务器向Choregraphe传输JSON控制NAO机器人失败求助

Flask向NAO机器人Choregraphe发送随机数并播报失败的排查与修复

我尝试编写代码实现从Flask服务器向Choregraphe发送数据,生成1-3的随机数并让NAO机器人播报对应数字,但未能成功。以下是我使用的代码:

Flask端发送数据代码

import http.client
import json
import random
from flask import Flask, request

app = Flask(__name__)

@app.route('/')
def index():
    IP = "10.0.0.23"  # 我的机器人IP地址
    PORT = 9559

    number = random.randint(1, 3)

    data = json.dumps({"number": number})

    # 连接Choregraphe
    conn = http.client.HTTPConnection(IP, PORT)

    # 发送数据到Choregraphe
    headers = { "Content-Type": "application/json" }
    conn.request("POST", "/module/ALMemory/value/ExampleKey", data, headers)

    return "Data sent to Choregraphe: " + data

if __name__ == '__main__':
    app.run()

Choregraphe端Python脚本盒代码

def onInput_onStart(self, p):
    # 连接ALMemory
    memory = ALProxy("ALMemory")

    # 读取"ExampleKey"对应的数值
    data = memory.getData("ExampleKey")

    # 将JSON字符串解析为字典
    data = json.loads(data)

    # 获取字典中的"number"值
    number = data["number"]

   if number == 1:
     text = "one"
   elif number == 2:
     text = "two"
  else
    text = "three"


  tts = ALProxy("ALTextToSpeech", "10.0.0.23", 9559)
  tts.say(text)

问题排查与修复方案

  1. 语法错误与依赖缺失

    • Choregraphe脚本未导入json模块,json.loads会直接报错,需在脚本开头添加import json。
    • else语句缺少冒号,属于基础语法错误,修正为else:。
  2. ALMemory接口请求方法错误
    ALMemory的HTTP接口设置值需使用PUT方法,原代码用POST无法正确写入数据。修改Flask中的请求方法:

    conn.request("PUT", "/module/ALMemory/value/ExampleKey", data, headers)
    
  3. 数据格式与解析问题
    直接存入JSON字符串会增加解析复杂度,可简化流程:

    • Flask端直接发送数字字符串,无需JSON序列化:
      number = random.randint(1, 3)
      data = str(number)
      headers = { "Content-Type": "text/plain" }
      conn.request("PUT", "/module/ALMemory/value/ExampleKey", data, headers)
      
    • Choregraphe端去掉JSON解析,直接转换为整数:
      data = memory.getData("ExampleKey")
      number = int(data)
      
  4. 脚本执行时机问题
    原脚本仅在启动时执行一次,若Flask发送数据晚于脚本启动,会读取到旧值或空值。改为订阅ExampleKey的变化事件,数据更新时自动触发播报:

    import json
    from naoqi import ALProxy
    
    def onLoad(self):
        self.memory = ALProxy("ALMemory")
        # 订阅数据变化事件
        self.subscriber = self.memory.subscriber("ExampleKey")
        self.subscriber.signal.connect(self.onNumberReceived)
        self.tts = ALProxy("ALTextToSpeech", "10.0.0.23", 9559)
    
    def onNumberReceived(self, value):
        number = int(value)
        text = "one" if number == 1 else "two" if number == 2 else "three"
        self.tts.say(text)
    

内容的提问来源于stack exchange,提问作者Tolis Tolis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 16:16:06