UniApp使用蓝牙连接对讲机

<template>
	<view>

		<!-- <video :src="voicePath" v-if="voicePath" style="width: 200rpx;height: 200rpx;" /> -->
		<button style="width: 200rpx;height: 200rpx;" @tap="playVoice">播放</button>
		<view v-for="(item,index) in BluetoothList" :key="index">
			<view style="width: 100%;height: 80rpx;line-height: 80rpx;text-align: center;"
				@click="connetBlue(item.deviceId)">{{item.name}}-----{{item.deviceId}}</view>
		</view>
	</view>
</template>

<script>
	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.autoplay = true;
	export default {
		data() {
			return {
				deviceId: "",
				BluetoothList: [],
				services: '',
				readyservices: '',
				notifyUuid: '',
				voicePath: ''
			}
		},
		onLoad() {
			let that = this
			that.player()
			recorderManager.onStop(function(res) {
				console.log('recorder stop' + JSON.stringify(res));
				console.log(res.tempFilePath, 'res.tempFilePath')
				that.voicePath = res.tempFilePath;
				console.log(that.voicePath, 'voijoiewqewq')
			});
		},
		methods: {
			playVoice() {
				console.log(this.voicePath, 'voicePath')
				if (this.voicePath) {
					innerAudioContext.src = this.voicePath;
					innerAudioContext.play();
				}
			},
			// 用户点击某个设备
			connetBlue(deviceId) {
				console.log('用户点击某个设备', deviceId)
				var that = this;
				setTimeout(() => {
					uni.createBLEConnection({
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
						deviceId, //设备id
						success: function(res) {
							console.log(res, '用户点击某个设备')
							console.log("连接蓝牙成功!-->11111")
							that.deviceId = deviceId;
							that.getServiceId() //5.0
							uni.stopBluetoothDevicesDiscovery({
								success: function(res) {
									console.log('连接蓝牙成功之后关闭蓝牙搜索');
								}
							})
						},
						fail: (err) => {
							console.log(err, '连接失败')
						}
					})
				}, 3000)
			},
			// 连接设备
			getServiceId() {
				console.log(123)
				var that = this
				setTimeout(() => {
					uni.getBLEDeviceServices({
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
						deviceId: that.deviceId,
						success: function(res) {
							console.log(res, '连接设备')
							console.log(res.services[1].uuid, '设备ID')
							//需要什么服务就用对应的services 
							that.readyservices = res.services[0].uuid //因设备而议:该特征值只支持读
							that.services = res.services[1].uuid //因设备而议:该特征值支持write和notfy服务
							that.getCharacteId() //6.0
						}
					})
				}, 1500)
			},
			// 如果蓝牙设备数据传输
			getCharacteId() {
				let that = this
				uni.getBLEDeviceCharacteristics({
					deviceId: that.deviceId,
					serviceId: that.services,
					success: (res) => {
						console.log(res, '如果蓝牙设备数据传输')
						// that.notifyUuid = res.characteristics[0].uuid
						// that.startNotice()
						for (var i = 0; i < res.characteristics.length; i++) { //2个值
							var model = res.characteristics[i]
							if (model.properties.write) {
								//model.uuid:用来写入的uuid值
								//this.sendMy()给设备写入
								// that.sendMy(model.uuid)
							}
							if (model.properties.notify) {
								console.log(model.uuid, 'uuid')
								//model.uuid:用来notify的uuid值
								that.notifyUuid = model.uuid
								that.startNotice()
							}
						}
					}
				})
			},
			ab2hex(buffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('')
			},
			// 接受数据
			startNotice() {
				let that = this
				console.log('deviceId:' + that.deviceId, 'serviceId:' + that.services, 'characteristicId:' + that
					.notifyUuid)
				setTimeout(() => {
					uni.notifyBLECharacteristicValueChange({
						state: true,
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 
						deviceId: that.deviceId,
						// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
						serviceId: that.services,
						// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
						characteristicId: that.notifyUuid, //第一步 开启监听 notityid  第二步发送指令 write
						success: (res) => {
							console.log(res, 'resres')
							// 接受蓝牙返回的信息
							uni.onBLECharacteristicValueChange((change) => {
								console.log(change, 'change')
								let value = that.ab2hex(change.value)
								console.log(value, 'value')
								// 开始
								if (value == '00') {
									console.log("开始")
									recorderManager.start({
										format: 'aac',
										detectDecibel: true
									});
								}
								// 结束
								if (value == 'ff') {
									console.log("结束")
									recorderManager.stop();
								}
								// console.log(that.ab2hex(change.value))
							})
						}
					})
				}, 1500)
			},
			// 初始化蓝牙设备
			player() {
				var that = this;
				uni.openBluetoothAdapter({ //调用微信小程序api 打开蓝牙适配器接口
					success: function(res) {
						console.log(res, '初始化蓝牙设备')
						that.findBlue(); //2.0
					},
					fail: function(res) { //如果手机上的蓝牙没有打开,可以提醒用户
						uni.showToast({
							title: '请打开蓝牙',
							type: 'error',
							icon: 'none'
						});
					}
				})
			},
			// 搜索周边设备
			findBlue() {
				var that = this
				uni.startBluetoothDevicesDiscovery({
					allowDuplicatesKey: false,
					interval: 0,
					success: function(res) {
						console.log(res, '搜索周边设备')
						that.getBlue() //3.0
					}
				})
			},
			//获取搜索到的设备信息
			getBlue() {
				var that = this
				//uni.getBluetoothDevices获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备
				setTimeout(() => {
					uni.getBluetoothDevices({
						success: function(res) {
							console.log(res, '获取搜索到的设备信息')
							that.BluetoothList = res.devices
							//将BluetoothList遍历给用户,当用户点击连接某个蓝牙时调用4.0
							uni.stopBluetoothDevicesDiscovery({
								success: (qql) => {
									console.log(qql, '有的话关闭')
								}
							})
						},
						fail: function() {
							console.log("搜索蓝牙设备失败")
						}
					})
				}, 1500)
			},

		}
	}
</script>

<style>

</style>

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值