app.js 8.9 KB

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