1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015 |
- // 安卓平台上,在调用 notifyBLECharacteristicValueChange 成功后立即调用 writeBLECharacteristicValue 接口,在部分机型上会发生 10008 系统错误
- // var http = require("../utils/config.js");
- var interval = null;
- const cmd = {
- heartBeat: 'heart', // 心跳包
- unlock: 'openBike', // 开锁命令
- lock: 'lock', // 开锁命令
- bell: 'bellBike', // 关锁命令
- temporaryUnlockBike: 'temporaryUnlockBike', // 关锁命令
- temporaryLockBike: 'temporaryLockBike', // 关锁命令
- batteryUnlock: 'batteryUnlock', // 关锁命令
- batteryLock: 'batteryLock', // 关锁命令
- // login: 'login', // 关锁命令
- status: 'status', // 关锁命令
- reboot: 'reboot'
- }
- const errorCode = {
- no_connection: 10006, //失去连接
- no_service: 10004, //没有找到指定服务
- apdater_no_avilable: 10001, //当前蓝牙适配器不可用
- discovery_timeOut: 1100, //扫描失败
- connet_timeOut: 10003 //连接超时
- }
- const GetBluUrl = 'https://bike.hanyiyun.com/app-api/bike/getKey';
- let util = require('./bluUtil.js');
- let dataTransition = require('./dataTransition.js');
- class BluetoothManager {
- constructor() {
- this._connectDeviceName = 'shanxiango'
- this._isFoundDevice = false
- this._deviceId = ''
- this._serviceId = ''
- this._bikeMainId = ''
- this._mac = '',
- this._sequenceId = 10
- this._characteristicId = ''
- this._characteristicId_write = ''
- this._discovering = false
- this.discoveryTimeOut = 10 * 1000
- this.isConnecting = false
- this.isAuth = false
- this.connnectTimeOut = 5 * 1000 //连接超时时间
- this.hardwareCallbackTimeOut = 5 * 1000 //硬件回调超时时间
- this.adapterStateChangeCallBack = undefined
- this.onConnectionStateChange = undefined
- this.heartTimer = ''
- // 处理接受数据
- this._receiveLength = 0
- this._receiveData = ''
- // this.initialNotification()
- this.readyStopDiscovery = false //标记准备关闭扫描
- this.instructions = '' //记录指令
- this.writeIndex = 0
- }
- /*******初始化各种回调**********/
- initialNotification() {
- var that = this;
- console.log('initialNotification')
- // this.getConnectedBluetoothDevices()
- // 监听蓝牙适配器状态改变
- uni.showLoading({
- title: '蓝牙连接中'
- })
- uni.onBluetoothAdapterStateChange(
- res => {
- console.log('onBluetoothAdapterStateChange', res)
- // this.connectDeivece(this._bikeMainId,this.instructions)
- if (that.adapterStateChangeCallBack) {
- that.adapterStateChangeCallBack(res)
- }
- if (res.available == false) {
- this.isConnecting = false;
- }
- }
- )
- // // 监听扫描到的设备
- uni.onBluetoothDeviceFound(
- res => {
- console.log('监听扫描到的设备')
- if (that._isFoundDevice) {
- return
- }
- console.log(res)
- for (var i = 0; i < res.devices.length; i++) {
- const device = res.devices[i];
- var name = device.name
- console.log(name, device.deviceId)
- if (name === 'shanxiango') {
- if (device.localName != name) return;
- if (name != that._connectDeviceName) return;
- let bf = device.advertisData.slice(2, 10);
- var abc = util.ab2hex(bf)
- let contentArr = util.strAverage2Arr(abc, 2)
- contentArr.reverse();
- var string = contentArr.join('').toUpperCase() //mac地址
- console.log(string, 'Mead===>', res.devices[i], that._mac)
- if (!that._isFoundDevice && name == that._connectDeviceName) {
- // 获取车辆中控编号
- console.log(that._mac)
- if (string == that._mac) {
- console.log('-------found ---', device.name, string)
- console.log(device)
- console.log(device.deviceId)
- that._isFoundDevice = true
- that._deviceId = device.deviceId
- if (that.deviceFoundBlock) {
- that.deviceFoundBlock(device.deviceId)
- }
- break
- // uni.stopBluetoothDevicesDiscovery()
- }
- }
- }
- }
- return
- }
- )
- // 监听蓝牙连接状态
- uni.onBLEConnectionStateChange(
- res => {
- console.log(res)
- console.log('监听蓝牙连接状态', res, this._deviceId)
- this.isConnecting = res.connected
- if (res.deviceId == this._deviceId && res.connected == false) {
- console.log('onBLEConnectionStateChange fail', this._connectionFailBlock);
- if (this._connectionFailBlock) {
- // uni.showModal({
- // title: '提示',
- // content: '蓝牙连接超时',
- // showCancel: false
- // })
- uni.hideLoading()
- this._connectionFailBlock(res)
- this._connectionFailBlock = undefined
- }
- if (this.onConnectionStateChange) {
- this.onConnectionStateChange(res)
- }
- uni.closeBLEConnection({
- deviceId: this._deviceId,
- success: function(res) {
- console.log('closeBLEConnection', res)
- },
- })
- }
- }
- )
- // 监听特征值变化
- uni.onBLECharacteristicValueChange(
- characteristic => {
- console.log('监听特征值变化', characteristic)
- if (characteristic.value) {
- let res = characteristic.value
- let resData = util.ab2hex(res.value);
- if (this._receiveLength == 0) {
- this._receiveLength = parseInt(resData.slice(8, 12), 16)
- }
- this._receiveData += resData
- if (this._receiveData.length === (this._receiveLength * 2 + 16)) {
- let _receiveData = this._receiveData
- console.log(_receiveData, '_receiveData')
- let flay = _receiveData.slice(0, 4)
- let crc16 = _receiveData.slice(12, 16);
- let systemState = _receiveData.slice(4, 6); //4c
- let sequenceId_16 = _receiveData.slice(6, 8); //0a
- let body = _receiveData.slice(16)
- let contentArr = util.addFlagBeforeArr(util.strAverage2Arr(body, 2));
- //校检数据
- if (parseInt(dataTransition.getCRC16(contentArr), 16) == parseInt(crc16, 16)) {
- let value = util.hexStringToArrayBuffer(`aa12${systemState}${sequenceId_16}00000000`);
- if (flay === 'aa10') {
- if (body.indexOf('aa10550b') > -1) {
- if (this.getRandomSuccessBlock) {
- this.getRandomSuccessBlock(body)
- this.getRandomSuccessBlock = undefined
- }
- }
- console.log('指令发送成功', body)
- } else if (flay === 'aa00') {} else if (flay === 'aa30') {
- console.log('校检错误')
- } else {
- // this.writeBLECharacteristicValue(value)
- // that.analysisBLEContent(body)
- }
- }
- // 返回ACK
- this._receiveLength = 0
- this._receiveData = ''
- }
- }
- }
- )
- }
- failToGetConnected() {
- var that = this;
- if (!that.getConnectedTimer) {
- clearTimeout(that.getConnectedTimer);
- that.getConnectedTimer = null;
- }
- that.getConnectedTimer = setTimeout(function() {
- uni.getBluetoothAdapterState({
- success: function(res) {
- console.log(res);
- var available = res.available;
- if (!available) {
- uni.showLoading({
- title: '请开蓝牙',
- icon: 'loading',
- duration: 2000
- })
- } else {
- if (!that.connectedDevice['state']) {
- that.getConnectedBluetoothDevices();
- }
- }
- },
- fail: function(err) {
- console.log(err);
- }
- })
- }, 3000);
- }
- /***********初始化接口***************/
- connectDeivece(bikeMainId, command = false) {
- console.log(this.isConnecting, this._bikeMainId, bikeMainId, cmd)
- this.instructions = command;
- // this._bikeMainId = bikeMainId;
- // this.isConnecting = true;
- if (this.isConnecting && bikeMainId == this._bikeMainId) {
- return new Promise(
- (resolve, reject) => {
- if (command == cmd.unlock) {
- this.unlockBike()
- } else if (command == cmd.lock) {
- this.lockBike()
- } else if (command == cmd.bell) {
- this.play_voice()
- } else if (command == cmd.batteryUnlock) {
- this.diankai()
- } else if (command == cmd.reboot) {
- this.chongqi()
- }
- resolve(true)
- return
- }
- )
- } else {
- if (this._deviceId) {
- this.closeConnection(this._deviceId)
- }
- }
- this._bikeMainId = bikeMainId //当前车辆编号
- // 初始化蓝牙
- this.initialNotification()
- return this.openAdapter().then(res => {
- return this.getSecretKey()
- }).then(res => {
- return this.startDiscovery()
- }).then(
- res => {
- console.log('startDiscovery---------', res)
- this._discovering = true
- // 等待发现设备
- return this.waitForDeviceFound()
- },
- reject => {
- console.log(reject)
- uni.showToast({
- title: '连接失败请检查蓝牙',
- icon: 'none'
- })
- }
- ).then(
- res => {
- console.log('stopDiscovery---------')
- this.readyStopDiscovery = true
- //关闭扫描
- return this.stopDiscovery()
- }
- ).then(
- res => {
- this.readyStopDiscovery = false
- this._discovering = false
- console.log('createConnection---------', res)
- //开始连接设备
- console.log(this._deviceId)
- return this.createConnection(this._deviceId)
- }
- ).then(
- res => {
- console.log('getServices---------', res)
- // 获取服务
- return this.getServices(this._deviceId)
- }
- ).then(
- res => {
- console.log('getCharacteristics---------', res)
- // 获取特征值
- console.log(this._deviceId)
- console.log(this._serviceId)
- return this.getCharacteristics(this._deviceId, this._serviceId)
- }
- ).then(
- res => {
- console.log('openNotifyChsValueChange---------', res)
- // 开启notify通道
- console.log('开启notify通道')
- console.log(this._deviceId, '=>', this._serviceId, '<++', this._characteristicId)
- switch (uni.getSystemInfoSync().platform) {
- case 'android':
- console.log('客户端是Android')
- return this.openNotifyChsValueChange(this._deviceId, this._serviceId, this._characteristicId_write)
- break;
- case 'ios':
- console.log('客户端是iOS')
- return this.openNotifyChsValueChange(this._deviceId, this._serviceId, this._characteristicId)
- break;
- }
- }
- )
- .then(
- res => {
- return this.onBLECharacteristicValueChange()
- }
- ).then(
- res => {
- if (command == cmd.unlock) {
- return this.unlockBike()
- } else if (command == cmd.lock) {
- return this.lockBike()
- } else if (command == cmd.bell) {
- return this.play_voice()
- } else if (command == cmd.batteryUnlock) {
- return this.diankai()
- } else if (command == cmd.reboot) {
- return this.chongqi()
- }
- return
- }
- )
- }
- // 监听特征值变化
- onBLECharacteristicValueChange() {
- let that = this
- uni.onBLECharacteristicValueChange(
- characteristic => {
- console.log('onBLECharacteristicValueChange', characteristic)
- setTimeout(function() {
- uni.showToast({
- title: '请求成功',
- icon: 'none'
- })
- }, 1000)
- // if (characteristic.value) {
- // let res = characteristic.value
- // let resData = util.ab2hex(res);
- // // 4244 00 04 0a0a0505
- // // 0a 01 01 a463
- // // mead
- // let resDatas = resData.split('4244').filter((res) => {
- // return res
- // }).map((res) => {
- // return '4244' + res
- // })
- // resDatas.forEach(res_data => {
- // //业务
- // console.log(res_data, 'resData')
- // let data = res_data.slice(0, -4)
- // console.log(data, 'data')
- // if (this.instruct != cmd.bell) {
- // this.writeIndex = this.writeIndex + 1
- // var zhiling = uni.getStorageSync('zhiling');
- // var arr1 = [];
- // if (zhiling == '' || zhiling == undefined) {
- // arr1 = arr1.concat(data)
- // } else {
- // arr1 = zhiling.concat(data)
- // }
- // uni.setStorageSync('zhiling', arr1)
- // var number = 1;
- // interval = setInterval(() => {
- // number += 1;
- // console.log(arr1)
- // console.log(data)
- // console.log(this.writeIndex)
- // console.log(arr1[this.writeIndex - 1])
- // if (arr1[this.writeIndex - 1] == data) {
- // console.log('111')
- // //成功响应 调接口告诉后台
- // clearInterval(interval)
- // if (this.instructions == cmd.unlock) {
- // var key5 = ['0x42', '0x44', '0x00', '0x01', '0x0A', '0x0A', '0x05', '0x05', '0x0A', '0x07', '0x01', '0x02', '0x00', '0x00', '0x00', '0x00', '0x00']
- // let value2 = util.CRC(key5)
- // var value3 = '424400010A0A05050A0701020000000000' + value2
- // this.writeBLECharacteristicValue(util.hexStringToArrayBuffer(value3), '123')
- // this.instructions = cmd.bell
- // }
- // if (this.instructions == cmd.lock) {
- // //播放语音
- // var key5 = ['0x42', '0x44', '0x00', '0x01', '0x0A', '0x0A', '0x05', '0x05', '0x0A', '0x07', '0x01', '0x01', '0x00', '0x00', '0x00', '0x00', '0x00']
- // let value2 = util.CRC(key5)
- // var value3 = '424400010A0A05050A0701010000000000' + value2
- // this.writeBLECharacteristicValue(util.hexStringToArrayBuffer(value3))
- // this.instructions = cmd.bell
- // }
- // return;
- // } else {
- // //未成功响应 再次发指令
- // if (number % 5 == 0) {
- // console.log(number)
- // //每5秒执行一次写入数据
- // if (this.instructions == cmd.unlock) {
- // this.unlockBike()
- // } else if (this.instructions == cmd.lock) {
- // this.lockBike()
- // } else if (this.instructions == cmd.bell) {
- // this.play_voice()
- // } else if (this.instructions == cmd.batteryUnlock) {
- // this.diankai()
- // } else if (this.instructions == cmd.reboot) {
- // this.chongqi()
- // }
- // clearInterval(interval)
- // }
- // }
- // if (number >= 30) {
- // //超时清空定时器
- // clearInterval(interval)
- // }
- // }, 1000);
- // }
- // let xiaojian = res_data.slice(res_data.length - 4)
- // let arr = [],
- // body = [];
- // for (let i = 0, index = 0; i < (data.length / 2); i++) {
- // arr.push('0x' + data.slice(index, index + 2))
- // if (index >= 16) {
- // body.push(data.slice(index, index + 2))
- // }
- // index = index + 2
- // }
- // let value = util.CRC(arr)
- // console.log(body)
- // console.log(value, 'value')
- // console.log(xiaojian, 'xiaojian')
- // if (value == xiaojian) {
- // console.log('数据正确')
- // switch (body[0]) {
- // case '01':
- // //获取ECU状态
- // break
- // case '02':
- // //电门开关
- // break
- // case '03':
- // //防盗开关
- // break
- // case '04':
- // //照明灯开关
- // break
- // case '05':
- // //开电池仓
- // break
- // case '06':
- // //后座锁开关
- // break
- // case '07':
- // //后轮锁开关
- // break
- // case '08':
- // //获取配置信息
- // break
- // case '09':
- // //综合参数配置
- // break
- // case '0a':
- // //语音设置
- // break
- // case '0b':
- // //重启设置
- // break
- // case '0c':
- // //获取ECU信息
- // break
- // case '0d':
- // //2.13 设置服务器域名(IP)和端口
- // break
- // case '0e':
- // //2.14 获取服务器域名(IP)和端口
- // break
- // case '0f':
- // //2.15 接单设置
- // break
- // }
- // }
- // });
- // // var resData = '424400040a0a05050a0101a463'
- // }
- if (characteristic.value) {
- let res = characteristic.value
- let resData = util.ab2hex(res);
- if (this._receiveLength == 0) {
- this._receiveLength = parseInt(resData.slice(8, 12), 16)
- }
- this._receiveData += resData
- if (this._receiveData.length === (this._receiveLength * 2 + 16)) {
- let _receiveData = this._receiveData
- console.log(_receiveData)
- let flay = _receiveData.slice(0, 4)
- let crc16 = _receiveData.slice(12, 16);
- let systemState = _receiveData.slice(4, 6); //4c
- let sequenceId_16 = _receiveData.slice(6, 8); //0a
- let dcArr = [];
- let body = _receiveData.slice(16)
- let contentArr = util.addFlagBeforeArr(util.strAverage2Arr(body, 2));
- //校检数据
- if (parseInt(dataTransition.getCRC16(contentArr), 16) == parseInt(crc16, 16)) {
- let response = util.hexStringToArrayBuffer(`aa12${systemState}${sequenceId_16}00000000`);
- if (flay === 'aa10') {
- console.log(this.getRandomSuccessBlock, 'getRandomSuccessBlock')
- if (this.getRandomSuccessBlock) {
- this.getRandomSuccessBlock(body)
- this.getRandomSuccessBlock = undefined
- }
- console.log('指令发送成功', body)
- } else if (flay === 'aa00') {} else if (flay === 'aa30') {
- console.log('CRC校验失败', body);
- } else {
- //响应数据
- // that.writeBLECharacteristicValue(response, undefined)
- // that.analysisBLEContent(body)
- }
- }
- this._receiveLength = 0
- this._receiveData = ''
- }
- }
- }
- )
- }
- //获取秘钥
- getSecretKey(box_no) {
- if (!box_no) box_no = this._bikeMainId
- let that = this
- console.log(box_no)
- return new Promise(function(res, rej) {
- let param = {
- box_no: box_no //我公司是通过设备编号获取的密钥
- };
- uni.request({
- url: 'https://bike.saas.yufengjiayun.com/app-api/bike/getKey',
- data: param,
- header: {
- Authorization: 'bearer' + ' ' + uni.getStorageSync('token').token
- },
- success: (resp) => {
- console.log(resp)
- that._mac = resp.data.key
- res(resp.data.key);
- },
- fail: (err) => {
- console.log(err)
- }
- })
- });
- }
- waitForDeviceFound() {
- return new Promise(
- (resolve, reject) => {
- this.deviceFoundBlock = resolve
- console.log('waitForDeviceFound ----')
- console.log(this._discovering, '<==>', !this._isFoundDevice)
- setTimeout(() => {
- console.log('waitForDeviceFound ++++', this._discovering, this._isFoundDevice)
- // 全局断了,_discovering 变为false(发心跳包失败,closeApater引起)
- console.log(this._discovering, '==>', !this._isFoundDevice)
- if (this._discovering && !this._isFoundDevice) {
- uni.showToast({
- title: '蓝牙扫描超时',
- icon: 'none'
- })
- console.log('waitForDeviceFound 扫描超时00', 'isconnecting :', this.isConnecting)
- reject({
- errCode: errorCode.discovery_timeOut
- })
- }
- if (this._discovering) {
- this.stopDiscovery()
- }
- }, this.discoveryTimeOut);
- }
- )
- }
- disconnecDevice() {
- return this.closeConnection(this._deviceId).then(
- res => {
- return this.closeAdapter()
- }
- )
- }
- /***********初始化接口***************/
- /***********蓝牙处理*************/
- // 打开适配器
- openAdapter() {
- console.log('打开适配器')
- return new Promise(
- (resolve, reject) => {
- uni.openBluetoothAdapter({
- success: resolve,
- fail: reject
- })
- }
- )
- }
- // 关闭适配器
- closeAdapter() {
- console.log('关闭适配器')
- this._isFoundDevice = false
- this._discovering = false
- this.isConnecting = false
- this.adapterStateChangeCallBack = undefined
- this.onConnectionStateChange = undefined
- return new Promise(
- (resolve, reject) => {
- this.isOpenAdpater = false
- this.isConnecting = false
- uni.closeBluetoothAdapter({
- success: resolve,
- fail: reject
- })
- }
- )
- }
- // 开启扫描
- startDiscovery() {
- console.log('开启扫描')
- return new Promise(
- (resolve, reject) => {
- uni.startBluetoothDevicesDiscovery({
- services: ['FFF0'],
- allowDuplicatesKey: true,
- success: resolve,
- fail: reject
- })
- }
- )
- }
- // 关闭扫描
- stopDiscovery() {
- console.log('关闭扫描')
- this._isFoundDevice = false;
- uni.hideLoading()
- return new Promise(
- (resolve, reject) => {
- uni.stopBluetoothDevicesDiscovery({
- success: resolve,
- fail: reject
- })
- }
- )
- }
- // 创建连接
- createConnection(deviceId) {
- console.log('创建连接')
- console.log(deviceId)
- return new Promise(
- (resolve, reject) => {
- this._connectionFailBlock = undefined
- this._connectionFailBlock = reject
- // this._needToToastConnectError = true
- console.log(deviceId)
- console.log(this.connnectTimeOut)
- uni.createBLEConnection({
- deviceId: deviceId,
- // timeout: this.connnectTimeOut,
- success: res => {
- console.log('--------createConnection success', res)
- // 创建成果并不代表发指令成功,有可能连接连接创建成功了,但是发指令的时候连接中断了
- resolve(res)
- },
- fail: error => {
- console.log('--------createConnection fail', error)
- this._connectionFailBlock = undefined
- reject(error)
- }
- })
- }
- )
- }
- // 关闭连接
- closeConnection(deviceId) {
- console.log('关闭连接')
- return new Promise(
- (resolve, reject) => {
- uni.closeBLEConnection({
- deviceId: deviceId,
- success: resolve,
- fail: reject
- })
- }
- )
- }
- // 获取服务
- getServices(deviceId) {
- console.log('获取服务')
- let that = this
- console.log(deviceId)
- return new Promise(
- (resolve, reject) => {
- this._connectionFailBlock = undefined
- this._connectionFailBlock = reject
- setTimeout(function() {
- uni.getBLEDeviceServices({
- deviceId: deviceId,
- success: res => {
- console.log(res)
- // if (res.errCode === 0) {
- res.services.forEach(function(value, index, array) {
- console.log("设备所有的UUId", value.uuid);
- if (value.uuid.indexOf('FFF0') > -1) { //找到serviceId包含FEF6的服务
- that._serviceId = array[index].uuid;
- // resolve(serviceId)
- console.log(that._serviceId)
- }
- })
- // }
- resolve(res)
- },
- fail: error => {
- console.log('getServices fail', error)
- reject(error)
- }
- })
- }, 3000)
- }
- )
- }
- // 获取特征值
- getCharacteristics(deviceId, serviceId) {
- console.log('获取特征值')
- let that = this
- console.log(deviceId)
- console.log(serviceId)
- return new Promise(
- (resolve, reject) => {
- this._connectionFailBlock = undefined
- this._connectionFailBlock = reject
- uni.getBLEDeviceCharacteristics({
- deviceId: deviceId,
- serviceId: serviceId,
- success: res => {
- console.log('getCharacteristics success', res)
- for (let i = 0; i < res.characteristics.length; i++) {
- if (res.characteristics[i].properties.notify && !res.characteristics[i].properties.write) {
- that._characteristicId = res.characteristics[i].uuid; //读的uuid
- console.log('读')
- }
- if (res.characteristics[i].properties.write) {
- that._characteristicId_write = res.characteristics[i].uuid; //写的uuid
- console.log('写')
- }
- }
- resolve(res)
- },
- fail: error => {
- console.log('getCharacteristics fail', error)
- reject(error)
- }
- })
- }
- )
- }
- // 开启notify功能,订阅特征值
- openNotifyChsValueChange(deviceId, serviceId, characteristicId) {
- let that = this;
- console.log(deviceId, serviceId, characteristicId)
- console.log(characteristicId, 'characteristicId')
- console.log(serviceId, 'serviceId')
- console.log(deviceId, 'deviceId')
- return new Promise(
- (resolve, reject) => {
- this._connectionFailBlock = undefined
- this._connectionFailBlock = reject
- uni.notifyBLECharacteristicValueChange({
- deviceId: deviceId,
- serviceId: serviceId,
- characteristicId: characteristicId,
- state: true,
- success: res => {
- console.log('openNotifyChsValueChange success', res)
- resolve(res)
- },
- fail: error => {
- console.log('openNotifyChsValueChange fail', error)
- reject(error)
- this.connectDeivece(this._bikeMainId, this.instructions)
- }
- })
- }
- )
- }
- //开锁
- unlockBike() {
- uni.showLoading({
- title: '开锁中...'
- })
- var key2 = ['0x42', '0x44', '0x00', '0x01', '0x0A', '0x0A', '0x05', '0x05', '0x02', '0x01', '0x01']
- let value = util.CRC(key2)
- console.log(value)
- var value1 = '424400010A0A0505020101' + value
- console.log(value1)
- this.writeBLECharacteristicValue(util.hexStringToArrayBuffer(value1), '123')
- //播放语音
- var key5 = ['0x42', '0x44', '0x00', '0x01', '0x0A', '0x0A', '0x05', '0x05', '0x0A', '0x07', '0x01', '0x02', '0x00',
- '0x00', '0x00', '0x00', '0x00'
- ]
- let value2 = util.CRC(key5)
- var value3 = '424400010A0A05050A0701020000000000' + value2
- this.writeBLECharacteristicValue(util.hexStringToArrayBuffer(value3), '123')
- }
- //发送关锁指令
- lockBike() {
- uni.showLoading({
- title: '关锁中...'
- })
- var key2 = ['0x42', '0x44', '0x00', '0x01', '0x0A', '0x0A', '0x05', '0x05', '0x02', '0x01', '0x00']
- let value = util.CRC(key2)
- console.log(value)
- var value1 = '424400010A0A0505020100' + value
- console.log(value1)
- this.writeBLECharacteristicValue(util.hexStringToArrayBuffer(value1))
- //播放语音
- var key5 = ['0x42', '0x44', '0x00', '0x01', '0x0A', '0x0A', '0x05', '0x05', '0x0A', '0x07', '0x01', '0x01', '0x00',
- '0x00', '0x00', '0x00', '0x00'
- ]
- let value2 = util.CRC(key5)
- var value3 = '424400010A0A05050A0701010000000000' + value2
- this.writeBLECharacteristicValue(util.hexStringToArrayBuffer(value3))
- }
- play_voice() {
- uni.showLoading({
- title: '响铃中...'
- })
- var key5 = ['0x42', '0x44', '0x00', '0x01', '0x0A', '0x0A', '0x05', '0x05', '0x0A', '0x07', '0x01', '0x09', '0x00',
- '0x00', '0x00', '0x00', '0x00'
- ]
- let value = util.CRC(key5)
- console.log(value)
- var value1 = '424400010A0A05050A0701090000000000' + value
- console.log(value1)
- this.writeBLECharacteristicValue(util.hexStringToArrayBuffer(value1))
- }
- diankai() {
- uni.showLoading({
- title: '开电池锁中...'
- })
- var key3 = ['0x42', '0x44', '0x00', '0x01', '0x0A', '0x0A', '0x05', '0x05', '0x05', '0x01', '0x01']
- let value = util.CRC(key3)
- console.log(value)
- var value1 = '424400010A0A0505050101' + value
- console.log(value1)
- this.writeBLECharacteristicValue(util.hexStringToArrayBuffer(value1))
- }
- chongqi() {
- uni.showLoading({
- title: '重启中...'
- })
- var key3 = ['0x42', '0x44', '0x00', '0x01', '0x0A', '0x0A', '0x05', '0x05', '0x0B', '0x07', '0x01', '0x01', '0x01',
- '0x01', '0x01', '0x01', '0x01'
- ]
- let value = util.CRC(key3)
- console.log(value)
- var value1 = '424400010A0A05050B0701010101010101' + value
- console.log(value1)
- this.writeBLECharacteristicValue(util.hexStringToArrayBuffer(value1))
- }
- //发送数据
- writeBLECharacteristicValue(data, reject) {
- console.log(this._deviceId, this._serviceId, this._characteristicId_write, '发送参数');
- console.log(data)
- uni.writeBLECharacteristicValue({
- deviceId: this._deviceId,
- serviceId: this._serviceId,
- characteristicId: this._characteristicId_write,
- value: data,
- success: res => {
- console.log('writeBLECharacteristicValue success', res)
- },
- fail: err => {
- console.log('writeBLECharacteristicValue fail', err, this._deviceId, this._serviceId, this._characteristicId)
- // if(){
- this.isConnecting = false;
- // }
- // reject(err)
- this.closeConnection(this._deviceId)
- },
- complete(res) {
- console.log(res, 'complete')
- switch (uni.getSystemInfoSync().platform) {
- case 'android':
- console.log('客户端是Android')
- uni.showToast({
- title:'操作成功'
- })
- return
- break;
- case 'ios':
- console.log('客户端是iOS')
- return
- break;
- }
- }
- })
- }
- /**
- * 根据指令码生成指令帧数据
- * commandCode --> 指令码
- * array --> 额为携带的数据
- */
- // generateCommandData(commandCode, array) {
- // let sequenceId_16 = dataTransition.getSequenceId(this._sequenceId);
- // // this._sequenceId++;
- // let sendData = '';
- // console.log(commandCode)
- // // console.log(sequenceId_16)
- // switch (commandCode) {
- // case cmd.unlock:
- // sendData = '03 00 02 01 00';
- // break
- // case cmd.lock:
- // sendData = '03 00 01 01 01';
- // break;
- // case cmd.bell:
- // sendData = '03 00 04 01 01';
- // break;
- // case cmd.batteryUnlock:
- // sendData = '03 00 05 01 01';
- // break;
- // case cmd.batteryLock:
- // sendData = '03 00 05 01 00';
- // break;
- // case cmd.temporaryUnlockBike:
- // sendData = '03 00 02 01 00 07 01 01';
- // break
- // case cmd.temporaryLockBike:
- // sendData = '03 00 07 01 08';
- // break;
- // // case cmd.login:
- // // // let secretKey = array.key.toString().trim().toLowerCase();
- // // console.log(secretKey)
- // // // let c = secretKey.toString().replace(/\s+/g, "");
- // // // let cLength = dataTransition.getSecretKeyLength(c);
- // // //发送内容
- // // let send = `02 00 01`; //02 连接命令 01连接请求 cLength秘钥长度。
- // // sendData = `${send} ${secretKey}`;
- // // console.log(sendData, 'sendValue')
- // // break;
- // case cmd.status:
- // sendData = '42 44 00 01 0A 0A 05 05'
- // console.log(sendData)
- // break
- // case cmd.ack:
- // sendData = array.data
- // break;
- // }
- // let header = dataTransition.header(sendData);
- // console.log(header)
- // if (commandCode == 'responseAck') {
- // header = ''
- // }
- // let data = header + sendData.replace(/\s+/g, "");
- // console.log(data)
- // console.log(`发送${commandCode}指令`, data);
- // return data;
- // }
- /*******util*********/
- }
- // export {
- // BluetoothManager
- // }
- module.exports = {
- BluetoothManager: BluetoothManager,
- BtErrorCode: errorCode,
- CMD: cmd
- }
|