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
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:
Once you get
mqttClient.isConnected()
true you can use other services.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:
If you use one of the Device SDKs rather than using MQTT directly, these steps are largely automated for you.