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.
Gaurav Kumar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.