mjs_wxble.js 7.9 KB

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