使用Node.js通过MQTT连接到Google Cloud IoT时出现问题

亚历克斯·斯奈德

我正在尝试创建一个将连接到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故障排除页面,但似乎没有任何帮助。使用Cloud SDK时,如建议的指南所示,我没有收到任何类型的错误消息或有用的信息。

我已经通过防火墙打开了8883端口,以防万一这是问题所在,但事实并非如此。

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

所以我不太确定如何进行!如果还有其他有用的信息,请告诉我。

谢谢。

达维奇

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

如果您需要有关身份验证的复习,也可以参考此链接

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用 Spring Boot 将 Cloud Run Application 连接到 Cloud SQL 时出现问题

使用Cloud Functions for Firebase和@ google-cloud / storage删除图像时出现问题

为什么我无法通过 MQTT 连接到 Google Cloud IOT Core 中的设备?

尝试使用Google Cloud运行BigQuery示例,但出现问题

Cloud Composer加载DAG连接到Cloud SQL时出现问题

使用C#连接到Oracle时出现问题

从App Engine Flexible连接到Cloud SQL时出现问题

连接 2 个外部 IP Google Cloud Platform 时出现问题

Node JS - 安装插件时 npm 出现问题

Express / Node / Cloud9-提供静态文件时出现问题

使用ring / compojure连接Clojure nREPL时出现问题

从使用emscripten编译的c ++连接websocket时出现问题

使用方法建立连接时出现问题

使用Google云端存储库时出现问题

在Google磁盘API中使用凭据时出现问题

使用Google脚本解析XML时,getChild出现问题

使用BeautifulSoup检索Google Scholar结果时出现问题

使用Google Calendar API时出现问题

使用express.js渲染视图时出现问题

Google Cloud Platform管道/容器构建器在Spring Boot Java Application中使用COPY或ADD命令构建docker映像时出现问题

使用 Debezium 通过 SSL 连接到 Cloud SQL 时出错

使用Electron编译node.js版本时出现问题

使用Q同步Node.js中的Promise时出现问题

使用Node.js / Express时出现问题,表示未安装

node.js:使用系统调用将文件写入/ tmp目录时出现问题

Cloud Data Fusion在使用HTTP源读取CSV导出时出现问题

将我的功能部署到Google Cloud时出现问题

使用JDBC连接到SQL Server 2012时出现问题

使用python和selenium连接到phantomJs Webdriver时出现问题