bt_helper.js 11 KB

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