mqttDemo.vue 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <template>
  2. <view class="mqttDemo">
  3. <view>{{mqttData}}</view>
  4. </view>
  5. </template>
  6. <script>
  7. import $mqtt from '@/utils/mqtt.min.js';
  8. export default {
  9. data() {
  10. return {
  11. client: {},
  12. //MQTT请求参数-传感器
  13. mtopic: "iot/device/sensor/sub/",
  14. //MQTT请求参数-智能控制
  15. mtopicOne: "iot/hardware/all/sub/",
  16. subId:'101093843117597548',
  17. mqttData:'',
  18. }
  19. },
  20. onLoad(option) {
  21. },
  22. onShow(){
  23. this.offMQTT('on');
  24. },
  25. mounted(){
  26. },
  27. methods: {
  28. //MQTT订阅
  29. sensorMQTT() {
  30. let self = this;
  31. this.client = $mqtt.connect(
  32. // #ifdef WEB
  33. 'wss://' + uni.getStorageSync('mqttUrl')
  34. // #endif
  35. // #ifdef MP-WEIXIN
  36. 'wxs://' + uni.getStorageSync('mqttUrl')
  37. // #endif
  38. , {
  39. username: uni.getStorageSync('mqttUser'),
  40. password: uni.getStorageSync('mqttPassword')
  41. });
  42. this.client.on("connect", e => {
  43. this.client.subscribe(this.mtopic + self.subId, (err) => {
  44. if (!err) {
  45. console.log("传感器订阅成功:" + this.mtopic + self.subId);
  46. } else {
  47. console.log("连接错误:" + err);
  48. }
  49. });
  50. this.client.subscribe(this.mtopicOne + self.subId, (err) => {
  51. if (!err) {
  52. console.log("智能控制订阅成功:" + this.mtopicOne + self.subId);
  53. } else {
  54. console.log("连接错误:" + err);
  55. }
  56. });
  57. });
  58. this.client.on("message", (topic, message) => {
  59. if (message) {
  60. let data = JSON.parse(message)
  61. console.log('data',data)
  62. this.$set(this,'mqttData',JSON.stringify(data));
  63. }
  64. });
  65. },
  66. //取消订阅关闭MQTT连接
  67. offMQTT(type) {
  68. let self = this;
  69. if (self.client.unsubscribe) {
  70. self.client.unsubscribe(self.mtopicOne + self.subId, error => {
  71. if (error) {
  72. // console.log('mqtt关闭连接错误:', error)
  73. }
  74. })
  75. self.client.end();
  76. self.$set(self, 'client', {});
  77. }
  78. //判断传入参数如果存在 发起一次新的连接
  79. if (type) {
  80. self.sensorMQTT();
  81. }
  82. },
  83. },
  84. onHide() {
  85. //清除MQTT
  86. let self = this;
  87. self.offMQTT();
  88. },
  89. beforeDestroy() {
  90. //清除MQTT
  91. let self = this;
  92. self.offMQTT();
  93. },
  94. }
  95. </script>
  96. <style lang="stylus" scoped>
  97. .mqttDemo{
  98. height:100%;
  99. width:100%;
  100. }
  101. </style>