意图处理程序因错误而失败:未定义缓冲区

如何解决意图处理程序因错误而失败:未定义缓冲区

我已经使用本地配送SDK构建了Google Smart Home Action,如以下文章所述:

我使用UDP进行设备发现,我的Google nest Hub可以成功扫描和检测笔记本电脑上运行的虚拟设备,以及下载本地应用程序的JS。

我的本​​地家庭SDK的配置如下-Local Home SDK Configuration

nest Hub执行我的应用处理程序的IDENTIFY意图时,我收到以下错误

[smarthome.DeviceManager] Intent handler Failed with error: Buffer is not defined

[smarthome.DeviceManager] Got a rejected promise Buffer is not defined 

这似乎是Node.JS错误,而不是本地SDK应用程序本身特有的错误。下面是我的本地应用程序的代码

/// <reference types="@google/local-home-sdk" />

import App = smarthome.App;
import Constants = smarthome.Constants;
import DataFlow = smarthome.DataFlow;
import Execute = smarthome.Execute;
import Intents = smarthome.Intents;
import IntentFlow = smarthome.IntentFlow;

const SERVER_PORT = 3388;

interface ILightParams {
  on?: boolean,brightness?: number
}

class LocalExecutionApp {

  constructor(private readonly app: App) { }

  identifyHandler(request: IntentFlow.IdentifyRequest):
      Promise<IntentFlow.IdentifyResponse> {
    console.log("IDENTIFY intent: " + JSON.stringify(request,null,2));

    const scanData = request.inputs[0].payload.device.udpScanData;
    console.log("SCANDATA: " + JSON.stringify(scanData));
    if (!scanData) {
      const err = new IntentFlow.HandlerError(request.requestId,'invalid_request','Invalid scan data');
      return Promise.reject(err);
    }

    const localdeviceid = Buffer.from(scanData.data,'hex');
    console.log("ScanData Local Device: " + localdeviceid);

    const response: IntentFlow.IdentifyResponse = {
      intent: Intents.IDENTIFY,requestId: request.requestId,payload: {
        device: {
          // id: localdeviceid.toString(),id: 'sample-device',verificationId: localdeviceid.toString(),}
      }
    };
    console.log("IDENTIFY response: " + JSON.stringify(response,2));

    return Promise.resolve(response);
  }

  executeHandler(request: IntentFlow.ExecuteRequest):
      Promise<IntentFlow.ExecuteResponse> {
    console.log("EXECUTE intent: " + JSON.stringify(request,2));

    const command = request.inputs[0].payload.commands[0];
    const execution = command.execution[0];
    const response = new Execute.Response.Builder()
      .setRequestId(request.requestId);

    const promises: Promise<void>[] = command.devices.map((device) => {
      console.log("Handling EXECUTE intent for device: " + JSON.stringify(device));

      // Convert execution params to a string for the local device
      const params = execution.params as ILightParams;
      const payload = this.getDataForCommand(execution.command,params);

      // Create a command to send over the local network
      const radioCommand = new DataFlow.HttpRequestData();
      radioCommand.requestId = request.requestId;
      radioCommand.deviceid = device.id;
      radioCommand.data = JSON.stringify(payload);
      radioCommand.dataType = 'application/json';
      radioCommand.port = SERVER_PORT;
      radioCommand.method = Constants.HttpOperation.POST;
      radioCommand.isSecure = false;

      console.log("Sending HTTP request to the smart home device:",payload);

      return this.app.getDeviceManager()
        .send(radioCommand)
        .then(() => {
          const state = {online: true};
          response.setSuccessstate(device.id,Object.assign(state,params));
          console.log(`Command successfully sent to ${device.id}`);
        })
        .catch((e: IntentFlow.HandlerError) => {
          e.errorCode = e.errorCode || 'invalid_request';
          response.setErrorState(device.id,e.errorCode);
          console.error('An error occurred sending the command',e.errorCode);
        });
    });

    return Promise.all(promises)
      .then(() => {
        return response.build();
      })
      .catch((e) => {
        const err = new IntentFlow.HandlerError(request.requestId,e.message);
        return Promise.reject(err);
      });
  }

  /**
   * Convert execution request into a local device command
   */
  getDataForCommand(command: string,params: ILightParams): unkNown {
    switch (command) {
      case 'action.devices.commands.OnOff':
        return {
          on: params.on ? true : false
        };
      default:
        console.error('UnkNown command',command);
        return {};
    }
  }
}

const localHomeSdk = new App('1.0.0');
const localApp = new LocalExecutionApp(localHomeSdk);
localHomeSdk
  .onIdentify(localApp.identifyHandler.bind(localApp))
  .onExecute(localApp.executeHandler.bind(localApp))
  .listen()
  .then(() => console.log('Ready'))
  .catch((e: Error) => console.error(e));

任何对为什么会发生此错误的见解都将受到赞赏。

干杯。

解决方法

在评论中重新发布答案:

Buffer不是浏览器环境中直接支持的类型。您可以尝试在网络浏览器的开发者控制台中运行类似x = new Buffer()之类的内容来自己查看。

要支持Buffer之类的类,可以使用Webpack之类的捆绑工具。在官方示例中,您可以看到example Webpack configuration。也可以使用其他捆绑工具,示例可以在official Local Home scaffolding tool中找到,也可以直接使用npm init命令来调用。

npm init @google/local-home-app app/ --bundler webpack
npm init @google/local-home-app app/ --bundler rollup
npm init @google/local-home-app app/ --bundler parcel

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?