skip to Main Content

When using the react native libraries like react-native-mqtt or sp-react-native-mqtt not able to connect the device to iot hub and send the messages using mqtt protocol. Getting unauthorized error. But am able to connect the device to iot hub and send the message using mqtt library in node js. Even after copy pasting the same sas token and node js code in the react native getting unauthorized error. Here is the node js code.

const mqtt = require("mqtt");

const deviceId = "exampledeviceid";
const iotHubName = "iotc-example-iotc-name";
const userName = ${iotHubName}.azure-devices.net/${deviceId}/?api-version=2021-04-12;
const iotHubTopic = devices/${deviceId}/messages/events/;
const sasToken = ‘examplesastoken’;

var client = mqtt.connect(mqtts://${iotHubName}.azure-devices.net:8883, {
keepalive: 10,
clientId: deviceId,
protocolId: ‘MQTT’,
clean: false,
protocolVersion: 4,
reconnectPeriod: 1000,
connectTimeout: 30 * 1000,
username: userName,
password: sasToken,
rejectUnauthorized: false,
});

client.on(‘connect’, doStuff);
client.on(‘error’, (error) => {
console.error(Error: ${error})
});

async function 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();
}

}

I want to connect the device to iot hub and send the messages using mqtt protocol.

2

Answers


  1. Try to use react-native-poho-mqtt library: https://www.npmjs.com/package/react-native-paho-mqtt

    first, you have to initialise the client and then do connect:

    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
        }
    }
    

    Once you get mqttClient.isConnected() true you can use other services.

     mqttClient.send(topic: string | Message, payload: string, qos: 0 | 1 | 2, retained: boolean) {
    
    Login or Signup to reply.
  2. If you’re connecting to IoT Central, you need to follow the DPS flow to discover the name of the underlying IoT Hub instance and to provision the device. For a summary of the connection flow, see https://learn.microsoft.com/azure/iot-central/core/overview-iot-central-developer#how-devices-connect.

    If you manually register the device using the IoT Central UI – you can get the SAS token the device needs to authenticate from the device page in the IoT Central UI.

    Internally, IoT Central uses one or more IoT Hub instances and DPS.

    In summary, the process for connecting a device to IoT Central is:

    1. Use the IoT Central UI to register the device and configure device authentication: SAS or X.509.
    2. In your device code, use the information from IoT Central to connect to DPS and retrieve the name of the assigned IoT Hub instance.
    3. In your device code, use the information from steps 1 & 2 to connect to the assigned IoT Hub instance.

    If you use one of the Device SDKs rather than using MQTT directly, these steps are largely automated for you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search