微信小程序连接蓝牙设备控制智能小车

Page({

    data: {

        discoverFlag: false,

        devices: [],

        deviceId: '',

        serviceId: '',

        services: [],

        showFlage: true,

        name: '',

        characteristics: [],

        characteristicId: '',

        showFlage1: false,

        showFlage2: false,

        available: false,

        read: false,

        write: false,

        showKeyboard: false,

        inputKey: true,

        showData: '',

        sliderValue: 1, // 初始值为一档

    },

    sliderChange: function(e) {  

        this.setData({  

          sliderValue: e.detail.value  

        })  

      },

    onLoad: function (options) {

        wx.openBluetoothAdapter({

            success(res) {

                console.log(res)

            }

        })

    },

    onShow: function () {

        let that = this

        wx.getBluetoothAdapterState({

            success(res) {

                console.log(res)

                if (res.available) {

                    that.setData({

                        available: true

                    })

                } else {

                    that.setData({

                        available: false

                    })

                    wx.showToast({

                        title: '请打开蓝牙',

                    })

                }

            }

        })

        wx.openBluetoothAdapter({

            success(res) {

                console.log(res)

            }

        })

    },

    discoverDevices() {

        let that = this

        wx.startBluetoothDevicesDiscovery({

            services: [],

            success(res) {

                console.log(res)

                that.setData({

                    discoverFlag: res.isDiscovering

                })

            }

        })

    },

    getDevices() {

        let that = this

        wx.startBluetoothDevicesDiscovery({

            services: [],

            success(res) {

                console.log(res)

                function ab2hex(buffer) {

                    var hexArr = Array.prototype.map.call(

                        new Uint8Array(buffer),

                        function (bit) {

                            return ('00' + bit.toString(16)).slice(-2)

                        }

                    )

                    return hexArr.join('');

                }

                wx.onBluetoothDeviceFound(function (res) {

                    var devices = res.devices;

                    console.log('new device list has founded')

                    console.log(devices)

                    console.log(ab2hex(devices[0].advertisData))

                })

                wx.getBluetoothDevices({

                    success: function (res) {

                        console.log(res)

                        that.setData({

                            devices: res.devices

                        })

                    }

                })

                if (that.data.devices.length >= 4) {

                    wx.stopBluetoothDevicesDiscovery({

                        success(res) {

                            console.log(res)

                        }

                    })

                }

            }

        })

    },

    create(e) {

        let that = this

        console.log(e)

        let index = e.currentTarget.dataset.index

        wx.getBluetoothAdapterState({

            success(res) {

                console.log(res)

                if (res.available) {

                    wx: wx.showToast({

                        title: '蓝牙有打开',

                    })

                }

            }

        })

        wx.createBLEConnection({

            deviceId: that.data.devices[index].deviceId,

            wx: wx.showLoading({

                title: '连接中',

            }),

            success(res) {

                console.log(res)

                that.setData({

                    deviceId: that.data.devices[index].deviceId,

                    name: that.data.devices[index].name,

                    showFlage: false,

                    showFlage1: true,


 

                })

                wx.getBLEDeviceServices({

                    // 这里的 deviceId 需要已经通过 wx.createBLEConnection 与对应设备建立连接

                    deviceId: that.data.deviceId,

                    success(res) {

                        console.log('device services:', res.services)

                        that.setData({

                            services: res.services

                        })

                    }

                })

            }

        })

    },

    choise(e) {

        console.log(e)

        let that = this

        let index = e.currentTarget.dataset.index

        let serviceId = this.data.services[index].uuid

        this.setData({

            serviceId: serviceId

        })

        wx.getBLEDeviceCharacteristics({

            // 这里的 deviceId 需要已经通过 wx.createBLEConnection 与对应设备建立链接

            deviceId: this.data.deviceId,

            // 这里的 serviceId 需要在 wx.getBLEDeviceServices 接口中获取

            serviceId: this.data.serviceId,

            success(res) {

                console.log('device getBLEDeviceCharacteristics:', res.characteristics)

                that.setData({

                    characteristics: res.characteristics,

                    showFlage2: true,

                    showFlage1: false,

                })

            }

        })

    },

    disconnect() {

        let that = this

        wx.closeBLEConnection({

            deviceId: this.data.deviceId,

            success(res) {

                console.log(res)

                that.setData({

                    showFlage: true,

                    showFlage1: false,

                    showFlage2: false,

                    inputKey: true,

                })

            }

        })

    },

    select(e) {

        let that=this

        console.log(e)

        let index = e.currentTarget.dataset.index

        let characteristicId = this.data.characteristics[index].uuid

        this.setData({

            characteristicId: characteristicId,

            showKeyboard: true,

            inputKey: false,

        })

        wx.notifyBLECharacteristicValueChange({

            characteristicId: this.data.characteristicId,

            deviceId: this.data.deviceId,

            serviceId: this.data.serviceId,

            state: true,

            success(res) {

                console.log('notifyBLECharacteristicValueChange success', res.errMsg)

            }

        })

    },

    // 前进  

  onForward() {  

    this.sendBLECommand([0x20,0x81,0x81,0xC1,0x92,0x80,0x80,0x80,0x80,0xF5]); // 假设0x01代表前进  

  },  

  

  // 后退  

  onBackward() {  

    this.sendBLECommand([0x20,0x81,0x81,0xC5,0x92,0x80,0x80,0x80,0x80,0xF9]); // 假设0x02代表后退  

  },  

  

  // 停止  

  onStop() {  

    this.sendBLECommand([0x20,0x81,0x81,0xDA,0x92,0x80,0x80,0x80,0x80,0x8E]); // 假设0x03代表停止  

  },  

  

  // 左转  

  onTurnLeft() {  

    this.sendBLECommand([0x20,0x81,0x81,0xC7,0x92,0x80,0x80,0x80,0x80,0xFB]); // 假设0x04代表左转  

  },  

  

  // 右转  

  onTurnRight() {  

    this.sendBLECommand([0x20,0x81,0x81,0xC3,0x92,0x80,0x80,0x80,0x80,0xF7]); // 假设0x05代表右转  

  },

  sendBLECommand(commandBytes) {   

    // 构建完整的数据数组,包括校验位和尾随字节(如果需要的话)  

    // 假设尾随字节已经包含在commandBytes中,这里只添加校验位  

    //const dataArray = new Uint8Array([...commandBytes, checksum]);  

  const dataArray=new Uint8Array([...commandBytes]);

   // 打印dataArray的内容,而不是buffer  

   console.log('Sending data:', [...dataArray].map(byte => byte.toString(16).padStart(2, '0')).join(' '));

        wx.writeBLECharacteristicValue({

            deviceId: this.data.deviceId,

            serviceId: this.data.serviceId,

            characteristicId: this.data.characteristicId,

            value: dataArray.buffer,

            success(res) {

                console.log('writeBLECharacteristicValue success', res.errMsg);

                console.log(dataArray.buffer)

                wx.showToast({

                    title: '发送成功',

                });

            },

            fail(res) {

                console.error('writeBLECharacteristicValue fail', res.errMsg); // 打印失败原因  

                wx.showToast({

                    title: '发送失败',

                });

            }

        });

    },

})

  • 25
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值