bt_helper.js 12 KB

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