• UNI使用蓝牙连接设备传输数据


    B站链接https://www.bilibili.com/read/cv5678982 

    只需要把下面第二个文件复制到项目里面,然后引入就可以了

    主要流程:

    1.初始化蓝牙适配器openBluetoothAdapter,如果不成功就onBluetoothAdapterStateChange监听蓝牙适配器状态变化事件

    2.startBluetoothDevicesDiscovery开始搜寻附近的蓝牙外围设备

    3.onBluetoothDeviceFound监听寻找到新设备的事件,在这里你可以用代码匹配设备

    4.createBLEConnection创建蓝牙连接,顺便在stopBluetoothDevicesDiscovery关闭搜寻附近的蓝牙外围设备

    5.getBLEDeviceServices获取蓝牙设备所有服务

    6.getBLEDeviceCharacteristics获取蓝牙设备某个服务中所有特征值

    7.onBLECharacteristicValueChange监听蓝牙设备发送给你的数据

    8.writeBLECharacteristicValue向蓝牙设备发送一个0x00的16进制数据或者writeBLECharacteristicValueString发送字符串

    <template>
    	<view>
    		
    	</view>
    </template>
    
    <script>
    	import bt from '../../utils/bluetooth.vue';
    	
    	export default {
    		data() {
    			return {
    				
    			}
    		},
    		methods: {
    			
    		},
    		onLoad(opt) {
    			bt.openBluetoothAdapter("DEMO1");
    		}
    	}
    </script>
    
    <style>
    
    </style>
    <template>
    	<view></view>
    </template>
    
    <script>
    	var _discoveryStarted = false;
    	
    	var _deviceId = null;
    	var _serviceId = null;
    	var _characteristicId = null;
    	var chs = [];
    	
    	var btvalue = null;
    	
    	function inArray(arr, key, val) {
    	  for (let i = 0; i < arr.length; i++) {
    	    if (arr[i][key] === val) {
    	      return i;
    	    }
    	  }
    	  return -1;
    	}
    	// ArrayBuffer转16进度字符串示例
    	function ab2hex(buffer) {
    	  var hexArr = Array.prototype.map.call(
    	    new Uint8Array(buffer),
    	    function (bit) {
    	      return ('00' + bit.toString(16)).slice(-2)
    	    }
    	  )
    	  return hexArr.join('');
    	}
    	
    	//准备开始扫描
    	function $openBluetoothAdapter(devicename){
    		//初始化蓝牙模块
    		uni.openBluetoothAdapter({
    			success: (res) => {
    			    console.log('openBluetoothAdapter success', res);
    			    $startBluetoothDevicesDiscovery(devicename);
    			},
    			fail: (res) => {
    				uni.showToast({
    				    title: '请打开蓝牙',
    				    duration: 1000
    				});
    			    if (res.errCode === 10001) {
    					//监听蓝牙适配器状态变化事件
    					uni.onBluetoothAdapterStateChange(function(res){
    						console.log('onBluetoothAdapterStateChange', res);
    						if (res.available) {
    							//开始扫描
    							$startBluetoothDevicesDiscovery(devicename)
    						}
    					})
    			    }
    			}
    		})
    	}
    	
    	function $startBluetoothDevicesDiscovery(devicename){
    		if (_discoveryStarted) {
    		    return;
    		}
    		_discoveryStarted = true;
    		//开始搜寻附近的蓝牙外围设备
    		uni.startBluetoothDevicesDiscovery({
    			allowDuplicatesKey: true,
    			    success: (res) => {
    			    console.log('startBluetoothDevicesDiscovery success', res);
    				//监听寻找到新设备的事件
    			    $onBluetoothDeviceFound(devicename)
    			},
    		})
    	}
    	
    	function $onBluetoothDeviceFound(devicename) {
    		//监听寻找到新设备的事件
    		uni.onBluetoothDeviceFound(function(res){
    			res.devices.forEach(device => {
    				if (!device.name && !device.localName) {
    				  return;
    				}
    				console.log(device);
    				//如果名字相同连接设备
    				if(device.name == devicename){
    					$createBLEConnection(device.deviceId);
    				}
    			})
    		})
    	}
    	
    	
    	function $createBLEConnection(deviceId){
    		//创建连接
    		uni.createBLEConnection({
    			deviceId:deviceId,
    			success: (res) => {
    				console.log(res);
    				$getBLEDeviceServices(deviceId);
    			},
    			fail: (err) =>{
    				console.log(err);
    			}
    		});
    		$stopBluetoothDevicesDiscovery();
    	}
    	
    	function $getBLEDeviceServices(deviceId) {
    		//获取蓝牙设备所有服务(service)
    		uni.getBLEDeviceServices({
    			deviceId,
    			success: (res) => {
    			  for (let i = 0; i < res.services.length; i++) {
    			    if (res.services[i].isPrimary) {
    			      $getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);
    				  return;
    			    }
    			  }
    			}
    		});
    	}
    	
    	function $getBLEDeviceCharacteristics(deviceId, serviceId){
    		//获取蓝牙设备某个服务中所有特征值(characteristic)。
    		uni.getBLEDeviceCharacteristics({
    			deviceId,
    			serviceId,
    			success: (res) => {
    				console.log('getBLEDeviceCharacteristics success', res.characteristics);
    				for (let i = 0; i < res.characteristics.length; i++) {
    				    let item = res.characteristics[i]
    				    if (item.properties.read) {
    						//读取低功耗蓝牙设备的特征值的二进制数据值。1
    						uni.readBLECharacteristicValue({
    							deviceId,
    							serviceId,
    							characteristicId: item.uuid,
    						})
    				    }
    				    if (item.properties.write) {
    				        _deviceId = deviceId;
    				        _serviceId = serviceId;
    				        _characteristicId = item.uuid;
    				        $writeBLECharacteristicValue();
    				    }
    				    if (item.properties.notify || item.properties.indicate) {
    						//启用低功耗蓝牙设备特征值变化时的 notify 功能,订阅特征值。
    						uni.notifyBLECharacteristicValueChange({
    				            deviceId,
    				            serviceId,
    				            characteristicId: item.uuid,
    				            state: true,
    				        });
    				    }
    				}
    			},
    			fail(res) {
    			    console.error('getBLEDeviceCharacteristics', res)
    			}
    		})
    		
    		//监听数据
    		// 操作之前先监听,保证第一时间获取数据
    		uni.onBLECharacteristicValueChange(function(characteristic){
    			const idx = inArray(chs, 'uuid', characteristic.characteristicId)
    			const data = {}
    			if (idx === -1) {
    			  data[`chs[${chs.length}]`] = {
    			    uuid: characteristic.characteristicId,
    			    value: ab2hex(characteristic.value)
    			  }
    			} else {
    			  data[`chs[${idx}]`] = {
    			    uuid: characteristic.characteristicId,
    			    value: ab2hex(characteristic.value)
    			  }
    			}
    			
    			console.log(data);
    			
    			btvalue = data;
    		})
    		
    	}
    	
    	
    	function $writeBLECharacteristicValue() {
    		// 向蓝牙设备发送一个0x00的16进制数据
    		let buffer = new ArrayBuffer(1)
    		let dataView = new DataView(buffer)
    		dataView.setUint8(0, 0x61 | 0);
    		
    		uni.writeBLECharacteristicValue({
    		      deviceId: _deviceId,
    		      serviceId: "0000FFE0-0000-1000-8000-00805F9B34FB",
    		      characteristicId: _characteristicId,
    		      value: buffer,
    		      success: function(res){
    		        console.log(res);
    		      },
    		      fail: function(res){
    		        console.log(res);
    		      }
    		})
    	};
    	
    	function $writeBLECharacteristicValueString(str) {
    		// 向蓝牙设备发送16进制数据
    		let buffer = new ArrayBuffer(str.length);
    		let dataView = new DataView(buffer);
    		
    		for (let i in str) {
    			dataView.setUint8(i, str[i].charCodeAt() | 0);
    		}
    		
    		uni.writeBLECharacteristicValue({
    		      deviceId: _deviceId,
    		      serviceId: "0000FFE0-0000-1000-8000-00805F9B34FB",
    		      characteristicId: _characteristicId,
    		      value: buffer,
    		      success: function(res){
    		        console.log(res);
    		      },
    		      fail: function(res){
    		        console.log(res);
    		      }
    		})
    	};
    	
    	function $stopBluetoothDevicesDiscovery(){
    		//关闭搜索
    		uni.stopBluetoothDevicesDiscovery({
    			success(res) {
    				console.log(res);
    			}
    		})
    	}
    	
    	
    	export default {
    		data() {
    			return {
    			
    			}
    		},
    		methods: {
    			
    		},
    		openBluetoothAdapter: $openBluetoothAdapter,
    		writeBLECharacteristicValue: $writeBLECharacteristicValue,
    		writeBLECharacteristicValueString: $writeBLECharacteristicValueString
    	}
    	
    	
    </script>
    
    <style>
    </style>
    
  • 相关阅读:
    [LeetCode] Dungeon Game
    [LeetCode] Maximal Rectangle
    [LeetCode] Scramble String -- 三维动态规划的范例
    [LeetCode] Palindrome Partitioning II
    [LeetCode] Palindrome Partitioning
    [LeetCode] Interleaving String
    [LeetCode] Longest Valid Parentheses -- 挂动态规划羊头卖stack的狗肉
    JPA将查询结果转换为DTO对象
    EOS签名R值过大导致报错"is_canonical( c ): signature is not canonical"
    比特币中P2SH(pay-to-script-hash)多重签名的锁定脚本和解锁脚本
  • 原文地址:https://www.cnblogs.com/kawayidamiao/p/13843762.html
Copyright © 2020-2023  润新知