uniapp开发微信小程序连接mqtt

2022-12-15 18:03:22 浏览数 (1)

下载mqtt

代码语言:javascript复制
npm i mqtt@2.18.8

存储mqtt客户端到vuex

代码语言:javascript复制
//  mqtt module
import mqtt from 'mqtt'

const CONNECT_MQTT = 'CONNECT_MQTT'

const SERVER_IP = ''
const SERVER_PORT = ''
const SERVER_PATH = 'mqtt'
//  连接地址
const SERVICE = `${SERVER_IP}:${SERVER_PORT}/${SERVER_PATH}`

//  连接配置项
const options = {
	wsOptions: {},
	protocolVersion: 4, //MQTT连接协议版本
	keepalive: 60,
	clean: true,
	clientId: CLIENT_ID,
	reconnectPeriod: 1000, //1000毫秒,两次重新连接之间的间隔
	connectTimeout: 30 * 1000,
	resubscribe: true ,//如果连接断开并重新连接,则会再次自动订阅已订阅的主题(默认true)
}

const state = () => ({ mqttClient: null })

const actions = {
  [CONNECT_MQTT]({ commit, state }) {
    //  连接mqtt 监听常用事件
    let client = mqtt.connect('wx://'   service   options)

	client.on('connect', () => {
	 
	}).on('error', () => {
	 
	}).on('reconnect', () => {
	 
	}).on('message', () => {
	 
	}).on('close', () => {
    
    })

	commit(CONNECT_MQTT, client)

  }
}

const mutations = {
  [CONNECT_MQTT](state, client) {
    state.mqttClient = client 
  }
}

根组件中连接mqtt

代码语言:javascript复制
import { mapActions } from 'vuex'
import { CONNECT_MQTT } from '@/store/actionTypes'

export default {
  onLaunch: function() {
    this.CONNECT_MQTT()
  },
  methods: {
    ...mapActions('mqtt', [CONNECT_MQTT]) 
  }
}

0 人点赞