| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- import mqtt from 'mqtt'
- //let HOST = '192.168.3.51'
- const apiInfo = uni.getStorageSync('apiInfo')
- let HOST = apiInfo.hostname
- if (process.env.NODE_ENV == 'development') {
- HOST = '124.71.68.31'
- }
- const ENDPOINT = '/mqtt'
- const connection = {
- protocol: 'ws',
- host: HOST,
- port: 81,
- endpoint: ENDPOINT,
- // for more options, please refer to https://github.com/mqttjs/MQTT.js#mqttclientstreambuilder-options
- clean: true,
- connectTimeout: 30 * 1000, // ms
- reconnectPeriod: 4000, // ms
- clientId: 'emqx_vue_' + Math.random().toString(16).substring(2, 8)
- }
- let Mymqtt = {
- data () {
- return {
- mqttClient: null
- }
- },
- beforeDestroy () {
- if (this.mqttClient) {
- this.mqttClient.end()
- }
- },
- methods: {
- mqttInit () {
- const { protocol, host, endpoint, port, ...options } = connection
- const connectUrl = `${protocol}://${host}:${port}${endpoint}`
- this.mqttClient = mqtt.connect(connectUrl, options)
- if (this.mqttClient.on) {
- this.mqttClient.on('connect', () => {
- console.log('连接成功')
- // 订阅
- this.doSubscribe(this.TOPIC)
- })
- this.mqttClient.on('reconnect', () => {
- console.log('重连')
- })
- this.mqttClient.on('error', error => {
- console.log('Connection failed', error)
- })
- this.mqttClient.on('message', (topic, message) => {
- console.log('ff', topic, JSON.parse(message))
- })
- this.mqttClient.on('message', (topic, message) => {
- let data = JSON.parse(message).items
- this.initMqttData(data)
- })
- }
- },
- // 订阅
- doSubscribe (subscription) {
- let { topic, qos } = subscription
- this.mqttClient.subscribe(topic, { qos }, (error, res) => {
- if (error) {
- console.log('Subscribe to topics error', error)
- return
- }
- console.log(`订阅:${topic}成功`, res)
- })
- }
- }
- }
- export default Mymqtt
|