xBlufi-wx-impl.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  1. const {
  2. isCN
  3. } = require('./../requestUtil.js');
  4. const {
  5. TextEncoder
  6. } = require('text-encoding');
  7. let tempTimer = 0;
  8. let client = null;
  9. let util = null
  10. let mDeviceEvent = null
  11. let crypto = null
  12. let md5 = null
  13. let aesjs = null
  14. const timeOut = 20; //超时时间
  15. var timeId = "";
  16. let sequenceControl = 0;
  17. let sequenceNumber = -1;
  18. let itue = true;
  19. let self = {
  20. data: {
  21. deviceId: null,
  22. isConnected: false,
  23. failure: false,
  24. value: 0,
  25. desc: "请耐心等待...",
  26. isChecksum: true,
  27. isEncrypt: true,
  28. flagEnd: false,
  29. defaultData: 1,
  30. ssidType: 2,
  31. passwordType: 3,
  32. meshIdType: 3,
  33. deviceId: "",
  34. ssid: "",
  35. uuid: "",
  36. serviceId: "",
  37. password: "",
  38. meshId: "",
  39. processList: [],
  40. result: [],
  41. service_uuid: "0000FFFF-0000-1000-8000-00805F9B34FB",
  42. characteristic_write_uuid: "0000FF01-0000-1000-8000-00805F9B34FB",
  43. characteristic_read_uuid: "0000FF02-0000-1000-8000-00805F9B34FB",
  44. customData: null,
  45. md5Key: 0,
  46. }
  47. }
  48. function buf2hex(buffer) {
  49. return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
  50. }
  51. function buf2string(buffer) {
  52. var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x);
  53. var str = '';
  54. for (var i = 0; i < arr.length; i++) {
  55. str += String.fromCharCode(arr[i]);
  56. }
  57. return str;
  58. }
  59. function getSsids(str) {
  60. var list = [],
  61. strs = str.split(":");
  62. for (var i = 0; i < strs.length; i++) {
  63. list.push(parseInt(strs[i], 16));
  64. }
  65. return list;
  66. }
  67. function getCharCodeat(str) {
  68. var list = [];
  69. const encoder = new TextEncoder('utf8');
  70. console.log(encoder);
  71. for (var i = 0; i < str.length; i++) {
  72. if (isCN(str[i])) {
  73. const t = encoder.encode(str[i]);
  74. for (var j = 0; j < t.length; j++) {
  75. list.push(t[j]);
  76. }
  77. } else {
  78. list.push(str.charCodeAt(i));
  79. }
  80. }
  81. return list;
  82. }
  83. //判断返回的数据是否加密
  84. function isEncrypt(fragNum, list, md5Key) {
  85. var checksum = [],
  86. checkData = [];
  87. if (fragNum[7] == "1") { //返回数据加密
  88. if (fragNum[6] == "1") {
  89. var len = list.length - 2;
  90. list = list.slice(0, len);
  91. }
  92. var iv = this.generateAESIV(parseInt(list[2], 16));
  93. if (fragNum[3] == "0") { //未分包
  94. list = list.slice(4);
  95. self.data.flagEnd = true
  96. } else { //分包
  97. list = list.slice(6);
  98. }
  99. } else { //返回数据未加密
  100. if (fragNum[6] == "1") {
  101. var len = list.length - 2;
  102. list = list.slice(0, len);
  103. }
  104. if (fragNum[3] == "0") { //未分包
  105. list = list.slice(4);
  106. self.data.flagEnd = true
  107. } else { //分包
  108. list = list.slice(6);
  109. }
  110. }
  111. return list;
  112. }
  113. function getSecret(deviceId, serviceId, characteristicId, client, kBytes, pBytes, gBytes, data) {
  114. var obj = [],
  115. frameControl = 0;
  116. sequenceControl = parseInt(sequenceControl) + 1;
  117. if (!util._isEmpty(data)) {
  118. obj = util.isSubcontractor(data, true, sequenceControl);
  119. frameControl = util.getFrameCTRLValue(false, true, util.DIRECTION_OUTPUT, false, obj.flag);
  120. } else {
  121. data = [];
  122. data.push(util.NEG_SET_SEC_ALL_DATA);
  123. var pLength = pBytes.length;
  124. var pLen1 = (pLength >> 8) & 0xff;
  125. var pLen2 = pLength & 0xff;
  126. data.push(pLen1);
  127. data.push(pLen2);
  128. data = data.concat(pBytes);
  129. var gLength = gBytes.length;
  130. var gLen1 = (gLength >> 8) & 0xff;
  131. var gLen2 = gLength & 0xff;
  132. data.push(gLen1);
  133. data.push(gLen2);
  134. data = data.concat(gBytes);
  135. var kLength = kBytes.length;
  136. var kLen1 = (kLength >> 8) & 0xff;
  137. var kLen2 = kLength & 0xff;
  138. data.push(kLen1);
  139. data.push(kLen2);
  140. data = data.concat(kBytes);
  141. obj = util.isSubcontractor(data, true, sequenceControl);
  142. frameControl = util.getFrameCTRLValue(false, true, util.DIRECTION_OUTPUT, false, obj.flag);
  143. }
  144. var value = util.writeData(util.PACKAGE_VALUE, util.SUBTYPE_NEG, frameControl, sequenceControl, obj.len, obj.lenData);
  145. var typedArray = new Uint8Array(value);
  146. wx.writeBLECharacteristicValue({
  147. deviceId: deviceId,
  148. serviceId: serviceId,
  149. characteristicId: characteristicId,
  150. value: typedArray.buffer,
  151. success: function (res) {
  152. if (obj.flag) {
  153. getSecret(deviceId, serviceId, characteristicId, client, kBytes, pBytes, gBytes, obj.laveData);
  154. }
  155. },
  156. fail: function (res) {}
  157. })
  158. }
  159. function writeDeviceRouterInfoStart(deviceId, serviceId, characteristicId, data) {
  160. var obj = {},
  161. frameControl = 0;
  162. sequenceControl = parseInt(sequenceControl) + 1;
  163. if (!util._isEmpty(data)) {
  164. obj = util.isSubcontractor(data, self.data.isChecksum, sequenceControl, self.data.isEncrypt);
  165. frameControl = util.getFrameCTRLValue(self.data.isEncrypt, self.data.isChecksum, util.DIRECTION_OUTPUT, false, obj.flag);
  166. } else {
  167. obj = util.isSubcontractor([self.data.defaultData], self.data.isChecksum, sequenceControl, true);
  168. frameControl = util.getFrameCTRLValue(self.data.isEncrypt, self.data.isChecksum, util.DIRECTION_OUTPUT, false, obj.flag);
  169. }
  170. var defaultData = util.encrypt(aesjs, self.data.md5Key, sequenceControl, obj.lenData, true);
  171. var value = util.writeData(util.PACKAGE_CONTROL_VALUE, util.SUBTYPE_WIFI_MODEl, frameControl, sequenceControl, obj.len, defaultData);
  172. var typedArray = new Uint8Array(value);
  173. wx.writeBLECharacteristicValue({
  174. deviceId: deviceId,
  175. serviceId: serviceId,
  176. characteristicId: characteristicId,
  177. value: typedArray.buffer,
  178. success: function (res) {
  179. if (obj.flag) {
  180. writeDeviceRouterInfoStart(deviceId, serviceId, characteristicId, obj.laveData);
  181. } else {
  182. writeRouterSsid(deviceId, serviceId, characteristicId, null);
  183. }
  184. },
  185. fail: function (res) {}
  186. })
  187. }
  188. function writeCutomsData(deviceId, serviceId, characteristicId, data) {
  189. var obj = {},
  190. frameControl = 0;
  191. sequenceControl = parseInt(sequenceControl) + 1;
  192. if (!util._isEmpty(data)) {
  193. obj = util.isSubcontractor(data, self.data.isChecksum, sequenceControl, self.data.isEncrypt);
  194. frameControl = util.getFrameCTRLValue(self.data.isEncrypt, self.data.isChecksum, util.DIRECTION_OUTPUT, false, obj.flag);
  195. } else {
  196. var ssidData = getCharCodeat(self.data.customData);
  197. obj = util.isSubcontractor(ssidData, self.data.isChecksum, sequenceControl, self.data.isEncrypt);
  198. frameControl = util.getFrameCTRLValue(self.data.isEncrypt, self.data.isChecksum, util.DIRECTION_OUTPUT, false, obj.flag);
  199. }
  200. var defaultData = util.encrypt(aesjs, self.data.md5Key, sequenceControl, obj.lenData, true);
  201. var value = util.writeData(util.PACKAGE_VALUE, util.SUBTYPE_CUSTOM_DATA, frameControl, sequenceControl, obj.len, defaultData);
  202. var typedArray = new Uint8Array(value);
  203. wx.writeBLECharacteristicValue({
  204. deviceId: deviceId,
  205. serviceId: serviceId,
  206. characteristicId: characteristicId,
  207. value: typedArray.buffer,
  208. success: function (res) {
  209. if (obj.flag) {
  210. writeCutomsData(deviceId, serviceId, characteristicId, obj.laveData);
  211. }
  212. },
  213. fail: function (res) {
  214. //console.log(257);
  215. }
  216. })
  217. }
  218. function writeRouterSsid(deviceId, serviceId, characteristicId, data) {
  219. var obj = {},
  220. frameControl = 0;
  221. sequenceControl = parseInt(sequenceControl) + 1;
  222. if (!util._isEmpty(data)) {
  223. obj = util.isSubcontractor(data, self.data.isChecksum, sequenceControl, self.data.isEncrypt);
  224. frameControl = util.getFrameCTRLValue(self.data.isEncrypt, self.data.isChecksum, util.DIRECTION_OUTPUT, false, obj.flag);
  225. } else {
  226. var ssidData = getCharCodeat(self.data.ssid);
  227. obj = util.isSubcontractor(ssidData, self.data.isChecksum, sequenceControl, self.data.isEncrypt);
  228. frameControl = util.getFrameCTRLValue(self.data.isEncrypt, self.data.isChecksum, util.DIRECTION_OUTPUT, false, obj.flag);
  229. }
  230. var defaultData = util.encrypt(aesjs, self.data.md5Key, sequenceControl, obj.lenData, true);
  231. var value = util.writeData(util.PACKAGE_VALUE, util.SUBTYPE_SET_SSID, frameControl, sequenceControl, obj.len, defaultData);
  232. var typedArray = new Uint8Array(value);
  233. wx.writeBLECharacteristicValue({
  234. deviceId: deviceId,
  235. serviceId: serviceId,
  236. characteristicId: characteristicId,
  237. value: typedArray.buffer,
  238. success: function (res) {
  239. if (obj.flag) {
  240. writeRouterSsid(deviceId, serviceId, characteristicId, obj.laveData);
  241. } else {
  242. writeDevicePwd(deviceId, serviceId, characteristicId, null);
  243. }
  244. },
  245. fail: function (res) {
  246. //console.log(257);
  247. }
  248. })
  249. }
  250. function writeDevicePwd(deviceId, serviceId, characteristicId, data) {
  251. var obj = {},
  252. frameControl = 0;
  253. sequenceControl = parseInt(sequenceControl) + 1;
  254. if (!util._isEmpty(data)) {
  255. obj = util.isSubcontractor(data, self.data.isChecksum, sequenceControl, self.data.isEncrypt);
  256. frameControl = util.getFrameCTRLValue(self.data.isEncrypt, self.data.isChecksum, util.DIRECTION_OUTPUT, false, obj.flag);
  257. } else {
  258. var pwdData = getCharCodeat(self.data.password);
  259. obj = util.isSubcontractor(pwdData, self.data.isChecksum, sequenceControl, self.data.isEncrypt);
  260. frameControl = util.getFrameCTRLValue(self.data.isEncrypt, self.data.isChecksum, util.DIRECTION_OUTPUT, false, obj.flag);
  261. }
  262. var defaultData = util.encrypt(aesjs, self.data.md5Key, sequenceControl, obj.lenData, true);
  263. var value = util.writeData(util.PACKAGE_VALUE, util.SUBTYPE_SET_PWD, frameControl, sequenceControl, obj.len, defaultData);
  264. var typedArray = new Uint8Array(value);
  265. wx.writeBLECharacteristicValue({
  266. deviceId: deviceId,
  267. serviceId: serviceId,
  268. characteristicId: characteristicId,
  269. value: typedArray.buffer,
  270. success: function (res) {
  271. if (obj.flag) {
  272. writeDevicePwd(deviceId, serviceId, characteristicId, obj.laveData);
  273. } else {
  274. writeDeviceEnd(deviceId, serviceId, characteristicId, null);
  275. }
  276. },
  277. fail: function (res) {}
  278. })
  279. }
  280. function writeDeviceEnd(deviceId, serviceId, characteristicId) {
  281. sequenceControl = parseInt(sequenceControl) + 1;
  282. var frameControl = util.getFrameCTRLValue(self.data.isEncrypt, false, util.DIRECTION_OUTPUT, false, false);
  283. var value = util.writeData(self.data.PACKAGE_CONTROL_VALUE, util.SUBTYPE_END, frameControl, sequenceControl, 0, null);
  284. var typedArray = new Uint8Array(value);
  285. wx.writeBLECharacteristicValue({
  286. deviceId: deviceId,
  287. serviceId: serviceId,
  288. characteristicId: characteristicId,
  289. value: typedArray.buffer,
  290. success: function (res) {
  291. },
  292. fail: function (res) {
  293. }
  294. })
  295. }
  296. function init() {
  297. let mOnFire = require("other/onfire.js");
  298. mDeviceEvent = require('xBlufi.js');
  299. util = require('../../utils/blufi/util.js');
  300. crypto = require('../../utils/blufi/crypto/crypto-dh.js');
  301. md5 = require('../../utils/blufi/crypto/md5.min.js');
  302. aesjs = require('../../utils/blufi/crypto/aes.js');
  303. wx.onBLEConnectionStateChange(function (res) {
  304. let obj = {
  305. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_STATUS_CONNECTED,
  306. 'result': res.connected,
  307. 'data': res
  308. }
  309. mDeviceEvent.notifyDeviceMsgEvent(obj);
  310. })
  311. mDeviceEvent.listenStartDiscoverBle(true, function (options) {
  312. if (options.isStart) {
  313. //第一步检查蓝牙适配器是否可用
  314. wx.onBluetoothAdapterStateChange(function (res) {
  315. if (!res.available) {}
  316. });
  317. if (!itue) {
  318. return;
  319. };
  320. itue = false;
  321. //第二步关闭适配器,重新来搜索
  322. wx.closeBluetoothAdapter({
  323. complete: function (res) {
  324. wx.openBluetoothAdapter({
  325. success: function (res) {
  326. wx.getBluetoothAdapterState({
  327. success: function (res) {
  328. wx.stopBluetoothDevicesDiscovery({
  329. success: function (res) {
  330. itue = true;
  331. let devicesList = [];
  332. let countsTimes = 0;
  333. wx.onBluetoothDeviceFound(function (devices) {
  334. //剔除重复设备,兼容不同设备API的不同返回值
  335. // let newOptions = devices.devices;
  336. // newOptions.forEach((v) => {
  337. // // let name = v.name ?? ""
  338. // let deviceId = v.deviceId ?? ""
  339. // // let localName =v.localName ?? ""
  340. // // if (name && name.includes("MW") ) {
  341. // if (deviceId && deviceId.includes("AAA4E8D0")) {
  342. // // let deviceStr = `${v.name ?? ""}, ${v.localName ?? ""}; `;
  343. // // deviceInfoStr += deviceStr;
  344. // console.log("搜索到的MW设备信息2:", mDeviceEvent.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS, JSON.stringify(v));
  345. // }
  346. // })
  347. var isnotexist = true;
  348. if (devices.deviceId) {
  349. if (devices.advertisData) {
  350. devices.advertisData = buf2hex(devices.advertisData)
  351. } else {
  352. devices.advertisData = ''
  353. }
  354. for (var i = 0; i < devicesList.length; i++) {
  355. if (devices.deviceId === devicesList[i].deviceId) {
  356. isnotexist = false
  357. }
  358. }
  359. if (isnotexist) {
  360. console.log("打印1")
  361. devicesList.push(devices)
  362. }
  363. } else if (devices.devices) {
  364. if (devices.devices[0].advertisData) {
  365. devices.devices[0].advertisData = buf2hex(devices.devices[0].advertisData)
  366. } else {
  367. devices.devices[0].advertisData = ''
  368. }
  369. for (var i = 0; i < devicesList.length; i++) {
  370. if (devices.devices[0].deviceId == devicesList[i].deviceId) {
  371. isnotexist = false
  372. }
  373. }
  374. if (isnotexist) {
  375. let name = devices.devices[0].name ?? ""
  376. let localName = devices.devices[0].localName ?? ""
  377. //AIrSMArT_d03110061a08
  378. // AIrSMArT_d03110c71019
  379. if (name.includes("MW_BLE") && localName === "") {} else if (
  380. name.includes("MW_BLE") && localName.includes("AIrSMArT")
  381. ) {
  382. devices.devices[0].name = localName;
  383. devicesList.push(devices.devices[0]);
  384. } else {
  385. devicesList.push(devices.devices[0]);
  386. }
  387. // if (name.includes("AIrSMArT") || localName.includes("AIrSMArT")) {
  388. // // devices.devices[0].name = name.includes("AIrSMArT") ? name : localName
  389. // console.log("打印2", JSON.stringify(devices.devices[0]))
  390. // }
  391. }
  392. } else if (devices[0]) {
  393. if (devices[0].advertisData) {
  394. devices[0].advertisData = buf2hex(devices[0].advertisData)
  395. } else {
  396. devices[0].advertisData = ''
  397. }
  398. for (var i = 0; i < devices_list.length; i++) {
  399. if (devices[0].deviceId == devicesList[i].deviceId) {
  400. isnotexist = false
  401. }
  402. }
  403. if (isnotexist) {
  404. console.log("打印3", devices[0].deviceId.inc)
  405. devicesList.push(devices[0])
  406. }
  407. }
  408. // console.log("打印:", newOptions);
  409. let obj = {
  410. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS,
  411. 'result': true,
  412. 'data': devicesList
  413. }
  414. mDeviceEvent.notifyDeviceMsgEvent(obj);
  415. })
  416. wx.startBluetoothDevicesDiscovery({
  417. allowDuplicatesKey: true,
  418. success: function (res) {
  419. let obj = {
  420. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_START,
  421. 'result': true,
  422. 'data': res
  423. }
  424. mDeviceEvent.notifyDeviceMsgEvent(obj);
  425. //开始扫码,清空列表
  426. devicesList.length = 0;
  427. },
  428. fail: function (res) {
  429. let obj = {
  430. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_START,
  431. 'result': false,
  432. 'data': res
  433. }
  434. mDeviceEvent.notifyDeviceMsgEvent(obj);
  435. }
  436. });
  437. },
  438. fail: function (res) {
  439. itue = true;
  440. let obj = {
  441. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_START,
  442. 'result': false,
  443. 'data': res
  444. }
  445. mDeviceEvent.notifyDeviceMsgEvent(obj);
  446. }
  447. });
  448. },
  449. fail: function (res) {
  450. itue = true;
  451. let obj = {
  452. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_START,
  453. 'result': false,
  454. 'data': res
  455. }
  456. mDeviceEvent.notifyDeviceMsgEvent(obj);
  457. }
  458. });
  459. },
  460. fail: function (res) {
  461. itue = true;
  462. let obj = {
  463. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_START,
  464. 'result': false,
  465. 'data': res
  466. }
  467. mDeviceEvent.notifyDeviceMsgEvent(obj);
  468. }
  469. });
  470. }
  471. });
  472. } else {
  473. wx.stopBluetoothDevicesDiscovery({
  474. success: function (res) {
  475. clearInterval(tempTimer);
  476. let obj = {
  477. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_STOP,
  478. 'result': true,
  479. 'data': res
  480. }
  481. mDeviceEvent.notifyDeviceMsgEvent(obj);
  482. },
  483. fail: function (res) {
  484. let obj = {
  485. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_STOP,
  486. 'result': false,
  487. 'data': res
  488. }
  489. mDeviceEvent.notifyDeviceMsgEvent(obj);
  490. }
  491. })
  492. }
  493. })
  494. mDeviceEvent.listenConnectBle(true, function (options) {
  495. console.log("我要连接====" + options.isStart);
  496. if (options.isStart)
  497. wx.createBLEConnection({
  498. deviceId: options.deviceId,
  499. success: function (res) {
  500. self.data.deviceId = options.deviceId
  501. mDeviceEvent.notifyDeviceMsgEvent({
  502. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_CONNECTED,
  503. 'result': true,
  504. 'data': {
  505. deviceId: options.deviceId,
  506. name: options.name
  507. },
  508. });
  509. },
  510. fail: function (res) {
  511. self.data.deviceId = null
  512. mDeviceEvent.notifyDeviceMsgEvent({
  513. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_CONNECTED,
  514. 'result': false,
  515. 'data': res,
  516. });
  517. }
  518. });
  519. else wx.closeBLEConnection({
  520. deviceId: options.deviceId,
  521. success: function (res) {
  522. console.log('断开成功')
  523. self.data.deviceId = null
  524. mDeviceEvent.notifyDeviceMsgEvent({
  525. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_CLOSE_CONNECTED,
  526. 'result': true,
  527. 'data': {
  528. deviceId: options.deviceId,
  529. name: options.name
  530. }
  531. });
  532. },
  533. fail: function (res) {
  534. self.data.deviceId = null
  535. mDeviceEvent.notifyDeviceMsgEvent({
  536. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_CLOSE_CONNECTED,
  537. 'result': false,
  538. 'data': res,
  539. });
  540. }
  541. })
  542. })
  543. mDeviceEvent.listenInitBleEsp32(true, function (options) {
  544. sequenceControl = 0;
  545. sequenceNumber = -1;
  546. self = null
  547. self = {
  548. data: {
  549. deviceId: null,
  550. isConnected: false,
  551. failure: false,
  552. value: 0,
  553. desc: "请耐心等待...",
  554. isChecksum: true,
  555. isEncrypt: true,
  556. flagEnd: false,
  557. defaultData: 1,
  558. ssidType: 2,
  559. passwordType: 3,
  560. meshIdType: 3,
  561. deviceId: "",
  562. ssid: "",
  563. uuid: "",
  564. serviceId: "",
  565. password: "",
  566. meshId: "",
  567. processList: [],
  568. result: [],
  569. service_uuid: "0000FFFF-0000-1000-8000-00805F9B34FB",
  570. characteristic_write_uuid: "0000FF01-0000-1000-8000-00805F9B34FB",
  571. characteristic_read_uuid: "0000FF02-0000-1000-8000-00805F9B34FB",
  572. customData: null,
  573. md5Key: 0,
  574. }
  575. }
  576. let deviceId = options.deviceId
  577. self.data.deviceId = options.deviceId
  578. wx.getBLEDeviceServices({
  579. // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
  580. deviceId: deviceId,
  581. success: function (res) {
  582. var services = res.services;
  583. if (services.length > 0) {
  584. for (var i = 0; i < services.length; i++) {
  585. if (services[i].uuid === self.data.service_uuid) {
  586. var serviceId = services[i].uuid;
  587. wx.getBLEDeviceCharacteristics({
  588. // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
  589. deviceId: deviceId,
  590. serviceId: serviceId,
  591. success: function (res) {
  592. var list = res.characteristics;
  593. if (list.length > 0) {
  594. for (var i = 0; i < list.length; i++) {
  595. var uuid = list[i].uuid;
  596. if (uuid == self.data.characteristic_write_uuid) {
  597. self.data.serviceId = serviceId;
  598. self.data.uuid = uuid;
  599. wx.notifyBLECharacteristicValueChange({
  600. state: true, // 启用 notify 功能
  601. deviceId: deviceId,
  602. serviceId: serviceId,
  603. characteristicId: list[1].uuid,
  604. success: function (res) {
  605. let characteristicId = self.data.characteristic_write_uuid
  606. //通知设备交互方式(是否加密) start
  607. client = util.blueDH(util.DH_P, util.DH_G, crypto);
  608. var kBytes = util.uint8ArrayToArray(client.getPublicKey());
  609. var pBytes = util.hexByInt(util.DH_P);
  610. var gBytes = util.hexByInt(util.DH_G);
  611. var pgkLength = pBytes.length + gBytes.length + kBytes.length + 6;
  612. var pgkLen1 = (pgkLength >> 8) & 0xff;
  613. var pgkLen2 = pgkLength & 0xff;
  614. var data = [];
  615. data.push(util.NEG_SET_SEC_TOTAL_LEN);
  616. data.push(pgkLen1);
  617. data.push(pgkLen2);
  618. var frameControl = util.getFrameCTRLValue(false, false, util.DIRECTION_OUTPUT, false, false);
  619. var value = util.writeData(util.PACKAGE_VALUE, util.SUBTYPE_NEG, frameControl, sequenceControl, data.length, data);
  620. var typedArray = new Uint8Array(value);
  621. wx.writeBLECharacteristicValue({
  622. deviceId: deviceId,
  623. serviceId: serviceId,
  624. characteristicId: characteristicId,
  625. value: typedArray.buffer,
  626. success: function (res) {
  627. getSecret(deviceId, serviceId, characteristicId, client, kBytes, pBytes, gBytes, null);
  628. },
  629. fail: function (res) {
  630. let obj = {
  631. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_INIT_ESP32_RESULT,
  632. 'result': false,
  633. 'data': res
  634. }
  635. mDeviceEvent.notifyDeviceMsgEvent(obj);
  636. }
  637. })
  638. //通知设备交互方式(是否加密) end
  639. wx.onBLECharacteristicValueChange(function (res) {
  640. let list2 = (util.ab2hex(res.value));
  641. // start
  642. let result = self.data.result;
  643. if (list2.length < 4) {
  644. cosnole.log(407);
  645. return false;
  646. }
  647. var val = parseInt(list2[0], 16),
  648. type = val & 3,
  649. subType = val >> 2;
  650. var dataLength = parseInt(list2[3], 16);
  651. if (dataLength == 0) {
  652. return false;
  653. }
  654. var fragNum = util.hexToBinArray(list2[1]);
  655. list2 = isEncrypt(fragNum, list2, self.data.md5Key);
  656. result = result.concat(list2);
  657. self.data.result = result
  658. if (self.data.flagEnd) {
  659. self.data.flagEnd = false
  660. if (type == 1) {
  661. let what = [];
  662. switch (subType) {
  663. case 15:
  664. if (result.length == 3) {
  665. mDeviceEvent.notifyDeviceMsgEvent({
  666. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_CONNECT_ROUTER_RESULT,
  667. 'result': false,
  668. 'data': {
  669. 'progress': 0,
  670. 'ssid': what.join('')
  671. }
  672. });
  673. } else {
  674. for (var i = 0; i <= result.length; i++) {
  675. var num = parseInt(result[i], 16) + "";
  676. if (i > 12) what.push(String.fromCharCode(parseInt(result[i], 16)));
  677. }
  678. mDeviceEvent.notifyDeviceMsgEvent({
  679. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_CONNECT_ROUTER_RESULT,
  680. 'result': true,
  681. 'data': {
  682. 'progress': 100,
  683. 'ssid': what.join('')
  684. }
  685. });
  686. }
  687. break;
  688. case 19: //自定义数据
  689. let customData = [];
  690. for (var i = 0; i <= result.length; i++) {
  691. customData.push(String.fromCharCode(parseInt(result[i], 16)));
  692. }
  693. let obj = {
  694. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_RECIEVE_CUSTON_DATA,
  695. 'result': true,
  696. 'data': customData.join('')
  697. }
  698. mDeviceEvent.notifyDeviceMsgEvent(obj);
  699. break;
  700. case util.SUBTYPE_NEGOTIATION_NEG:
  701. var arr = util.hexByInt(result.join(""));
  702. var clientSecret = client.computeSecret(new Uint8Array(arr));
  703. var md5Key = md5.array(clientSecret);
  704. self.data.md5Key = md5Key;
  705. mDeviceEvent.notifyDeviceMsgEvent({
  706. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_INIT_ESP32_RESULT,
  707. 'result': true,
  708. 'data': {
  709. deviceId,
  710. serviceId,
  711. characteristicId
  712. }
  713. });
  714. break;
  715. default:
  716. console.log(468);
  717. //self.setFailProcess(true, util.descFailList[4])
  718. console.log("入网失败 468 :", util.failList[4]);
  719. break;
  720. }
  721. self.data.result = []
  722. } else {
  723. //console.log(472);
  724. console.log("入网失败 472:", util.failList[4]);
  725. }
  726. }
  727. // end
  728. })
  729. },
  730. fail: function (res) {
  731. let obj = {
  732. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_INIT_ESP32_RESULT,
  733. 'result': false,
  734. 'data': res
  735. }
  736. mDeviceEvent.notifyDeviceMsgEvent(obj);
  737. }
  738. })
  739. }
  740. }
  741. }
  742. },
  743. fail: function (res) {
  744. let obj = {
  745. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_INIT_ESP32_RESULT,
  746. 'result': false,
  747. 'data': res
  748. }
  749. mDeviceEvent.notifyDeviceMsgEvent(obj);
  750. console.log("fail getBLEDeviceCharacteristics:" + JSON.stringify(res))
  751. }
  752. })
  753. break;
  754. }
  755. }
  756. }
  757. },
  758. fail: function (res) {
  759. let obj = {
  760. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_INIT_ESP32_RESULT,
  761. 'result': false,
  762. 'data': res
  763. }
  764. mDeviceEvent.notifyDeviceMsgEvent(obj);
  765. console.log("fail getBLEDeviceServices:" + JSON.stringify(res))
  766. }
  767. })
  768. })
  769. mDeviceEvent.listenSendRouterSsidAndPassword(true, function (options) {
  770. self.data.password = options.password
  771. self.data.ssid = options.ssid
  772. writeDeviceRouterInfoStart(self.data.deviceId, self.data.service_uuid, self.data.characteristic_write_uuid, null);
  773. })
  774. mDeviceEvent.listenSendCustomData(true, function (options) {
  775. self.data.customData = options.customData
  776. writeCutomsData(self.data.deviceId, self.data.service_uuid, self.data.characteristic_write_uuid, null);
  777. })
  778. }
  779. function ab2hex(buffer) {
  780. var hexArr = Array.prototype.map.call(
  781. new Uint8Array(buffer),
  782. function (bit) {
  783. return ('00' + bit.toString(16)).slice(-2)
  784. }
  785. )
  786. return hexArr.join('');
  787. }
  788. /****************************** 对外 ***************************************/
  789. module.exports = {
  790. init: init,
  791. };