微信小程序蓝牙模块开发

//index.js
//获取应用实例

const app = getApp()
const util = require('../../utils/util.js')
const bletool = require('../../utils/bletool.js')

Page({
data: {
// lists: [{ 'order_no': '1111', 'car_no': '321', 'car_type': '尚好捷', 'order_date': '2018-01-02 08:00', 'order_money': '16.00', 'order_time': '4' }],
car_no: '',
order_no: '',
lists: [],
bleList: [], //蓝牙设备数组
serviceId: '',//592B3370-3900-9A71-4535-35D4212D2837
serviceMac: '',//C9:9B:4C:E7:DE:10
service_psd: '',//855525B837253705595800000329
service_uuid: '',
deviceId:'',
characteristics:[] //特征值
},
onLoad: function (options) {
this.initBle();
},
onReady: function () {
// 页面渲染完成
},
onShow: function () {
if (app.globalData.car_no.length>0){
this.getDeviceInfo();
}
},
onHide: function () {
// 页面隐藏
},
onUnload: function () {
// 页面关闭
app.globalData.car_no=''
},
//蓝牙相关
//初始化蓝牙
initBle: function () {
var that = this;
wx.onBluetoothAdapterStateChange(function (res) {
console.log('adapterState changed, now is', res)
app.globalData.ble_state = res.available;
if (res.available) {
that.initBle();
} else {
util.showToast('手机蓝牙已关闭');
app.globalData.ble_isonnectting = false;
}
})
//打开蓝牙适配器
wx.openBluetoothAdapter({
success: function (res) {
console.log('打开蓝牙适配器成功');
that.getBluetoothAdapterState();
app.globalData.ble_state = true;
that.onBluetoothDeviceFound();
},
fail: function (res) {
// fail
console.log(res)
util.showToast('请打开手机蓝牙');
},
complete: function (res) {
// complete
}
})
},
onBluetoothDeviceFound:function(){
var that = this;
//监听扫描
wx.onBluetoothDeviceFound(function (res) {
// res电脑模拟器返回的为数组;手机返回的为蓝牙设备对象
console.log('监听搜索新设备:', res);
that.updateBleList([res])
})
},
getBluetoothAdapterState: function () {
var that = this;
wx.getBluetoothAdapterState({
success: function (res) {
var available = res.available;
var discovering = res.discovering;
if (!available) {
util.showToast('蓝牙不可用');
} else {
if (!discovering) {
// that.startBluetoothDevicesDiscovery();
}
}
}
})
},
startBluetoothDevicesDiscovery: function () {
var that = this;
var services = [];
services.push(this.data.serviceId);
wx.showLoading({
title: '设备搜索中'
});
setTimeout(function () {
wx.hideLoading();
if (app.globalData.deviceId.length==0){
util.showModal('设备搜索失败,请重试');
}
}, 10000)
if(bletool.isIOS()){
wx.startBluetoothDevicesDiscovery({
services: services,
allowDuplicatesKey: true,
success: function (res) {
console.log('ios搜索成功');
console.log(res);
},
fail: function (err) {
console.log(err);
}
});
}else{
wx.startBluetoothDevicesDiscovery({
// services: services,
allowDuplicatesKey: true,
success: function (res) {
console.log('Android搜索成功');
console.log(res);
},
fail: function (err) {
console.log(err);
wx.hideLoading();
that.startBluetoothDevicesDiscovery();
// that.getBluetoothAdapterState();
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.getService(that.deviceId);
}
},
fail: function (err) {
console.log('连接失败:', err);
wx.hideLoading();
util.showModal('设备连接失败,请重试');
// if (ltype == 'loop') {
// that.connectDeviceIndex += 1;
// that.loopConnect(array);
// } else {
// that.startBluetoothDevicesDiscovery();
// that.getConnectedBluetoothDevices();
// }
app.globalData.ble_isonnectting = false;
},
complete: function () {
}
});
},
getService: function (deviceId) {
var that = this;
// 监听蓝牙连接
wx.onBLEConnectionStateChange(function (res) {
console.log(res);
app.globalData.ble_isonnectting = res.connected
if (!res.connected) {
util.showToast('连接断开');
}
});
// 获取蓝牙设备service值
wx.getBLEDeviceServices({
deviceId: deviceId,
success: function (res) {
console.log('获取蓝牙设备service值');
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.onBLECharacteristicValueChange(function (res) {
// callback
console.log('value change', res)
const hex = bletool.buf2char(res.value)
console.log('返回的数据:', hex)
//配对密码
if (hex.indexOf('855800000106') != -1) {
wx.hideLoading();
var charact_write = that.data.characteristics[1]
bletool.writeDataToDevice(that.data.deviceId, that.data.service_uuid, charact_write, that.data.service_psd);
wx.showToast({
title: '设备已连接',
icon: 'success',
duration: 3000
})
setTimeout(function () {
bletool.writeDataToDevice(that.data.deviceId, that.data.service_uuid, charact_write, '235525B837253705590400000273');
}, 2000)
} else if (hex.indexOf('23040000') != -1) {
//启动成功
that.starRenting();
}
})
wx.getBLEDeviceCharacteristics({
deviceId: deviceId,
serviceId: that.getServiceUUID(),
success: function (res) {
wx.getBLEDeviceCharacteristics({
deviceId: deviceId,
serviceId: that.getServiceUUID(),
success: function (res) {
console.log('特征', res)
that.setData({
characteristics:res.characteristics
})
app.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.startBluetoothDevicesDiscovery();
that.getConnectedBluetoothDevices();
}
},
//更新数据 devices为数组类型
updateBleList: function (devices) {
console.log('设备数据:',devices);
var newData = this.data.bleList
var that = this
var tempDevice = null;
for (var i = 0; i < devices.length; i++) {
//ios设备
if (devices[i].devices != null) {
if (devices[i].devices.length > 0) {
tempDevice = devices[i].devices[0];
}
else {
continue
}
}
//安卓
else {
tempDevice = devices[i];
}
if (!this.isExist(tempDevice)) {
newData.push(tempDevice)
}
}
console.log('数据:');
console.log(newData)
this.setData({
bleList: newData
})
if (!app.globalData.ble_isonnectting) {
var that = this;
this.data.bleList.forEach(function (value, index, array) {
//找到对应id的设备,ios判断服务id安卓判断mac地址
var deviceId = value['deviceId'];
if(bletool.isIOS()){
let advertisServiceUUID = value['advertisServiceUUIDs'][0];
if (advertisServiceUUID == that.data.serviceId.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; i < tempData.length; i++) {
if (tempData[i].deviceId == device.deviceId) {
return true
}
}
return false
},
//服务uuid
getServiceUUID: function () {
return bletool.stringTransition(this.data.service_uuid);
},
getDeviceInfo: function () {
let car_no = app.globalData.car_no;
var that = this;
wx.request({
url: app.globalData.serverURL + '?c=car&a=getDeviceInfo&open_id=' + app.globalData.open_id + '&car_no=' + car_no,
method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
header: { 'content-type': '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
}
});
},
})

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

推荐阅读更多精彩内容