【问题标题】:Trouble Connecting to Google Cloud IoT via MQTT with Node.js使用 Node.js 通过 MQTT 连接到 Google Cloud IoT 时遇到问题
【发布时间】:2020-11-22 20:06:51
【问题描述】:

我正在尝试创建一个连接到 Google Cloud IoT Core 的 MQTT 客户端,但由于某种原因,它根本无法连接。这是我目前所拥有的

mqtt = require("mqtt")
fs = require("fs")
var jwt = require('jsonwebtoken');


const projectId = "my-project" 
const deviceId = "my-device" 
const registryId = "my-degistry" 
const region = "us-central1"
const algorithm = "RS256"
const privateKeyFile = "./rsa_private.pem"
const mqttBridgeHostname = "mqtt.googleapis.com"
const mqttBridgePort = 8883
const messageType = "events"

//The mqttClientId is a unique string that identifies a particular device. 
//For Google Cloud IoT Core, it must be the format below
const mqttClientId = `projects/${projectId}/locations/${region}/registries/${registryId}/devices/${deviceId}`
const mqttTopic = `/devices/${deviceId}/${messageType}`;


const createJwt = (projectId, privateKeyFile, algorithm) => {
    // Create a JWT to authenticate this device. The device will be disconnected
    // after the token expires, and will have to reconnect with a new token. The
    // audience field should always be set to the GCP project id.
    const token = {
      iat: parseInt(Date.now() / 1000),
      exp: parseInt(Date.now() / 1000) + 20 * 60, // 20 minutes
      aud: projectId,
    };
    const privateKey = fs.readFileSync(privateKeyFile);
    return jwt.sign(token, privateKey, {algorithm: algorithm});
  };

//Username field is ignored in Cloud IoT Core, but it must be set to something
//Password field sends a JWT (javascript web token) to authorize the device
//mqtts protocol causes library to connecti using SSL, which is required for IoT Core
const connectionArgs = {
    host: mqttBridgeHostname,
    port: mqttBridgePort,
    clientId: mqttClientId,
    username: "unused",
    password: createJwt(projectId, privateKeyFile, algorithm),
    protocol: "mqtts",
    secureProtocol: "TLSv1_2_method"
}

const client = mqtt.connect(connectionArgs)

client.on("connect", (connected)=>{
    console.log("Attempting to connect")
    if (!connected) {
        console.log("Client failed to connect")
    } else {
        console.log("Client is connected!")
    }
})

client.on("error", err => {
    console.log(err)
    setTimeout(( ()=> {  
        console.log('Terminating process')
        return process.kill(process.pid);
    }), 1000);
})

client.on("packetsend", (payload) => {
    console.log("Payload has been sent")
    return process.kill(process.pid)
})

client.on("packetreceive", packet => {
    console.log("Killing")
    //return process.kill(process.pid)
})

client.on("reconnect", ()=>{
    console.log("Attempting a reconnect")
    //return process.kill(process.pid)
})

client.on("close", ()=>{
    console.log("A disconnect occurred")
    // return process.kill(process.pid)
})

client.on("offline", () => {
    console.log("Client is offline")
    //return process.kill(process.pid)
})

当我尝试连接到服务器时,我没有收到任何错误。换句话说,一切似乎都在正确地进行身份验证,并且我没有收到任何错误消息,但客户端从未连接到云,而是在无休止的循环中反复尝试重新连接(这就是我包含代码以终止脚本的原因)。我尝试浏览 Google Cloud troubleshooting 页面,但似乎没有任何帮助。在按照指南建议的方式使用 Cloud SDK 时,我没有收到任何类型的错误消息或有用的信息。

我已经通过防火墙打开了端口 8883,以防万一这是问题,但似乎不是。

此代码基于 Google 的一些指南,并基于此处的 this 指南。我有一个注册表、项目和设备都设置了正确的 RSA 密钥。

所以我不确定如何继续!如果有任何其他信息对您有帮助,请告诉我。

谢谢。

【问题讨论】:

  • 我们很难诊断这个问题,因为您提到没有错误消息。您是否可以按照这个示例教程 [1] 并使用这个 Github 链接 [2](用于 node.js 代码)来模拟一个简单的 IOT 快速入门来隔离问题? [1] - cloud.google.com/iot/docs/quickstart#create_a_device_registry [2] - github.com/googleapis/nodejs-iot
  • 使用我之前评论中提到的链接,我设法使它工作。
  • 我会尝试示例教程并报告我的结果!
  • 所以我在您链接的 github 上下载了 package.json 和 cloudiot_mqtt_example_nodejs.js 文件,然后在安装依赖项后使用脚本运行以下命令: node cloudiot_mqtt_example_nodejs.js --registryId=mqttDeviceDemo / - -registryId=my-registry / --deviceId=my-device / --privateKeyFile=./rsa_private.pem / --algorithm=RS256 脚本所做的只是重复打印“关闭”。如果我正确使用了该示例,那么可能是身份验证问题?
  • 身份验证可能是其中的一个因素,但既然您提到日志中没有错误消息,那么真的很难说。尝试连接身份验证问题应该至少会给您一个错误。虽然没有可用的日志,但我建议您查看提供的 Github 链接中的示例代码并将其与您的代码进行比较。另一种方法是从示例代码开始并将其转换为您最初在此article 中遵循的内容。

标签: node.js mqtt iot google-cloud-iot


【解决方案1】:

我意识到,当我在 Google 控制台上创建项目和注册表时,我实际上打错了我想要的名称(我以为是“testmqtt”,但实际上是“tesmqtt”)。

因此,如果您遇到与此类似的问题,我建议您尝试以下方法:

  • 确保您的拼写正确。确保项目名称正确,注册表名称等。这听起来很愚蠢,但这些类型的错误会发生,所以先检查它们并没有什么坏处。否则你会像我一样想太多。
  • 查看此this 页面进行故障排除。此故障排除页面的两个部分可能对您有帮助。首先是尝试查看您是否可以真正连接到云。您可以通过在命令行上发出 openssl s_client -connect mqtt.googleapis.com:8883 之类的命令来测试是否能够建立连接。但是,您需要下载 openssl 才能发出该命令。您可以查看我刚刚链接的页面,了解有关测试连接的更多详细信息。您可以做的第二件事是通过使用 Google 的 sdk 运行 gcloud 命令来检查您是否具有身份验证。我链接的故障排除页面也有这方面的更多详细信息。
  • 这个quickstart guide 也特别有用。一开始导航可能会令人困惑,但最好的选择是理解它。
  • Google 的 github repository 也提供了一些很好的示例,说明如何建立与云 IoT 核心的 mqtt 连接。

下面 cmets 中的 DavidC 帮助我找到了其中一些有用的链接,因此应该归功于他。

【讨论】:

    【解决方案2】:

    除了我在评论部分提供的链接以及您发现的内容之外,一些用户使用项目编号而不是项目 ID,这会导致您遇到类似的问题。在进行故障排除时仔细检查配置中的所有内容确实值得。

    如果您需要对身份验证进行复习,也可以参考此link

    【讨论】: