123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238 |
- const server_uuid = "0000FFE5-0000-1000-8000-00805F9B34FB";
- let callback = null
- let connecting = false
- let connected = false
- let deviceId = null
- let configTimeout = null
- let iccid = ''
- /**
- * 连接ble设备
- * @param {string} mac 设备mac地址
- * @param {function} cb 连接的回调
- */
- function connectBle(mac, cb) {
- if (!connecting && !connected) {
- deviceId = mac
- connecting = true
- callback = cb
- iccid = ''
- uni.createBLEConnection({
- deviceId,
- success(res) {
- console.log('ble连接成功')
- //console.log(res)
- connected = true
- connecting = false
- //获取服务
- getBleDeviceServices()
- },
- fail(err) {
- console.log(`ble连接失败 code :${err.errCode}`)
- connecting = false
- connected = false
- callback(err)
- //errorText = '连接失败!请将手机靠近设备'
- }
- })
- }
- }
- /**
- * 获取ble的特征
- * @param {string} deviceId 设备mac地址
- */
- function getBleDeviceServices() {
- setTimeout(() => {
- uni.getBLEDeviceServices({
- deviceId,
- success(res) {
- console.log('ble获取服务成功')
- for (let service of res.services) {
- //console.log(service)
- if (server_uuid.toUpperCase() == service.uuid.toUpperCase()) {
- //获取特征
- getBLEDeviceCharacteristics()
- return
- }
- }
- },
- fail(err) {
- console.log(`ble获取服务失败 code :${err.errCode}`)
- closeBLEConnection()
- callback(err)
- }
- })
- }, 1000)
- }
- /**
- * 获取特征
- */
- function getBLEDeviceCharacteristics() {
- //setTimeout(() => {
- uni.getBLEDeviceCharacteristics({
- deviceId,
- serviceId: server_uuid,
- success(res) {
- console.log('ble获取特征成功');
- notifyBLECharacteristicValueChange(res.characteristics[0].uuid)
- },
- fail(err) {
- console.log(`获取特征失败 code :${err.errCode}`);
- //console.log(err);
- closeBLEConnection()
- callback(err)
- }
- })
- //}, 1000)
- }
- /**
- * 监听设备发送过来的数据
- * @param {string} characteristicId 特征的uuid
- */
- function notifyBLECharacteristicValueChange(characteristicId) {
- setTimeout(() => {
- //设置一个超时配网的时间
- configTimeout = setTimeout(() => {
- closeBLEConnection()
- if (callback) {
- callback({ errCode: -100 })
- }
- }, 20 * 1000)
- uni.notifyBLECharacteristicValueChange({
- state: true,
- deviceId,
- serviceId: server_uuid,
- characteristicId: characteristicId,
- })
- //监听设备发送过来的数据
- uni.onBLECharacteristicValueChange(function (res) {
- let buf = Buffer.from(res.value);
- let receiveStr = buf.toString()
- console.log(`收到数据:${receiveStr}`);
- if (receiveStr === 'connect_success') {
- //配网成功
- closeBLEConnection()
- if (callback && iccid && iccid.length > 0) {
- callback({ errCode: 0, iccid })
- }
- } else if (receiveStr.indexOf('failure') >= 0) {
- //'配网失败'
- closeBLEConnection()
- if (callback) {
- callback({ errCode: -101 })
- }
- } else if (receiveStr.indexOf('ic0:') >= 0) { //用来获取iccid的
- iccid = receiveStr.substring(4, receiveStr.length);
- } else if (receiveStr.indexOf('ic1:') >= 0) { //用来获取iccid的 把ic0 和ic1拼接起来
- let ic1 = receiveStr.substring(4, receiveStr.length);
- iccid = iccid + ic1;
- //发送4G配网指令
- let buf = Buffer.from('without_WiFi')
- setTimeout(() => { sendCongifCmd(characteristicId, buf.buffer) }, 800)
- } else if (receiveStr.indexOf('start_network') >= 0) {
- //发送 AIrSMArT_CLOSE指令
- setTimeout(() => {
- let buf = Buffer.from('AIrSMArT_CLOSE')
- sendCongifCmd(characteristicId, buf.buffer)
- }, 2000)
- }
- else if (receiveStr.indexOf('recv_finish') >= 0) {
- //todo 设备这里流程没有统一,目前唯一的设备MW-V是收到recv_finish就配网结束了
- setTimeout(() => {
- closeBLEConnection()
- if (callback && iccid && iccid.length > 0) {
- callback({ errCode: 0, iccid })
- }
- }, 1000)
- } else if (receiveStr.indexOf('without_WiFi_OK') >= 0) {
- //配网成功
- closeBLEConnection()
- if (callback && iccid && iccid.length > 0) {
- callback({ errCode: 0, iccid })
- }
- }
- })
- //发送get_iccid数据给设备
- setTimeout(() => {
- //获取iccid
- let buf = Buffer.from('get_iccid')
- let buffer = buf.buffer
- sendCongifCmd(characteristicId, buffer)
- }, 800)
- }, 1000)
- }
- /**
- * 发送数据给设备
- * @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)
- })();
- }
- /**
- * 关闭ble连接
- */
- function closeBLEConnection() {
- if (deviceId) {
- uni.closeBLEConnection({
- deviceId,
- success(res) {
- console.log('ble关闭连接成功');
- },
- fail(err) {
- console.log(`ble关闭连接失败 code :${err.errCode}`);
- }
- })
- //clearInterval(withoutWifiInterval)
- clearTimeout(configTimeout)
- connected = false
- }
- }
- module.exports = { closeBLEConnection, connectBle };
|