app.js 10 KB

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