uniapp 小程序 蓝牙

1 篇文章 0 订阅
1 篇文章 0 订阅
  1. 创建 bluetooth.js 文件
function ble_com(readCallBack, statusCallBack) {
	this.readCallBack = readCallBack;
	this.statusCallBack = statusCallBack;
	this.characteristicObj = {
		read: '',
		write: '',
		notify: ''
	}
	this.writeserveObjUuid = ''
	this.readServerObjUuid = ''
	this.characteristics = ''
	this.waiweiId = ''
	this.advertisData = ''
	this.asciiRes = ''
	this.asciiCode = ''
	this.asciiSuc = ''
	this.asciiStep = ''
	this.asciiHex = ''
	this.instruct = ''
	this.blueToothconnected = ''
	this.readVal = ''
	this.writeState = false
	this.callBackState = false
}
ble_com.prototype = {
	onLoad: function(tableNumber) {
		//在页面加载时候初始化蓝牙适配器
		uni.openBluetoothAdapter({
			success: (e) => {
				uni.showLoading({
					title: '连接中',
					mask: true
				});
				// 初始化完毕开始搜索
				this.startBluetoothDeviceDiscovery(tableNumber)
			},
			fail: res => {
				uni.showToast({
					icon: "none",
					title: "请检查蓝牙是否开启!",
					duration: 2000
				})
			}
		});
		this.onBLEConnectionStateChange()
	},

	// 初始化完毕开始搜索
	startBluetoothDeviceDiscovery: function(tableNumber) {
		//在页面显示的时候判断是都已经初始化完成蓝牙适配器若成功,则开始查找设备
		uni.startBluetoothDevicesDiscovery({
			success: res => {
				this.onBluetoothDeviceFound(tableNumber);
			},
			fail: res => {
				uni.showToast({
					icon: "none",
					title: "查找设备失败!",
					duration: 3000
				})
			}
		});
	},
	ab2hex: function(buffer) {
		const hexArr = Array.prototype.map.call(
			new Uint8Array(buffer),
			function(bit) {
				return ('00' + bit.toString(16)).slice(-2)
			}
		)
		return hexArr.join('')
	},
	// 发现外围设备
	onBluetoothDeviceFound: function(tableNumber) {
		uni.onBluetoothDeviceFound(devices => {
			if (devices.devices[0].localName) {
				if (devices.devices[0].localName.indexOf('JNM-' + tableNumber) != -1 && devices
					.devices[0].advertisData) {
					this.advertisData = this.ab2hex(devices.devices[0].advertisData)
					this.stopBluetoothDevicesDiscovery();
					this.waiweiId = devices.devices[0].deviceId
					this.createBLEConnection(devices.devices[0].deviceId)
					return;
				}
			}
		});
	},
	//停止搜索蓝牙设备
	stopBluetoothDevicesDiscovery: function() {
		uni.stopBluetoothDevicesDiscovery({
			success: e => {
				console.log('停止搜索蓝牙设备:' + e.errMsg);
			},
			fail: e => {
				console.log('停止搜索蓝牙设备失败,错误码:' + e.errCode);
			}
		});
	},
	//断开蓝牙连接
	closeBLEConnection: function() {
		uni.closeBLEConnection({
			deviceId: this.waiweiId,
			success: res => {}
		})
	},

	createBLEConnection: function(deviceId) {
		uni.createBLEConnection({
			deviceId: deviceId,
			success: res => {
				this.stopBluetoothDevicesDiscovery();
				this.getBLEDeviceServices(deviceId);
			},
			fail: res => {
				console.log(res)
			}
		})
	},

	getBLEDeviceServices: function(deviceId) {
		setTimeout(() => {
			uni.getBLEDeviceServices({
				// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
				deviceId: deviceId,
				success: (res) => {
					this.writeState = false
					console.log(res, '126');
					res.services.forEach(item => {
						this.getBLEDeviceCharacteristics(deviceId, item.uuid)
					})
				}
			})
		}, 1000)
	},

	getBLEDeviceCharacteristics: function(deviceId, serviceId) {
		setTimeout(() => {
			uni.getBLEDeviceCharacteristics({
				// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
				deviceId: deviceId,
				// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
				serviceId: serviceId,
				success: (res) => {
					let state = 0
					console.log(res, '129');
					this.characteristics = res.characteristics
					res.characteristics.forEach(item => {
						if (item.properties.read) {
							this.characteristicObj.read = item.uuid
							this.readServerObjUuid = serviceId
							this.readBLECharacteristicValue(deviceId, serviceId,
								item.uuid
							);
						}
						if (item.properties.write && !this.writeState) {
							this.characteristicObj.write = item.uuid
							this.writeserveObjUuid = serviceId
							this.writeState = true
						}

						if (item.properties.notify && state === 0) {
							this.characteristicObj.notify = serviceId
							state = 1
							this.notifyBLECharacteristicValueChange(deviceId, item
								.uuid, serviceId)

						}

					})

				},
				fail: (res) => {
					console.log(res, '153')
				}
			})
		}, 2000)
	},
	readBLECharacteristicValue: function(deviceId, serviceId, characteristicId) {
		uni.readBLECharacteristicValue({
			deviceId: deviceId,
			serviceId: serviceId,
			characteristicId: characteristicId,
			success: (res) => {
				console.log(res, '167');
			},
			fail: (res) => {
				console.log(res, '170');
			}
		})
	},
	// 启用 notify 功能
	notifyBLECharacteristicValueChange: function(deviceId, characteristicId, serviceId) {
		uni.notifyBLECharacteristicValueChange({
			state: true, // 启用 notify 功能
			// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
			deviceId: deviceId,
			// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
			serviceId: serviceId,
			// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
			characteristicId: characteristicId,
			success: (res) => {
				uni.hideLoading();
				console.log('初始化完成');
				this.onBLECharacteristicValueChange(deviceId);
			},
			fail: (res) => {
				console.log('notifyBLECharacteristicValueChange success', res.errMsg)
			}
		})
	},
	//蓝牙连接状态回调
	onBLEConnectionStateChange: function() {
		uni.onBLEConnectionStateChange((res) => {
			this.statusCallBack({
				advertisData: this.advertisData,
				connected: res.connected
			})
			if (res.connected) {
				uni.hideLoading();
				uni.showToast({
					title: '连接成功!等待初始化!',
					duration: 2000
				});
				uni.showLoading({
					title: '初始化中 请等待',
					mask: true
				});
			} else {

				// uni.showToast({
				// 	title: '蓝牙已断开!',
				// 	icon: "none",
				// 	duration: 2000
				// });
			}
		})
	},

	//回调
	onBLECharacteristicValueChange: function(deviceId) {
		uni.onBLECharacteristicValueChange((res) => {
			this.callBackState = true
			let hex = this.ab2hex(res.value)
			this.readVal += hex;
			console.log(this.readVal, '232');
			//测试
			if (this.instruct === 'writeTable') {
				this.readCallBack({
					data: this.readVal,
					cmd: this.instruct,
				})
			} else {
				this.readCallBack({
					data: this.readVal,
					cmd: 'connectState',
				})
			}
		})

	},

	ab2hex: function(buffer) {
		const hexArr = Array.prototype.map.call(
			new Uint8Array(buffer),
			function(bit) {
				return ('00' + bit.toString(16)).slice(-2)
			}
		)
		return hexArr.join('')
	},
	/**
	 * @param {Object} value
	 */
	writeBLECharacteristicValue: function(value) {
		let buffer = this.stringToBytes(value)
		uni.writeBLECharacteristicValue({
			// 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
			deviceId: this.waiweiId,
			writeType: 'write',
			// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
			serviceId: this.writeserveObjUuid,
			// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
			characteristicId: this.characteristicObj.write,
			// 这里的value是ArrayBuffer类型
			value: buffer,
			success: (res) => {
				console.log('writeBLECharacteristicValue success', res)
			},
			fail: (res) => {
				console.log('writeBLECharacteristicValue success', res)
			}
		})
	},
	//批次写入
	multipleWriteBLECharacteristicValue: function(values) {
		console.log(values);
		values.forEach(item => {
			let buffer = this.stringToBytes(item)
			uni.writeBLECharacteristicValue({
				// 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
				deviceId: this.waiweiId,
				writeType: 'writeNoResponse',
				// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
				serviceId: this.writeserveObjUuid,
				// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
				characteristicId: this.characteristicObj.write,
				// 这里的value是ArrayBuffer类型
				value: buffer,
				success: (res) => {
					console.log('writeBLECharacteristicValue success', res)
				},
				fail: (res) => {
					console.log('writeBLECharacteristicValue success', res)
				}
			})
		})
	},
	/**
	 * @param {Object} hex
	 */
	stringToBytes: function(hex) {
		var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function(h) {
			return parseInt(h, 16)
		}))
		return typedArray.buffer
	},
	writeTable: function(data) {
		console.log(data);
		this.resetState()
		this.instruct = 'writeTable'
		this.writeBLECharacteristicValue(data)
	},
	xorSum: function(hex) {
		var sum = 0;
		for (var i = 0; i < hex.length / 2; i++) {
			if (i == 0) {
				sum = parseInt(hex.substr(i * 2, 2), 16);
			} else {
				sum ^= parseInt(hex.substr(i * 2, 2), 16);
			}
		}
		var sumHex = sum.toString(16)
		if (sumHex.length < 2) {
			sumHex = '0' + sumHex;
		}
		return sumHex.toUpperCase();
	},
	hex2ascii: function(hex) {
		let str = '';
		for (let i = 0; i < hex.length / 2; i++) {
			str += String.fromCharCode(parseInt(hex.substr(i * 2, 2), 16));
		}
		return str;
	},
	resetState: function() {
		this.asciiRes = ''
		this.asciiCode = ''
		this.asciiSuc = ''
		this.asciiStep = ''
		this.asciiHex = ''
		this.callBackState = false;
	}
}

export default {
	ble_com
}
  1. 在main.js 添加
import {
	createSSRApp
} from "vue";
import App from "./App.vue";
import uviewPlus from 'uview-plus'
import bluetooth from '@/utils/bluetooth.js'
export function createApp() {
	const app = createSSRApp(App);
	var ble_com = new bluetooth.ble_com((e) => {}, (e) => {})
	app.config.globalProperties.$global = {
		bleCom: ble_com
	}
	app.use(uviewPlus)
	// 需要在app.use(uview-plus)之后执行
	uni.$u.setConfig({
		// 修改$u.config对象的属性
		config: {
			// 修改默认单位为rpx,相当于执行 uni.$u.config.unit = 'rpx'
			unit: 'rpx'
		},
		// 修改$u.props对象的属性
		props: {
			// 修改radio组件的size参数的默认值,相当于执行 uni.$u.props.radio.size = 30
			radio: {
				size: 15
			}
			// 其他组件属性配置
			// ......
		}
	})
	return {
		app,
	};
}
  1. 在vue 页面使用
	data() {
			return {
				searchForm: {
					meterNo: "",
					notifyData: "",
					areaCode: "",
				}
			};
		},
	onLoad() {
			let _this = this
			this.proxy = getCurrentInstance().proxy
			this.proxy.$global.bleCom.readCallBack = (res) => {
				if (res.cmd === 'connectState') {
					_this.searchForm.notifyData = res.data
				}
				if (res.cmd === 'writeTable') {
					_this.onCallBack(res.data)
				}
			}
			this.proxy.$global.bleCom.statusCallBack = (res) => {
				if (uni.getSystemInfoSync().platform === 'ios') {
					_this.searchForm.notifyData = res.advertisData
				}
				if (res.connected) {
					// 成功之后的业务需求 
					// _this.onSubmit()
				}
			}
		},
  1. 注意:安卓与ios的 notifyData 值是不同方法取的 原因自行百度
//安卓  通过onBLECharacteristicValueChange 回调获取 在bluebooth.js文件找
//ios  在蓝牙成功时就能获取一个advertisData 通过this.ab2hex(devices.devices[0].advertisData)转换
	ab2hex: function(buffer) {
		const hexArr = Array.prototype.map.call(
			new Uint8Array(buffer),
			function(bit) {
				return ('00' + bit.toString(16)).slice(-2)
			}
		)
		return hexArr.join('')
	},
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值