bt_helper.js 12 KB

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