app.js 9.4 KB

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