123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267 |
- const SERVER_UUID = "0000AB00-0000-1000-8000-00805F9B34FB";
- const DISSCONNECTED = 0
- const CONNECTING = 1
- const CONNECTED = 2
- const DISSCONNECTING = 3
- let callback = null
- let deviceId = null
- let writeCharacteristicId = null
- let configTimeout = null
- let state = DISSCONNECTED
- /**
- * 连接ble设备
- * @param {string} mac 设备mac地址
- * @param {function} cb 连接的回调
- */
- function connectBle(mac, cb) {
- if (state === DISSCONNECTED) {
- deviceId = mac
- callback = cb
- state = CONNECTING
- uni.createBLEConnection({
- deviceId,
- success(res) {
- console.log('ble连接成功')
- state = CONNECTED
- //获取服务
- getBleDeviceServices()
- },
- fail(err) {
- console.log(`ble连接失败 code :${err.errCode}`)
- state = DISSCONNECTED
- callback(err)
- }
- })
- }
- }
- /**
- * 获取ble的特征
- * @param {string} deviceId 设备mac地址
- */
- function getBleDeviceServices() {
- setTimeout(() => {
- uni.getBLEDeviceServices({
- deviceId,
- success(res) {
- console.log('ble获取服务成功')
- //let SERVER_UUID = res.services[0].uuid
- //getBLEDeviceCharacteristics()
- for (let service of res.services) {
- console.log(service)
- if (SERVER_UUID.toUpperCase() == service.uuid.toUpperCase()) {
- //获取特征
- getBLEDeviceCharacteristics(service.uuid)
- return
- }
- }
- },
- fail(err) {
- console.log(`ble获取服务失败 code :${err.errCode}`)
- closeBLEConnection()
- callback(err)
- }
- })
- }, 200)
- }
- /**
- * 获取特征
- */
- function getBLEDeviceCharacteristics(serverId) {
- //setTimeout(() => {
- uni.getBLEDeviceCharacteristics({
- deviceId,
- serviceId: serverId,
- success(res) {
- console.log(`ble获取特征成功`);
- for (let characteristic of res.characteristics) {
- console.log(characteristic.properties);
- // console.log(characteristic.properties.notify);
- if (characteristic.properties.notify) {
- console.warn(`NOTIFY ${characteristic.uuid}`);
- notifyBLECharacteristicValueChange(characteristic.uuid)
- } else {
- writeCharacteristicId = characteristic.uuid
- startAcivateDevice(characteristic.uuid)
- }
- }
- },
- fail(err) {
- console.log(`获取特征失败 code :${err.errCode}`);
- //console.log(err);
- //closeBLEConnection()
- callback(err)
- }
- })
- //}, 1000)
- }
- /**
- * 监听设备发送过来的数据
- * @param {string} characteristicId 特征的uuid
- */
- function notifyBLECharacteristicValueChange(nofifyCharacteristicId) {
- setTimeout(() => {
- //设置一个超时配网的时间
- configTimeout = setTimeout(() => {
- closeBLEConnection()
- if (callback) {
- callback({ errCode: -100 })
- }
- }, 60 * 1000)
- uni.notifyBLECharacteristicValueChange({
- state: true,
- deviceId,
- serviceId: SERVER_UUID,
- characteristicId: nofifyCharacteristicId,
- })
- //监听设备发送过来的数据
- uni.onBLECharacteristicValueChange(function(res) {
- let buf = Buffer.from(res.value);
- let receiveStr = buf.toString()
- console.log(`收到数据:${receiveStr}`);
- if (receiveStr.indexOf('ID0:') >= 0) {
- //获取id1
- let buffer = Buffer.from('getID1:').buffer
- setTimeout(() => { sendCongifCmd(writeCharacteristicId, buffer) }, 500)
- } else if (receiveStr.indexOf('ID1:') >= 0) {
- let data = "E2E7A1A90C89E81A62BACA5DD386F2A8ADD1192C5F3400F4D4D5B2FBF32B3B60B1209598A82C679D30C4604726D30DC09A31E241B716258CC2887FE6395D6181B9D55476A4F8F4C3D11A850BE4FE10BC42F126D74053F7A1B9FB44F76FE79B9903F48B0C5FB38746E6CDCA35121C785F46FC66460C56A8382D7656FBE4D0DB3A363149E0BCF94C05C69D2120241A98C83C8D05BA409C6F981F3491226AFBB7ACF987BD8E72E7B53AE77CFFE51E8CDE6F787BA7641B4F601BC5744FB99C50E7AC"
- setTimeout(() => { sendLongData(writeCharacteristicId, data) }, 500)
- }
- })
- }, 200)
- }
- function startAcivateDevice(characteristicId) {
- setTimeout(() => {
- //获取id0
- let buf = Buffer.from('getID0:').buffer
- setTimeout(() => { sendCongifCmd(characteristicId, buf) }, 500)
- }, 800)
- }
- /**
- * 发送数据给设备
- * @param {string} characteristicId 特征uuid
- * @param {ArrayBuffer} buffer 发送的数据
- */
- function sendCongifCmd(characteristicId, buffer) {
- let count = Math.ceil(buffer.byteLength / 20)
- //拆分成的ArrayBuffer数组,每个ArrayBuffer不超过20个字节
- let buffers = []
- for (var i = 0; i < count; i++) {
- let size = Math.min(20, buffer.byteLength - i * 20)
- let buf = buffer.slice(i * 20, size + i * 20)
- buffers.push(buf)
- }
- //返回的是一个promise对象
- function sendData(buffer) {
- return uni.writeBLECharacteristicValue({
- deviceId,
- serviceId: SERVER_UUID,
- characteristicId,
- value: buffer,
- })
- };
- (async() => {
- for (let b of buffers) {
- let res = await sendData(b)
- //console.log(res);
- console.log(`发送的数据为:${Buffer.from(b)} errorCode: ${res[res.length - 1].errCode}`);
- }
- // let promises = buffers.map((b) => sendData(b))
- // let res = await Promise.all(promises)
- })();
- }
- function sendLongData(characteristicId, dataStr) {
- let buffer = Buffer.from(dataStr)
- //每个包20个字节 间隔200毫秒
- //0x54 + 0x3a +pack_count(总数)+pack_index(包号)+data_len+data(长度最长15位)
- let count = Math.ceil(buffer.byteLength / 15)
- let buffers = []
- for (var i = 0; i < count; i++) {
- let size = Math.min(15, buffer.byteLength - i * 15)
- let buf = buffer.slice(i * 15, size + i * 15)
- let pkgBuf = Buffer.allocUnsafe(size + 5)
- pkgBuf.writeUInt8(0x54, 0) //固定0x54
- pkgBuf.writeUInt8(0x3a, 1) //固定0x54
- pkgBuf.writeUInt8(count, 2) //pack_count(包总数)
- pkgBuf.writeUInt8(i, 3) //pack_index(包号)
- pkgBuf.writeUInt8(size, 4) //data_len
- pkgBuf.write(buf.toString(), 5) //data
- //console.log(pkgBuf);
- buffers.push(pkgBuf.buffer)
- }
- // for (let b of buffers) {
- // console.warn(Buffer.from(b));
- // }
- //返回的是一个promise对象
- function sendData(buffer) {
- return uni.writeBLECharacteristicValue({
- deviceId,
- serviceId: SERVER_UUID,
- characteristicId,
- value: buffer,
- })
- };
- (async() => {
- for (let b of buffers) {
- let res = await sendData(b)
- //console.log(res);
- console.log(Buffer.from(b));
- console.log(`errorCode: ${res[res.length - 1].errCode}`);
- await sleep(200)
- }
- })();
- }
- function sleep(time) {
- return new Promise((resolve) => setTimeout(resolve, time))
- }
- /**
- * 关闭ble连接
- */
- function closeBLEConnection() {
- if (state !== DISSCONNECTED) {
- state = DISSCONNECTING
- uni.closeBLEConnection({
- deviceId,
- success(res) {
- state = DISSCONNECTED
- console.log('ble关闭连接成功');
- },
- fail(err) {
- console.log(`ble关闭连接失败 code :${err.errCode}`);
- }
- })
- clearTimeout(configTimeout)
- }
- }
- module.exports = { closeBLEConnection, connectBle, sendLongData };
|