Alipay applet integrates mqtt and is compatible with IOS and Android

1 Introduction

Last year, I wanted to make an Alipay applet to connect to the mqtt protocol. But in the end, after multiple consultations, customer service and the community, the answer was that the Alipay applet cannot directly support the mqtt protocol. I accidentally discovered the masterpiece of Xu Hong, and finally discovered the good thing xmqtt.js. It realizes the perfect access of Alipay applet to the mqtt protocol, and the device can connect, subscribe, and send and receive messages normally. Here we stand on the shoulders of giants and share the entire process of accessing xmqtt.js.

2. xmqtt.js

xmqtt.js free 0 points download address https://download.csdn.net/download/qq_35921773/88306608

3. Encapsulate API

Create a new alimqtt.js. For ease of use, we encapsulate it.

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;

4. How to use

  1. When this js is introduced into the page, it will automatically connect to the mqtt server.

    //#ifdef MP-ALIPAY
    import mqtt from "../../common/utils/alimqtt";
    //#endif
    
  2. Subscribe to topic

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

      methods: {
      	deviceReceiveMsg(topic, msgObj) {
          //mqtt收到消息
          console.log('当前主题' + topic)
          console.log('消息内容' + msgObj)
        }
      }
    
  4. send message

     mqtt.publish("device", "测试消息", 0)
    

Guess you like

Origin blog.csdn.net/qq_35921773/article/details/132719439