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

Device connection disconnect constantly #429

Closed iagocarmona closed 7 months ago

iagocarmona commented 7 months ago

The device connection is getting offline constantly

import { Injectable, OnApplicationBootstrap } from '@nestjs/common'
import { EventEmitter2 } from '@nestjs/event-emitter'
import { Logger } from '@saas/architecture'
import { S3Client, GetObjectCommand } from '@aws-sdk/client-s3'
import * as awsIot from 'aws-iot-device-sdk'
import { Readable } from 'stream'

@Injectable()
export class AWSMqttProvider implements OnApplicationBootstrap {
  private subscriptionTopic: string
  private clientId: string
  private endpoint: string
  private device: awsIot.device
  private decoder: TextDecoder
  private s3Client: S3Client

  constructor(private eventEmitter: EventEmitter2) {
    this.subscriptionTopic = process.env.SUBSCRIPTION_TOPIC ?? ''
    this.clientId = process.env.AWS_IOT_CLIENT_ID ?? ''
    this.endpoint = process.env.AWS_IOT_ENDPOINT ?? ''
    this.decoder = new TextDecoder('utf8')

    this.s3Client = new S3Client({
      region: 'us-east-1',
    })
  }

  private handleMessage = (_topic: string, payload: ArrayBuffer): void => {
    const json = this.decoder.decode(payload)
    const jsonPayload = JSON.parse(json)
    this.eventEmitter.emit('device.state', jsonPayload)
  }

  private handleConnect = (): void => {
    this.device.subscribe(this.subscriptionTopic)
    Logger.debug(`Connected to the topic ${this.subscriptionTopic}`)
  }

  private handleError = (err: string | Error): void => {
    Logger.error('Error on device connection', err)
  }

  private handleOffline = (): void => {
    Logger.debug('Offline')
  }

  private handleReconnect = (): void => {
    Logger.debug('Reconnecting...')
  }

  async onApplicationBootstrap() {
    const clientCert = await this.getCertificateFromS3(`${this.clientId}.cert.pem`)
    const privateKey = await this.getCertificateFromS3(`${this.clientId}.private.key`)
    const caCert = await this.getCertificateFromS3('root-CA.crt')

    this.device = new awsIot.device({
      clientId: this.clientId,
      host: this.endpoint,
      clientCert,
      privateKey,
      caCert,
      baseReconnectTimeMs: 100,
    })

    this.device.on('connect', this.handleConnect)
    this.device.on('message', this.handleMessage)
    this.device.on('error', this.handleError)
    this.device.on('offline', this.handleOffline)
    this.device.on('reconnect', this.handleReconnect)
  }

The connection is getting offline constantly

Expected Behavior

I would like to keep it alive

Current Behavior

Is disconnecting constatly

Reproduction Steps

Connect to a device on aws

Possible Solution

No response

Additional Information/Context

No response

SDK version used

2.2.13

Environment details (OS name and version, etc.)

ubuntu

jmklix commented 7 months ago

Can you try running the device-example with your certs to make sure you have the certificates set up and registered correctly? IoT core just disconnects without any error message when you try to connect with invalid credentials. Please include any logs if this still doesn't work for you.

It's recommended to use aws-iot-device-sdk-js-v2 for better functionality. Using MQTT5 with that sdk will give better error messages when you fail to connect.

iagocarmona commented 7 months ago

Thank you very much for your attention! I ran some tests and found an issue. I was using the same clientId in all environments (production, homolog, and development). I believe that, it kept disconnecting and reconnecting. To fix it, I changed the certificate policy, I'm using to allow clientId from homolog, production, and development. Now it's working correctly. Thank's for attention :)

jmklix commented 7 months ago

I'm glad that you were able to get it working. Please let us know if you have any other problems/questions when using this sdk.

github-actions[bot] commented 7 months ago

⚠️COMMENT VISIBILITY WARNING⚠️

Comments on closed issues are hard for our team to see. If you need more assistance, please either tag a team member or open a new issue that references this one. If you wish to keep having a conversation with other community members under this issue feel free to do so.