app.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. import mqtt from './utils/mqtt';
  2. import update from './utils/update';
  3. import strings from './utils/strings';
  4. import store from './utils/store.js';
  5. import env from './utils/env.js';
  6. //连接的服务器域名
  7. // const host = 'wxs://mqtt.test.radio1964.com';
  8. // const host = 'wxs://mqtt.ssl.keepradioon.net:8884'
  9. const iosHost = 'wxs://mqtt.test.radio1964.com:8884';
  10. const androidHost = 'wxs://mqtt.ssl.keepradioon.net:8884'
  11. App({
  12. globalData: {
  13. isRelease: false,
  14. is_debug: 2, // 1 测试环境 // 2正式环境
  15. baseUrl: env.prod.baseUrl,
  16. userInfo: null,
  17. classifyProducts: "",
  18. statusBarHeight: 0,
  19. safeBottomHeight: 0,
  20. navBarHeight: 0,
  21. MenuButtonheight: 0,
  22. MenuButtonTop: 0,
  23. scopeBluetooth: true,
  24. ssid: "",
  25. pwdData: "",
  26. userData: null,
  27. client: null,
  28. oneInitBluetooth: true,
  29. mDeviceList: [],
  30. // 当前设备
  31. // device: {},
  32. // 设备列表,跟app同步字段
  33. classifyProducts: [],
  34. //MQTT连接的配置
  35. host: iosHost,
  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. ///全局初始化
  45. onLaunch() {
  46. var that = this;
  47. that.globalData.is_debug = that.globalData.isRelease ? 2 : 1;
  48. that.globalData.baseUrl = that.globalData.isRelease ? env.prod.baseUrl : env.test.baseUrl;
  49. ///用户信息
  50. var userInfo = store.getStore("userInfo");
  51. if (!strings.isEmpty(userInfo)) {
  52. that.globalData.userInfo = userInfo;
  53. }
  54. ///设备列表
  55. var classifyProducts = store.getStore("classifyProducts");
  56. if (!strings.isEmpty(classifyProducts)) {
  57. that.globalData.classifyProducts = classifyProducts;
  58. }
  59. //自定义导航栏 获取设备顶部窗口的高度(不同设备窗口高度不一样,根据这个来设置自定义导航栏的高度)
  60. const res = wx.getSystemInfoSync(); // 获取系统信息
  61. /// android ios
  62. const platform = res.platform; // 获取平台类型
  63. if (platform === 'android') {
  64. that.globalData.host = androidHost;
  65. }
  66. const safeArea = res.safeArea;
  67. var height = safeArea.height || 0;
  68. var bottom = safeArea.bottom || 0;
  69. var reduce = bottom - height;
  70. var safeBottomHeight = reduce > 0 ? reduce : -reduce;
  71. that.globalData.safeBottomHeight = safeBottomHeight;
  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. wx.onAppShow(() => {
  81. if (!(that.globalData.client && that.globalData.client.connected)) {
  82. that.connect();
  83. }
  84. });
  85. ///界面后台化
  86. wx.onAppHide(() => {
  87. // if (that.globalData.client && that.globalData.client.connected) {
  88. // that.globalData.client.end(true);
  89. // };
  90. });
  91. },
  92. onShow: function () {
  93. update.update();
  94. },
  95. onHide: function () {},
  96. ///连接设备
  97. connect() {
  98. var that = this;
  99. var options = that.globalData.options;
  100. var host = that.globalData.host;
  101. that.globalData.client = mqtt.connect(host, options);
  102. // 设备连接
  103. that.globalData.client.on('connect', () => {
  104. var pages = getCurrentPages();
  105. var length = pages.length;
  106. var currentPage = pages[length - 1];
  107. if (!strings.isEmpty(currentPage.mqttCallback)) {
  108. currentPage.mqttCallback("connect")
  109. };
  110. ///多个界面回调首页
  111. if (length > 1) {
  112. pages[0].mqttCallback("connect");
  113. }
  114. });
  115. // 消息回调 wx.hideLoading();
  116. that.globalData.client.on("message", function (topic, payload) {
  117. var pages = getCurrentPages();
  118. var length = pages.length;
  119. var currentPage = pages[length - 1];
  120. if (topic.indexOf("status/onoffline") !== -1) {
  121. ///当前界面回调
  122. if (!strings.isEmpty(currentPage.mqttCallback)) {
  123. currentPage.mqttCallback("message_onoffline", {
  124. topic,
  125. payload
  126. });
  127. }
  128. if (length > 1) {
  129. pages[0].mqttCallback("message_onoffline", {
  130. topic,
  131. payload
  132. });
  133. }
  134. } else if (topic.indexOf("user/pub_response") !== -1) {
  135. if (!strings.isEmpty(currentPage.mqttCallback)) {
  136. currentPage.mqttCallback("message", {
  137. topic,
  138. payload
  139. });
  140. }
  141. if (length > 1) {
  142. pages[0].mqttCallback("message", {
  143. topic,
  144. payload
  145. });
  146. }
  147. }
  148. });
  149. // 重连
  150. that.globalData.client.on("reconnect", function (errr) {
  151. console.log("reconnect的回调==" + JSON.stringify(errr))
  152. var pages = getCurrentPages();
  153. var length = pages.length;
  154. var currentPage = pages[length - 1];
  155. if (!strings.isEmpty(currentPage.mqttCallback)) {
  156. currentPage.mqttCallback("reconnect")
  157. };
  158. if (length > 1) {
  159. pages[0].mqttCallback("reconnect");
  160. }
  161. });
  162. // 离线回调
  163. that.globalData.client.on("offline", function (errr) {
  164. console.log("offline的回调==" + JSON.stringify(errr))
  165. var pages = getCurrentPages();
  166. var length = pages.length;
  167. var currentPage = pages[length - 1];
  168. if (!strings.isEmpty(currentPage.mqttCallback)) {
  169. currentPage.mqttCallback("offline")
  170. };
  171. if (length > 1) {
  172. pages[0].mqttCallback("offline");
  173. }
  174. });
  175. // 错误回调
  176. that.globalData.client.on("error", function (error) {
  177. console.log("错误码的回调==" + JSON.stringify(errr))
  178. var pages = getCurrentPages();
  179. var length = pages.length;
  180. var currentPage = pages[length - 1];
  181. if (!strings.isEmpty(currentPage.mqttCallback)) {
  182. currentPage.mqttCallback("error", {})
  183. };
  184. if (length > 1) {
  185. pages[0].mqttCallback("error", {});
  186. }
  187. });
  188. },
  189. // topic
  190. // /AIrSMArT_7cdfa1fd3af0/status/onoffline
  191. // /AIrSMArT_7cdfa1fd3af0/user/pub_response
  192. // 订阅主题
  193. subscribe: function (topic, callback) {
  194. var that = this;
  195. if (that.globalData.client && that.globalData.client.connected) {
  196. //订阅主题
  197. // err:null
  198. // granted:[{"topic":"/AIrSMArT_861210052355545/status/onoffline","qos":0}]
  199. that.globalData.client.subscribe(topic, function (err, granted) {
  200. if (!err) {
  201. if (callback) {
  202. callback();
  203. }
  204. console.log("订阅成功===" + topic);
  205. } else {
  206. console.log('订阅主题失败');
  207. }
  208. })
  209. } else {
  210. console.log("服务器已断开");
  211. }
  212. },
  213. // 取消订阅
  214. unsubscribe: function (topic) {
  215. var that = this;
  216. if (that.globalData.client && that.globalData.client.connected) {
  217. that.globalData.client.unsubscribe(topic);
  218. } else {
  219. console.log('请先连接服务器');
  220. }
  221. },
  222. /**
  223. * 发布信息
  224. * @param {*} data
  225. * DstDeviceName:目标设备
  226. * type: 指令
  227. * other:other
  228. * .......................
  229. * AIrSMArT_: 设备前缀
  230. */
  231. PubMsg(option, callback) {
  232. var that = this;
  233. if (strings.isEmpty(that.globalData.userInfo)) {
  234. return;
  235. }
  236. // {"type":"get_dev_info","DstDeviceName":"AIrSMArT_7cdfa1fd3af0"}
  237. // get_dev_info
  238. var type = option.type;
  239. // AIrSMArT_7cdfa1fd3af0
  240. var DstDeviceName = option.DstDeviceName;
  241. // ALY_933625
  242. var SrcDeviceName = `ALY_${that.globalData.userInfo.userId}`;
  243. if (that.globalData.client && that.globalData.client.connected) {
  244. const data = {
  245. "type": type,
  246. "DstDeviceName": DstDeviceName,
  247. "SrcDeviceName": SrcDeviceName,
  248. };
  249. if (option.other) {
  250. data.other = option.other;
  251. };
  252. // /AIrSMArT_7cdfa1fd3af0/user/sub_control
  253. var publish = `/${DstDeviceName}/user/sub_control`;
  254. // {"type":"get_dev_info","DstDeviceName":"AIrSMArT_7cdfa1fd3af0","SrcDeviceName":"ALY_933625"}
  255. var dataString = `${JSON.stringify(data)}`;
  256. that.globalData.client.publish(publish, dataString, (err) => {
  257. if (err) {
  258. console.log("发布消息失败");
  259. }
  260. });
  261. } else {
  262. console.log("服务器已断开");
  263. }
  264. },
  265. // 获取蓝牙权限
  266. getBluetoothStatus() {
  267. var that = this;
  268. wx.getSetting({
  269. success(res) {
  270. if (res.authSetting["scope.bluetooth"]) {
  271. that.globalData.scopeBluetooth = true;
  272. } else if (res.authSetting["scope.bluetooth"] === undefined) {
  273. that.globalData.scopeBluetooth = false;
  274. wx.authorize({
  275. scope: "scope.bluetooth",
  276. complete() {
  277. that.getBluetoothStatus();
  278. }
  279. });
  280. } else {
  281. that.globalData.scopeBluetooth = false;
  282. wx.showModal({
  283. title: '请打开系统蓝牙进行配网',
  284. content: '如已打开蓝牙仍然弹框,请尝试重启小程序',
  285. success(res) {
  286. if (res.confirm) {
  287. console.log('用户点击确定')
  288. wx.openSetting({
  289. complete() {
  290. // that.getBluetoothStatus();
  291. }
  292. })
  293. } else if (res.cancel) {
  294. console.log('用户点击取消')
  295. }
  296. }
  297. })
  298. };
  299. if (getCurrentPages()[getCurrentPages().length - 1].getBluetoothStatusCallck) {
  300. getCurrentPages()[getCurrentPages().length - 1].getBluetoothStatusCallck(that.globalData.scopeBluetooth);
  301. }
  302. }
  303. });
  304. },
  305. })