ESP32与手机蓝牙通信(uniapp)

在网上找了很久都找不到直接可以用的,对新手来说苦啊!!!主要是收发数据,网上的资料都用不了(鸿蒙系统),现在解决了,希望新手少走弯路。

<template>
	<view class="content">
		<view class="text-area">
			<button @click="readBLECharacteristicValue">读取数据</button>
			<button @click="writeBLECharacteristicValue('hfk中g')">发送数据</button>
			<button @click="Search">搜索蓝牙</button>
			<!--  <button @click="goto1">控制风扇</button> -->
		</view>
		<scroll-view scroll-y class="box">
			<view class="item" v-for="item in devicesList">
				<view>
					<text>id:{{item.deviceId}}</text>
				</view>
				<view>
					<text>name:{{item.name}}</text>
					<button @click="ConnectByID(item)">连接</button>
				</view>

			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				title: 'Hello',
				deviceId: '',
				serviceId: '',
				characteristicId: '',
				connectedDeviceId: '',
				devicesList: [],

			}
		},

		methods: {
			Search() {
				var that = this;
				//console.log("search:", that.searching);
				if (!that.searching) {
					//关闭现有的蓝牙连接
					uni.closeBluetoothAdapter({
						complete: function(res) {
							console.log("关闭蓝牙模块-----------------------------------------");
							console.log(res);
							//打开蓝牙适配
							uni.openBluetoothAdapter({
								success: function(res) {
									console.log(
										"初始化蓝牙模块----------------------------------------"
									);
									console.log(res);
									uni.getBluetoothAdapterState({
										success: function(res) {
											console.log(
												"获取本机蓝牙适配器状态----------------------------------------"
											);
											console.log(res);
										},
									});

									//开始搜索蓝牙设备
									uni.startBluetoothDevicesDiscovery({
										allowDuplicatesKey: false,
										success: function(res) {
											console.log(
												"搜索设备-----------------------------------------"
											);
											that.onBluetoothDeviceFound();
											that.searching = true;
											that.devicesList = [];
										},
									});
								},
								fail: function(res) {
									console.log("############");
									console.log(res);
									setTimeout(() => {
										uni.showModal({
											title: "温馨提示",
											content: "蓝牙未打开,请打开后再连接",
											showCancel: false,
											confirmColor: "#008fd6",
										});
										that.isSearch = false;
									}, 1000);
								},
							});
						},
					});
				} else {
					uni.stopBluetoothDevicesDiscovery({
						success: function(res) {
							console.log("停止搜索设备-----------------------------------------");
							console.log(res);
							that.searching = false;
						},
					});
				}
			},
			ConnectByID(item) {
				var that = this;
				console.log(item);
				that.connectedDeviceId = item.deviceId;
				uni.setStorageSync('pageName', item.name);
				uni.setStorageSync('connectedDeviceId', that.connectedDeviceId);
				uni.showLoading({
					title: '正在连接设备...',
				});

				uni.createBLEConnection({
					deviceId: item.deviceId,
					success(res) {
						uni.hideLoading()
						uni.showToast({
							title: '连接成功',
							duration: 2000,
							icon: "none"
						});
						// that.open()
						console.log("已连接设备----------------------------------------");
						that.getBLEDeviceServices(); //获取特征值

					},
					fail(res) {
						console.log(res)
						uni.hideLoading()
						uni.showModal({
							title: '提示',
							content: '连接失败',
							showCancel: false
						})
					}
				})
				// }
			},
			//获取蓝牙设备的服务uuid    //服务uuid可能有多个
			getBLEDeviceServices() {
				var that = this;
				setTimeout(() => {
					//获取数据可能会有延迟
					uni.getBLEDeviceServices({
						deviceId: that.connectedDeviceId,
						success: function(res) {
							console.log(
								"获取蓝牙设备的服务uuid:" + JSON.stringify(res.services)
							);
							that.services = res.services;
							that.serviceId = res.services[2].uuid;
							that.deviceId = that.connectedDeviceId;
							uni.setStorageSync("serviceId", that.serviceId);
							that.getBLEDeviceCharacteristics();
						},
						fail(res) {
							console.log(res);
						},
					});
				}, 1000);
			},
			// 根据服务uuid获取蓝牙特征值开始监听写入和接收
			getBLEDeviceCharacteristics() {
				let that = this;
				uni.getBLEDeviceCharacteristics({
					deviceId: that.connectedDeviceId,
					serviceId: that.serviceId,
					success: function(res) {
						console.log(
							"获取蓝牙设备的特征" + JSON.stringify(res.characteristics)
						);
						for (var i = 0; i < res.characteristics.length; i++) {
							if (res.characteristics[i].properties.notify === true) {
								that.characteristics = res.characteristics[i];
								that.characteristicId = res.characteristics[i].uuid;
							}

							if (res.characteristics[i].properties.write === true) {
								that.characteristics = res.characteristics[i];
								that.writeId = res.characteristics[i].uuid;
							}
						}
						uni.setStorageSync("characteristicId", that.characteristicId);
						uni.setStorageSync("writeId", that.writeId);
						that.notifyBLECharacteristicValueChange(); //7.0,开始侦听数据
					},
				});
			},



			notifyBLECharacteristicValueChange() {
				var that = this;
				uni.notifyBLECharacteristicValueChange({
					
					state: true,
					deviceId: that.deviceId,
					serviceId: that.serviceId,
					characteristicId: that.characteristicId,

					success: function(res) {
						console.log("启用notify成功");
						that.onBLECharacteristicValueChange();
					},
					fail: function(res) {
						console.log("启用notify失败");
					},
				});
			},
			ab2hex(buffer) {
			  const hexArr = Array.prototype.map.call(
			    new Uint8Array(buffer),
			    function (bit) {
			      return ('00' + bit.toString(16)).slice(-2)
			    }
			  )
			  return '%' + hexArr.join('%')
			},
			//设备返回数据的接收
			onBLECharacteristicValueChange() {
				var that = this;
				console.log("开启数据监听");
				uni.onBLECharacteristicValueChange((res) => {
					// 此时可以拿到蓝牙设备返回来的数据是一个ArrayBuffer类型数据,所以需要通过这个方法转换成字符串
				//var resHex = that.ab2hex(res.value);
				console.log("处理数据1:" + (Buffer)(res.value));  //重点在这里直接 (Buffer)就可以用了。网上还要转码。
				//console.log("处理数据2:" + decodeURIComponent(resHex));
				});
			},

			//监听寻找到新设备的事件
			//平时有数据来也没反应,执行一次readBLECharacteristicValue才反应一次
			onBluetoothDeviceFound() {
				var that = this;
				console.log("打开设备监听");
				uni.onBluetoothDeviceFound(function(devices) {
					var reg = new RegExp(/[^\s]+/g);
					if (devices.devices) {
						if (devices.devices[0].name.match(reg)) {
							console.log(devices.devices[0]);
							if (devices.devices[0].name.indexOf("ESP32") >= 0) {
								
								//在app显示
								that.devicesList.push(devices.devices[0]);
								console.log("发现ESP32");
								//连接蓝牙设备
								setTimeout(ConnectByID(devices.devices[0]),1000);
							}
						}
					}
				});
			},
			onBLEConnectionStateChange() {
				var that = this;
				uni.onBLEConnectionStateChange(function(res) {
					that.connected = res.connected;
					if (!that.connected) {
						console.log("蓝牙已断开");
						uni.createBLEConnection({
							// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
							deviceId: that.connectedDeviceId,
							success(res) {
								that.getBLEDeviceServices();
								//获取该设备地址
								console.log("蓝牙重新连接" + JSON.stringify(res));
							},
							fail(res) {
								console.log("蓝牙重新连接失败" + JSON.stringify(res));
							},
						});
					} else {
						console.log("蓝牙连接成功");
					}
				});
			},
			// 读取设备二进制数据
			//其实这里并不能得到数据,坑啊!!!!!
			readBLECharacteristicValue() {
				let _this = this;
				plus.bluetooth.readBLECharacteristicValue({
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId: _this.deviceId,
					// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
					serviceId: _this.serviceId,
					// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
					characteristicId: _this.characteristicId,
					success: res => {
						console.log('readBLECharacteristicValue:', res.value);
						this.readCode = res.errCode;
						this.readCodeMsg = res.errMsg;
						//_this.onBLECharacteristicValueChange(this.deviceId);
					},
					fail: res => {
						console.log('readBLECharacteristicValue:', res);
						this.readCode = res.errCode;
						this.readCodeMsg = res.errMsg;
						//_this.onBLECharacteristicValueChange(this.deviceId);
					}
				});
			},

			// 写入低功耗蓝牙设备的特征值
			writeBLECharacteristicValue(value) {
				const _this = this;
				console.log('写入低功耗蓝牙设备的特征值');
				
				
				//var valuebuffer = new Buffer(value);
				//console.log(valuebuffer.length); // => 3
				//console.log(valuebuffer[5].toString(16));
				
				// const data = new Uint8Array(_this.write.qp).buffer;
				//2encodeURIComponent() 
				//let codeLength = value.length;
				
				// _this.buffer = new ArrayBuffer(codeLength);
				// const dataView = new DataView(_this.buffer);

				// let data = [];
				// //在这里解析将要写入的值
				// for (let i = 0; i < codeLength; i++) {
				// 	let dddd = value.charCodeAt(i).toString(16);
				// 	dataView.setUint8(i, '0X' + dddd);

				// 	data.push(value.substring( i,  i + 1));
				// }
				**//网里找的复杂啊(上面都是),其实只要下面一句,还解决了中文问题**
				_this.buffer = new Buffer(value); //UTF-8字符
				uni.writeBLECharacteristicValue({
					deviceId: _this.deviceId,
					serviceId: _this.serviceId,
					characteristicId: _this.characteristicId,
					value: _this.buffer,
					writeType: 'writeNoResponse',
					success: function(e) {
						//console.log('发送成功', data.join(','));
						
						console.log('write characteristics success: ' + JSON.stringify(e));
					},
					fail: function(e) {
						console.log('write characteristics failed: ' + JSON.stringify(e));
					}
				});
			},
//断开蓝牙连接
			closeBLEConnection(deviceId, index) {
				const _this = this;
				plus.bluetooth.closeBLEConnection({
					deviceId: deviceId,
					success: res => {
						console.log('断开蓝牙连接');
						if (index >= 0) {
							_this.isLink.splice(index, 1, 4);
						}
						mHelper.toast('已断开连接!');
					}
				});
			},

		},


		onLoad() {
			let hexString = "68656c6c6f"; 
			let str = ""; 
			console.log(hexString); // 输出 "hello" 
			for (let i = 0; i < hexString.length; i += 2) { 
				let hex = hexString.substr(i, 2); 
				str += String.fromCharCode(parseInt(hex, 16)); 
			} 
			console.log(str); // 输出 "hello" 
			this.Search();

			
		},
	}
</script>

<style>
	.box {
		width: 100%;
		height: 800rpx;
		box-sizing: border-box;
		margin-bottom: 20rpx;
		border: 2px solid dodgerblue;
	}

	.item {
		box-sizing: border-box;
		padding: 10rpx;
		border-bottom: 1px solid #ccc;
	}

	button {
		margin-bottom: 20rpx;
	}
</style>
  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值