mjs_wxble.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. import {handle} from "./mjs_handle";
  2. import {buf2hex, hex2ab} from "./mjs_buffer";
  3. class BLE{
  4. // 白名单设备id列表
  5. whiteList = [];
  6. nameList = [];
  7. useWhiteList = false;
  8. constructor(whiteList = [], nameList = []){
  9. // this代表实例对象
  10. this.isInit= false;
  11. whiteList = whiteList?whiteList:[];
  12. nameList = nameList?nameList:[];
  13. this.whiteList = whiteList;
  14. this.nameList = nameList;
  15. this.useWhiteList = whiteList.length > 0 || nameList.length > 0;
  16.  }
  17. async initBle(option){
  18. let [err,ok] = await handle(wx.openBluetoothAdapter(option));
  19. if(err){
  20. throw err;
  21. }
  22. return 0
  23. }
  24. search(onSearchCallback){
  25. // wx.onBluetoothDeviceFound((res) => {
  26. // res.devices.forEach((device) => {
  27. // // 这里可以做一些过滤
  28. // console.log('Device Found', device)
  29. // })
  30. // // 找到要搜索的设备后,及时停止扫描
  31. // wx.stopBluetoothDevicesDiscovery()
  32. // })
  33. console.log("搜索蓝牙中:");
  34. setTimeout(() => {
  35. console.log("test");
  36. }, 2500);
  37. wx.onBluetoothDeviceFound((res)=> {
  38. let bleArray = res.devices;
  39. let advertisData = "",
  40. deviceId = "";
  41. let isAdd = false;
  42. //这里会收到周边搜索到的蓝牙
  43. console.log("\n\nfind devices ----");
  44. // console.log(res);
  45. console.log(res.devices);
  46. // 对
  47. for (let index = 0; index < bleArray.length; index++) {
  48. let ble = bleArray[index];
  49. isAdd = false;
  50. deviceId = buf2hex(ble.deviceId);
  51. // 特征值
  52. if(ble.advertisData) advertisData = ble.advertisData;
  53. // 判断是否有白名单
  54. if (this.useWhiteList ){
  55. // 特征值检测
  56. isAdd = !!this.whiteList.find( codeStr => advertisData.startsWith(codeStr));
  57. // 设备名检测
  58. isAdd = !!this.nameList.find( codeStr => ble.name.startsWith(codeStr))
  59. }else{
  60. // 没有白名单,全部返回
  61. isAdd = true;
  62. }
  63. if(isAdd){
  64. console.log(`设备名:${ble.name} 设备id:${deviceId} 特征值:${advertisData}`);
  65. onSearchCallback({
  66. ...ble,
  67. hexAdvertisData: advertisData
  68. });
  69. }
  70. }
  71. // 防止检索漏掉设备
  72. // wx.getBluetoothDevices({complete:(res, err)=> {
  73. // for (let i = 0; i < res.devices.length; i++) {
  74. // let ble = res.devices[i];
  75. // isAdd = false;
  76. // if(ble.advertisData){
  77. // advertisData = ble.advertisData;
  78. // }
  79. // if(this.useWhiteList){
  80. // isAdd = !!this.nameList.find(nameStr=>ble.name.startsWith(nameStr));
  81. // isAdd = !!this.whiteList.find(codeStr=>advertisData.startsWith(codeStr));
  82. // }else{
  83. // isAdd = true;
  84. // }
  85. // if(isAdd){
  86. // console.log(`设备名:${ble.name} 设备id:${deviceId} 特征值:${advertisData}`);
  87. // onSearchCallback({
  88. // ...ble,
  89. // hexAdvertisData: advertisData
  90. // })
  91. // }
  92. // }
  93. // }});
  94. });
  95. wx.startBluetoothDevicesDiscovery({
  96. success(res) {
  97. console.log("开始搜索蓝牙:", res)
  98. },
  99. fail(res) {
  100. console.log(res)
  101. }
  102. })
  103. }
  104. onSearch(){
  105. console.log('on serarch');
  106. }
  107. async stopSearch(){
  108. let [err,res] = await handle(wx.stopBluetoothDevicesDiscovery());
  109. if(err){
  110. throw err;
  111. }
  112. return res;
  113. }
  114. connectDev(deviceId){
  115. return new Promise((resolve,reject)=>{
  116. console.log(`连接到:${deviceId}`);
  117. wx.createBLEConnection({
  118. deviceId:deviceId,
  119. success:function(res){
  120. resolve(res);
  121. },
  122. fail:function(err){
  123. console.error(err);
  124. reject(err);
  125. }
  126. })
  127. })
  128. }
  129. // 获取蓝牙服务
  130. getBleServices(devId){
  131. let self = this;
  132. console.log(`获取蓝牙[ ${devId} ]的服务`);
  133. return new Promise((resolve,reject)=>{
  134. wx.getBLEDeviceServices({
  135. //蓝牙设备ID
  136. deviceId: devId,
  137. success: async function (res) {
  138. let services = res.services;
  139. console.log(services)
  140. for (let i = 0; i < services.length; i++) {
  141. console.log(services[i].uuid);
  142. let [err,res] = await handle(self.getServerCharacteristics(devId,services[i].uuid));
  143. if(err){
  144. console.log(`获取服务特征值失败 服务id:${services[i].uuid}`);
  145. return reject(err);
  146. }
  147. services[i].characteristics = res;
  148. }
  149. console.log('--------');
  150. resolve(services);
  151. //获取蓝牙设备服务UUID成功
  152. },
  153. fail(res) {
  154. //获取蓝牙设备服务失败
  155. reject(res);
  156. }
  157. })
  158. })
  159. }
  160. // 获取蓝牙服务特征值
  161. getServerCharacteristics(devId,bleServiceUUID){
  162. let self = this;
  163. return new Promise((resolve,reject)=>{
  164. wx.getBLEDeviceCharacteristics({
  165. //蓝牙设备ID
  166. deviceId: devId,
  167. //蓝牙服务ID
  168. serviceId: bleServiceUUID,
  169. success: function (res) {
  170. console.log(res);
  171. res.characteristics.forEach(async c=>{
  172. // console.log(c);
  173. if(c.properties.notify){
  174. console.log(`监听${bleServiceUUID}的${c.uuid.substr(0,8)}`);
  175. let [err,res] = await handle(self.listenData(devId,bleServiceUUID,c.uuid));
  176. if(err){
  177. console.error(err);
  178. console.log(`添加监听${bleServiceUUID}的${c.uuid.substr(0,8)}失败`);
  179. }
  180. console.log(res);
  181. }
  182. })
  183. resolve(res.characteristics);
  184. },
  185. fail(err){
  186. reject(err);
  187. }
  188. });
  189. });
  190. }
  191. // 向指定特征发送数据
  192. sendData(devId, serviceId,characteristicId, hexStr){
  193. console.log(`向${devId}的${serviceId}的${characteristicId}发送数据`);
  194. console.log(hexStr);
  195. hexStr = hex2ab(hexStr);
  196. console.log(hexStr);
  197. return new Promise((resolve,reject)=>{
  198. wx.writeBLECharacteristicValue({
  199. //蓝牙设备ID
  200. deviceId: devId,
  201. //蓝牙服务ID
  202. serviceId: serviceId,
  203. //写特征值ID
  204. characteristicId: characteristicId,
  205. //数据ArrayBuffer
  206. value: hexStr,
  207. success(res) {
  208. //发送蓝牙数据成功
  209. resolve(res);
  210. },
  211. fail(res) {
  212. //发送蓝牙数据失败
  213. reject(res);
  214. }
  215. })
  216. })
  217. }
  218. // 监听数据
  219. listenData(devId,serviceId,uuid){
  220. return new Promise((resolve,reject)=>{
  221. wx.notifyBLECharacteristicValueChange({
  222. state: true,
  223. //蓝牙设备ID
  224. deviceId: devId,
  225. //蓝牙服务ID
  226. serviceId: serviceId,
  227. //特征值ID
  228. characteristicId: uuid,
  229. success: function (res) {
  230. //开启通知成功
  231. wx.onBLECharacteristicValueChange(function (res) {
  232. //这里坐等数据过来,res.value
  233. console.log('got data ');
  234. console.log(res);
  235. console.log(buf2hex(res.value));
  236. console.log('got data ');
  237. })
  238. resolve(res);
  239. },
  240. fail: function (res) {
  241. //开启通知失败
  242. reject(res);
  243. }
  244. });
  245. })
  246. }
  247. //
  248. }
  249. export default BLE;