[转]微信小程序--Ble蓝牙

在前面已经写了两篇关于Android蓝牙和iOS 蓝牙开发的文章,今天带来的是微信小程序蓝牙实现。
Android蓝牙
ios蓝牙(Swift)

有一段时间没有。没有写关于小程序的文章了。3月28日,微信的api又一次新的更新。期待已久的蓝牙api更新。就开始撸一番。
源码地址

1.简述

蓝牙适配器接口是基础库版本 1.1.0 开始支持。
iOS 微信客户端 6.5.6 版本开始支持,Android 客户端暂不支持
蓝牙总共增加了18个api接口。

2.Api分类

搜索类
连接类
通信类

3.API的具体使用

详细见官网:
https://mp.weixin.qq.com/debug/wxadoc/dev/api/bluetooth.html#wxgetconnectedbluethoothdevicesobject

4. 案例实现

4.1 搜索蓝牙设备

/**
 * 搜索设备界面
 */
Page({
  data: {
    logs: [],
    list:[],
  },
   onLoad: function () {
    console.log('onLoad')
var that = this;
// const SDKVersion = wx.getSystemInfoSync().SDKVersion || '1.0.0'
// const [MAJOR, MINOR, PATCH] = SDKVersion.split('.').map(Number)
// console.log(SDKVersion);
// console.log(MAJOR);
// console.log(MINOR);
// console.log(PATCH);

// const canIUse = apiName => {
//   if (apiName === 'showModal.cancel') {
//     return MAJOR >= 1 && MINOR >= 1
//   }
//   return true
// }

// wx.showModal({
//   success: function(res) {
//     if (canIUse('showModal.cancel')) {
//       console.log(res.cancel)
//     }
//   }
// })
      wx.openBluetoothAdapter({
      success: function(res){
        // success
        console.log("-----success----------");
         console.log(res);
       wx.startBluetoothDevicesDiscovery({
  services: [],
  success: function(res){
    // success
     console.log("-----startBluetoothDevicesDiscovery--success----------");
     console.log(res);
  },
  fail: function(res) {
    // fail
     console.log(res);
  },
  complete: function(res) {
    // complete
     console.log(res);
  }
})


      },
      fail: function(res) {
         console.log("-----fail----------");
        // fail
         console.log(res);
      },
      complete: function(res) {
        // complete
         console.log("-----complete----------");
         console.log(res);
      }
    })

     wx.getBluetoothDevices({
       success: function(res){
         // success
         //{devices: Array[11], errMsg: "getBluetoothDevices:ok"}
         console.log("getBluetoothDevices");
         console.log(res);
          that.setData({
          list:res.devices
          });
          console.log(that.data.list);
       },
       fail: function(res) {
         // fail
       },
       complete: function(res) {
         // complete
       }
     })

  },
  onShow:function(){
 

  },
   //点击事件处理
  bindViewTap: function(e) {
     console.log(e.currentTarget.dataset.title);
     console.log(e.currentTarget.dataset.name);
     console.log(e.currentTarget.dataset.advertisData);
     
    var title =  e.currentTarget.dataset.title;
    var name = e.currentTarget.dataset.name;
     wx.redirectTo({
       url: '../conn/conn?deviceId='+title+'&name='+name,
       success: function(res){
         // success
       },
       fail: function(res) {
         // fail
       },
       complete: function(res) {
         // complete
       }
     })
  },

   

})

4.2连接 获取数据

/**
 * 连接设备。获取数据
 */
Page({
    data: {
        motto: 'Hello World',
        userInfo: {},
        deviceId: '',
        name: '',
        serviceId: '',
        services: [],
        cd20: '',
        cd01: '',
        cd02: '',
        cd03: '',
        cd04: '',
        characteristics20: null,
        characteristics01: null,
        characteristics02: null,
        characteristics03: null,
        characteristics04: null,
        result: result

    },
    onLoad: function onLoad(opt) {
        var that = this;
        console.log("onLoad");
        console.log('deviceId=' + opt.deviceId);
        console.log('name=' + opt.name);
        that.setData({ deviceId: opt.deviceId });
        /**
         * 监听设备的连接状态
         */
        wx.onBLEConnectionStateChanged(function (res) {
            console.log('device ' + res.deviceId + ' state has changed, connected: ' + res.connected);
        });
        /**
         * 连接设备
         */
        wx.createBLEConnection({
            deviceId: that.data.deviceId,
            success: function success(res) {
                // success
                console.log(res);
                /**
                 * 连接成功,后开始获取设备的服务列表
                 */
                wx.getBLEDeviceServices({
                    // 这里的 deviceId 需要在上面的 getBluetoothDevices中获取
                    deviceId: that.data.deviceId,
                    success: function success(res) {
                        console.log('device services:', res.services);
                        that.setData({ services: res.services });
                        console.log('device services:', that.data.services[1].uuid);
                        that.setData({ serviceId: that.data.services[1].uuid });
                        console.log('--------------------------------------');
                        console.log('device设备的id:', that.data.deviceId);
                        console.log('device设备的服务id:', that.data.serviceId);
                        /**
                         * 延迟3秒,根据服务获取特征 
                         */
                        setTimeout(function () {
                            wx.getBLEDeviceCharacteristics({
                                // 这里的 deviceId 需要在上面的 getBluetoothDevices
                                deviceId: that.data.deviceId,
                                // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
                                serviceId: that.data.serviceId,
                                success: function success(res) {
                                    console.log('000000000000' + that.data.serviceId);
                                    console.log('device getBLEDeviceCharacteristics:', res.characteristics);
                                    for (var i = 0; i < 5; i++) {
                                        if (res.characteristics[i].uuid.indexOf("ffe1") != -1) {
                                            that.setData({
                                                cd20: res.characteristics[i].uuid,
                                                characteristics20: res.characteristics[i]
                                            });
                                        }
                                        if (res.characteristics[i].uuid.indexOf("ffe2") != -1) {
                                            that.setData({
                                                cd01: res.characteristics[i].uuid,
                                                characteristics01: res.characteristics[i]
                                            });
                                        }
                                        if (res.characteristics[i].uuid.indexOf("fec8") != -1) {
                                            that.setData({
                                                cd02: res.characteristics[i].uuid,
                                                characteristics02: res.characteristics[i]
                                            });
                                        }if (res.characteristics[i].uuid.indexOf("fec7") != -1) {
                                            that.setData({
                                                cd03: res.characteristics[i].uuid,
                                                characteristics03: res.characteristics[i]
                                            });
                                        }
                                        if (res.characteristics[i].uuid.indexOf("fec9") != -1) {
                                            that.setData({
                                                cd04: res.characteristics[i].uuid,
                                                characteristics04: res.characteristics[i]
                                            });
                                        }
                                    }
                                    console.log('cd01= ' + that.data.cd01 + 'cd02= ' + that.data.cd02 + 'cd03= ' + that.data.cd03 + 'cd04= ' + that.data.cd04 + 'cd20= ' + that.data.cd20);
                                    /**
                                     * 回调获取 设备发过来的数据
                                     */
                                    wx.onBLECharacteristicValueChange(function (characteristic) {
                                        console.log('characteristic value comed:', characteristic.value);
                                        //{value: ArrayBuffer, deviceId: "D8:00:D2:4F:24:17", serviceId: "ba11f08c-5f14-0b0d-1080-007cbe238851-0x600000460240", characteristicId: "0000cd04-0000-1000-8000-00805f9b34fb-0x60800069fb80"}
                                        /**
                                         * 监听cd04cd04中的结果
                                         */
                                        if (characteristic.characteristicId.indexOf("cd01") != -1) {
                                            var _result = characteristic.value;
                                            var hex = that.buf2hex(_result);
                                            console.log(hex);
                                        }
                                        if (characteristic.characteristicId.indexOf("cd04") != -1) {
                                            var _result2 = characteristic.value;
                                            var _hex = that.buf2hex(_result2);
                                            console.log(_hex);
                                            that.setData({ result: _hex });
                                        }
                                    });
                                    /**
                                     * 顺序开发设备特征notifiy
                                     */
                                    wx.notifyBLECharacteristicValueChanged({
                                        deviceId: that.data.deviceId,
                                        serviceId: that.data.serviceId,
                                        characteristicId: that.data.cd01,
                                        state: true,
                                        success: function success(res) {
                                            // success
                                            console.log('notifyBLECharacteristicValueChanged success', res);
                                        },
                                        fail: function fail(res) {
                                            // fail
                                        },
                                        complete: function complete(res) {
                                            // complete
                                        }
                                    });
                                    wx.notifyBLECharacteristicValueChanged({
                                        deviceId: that.data.deviceId,
                                        serviceId: that.data.serviceId,
                                        characteristicId: that.data.cd02,
                                        state: true,
                                        success: function success(res) {
                                            // success
                                            console.log('notifyBLECharacteristicValueChanged success', res);
                                        },
                                        fail: function fail(res) {
                                            // fail
                                        },
                                        complete: function complete(res) {
                                            // complete
                                        }
                                    });
                                    wx.notifyBLECharacteristicValueChanged({
                                        deviceId: that.data.deviceId,
                                        serviceId: that.data.serviceId,
                                        characteristicId: that.data.cd03,
                                        state: true,
                                        success: function success(res) {
                                            // success
                                            console.log('notifyBLECharacteristicValueChanged success', res);
                                        },
                                        fail: function fail(res) {
                                            // fail
                                        },
                                        complete: function complete(res) {
                                            // complete
                                        }
                                    });

                                    wx.notifyBLECharacteristicValueChanged({
                                        // 启用 notify 功能
                                        // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
                                        deviceId: that.data.deviceId,
                                        serviceId: that.data.serviceId,
                                        characteristicId: that.data.cd04,
                                        state: true,
                                        success: function success(res) {
                                            console.log('notifyBLECharacteristicValueChanged success', res);
                                        }
                                    });
                                }, fail: function fail(res) {
                                    console.log(res);
                                }
                            });
                        }, 1500);
                    }
                });
            },
            fail: function fail(res) {
                // fail
            },
            complete: function complete(res) {
                // complete
            }
        });
    },

    /**
     * 发送 数据到设备中
     */
    bindViewTap: function bindViewTap() {
        var that = this;
        //var hex = 'AA5504B10000B5'
        // var hex = '7e7e12000e02000000010000000501090000009922aa'//close power off
        var hex = '7e7e12000e0200000001000000050009000000591faa'; //open power off
        var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {
            return parseInt(h, 16);
        }));
        console.log(typedArray);
        console.log([0xAA, 0x55, 0x04, 0xB1, 0x00, 0x00, 0xB5]);
        var buffer1 = typedArray.buffer;
        console.log(buffer1);
        wx.writeBLECharacteristicValue({
            deviceId: that.data.deviceId,
            serviceId: that.data.serviceId,
            characteristicId: that.data.cd20,
            value: buffer1,
            success: function success(res) {
                // success
                console.log("success  指令发送成功");
                console.log(res);
            },
            fail: function fail(res) {
                // fail
                console.log(res);
            },
            complete: function complete(res) {
                // complete
            }
        });
    },
    buf2hex: function buf2hex(buffer) {
        // buffer is an ArrayBuffer
        return Array.prototype.map.call(new Uint8Array(buffer), function (x) {
            return ('00' + x.toString(16)).slice(-2);
        }).join('');
    }
});

5.效果展示

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

推荐阅读更多精彩内容