• 支付宝小程序集成mqtt兼容IOS和安卓


    1. 前言

    ​ 去年就想做支付宝小程序接入mqtt协议。但最终多方咨询,问客服问社区得到的答案都是支付宝小程序不能直接支持mqtt协议。偶然间发现徐宏大神的佳作,终于发现了xmqtt.js这个好东西。它实现了支付宝小程序完美接入mqtt协议,设备可以正常连接、订阅、收发消息。这里站在巨人的肩膀上分享下,接入xmqtt.js的全过程。

    2. xmqtt.js

    xmqtt.js免费0积分下载地址https://download.csdn.net/download/qq_35921773/88306608

    3. 封装api

    新建alimqtt.js,这里为了便于使用,我们对他进行一次封装。

    let xmqtt = require('./xmqtt.js');
    var mqtt = {};
    import { uuid } from 'vue-uuid';
    const host = 'alis://'+process.env.SERVER_HOST+':8084/mqtt';
    //client对象
    var client = null;
    var options={
        protocolVersion: 4, //MQTT连接协议版本
        clientId: 'wxapp_client_'+uuid.v1(),
        myAli: null,
        clean: true,
        password: 'dd',
        username: 'admin',
        reconnectPeriod: 3000, //1000毫秒,两次重新连接之间的间隔
        connectTimeout: 30 * 1000, //1000毫秒,两次重新连接之间的间隔
        resubscribe: true //如果连接断开并重新连接,则会再次自动订阅已订阅的主题(默认true)
    }
    //订阅的主题与回掉方法
    var map = new Map();
    
    /**
     * mqtt 连接状态
     * 0:正在连接
     * 1:连接成功建立
     * 2:连接正在关闭
     * 3:连接已经关闭
     */
    let connectStatus = 0;
    
    //初始化weboscket
    mqtt.initMqtt = () => {
        //开始连接
        if(null == client){
            console.log('连接mqtt服务器',host,options)
            client = xmqtt.connect(host, options);
        }
    
        client.on('connect', function (connack) {
            console.log('连接成功')
        })
    
        //服务器下发消息的回调
        client.on("message", function (topic, payload) {
            console.log(" 收到 topic:" + topic + " , payload :" + payload)
        })
    
        //服务器连接异常的回调
        client.on("error", function (error) {
            console.log(" 服务器 error 的回调" + error)
        })
    
        //服务器重连连接异常的回调,一般是域名或者服务器不存在
        client.on("reconnect", function () {
            console.log(" 服务器 reconnect的回调")
        })
    
        //服务器连接异常的回调
        client.on("offline", function (err) {
            console.log(" 服务器offline的回调"+JSON.stringify(err))
        })
    }
    
    
    /**
     * 订阅主题
     * topic:主题名称
     * qos:服务质量
     */
    mqtt.subscribe = function(topic, qos, receiveCallback) {
        if (client && client.connected) {
            //仅订阅单个主题
            client.subscribe(topic, function (err, granted) {
                if (!err) {
                    console.log('订阅主题成功')
                    map.set('device',receiveCallback);
                } else {
                    console.log('订阅主题失败')
                }
            })
        } else {
            console.log('请先连接服务器')
            setTimeout(function() {
                mqtt.subscribe(topic, qos, receiveCallback);
            }, 1000)
        }
    }
    
    /**
     * 取消订阅主题
     * topic:主题名称
     */
    mqtt.unsubscribe = function(topic) {
        if (client && client.connected) {
            client.unsubscribe(topic);
            map.delete('device')
        } else {
            console.log('请先连接服务器')
            setTimeout(function() {
                mqtt.unsubscribe(topic);
            }, 1000)
        }
    }
    
    /**
     * 发送消息
     * message:消息内容
     * topic:主题
     * qos:服务质量
     */
    mqtt.publish = function(message, topic, qos) {
        if (client && client.connected) {
            client.publish(topic, message,qos);
            console.log('发布成功')
        } else {
            console.log('请先连接服务器')
            uni.showToast({
                title: '正在重新连接服务器,请稍后重试',
                icon: 'none',
                duration: 2000
            })
            setTimeout(function() {
                mqtt.publish(message, topic, qos);
            }, 1000)
        }
    }
    
    
    /**
     * 关闭连接
     */
    mqtt.disconnect = function() {
        console.log("关闭mqtt连接");
        if (null != client) {
            client.disconnect();
        } else {
            //Do-nothing
        }
        client = null;
    }
    
    mqtt.initMqtt();
    
    export default mqtt;
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144

    4. 如何使用

    1. 页面引入此js,会自动连接mqtt服务器。

      //#ifdef MP-ALIPAY
      import mqtt from "../../common/utils/alimqtt";
      //#endif
      
      • 1
      • 2
      • 3
    2. 订阅主题

       onLoad(option) {
       //初始化时订阅该主题,当收到消息后自动调用deviceReceiveMsg方法
       	 mqtt.subscribe('device', 0, this.deviceReceiveMsg);
       }
      
      • 1
      • 2
      • 3
      • 4
    3. 消息接收

        methods: {
        	deviceReceiveMsg(topic, msgObj) {
            //mqtt收到消息
            console.log('当前主题' + topic)
            console.log('消息内容' + msgObj)
          }
        }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
    4. 消息发送

       mqtt.publish("device", "测试消息", 0)
      
      • 1
  • 相关阅读:
    ssm(Spring+SpringMVC+MyBatis)台球室内乒乓球室体育器械租赁收费系统
    Linux 5种网络模型
    java计算机毕业设计-旅游产品销售管理-演示录像2020源码+数据库+系统+lw文档+mybatis+运行部署
    Qt QScrollArea
    面试官:说说JVM内存整体结构?
    【计算机组成原理】详细分析RAM、RRAM、SRAM以及DRAM 的基本知识
    Ubuntu 18.04误装Nvidia 显卡驱动后,在[OK] started LSB 处卡死
    frp内网穿透—将kali代理在公网中进行渗透测试
    电子技术基础之一(电容和电感)
    基于spring boot开发的快递管理系统开题报告
  • 原文地址:https://blog.csdn.net/qq_35921773/article/details/132719439