mqtt.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import mqtt from 'mqtt'
  2. //let HOST = '192.168.3.51'
  3. const apiInfo = uni.getStorageSync('apiInfo')
  4. let HOST = apiInfo.hostname
  5. if (process.env.NODE_ENV == 'development') {
  6. HOST = '124.71.68.31'
  7. }
  8. const ENDPOINT = '/mqtt'
  9. const connection = {
  10. protocol: 'ws',
  11. host: HOST,
  12. port: 81,
  13. endpoint: ENDPOINT,
  14. // for more options, please refer to https://github.com/mqttjs/MQTT.js#mqttclientstreambuilder-options
  15. clean: true,
  16. connectTimeout: 30 * 1000, // ms
  17. reconnectPeriod: 4000, // ms
  18. clientId: 'emqx_vue_' + Math.random().toString(16).substring(2, 8)
  19. }
  20. let Mymqtt = {
  21. data () {
  22. return {
  23. mqttClient: null
  24. }
  25. },
  26. beforeDestroy () {
  27. if (this.mqttClient) {
  28. this.mqttClient.end()
  29. }
  30. },
  31. methods: {
  32. mqttInit () {
  33. const { protocol, host, endpoint, port, ...options } = connection
  34. const connectUrl = `${protocol}://${host}:${port}${endpoint}`
  35. this.mqttClient = mqtt.connect(connectUrl, options)
  36. if (this.mqttClient.on) {
  37. this.mqttClient.on('connect', () => {
  38. console.log('连接成功')
  39. // 订阅
  40. this.doSubscribe(this.TOPIC)
  41. })
  42. this.mqttClient.on('reconnect', () => {
  43. console.log('重连')
  44. })
  45. this.mqttClient.on('error', error => {
  46. console.log('Connection failed', error)
  47. })
  48. this.mqttClient.on('message', (topic, message) => {
  49. console.log('ff', topic, JSON.parse(message))
  50. })
  51. this.mqttClient.on('message', (topic, message) => {
  52. let data = JSON.parse(message).items
  53. this.initMqttData(data)
  54. })
  55. }
  56. },
  57. // 订阅
  58. doSubscribe (subscription) {
  59. let { topic, qos } = subscription
  60. this.mqttClient.subscribe(topic, { qos }, (error, res) => {
  61. if (error) {
  62. console.log('Subscribe to topics error', error)
  63. return
  64. }
  65. console.log(`订阅:${topic}成功`, res)
  66. })
  67. }
  68. }
  69. }
  70. export default Mymqtt