bt_helper.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. // 引入必要的模块
  2. // const DeviceUtil = require('./DeviceUtil');
  3. // const BtAndroidHelper = require('./BtAndroidHelper');
  4. // const BtIOSHelper = require('./BtIOSHelper');
  5. // const QueueManager = require('./QueueManager');
  6. // const DeviceManager = require('./DeviceManager');
  7. const {
  8. CmdBase,
  9. BtCmd,
  10. } = require('./../devices/bluetooth/bt_cmd');
  11. const BtParse = require('./../devices/bluetooth/bt_parse');
  12. // const VolumeUtil = require('./VolumeUtil');
  13. // const EventManager = require('./EventManager');
  14. // const CmdBase = require('./../devices/bluetooth/bt_cmd');
  15. const bleManager = require('./ble_manager');
  16. const QueueManager = require('./QueueManager');
  17. // const EnumConnectStatus = require('./EnumConnectStatus');
  18. // const EnumOpen = require('./EnumOpen');
  19. // const EnumSupplier = require('./EnumSupplier');
  20. // const EnumLowDelayModeOpen = require('./EnumLowDelayModeOpen');
  21. // const EnumLowDelayMode = require('./EnumLowDelayMode');
  22. // const EnumPlayStatus = require('./EnumPlayStatus');
  23. class BtHelper {
  24. static getInstance() {
  25. // if (!BtHelper._instance) {
  26. // BtHelper._instance = new BtHelper();
  27. // }
  28. return BtHelper._instance;
  29. }
  30. static _instance = new BtHelper();
  31. static _isConnecting = false;
  32. static isDisConnectByOTA = false;
  33. // _helper;
  34. constructor() {
  35. this.timer = null;
  36. this.bleManager = new bleManager();
  37. // if (DeviceUtil.isAndroid) {
  38. // this._helper = BtAndroidHelper.instance;
  39. // } else {
  40. // this._helper = BtIOSHelper.instance;
  41. // }
  42. // QueueManager.instance.listenTask((task) => {
  43. // if (!DeviceManager.instance.isWatch) {
  44. // this._helper.send({ cmd: task });
  45. // }
  46. // });
  47. this.queueManager = new QueueManager();
  48. let _this = this
  49. this.queueManager.clear();
  50. this.queueManager.listenTask((task) => {
  51. _this.bleManager.sendData(task);
  52. });
  53. }
  54. resetConnectState(connect) {
  55. // BtHelper._isConnecting = connect;
  56. }
  57. async search(stopCall) {
  58. let res = await this.bleManager.startScan();
  59. this.timer = null;
  60. this.timer = setTimeout(() => {
  61. this.stopSearch();
  62. if (stopCall) {
  63. stopCall()
  64. }
  65. }, 10000);
  66. // console.log(res);
  67. // return await this._helper.search();
  68. }
  69. async findDevices(callback) {
  70. this.bleManager.onBluetoothDeviceFound(callback)
  71. // return await this._helper.search();
  72. }
  73. async stopSearch() {
  74. clearTimeout(this.timer);
  75. this.timer = null;
  76. await this.bleManager.stopScan();
  77. }
  78. async _connectSuccess() {
  79. this.checkDevice()
  80. this.getDeviceInfo()
  81. }
  82. async connect(data, onChanged) {
  83. // await this._helper.connect({ data, onChanged, isClick });
  84. clearTimeout(this.timer);
  85. this.timer = null;
  86. this.bleManager.stopScan()
  87. var res = await this.bleManager.connectToDevice(data);
  88. console.log(res ? '连接成功' : '连接失败');
  89. // this.setData({ connectedDeviceId: deviceId });
  90. if (res === false) {
  91. console.log("连接失败")
  92. this.disconnect(data)
  93. if (onChanged) {
  94. onChanged(false)
  95. }
  96. return
  97. }
  98. const serviceId = await this.bleManager.discoverServices(data.deviceId);
  99. if (serviceId == "") {
  100. console.log("连接失败")
  101. this.disconnect(data)
  102. if (onChanged) {
  103. onChanged(false)
  104. }
  105. return
  106. }
  107. // this.setData({ services });
  108. console.log("服务ID:" + serviceId)
  109. var characteristics = await this.bleManager.discoverCharacteristics(data.deviceId, serviceId)
  110. if (characteristics == "") {
  111. console.log("连接失败")
  112. this.disconnect(data)
  113. if (onChanged) {
  114. onChanged(false)
  115. }
  116. return
  117. }
  118. console.log('device特征值:', characteristics)
  119. // let uuids = ["ab00", "ffc0"];
  120. for (let i = 0; i < characteristics.length; i++) {
  121. let charc = characteristics[i];
  122. // if (!uuids.includes(charc.uuid)) {
  123. // if (onChanged) {
  124. // console.log('没有特征值:', charc.uuid);
  125. // onChanged(false)
  126. // }
  127. // return;
  128. // }
  129. if (charc.properties.notify) {
  130. console.log('订阅数据:', charc.uuid);
  131. // 订阅的
  132. this.bleManager.notifyCharacteristicValueChange(charc.uuid, (res) => {
  133. BtParse.parseTLV(res);
  134. })
  135. }
  136. if (charc.properties.write || charc.properties.writeWithoutResponse) {
  137. // 写入的
  138. this.bleManager.setWrite(charc, charc.uuid)
  139. setTimeout(() => {
  140. this._connectSuccess()
  141. }, 500);
  142. if (onChanged) {
  143. onChanged(true)
  144. }
  145. }
  146. // if (charc.properties.read) {
  147. // var chara = await this.bleManager.readCharacteristicValue(charc.uuid,)
  148. // }
  149. }
  150. // this.setData({ characteristics: { ...this.data.characteristics, [service.uuid]: characteristics } });
  151. }
  152. async disconnect(data) {
  153. this.bleManager.disconnect(data.deviceId)
  154. }
  155. async dispose() {
  156. // await this._helper.dispose();
  157. }
  158. async sendNow(cmd) {
  159. if (cmd) {
  160. this.bleManager.sendData(cmd)
  161. }
  162. }
  163. async send(cmd, type) {
  164. if (cmd) {
  165. this.queueManager.addTask(cmd)
  166. }
  167. // QueueManager.instance.addTask({ task: cmd });
  168. }
  169. // onLoad: function () {
  170. // bleManager = new bleManager();
  171. // this.initBluetooth();
  172. // }
  173. ///初始化蓝牙
  174. async initBluetooth(callback) {
  175. var that = this;
  176. let adpter = await that.bleManager.initBluetoothAdapter((res) => {
  177. if (!res) {
  178. wx.showToast({
  179. title: '请开启蓝牙功能',
  180. icon: 'none'
  181. })
  182. if (callback) {
  183. callback(false, false)
  184. }
  185. return
  186. }
  187. });
  188. // console.log(res)
  189. that.bleManager.checkBluetoothPermission(function (per) {
  190. if (!per) {
  191. wx.showToast({
  192. title: '没有蓝牙权限',
  193. icon: 'none'
  194. })
  195. }
  196. if (callback) {
  197. callback(adpter, per)
  198. }
  199. });
  200. }
  201. closeBle() {
  202. var that = this;
  203. that.bleManager.closeBle()
  204. }
  205. async getConnectedDevices() {
  206. try {
  207. const connectedDevices = await this.bleManager.getConnectedDevices();
  208. console.log("全部设备1:", connectedDevices)
  209. if (connectedDevices.length) {
  210. // todo 已经连接上的设备
  211. }
  212. const allDevices = await this.bleManager.getAllConnectedDevices()
  213. console.log("全部设备2:", allDevices)
  214. let newDevices = connectedDevices.concat(allDevices);
  215. return newDevices
  216. } catch (error) {
  217. console.error(error);
  218. return []
  219. }
  220. }
  221. async checkDevice() {
  222. // console.log("校验设备:", BtCmd); // 输出: EarPhone Info
  223. this.sendNow(BtCmd.checkDevice());
  224. //2.0有发这个,不知道是啥
  225. this.send([0x54, 0x44, 0x44, 0x48, 0x01, 0x09, 0x26, 0x01, 0x01]);
  226. }
  227. async getVersion() {
  228. this.send(BtCmd.queryVersion());
  229. }
  230. _time() {
  231. return 400;
  232. }
  233. getDeviceInfo() {
  234. // if (DeviceManager.instance.isEarphone) {
  235. // this.send(BtCmd.queryKwhEarPhone);
  236. // this.send(BtCmd.queryLowDelayMode);
  237. // this.send(BtCmd.queryEQ);
  238. // this.send(BtCmd.queryLowPower);
  239. // this.send(BtCmd.queryCtrlStatus);
  240. // } else {
  241. // this.send(BtCmd.setDevTime());
  242. this.send(BtCmd.queryKwh());
  243. this.getSleep();
  244. this.getAlert();
  245. this.send(BtCmd.queryRGB());
  246. this.getVolume();
  247. this.setVolume(8)
  248. this.getPauseSleep();
  249. // }
  250. }
  251. async getAlert() {
  252. this.send(BtCmd.queryAlarm());
  253. }
  254. async getSleep() {
  255. this.send(BtCmd.querySleep());
  256. }
  257. async setAlert(open, weekCycle, hour, minutes, channel = 1) {
  258. this.send(BtCmd.setAlarm({
  259. switchStatus: open,
  260. weekCycle,
  261. hour,
  262. minutes
  263. }));
  264. }
  265. async setAutoPlay(open) {
  266. this.send(BtCmd.setAutoPlay({
  267. switchStatus: open
  268. }));
  269. }
  270. async getAutoPlay() {
  271. this.send(BtCmd.getAutoPlay);
  272. }
  273. async setLowKwhWarningTone(notify) {
  274. this.send(BtCmd.setLowKwhWarningTone({
  275. notify
  276. }));
  277. }
  278. async setPauseSleep(time) {
  279. this.send(BtCmd.setSleepAfterPlayPause({
  280. time
  281. }));
  282. }
  283. async getPauseSleep() {
  284. this.send(BtCmd.querySleepAfterPlayPause());
  285. }
  286. async setRGB(r, g, b) {
  287. this.send(BtCmd.setRGB({
  288. r,
  289. g,
  290. b
  291. }));
  292. }
  293. async setSleep(open, hour, minutes) {
  294. this.send(BtCmd.setSleep({
  295. switchStatus: open,
  296. hour,
  297. minutes
  298. }));
  299. }
  300. async setTime() {
  301. console.log("setTime========111")
  302. // this.send(BtCmd.setTime());
  303. }
  304. async setVolume(volume) {
  305. // VolumeUtil.setVolume(volume, { hideVolumeView: true });
  306. const phoneMax = 15; //await VolumeUtil.getMaxVolume();
  307. const result = Math.floor(CmdBase.volumeMax * volume / phoneMax);
  308. console.log(`phoneMax=${phoneMax}, deviceMax=${CmdBase.volumeMax}, setVolume=${volume}, result=${result}`);
  309. this.send(BtCmd.setVolume({
  310. volume: 8
  311. }));
  312. }
  313. async getVolume() {
  314. this.send(BtCmd.queryVolume());
  315. }
  316. stop() {
  317. // EventManager.fire({ event: 'playStatus', playStatus: EnumPlayStatus.stop.index });
  318. }
  319. next() {
  320. // TODO: implement next
  321. }
  322. pause() {
  323. // EventManager.fire({ event: 'playStatus', playStatus: EnumPlayStatus.pause.index });
  324. }
  325. play() {
  326. // TODO: implement play
  327. }
  328. previous() {
  329. // TODO: implement previous
  330. }
  331. startVoiceRecordResponse(supplier) {
  332. console.log(`回调开始录音:${supplier}`);
  333. // switch (supplier) {
  334. // case EnumSupplier.jieLi:
  335. // this.send(BtCmd.jlStartVoiceResponse);
  336. // break;
  337. // case EnumSupplier.lingXin:
  338. // this.send(BtCmd.lxStartVoiceResponse);
  339. // break;
  340. // case EnumSupplier.qiXinWei:
  341. // this.send(BtCmd.b1StartVoiceResponse);
  342. // break;
  343. // }
  344. }
  345. stopVoiceRecordResponse(supplier) {
  346. console.log(`回调结束录音:${supplier}`);
  347. // switch (supplier) {
  348. // case EnumSupplier.jieLi:
  349. // this.send(BtCmd.jlStopVoiceResponse());
  350. // break;
  351. // case EnumSupplier.lingXin:
  352. // this.send(BtCmd.lxStopVoiceResponse());
  353. // break;
  354. // case EnumSupplier.qiXinWei:
  355. // this.send(BtCmd.b1StopVoiceResponse());
  356. // break;
  357. // }
  358. }
  359. async getLowDelayMode() {
  360. this.send(BtCmd.queryLowDelayMode());
  361. }
  362. async setLowDelayMode(open, mode) {
  363. this.send(BtCmd.setLowDelayMode({
  364. open,
  365. mode
  366. }));
  367. }
  368. async setLowPowerMode(isOpen) {
  369. this.send(BtCmd.setLowPowerMode({
  370. isOpen: isOpen ? EnumOpen.open : EnumOpen.close
  371. }));
  372. }
  373. async queryLowPower() {
  374. this.send(BtCmd.queryLowPower());
  375. }
  376. async setCtrlStatus(singleClick, doubleClick, longClick) {
  377. this.send(BtCmd.setCtrlStatus({
  378. singleClick,
  379. doubleClick,
  380. longClick
  381. }));
  382. }
  383. async getEQ() {
  384. this.send(BtCmd.queryEQ());
  385. }
  386. async setEQ(list) {
  387. this.send(BtCmd.setEQ({
  388. list
  389. }));
  390. }
  391. async queryLowKwhWarningTone() {
  392. this.send(BtCmd.queryLowKwhWarningTone());
  393. }
  394. async changeChannelCallBack() {
  395. this.send(Uint8Array.from([0x54, 0x44, 0x44, 0x48, 0x01, 0x0a, 0x29, 0x02, 0x00, 0x01]));
  396. this.send(Uint8Array.from([0x54, 0x44, 0x44, 0x48, 0x01, 0x09, 0x39, 0x01, 0x00]));
  397. }
  398. /* 黑胶音箱的指令 */
  399. // 壁纸指令 1开始, 0结束
  400. static wallPaper(value) {
  401. this.send(BtCmd.wallPaper(value));
  402. }
  403. // 壁纸指令
  404. static wallPaperData(value) {
  405. this.send(BtCmd.wallPaperData(value));
  406. }
  407. // 背景图指令
  408. static backgroudImg(value) {
  409. this.send(BtCmd.backgroudImg(value));
  410. } // 背景图指令
  411. static backgroudImgData(value) {
  412. this.send(BtCmd.backgroudImgData(value));
  413. }
  414. // OTA指令
  415. static OTA(value) {
  416. this.send(BtCmd.OTA(value));
  417. }
  418. static OtaData(value) {
  419. this.send(BtCmd.OtaData(value));
  420. }
  421. }
  422. // 导出 BtHelper 类
  423. // const btHelper = new BtHelper();
  424. module.exports = {
  425. BtHelper
  426. }