Google IOT Core连接设备MQTT客户端

4 篇文章 1 订阅

实现Google IOT Core核心连接到物联网设备(MQTT)具体过程:

  1. 通过函数API创建返回公/私钥值,保存到云存储;(上一篇有详细讲解如何调用API公/私钥)。
  2. 读取云存储公/私钥,判断是否注册以及是否过期,如果过期,再次注册API公/私钥。
  3. 检查公/私钥值是否正确导入项目,RSA256或RSA_X256。
  4. 私钥创建JWT身份验证。
  5. 通过JWT以及私钥串与设备名连接到MQTT。

一:导入项目mqtt包(Nodejs)

1.package.json

"jsonwebtoken": "^8.5.1",
 "mqtt": "^3.0.0",

2.mqtt.js

'use strict';

// [START iot_mqtt_include]
const fs = require('fs');
const jwt = require('jsonwebtoken');
const mqtt = require('mqtt');
// [END iot_mqtt_include]
// The initial backoff time after a disconnection occurs, in seconds.
const MINIMUM_BACKOFF_TIME = 1;

// The maximum backoff time before giving up, in seconds.
const MAXIMUM_BACKOFF_TIME = 32;

// Whether to wait with exponential backoff before publishing.
let shouldBackoff = false;

// The current backoff time.
let backoffTime = 1;

// Whether an asynchronous publish chain is in progress.
let publishChainInProgress = false;

console.log('Google Cloud IoT Core MQTT example.');

const deviceId = "你的设备名";
const registryId = "注册表";
const projectId = "项目名";
const region = "us-central1";//区域
const algorithm = "RS256";//密钥类型
const privateKeyFile = "rsa_private.pem";//文件
const mqttBridgeHostname = "mqtt.googleapis.com";
const mqttBridgePort = "443";//或者8883(国外)
const messageType = "events";
const numMessages = "50";
const tokenExpMins = "20";
const gatewayId = "my-region-001";//网关id
const clientDuration = "6000";

//创建JWT函数
const createJwt = (projectId, privateKeyFile, algorithm) => {

    const token = {
        iat: parseInt(Date.now() / 1000),
        exp: parseInt(Date.now() / 1000) + 20 * 60, // 20 minutes
        aud: projectId,
    };
    const privateKey = fs.readFileSync(privateKeyFile);
    console.log("privateKey:",privateKey.toString());
    console.log("createJwt yes:",jwt.sign(token, privateKey, {algorithm: algorithm}));
    return jwt.sign(token, privateKey, {algorithm: algorithm});

};

3.MQTT连接的函数实现:

//mqtt的连接
const mqttDeviceDemo = (
    deviceId,
    registryId,
    projectId,
    region,
    algorithm,
    privateKeyFile,
    mqttBridgeHostname,
    mqttBridgePort,
    messageType,
    numMessages
) => {
    // The mqttClientId is a unique string that identifies this device. For Google
    // Cloud IoT Core, it must be in the format below.
    const mqttClientId = `projects/${projectId}/locations/${region}/registries/${registryId}/devices/${deviceId}`;
    console.log("000++",mqttClientId);
    const connectionArgs = {
        host: mqttBridgeHostname,
        port: mqttBridgePort,
        clientId: mqttClientId,
        username: 'unused',
        password: createJwt(projectId, privateKeyFile, algorithm),
        protocol: 'mqtts',
        secureProtocol: 'TLSv1_2_method',
    };
    console.log("001++",connectionArgs);

    // Create a client, and connect to the Google MQTT bridge.
    const iatTime = parseInt(Date.now() / 1000);
    const client = mqtt.connect(connectionArgs);

    client.subscribe(`/devices/${deviceId}/config`, {qos: 1});
    client.subscribe(`/devices/${deviceId}/commands/#`, {qos: 0});
    console.log('client002======',client);
    const mqttTopic = `/devices/${deviceId}/${messageType}`;
    console.log('mqttTopic003======',mqttTopic);
    client.on('connect', success => {
        console.log('connect004');
        if (!success) {
            console.log('Client not connected005...');
        } else if (!publishChainInProgress) {
            console.log('connected...666999999');
            //publishAsync(mqttTopic, client, iatTime, 1, numMessages, connectionArgs);
        }
    });

    client.on('close', () => {
        console.log('close');
        shouldBackoff = true;
    });

    client.on('error', err => {
        console.log('error', err);
    });

    client.on('message', (topic, message) => {
        let messageStr = 'Message received: ';
        if (topic === `/devices/${deviceId}/config`) {
            messageStr = 'Config message received: ';
        } else if (topic.startsWith(`/devices/${deviceId}/commands`)) {
            messageStr = 'Command message received: ';
        }

        messageStr += Buffer.from(message, 'base64').toString('ascii');
        console.log(messageStr);
    });

    client.on('packetsend', () => {
        // Note: logging packet send is very verbose
    });

    // Once all of the messages have been published, the connection to Google Cloud
    // IoT will be closed and the process will exit. See the publishAsync method.
    // [END iot_mqtt_run]
};

4.调用云函数功能:

exports.tmwrilmqtt_conent = async (req,res) => {

    mqttDeviceDemo(
        deviceId,
        registryId,
        projectId,
        region,
        algorithm,
        privateKeyFile,
        mqttBridgeHostname,
        mqttBridgePort,
        messageType,
        numMessages
    );
}

二:部署到Google Function云函数,可通过PostMan进行调试。

1.cd~ 项目名
2.gcloud functions deploy (函数的名称) --runtime nodejs8 --trigger-http

三:调试样本:

在这里插入图片描述在这里插入图片描述

四:通过命令发布消息到设备

const SendDevice = async(
    projectId,
    cloudRegion,
    registryId,
    deviceId,
    sendevicedata,
    res
) => {
    const iot = require('@google-cloud/iot');
    const client = new iot.v1.DeviceManagerClient({
        // optional auth parameters.
    });
    const binaryData = Buffer.from(sendevicedata).toString('base64');
    const formattedName = client.devicePath(projectId,cloudRegion,registryId,deviceId);
   // const binaryData = Buffer.from('wo shi ming ling device 001');
    const request = {
        name:formattedName,
        binaryData:binaryData,
    };
    client.sendCommandToDevice(request)
        .then(responses => {
            const response = responses[0];
            res.send(response);
            // doThingsWith(response)
        })
        .catch(err => {
            console.error(err);
            res.send(err);
        });
}

在这里插入图片描述
在这里插入图片描述

五:MQTT连接设备错误排除:

  • Error: Connection refused: Not authorized at

解决办法:仔细检查客户端的私钥Key,是否是RSA256官方创建的,并不是带X509。
在这里插入图片描述

MQTT连接Google IOT Core设备源码

MQTT连接设备讲解到此为止,如果依然还有不懂的,可以留言咨询,谢谢希望能帮助到您!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: MQTT客户端 for Window是一种在Windows操作系统上运行的MQTT协议的客户端软件。MQTT(Message Queuing Telemetry Transport)是一种轻量级的、开放的、基于发布/订阅的消息传输协议,常用于物联网(IoT)应用中。 MQTT客户端 for Window可以通过与MQTT代理服务器进行通信,实现设备之间的数据传输和通信。它具有以下特点: 1. 轻量级:MQTT协议非常轻量级,可以在带宽较低和计算能力有限的设备上运行,而不会造成过多的资源占用。 2. 简单易用:MQTT客户端 for Window提供了友好的用户界面,使用户可以方便地创建、配置和管理MQTT连接和订阅。 3. 灵活的发布/订阅模式:MQTT客户端 for Window基于发布/订阅模式,使得设备可以订阅感兴趣的主题(Topic),并接收来自其他设备或服务器的相应消息。 4. 可扩展性:MQTT客户端 for Window支持多种设备和平台,可以与各种硬件设备和操作系统兼容,具有很好的可扩展性。 5. 安全性:MQTT客户端 for Window支持MQTT协议的加密和数据传输的安全性,可以通过SSL/TLS协议进行安全通信。 总之,MQTT客户端 for Window是一种在Windows操作系统上运行的MQTT协议的客户端软件,它可以帮助用户轻松实现设备之间的通信和数据传输,非常适用于物联网应用场景。 ### 回答2: MQTT客户端是一种用于连接MQTT代理服务器的应用程序,可以在Windows操作系统上运行。它允许用户通过MQTT协议与其他设备或应用程序进行实时的、双向的通信。 MQTT客户端可用于多种不同的应用场景,比如物联网(IoT)、传感器网络、远程监控等。它可以与各种设备进行通信,包括传感器、智能家居设备、工业控制器等。 在Windows上使用MQTT客户端,用户可以配置代理服务器的连接参数,如IP地址、端口号、订阅主题等。一旦与代理服务器建立连接MQTT客户端可以发布(publish)和订阅(subscribe)消息。发布消息表示客户端向代理服务器发送消息,而订阅消息表示客户端接收代理服务器发布的消息。 MQTT客户端可以通过不同的方式实现,例如使用各种编程语言编写的自定义应用程序,或者使用现有的MQTT客户端软件,如MQTT.fx、mosquitto_pub等。这些软件通常提供了直观的用户界面,方便用户进行操作和监控。 总之,MQTT客户端在Windows操作系统上的使用非常灵活和方便,可以帮助用户轻松地构建与其他设备和应用程序之间的实时通信连接。它是物联网和传感器网络等领域中不可或缺的组件,为用户提供了许多有用的功能和服务。 ### 回答3: MQTT客户端是一种用于与MQTT(Message Queuing Telemetry Transport)代理服务器通信的应用程序。在Windows操作系统上,有许多不同的MQTT客户端可供选择,以满足不同用户的需求。 首先,Eclipse Paho是一个非常受欢迎的MQTT客户端,具有跨平台的特性,包括适用于Windows的版本。它提供了丰富的功能,使开发人员能够轻松地与MQTT代理服务器进行通信,包括发布和订阅消息、设置QoS(Quality of Service)级别、处理断开连接、处理消息保留等。 其次,HiveMQ是另一个流行的MQTT客户端,也提供了适用于Windows的版本。HiveMQ具有高度可扩展性和可靠性,并提供诸如消息路由、消息处理、会话管理等高级功能。它还支持一些高级协议和功能,如MQTT 5.0、请求/响应模式等。 此外,有一些其他适用于Windows的MQTT客户端,如MQTT.fx、MQTT Explorer等,它们提供了直观的图形用户界面,用于连接和交互。这些客户端通常支持易于配置的用户界面、消息发布/订阅、主题过滤等基本功能,以及一些高级功能,如SSL/TLS安全连接、多个代理服务器支持等。 无论选择哪个MQTT客户端,用户都可以根据自己的需求和偏好来决定。这些客户端都提供了易于使用的界面和强大的功能,使得使用MQTT协议进行通信变得更加方便和灵活。无论是开发人员还是普通用户,都可以通过这些客户端享受到MQTT技术所带来的便利和强大能力。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值