【问题标题】:Azure IoT Edge node SDK invokeDeviceMethod not working asynchronouslyAzure IoT Edge 节点 SDK invokeDeviceMethod 无法异步工作
【发布时间】:2020-02-04 20:13:46
【问题描述】:

我正在尝试以异步方式返回直接方法调用的结果。

我试过了:

var client = Client.fromConnectionString(process.env.AZ_IOT_CONNECTION_STRING);
var methodParams = {
  methodName: "method",
  payload: 10, // Number of seconds.
  responseTimeoutInSeconds: 60
};

// Call the direct method on your device using the defined parameters.
client.invokeDeviceMethod(
  req.params.deviceId,
  methodParams,
  (err, result) => {
    if (err) {
      console.error(err);
    } else {
      console.log("success");
    }
  }
);

在设备上:

const method = async (request, response) => {
  const longProcess = () => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve();
      }, 5000);
    });
  };

  try {
    await longProcess();
    response.send(200, `success`);
  } catch (error) {
    response.send(500, `Error: ${error}:`);
  }
};


client.onDeviceMethod("method", method);

预期:5秒后返回成功

实际:返回 "BadRequest" "errorCode :400027" 但方法执行正确。

【问题讨论】:

    标签: javascript node.js azure azure-iot-hub azure-iot-edge


    【解决方案1】:

    请使用 promise 函数而不是回调函数:

    async deviceSyncInvoke(deviceID: string, methodName: string, data:any, responseTimeoutInSeconds?: number): Promise<[number, any]> {
            try{
                if (!this.client){
                    await this.openClient();
                }
    
                const methodParam: DeviceMethodParams = {
                    methodName: methodName,
                    payload: JSON.stringify(data)
                }
    
                // The minimum and maximum values for responseTimeoutInSeconds are 5 and 300 seconds.
                //If timeout is not provided, it the default value of 30 seconds is used
                if (responseTimeoutInSeconds && responseTimeoutInSeconds !== undefined) {
                    methodParam.responseTimeoutInSeconds = responseTimeoutInSeconds;
                }
    
    
                const res: ResultWithIncomingMessage<any> = await this.client.invokeDeviceMethod(deviceID, methodParam);
                if (res.message.statusCode == undefined || res.message.statusCode > 299) {
                    throw new Error(`statusCode: ` + res.message.statusCode + `statusMessage: ` + res.message.statusMessage);
                }
    
                return [2001, "message invoking command with res: " + res];
            }catch(err) {
                return [5000, "error deviceSyncInvoke: " + err];
            }
        }
    

    【讨论】:

    • 这不能回答问题,这取决于您使用的 SDK 版本。你只是在挑选无关紧要的东西。
    猜你喜欢
    • 2019-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-04
    • 1970-01-01
    • 2014-11-21
    • 1970-01-01
    相关资源
    最近更新 更多