123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660 |
- class Manager {
- constructor() {
- var that = this;
- ///正在连接中的设备
- that.connectWillDevice = null;
- ///正在连接的设备,成功后返回的数据
- that.callBackConnect = null;
- ///搜索过快会失败,给的一定的缓冲时间
- that.requestBlueTime = 0;
- ///蓝牙是否已打开,是否可用
- that.isAvailable = false;
- ///蓝牙正在搜索中,则不允许继续搜索
- that.doStartScaning = false;
- ///蓝牙设备搜索的所有在线设备,用来和现有设备比较
- that.compareList = [];
- ///离线的所有设备,也可以用来比较
- that.dissmissDevice = [];
- ///当前蓝牙ble连接设备的相关属性
- that.writeCharaterId = "";
- that.writeServiceId = "";
- that.readCharaterId = "";
- that.readServiceId = "";
- }
- ///获取比较的数据
- getCompareList() {
- var that = this;
- return that.compareList;
- }
- setCompareList(compareList) {
- var that = this;
- that.compareList = compareList;
- }
- getDissmissDevice() {
- var that = this;
- return that.dissmissDevice;
- }
- setConnectWillDevice(connectWillDevice) {
- var that = this;
- that.connectWillDevice = connectWillDevice;
- }
- getCallBackConnect() {
- var that = this;
- return that.callBackConnect;
- }
- setCallBackConnect(callBackConnect) {
- this.callBackConnect = callBackConnect;
- }
- /// 监控蓝牙打开状态
- initBlueAdapter() {
- var that = this;
- wx.onBluetoothAdapterStateChange(function (res) {
- that.isAvailable = res.available;
- if (!that.isAvailable) {
- that.compareList = [];
- that.dissmissDevice = [];
- getCurrentPages()[0].closeBlueResetOffline(false, true);
- }
- })
- }
- ///监听搜索设备列表
- listenBlueDevices() {
- var that = this;
- const hexUtil = require('../hexUtil');
- wx.onBluetoothDeviceFound(function (res) {
- ///第一种情况
- if (res.deviceId) {
- if (that.callBackConnect != null) {
- if (that.connectWillDevice != null && res.name == that.connectWillDevice.clientType) {
- res.mac = res.advertisData ? hexUtil.buf2hex(res.advertisData) : '';
- if (that.callBackConnect != null) {
- that.callBackConnect(res);
- }
- }
- } else {
- if (res.name != "") {
- if (that.compareList.length > 0) {
- var has = false;
- for (var i = 0; i < that.compareList.length; i++) {
- if (res.deviceId == that.compareList[i].deviceId) {
- has = true;
- break;
- }
- }
- if (!has) {
- that.compareList.push(res);
- }
- } else {
- that.compareList.push(res);
- }
- }
- }
- }
- ///第二种情况
- else if (res.devices) {
- if (that.callBackConnect != null) {
- for (var i = 0; i < res.devices.length; i++) {
- var temp = res.devices[i];
- if (that.connectWillDevice != null && temp.name == that.connectWillDevice.clientType) {
- temp.mac = temp.advertisData ? hexUtil.buf2hex(temp.advertisData) : '';
- temp.mac2 = that.ab2hex(temp.advertisData ?? "")
- if (that.callBackConnect != null) {
- that.callBackConnect(temp);
- }
- break;
- }
- }
- } else {
- for (var i = 0; i < res.devices.length; i++) {
- if (that.compareList.length > 0) {
- var has = false;
- for (var j = 0; j < that.compareList.length; j++) {
- if (res.devices[i].name != "") {
- if (res.devices[i].deviceId == that.compareList[j].deviceId) {
- has = true;
- break;
- }
- }
- }
- if (!has) {
- that.compareList.push(res.devices[i]);
- }
- } else {
- that.compareList.push(res.devices[i]);
- }
- }
- }
- }
- ///第三种情况
- else if (res[0]) {
- if (that.callBackConnect != null) {
- if (that.connectWillDevice != null && res[0].name == that.connectWillDevice.clientType) {
- res[0].mac = res[0].advertisData ? hexUtil.buf2hex(res[0].advertisData) : '';
- if (that.callBackConnect != null) {
- that.callBackConnect(res[0]);
- }
- }
- } else {
- if (res[0].name != "") {
- if (that.compareList.length > 0) {
- var has = false;
- for (var i = 0; i < that.compareList.length; i++) {
- if (res[0].deviceId == that.compareList[i].deviceId) {
- has = true;
- break;
- }
- }
- if (!has) {
- that.compareList.push(res[0]);
- }
- } else {
- that.compareList.push(res[0]);
- }
- }
- }
- }
- });
- ///监听 离线和连接成功设备导入
- // {"deviceId":"E4:9F:80:09:40:EC","connected":false}
- wx.onBLEConnectionStateChange((result) => {
- if (result.connected) {
- for (var i = 0; i < that.dissmissDevice.length; i++) {
- if (result.deviceId == that.dissmissDevice[i].deviceId) {
- that.dissmissDevice.splice(i, 1);
- break;
- }
- }
- } else {
- var has = false;
- for (var i = 0; i < that.dissmissDevice.length; i++) {
- if (result.deviceId == that.dissmissDevice[i].deviceId) {
- has = true;
- break;
- }
- }
- if (!has) {
- that.dissmissDevice.push(result);
- }
- }
- });
- }
- // 开始搜索蓝牙设备
- async startScan(connectWillDevice, boolean, callBackConnect) {
- var that = this;
- ///限制搜索没有打开蓝牙一直询问打开蓝牙
- if (!that.isAvailable) {
- if (callBackConnect == null) {
- return;
- }
- ///做搜索蓝牙适配器权限
- const permissionUtil = require('../../utils/permissionUtil');
- var available = await permissionUtil.openBluetoothAdapter();
- that.isAvailable = available;
- if (!available) {
- that.doStartScaning = false;
- that.requestBlueTime = that.getCurrentMills();
- if (boolean != null) {
- boolean(false);
- }
- return;
- }
- }
- const routeUtil = require('../../utils/routeUtil');
- const routeRoot = require('../../utils/routeRoot');
- const index = routeRoot.index;
- const connectBleRoot = routeRoot.connectBleRoot;
- var lastPageRoute = routeUtil.getLastPageRoute();
- if (lastPageRoute != index && lastPageRoute != connectBleRoot) {
- return;
- }
- ///蓝牙连接 做限制
- if (lastPageRoute == index) {
- if (that.doStartScaning == true) {
- return;
- }
- }
- const timeUtil = require('../../utils/timeUtil');
- that.doStartScaning = true;
- var currentMill = timeUtil.getCurrentMills();
- var waitMills = 0;
- var reduce = currentMill - that.requestBlueTime;
- const dMills = 6 * 1000;
- if (reduce > 0 && reduce < dMills) {
- waitMills = dMills - reduce;
- }
- if (waitMills > 0) {
- await timeUtil.delayMills(waitMills);
- }
- if (callBackConnect == null && lastPageRoute == connectBleRoot) {
- that.doStartScaning = false;
- return;
- }
- wx.stopBluetoothDevicesDiscovery({
- success: (res) => {
- that.search(connectWillDevice, boolean, callBackConnect);
- },
- fail: (err) => {
- that.doStartScaning = false;
- that.requestBlueTime = timeUtil.getCurrentMills();
- if (boolean != null) {
- boolean(false);
- }
- }
- });
- }
- ///搜索设备
- search(connectWillDevice, boolean, callBackConnect) {
- var that = this;
- const timeUtil = require('../../utils/timeUtil');
- wx.startBluetoothDevicesDiscovery({
- allowDuplicatesKey: true,
- success: function (res) {
- // that.getConnectedDevices();
- that.doStartScaning = false;
- that.requestBlueTime = timeUtil.getCurrentMills();
- if (boolean != null) {
- boolean(true);
- }
- that.setConnectWillDevice(connectWillDevice);
- that.setCallBackConnect(callBackConnect);
- that.compareList = [];
- },
- fail(err) {
- that.doStartScaning = false;
- that.requestBlueTime = timeUtil.getCurrentMills();
- if (boolean != null) {
- boolean(false);
- }
- },
- });
- }
- // 停止搜索
- stopScan() {
- var that = this;
- that.setCallBackConnect(null);
- that.setConnectWillDevice(null);
- return new Promise((resolve, reject) => {
- wx.stopBluetoothDevicesDiscovery({
- success: (res) => {
- resolve(res);
- },
- fail: (err) => {
- reject('停止搜索失败');
- }
- });
- });
- }
- ///开始连接设备
- startConnect(device) {
- var deviceId = device.deviceId;
- return new Promise((resolve, reject) => {
- wx.createBLEConnection({
- deviceId: deviceId,
- success: function (res) {
- resolve(true);
- },
- fail: function (res) {
- var errCode = res.errCode;
- var errMsg = res.errMsg;
- if (errCode == -1 && errMsg == "createBLEConnection:fail:already connect") {
- resolve(true);
- } else {
- resolve(false);
- }
- }
- });
- });
- }
- // 发现服务
- discoverServices(device) {
- var deviceId = device.deviceId;
- return new Promise((resolve, reject) => {
- wx.getBLEDeviceServices({
- deviceId: deviceId,
- success: (res) => {
- let service_id = "";
- for (let i = 0; i < res.services.length; i++) {
- if (res.services[i].uuid.toUpperCase().indexOf("AB00") != -1 ||
- res.services[i].uuid.toUpperCase().indexOf("FFC0") != -1
- ) {
- service_id = res.services[i].uuid;
- break;
- }
- service_id = res.services[i].uuid;
- }
- // if (that.publicDevice) {
- // that.publicDevice.serviceId = service_id;
- // }
- resolve(service_id);
- },
- fail: (err) => {
- reject("");
- }
- });
- });
- }
- ///初始化 接收数据 获取特征值
- getNotifyServices(device) {
- var deviceId = device.deviceId;
- return new Promise((resolve, reject) => {
- wx.getBLEDeviceServices({
- deviceId: deviceId,
- success: function (res) {
- resolve(res.services);
- },
- fail: function (res) {
- resolve("");
- }
- });
- });
- }
- // 发现服务
- discoverServices(device) {
- var deviceId = device.deviceId;
- return new Promise((resolve, reject) => {
- wx.getBLEDeviceServices({
- deviceId: deviceId,
- success: (res) => {
- let service_id = "";
- for (let i = 0; i < res.services.length; i++) {
- if (res.services[i].uuid.toUpperCase().indexOf("AB00") != -1 ||
- res.services[i].uuid.toUpperCase().indexOf("FFC0") != -1
- ) {
- service_id = res.services[i].uuid;
- break;
- }
- service_id = res.services[i].uuid;
- }
- resolve(service_id);
- },
- fail: (err) => {
- console.error('发现服务失败:', err);
- reject("");
- }
- });
- });
- }
- setWriteServiceId(serviceId) {
- var that = this;
- that.writeServiceId = serviceId;
- }
- ///获取设备真正的属性特征值
- getCharacteristics(device, failed, readSucceed) {
- var that = this;
- var deviceId = device.deviceId;
- wx.getBLEDeviceCharacteristics({
- deviceId: deviceId,
- serviceId: that.writeServiceId,
- success: function (res) {
- that._forProcessDeal(res, failed, readSucceed);
- },
- fail: (err) => {
- failed();
- }
- });
- }
- async _forProcessDeal(res, failed, readSucceed) {
- var that = this;
- const timeUtil = require('../../utils/timeUtil');
- var characteristics = res.characteristics;
- if (characteristics.length <= 0) {
- failed();
- return;
- }
- var isWrited = false;
- for (let i = 0; i < characteristics.length; i++) {
- var charc = characteristics[i];
- ///可以开始写入数据
- if (charc.properties.write || charc.properties.writeWithoutResponse) {
- isWrited = true;
- that.writeCharaterId = charc.uuid;
- break;
- }
- }
- if (!isWrited) {
- failed();
- return;
- }
- var isReaded = false;
- for (let i = 0; i < characteristics.length; i++) {
- var charc = characteristics[i];
- ///可以开始读取数据
- if (charc.properties.notify) {
- isReaded = true;
- readSucceed(charc.uuid);
- break;
- }
- }
- if (!isReaded) {
- failed();
- return;
- }
- // for (let i = 0; i < characteristics.length; i++) {
- // var charc = characteristics[i];
- // ///可以开始读取数据
- // if (charc.properties.notify) {
- // writeSucceed(charc.uuid);
- // }
- // ///可以开始写入数据
- // if (charc.properties.write || charc.properties.writeWithoutResponse) {
- // that.writeCharaterId = charc.uuid;
- // readSucceed();
- // }
- // }
- }
- // 监听特征值变化
- monitorCharacteristicValueChange(device, serviceId, notifyCharaterId) {
- return new Promise((resolve, reject) => {
- var deviceId = device.deviceId;
- wx.notifyBLECharacteristicValueChange({
- state: true,
- deviceId: deviceId,
- serviceId: serviceId,
- characteristicId: notifyCharaterId,
- success: function (res) {
- resolve(true);
- },
- ///{"errno":1500104,"errMsg":"notifyBLECharacteristicValueChange:fail:no descriptor"}
- fail: function (res) {
- resolve(false);
- }
- });
- });
- }
- ///收取到的数据转换为文字
- onBLECharacteristicValueChange(device, callback) {
- wx.onBLECharacteristicValueChange(function (characteristic) {
- //characteristic: {"value":{},"deviceId":"22:10:14:95:F0:1E","serviceId":"0000FFE5-0000-1000-8000-00805F9B34FB","characteristicId":"0000FFE5-0001-1000-8000-00805F9B34FB"}
- const hexUtil = require('../hexUtil');
- var buffer = characteristic.value
- var dataView = new DataView(buffer)
- var dataResult = []
- for (let i = 0; i < dataView.byteLength; i++) {
- dataResult.push(dataView.getUint8(i))
- }
- var value = hexUtil.buf2string(dataResult);
- ///109,113,116,116
- ///114,101,99,118,95,102,105,110,105,115,104
- callback(value);
- });
- }
- // 断开设备的连接
- disconnect(device) {
- return new Promise((resolve, reject) => {
- var deviceId = device.deviceId;
- wx.closeBLEConnection({
- deviceId: deviceId,
- success: (res) => {
- resolve(true);
- },
- fail: (err) => {
- resolve(false);
- }
- });
- });
- }
- ///发送数据
- sendData(device, data) {
- var that = this;
- return new Promise((resolve, reject) => {
- var buffer = new ArrayBuffer(data.length);
- // 下面是赋值,不能删
- const dataView = new DataView(buffer);
- // 将每个16进制数值写入到 buffer 中
- data.forEach((value, index) => {
- dataView.setUint8(index, value);
- });
- var deviceId = device.deviceId;
- wx.writeBLECharacteristicValue({
- deviceId: deviceId,
- serviceId: that.writeServiceId,
- characteristicId: that.writeCharaterId,
- value: buffer,
- success: function (res) {
- resolve(true);
- },
- fail(err) {
- resolve(false);
- }
- });
- });
- }
- }
- module.exports = Manager;
- ///获取设备真正的属性特征值
- // getCharacteristics(device, services, index, notify, write, read, succeed, fail) {
- // var that = this;
- // var deviceId = device.deviceId;
- // var serviceId = services[index].uuid;
- // wx.getBLEDeviceCharacteristics({
- // deviceId: deviceId,
- // serviceId: serviceId,
- // success: function (res) {
- // var notifyCharaterId = "";
- // var notifyServiceId = "";
- // for (var i = 0; i < res.characteristics.length; i++) {
- // var properties = res.characteristics[i].properties;
- // var charaterId = res.characteristics[i].uuid;
- // if (!notify) {
- // if (properties.notify) {
- // notifyCharaterId = charaterId;
- // notifyServiceId = services[index].uuid;
- // notify = true;
- // }
- // }
- // if (!write) {
- // if (properties.write) {
- // that.writeCharaterId = charaterId;
- // that.writeServiceId = services[index].uuid;
- // write = true;
- // }
- // }
- // if (!read) {
- // if (properties.read) {
- // that.readCharaterId = charaterId;
- // that.readServiceId = services[index].uuid;
- // read = true;
- // }
- // }
- // }
- // if (!notify) {
- // index++
- // if (index == services.length) {
- // fail();
- // } else {
- // that.getCharacteristics(device, services, index, notify, write, read, succeed, fail);
- // }
- // } else {
- // succeed(notifyServiceId, notifyCharaterId);
- // }
- // }
- // })
- // }
- ///获取 所有搜索过的蓝牙设备
- // getConnectedDevices() {
- // var that = this;
- // const hexUtil = require('../hexUtil');
- // wx.getBluetoothDevices({
- // success: (res) => {
- // if (that.callBackConnect != null) {
- // for (var i = 0; i < res.devices.length; i++) {
- // var temp = res.devices[i];
- // if (that.connectWillDevice != null && temp.name == that.connectWillDevice.clientType) {
- // temp.mac = temp.advertisData ? hexUtil.buf2hex(temp.advertisData) : '';
- // if (that.callBackConnect != null) {
- // that.callBackConnect(temp);
- // }
- // break;
- // }
- // }
- // } else {
- // for (var i = 0; i < res.devices.length; i++) {
- // if (that.compareList.length > 0) {
- // var has = false;
- // for (var j = 0; j < that.compareList.length; j++) {
- // if (res.devices[i].name != "") {
- // if (res.devices[i].deviceId == that.compareList[j].deviceId) {
- // has = true;
- // break;
- // }
- // }
- // }
- // if (!has) {
- // that.compareList.push(res.devices[i]);
- // }
- // } else {
- // that.compareList.push(res.devices[i]);
- // }
- // }
- // }
- // },
- // fail: (err) => {
- // console.error('获取蓝牙设备列表失败', err);
- // }
- // });
- // }
|