app.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. // app.ts
  2. import mqtt from './utils/mqtt';
  3. const eventBus = require('./utils/eventBus')
  4. //连接的服务器域名
  5. // const host = 'wxs://mqtt.test.radio1964.com';
  6. // const host = 'wxs://mqtt.test.radio1964.com:8884';
  7. const host = 'wxs://mqtt.ssl.keepradioon.net:8884'
  8. App({
  9. globalData: {
  10. statusBarHeight: 0,
  11. navBarHeight: 0,
  12. MenuButtonheight: 0,
  13. MenuButtonTop: 0,
  14. scopeBluetooth: true,
  15. ssid: "",
  16. pwdData: "",
  17. userData: null,
  18. userInfo: null,
  19. newDeviceId: null,
  20. is_debug: 2, // 1 测试环境 // 2正式环境
  21. client: null,
  22. oneInitBluetooth: true,
  23. systemInfo:null,
  24. //MQTT连接的配置
  25. options: {
  26. clientId: "wx_" + parseInt(Math.random() * 100 + 800, 10),
  27. reconnectPeriod: 1000, //1000毫秒,两次重新连接之间的间隔
  28. connectTimeout: 30 * 1000, //1000毫秒,两次重新连接之间的间隔
  29. resubscribe: true, //如果连接断开并重新连接,则会再次自动订阅已订阅的主题(默认true
  30. keepalive: 3,//每3秒发送一次心跳
  31. },
  32. },
  33. eventBus: eventBus,
  34. /**
  35. * 连接设备
  36. * mqttCallback:mqtt回调统一方法
  37. */
  38. connect() {
  39. this.globalData.client = mqtt.connect(host, this.globalData.options);
  40. // 连接成功
  41. this.globalData.client.on('connect', ()=> {
  42. const pageinfo = getCurrentPages()[getCurrentPages().length - 1];
  43. if(pageinfo.mqttCallback) {
  44. pageinfo.mqttCallback("connect")
  45. };
  46. });
  47. // 接收消息
  48. this.globalData.client.on("message", function(topic, payload) {
  49. wx.hideLoading();
  50. const pageinfo = getCurrentPages()[getCurrentPages().length - 1];
  51. const thisPageIsIndex = getCurrentPages().length === 1;
  52. if(pageinfo.mqttCallback) {
  53. if(topic.indexOf("status/onoffline") !== -1) {
  54. pageinfo.mqttCallback("message_onoffline", {topic, payload});
  55. if(!thisPageIsIndex) {
  56. getCurrentPages()[0].mqttCallback("message_onoffline", {topic, payload})
  57. }
  58. } else if(topic.indexOf("user/pub_response") !== -1) {
  59. pageinfo.mqttCallback("message", {topic, payload});
  60. }
  61. };
  62. });
  63. //服务器连接异常的回调
  64. this.globalData.client.on("error", function(error) {
  65. console.log(" 服务器 error 的回调" + error)
  66. const pageinfo = getCurrentPages()[getCurrentPages().length - 1];
  67. if(pageinfo.mqttCallback) {
  68. pageinfo.mqttCallback("error")
  69. };
  70. })
  71. // 服务器重连
  72. this.globalData.client.on("reconnect", function(errr) {
  73. console.log(" 服务器 reconnect的回调", errr);
  74. const pageinfo = getCurrentPages()[getCurrentPages().length - 1];
  75. if(pageinfo.mqttCallback) {
  76. pageinfo.mqttCallback("reconnect")
  77. };
  78. })
  79. //服务器断开连接
  80. this.globalData.client.on("offline", function(errr) {
  81. console.log(" 服务器 offline的回调", errr)
  82. const pageinfo = getCurrentPages()[getCurrentPages().length - 1];
  83. if(pageinfo.mqttCallback) {
  84. pageinfo.mqttCallback("offline")
  85. };
  86. })
  87. },
  88. changeUserRight() {
  89. const i = wx.getStorageSync('rightId') || 0
  90. const id = i === 0 ? 1 : 0
  91. wx.setStorageSync('rightId', id)
  92. getApp().eventBus.emit('rightChange', id)
  93. },
  94. // 订阅主题
  95. subscribe: function(topic, callback) {
  96. if (this.globalData.client && this.globalData.client.connected) {
  97. //订阅主题
  98. this.globalData.client.subscribe(topic, function(err, granted) {
  99. if (!err) {
  100. if(callback) {
  101. callback();
  102. }
  103. console.log("订阅成功");
  104. } else {
  105. console.log('订阅主题失败');
  106. }
  107. })
  108. } else {
  109. console.log("服务器已断开");
  110. // wx.showToast({
  111. // title: '服务器已断开',
  112. // icon: 'error',
  113. // duration: 2000
  114. // })
  115. }
  116. },
  117. // 取消订阅
  118. unsubscribe: function(Topic) {
  119. if (this.globalData.client && this.globalData.client.connected) {
  120. this.globalData.client.unsubscribe(Topic);
  121. } else {
  122. console.log('请先连接服务器');
  123. // wx.showToast({
  124. // title: '请先连接服务器',
  125. // icon: 'none',
  126. // duration: 2000
  127. // })
  128. }
  129. },
  130. /**
  131. * 发布信息
  132. * @param {*} data
  133. * DstDeviceName:目标设备
  134. * type: 指令
  135. * other:other
  136. * .......................
  137. * AIrSMArT_: 设备前缀
  138. */
  139. PubMsg(option, callback) {
  140. if (this.globalData.client && this.globalData.client.connected) {
  141. wx.showLoading({
  142. title: '请稍后',
  143. });
  144. const data = {"DstDeviceName": option.DstDeviceName,"SrcDeviceName": `ALY_${this.globalData.userInfo.userId}`,"type": option.type};
  145. if(option.other) {
  146. data.other = option.other;
  147. };
  148. this.globalData.client.publish(`/${option.DstDeviceName}/user/sub_control`, `${JSON.stringify(data)}`,(err) => {
  149. if (err) {
  150. console.log("发布消息失败");
  151. }
  152. });
  153. } else {
  154. console.log("服务器已断开");
  155. // wx.showToast({
  156. // title: '服务器已断开',
  157. // icon: 'error',
  158. // duration: 2000
  159. // })
  160. }
  161. },
  162. onLaunch() {
  163. var _this = this;
  164. wx.onAppHide(()=> {
  165. if(_this.globalData.client && _this.globalData.client.connected){
  166. _this.globalData.client.end(true);
  167. _this.globalData.client.end(true);
  168. console.log("断开");
  169. };
  170. });
  171. wx.onAppShow(()=> {
  172. console.log("加载")
  173. if(_this.globalData.userInfo !== null){
  174. if(_this.globalData.client) {
  175. _this.globalData.client.end(true);
  176. _this.globalData.client.end(true);
  177. }
  178. console.log("重连");
  179. _this.connect();
  180. };
  181. });
  182. this.getBluetoothStatus();
  183. //自定义导航栏 获取设备顶部窗口的高度(不同设备窗口高度不一样,根据这个来设置自定义导航栏的高度)
  184. wx.getSystemInfo({
  185. success: (res) => {
  186. let custom = wx.getMenuButtonBoundingClientRect();
  187. _this.globalData.systemInfo = res;
  188. _this.globalData.navBarHeight = res.statusBarHeight + custom.height + (custom.top - res.statusBarHeight) * 2;
  189. _this.globalData.MenuButtonheight = custom.height;
  190. _this.globalData.MenuButtonTop = custom.top;
  191. }
  192. })
  193. },
  194. // 获取蓝牙权限
  195. getBluetoothStatus(){
  196. const _this = this;
  197. wx.getSetting({
  198. success (res) {
  199. if(res.authSetting["scope.bluetooth"]) {
  200. _this.globalData.scopeBluetooth = true;
  201. } else if(res.authSetting["scope.bluetooth"] === undefined) {
  202. _this.globalData.scopeBluetooth = false;
  203. wx.authorize({
  204. scope: "scope.bluetooth",
  205. complete () {
  206. _this.getBluetoothStatus();
  207. }
  208. });
  209. } else {
  210. _this.globalData.scopeBluetooth = false;
  211. wx.showModal({
  212. title: '请打开系统蓝牙进行配网',
  213. content: '如已打开蓝牙仍然弹框,请尝试重启小程序',
  214. success (res) {
  215. if (res.confirm) {
  216. console.log('用户点击确定')
  217. wx.openSetting({
  218. complete () {
  219. // _this.getBluetoothStatus();
  220. }
  221. })
  222. } else if (res.cancel) {
  223. console.log('用户点击取消')
  224. }
  225. }
  226. })
  227. };
  228. if(getCurrentPages()[getCurrentPages().length - 1].getBluetoothStatusCallck) {
  229. getCurrentPages()[getCurrentPages().length - 1].getBluetoothStatusCallck(_this.globalData.scopeBluetooth);
  230. }
  231. // res.authSetting = {
  232. // "scope.userInfo": true,
  233. // "scope.userLocation": true
  234. // }
  235. }
  236. })
  237. },
  238. })