bt_helper.js 12 KB

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