Nodejs Nestjs MQTT通信插件nestjs-mqtt的使用

Nodejs Nestjs MQTT通信插件nestjs-mqtt的使用
nestjs-mqtt 是一个用于 NestJS 应用程序的 MQTT 客户端插件。它基于 mqtt npm 包,并提供了 NestJS 服务和模块来帮助你轻松地在 NestJS 应用中集成 MQTT。

安装

首先,你需要安装 nestjs-mqttmqtt

npm install @nestjs/mqtt mqtt

配置

接下来,你需要在你的 NestJS 应用中配置 @nestjs/mqtt 模块。这通常在你的主应用模块(通常是 AppModule)中完成。

基本配置

import { Module } from '@nestjs/common';
import { MqttModule } from '@nestjs/mqtt';

@Module({
  imports: [
    MqttModule.forRoot({
      // MQTT Broker 的 URL
      url: 'mqtt://broker.hivemq.com',
      // 可选:客户端 ID
      clientId: 'your-client-id',
      // 可选:连接选项
      connectOptions: {
        keepalive: 10,
        clientId: 'your-client-id',
        will: {
          topic: 'WillMsg',
          payload: 'Connection Closed abnormally !!',
          qos: 0,
          retain: false,
        },
        rejectUnauthorized: false,
      },
    }),
  ],
})
export class AppModule {}

使用 MQTT 服务

你可以通过注入 MqttClient 来使用 MQTT 功能。这里有一个简单的例子:

创建一个 MQTT 服务

import { Injectable } from '@nestjs/common';
import { Client, MqttModule, MqttClient } from '@nestjs/mqtt';

@Injectable()
export class MqttService {
  @Client({
    url: 'mqtt://broker.hivemq.com',
  })
  client: MqttClient;

  constructor() {
    this.client.on('connect', () => {
      console.log('Connected');
    });

    this.client.on('error', (error) => {
      console.error(error);
    });
  }

  publish(topic: string, message: string) {
    this.client.publish(topic, message);
  }

  subscribe(topic: string) {
    this.client.subscribe(topic);
  }
}

在控制器中使用

import { Controller, Get } from '@nestjs/common';
import { MqttService } from './mqtt.service';

@Controller()
export class AppController {
  constructor(private readonly mqttService: MqttService) {}

  @Get()
  getHello(): string {
    return 'Hello World!';
  }

  @Get('publish')
  publishMessage() {
    this.mqttService.publish('test/topic', 'Hello MQTT');
    return 'Message published';
  }

  @Get('subscribe')
  subscribeToTopic() {
    this.mqttService.subscribe('test/topic');
    return 'Subscribed to test/topic';
  }
}

总结

以上就是如何在 NestJS 中使用 nestjs-mqtt 插件的基本步骤。你可以根据需要调整配置选项,例如更改 MQTT 服务器地址、添加认证信息等。希望这些信息对你有所帮助!


3 回复

当然,要使用NestJS中的nestjs-mqtt插件来实现MQTT通信,你可以按照以下步骤操作:

  1. 安装:首先,你需要通过npm安装nestjs-mqtt包。

    npm install [@nestjs](/user/nestjs)/mqtt mqtt
    
  2. 配置:在你的应用模块中配置MQTT客户端。例如,在app.module.ts中:

    import { MqttModule } from '[@nestjs](/user/nestjs)/mqtt';
    import { Module } from '[@nestjs](/user/nestjs)/common';
    
    [@Module](/user/Module)({
      imports: [
        MqttModule.forRoot({
          host: 'broker.hivemq.com',
          port: 1883,
          clientId: `mqtt_${Math.random().toString(16).slice(3)}`,
        }),
      ],
    })
    export class AppModule {}
    
  3. 创建服务:创建一个服务来处理MQTT消息。

    import { Injectable } from '[@nestjs](/user/nestjs)/common';
    import { Client, MqttClient } from 'mqtt';
    
    [@Injectable](/user/Injectable)()
    export class MqttService {
      private client: MqttClient;
    
      constructor(private readonly mqttModule: MqttModule) {
        this.client = mqttModule.getClient();
      }
    
      subscribe(topic: string): void {
        this.client.subscribe(topic);
      }
    
      publish(topic: string, message: string): void {
        this.client.publish(topic, message);
      }
    }
    
  4. 使用服务:在控制器或其他服务中注入并使用这个MQTT服务。

这样,你就有了一个基本的MQTT通信设置!别忘了根据需要调整配置和逻辑。祝编程愉快!


nestjs-mqtt 是一个用于 NestJS 应用程序的 MQTT 通信插件。它允许你轻松地集成 MQTT 协议到你的 NestJS 项目中。以下是如何安装和使用 nestjs-mqtt 的基本步骤:

安装

首先,你需要通过 npm 安装 nestjs-mqtt

npm install @nestjs-modules/mqtt

如果你的应用使用了 TypeScript,可能还需要安装 @types/node(虽然大多数情况下不需要显式安装,因为它是作为 node 包的一部分):

npm install --save-dev @types/node

配置

然后,在你的应用模块中配置 MQTTModule。例如,在 app.module.ts 中:

import { Module } from '@nestjs/common';
import { MqttModule, MqttOptions } from '@nestjs-modules/mqtt';

@Module({
  imports: [
    MqttModule.forRoot({
      // MQTT 连接配置
      connect: {
        url: 'mqtt://broker.hivemq.com', // MQTT broker 地址
        port: 1883, // 端口,默认是1883
        clientId: 'your_client_id', // 客户端ID
        username: 'your_username', // 用户名,如果有
        password: 'your_password', // 密码,如果有
      },
      defaultTopic: '/default/topic', // 默认主题
    }),
    // 其他模块
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

使用

发布消息

你可以创建一个服务来发布 MQTT 消息:

import { Injectable } from '@nestjs/common';
import { ClientProxy } from '@nestjs/microservices';

@Injectable()
export class MqttPublisherService {
  constructor(private readonly clientProxy: ClientProxy) {}

  publishMessage(topic: string, message: string) {
    this.clientProxy.emit(topic, message);
  }
}

订阅消息

同样地,创建一个服务来订阅消息:

import { Injectable } from '@nestjs/common';
import { ClientProxy } from '@nestjs/microservices';

@Injectable()
export class MqttSubscriberService {
  constructor(private readonly clientProxy: ClientProxy) {}

  subscribeToTopic(topic: string, callback: (message: any) => void) {
    this.clientProxy.subscribe(topic, (message) => {
      callback(message);
    });
  }
}

在控制器中使用

最后,在控制器中注入这些服务:

import { Controller, Get } from '@nestjs/common';
import { MqttPublisherService } from './mqtt-publisher.service';
import { MqttSubscriberService } from './mqtt-subscriber.service';

@Controller()
export class AppController {
  constructor(
    private readonly mqttPublisherService: MqttPublisherService,
    private readonly mqttSubscriberService: MqttSubscriberService,
  ) {}

  @Get('publish')
  publishMessage() {
    this.mqttPublisherService.publishMessage('/test/topic', 'Hello MQTT');
  }

  @Get('subscribe')
  subscribeMessage() {
    this.mqttSubscriberService.subscribeToTopic('/test/topic', (message) => {
      console.log(`Received message: ${message}`);
    });
  }
}

以上就是如何在 NestJS 应用程序中使用 nestjs-mqtt 插件的基本流程。希望这对你有所帮助!

nestjs-mqtt 是一个用于NestJS框架的MQTT通信插件。首先安装插件:

npm install @nestjs/mqtt mqtt

然后,在模块文件中导入MqttModule并配置连接选项:

import { MqttModule } from '@nestjs/mqtt';

@Module({
  imports: [
    MqttModule.forRoot({
      connect: {
        url: 'mqtt://broker.hivemq.com',
      },
    }),
  ],
})
export class AppModule {}

创建服务来处理MQTT消息:

import { MqttService } from '@nestjs/mqtt';
@Injectable()
export class MqttServiceClass {
  constructor(private readonly mqttService: MqttService) {}

  publishMessage(topic: string, message: string) {
    this.mqttService.publish(topic, message);
  }

  subscribeToTopic(topic: string) {
    this.mqttService.subscribe(topic, (topic, payload) => {
      console.log(`Received message on topic ${topic}: ${payload.toString()}`);
    });
  }
}

这样你就可以在NestJS项目中实现MQTT通信了。

回到顶部