app.js 10 KB

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