| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387 |
- cc.Class({
- extends: cc.Component,
- properties: {
- Text: {
- default: null,
- type: cc.Node,
- serializable: true,
- }
- },
- start () {
- this.isopen = false;
- this.connected = false;
- this.CurrentDevice=[];
- },
- clear(){
- this.Text.getComponent(cc.Label).string = '';
- },
- startScan: function() {
- var that = this;
- that._discoveryStarted = false;
- if (that.isopen) { //如果已初始化小程序蓝牙模块,则直接执行扫描
- that.getBluetoothAdapterState();
- } else {
- that.openBluetoothAdapter();
- }
- },
- //获取本机蓝牙适配器状态
- getBluetoothAdapterState: function() {
- var that = this;
- wx.getBluetoothAdapterState({
- success: function(res) {
- var isDiscov = res.discovering; //是否正在搜索设备
- var isDvailable = res.available; //蓝牙适配器是否可用
- if (isDvailable) {
- var log = "本机蓝牙适配器状态:可用 \n";
- that.Text.getComponent(cc.Label).string += log;
- if (!isDiscov) {
- that.startBluetoothDevicesDiscovery();
- } else {
- var log = "已在搜索设备 \n";
- that.Text.getComponent(cc.Label).string += log;
- }
- }
- }
- })
- },
- //初始化小程序蓝牙模块
- openBluetoothAdapter: function() {
- var that = this;
- wx.openBluetoothAdapter({
- success: function(res) {
- var log = "打开蓝牙适配器成功!\n";
- that.Text.getComponent(cc.Label).string += log;
- this.isopen = true;
- that.getBluetoothAdapterState();
- },
- fail: function(err) {
- this.isopen = true;
- // app.showModal1("蓝牙开关未开启");
- var log = "蓝牙开关未开启 \n";
- that.Text.getComponent(cc.Label).string += log;
- }
- })
- //监听蓝牙适配器状态变化事件
- wx.onBluetoothAdapterStateChange(function(res) {
- console.log('onBluetoothAdapterStateChange', res)
- that.Text.getComponent(cc.Label).string += 'onBluetoothAdapterStateChange', res;
- var isDvailable = res.available; //蓝牙适配器是否可用
- if (isDvailable) {
- that.getBluetoothAdapterState();
- } else {
- that.stopBluetoothDevicesDiscovery(); //停止搜索
- that.Text.getComponent(cc.Label).string += log;
- // that.setData({
- // devices: []
- // });
- // app.showModal1("蓝牙开关未开启");
- }
- })
- },
- //停止搜寻附近的蓝牙外围设备。若已经找到需要的蓝牙设备并不需要继续搜索时,建议调用该接口停止蓝牙搜索。
- stopBluetoothDevicesDiscovery: function() {
- var that = this;
- var log = "停止搜寻附近的蓝牙外围设备 \n";
- that.Text.getComponent(cc.Label).string += log;
- wx.stopBluetoothDevicesDiscovery()
- },
- //获取本机蓝牙适配器状态
- getBluetoothAdapterState: function() {
- var that = this;
- wx.getBluetoothAdapterState({
- success: function(res) {
- var isDiscov = res.discovering; //是否正在搜索设备
- var isDvailable = res.available; //蓝牙适配器是否可用
- if (isDvailable) {
- var log = "本机蓝牙适配器状态:可用 \n";
- that.Text.getComponent(cc.Label).string +=log;
- console.log(log);
- if (!isDiscov) {
- that.startBluetoothDevicesDiscovery();
- } else {
- var log = "已在搜索设备 \n";
- that.Text.getComponent(cc.Label).string +=log;
- console.log(log);
- }
- }
- }
- })
- },
- //开始扫描附近的蓝牙外围设备。
- //注意,该操作比较耗费系统资源,请在搜索并连接到设备后调用 stop 方法停止搜索。
- startBluetoothDevicesDiscovery: function() {
- var that = this;
- if (that._discoveryStarted) {
- return
- }
- that._discoveryStarted = true;
- // app.showLoading("正在扫描..");
- var log = "正在扫描..\n";
- that.Text.getComponent(cc.Label).string +=log;
- console.log(log);
- setTimeout(function() {
- wx.hideLoading(); //隐藏loading
- }, 3000);
- wx.startBluetoothDevicesDiscovery({
- // services: [],
- // allowDuplicatesKey: true, //是否允许重复上报同一设备, 如果允许重复上报,则onDeviceFound 方法会多次上报同一设备,但是 RSSI(信号) 值会有不同
- success: function(res) {
- var log = "扫描附近的蓝牙外围设备成功,准备监听寻找新设备:" + res + "\n";
- that.Text.getComponent(cc.Label).string +=log;
- console.log(log);
- that.onBluetoothDeviceFound(); //监听寻找到新设备的事件
- }
- });
- },
- //监听寻找到新设备的事件
- onBluetoothDeviceFound: function() {
- var that = this;
- wx.onBluetoothDeviceFound(function(res) {
- res.devices.forEach(function(device) {
- if (!device.name && !device.localName) {
- return
- }
- that.CurrentDevice = device;
- console.log(device.name);
- that.Text.getComponent(cc.Label).string +=device.name;
- // const foundDevices = that.data.devices;
- // const idx = inArray(foundDevices, 'deviceId', device.deviceId);
- // const data = {};
- // if (idx === -1) {
- // data[`devices[${foundDevices.length}]`] = device
- // } else {
- // data[`devices[${idx}]`] = device
- // }
- // that.setData(data)
- })
- })
- },
- //连接低功耗蓝牙设备。
- createBLEConnection: function() {
- var that = this;
- const ds = that.CurrentDevice;
- const devId = ds.deviceId; //设备UUID
- const name = ds.name; //设备名
- // that.stopConnectDevices(); //配对之前先断开已连接设备
- // app.showLoading("正在连接,请稍后");
- var log = "正在连接,请稍后..\n";
- that.Text.getComponent(cc.Label).string +=log;
- // app.showLoading("连接中..");
- wx.createBLEConnection({
- deviceId: devId,
- success: function(res) {
- wx.hideLoading(); //隐藏loading
- var log = "配对成功,获取服务..\n";
- that.Text.getComponent(cc.Label).string +=log;
- that.connected = true;
- // that.setData({
- // textLog: log,
- // connected: true,
- // name,
- // devId,
- // });
- that.getBLEDeviceServices(devId)
- },
- fail: function(err) {
- wx.hideLoading(); //隐藏loading
- var log = "连接失败,错误码:" + err.errCode + "\n";
- that.Text.getComponent(cc.Label).string +=log;
- if (err.errCode === 10012) {
- // app.showModal1("连接超时,请重试!");
- that.Text.getComponent(cc.Label).string +="连接超时,请重试!";
- } else if (err.errCode === 10013) {
- // app.showModal1("连接失败,蓝牙地址无效!");
- that.Text.getComponent(cc.Label).string +="连接失败,蓝牙地址无效!";
- } else {
- // app.showModal1("连接失败,请重试!"); // + err.errCode10003原因多种:蓝牙设备未开启或异常导致无法连接;蓝牙设备被占用或者上次蓝牙连接未断开导致无法连接
- that.Text.getComponent(cc.Label).string +="连接失败,请重试!";
- }
- that.closeBLEConnection()
- },
- });
- that.stopBluetoothDevicesDiscovery(); //停止搜索
- },
- //断开与低功耗蓝牙设备的连接
- closeBLEConnection: function() {
- wx.closeBLEConnection({
- deviceId: this.data.devId
- })
- this.connected=false;
- this.chs=[];
- this.canWrite=false;
- // this.setData({
- // connected: false,
- // chs: [],
- // canWrite: false,
- // })
- },
- //获取蓝牙设备所有 service(服务)
- getBLEDeviceServices: function(devId) {
- var that = this;
- wx.getBLEDeviceServices({
- deviceId: devId,
- success: function(res) {
- for (let i = 0; i < res.services.length; i++) {
- if (res.services[i].isPrimary) { //该服务是否为主服务
- // var s = res.services[i].uuid;
- var log = "该服务是为主服务:" + res.services[i].uuid + "\n";
- // that.setData({
- // textLog: log
- // });
- that.Text.getComponent(cc.Label).string += log;
- that.serviceId = res.services[i].uuid;
- that.getBLEDeviceCharacteristics();
- // wx.navigateTo({
- // url: '/pages/functionPage/functionPage?name=' + encodeURIComponent(that.data.name) + '&deviceId=' + encodeURIComponent(devId) + '&serviceId=' + encodeURIComponent(res.services[i].uuid)
- // });
- return
- }
- }
- }
- })
- },
- //获取蓝牙设备某个服务中的所有 characteristic(特征值)
- getBLEDeviceCharacteristics: function (order){
- var that = this;
- wx.getBLEDeviceCharacteristics({
- deviceId: that.CurrentDevice.deviceId,
- serviceId: that.serviceId,
- success: function (res) {
- for (let i = 0; i < res.characteristics.length; i++) {
- let item = res.characteristics[i]
- if (item.properties.read) {//该特征值是否支持 read 操作
- var log = "该特征值支持 read 操作:" + item.uuid + "\n";
- that.Text.getComponent(cc.Label).string += log;
- that.readCharacteristicId = item.uuid;
- // that.setData({
- // textLog: log,
- // readCharacteristicId: item.uuid
- // });
- }
- if (item.properties.write) {//该特征值是否支持 write 操作
- var log = "该特征值支持 write 操作:" + item.uuid + "\n";
- that.Text.getComponent(cc.Label).string += log;
- that.writeCharacteristicId= item.uuid;
- that.canWrite=true;
- // that.setData({
- // textLog: log,
- // writeCharacteristicId: item.uuid,
- // canWrite:true
- // });
- }
- if (item.properties.notify || item.properties.indicate) {//该特征值是否支持 notify或indicate 操作
- var log = "该特征值支持 notify 操作:" + item.uuid + "\n";
- that.Text.getComponent(cc.Label).string += log;
- that.notifyCharacteristicId = item.uuid;
- // that.setData({
- // textLog: log,
- // notifyCharacteristicId: item.uuid,
- // });
- that.notifyBLECharacteristicValueChange();
- }
- }
- }
- })
- // that.onBLECharacteristicValueChange(); //监听特征值变化
- },
- //启用低功耗蓝牙设备特征值变化时的 notify 功能,订阅特征值。
- //注意:必须设备的特征值支持notify或者indicate才可以成功调用,具体参照 characteristic 的 properties 属性
- notifyBLECharacteristicValueChange: function (){
- var that = this;
- wx.notifyBLECharacteristicValueChange({
- state: true, // 启用 notify 功能
- deviceId: that.CurrentDevice.deviceId,
- serviceId: that.serviceId,
- characteristicId: that.notifyCharacteristicId,
- success: function (res) {
- var log = "notify启动成功" + res.errMsg+"\n";
- that.Text.getComponent(cc.Label).string += log;
- // that.setData({
- // textLog: log,
- // });
- that.onBLECharacteristicValueChange(); //监听特征值变化
- },
- fail: function (res) {
- // wx.showToast({
- // title: 'notify启动失败',
- // mask: true
- // });
- var log = "notify启动失败\n";
- that.Text.getComponent(cc.Label).string += log;
- setTimeout(function () {
- wx.hideToast();
- }, 2000)
- }
- })
- },
- // ArrayBuffer转16进制字符串示例
- ab2hext(buffer) {
- var hexArr = Array.prototype.map.call(
- new Uint8Array(buffer),
- function (bit) {
- return ('00' + bit.toString(16)).slice(-2)
- }
- )
- return hexArr.join('');
- },
- //16进制转字符串
- hexToString(str) {
- var trimedStr = str.trim();
- var rawStr =
- trimedStr.substr(0, 2).toLowerCase() === "0x" ?
- trimedStr.substr(2) :
- trimedStr;
- var len = rawStr.length;
- if (len % 2 !== 0) {
- // alert("Illegal Format ASCII Code!");
- return "";
- }
- var curCharCode;
- var resultStr = [];
- for (var i = 0; i < len; i = i + 2) {
- curCharCode = parseInt(rawStr.substr(i, 2), 16); // ASCII Code Value
- resultStr.push(String.fromCharCode(curCharCode));
- }
- return resultStr.join("");
- },
- //监听低功耗蓝牙设备的特征值变化。必须先启用notify接口才能接收到设备推送的notification。
- onBLECharacteristicValueChange:function(){
- var that = this;
- wx.onBLECharacteristicValueChange(function (res) {
- var resValue = that.ab2hext(res.value); //16进制字符串
- var resValueStr = that.hexToString(resValue);
- var log = "成功获取:" + resValueStr + "\n";
- that.Text.getComponent(cc.Label).string += log;
- });
- },
- //断开与低功耗蓝牙设备的连接
- closeBLEConnection: function () {
- var that = this;
- wx.closeBLEConnection({
- deviceId: that.CurrentDevice.deviceId
- })
- that.connected=false;
- var log = "连接已断开\n";
- that.Text.getComponent(cc.Label).string +=log;
- // wx.showToast({
- // title: '连接已断开',
- // icon: 'success'
- // });
- setTimeout(function () {
- // wx.navigateBack();
- }, 2000)
- },
- });
|