无法使用反应本机库连接并向物联网中心发送消息

问题描述 投票:0回答:1

当使用react-native-mqtt或sp-react-native-mqtt等React Native库时,无法将设备连接到物联网集线器并使用mqtt协议发送消息。出现未经授权的错误。但我能够将设备连接到物联网集线器并使用 Node js 中的 mqtt 库发送消息。即使在 React Native 中复制粘贴相同的 sas 令牌和 Node js 代码后,也会出现未经授权的错误。这是节点 js 代码。

const mqtt = require("mqtt");

const deviceId = "exampledeviceid"; const iotHubName = "iotc-example-iotc-name"; const 用户名 =

${iotHubName}.azure-devices.net/${deviceId}/?api-version=2021-04-12
; const iotHubTopic =
devices/${deviceId}/messages/events/
; const sasToken = 'examplesastoken';

var 客户端 = mqtt.connect(

mqtts://${iotHubName}.azure-devices.net:8883
, { 保持活动:10, clientId: 设备Id, 协议 ID: 'MQTT', 干净:假, 协议版本:4, 重新连接周期:1000, 连接超时:30 * 1000, 用户名: 用户名, 密码:sasToken, 拒绝未经授权:假, });

client.on('connect', doStuff); client.on('错误', (错误) => { 控制台.错误(

Error: ${error}
) });

异步函数 doStuff() {

console.log("Starting");
try {
    await client.publish(iotHubTopic, "{'id': 12145}");
    console.log('client connected', await client.connected);
    console.log("message sent");
    // This line doesn't run until the server responds to the publish
    await client.end();
    // This line doesn't run until the client has disconnected without error
    console.log("Done");
} catch (e){
    // Do something about it!
    console.log("Error while sending a message...");
    console.log(e.stack);
    process.exit();
}

}

我想将设备连接到物联网集线器并使用 mqtt 协议发送消息。

node.js react-native azure-iot-hub mqtt.js react-native-mqtt
1个回答
0
投票

尝试使用react-native-poho-mqtt库:https://www.npmjs.com/package/react-native-paho-mqtt

首先,您必须初始化客户端,然后进行连接:

import AsyncStorage from "@react-native-async-storage/async-storage";
import Storage from "react-native-storage";
import { Client } from "react-native-paho-mqtt";

const mqttClient = new Client({
uri: wss://sample.co.in:8083,
clientId: "rendom" + Math.round(Math.random(100000000, 1000000000)*1000000000),
storage: new Storage({ storageBackend: AsyncStorage })
});


export const connectMqtt = async () => {  
    try{
        await  mqttClient.connect({
            userName: "username",
            password: "password",
        })  
        return mqttClient.isConnected()
    }
    catch(error){
        return error
    }
}

一旦您获得

mqttClient.isConnected()
true,您就可以使用其他服务。

 mqttClient.send(topic: string | Message, payload: string, qos: 0 | 1 | 2, retained: boolean) {
© www.soinside.com 2019 - 2024. All rights reserved.