uniapp 通过蓝牙连接设备并发送命令

初始化蓝牙模块

openBluetoothAdapter() {

uni.openBluetoothAdapter({

success: e => {

// console.log('初始化蓝牙成功:' + e.errMsg);

this.onBluetoothDeviceFound()

//获取本机蓝牙适配器状态。

uni.getBluetoothAdapterState({

success: function(res) {

// 初始化完毕开始搜索

if (res.available) {

if (res.discovering) {

// console.log('停止连接');

this.closeBluetooth()

}

uni.startBluetoothDevicesDiscovery({

success: res => {

},

fail: res => {

onsole.log("查找设备失败!");

uni.showToast({

icon: "none",

title: "查找设备失败!",

duration: 3000,

})

}

})

} else {

console.log('本机蓝牙不可用')

}

}

})

},

fail: e => {

if (e.errCode == 10001) {

uni.showModal({

title: "提示",

content: "您的蓝牙没有打开,请打开蓝牙",

success: function(res) {

if (res.confirm == true) {

if (uni.getSystemInfoSync().platform == 'ios') {

} else if (uni.getSystemInfoSync().platform === 'android') {

}

} else {

uni.navigateBack({

url: '../../detail3/detail3'

})

}

},

});

}

console.log('初始化蓝牙失败,错误码:' + (e.errCode || e.errMsg));

}

});

},

//发现外围设备

onBluetoothDeviceFound() {

// console.log("监听寻找新设备");

uni.onBluetoothDeviceFound(devices => {

// console.log('开始监听寻找到新设备的事件');

// console.log(devices.length);

this.getBluetoothDevices();

});

},

//获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。

getBluetoothDevices() {

// console.log("获取蓝牙设备");

uni.getBluetoothDevices({

success: res => {

// console.log('获取蓝牙设备');

this.resdic = res

// console.log(res)

// console.log('devices.length===='+this.resdic.devices.length);

for (let i = 0; i < this.resdic.devices.length; i++) {

let devicesDic = this.resdic.devices[i];

if (devicesDic.name && devicesDic.name == '<Dobiy>' && devicesDic.advertisServiceUUIDs) {

this.deviceIdStr = devicesDic.deviceId

this.stopBluetooth()

this.createBLEConnection(devicesDic.deviceId)

}

}

}

});

},

//连接低功耗蓝牙设备。

createBLEConnection(deviceIds) {

console.log("连接蓝牙---------------" + deviceIds)

// setTimeout(function(){

//    that.closeBLEConnection();

//    that.createBLEConnection(deviceIds)

// },5000)

uni.createBLEConnection({

deviceId: deviceIds.toString(),

success: (res) => {

console.log('蓝牙连接成功');

// this.getBLEDeviceServices(deviceIds)

this.stopBluetooth()

var that = this

uni.getSystemInfo({

success(res) {

if (res.platform == 'ios') {

setTimeout(() => {

that.getBLEDeviceServices(deviceIds)

}, 2000)

} else {

setTimeout(() => {

that.nogetBLEDeviceServices(deviceIds)

}, 3000)

}

},

fail(res) {

console.log(777777777777777)

}

})

},

fail: (res) => {

console.log('蓝牙连接失败:' + res.errCode)

that.closeBLEConnection();

that.createBLEConnection(deviceIds)

},

});

},

//iOS端获取ServicesID

async getBLEDeviceServices(deviceIds) {

var that = this

let deviceServices = await uni.getBLEDeviceServices({

deviceId: deviceIds

})

if (deviceServices[0] == null) {

let services = deviceServices[1].services

if (services.length == 0) {

setTimeout(() => {

that.getBLEDeviceServices(deviceIds)

}, 1500)

} else {

console.log(services, 88888888888)

for (let i = 0; i < services.length; i++) {

let serviceId = services[i].uuid

// console.log('serviceId====' + serviceId);

let characteristicsDic = await uni.getBLEDeviceCharacteristics({

deviceId: deviceIds,

serviceId: serviceId,

})

.then(data => {

// console.log(JSON.stringify(data))

if (data[0] == null) {

let characteristicsArr = data[1].characteristics

let properties = characteristicsArr[0].properties

console.log(properties)

if (properties.write == true) {

that.serviceIdStr = serviceId;

that.characteristicsIdStr = data[1].characteristics[0].uuid;

that.notifyBLECharacteristicValueChange(that.characteristicsIdStr)

// console.log(deviceIds)

// console.log(that.serviceIdStr)

// console.log(that.characteristicsIdStr)

that.writeBLECharacteristic(deviceIds, serviceId, that.characteristicsIdStr)

} else {

console.log('不可编辑', data[1].characteristics[0].uuid)

}

}

})

}

}

} else {

uni.showModal({

title: "提示",

content: "获取设备服务信息失败,请重新获取",

showCancel: false,

success(res) {

uni.navigateBack({

url: '../uploadImg/uploadImg'

})

}

})

}

},

//安卓获取Servicesid

nogetBLEDeviceServices(deviceIds) {

var that = this

console.log(777777)

uni.getBLEDeviceServices({

deviceId: deviceIds,

success(res) {

let services = res.services

console.log(services, 55555)

if (services.length == 0) {

setTimeout(() => {

that.nogetBLEDeviceServices(deviceIds)

}, 3000)

} else {

for (let i = 0; i < services.length; i++) {

let serviceId = services[i].uuid

//这个比对serviceId,设备厂家会告诉,因为安卓获取特征值都是不可写入的,iOS 的可以写入的,所以安卓直接判断serviceId是不是厂家发的serviceId

if (serviceId == '') {

uni.getBLEDeviceCharacteristics({

deviceId: deviceIds,

serviceId: serviceId,

success(result) {

let propertiesDic = result.characteristics[0]

console.log(propertiesDic, 55555)

// if (propertiesDic.properties.write == true) {

that.serviceIdStr = serviceId;

that.characteristicsIdStr = propertiesDic.uuid;

that.notifyBLECharacteristicValueChange(that.characteristicsIdStr)

setTimeout(() =>{

that.writeBLECharacteristic(deviceIds, serviceId, that.characteristicsIdStr)

}, 2000)

// } else {

// console.log('不可编辑', propertiesDic.uuid)

// }

},

fail(result) {

console.log(result, 2222222)

}

})

}

}

}

},

fail(res) {

console.log(res, 8888888)

}

})

},

// 启用 notify 功能

一定要调用这个方法,否则无法监听设备返回的数据,之前一直以为在uni.writeBLECharacteristicValue的回调里能得到返回的值,这个方法没有用,结果试了几天都不行,

notifyBLECharacteristicValueChange(characteristicId) {

console.log(characteristicId, 'characteristicId')

uni.notifyBLECharacteristicValueChange({

state: true, // 启用 notify 功能

deviceId: this.deviceIdStr,

serviceId: this.serviceIdStr,

characteristicId: this.characteristicsIdStr,

success: (res) => {

// console.log(res)

// console.log(this.characteristicId)

console.log('notifyBLECharacteristicValueChange success', res)

// that.writeBLECharacteristic(deviceIds, serviceId, that.characteristicsIdStr)             

this.onBLECharacteristicValue()

},

fail: (res) => {

console.log('notifyBLECharacteristicValueChange success2', res.errMsg)

}

})

},

onBLECharacteristicValue() {

var that = this

uni.onBLECharacteristicValueChange(function(res) {

// console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`)

let resultStr = that.bufferString(res.value)

// console.log(resultStr,111)

if (resultStr && resultStr != '') {

//resultStr就是设备上返回的数据,根据设备不同,获取的设备格式也就不同,自己筛选吧

}

})

},

writeBLECharacteristic(deviceId, serviceId, characteristicId) {

var that = this

console.log(1111111111)

let sgInt = that.string2buffer('<sAg>')

// console.log(sgInt.byteLength)

uni.writeBLECharacteristicValue({

deviceId: that.deviceIdStr,

serviceId: that.serviceIdStr,

characteristicId: that.characteristicsIdStr,

value: sgInt,

success: function(res) {

console.log(typeof(res))

console.log('writeBLECharacteristicValue success', res.errMsg)

// that.closeBluetooth()

},

fail: function(res) {

console.log(typeof(res))

console.log('writeBLECharacteristicValue fail==', res.errCode, res.errMsg)

}

})

},

//字符串转arraybuffer

string2buffer: function(str) {

// 首先将字符串转为16进制

let val = ""

for (let i = 0; i < str.length; i++) {

if (val === '') {

val = str.charCodeAt(i).toString(16)

} else {

val += ',' + str.charCodeAt(i).toString(16)

}

}

// console.log(val)

// 将16进制转化为ArrayBuffer

return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function(h) {

return parseInt(h, 16)

})).buffer

},

//arraybuffer 转字符串

bufferString: function(str) {

// ArrayBuffer转16进度字符串示例

function ab2hex(buffer) {

const hexArr = Array.prototype.map.call(

new Uint8Array(buffer),

function(bit) {

return ('00' + bit.toString(16)).slice(-2)

}

)

return hexArr.join('')

}

//16进制

let systemStr = ab2hex(str)

// console.log(hexCharCodeToStr(systemStr),99)

function hexCharCodeToStr(hexCharCodeStr) {

var trimedStr = hexCharCodeStr.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

let str5 = String.fromCharCode(curCharCode)

if (str5.startsWith('\n') == false) {

resultStr.push(String.fromCharCode(curCharCode));

}

}

return resultStr.join("");

}

// console.log(hexCharCodeToStr(systemStr),888)

return hexCharCodeToStr(systemStr)

},

//监听低功耗蓝牙连接状态的改变事件

onBLEConnectionStateChange() {

uni.onBLEConnectionStateChange(function(res) {

if (!res.connected) {

// console.log('蓝牙断开链接')

this.closeBluetooth()

}

})

},

stopBluetooth() {

uni.stopBluetoothDevicesDiscovery({

success: e => {

// console.log('停止搜索蓝牙设备:' + e.errMsg);

},

fail: e => {

// console.log('停止搜索蓝牙设备失败,错误码:' + e.errCode);

}

});

},

//关闭蓝牙模块

closeBluetooth() {

uni.closeBluetoothAdapter({

success(res) {

console.log(res)

}

})

}

},

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,445评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,889评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,047评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,760评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,745评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,638评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,011评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,669评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,923评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,655评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,740评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,406评论 4 320
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,995评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,961评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,197评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,023评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,483评论 2 342