addMattresses.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. // subpages/addMattresses/addMattresses.js
  2. const app = getApp();
  3. const util = require('../../utils/util.js');
  4. const timeOut = 20; //超时时间
  5. var timeId = "";
  6. var sequenceControl = 0;
  7. Page({
  8. /**
  9. * 页面的初始数据
  10. */
  11. data: {
  12. showBluetoothList: false,
  13. showBluetoothConnected: false,//连接中
  14. isBluetoothConnected: false,//连接成功
  15. bluetoothConnectedStep: 0,
  16. placeOfUse: "",
  17. usingHuman: "",
  18. sn: "",
  19. ssid: "",
  20. password: "",
  21. bluetoothSelectIndex: -1,
  22. activeIcon: "/subpages/images/ic_blue_radio_check.png",
  23. normalIcon: "/subpages/images/ic_blue_radio_uncheck.png",
  24. deviceList: [],
  25. deviceId: "",
  26. deviceIds: [],
  27. wifiInfo: null,
  28. deviceId: "",
  29. password: "",
  30. notice: "",
  31. value: 90,
  32. gradientColor: {
  33. '0%': '#00CEB2',
  34. '50%': '#00C7FF',
  35. '100%': '#53DAFF',
  36. },
  37. statusDefault: ['蓝牙连接...', '蓝牙连接成功', '成功获取设备信息', '获取属性信息成功', '发送配置信息...', '配置信息发送成功', '连接成功'],
  38. descFailList: ["蓝牙连接失败", "获取设备信息失败", "获取属性信息失败", "发送配置信息失败", "分配网络失败"],
  39. failure: false,
  40. value: 0,
  41. desc: "设备连接...",
  42. blueConnectNum: 0,
  43. isChecksum: true,
  44. isEncrypt: false,
  45. flagEnd: false,
  46. defaultData: 1,
  47. ssidType: 2,
  48. passwordType: 3,
  49. meshIdType: 3,
  50. deviceNo: 0,
  51. uuid: "",
  52. serviceId: "",
  53. meshId: "",
  54. processList: [],
  55. result: [],
  56. },
  57. onClose() {
  58. this.setData({ showBluetoothList: false, showBluetoothConnected: false });
  59. },
  60. checkBluetoothSelectIndex(e) {
  61. const index = e.currentTarget.dataset.index;
  62. this.setData({ bluetoothSelectIndex: index });
  63. },
  64. commitData() {
  65. console.log(this.data.placeOfUse);
  66. console.log(this.data.usingHuman);
  67. console.log(this.data.deviceId);
  68. console.log(this.data.ssid);
  69. console.log(this.data.password);
  70. this.checkSn(this.data.deviceId);
  71. },
  72. // 开启蓝牙
  73. bindViewBlue: function () {
  74. const that = this;
  75. wx.closeBluetoothAdapter();
  76. wx.openBluetoothAdapter({
  77. success(res) {
  78. //console.log(res);
  79. that.getBluDevice()
  80. },
  81. fail(res) {
  82. console.log(res);
  83. wx.showToast({
  84. icon:'none',
  85. title: "请打开系统蓝牙"
  86. });
  87. }
  88. })
  89. },
  90. // 获取蓝牙设备列表
  91. getBluDevice () {
  92. var self = this;
  93. //第一步检查蓝牙适配器是否可用
  94. wx.onBluetoothAdapterStateChange(function (res) {
  95. if (!res.available) {
  96. util.showToast('蓝牙不可用');
  97. return false;
  98. }
  99. });
  100. //第二步关闭适配器,重新来搜索
  101. wx.openBluetoothAdapter({
  102. success: function (res) {
  103. wx.getBluetoothAdapterState({
  104. success: function (res) {
  105. wx.stopBluetoothDevicesDiscovery({
  106. success: function (res) {
  107. wx.startBluetoothDevicesDiscovery({
  108. success: function (res) {
  109. wx.onBluetoothDeviceFound(function (res) {
  110. var list = util.filterDevice(res.devices, "name");
  111. if (list.length > 0) {
  112. console.log('==========onBluetoothDeviceFound===========');
  113. console.log(list);
  114. var deviceList = self.data.deviceList;
  115. var doDevices = wx.getStorageSync('doDevices');
  116. if (doDevices) {
  117. } else {
  118. doDevices = [];
  119. }
  120. console.log(deviceList);
  121. console.log(doDevices);
  122. wx.setStorageSync('doDevices', doDevices);
  123. wx.hideLoading();
  124. list.forEach(function (item) {
  125. var flag = true;
  126. for (var i = 0; i < deviceList.length; i++) {
  127. var itemSub = deviceList[i];
  128. if (itemSub.deviceId === item.deviceId) {
  129. flag = false;
  130. break;
  131. }
  132. }
  133. if (flag) {
  134. var arrD = item['name'].split(' ');
  135. item['sn'] = arrD[1];
  136. wx.request({
  137. url: 'https://aipush.aidsleep.cn/checkbeds',
  138. method: 'POST',
  139. header: {
  140. 'content-type': 'application/json' // 设置请求的 header
  141. },
  142. data: {
  143. "snlists": arrD[1], // 需要发送的数据
  144. "token": "89835e65993fee4a6a6cbbe4c271da51e5521822934e13769e61cadabaed72c3"
  145. },
  146. success: function (res) {
  147. //console.log(res);
  148. if (res.data.data[arrD[1]].trim() == 'yes') {
  149. item['beOnline'] = 'icon-deng-ok';
  150. } else {
  151. item['beOnline'] = '';
  152. if (doDevices.indexOf(item['deviceId']) >= 0) {
  153. item['beOnline'] = 'icon-deng-ok';
  154. }
  155. }
  156. deviceList.push(item);
  157. self.setData({
  158. deviceList: deviceList,
  159. showBluetoothList:true
  160. });
  161. wx.setStorageSync('deviceList', deviceList);
  162. },
  163. fail: function (error) {
  164. console.error(error);
  165. }
  166. });
  167. }
  168. })
  169. }
  170. })
  171. }
  172. })
  173. },
  174. fail: function (res) {
  175. console.log(res);
  176. }
  177. });
  178. },
  179. fail: function (res) {
  180. console.log(res);
  181. }
  182. });
  183. },
  184. fail: function (res) {
  185. console.log(res);
  186. }
  187. });
  188. },
  189. commitBluetooth() {
  190. this.onClose();
  191. var deviceId = this.data.deviceList[this.data.bluetoothSelectIndex].deviceId;
  192. this.setData({
  193. deviceId: deviceId,
  194. sn:deviceId
  195. })
  196. },
  197. // 开始配网
  198. bindViewConnect() {
  199. const that = this;
  200. if (bluetoothSelectIndex < 0) {
  201. util.showToast("没有指定要配网的设备");
  202. return false;
  203. }
  204. var deviceIds = this.data.deviceList[this.data.bluetoothSelectIndex];
  205. if (this.data.deviceList.length == 0 || deviceIds.length === 0) {
  206. util.showToast("没有指定要配网的设备");
  207. return false;
  208. }
  209. that.gotoProvision()
  210. },
  211. // 获取Wifi
  212. getWifiInfo: function () {
  213. wx.startWifi({
  214. success(res) {
  215. //console.log(' ================== startWifi ================== ');
  216. //console.log(res);
  217. wx.getConnectedWifi({
  218. success(res) {
  219. },
  220. fail: function (err) {
  221. console.log(' ================== startWifi fail ================== ');
  222. console.log(err);
  223. if (app.data.sytem == 'ios') {
  224. util.showToast("获取Wi-Fi信息失败,请更新微信到最新版");
  225. } else {
  226. util.showToast("获取Wi-Fi信息失败");
  227. }
  228. }
  229. });
  230. }
  231. });
  232. const self = this;
  233. wx.startWifi({
  234. success(res) {
  235. //console.log(res)
  236. // 先取一次,防止IOS获取不到
  237. wx.getConnectedWifi({
  238. success(res) {
  239. self.setData({
  240. wifiInfo: res.wifi,
  241. ssid: res.wifi.SSID
  242. });
  243. //console.log('== getConnectedWifi ==');
  244. //console.log(res);
  245. if (res.frequency >= 2412 && res.frequency <= 2472) { } else {
  246. self.setData({
  247. notice: "温馨提示:当前您连接的Wi-Fi网络是5G频段,建议连接2.4G频段配网"
  248. })
  249. }
  250. },
  251. fail: function (err) {
  252. util.showToast("获取Wi-Fi信息失败");
  253. }
  254. })
  255. wx.onWifiConnected(function (res) {
  256. // console.log('== onWifiConnected ==');
  257. // console.log(res);
  258. self.setData({
  259. wifiInfo: res.wifi
  260. })
  261. })
  262. },
  263. fail(res) {
  264. console.log('WIFI初始化失败', res)
  265. util.showToast("WIFI初始化失败");
  266. }
  267. })
  268. },
  269. gotoProvision: function () {
  270. const wifiInfo = this.data.wifiInfo;
  271. const ssid = wifiInfo != null ? wifiInfo.SSID : null;
  272. const bssid = wifiInfo != null ? wifiInfo.BSSID : null;
  273. const password = this.data.password;
  274. if (wifiInfo == null) {
  275. util.showToast("没有Wi-Fi连接");
  276. return;
  277. } else {
  278. if (ssid == null || ssid == '' || password == '') {
  279. util.showToast("WiFi登录名和密码不能为空");
  280. return;
  281. } else {
  282. const info = {
  283. ssid: ssid,
  284. bssid: bssid,
  285. password: password,
  286. deviceIds: this.data.deviceId
  287. }
  288. this.blueConnect();
  289. }
  290. }
  291. },
  292. // 蓝牙链接
  293. blueConnect: function (event) {
  294. //console.log(' =============== blueConnect start ===============')
  295. var self = this;
  296. sequenceControl = 0;
  297. self.setData({
  298. flagEnd: false,
  299. serviceId: "",
  300. uuid: "",
  301. showBluetoothConnected:true
  302. });
  303. self.setProcess(0, util.descSucList[0],1);
  304. //第一步检查蓝牙适配器是否可用
  305. wx.onBluetoothAdapterStateChange(function (res) {
  306. if (!res.available) {
  307. util.showToast('蓝牙不可用');
  308. return false;
  309. }
  310. });
  311. //console.log(app.data);
  312. if (app.data.sytem == 'ios') {
  313. }
  314. //console.log('deviceId = ' + self.data.deviceId)
  315. wx.createBLEConnection({
  316. // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
  317. deviceId: self.data.deviceId,
  318. timeout: 10000,
  319. success: function (res) {
  320. wx.setBLEMTU({
  321. deviceId: self.data.deviceId,
  322. mtu: 128
  323. })
  324. //console.log("============ createBLEConnection success =============")
  325. //console.log(self.data.deviceId)
  326. self.getDeviceServices(self.data.deviceId);
  327. },
  328. fail: function (res) {
  329. console.log("============ createBLEConnection fail =============")
  330. console.log(res)
  331. console.log(self.data.blueConnectNum)
  332. var num = self.data.blueConnectNum;
  333. if (num < 3) {
  334. self.blueConnect();
  335. num++;
  336. self.setData({
  337. blueConnectNum: num
  338. })
  339. } else {
  340. self.setFailProcess(true, res.errCode + "::" + util.descFailList[0]);
  341. }
  342. }
  343. })
  344. },
  345. getDeviceServices: function (deviceId) {
  346. var self = this;
  347. wx.getBLEDeviceServices({
  348. // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
  349. deviceId: deviceId,
  350. success: function (res) {
  351. self.setProcess(10, util.descSucList[1],2);
  352. var services = res.services;
  353. if (services.length > 0) {
  354. for (var i = 0; i < services.length; i++) {
  355. var uuid = services[i].uuid;
  356. if (uuid == app.data.service_uuid) {
  357. self.getDeviceCharacteristics(deviceId, uuid);
  358. return false;
  359. }
  360. }
  361. }
  362. },
  363. fail: function (res) {
  364. self.setFailProcess(true, res.errCode + "::" + util.descFailList[1]);
  365. }
  366. })
  367. },
  368. getDeviceCharacteristics: function (deviceId, serviceId) {
  369. //console.log(" ============== getDeviceCharacteristics =============== ");
  370. var self = this;
  371. wx.getBLEDeviceCharacteristics({
  372. // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
  373. deviceId: deviceId,
  374. serviceId: serviceId,
  375. success: function (res) {
  376. self.setProcess(40, util.descSucList[2],3);
  377. var list = res.characteristics;
  378. if (list.length > 0) {
  379. for (var i = 0; i < list.length; i++) {
  380. var uuid = list[i].uuid;
  381. if (uuid == app.data.characteristic_write_uuid) {
  382. self.openNotify(deviceId, serviceId, uuid);
  383. self.setData({
  384. serviceId: serviceId,
  385. uuid: uuid,
  386. })
  387. return false;
  388. }
  389. }
  390. }
  391. },
  392. fail: function (res) {
  393. console.log(res);
  394. self.setFailProcess(true, res.errCode + "::" + util.descFailList[2]);
  395. }
  396. })
  397. },
  398. //连接超时
  399. onTimeout: function (num) {
  400. const self = this;
  401. timeId = setInterval(function () {
  402. if (num < timeOut) {
  403. num++;
  404. } else {
  405. clearInterval(timeId);
  406. self.setFailProcess(true, res.errCode + "::" + util.descFailList[4]);
  407. }
  408. }, 1000)
  409. },
  410. //启用通知
  411. openNotify: function (deviceId, serviceId, characteristicId) {
  412. //console.log("=========== openNotify ============");
  413. var self = this;
  414. wx.notifyBLECharacteristicValueChange({
  415. state: true, // 启用 notify 功能
  416. deviceId: deviceId,
  417. serviceId: serviceId,
  418. characteristicId: app.data.characteristic_read_uuid,
  419. success: function (res) {
  420. //console.log(res);
  421. self.writeDevice(deviceId, serviceId, characteristicId, null);
  422. self.onNotify();
  423. },
  424. fail: function (res) {
  425. console.log(res);
  426. }
  427. })
  428. },
  429. //监听通知
  430. onNotify: function () {
  431. //console.log("=========== onNotify ============");
  432. var self = this;
  433. wx.onBLECharacteristicValueChange(function (res) {
  434. //console.log(res);
  435. self.getResultType(util.ab2hex(res.value));
  436. })
  437. },
  438. // 设备数据开始写入
  439. writeDevice: function (deviceId, serviceId, characteristicId, data) {
  440. //console.log("===== writeDevice =====");
  441. var self = this,
  442. obj = {};
  443. self.setProcess(60, util.descSucList[4],3);
  444. sequenceControl = parseInt(sequenceControl) + 1;
  445. if (!util._isEmpty(data)) {
  446. obj = util.isSubcontractor(data, true, sequenceControl);
  447. } else {
  448. data = util.writeData(self.getCharCodeat('"' + self.data.ssid + '","' + self.data.password + '"'));
  449. obj = util.isSubcontractor(data, self.data.isChecksum, sequenceControl);
  450. }
  451. var typedArray = new Uint8Array(obj.lenData)
  452. wx.writeBLECharacteristicValue({
  453. deviceId: deviceId,
  454. serviceId: serviceId,
  455. characteristicId: characteristicId,
  456. value: typedArray.buffer,
  457. success: function (res) {
  458. //console.log(res);
  459. if (obj.flag) {
  460. self.writeDevice(deviceId, serviceId, characteristicId, obj.laveData);
  461. } else {
  462. self.setProcess(80, util.descSucList[5],4);
  463. }
  464. },
  465. fail: function (res) {
  466. console.log(res);
  467. self.setFailProcess(true, res.errCode + "::" + util.descFailList[3]);
  468. }
  469. })
  470. },
  471. getResultType: function (list) {
  472. console.log(' ========= getResultType ========= ');
  473. var self = this;
  474. console.log(list);
  475. var deviceList = wx.getStorageSync('deviceList');
  476. console.log(deviceList);
  477. if (list.length < 4) {
  478. self.setFailProcess(true, res.errCode + "::" + util.descFailList[4]);
  479. return false;
  480. }
  481. var val = list[4];
  482. if (val == "00") {
  483. var idx = self.data.deviceNo + 1;
  484. var doDevices = wx.getStorageSync('doDevices');
  485. if (doDevices) {
  486. if (doDevices.indexOf(self.data.deviceId) < 0) {
  487. doDevices.push(self.data.deviceId);
  488. }
  489. } else {
  490. doDevices = [self.data.deviceId];
  491. }
  492. wx.setStorageSync('doDevices', doDevices);
  493. var deviceSn = self.data.deviceId;
  494. for (var i = 0; i < deviceList.length; i++) {
  495. var itemSub = deviceList[i];
  496. if (itemSub.deviceId === self.data.deviceId) {
  497. deviceSn = itemSub.sn;
  498. break;
  499. }
  500. }
  501. if (idx < self.data.deviceIds.length) {
  502. self.setProcess(90, 'SN:' + deviceSn + ' 连接成功', 5);
  503. wx.closeBLEConnection({
  504. deviceId: self.data.deviceId,
  505. success: function (res) { }
  506. })
  507. self.setData({
  508. deviceNo: idx,
  509. deviceId: self.data.deviceIds[idx],
  510. blueConnectNum: 0
  511. });
  512. self.blueConnect();
  513. } else {
  514. self.setProcess(90, 'SN:' + deviceSn + ' 连接成功', 5);
  515. self.setProcess(100, util.descSucList[6],6);
  516. self.setData({
  517. result: [],
  518. })
  519. }
  520. } else {
  521. self.setFailProcess(true, res.errCode + "::" + util.descFailList[4])
  522. }
  523. },
  524. setProcess: function (value, desc,step = 0) {
  525. var self = this,
  526. list = [];
  527. list = self.data.processList;
  528. if (list.indexOf(desc) == -1) {
  529. list.push(desc);
  530. }
  531. if (self.data.value <= value) {
  532. self.setData({
  533. value: value,
  534. bluetoothConnectedStep:step
  535. });
  536. }
  537. self.setData({
  538. processList: list
  539. });
  540. //console.log(value);
  541. //console.log(desc);
  542. if (value == 100) {
  543. self.closeConnect();
  544. wx.closeBluetoothAdapter();
  545. self.setData({
  546. isBluetoothConnected:true,
  547. desc: util.descSucList[6]
  548. });
  549. clearInterval(timeId);
  550. sequenceControl = 0;
  551. }
  552. },
  553. setFailProcess: function (flag, desc) {
  554. var self = this,
  555. list = [];
  556. list = self.data.processList;
  557. list.push(desc);
  558. self.setData({
  559. failure: flag,
  560. processList: list
  561. });
  562. },
  563. closeConnect: function () {
  564. var self = this;
  565. wx.closeBLEConnection({
  566. deviceId: self.data.deviceId,
  567. success: function (res) { }
  568. })
  569. },
  570. /**
  571. * 生命周期函数--监听页面加载
  572. */
  573. onLoad(options) {
  574. this.getWifiInfo();
  575. if (options.type && options.type == "edit") {
  576. wx.setNavigationBarTitle({
  577. title:"编辑床垫"
  578. })
  579. const item = wx.getStorageSync("item");
  580. if (item) {
  581. this.setData({
  582. placeOfUse: item.location,
  583. usingHuman: item.person,
  584. sn: item.sn,
  585. ssid: "",
  586. password: "",
  587. })
  588. wx.removeStorageSync("item")
  589. }
  590. }
  591. },
  592. checkSn(sntram) {
  593. const that = this;
  594. wx.request({
  595. url: 'https://aipush.aidsleep.cn/customerlist',
  596. method: 'POST',
  597. data: {
  598. token: "89835e65993fee4a6a6cbbe4c271da51e5521822934e13769e61cadabaed72c3" || wx.getStorageSync('token'),
  599. sntram: sntram,
  600. },
  601. success: (res) => {
  602. var incustom = res.data.incustom;
  603. if (incustom == "true") {
  604. that.bindViewConnect();
  605. } else {
  606. wx.showToast({
  607. icon: 'none',
  608. title: "sn 不合法"
  609. });
  610. }
  611. },
  612. fail: () => {
  613. wx.showToast({
  614. icon: 'none',
  615. title: "sn 不合法"
  616. });
  617. }
  618. });
  619. },
  620. /**
  621. * 生命周期函数--监听页面初次渲染完成
  622. */
  623. onReady() {
  624. },
  625. /**
  626. * 生命周期函数--监听页面显示
  627. */
  628. onShow() {
  629. },
  630. /**
  631. * 生命周期函数--监听页面隐藏
  632. */
  633. onHide() {
  634. },
  635. /**
  636. * 生命周期函数--监听页面卸载
  637. */
  638. onUnload() {
  639. wx.offWifiConnected({});
  640. wx.stopWifi({})
  641. this.closeConnect()
  642. },
  643. /**
  644. * 页面相关事件处理函数--监听用户下拉动作
  645. */
  646. onPullDownRefresh() {
  647. },
  648. /**
  649. * 页面上拉触底事件的处理函数
  650. */
  651. onReachBottom() {
  652. },
  653. /**
  654. * 用户点击右上角分享
  655. */
  656. onShareAppMessage() {
  657. }
  658. })