Can we use mqtt.js library to connect with AWS IoT Core and subscribe messages on specific topic?

0

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');
});


1 Answer
0

Hi. It should work: https://aws.amazon.com/blogs/iot/use-aws-iot-core-mqtt-broker-with-standard-mqtt-libraries/. Please check the MQTT.js section in the blog. I think your configuration object is incorrect.

profile pictureAWS
EXPERT
Greg_B
answered 6 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions