当前位置: 首页 > article >正文

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>





http://www.kler.cn/news/156312.html

相关文章:

  • Oracle下统计平均用餐时间、用餐总量、好评率
  • Mars3d标绘的时候通过绑定单击事件,查询点击落点的图层类型
  • “微流控芯片建模与肿瘤标志物/感染性疾病细胞分析:合成生物学的新前沿“
  • 编织魔法——我与计算机的不解之缘
  • STL中使用[]重载的类
  • dart 控制台应用
  • 小程序如何刷新当前页面?
  • SQL server 2016安装
  • IEEE 机器人最优控制开源库 Model-based Optimization for Robotics
  • 【开源】基于JAVA的校园电商物流云平台
  • 【C++】sizeof()、strlen()、length()\以及size()用法区别
  • 【每日一题】1038. 从二叉搜索树到更大和树-2023.12.4
  • python-GC机制、装饰器、生成器、迭代器、三元表达式、列表生成式、生成器表达式、函数递归、面向对象、
  • 【数据结构】八大排序 (三)
  • 如何精准操作无人机自动停机坪?
  • (c语言进阶)作业讲解
  • Docker pull 命令
  • 网件R8500 trojan
  • 技术前沿丨Teranode如何实现无限扩容
  • 36、红外遥控(外部中断)
  • 数据库事务的隔离级别
  • PyQt实战 创建一个PyQt5项目
  • 【算法】滑动窗口题单——5.多指针滑动窗口⭐
  • LabVIEW通过编程将图形类控件的X轴显示为时间戳
  • easyrecovery2024绿色版中文语言电脑数据恢复工具
  • 网络层之SDN基本概念、路由算法和路由协议
  • java的弱引用、软引用和虚引用
  • Ubuntu Server 20.04.6安装Anaconda3
  • javascript中的过滤操作
  • 11月推荐阅读的12篇大语言模型相关论文