위챗 애플릿 블루투스 모듈 개발

9564 단어
//index.js//응용 실례 가져오기
const app = getApp() const util = require('../../utils/util.js') const bletool = require('../../utils/bletool.js')
Page({data: {//lists: [{'order no':'111','car no':'321','car type':'상호첩','order date':'2018-01-02 08:00','order money':'16.00','order time':'4'}], car no:', order no:','order no:', lists:[],ble List: [],//블루투스 장치 배열 서비스 Id:",//592B3370-3900-9A71-4535-35D4212D2837 서비스Mac:",//C9:9B:4C:E7:DE:10 서비스psd: '',//855525B837253705595800000329 service_uiid:", deviceId:",characteristics:[]//특징값},onLoad:function(options) {this.initBle(),},onReady: function() {//페이지 렌더링 완료}, onShow: function() {if(app.globalData.car no.length>0) {this.getDeviceInfo();},온 Hide: function(() {//페이지 숨김}, 온 Unload: function() {//페이지는 app.globabababababababal Data.car no=no=function() {//페이지는 app.globababababal Data.car.car no='no='''''''nonction: function: function(((()): func.function 페이지는 app는 apt.gcar.car no no='''''''''''''''''nonction((((((((((((((())))) 페이지는 페이지는 은))) initBle();}else {util.showToast('휴대폰 블루투스 꺼짐'), app.globalData.ble isonnectting = false;}}}//블루투스 어댑터 wx를 엽니다.openBluetoothAdapter({success: function(res) {console.log('블루투스 어댑터 열기 성공'), that.getBluetoothAdapterState(), app.globalData.ble state =true, that.on BluetoothDeviceFound(),fail:function(res){//fail console.log(res)util.showToast('휴대폰 블루투스 켜주세요');},complete: function(res) {//complete})}, onBluetooth Device Found: function () {var that = this;//스캐너 wx.on Bluetooth Device Found(function(res) {//res 컴퓨터 시뮬레이터는 배열로, 휴대전화는 블루투스 장치 대상인console.log('새 장치 검색 감청:', res), that.update BleList([res]),}Bluetooth AdapterState: function() {var that = this, wx.getBluetooth AdapterState({success: function(res) {var available = res.available, var discovering = res.discovering, if (! available) {util.showToast ('블루투스 사용 불가')}else { if (!discovering) {//that.startBluetoothDevicesDiscovery(); } } } }) }, startBluetoothDevices Discovery: function () {var that = this; var 서비스 = []; 서비스.push (this.data.service Id); wx.showLoading ({title: '장치 검색 중'});setTimeout(function() {wx.hideLoading(), if(app.globalData.deviceId.length=0) {util.showModal('장치 검색 실패, 다시 시도하십시오'),}10000)if(bletool.isIOS() {wx.start Bluetooth Devices Discovery({서비스: 서비스, allow Duplicates Key:true, success: function(res) {console.log('ios 검색 성공'), console.log(res);,fail: function (err) { console.log(err); } }); }else {wx.start Bluetooth Devices Discovery ({//서비스s: 서비스, allow Duplicates Key:true, success: function(res) {console.log ('Android 검색 성공'), console.log (res);,fail: function(err) {console.log(err), wx.hideLoading(), that.startBluetoothDevicesDiscovery(),//that.getBluettoothAdapterState(), util.showToast('검색 실패'),}
}, startConnectDevices: function (ltype, array) { var that = this; clearTimeout(that.getConnectedTimer); that.getConnectedTimer = null; wx.stopBluetoothDevicesDiscovery({ success: function (res) {//success } }) app.globalData.ble_isonnectting = true; console.log('연결 전:'+that.deviceId);wx.createBLEconnection ({deviceId: that.deviceId, success: function(res) {if(res.errCode==0) {console.log ('접속 성공:'), that.get Service (that.deviceId);},fail: function(err) {console.log('연결 실패:', err), wx.hideLoading(), util.showModal('장치 연결 실패, 다시 시도합니다'),//if(ltype='loop') {//that.hidededededeLoading(): hidededededededeLoading(); util.showwModal.showModal('장치 연결 실패, 다시 시도해 보십시오');//////////('연결 실패:'연결 실패:'연결 실패:''연결 실패:'''''''연결 실패:':'loop')) {//wxxxwx.hithx.hidededevi} app.globalData.ble_isonnectting = false; }, complete: function () { } }); }, getService: function(deviceId) {var that = this;//Bluetooth 연결 wx.onBLEconnection StateChange(function(res) {console.log(res), app.global Data.ble isonnectting = res.connected if(!res.connected) {util.showToast('연결 끊기')));//블루투스 장치 서비스 값 wx를 가져옵니다.getBLEDevice 서비스({deviceId: deviceId, success: function(res) {console.log('블루투스 장치 서비스 값 가져오기'), console.log(res), that.getCharacter(deviceId,res.services),}),getCharacter: function (deviceId, services) { var that = this; services.forEach(function (value, index, array) { if (value.isPrimary) { that.setData({ service_uuid: value.uuid, deviceId: deviceId }) app.globalData.service_uuid= value.uuid; app.globalData.deviceId=deviceId; } });//감청 통지 wx.BLECharacteristicValueChange(function(res) {//callback console.log('value change'·res) consthex = bletool.bufchar(res.value)console.log('되돌아오는 데이터:', hex)/배합 암호if(hex.indexOf('8558000000106')!==-1) {wwbuffffff2char(w) consolbalbalbalback consolback console.log console.log('·re)///////'valballactalballact consosososolack consosososo(that.data.deviceId, that.data.service_uuid, charact_write, that.data.service_psd); wx.Toast({title:'장치가 연결되었음', icon:'success', duration: 3000}) setTimeout(function) {bletool. write DataToDevice(that.data.deviceId,that.data.service uuid,charact write,'235525B837205590400000273');2000) } else if (hex.indexOf('23040000') != -1) {//부팅 성공that.starRenting();}wx.getBLEDeviceCharacteristics({deviceId: deviceId, 서비스Id: that.getServiceUUID(), success: function(res) {wx.getBLEDeviceCharacteristics({deviceId: deviceId, 서비스Id: that.getServiceUID(), success: function(res) {console.log('특징', res) Datathaterices({stices:charices:acterices.scharterics).globalData.characteristics = res.characteristics; var charact_read = res.characteristics[0]
        wx.notifyBLECharacteristicValueChange({
          state: true, //   notify  
          deviceId: deviceId,
          serviceId: that.getServiceUUID(),
          characteristicId: charact_read.uuid,
          success: function (res) {
            console.log('notifyBLECharacteristicValueChange success', res.errMsg)
          }
        })
        wx.readBLECharacteristicValue({
          deviceId: deviceId,
          serviceId: that.getServiceUUID(),
          characteristicId: charact_read.uuid,
          success: function (res) {
            console.log('readBLECharacteristicValue:', res)
          }
        })

      },

    })
  },
  fail: function (err) {
    console.log(err);
  },
  complete: function () {
    console.log('complete');
  }
})

}, loopConnect: function (devicesId) { var that = this; var listLen = devicesId.length; if (devicesId[this.connectDeviceIndex]) { this.deviceId = devicesId[this.connectDeviceIndex]; this.startConnectDevices('loop', devicesId); } else {console.log('짝을 이룬 장치 애플릿 블루투스 연결 실패'), that.startBluetoothDevices Discovery(), that.getConnectedBluetoothDevices(),},//데이터 업데이트 장치는 배열 유형으로 업데이트되어 BleList: function(devices) {console.log('장치 데이터:', devices), var new Data = this.data.bleList: function(devices) {console.log('장치 데이터:''''',devices), var new Davices), var new Data = var nevices = var =, devices), var 데이터 = var nevices 데이터:'<<, devices)), var var var var nevices), var var:'s =', devices; i++ i+ i++ i++ i++ i+ i+ i+ i+.devices[0];}else {continue}//안드로이드 {tempDevice = devices [i];}if (!this.isExist(tempDevice)) { newData.push(tempDevice) } } console.log('데이터:');console.log(newData) this.set Data({ble List: new Data}) if(! app.global Data.ble Data.ble Data.ble It) if(! app.blobal Data.ble ble Data.ble ble ble Data.ble ble ble ble able ble able ble able ble able ble ble ble able ble ble ble ble ble ble ble ble ble able Data.ble ble ble ble ble ble ble ble ble ble ble ble ble ble abla(advertis ServiceUUID = that.data.service Id.toUpperCase(){ that.deviceId = deviceId; console.log(that.deviceId); that.startConnectDevices(); } }else{ if (deviceId == that.data.serviceMac) { that.deviceId = deviceId; console.log(that.deviceId); that.startConnectDevices(); } } }); } },//true를 반환하지 않으면 false isExist: function(device) {var tempData = this.data.bleList for(var i = 0; tempData.length; i+) {if(tempData[i].deviceId = device.deviviceId.deviceId) {return true} 0 = 0 = 0 0 0 0;;;;;;;;;;;;;;; t retureturetureturetureturet an false} palse e} false}} false} false} {false e e e e e e e e e e e e e e e e,get Device Info: function() {let car no = app.globaData.car no; var that = this; wx.request({url: app.globabababababababababababababalata.serverururururr+'?c=car&car&a=a==car&a===a==agaggetDeviceInfo&amp&o&opopopopen id========'vat that===='vat that = vat = vat that =that = that = that = that = that = that = that:'application/json'},//요청한 header success:function(res) 설정{//success var data = res.data; console.log(data); if (data.result == 1) { app.globalData.serviceId = data.data.service_id; app.globalData.serviceMac = data.data.service_mac, app.globalData.service_psd = '85' + data.data.service_psd + '5800000329'; that.setData({ serviceId: data.data.service_id, serviceMac: data.data.service_mac, service_psd: '85' + data.data.service_psd+'5800000329', }) app.startBluetoothDevicesDiscovery();//that.onBLECharacteristicValueChange(); } else { util.showModal(data.msg); } }, fail: function () { }, complete: function () {//complete } }); }, })

좋은 웹페이지 즐겨찾기