bt_helper.js 12 KB

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