I am not able to connect to AWS IoT Core using the mqtt.js library. The same code works with aws-iot-sdk-js package. I am not getting what can be the wrong? so I really have question that Can we use mqtt.js library to connect with AWS IoT Core and subscribe messages on specific topic?
Here is the sample code
// Dependencies
const awsIot = require('aws-iot-device-sdk');
const mqtt = require('mqtt');
const config = {
clientId: 'iot_gateway_mac-1',
host: 'a338ffc7x8cytc09a-ats.iot.us-east-1.amazonaws.com',
port: 8883,
keyPath: './private.pem.key',
certPath: './certificate.pem.crt',
caPath: './AmazonRootCA1.pem',
debug: true,
}
// const device = awsIot.device(config);
// const event_topic = "/building/pacs/event"
const client = mqtt.connect(config)
// Handle errors
client.on('error', (error) => {
console.error('Error:', error);
});
// Handle connection to the MQTT broker
client.on('connect', () => {
console.log('Connected to MQTT Broker');
// Subscribe to a topic
const topic = '/building/pacs/event';
client.subscribe(topic, (err) => {
if (!err) {
console.log(`Subscribed to ${topic}`);
}
});
});
// Handle incoming messages
client.on('message', (topic, message) => {
console.log(`Received message on topic ${topic}: ${message.toString()}`);
});
// Handle disconnection
client.on('close', () => {
console.log('Disconnected from AWS IoT');
});