记录一下mqtt的封装

mqtt npm 地址

mqtt安装
npm install mqtt --save

import mqtt from 'mqtt'

interface ConfigOption  {
    clientId: string,
    keepalive: number,
    reconnectPeriod: number
}
export default class MQTT {
    // 配置
    private options: ConfigOption =  {
        clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
        keepalive: 60,
        reconnectPeriod: 600
    }
    // 实例
    private mqttClient: any = '';
    // 连接状态 成功true 掉线失败 false
    private state: Boolean = false;
    // 事件
    private events: string[] = []
    // 主题
    private topicList: string[] = []

    constructor(MQTT_URL = "ws://xxxxxxx") {

        // 初始化配置
        this.mqttClient = mqtt.connect(MQTT_URL, this.options);

        // 连接状态
        this.state = false;

        // 事件
        this.events = ["connect", "reconnect", "disconnect", "error"]  
  
        // 状态监听
        this.on()
    }
    // 监听方法  
    on(success = () => {}, error = () => {}) {
        let {events} = this;
        for(let e of events) {
            this.mqttClient.on(e, (event: any) => {
                
                switch(e) {
                    case "connect": //连接成功
                        this.state = true;
                        success();
                    break;
                    case "reconnect": //重新连接
                        this.state = true;
                        success();
                    break;
                    case "disconnect": //断开连接
                        this.state = false;
                        console.error('mqtt断开连接', event)
                        error();
                    break;
                    case "error": // 连接出错
                        this.state = false;
                        console.error('连接出错', event)
                        error();
                    break;
                }
            })
        }
    }
    // 接受消息通知
    onMessage(topicValue: string, cb?: any) {
        this.mqttClient.on("message", (topic: string, uint8Array: any) => {
            if(topicValue == topic) {
                
                const decoder = new TextDecoder();
                const message = decoder.decode(uint8Array);

                cb&&cb(message)
            }
        })
    }
    // 发布
    publish(topic: string, message: string, cb?: any) {
        if (!this.state) {
            console.log('未连接')
            return
        }
        this.mqttClient.publish(topic, message, {qos: 1},(err: any) => {
            if(!err) {
                console.log('主题'+ topic + "发布成功")
                cb&&cb()
            }
        })
    }
    // 订阅 
    subscribe(topic: string, cb?: any) {
        // 判断连接状态
        let {topicList} = this;
        if(this.state) {//成功
            if(!topicList.includes(topic)) {//添加
                this.mqttClient.subscribe([...topicList, topic], {}, (e: any) => {
                    cb&&cb(e)
                    this.topicList.push(topic);
                    console.log(`主题${topic}订阅成功!`)
                })
            } else {
                console.log(`主题${topic}已订阅!`)
                cb&&cb()
            }

        } else {//掉线状态
            console.error('未连接,订阅失败')
        }
    }
    // 取消订阅
    unsubscribe(topic: string, cb?: any) {
         // 判断连接状态
         let {topicList} = this;
         if(this.state) {//成功
            let index = topicList.findIndex(item => item == topic) as number;
            if(index !== -1) {
                this.mqttClient.unsubscribe(topic, (e: any)=> {
                    console.log(`该主题${topic}取消订阅成功!`)
                    cb&&cb(e)
                    this.topicList.splice(index, 1);
                })
            } else {
                console.log(`该主题${topic}暂未订阅!`)
            }
 
         } else {//掉线状态
             console.error('未连接,取消订阅失败')
         }
    }
    // 断开关闭
    unconnect() {
        if(!this.mqttClient) return
        this.mqttClient.end()
        this.topicList = []
        this.state = false;
        this.mqttClient = null
        console.log('服务器已断开连接!')
    }

}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python对MQTT进行封装的库有很多,其中比较常用的有paho-mqttmqtt-python。这两个库都是基于Python语言实现的MQTT客户端,提供了简单易用的API,方便开发者进行MQTT通信。 下面分别介绍这两个库的使用方法: 1. paho-mqtt paho-mqtt是一个Python实现的MQTT客户端库,支持MQTT v3.1和v3.1.1协议。它提供了多种MQTT通信模式,如发布/订阅模式、请求/响应模式等。 安装paho-mqtt库: ``` pip install paho-mqtt ``` 使用paho-mqtt库进行MQTT通信: ```python import paho.mqtt.client as mqtt # 连接MQTT服务器 client = mqtt.Client() client.connect("localhost", 1883, 60) # 发布消息 client.publish("topic/test", "Hello, MQTT!") # 订阅主题 def on_message(client, userdata, msg): print(msg.topic + " " + str(msg.payload)) client.on_message = on_message client.subscribe("topic/test") # 开始循环监听MQTT消息 client.loop_forever() ``` 2. mqtt-python mqtt-python是另一个Python实现的MQTT客户端库,同样支持MQTT v3.1和v3.1.1协议。它提供了MQTT客户端和MQTT broker两种模式,方便开发者进行MQTT通信。 安装mqtt-python库: ``` pip install mqtt-python ``` 使用mqtt-python库进行MQTT通信: ```python from mqtt import MQTTClient # 连接MQTT服务器 client = MQTTClient("client_id", "localhost", 1883) client.connect() # 发布消息 client.publish("topic/test", "Hello, MQTT!") # 订阅主题 def on_message(topic, message): print(topic + " " + message) client.on_message = on_message client.subscribe("topic/test") # 开始循环监听MQTT消息 client.loop_forever() ``` 以上是paho-mqttmqtt-python库的基本用法,具体的API和使用方法可以参考官方文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值