aws / aws-iot-device-sdk-js

SDK for connecting to AWS IoT from a device using JavaScript/Node.js
Apache License 2.0
964 stars 384 forks source link

Receiving Same Message Multiple Times Upon Resubscribing #342

Closed khan-07 closed 4 years ago

khan-07 commented 4 years ago

Hi,

Hope you are good. I have a very simple task of subscribing to a topic , unsubscribing and resubcribing at some later time. But the client remains active during that duration. My architecture doesn't allows me to create multiple devices so i want to reuse the same device. When i unsubscibe the data stream stops correctly but upon resubscribing i start getting same message twice(or the amount of times i call unsubcribe/subscribe). This is a small test code for replicating the issue

const { v4:uuidv4 } = require('uuid');
const deviceModule = require('aws-iot-device-sdk').device;

let clientId = "sdk-nodejs-" + uuidv4();
let args = {
    Debug: false,
    Host: 'ednpoint',
    privateKey: './certs/private.pem.key',
    clientCert: './certs/certificate.pem.crt',
    caCert: './certs/root-CA.crt',
    clientId: clientId,
    Protocol: 'mqtts',
    baseReconnectTimeMs: 4000,
    keepalive: 300,
};

let device =  deviceModule(
    args
);

let topic = "D2";
device.subscribe('D2');

setTimeout(()=>{
    device.unsubscribe(topic);
},8000)

setTimeout(()=>{
    device.subscribe(topic);
},16000)

Help would be really appreciated.

khan-07 commented 4 years ago

Actually my bad, i was doing in this in the callback of the subscribe wrapper i wrote. That was really stupid of me. It was receiving just one message but printing multiple because multiple callbacks were being triggered(one for each subscribe).

   device.on('message', function(topic, payload) {
                    console.log('Message received from server on topic ', topic, payload.toString());

   });