Skip to content

Repository files navigation

NestJS MQTT Service

一个基于 NestJS 的 MQTT 消息发送服务,连接到 EMQX 公共服务。

功能特性

  • 接收 GET 请求发送 MQTT 消息
  • 自动生成随机 clientId
  • 按需连接、订阅、发布、断开连接
  • 完整的日志记录
  • 可配置的 MQTT 连接参数

项目结构

aipro/
├── src/
│   ├── mqtt/
│   │   ├── mqtt.module.ts    # MQTT 模块
│   │   └── mqtt.service.ts   # MQTT 服务
│   ├── dto/
│   │   └── send-tip.dto.ts   # 请求参数验证
│   ├── app.module.ts         # 根模块
│   ├── tip.controller.ts     # 控制器
│   └── main.ts               # 应用入口
├── package.json
├── tsconfig.json
└── README.md

快速开始

安装依赖

cd /Users/dmhsq/Desktop/aipro
npm install

开发模式运行

npm run start:dev

服务将在 http://localhost:3000 启动。

构建生产版本

npm run build
npm run start:prod

API 使用

发送 MQTT 消息

接口: GET /sendTip

查询参数:

参数 类型 必填 描述
topic string 是 要订阅和发布消息的主题
content string 是 要发送的消息内容

示例请求:

curl "http://localhost:3000/sendTip?topic=test/topic&content=Hello%20MQTT"

成功响应:

{
  "success": true,
  "message": "Message sent successfully",
  "clientId": "nestjs_1773231062904_vurcna",
  "topic": "test/topic",
  "content": "Hello MQTT"
}

工作原理

  1. 收到请求后,生成随机 clientId
  2. 连接到 EMQX 公共服务 (broker.emqx.io:1883)
  3. 订阅指定的主题(QoS=0)
  4. 向该主题发布消息(QoS=0)
  5. 断开 MQTT 连接
  6. 返回响应结果

配置

可以在 src/app.module.ts 中修改 MQTT 连接配置:

MqttModule.register({
  host: 'broker.emqx.io',      // MQTT Broker 地址
  port: 1883,                  // 端口
  protocol: 'mqtt',            // 协议: mqtt, mqtts, ws, wss
  connectTimeout: 30000,       // 连接超时(ms)
  reconnectPeriod: 0,          // 重连间隔(0=不自动重连)
  clean: true,                 // 清理会话
  // 其他 mqtt 连接选项...
})

依赖

  • @nestjs/core, @nestjs/common, @nestjs/platform-express: NestJS 框架
  • mqtt: MQTT 客户端库
  • class-validator, class-transformer: DTO 验证

测试

可以使用任何 MQTT 客户端订阅主题来验证消息是否成功发送。例如:

# 使用 mqtt-cli
mqtt sub -h broker.emqx.io -t "test/topic"

# 或使用在线 MQTT 客户端: https://mqttfx.jensd.de/

然后在另一个终端发送请求:

curl "http://localhost:3000/sendTip?topic=test/topic&content=Test%20Message"

你应该能在订阅端收到消息。

许可证

ISC

About

向mqtt公共服务发送订阅,用于ai向我其他应用推送

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages