app.js 9.2 KB

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