直接上代码,也是拼拼凑凑就成了

<template>
	<view class="content">
		<button type="default" @click="startBluetoothDevicesDiscovery">搜索蓝牙</button>
		<button type="default" @click="stopBluetoothDevicesDiscovery">停止搜索蓝牙</button>
		<button type="default" @click="print">打印模板</button>
		<view class="bluetooth-list">
			<text>蓝牙列表</text>
			<view class="bluetooth-list-item">
				<text>name</text>
				<text>deviceId</text>
			</view>
			<view class="bluetooth-list-item" v-for="(item, index) in devicesList" :key="index" :class="item.isConnect ? 'activeList' : ''">
				<text>{{item.name}}</text>
				<text>{{item.deviceId}}</text>
				<text :style="{color: !item.isConnect ? 'red' : 'green'}" class="" @tap="!item.isConnect ? connect(item, index) : unConnect(item, index)">{{!item.isConnect ? '点击连接' : '断开连接'}}</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				devicesList: [],
				device: null
			}
		},
		onLoad() {
			// 初始化蓝牙模块
			this.openBluetoothAdapter()
			uni.hideLoading()
		},
		methods: {
			/* 初始化蓝牙模块 */
			openBluetoothAdapter () {
				uni.openBluetoothAdapter({
					success: res => {
						console.log('blueth is ok', res)
					},
					fail: err => {
						console.log('blueth is err', err)
					},
				});
			},
			/* 搜索蓝牙 */
			startBluetoothDevicesDiscovery () {
				setTimeout(() => {
					uni.startBluetoothDevicesDiscovery({
						allowDuplicatesKey: true, // 启用重复上报方便删除后可快速拿到设备
						success: res => {
							// console.log('startBluetoothDevicesDiscovery ok:', res)
							// 监听寻找蓝牙新设备
							this.onBluetoothDeviceFound()
						},
						fail: err => {
							console.log('startBluetoothDevicesDiscovery err:', err)
						}
					})
				}, 1000)
			},
			/* 监听寻找蓝牙新设备*/
			onBluetoothDeviceFound () {
				uni.onBluetoothDeviceFound(res => {
					// console.log('find dev list:', res)
					if (
						res.devices[0].name &&
						!this.devicesList.some(item => {
							return item.deviceId === res.devices[0].deviceId
						})
					) {
						this.devicesList.push({...res.devices[0], isConnect: false})
					}
				})
			},
			/* 停止搜索蓝牙 */
			stopBluetoothDevicesDiscovery () {
				uni.stopBluetoothDevicesDiscovery({
					success: res => {
						console.log('topBluetoothDevices ok:', res)
					},
					fail: err => {
						console.log('topBluetoothDevices err:', err)
					}
				})
			},
			/* 连接低功耗蓝牙 */
			createBLEConnection(deviceId) {
				return new Promise((resolve, reject) => {
					uni.createBLEConnection({
						deviceId,
						success: async res => {
							resolve(true)
						},
						fail: err => {
							reject(err)
						}
					})
				});
			},
			/*  获取蓝牙设备某个服务中所有特征值(characteristic) */
			getBLEDeviceCharacteristics(deviceId, serviceId, characteristicId) {
				let self = this;
				return new Promise((resolve, reject) => {
					uni.getBLEDeviceCharacteristics({
						deviceId,
						serviceId,
						success: async res => {
							if (!characteristicId) {
								return resolve(res.characteristics)
							}
							let sure = false;
							for (var i = 0; i < res.characteristics.length; i++) {
								if (res.characteristics[i].uuid.toUpperCase().indexOf(
										characteristicId) != -1) {
									sure = true
									break;
								}
							}
							sure ? resolve(true) : reject({
								errMsg: '设备功能不匹配'
							})
						},
						fail: err => {
							reject(false)
						}
					})
				});
			},
			/* 连接设备 */
			async connect (item, index) {
				// 连接低功耗蓝牙
				const name = item.name
				const deviceId = item.deviceId
				console.log(deviceId)
				try{
					await this.createBLEConnection(deviceId)
					this.showToast(`${name}连接成功`)
					// 更改连接状态
					let devObj = this.devicesList[index]
					devObj.isConnect = true
					this.$set(this.devicesList, index, devObj)
					// 获取蓝牙设备所有服务(service)
					const serviceTimer = setTimeout(() => {
						uni.getBLEDeviceServices({
							deviceId,
							success: async res => {
								const services = res.services
								if (services.length > 0) {
									for (var i = 0; i < services.length; i++) {
										if (services[i].isPrimary) {
											// 获取设备特征值
											var characteristicsRes = await this.getBLEDeviceCharacteristics(deviceId,
												services[i].uuid)
											if (characteristicsRes.length > 0) {
												for (var s = 0; s < characteristicsRes.length; s++) {
													if (characteristicsRes[s].properties.write) {
														let list = Object.assign(item, {
															characteristicId: characteristicsRes[s].uuid,
															serviceId: services[i].uuid
														})
														this.device = list
														// console.log(this.device)
													}
												}
											}
										}
									}
								} else {
									this.showToast(`该设备无权限,可能无法使用该功能`)
									this.unConnect(item, index)
								}
							}
						})
						clearTimeout(serviceTimer)
					}, 1000)
				}catch(err){
					//TODO handle the exception
					this.showToast(`${name}连接失败`)
					console.log('蓝牙连接失败:', err)
				}
			},
			/* 断开连接 */
			unConnect (item, index) {
				const deviceId = item.deviceId
				const name = item.name
				uni.closeBLEConnection({
					deviceId,
					success: async res => {
						// 更改连接状态
						let devObj = this.devicesList[index]
						devObj.isConnect = false
						this.$set(this.devicesList, index, devObj)
						this.showToast(`${name}蓝牙已断开`)
						this.device = []
					},
					fail: err => {
						reject(err);
					}
				})
			},
			/* 打印 */
			print () {
				const device = this.device
				const printStr = require(`./cpclDemo.js`)
				console.log(device)
				// if (device === null) {
				// 	this.showToast('您还没有连接打印机!')
				// 	return false
				// }
				// this.showLoading({
				// 	title: '打印中...',
				// 	mask: true
				// })
				const encode = encodeURI(printStr.val)
				// 对编码的字符串转化base64
				const base64 = btoa(encode)
				const arrayBuffer = uni.base64ToArrayBuffer(base64)
				const writeTimer = setTimeout(subPackage => {
					uni.writeBLECharacteristicValue({
						deviceId: device.deviceId, // 蓝牙设备ID
						characteristicId: device.characteristicId, // 蓝牙特征值的 uuid
						serviceId: device.serviceId, // 蓝牙特征值对应服务的 uuid
						value: arrayBuffer, // 蓝牙设备特征值对应的二进制值
						success(e) {
							// this.showToast('打印成功')
							console.log('打印成功')
						},
						fail(err) {
							// this.showToast('打印失败!')
							uni.hideLoading()
							console.log(err)
						}
					})
					clearTimeout(writeTimer)
				}, 20);
				// this.showLoading({
				// 	title: '打印中...',
				// 	mask: true
				// })
				// 打印机排版需要遵循 ”CPCL指令“ 编码格式,打印时,需要将该格式的数据转化为 buffer 然后分包发送给打印机
				/* const base = require('./base64gb2312.js')
				let buffer = []
				for (let n = 0; n < Math.ceil(printStr.length / 10); n++) {
					buffer[n] = base.base64ToArrayBuffer(base.encode64gb2312(printStr.substr(n * 10, 10)));
				}
				console.log(buffer)
				const maxChunk = 20
				for (let c = 0; c < buffer.length; c++) {
					for (let i = 0, j = 0, length = buffer[c].byteLength; i < length; i += maxChunk,
						j++) {
						let subPackage = buffer[c].slice(i, i + maxChunk <= length ? (i + maxChunk) :
							length);
						setTimeout(subPackage => {
							uni.writeBLECharacteristicValue({
								deviceId: device.deviceId, // 蓝牙设备ID
								characteristicId: device.characteristicId, // 蓝牙特征值的 uuid
								serviceId: device.serviceId, // 蓝牙特征值对应服务的 uuid
								value: subPackage, // 蓝牙设备特征值对应的二进制值
								success(e) {
									if (c >= (buffer.length - 1)) {
										// this.showToast('打印成功')
									}
								},
								fail(err) {
									// this.showToast('打印失败!')
									uni.hideLoading()
									console.log(err)
								}
							})
						}, 20, subPackage);
					}
				} */
			},
			/* 提示 */
			showToast(title, icon = 'none', position = 'bottom', duration = 1500, mask = false) {
				uni.showToast({
					title,
					icon,
					duration,
					position,
					mask
				})
			},
			showLoading(object) {
				uni.showLoading(object)
			}
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
	}
	.bluetooth-list-item {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		padding: 20upx 40upx;
		border-bottom: 1px solid #ff0000;
	}
	.bluetooth-list-item:nth-child(1) {
		border-bottom: 1px solid #00ff00!important;
	}
	.activeList {
		color: #007AFF;
	}
</style>
© 版权声明
分享是一种美德,转载请保留原链接