uniapp连接低功耗蓝牙

<template>
	<view class="dialogWrapp" v-if="showFlag">
		<view class="content">
			<view class="title text-center">
				<text>选择配对设备进行连接</text>
				<uni-icons type="closeempty" class="closeModel" @click="closeBulet(1)" size="16"></uni-icons>
			</view>
			<view class="scrollList">
				<view v-for="(item, index) in bluetooth">
					<text>{{ item.name }}</text>
					<button class="cu-btn round bg-blue " v-if="isLink[index] != 2"
						@click="action(item.deviceId, index)">连接</button>
					<button class="cu-btn round bg-blue " v-if="isLink[index] == 2"
						@click="action(item.deviceId, index)">已连接</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	//蓝牙操作模块
	import {
		BluetoothTool
	} from '@/store/bluetoothUtil.js';
	import mHelper from '@/utils/helper.js';
	export default {
		data() {
			return {
				textList: ['连接', '连接中', '已连接', '断开连接', '连接失败', '已断开', '断开连接'],
				showFlag: false,
				isSearch: false,
				bluetooth: [],
				isLink: [],
				// 调试数据
				serverList: [],
				characteristics: [],
				readCode: '',
				readCodeMsg: '',
				serviceId: '',
				characteristicId: '',
				value: '0102',
				returnMessage: '',
				macAddress: '',
				macValue: '', //获取的重量
				buffer: '',
				deviceId: '',
			};
		},
		onLoad() {

		},
		methods: {
			init(num) {
				let data = this.$store.state.BluetoothConnectState
				if (num == 1) {
					console.log(1);
					this.closeBLEConnection(data.deviceId, -1)
				}
				this.getBlueInfo();
				this.showFlag = true;

			},
			//操作
			action(id, index) {
				this.stopBluetoothDevicesDiscovery()
				if (this.isLink[index] != 2) {
					this.createBLEConnection(id, index);
				} else if (this.isLink[index] == 2) {
					this.closeBLEConnection(id, index);
				}
			},
			// 监听蓝牙设备连接状态
			listenerConnection() {
				console.log('监听蓝牙设备连接状态');
				let _this = this;
				plus.bluetooth.onBLEConnectionStateChange(function(e) {
					console.log('connection state changed: ' + JSON.stringify(e));
					_this.deviceId = e.deviceId;
					_this.createBLEConnection(_this.deviceId);
				});
			},

			// 蓝牙手机初始化
			getBlueInfo() {
				const _this = this;
				plus.bluetooth.openBluetoothAdapter({
					success(res) {
						_this.startBluetoothDevicesDiscovery();
					},
					fail(err) {
						console.log('fail', err);
						uni.showToast({
							title: '未检测到蓝牙',
							icon: 'none'
						});
					}
				});
			},
			// 搜索周围蓝牙设备
			startBluetoothDevicesDiscovery() {
				console.log('开始搜索蓝牙设备');
				const _this = this;
				this.isSearch = true;
				this.bluetooth = [];
				this.searchNoNameBluetooths = [];
				plus.bluetooth.startBluetoothDevicesDiscovery({
					// services:['FE7D','FFF0'],//可选 要获取设备的uuid列表
					success(res) {
						// console.log(JSON.stringify(res));
						plus.bluetooth.onBluetoothDeviceFound(res => {
							// console.log(JSON.stringify(res));
							_this.getBluetoothDevices();
						});
					},
					fail(err) {
						console.log('错误信息', JSON.stringify(err));

						uni.showToast({
							title: '蓝牙未初始化',
							icon: 'none',
							duration: 2000
						});
					}
				});
			},
			// 停止搜索

			stopBluetoothDevicesDiscovery() {
				plus.bluetooth.stopBluetoothDevicesDiscovery({
					success: e => {
						console.log('停止搜索蓝牙设备:' + e.errMsg);
					},
					fail: e => {
						console.log('停止搜索蓝牙设备失败,错误码:' + e.errCode);
					}
				});
			},
			// 获取已发现的蓝牙设备
			getBluetoothDevices() {
				const _this = this;
				plus.bluetooth.getBluetoothDevices({
					success(res) {
						console.log(' 获取已发现的蓝牙设备', res)
						// _this.stopBluetoothDevicesDiscovery()
						_this.bluetooth = res.devices.filter(item => {
							return item.name;
						});
						_this.isLink = [];
						_this.bluetooth.forEach(e => {
							_this.isLink.push(0);
						});
					}
				});
			},
			// 获取蓝牙适配器状态
			getBluetoothAdapterState() {
				plus.bluetooth.getBluetoothAdapterState({
					success(res) {
						console.log('获取蓝牙适配器状态', res);
					}
				});
			},
			// 连接蓝牙
			createBLEConnection(deviceId, index) {

				const _this = this;
				this.deviceId = deviceId;
				if (this.isLink[index] == 2) {
					console.log(10012);
					return;
				}
				this.isLink.splice(index, 1, 1);
				console.log(_this.deviceId, 1122);
				let flage= true
					plus.bluetooth.createBLEConnection({
						deviceId: _this.deviceId,
						success: res => {
							console.log(111);
							_this.isLink.splice(index, 1, 2);
							_this.stopBluetoothDevicesDiscovery();
							_this.getBLEDeviceServices(_this.deviceId);
							uni.showLoading({
								title: '连接中...',
								mask: true
							});
						},
						fail: res => {
							if (res.message == 'already connect') {
								_this.isLink[index] = 2;
								_this.stopBluetoothDevicesDiscovery();
								_this.getBLEDeviceServices(_this.deviceId);
							} else {
								_this.isLink.splice(index, 1, 3);
							}
							console.log(222);
							console.log(JSON.stringify(res));
						},
						complete: es => {
							console.log(es);
							if (es.code == '10012') {
								uni.showToast({
									title: '连接失败,请重试',
									mask: true
								});
							}
							flage = false
						}
					});
				setTimeout(()=>{
					if(flage){
						this.createBLEConnection(deviceId, index)
					}
				},3000)
				
			},

			//获取蓝牙设备所有服务(service)。
			getBLEDeviceServices(deviceId) {
				const _this = this;
				console.log(deviceId);
				setTimeout(() => {
					plus.bluetooth.getBLEDeviceServices({
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
						deviceId: deviceId,
						success: res => {
							console.log('获取蓝牙设备所有服务:', JSON.stringify(res.services));
							_this.serverList = res.services;
							var findItem = res.services.find(item => {
								//FE7D FFF0
								if (
									item.uuid != '00001800-0000-1000-8000-00805F9B34FB' &&
									item.uuid != '00001801-0000-1000-8000-00805F9B34FB' &&
									item.uuid != '0000180A-0000-1000-8000-00805F9B34FB'
								) {
									return item;
								}
							});
							console.log(JSON.stringify(findItem));
							_this.serviceId = findItem.uuid;
							_this.getBLEDeviceCharacteristics(_this.deviceId);
						},

						fail: res => {
							console.log(res);
						}
					});
				}, 1000);
			},

			// 获取蓝牙特征值
			getBLEDeviceCharacteristics(deviceId) {
				console.log('进入特征');
				const _this = this;
				setTimeout(() => {
					plus.bluetooth.getBLEDeviceCharacteristics({
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
						deviceId: deviceId,
						// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
						serviceId: this.serviceId,
						success: res => {
							_this.characteristics = res.characteristics;
							console.log('characteristics', JSON.stringify(_this.characteristics));

							let findItem = res.characteristics.find(item => {
								let uuid = item.uuid;
								console.log(uuid);
								return item.properties.notify;
							});
							_this.characteristicId = findItem.uuid;
							console.log('当前使用的特征characteristicId:', _this.characteristicId);
							_this.notifyBLECharacteristicValueChange(_this.deviceId);
							let bluetoothData = {
								deviceId: _this.deviceId,
								serviceId: _this.serviceId,
								characteristicId: _this.characteristicId
							};
							uni.setStorageSync('bluetoothData', bluetoothData);
							mHelper.toast('连接成功!');
							_this.closeBulet()
						},
						fail: res => {
							uni.hideLoading();
							console.log(res);
							mHelper.toast('连接失败!');
						}
					});
				}, 4000);
			},
			// 启用 notify 功能
			notifyBLECharacteristicValueChange(deviceId) {
				const _this = this;

				plus.bluetooth.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId: deviceId,
					// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
					serviceId: _this.serviceId,
					// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
					characteristicId: _this.characteristicId,
					success: res => {
						_this.$api.msg('连接成功', 'success');
					},
					fail: res => {
						_this.$api.msg('连接失败');
					}
				});
			},
			ab2hex(buffer) {
				const hexArr = Array.prototype.map.call(new Uint8Array(buffer), function(bit) {
					return ('00' + bit.toString(16)).slice(-2);
				});
				return hexArr.join('');
			},
			//十六进制转字符串,调整高低位
			hexCharCodeToStr(hexCharCodeStr) {
				let trimedStr = hexCharCodeStr.trim();
				let rawStr = trimedStr.substr(0, 2).toLowerCase() === '0x' ? trimedStr.substr(2) : trimedStr;
				let len = rawStr.length;
				if (len % 2 !== 0) {
					alert('Illegal Format ASCII Code!');
					return '';
				}
				let curCharCode;
				let resultStr = [];
				for (let i = 0; i < len; i = i + 2) {
					curCharCode = parseInt(rawStr.substr(i, 2), 16); // ASCII Code Value
					resultStr.unshift(String.fromCharCode(curCharCode));
				}

				return Math.round(parseFloat(resultStr.join('')) * 100) / 100;
			},

			// 监听低功耗蓝牙设备的特征值变化
			onBLECharacteristicValueChange(deviceId) {
				const _this = this;
				plus.bluetooth.onBLECharacteristicValueChange(res => {
					_this.macAddress = res.deviceId;
					let val = _this.ab2hex(res.value);

					let resValue = _this.hexCharCodeToStr(val);
					_this.macValue = resValue;
					console.log(resValue + '千克');
				});
			},

			// 读取设备二进制数据
			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);
						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('写入低功耗蓝牙设备的特征值');
				// const data = new Uint8Array(_this.write.qp).buffer;
				//2
				let codeLength = value.length / 2;
				_this.buffer = new ArrayBuffer(codeLength);
				const dataView = new DataView(_this.buffer);

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

					data.push(value.substring(2 * i, 2 * i + 2));
				}
				plus.bluetooth.writeBLECharacteristicValue({
					deviceId: _this.deviceId,
					serviceId: _this.serviceId,
					characteristicId: _this.characteristicId,
					value: _this.buffer,
					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('已断开连接!');
					}
				});
			},
			closeBulet(num) {
				if(num != 1){
					let _this = this
					
					let formData = {
						deviceId: _this.deviceId,
						serviceId: _this.serviceId,
						characteristicId: _this.characteristicId,
						buffer: _this.buffer,
					}
					this.$parent.animationly()
					this.$store.commit('BluetoothConnectState', formData)
				}
	this.showFlag = false
				this.stopBluetoothDevicesDiscovery()
			}
		}
	};
</script>

<style lang="less">
	page {
		.dialogWrapp {
			width: 100%;
			height: 100%;
			position: fixed;
			left: 0;
			top: 0;
			z-index: 9;
			background-color: rgba(0, 0, 0, 0.2);
			display: flex;
			justify-content: center;
			align-items: center;

			.content {
				height: auto;
				padding: 20px;
				background-color: #fff;

				.title {
					font-size: 16px;
					padding-bottom: 10px;
					border-bottom: 1px solid #ccc;
				}

				.scrollList {
					margin-top: 5px;

					view {
						height: 40px;
						font-size: 14px;
						display: flex;
						justify-content: space-between;
						align-items: center;
					}
				}
			}
		}
	}

	.ul {
		margin: 10px;

		.li {
			display: flex;
			justify-content: space-between;
			background: #ffffff;
			margin-top: 13upx;
			align-items: center;
			font-size: 30upx;
			border-radius: 20upx;
			height: 160upx;
			padding-left: 43upx;

			.li-left {
				display: flex;

				.blueImg {
					width: 77upx;
					height: 74upx;
					margin-right: 40upx;

					image {
						width: 100%;
						height: 100%;
					}
				}

				.eqName {
					color: #000000;
					font-size: 30upx;
					width: 250upx;
					word-break: break-all;
					display: flex;
					align-items: center;
				}
			}

			.status {
				display: flex;

				view {
					margin-right: 48upx;
				}
			}
		}
	}

	.search {
		width: 358upx;
		height: 70upx;
		border-radius: 35upx;
		border: 1px solid #5ca3f9;
		margin-top: 131upx;
		color: #5ca3f9;
		font-size: 24upx;
		line-height: 70upx;
		text-align: center;
	}

	.foot-btn-g {
		color: #007fff;
		margin-top: 80upx;
	}

	.ft-color-999999 {
		color: #999999;
	}

	.ft-color-007FFF {
		color: #007fff;
	}
	.closeModel{
		top: -15px;
		position: relative;
		right: -10px;
	}
</style>
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值