bt_helper.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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 = ["AB01", "FFC1"];
  117. for (let i = 0; i < characteristics.length; i++) {
  118. let charc = characteristics[i];
  119. if (uuids.includes(charc.uuid.toUpperCase())) {
  120. console.log('有特征值:', charc.uuid);
  121. }
  122. if (charc.properties.notify) {
  123. console.log('订阅数据:', charc.uuid);
  124. // 订阅的
  125. this.bleManager.notifyCharacteristicValueChange(charc.uuid, (res) => {
  126. BtParse.parseTLV(res);
  127. })
  128. }
  129. if (charc.properties.write || charc.properties.writeWithoutResponse) {
  130. // 写入的
  131. this.bleManager.setWrite(charc, charc.uuid)
  132. setTimeout(() => {
  133. this._connectSuccess()
  134. }, 100);
  135. if (onChanged) {
  136. onChanged(true)
  137. }
  138. }
  139. // if (charc.properties.read) {
  140. // var chara = await this.bleManager.readCharacteristicValue(charc.uuid,)
  141. // }
  142. }
  143. // this.setData({ characteristics: { ...this.data.characteristics, [service.uuid]: characteristics } });
  144. }
  145. async disconnect(data) {
  146. this.bleManager.disconnect(data.deviceId)
  147. }
  148. async dispose() {
  149. // await this._helper.dispose();
  150. }
  151. async sendNow(cmd) {
  152. if (cmd) {
  153. this.bleManager.sendData(cmd)
  154. }
  155. }
  156. async send(cmd, type) {
  157. if (cmd) {
  158. this.queueManager.addTask(cmd)
  159. }
  160. // QueueManager.instance.addTask({ task: cmd });
  161. }
  162. // onLoad: function () {
  163. // bleManager = new bleManager();
  164. // this.initBluetooth();
  165. // }
  166. async initBluetooth(callback) {
  167. let adpter = await this.bleManager.initBluetoothAdapter((res) => {
  168. if (!res) {
  169. wx.showToast({
  170. title: '请开启蓝牙功能',
  171. icon: 'none'
  172. })
  173. if (callback) {
  174. callback(false, false)
  175. }
  176. return
  177. }
  178. });
  179. // console.log(res)
  180. this.bleManager.checkBluetoothPermission(function (per) {
  181. if (!per) {
  182. wx.showToast({
  183. title: '没有蓝牙权限',
  184. icon: 'none'
  185. })
  186. }
  187. if (callback) {
  188. callback(adpter, per)
  189. }
  190. });
  191. }
  192. closeBle() {
  193. this.bleManager.closeBle()
  194. }
  195. async getConnectedDevices() {
  196. try {
  197. const connectedDevices = await this.bleManager.getConnectedDevices();
  198. console.log("全部设备1:", connectedDevices)
  199. if (connectedDevices.length) {
  200. // todo 已经连接上的设备
  201. }
  202. const allDevices = await this.bleManager.getAllConnectedDevices()
  203. console.log("全部设备2:", allDevices)
  204. let newDevices = connectedDevices.concat(allDevices);
  205. return newDevices
  206. } catch (error) {
  207. console.error(error);
  208. return []
  209. }
  210. }
  211. async checkDevice() {
  212. // console.log("校验设备:", BtCmd); // 输出: EarPhone Info
  213. this.sendNow(BtCmd.checkDevice());
  214. //2.0有发这个,不知道是啥
  215. this.send([0x54, 0x44, 0x44, 0x48, 0x01, 0x09, 0x26, 0x01, 0x01]);
  216. }
  217. async getVersion() {
  218. this.send(BtCmd.queryVersion());
  219. }
  220. _time() {
  221. return 400;
  222. }
  223. getDeviceInfo() {
  224. // if (DeviceManager.instance.isEarphone) {
  225. // this.send(BtCmd.queryKwhEarPhone);
  226. // this.send(BtCmd.queryLowDelayMode);
  227. // this.send(BtCmd.queryEQ);
  228. // this.send(BtCmd.queryLowPower);
  229. // this.send(BtCmd.queryCtrlStatus);
  230. // } else {
  231. // this.send(BtCmd.setDevTime());
  232. this.send(BtCmd.queryKwh());
  233. this.getSleep();
  234. this.getAlert();
  235. this.send(BtCmd.queryRGB());
  236. this.getVolume();
  237. this.setVolume(8)
  238. this.getPauseSleep();
  239. this.send(BtCmd.getClientType());
  240. this.send(BtCmd.getIsConnect());
  241. this.send(BtCmd.getMac());
  242. // }
  243. }
  244. async getAlert() {
  245. this.send(BtCmd.queryAlarm());
  246. }
  247. async getSleep() {
  248. this.send(BtCmd.querySleep());
  249. }
  250. async setAlert(open, weekCycle, hour, minutes, channel = 1) {
  251. this.send(BtCmd.setAlarm({ switchStatus: open, weekCycle, hour, minutes }));
  252. }
  253. async setAutoPlay(open) {
  254. this.send(BtCmd.setAutoPlay({ switchStatus: open }));
  255. }
  256. async getAutoPlay() {
  257. this.send(BtCmd.getAutoPlay);
  258. }
  259. async setLowKwhWarningTone(notify) {
  260. this.send(BtCmd.setLowKwhWarningTone({ notify }));
  261. }
  262. async setPauseSleep(time) {
  263. this.send(BtCmd.setSleepAfterPlayPause({ time }));
  264. }
  265. async getPauseSleep() {
  266. this.send(BtCmd.querySleepAfterPlayPause());
  267. }
  268. async setRGB(r, g, b) {
  269. this.send(BtCmd.setRGB({ r, g, b }));
  270. }
  271. async setSleep(open, hour, minutes) {
  272. this.send(BtCmd.setSleep({ switchStatus: open, hour, minutes }));
  273. }
  274. async setTime() {
  275. console.log("setTime========111")
  276. // this.send(BtCmd.setTime());
  277. }
  278. async setVolume(volume) {
  279. // VolumeUtil.setVolume(volume, { hideVolumeView: true });
  280. const phoneMax = 15;//await VolumeUtil.getMaxVolume();
  281. const result = Math.floor(CmdBase.volumeMax * volume / phoneMax);
  282. console.log(`phoneMax=${phoneMax}, deviceMax=${CmdBase.volumeMax}, setVolume=${volume}, result=${result}`);
  283. this.send(BtCmd.setVolume(8));
  284. }
  285. async getVolume() {
  286. this.send(BtCmd.queryVolume());
  287. }
  288. stop() {
  289. // EventManager.fire({ event: 'playStatus', playStatus: EnumPlayStatus.stop.index });
  290. }
  291. next() {
  292. // TODO: implement next
  293. }
  294. pause() {
  295. // EventManager.fire({ event: 'playStatus', playStatus: EnumPlayStatus.pause.index });
  296. }
  297. play() {
  298. // TODO: implement play
  299. }
  300. previous() {
  301. // TODO: implement previous
  302. }
  303. startVoiceRecordResponse(supplier) {
  304. console.log(`回调开始录音:${supplier}`);
  305. // switch (supplier) {
  306. // case EnumSupplier.jieLi:
  307. // this.send(BtCmd.jlStartVoiceResponse);
  308. // break;
  309. // case EnumSupplier.lingXin:
  310. // this.send(BtCmd.lxStartVoiceResponse);
  311. // break;
  312. // case EnumSupplier.qiXinWei:
  313. // this.send(BtCmd.b1StartVoiceResponse);
  314. // break;
  315. // }
  316. }
  317. stopVoiceRecordResponse(supplier) {
  318. console.log(`回调结束录音:${supplier}`);
  319. // switch (supplier) {
  320. // case EnumSupplier.jieLi:
  321. // this.send(BtCmd.jlStopVoiceResponse());
  322. // break;
  323. // case EnumSupplier.lingXin:
  324. // this.send(BtCmd.lxStopVoiceResponse());
  325. // break;
  326. // case EnumSupplier.qiXinWei:
  327. // this.send(BtCmd.b1StopVoiceResponse());
  328. // break;
  329. // }
  330. }
  331. async getLowDelayMode() {
  332. this.send(BtCmd.queryLowDelayMode());
  333. }
  334. async setLowDelayMode(open, mode) {
  335. this.send(BtCmd.setLowDelayMode({ open, mode }));
  336. }
  337. async setLowPowerMode(isOpen) {
  338. this.send(BtCmd.setLowPowerMode({ isOpen: isOpen ? EnumOpen.open : EnumOpen.close }));
  339. }
  340. async queryLowPower() {
  341. this.send(BtCmd.queryLowPower());
  342. }
  343. async setCtrlStatus(singleClick, doubleClick, longClick) {
  344. this.send(BtCmd.setCtrlStatus({ singleClick, doubleClick, longClick }));
  345. }
  346. async getEQ() {
  347. this.send(BtCmd.queryEQ());
  348. }
  349. async setEQ(list) {
  350. this.send(BtCmd.setEQ({ list }));
  351. }
  352. async queryLowKwhWarningTone() {
  353. this.send(BtCmd.queryLowKwhWarningTone());
  354. }
  355. async changeChannelCallBack() {
  356. this.send(Uint8Array.from([0x54, 0x44, 0x44, 0x48, 0x01, 0x0a, 0x29, 0x02, 0x00, 0x01]));
  357. this.send(Uint8Array.from([0x54, 0x44, 0x44, 0x48, 0x01, 0x09, 0x39, 0x01, 0x00]));
  358. }
  359. /* 黑胶音箱的指令 */
  360. // 壁纸指令 1开始, 0结束
  361. static wallPaper(value) {
  362. this.send(BtCmd.wallPaper(value));
  363. }
  364. // 壁纸指令
  365. static wallPaperData(value) {
  366. this.send(BtCmd.wallPaperData(value));
  367. }
  368. // 背景图指令
  369. static backgroudImg(value) {
  370. this.send(BtCmd.backgroudImg(value));
  371. } // 背景图指令
  372. static backgroudImgData(value) {
  373. this.send(BtCmd.backgroudImgData(value));
  374. }
  375. // OTA指令
  376. static OTA(value) {
  377. this.send(BtCmd.OTA(value));
  378. } static OtaData(value) {
  379. this.send(BtCmd.OtaData(value));
  380. }
  381. }
  382. // 导出 BtHelper 类
  383. // const btHelper = new BtHelper();
  384. module.exports = { BtHelper }