xBlufi-wx-impl.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  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 {
  380. devices.devices[0].name = localName;
  381. devicesList.push(devices.devices[0]);
  382. }
  383. // if (name.includes("AIrSMArT") || localName.includes("AIrSMArT")) {
  384. // // devices.devices[0].name = name.includes("AIrSMArT") ? name : localName
  385. // console.log("打印2", JSON.stringify(devices.devices[0]))
  386. // }
  387. }
  388. } else if (devices[0]) {
  389. if (devices[0].advertisData) {
  390. devices[0].advertisData = buf2hex(devices[0].advertisData)
  391. } else {
  392. devices[0].advertisData = ''
  393. }
  394. for (var i = 0; i < devices_list.length; i++) {
  395. if (devices[0].deviceId == devicesList[i].deviceId) {
  396. isnotexist = false
  397. }
  398. }
  399. if (isnotexist) {
  400. console.log("打印3", devices[0].deviceId.inc)
  401. devicesList.push(devices[0])
  402. }
  403. }
  404. // console.log("打印:", newOptions);
  405. let obj = {
  406. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS,
  407. 'result': true,
  408. 'data': devicesList
  409. }
  410. mDeviceEvent.notifyDeviceMsgEvent(obj);
  411. })
  412. wx.startBluetoothDevicesDiscovery({
  413. allowDuplicatesKey: true,
  414. success: function (res) {
  415. let obj = {
  416. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_START,
  417. 'result': true,
  418. 'data': res
  419. }
  420. mDeviceEvent.notifyDeviceMsgEvent(obj);
  421. //开始扫码,清空列表
  422. devicesList.length = 0;
  423. },
  424. fail: function (res) {
  425. let obj = {
  426. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_START,
  427. 'result': false,
  428. 'data': res
  429. }
  430. mDeviceEvent.notifyDeviceMsgEvent(obj);
  431. }
  432. });
  433. },
  434. fail: function (res) {
  435. itue = true;
  436. let obj = {
  437. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_START,
  438. 'result': false,
  439. 'data': res
  440. }
  441. mDeviceEvent.notifyDeviceMsgEvent(obj);
  442. }
  443. });
  444. },
  445. fail: function (res) {
  446. itue = true;
  447. let obj = {
  448. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_START,
  449. 'result': false,
  450. 'data': res
  451. }
  452. mDeviceEvent.notifyDeviceMsgEvent(obj);
  453. }
  454. });
  455. },
  456. fail: function (res) {
  457. itue = true;
  458. let obj = {
  459. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_START,
  460. 'result': false,
  461. 'data': res
  462. }
  463. mDeviceEvent.notifyDeviceMsgEvent(obj);
  464. }
  465. });
  466. }
  467. });
  468. } else {
  469. wx.stopBluetoothDevicesDiscovery({
  470. success: function (res) {
  471. clearInterval(tempTimer);
  472. let obj = {
  473. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_STOP,
  474. 'result': true,
  475. 'data': res
  476. }
  477. mDeviceEvent.notifyDeviceMsgEvent(obj);
  478. },
  479. fail: function (res) {
  480. let obj = {
  481. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_STOP,
  482. 'result': false,
  483. 'data': res
  484. }
  485. mDeviceEvent.notifyDeviceMsgEvent(obj);
  486. }
  487. })
  488. }
  489. })
  490. mDeviceEvent.listenConnectBle(true, function (options) {
  491. console.log("我要连接====" + options.isStart);
  492. if (options.isStart)
  493. wx.createBLEConnection({
  494. deviceId: options.deviceId,
  495. success: function (res) {
  496. self.data.deviceId = options.deviceId
  497. mDeviceEvent.notifyDeviceMsgEvent({
  498. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_CONNECTED,
  499. 'result': true,
  500. 'data': {
  501. deviceId: options.deviceId,
  502. name: options.name
  503. },
  504. });
  505. },
  506. fail: function (res) {
  507. self.data.deviceId = null
  508. mDeviceEvent.notifyDeviceMsgEvent({
  509. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_CONNECTED,
  510. 'result': false,
  511. 'data': res,
  512. });
  513. }
  514. });
  515. else wx.closeBLEConnection({
  516. deviceId: options.deviceId,
  517. success: function (res) {
  518. console.log('断开成功')
  519. self.data.deviceId = null
  520. mDeviceEvent.notifyDeviceMsgEvent({
  521. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_CLOSE_CONNECTED,
  522. 'result': true,
  523. 'data': {
  524. deviceId: options.deviceId,
  525. name: options.name
  526. }
  527. });
  528. },
  529. fail: function (res) {
  530. self.data.deviceId = null
  531. mDeviceEvent.notifyDeviceMsgEvent({
  532. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_CLOSE_CONNECTED,
  533. 'result': false,
  534. 'data': res,
  535. });
  536. }
  537. })
  538. })
  539. mDeviceEvent.listenInitBleEsp32(true, function (options) {
  540. sequenceControl = 0;
  541. sequenceNumber = -1;
  542. self = null
  543. self = {
  544. data: {
  545. deviceId: null,
  546. isConnected: false,
  547. failure: false,
  548. value: 0,
  549. desc: "请耐心等待...",
  550. isChecksum: true,
  551. isEncrypt: true,
  552. flagEnd: false,
  553. defaultData: 1,
  554. ssidType: 2,
  555. passwordType: 3,
  556. meshIdType: 3,
  557. deviceId: "",
  558. ssid: "",
  559. uuid: "",
  560. serviceId: "",
  561. password: "",
  562. meshId: "",
  563. processList: [],
  564. result: [],
  565. service_uuid: "0000FFFF-0000-1000-8000-00805F9B34FB",
  566. characteristic_write_uuid: "0000FF01-0000-1000-8000-00805F9B34FB",
  567. characteristic_read_uuid: "0000FF02-0000-1000-8000-00805F9B34FB",
  568. customData: null,
  569. md5Key: 0,
  570. }
  571. }
  572. let deviceId = options.deviceId
  573. self.data.deviceId = options.deviceId
  574. wx.getBLEDeviceServices({
  575. // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
  576. deviceId: deviceId,
  577. success: function (res) {
  578. var services = res.services;
  579. if (services.length > 0) {
  580. for (var i = 0; i < services.length; i++) {
  581. if (services[i].uuid === self.data.service_uuid) {
  582. var serviceId = services[i].uuid;
  583. wx.getBLEDeviceCharacteristics({
  584. // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
  585. deviceId: deviceId,
  586. serviceId: serviceId,
  587. success: function (res) {
  588. var list = res.characteristics;
  589. if (list.length > 0) {
  590. for (var i = 0; i < list.length; i++) {
  591. var uuid = list[i].uuid;
  592. if (uuid == self.data.characteristic_write_uuid) {
  593. self.data.serviceId = serviceId;
  594. self.data.uuid = uuid;
  595. wx.notifyBLECharacteristicValueChange({
  596. state: true, // 启用 notify 功能
  597. deviceId: deviceId,
  598. serviceId: serviceId,
  599. characteristicId: list[1].uuid,
  600. success: function (res) {
  601. let characteristicId = self.data.characteristic_write_uuid
  602. //通知设备交互方式(是否加密) start
  603. client = util.blueDH(util.DH_P, util.DH_G, crypto);
  604. var kBytes = util.uint8ArrayToArray(client.getPublicKey());
  605. var pBytes = util.hexByInt(util.DH_P);
  606. var gBytes = util.hexByInt(util.DH_G);
  607. var pgkLength = pBytes.length + gBytes.length + kBytes.length + 6;
  608. var pgkLen1 = (pgkLength >> 8) & 0xff;
  609. var pgkLen2 = pgkLength & 0xff;
  610. var data = [];
  611. data.push(util.NEG_SET_SEC_TOTAL_LEN);
  612. data.push(pgkLen1);
  613. data.push(pgkLen2);
  614. var frameControl = util.getFrameCTRLValue(false, false, util.DIRECTION_OUTPUT, false, false);
  615. var value = util.writeData(util.PACKAGE_VALUE, util.SUBTYPE_NEG, frameControl, sequenceControl, data.length, data);
  616. var typedArray = new Uint8Array(value);
  617. wx.writeBLECharacteristicValue({
  618. deviceId: deviceId,
  619. serviceId: serviceId,
  620. characteristicId: characteristicId,
  621. value: typedArray.buffer,
  622. success: function (res) {
  623. getSecret(deviceId, serviceId, characteristicId, client, kBytes, pBytes, gBytes, null);
  624. },
  625. fail: function (res) {
  626. let obj = {
  627. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_INIT_ESP32_RESULT,
  628. 'result': false,
  629. 'data': res
  630. }
  631. mDeviceEvent.notifyDeviceMsgEvent(obj);
  632. }
  633. })
  634. //通知设备交互方式(是否加密) end
  635. wx.onBLECharacteristicValueChange(function (res) {
  636. let list2 = (util.ab2hex(res.value));
  637. // start
  638. let result = self.data.result;
  639. if (list2.length < 4) {
  640. cosnole.log(407);
  641. return false;
  642. }
  643. var val = parseInt(list2[0], 16),
  644. type = val & 3,
  645. subType = val >> 2;
  646. var dataLength = parseInt(list2[3], 16);
  647. if (dataLength == 0) {
  648. return false;
  649. }
  650. var fragNum = util.hexToBinArray(list2[1]);
  651. list2 = isEncrypt(fragNum, list2, self.data.md5Key);
  652. result = result.concat(list2);
  653. self.data.result = result
  654. if (self.data.flagEnd) {
  655. self.data.flagEnd = false
  656. if (type == 1) {
  657. let what = [];
  658. switch (subType) {
  659. case 15:
  660. if (result.length == 3) {
  661. mDeviceEvent.notifyDeviceMsgEvent({
  662. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_CONNECT_ROUTER_RESULT,
  663. 'result': false,
  664. 'data': {
  665. 'progress': 0,
  666. 'ssid': what.join('')
  667. }
  668. });
  669. } else {
  670. for (var i = 0; i <= result.length; i++) {
  671. var num = parseInt(result[i], 16) + "";
  672. if (i > 12) what.push(String.fromCharCode(parseInt(result[i], 16)));
  673. }
  674. mDeviceEvent.notifyDeviceMsgEvent({
  675. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_CONNECT_ROUTER_RESULT,
  676. 'result': true,
  677. 'data': {
  678. 'progress': 100,
  679. 'ssid': what.join('')
  680. }
  681. });
  682. }
  683. break;
  684. case 19: //自定义数据
  685. let customData = [];
  686. for (var i = 0; i <= result.length; i++) {
  687. customData.push(String.fromCharCode(parseInt(result[i], 16)));
  688. }
  689. let obj = {
  690. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_RECIEVE_CUSTON_DATA,
  691. 'result': true,
  692. 'data': customData.join('')
  693. }
  694. mDeviceEvent.notifyDeviceMsgEvent(obj);
  695. break;
  696. case util.SUBTYPE_NEGOTIATION_NEG:
  697. var arr = util.hexByInt(result.join(""));
  698. var clientSecret = client.computeSecret(new Uint8Array(arr));
  699. var md5Key = md5.array(clientSecret);
  700. self.data.md5Key = md5Key;
  701. mDeviceEvent.notifyDeviceMsgEvent({
  702. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_INIT_ESP32_RESULT,
  703. 'result': true,
  704. 'data': {
  705. deviceId,
  706. serviceId,
  707. characteristicId
  708. }
  709. });
  710. break;
  711. default:
  712. console.log(468);
  713. //self.setFailProcess(true, util.descFailList[4])
  714. console.log("入网失败 468 :", util.failList[4]);
  715. break;
  716. }
  717. self.data.result = []
  718. } else {
  719. //console.log(472);
  720. console.log("入网失败 472:", util.failList[4]);
  721. }
  722. }
  723. // end
  724. })
  725. },
  726. fail: function (res) {
  727. let obj = {
  728. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_INIT_ESP32_RESULT,
  729. 'result': false,
  730. 'data': res
  731. }
  732. mDeviceEvent.notifyDeviceMsgEvent(obj);
  733. }
  734. })
  735. }
  736. }
  737. }
  738. },
  739. fail: function (res) {
  740. let obj = {
  741. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_INIT_ESP32_RESULT,
  742. 'result': false,
  743. 'data': res
  744. }
  745. mDeviceEvent.notifyDeviceMsgEvent(obj);
  746. console.log("fail getBLEDeviceCharacteristics:" + JSON.stringify(res))
  747. }
  748. })
  749. break;
  750. }
  751. }
  752. }
  753. },
  754. fail: function (res) {
  755. let obj = {
  756. 'type': mDeviceEvent.XBLUFI_TYPE.TYPE_INIT_ESP32_RESULT,
  757. 'result': false,
  758. 'data': res
  759. }
  760. mDeviceEvent.notifyDeviceMsgEvent(obj);
  761. console.log("fail getBLEDeviceServices:" + JSON.stringify(res))
  762. }
  763. })
  764. })
  765. mDeviceEvent.listenSendRouterSsidAndPassword(true, function (options) {
  766. self.data.password = options.password
  767. self.data.ssid = options.ssid
  768. writeDeviceRouterInfoStart(self.data.deviceId, self.data.service_uuid, self.data.characteristic_write_uuid, null);
  769. })
  770. mDeviceEvent.listenSendCustomData(true, function (options) {
  771. self.data.customData = options.customData
  772. writeCutomsData(self.data.deviceId, self.data.service_uuid, self.data.characteristic_write_uuid, null);
  773. })
  774. }
  775. function ab2hex(buffer) {
  776. var hexArr = Array.prototype.map.call(
  777. new Uint8Array(buffer),
  778. function (bit) {
  779. return ('00' + bit.toString(16)).slice(-2)
  780. }
  781. )
  782. return hexArr.join('');
  783. }
  784. /****************************** 对外 ***************************************/
  785. module.exports = {
  786. init: init,
  787. };