app.js 9.6 KB

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