123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261 |
- import {handle} from "./mjs_handle";
- import {buf2hex, hex2ab} from "./mjs_buffer";
- class BLE{
- // 白名单设备id列表
- whiteList = [];
- nameList = [];
- useWhiteList = false;
- constructor(whiteList = [], nameList = []){
- // this代表实例对象
- this.isInit= false;
- whiteList = whiteList?whiteList:[];
- nameList = nameList?nameList:[];
- this.whiteList = whiteList;
- this.nameList = nameList;
- this.useWhiteList = whiteList.length > 0 || nameList.length > 0;
- }
-
-
- async initBle(option){
- let [err,ok] = await handle(wx.openBluetoothAdapter(option));
- if(err){
- throw err;
- }
- return 0
- }
- search(onSearchCallback){
- // wx.onBluetoothDeviceFound((res) => {
- // res.devices.forEach((device) => {
- // // 这里可以做一些过滤
- // console.log('Device Found', device)
- // })
- // // 找到要搜索的设备后,及时停止扫描
- // wx.stopBluetoothDevicesDiscovery()
- // })
- console.log("搜索蓝牙中:");
- setTimeout(() => {
- console.log("test");
- }, 2500);
- wx.onBluetoothDeviceFound((res)=> {
- let bleArray = res.devices;
- let advertisData = "",
- deviceId = "";
- let isAdd = false;
- //这里会收到周边搜索到的蓝牙
- console.log("\n\nfind devices ----");
- // console.log(res);
- console.log(res.devices);
- // 对
- for (let index = 0; index < bleArray.length; index++) {
- let ble = bleArray[index];
- isAdd = false;
- deviceId = buf2hex(ble.deviceId);
- // 特征值
- if(ble.advertisData) advertisData = ble.advertisData;
- // 判断是否有白名单
- if (this.useWhiteList ){
- // 特征值检测
- isAdd = !!this.whiteList.find( codeStr => advertisData.startsWith(codeStr));
- // 设备名检测
- isAdd = !!this.nameList.find( codeStr => ble.name.startsWith(codeStr))
- }else{
- // 没有白名单,全部返回
- isAdd = true;
- }
- if(isAdd){
- console.log(`设备名:${ble.name} 设备id:${deviceId} 特征值:${advertisData}`);
- onSearchCallback({
- ...ble,
- hexAdvertisData: advertisData
- });
- }
-
- }
- // 防止检索漏掉设备
- // wx.getBluetoothDevices({complete:(res, err)=> {
- // for (let i = 0; i < res.devices.length; i++) {
- // let ble = res.devices[i];
- // isAdd = false;
- // if(ble.advertisData){
- // advertisData = ble.advertisData;
- // }
- // if(this.useWhiteList){
- // isAdd = !!this.nameList.find(nameStr=>ble.name.startsWith(nameStr));
- // isAdd = !!this.whiteList.find(codeStr=>advertisData.startsWith(codeStr));
- // }else{
- // isAdd = true;
- // }
- // if(isAdd){
- // console.log(`设备名:${ble.name} 设备id:${deviceId} 特征值:${advertisData}`);
- // onSearchCallback({
- // ...ble,
- // hexAdvertisData: advertisData
- // })
- // }
- // }
- // }});
- });
- wx.startBluetoothDevicesDiscovery({
- success(res) {
- console.log("开始搜索蓝牙:", res)
- },
- fail(res) {
- console.log(res)
- }
- })
- }
- onSearch(){
- console.log('on serarch');
- }
- async stopSearch(){
- let [err,res] = await handle(wx.stopBluetoothDevicesDiscovery());
- if(err){
- throw err;
- }
- return res;
- }
- connectDev(deviceId){
- return new Promise((resolve,reject)=>{
- console.log(`连接到:${deviceId}`);
- wx.createBLEConnection({
- deviceId:deviceId,
- success:function(res){
- resolve(res);
- },
- fail:function(err){
- console.error(err);
- reject(err);
- }
- })
- })
- }
- // 获取蓝牙服务
- getBleServices(devId){
- let self = this;
- console.log(`获取蓝牙[ ${devId} ]的服务`);
- return new Promise((resolve,reject)=>{
- wx.getBLEDeviceServices({
- //蓝牙设备ID
- deviceId: devId,
- success: async function (res) {
- let services = res.services;
- console.log(services)
- for (let i = 0; i < services.length; i++) {
- console.log(services[i].uuid);
- let [err,res] = await handle(self.getServerCharacteristics(devId,services[i].uuid));
- if(err){
- console.log(`获取服务特征值失败 服务id:${services[i].uuid}`);
- return reject(err);
- }
- services[i].characteristics = res;
- }
- console.log('--------');
- resolve(services);
- //获取蓝牙设备服务UUID成功
- },
- fail(res) {
- //获取蓝牙设备服务失败
- reject(res);
- }
- })
-
- })
- }
- // 获取蓝牙服务特征值
- getServerCharacteristics(devId,bleServiceUUID){
- let self = this;
- return new Promise((resolve,reject)=>{
- wx.getBLEDeviceCharacteristics({
- //蓝牙设备ID
- deviceId: devId,
- //蓝牙服务ID
- serviceId: bleServiceUUID,
- success: function (res) {
- console.log(res);
- res.characteristics.forEach(async c=>{
- // console.log(c);
- if(c.properties.notify){
- console.log(`监听${bleServiceUUID}的${c.uuid.substr(0,8)}`);
- let [err,res] = await handle(self.listenData(devId,bleServiceUUID,c.uuid));
- if(err){
- console.error(err);
- console.log(`添加监听${bleServiceUUID}的${c.uuid.substr(0,8)}失败`);
- }
- console.log(res);
- }
- })
- resolve(res.characteristics);
- },
- fail(err){
- reject(err);
- }
- });
- });
- }
- // 向指定特征发送数据
- sendData(devId, serviceId,characteristicId, hexStr){
- console.log(`向${devId}的${serviceId}的${characteristicId}发送数据`);
- console.log(hexStr);
- hexStr = hex2ab(hexStr);
- console.log(hexStr);
- return new Promise((resolve,reject)=>{
- wx.writeBLECharacteristicValue({
- //蓝牙设备ID
- deviceId: devId,
- //蓝牙服务ID
- serviceId: serviceId,
- //写特征值ID
- characteristicId: characteristicId,
- //数据ArrayBuffer
- value: hexStr,
- success(res) {
- //发送蓝牙数据成功
- resolve(res);
- },
- fail(res) {
- //发送蓝牙数据失败
- reject(res);
- }
- })
- })
-
- }
- // 监听数据
- listenData(devId,serviceId,uuid){
- return new Promise((resolve,reject)=>{
- wx.notifyBLECharacteristicValueChange({
- state: true,
- //蓝牙设备ID
- deviceId: devId,
- //蓝牙服务ID
- serviceId: serviceId,
- //特征值ID
- characteristicId: uuid,
- success: function (res) {
- //开启通知成功
- wx.onBLECharacteristicValueChange(function (res) {
- //这里坐等数据过来,res.value
- console.log('got data ');
- console.log(res);
- console.log(buf2hex(res.value));
- console.log('got data ');
- })
- resolve(res);
- },
- fail: function (res) {
- //开启通知失败
- reject(res);
- }
- });
- })
- }
- //
- }
- export default BLE;
|