uniapp连接蓝牙称(接收,发送)

复制即用,看好注释修改

用微信开发者的->真机调试,进行调试

<view>{{ www }}</view> //数据展示

<template>
	<view>{{ www }}</view>
</template>

<script>
	export default {
		data() {
			return {
				bluetooth: false, //按钮状态
				connectedDeviceId: '', // 连接蓝牙设备id
				serviceId: '',  // 服务,也就是uuid 一个设备可能有多个uuid 
				writeId: '',    //只用用一个 uuid
				characteristicId: '', // 设备特征id 发送指令会用到
				devicesList: [],
				www: '',
				convertWeight: '',  //接收的数据 处理过后 显示重量
				endow: false,    // 是否用蓝牙称给的数据
			}
		},
		onUnload() { // 离开断开蓝牙
			this.closeBLEConnection();
			uni.showLoading({
				title: '断开蓝牙',
			});
			setTimeout(function() {
				uni.hideLoading();
			}, 1000);
		},
		created(){
			this.Search(); //进来直接开始搜索
			//发送指令
			// this.sendMy();   这里是发送指令 自己找按钮调用
		},
		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(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;
						},
					});
				}
			},
			//监听寻找到新设备的事件
			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]);
							that.devicesList.push(devices.devices[0]);
						}
					}
				});
			},
			
			//这里写一个按钮调一下   e 就是上面给方法返回来的数据,取一个获取就行,看打印日志,跟所需参数
			select(e) {
				console.log('点击连接', e);
				var that = this;
				that.ConnectByID({
					"deviceId": e.deviceId,
					"name": e.name
				}, 1);
			},
			
			ConnectByID(item, index) { //连接蓝牙
				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("已连接设备----------------------------------------");
						uni.setStorageSync("deviceId", item.deviceId)
						uni.setStorageSync("name", item.name)
						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)
							);
							console.log("服务uuid", res)
							that.services = res.services;
							that.serviceId = res.services[1].uuid;
							that.deviceId = that.connectedDeviceId;
							uni.setStorageSync("serviceId", that.serviceId);
							that.getBLEDeviceCharacteristics();
						},
						fail(res) {
							console.log('错误', res);
						},
					});
				}, 3000);
			},
			// 根据服务uuid获取蓝牙特征值开始监听写入和接收
			getBLEDeviceCharacteristics() {
				console.log("开始监听.....")
				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;
				// console.log(that.deviceId, that.serviceId, that.characteristicId)
				uni.notifyBLECharacteristicValueChange({
					state: true,
					deviceId: that.deviceId,
					serviceId: that.serviceId,
					characteristicId: that.characteristicId,

					success: function(res) {
						console.log("启用notify成功");
						that.onBLECharacteristicValueChange();
					},
					fail: function(res) {

						that.onBLECharacteristicValueChange();
						console.log("启用notify失败");
					},
				});

				that.onBLECharacteristicValueChange();
			},
			onBLECharacteristicValueChange() {
				console.log("开始接收")

				var that = this;
				uni.onBLECharacteristicValueChange((res) => {
					// 此时可以拿到蓝牙设备返回来的数据是一个ArrayBuffer类型数据,所以 ArrayBuffer 转 16进制 在转字符串

					that.www = that.hexCharCodeToStr(that.buf2hex(res.value));
					
				});
			},
			hexCharCodeToStr(hexCharCodeStr) {
				var trimedStr = hexCharCodeStr.trim();
				var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
				var len = rawStr.length;
				if (len % 2 !== 0) {
					alert("存在非法字符!");
					return "";
				}
				var curCharCode;
				var resultStr = [];
				for (var i = 0; i < len; i = i + 2) {
					curCharCode = parseInt(rawStr.substr(i, 2), 16);
					resultStr.push(String.fromCharCode(curCharCode));
				}
				return resultStr.join("");
			},
			buf2hex(buffer) { // buffer is an ArrayBuffer
				return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
			},
			//断开蓝牙
			closeBLEConnection() { // 这个是断开蓝牙
				uni.closeBLEConnection({
					deviceId: this.deviceId,
					success(res) {
						console.log('关闭成功', res)
					},
					fail(res) {
						console.log('关闭失败', res)
					}
				})
			},
			//关闭蓝牙模块    这个是手机的蓝牙
			// closeBluetoothAdapter({
			// 	success(res){
			// 		console.log('关闭成功',res)
			// 	},fail(res){
			// 		console.log('关闭失败',res)
			// 	}
			// })
			//buffer允许写入的uuid
			//buffer允许写入的uuid
			sendMy() {
				var that = this
				//this.string2buffer-->字符串转换成ArrayBufer(设备接收数据的格式ArrayBufer)
				var buff = that.string2buffer('1B0D0A'); // 你的指令
				uni.writeBLECharacteristicValue({
					// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
					deviceId: that.deviceId,
					// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
					serviceId: that.serviceId,
					// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
					characteristicId: that.characteristicId,
					// 这里的value是ArrayBuffer类型
					value: buff,
					success: function(res) {
						//此时设备已接收到你写入的数据
						console.log("写入成功")
					},
					fail: function(err) {
						console.log(err)
					},
					complete: function() {
						console.log("调用结束");
					}
				})
			},
			string2buffer(str) {
				let val = ""
				if (!str) return;
				let length = str.length;
				let index = 0;
				let array = []
				while (index < length) {
					array.push(str.substring(index, index + 2));
					index = index + 2;
				}
				val = array.join(",");
				// 将16进制转化为ArrayBuffer
				return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function(h) {
					return parseInt(h, 16)
				})).buffer
			},
		}
	}
</script>




你可能感兴趣的:(uni-app,前端,javascript,蓝牙)