搜索蓝牙 连接蓝牙 获取特征 存储特征

	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				isSearching: false, //是否正在搜索中
				list: [],
				services: [],
				detail:"", // 货品详情
				serviceId: 0,
				writeCharacter: false,
				readCharacter: false,
				notifyCharacter: false
			};
		},
		computed: {...mapState(['sysinfo', 'Bluetooth'])},
		onLoad(option) {
			this.detail = option.data
		},
		onUnload() {
			//停止搜索蓝牙设备
			if (this.isSearching) {
				uni.stopBluetoothDevicesDiscovery();
			}
		},
		methods:{ 
			//错误码提示
			errorCodeTip(code) {
				if (code == 0) {
					//正常
				} else if (code == 10000) {
					uni.showToast({
						title: '未初始化蓝牙适配器',
						icon: 'none'
					})
				} else if (code == 10001) {
					uni.showToast({
						title: '当前蓝牙适配器不可用',
						icon: 'none'
					})
				} else if (code == 10002) {
					uni.showToast({
						title: '没有找到指定设备',
						icon: 'none'
					})
				} else if (code == 10003) {
					uni.showToast({
						title: '连接失败',
						icon: 'none'
					})
				} else if (code == 10004) {
					uni.showToast({
						title: '没有找到指定服务',
						icon: 'none'
					})
				} else if (code == 10005) {
					uni.showToast({
						title: '没有找到指定特征值',
						icon: 'none'
					})
				} else if (code == 10006) {
					uni.showToast({
						title: '当前连接已断开',
						icon: 'none'
					})
				} else if (code == 10007) {
					uni.showToast({
						title: '当前特征值不支持此操作',
						icon: 'none'
					})
				} else if (code == 10008) {
					uni.showToast({
						title: '其余所有系统上报的异常',
						icon: 'none'
					})
				} else if (code == 10009) {
					uni.showToast({
						title: 'Android 系统特有,系统版本低于 4.3 不支持 BLE',
						icon: 'none'
					})
				}
			},
			//开始搜索蓝牙
			handleStartSearch() {
				let that = this
				uni.openBluetoothAdapter({
					success(res) {
						uni.getBluetoothAdapterState({
							success(res2) {
								if (res2.available) {
									that.isSearching = true;
									if (res2.discovering) {
										uni.showToast({
											title: '正在搜索附近打印机设备',
											icon: "none"
										})
										return;
									}
			
									//获取蓝牙设备信息
									that.getBluetoothDevices()
			
									// that.checkPemission()
								} else {
									uni.showModal({
										title: '提示',
										content: '本机蓝牙不可用',
									})
								}
							}
						});
					},
					fail() {
						uni.showModal({
							title: '提示',
							content: '蓝牙初始化失败,请打开蓝牙',
						})
					}
				})
			},
			// 停止搜索
			handleStopSearch() {
				uni.stopBluetoothDevicesDiscovery({
					success: (res) => {
						this.isSearching = false;
					},
					fail: (e) => {
						this.errorCodeTip(e.errCode);
					}
				})
			},
			//获取蓝牙设备信息
			getBluetoothDevices() {
				let that = this
				that.list = [];
				uni.startBluetoothDevicesDiscovery({
					success(res) {
						//蓝牙设备监听 uni.onBluetoothDeviceFound
						uni.onBluetoothDeviceFound((result) => {
							let arr = that.list;
							let devices = [];
							let list = result.devices;
							for (let i = 0; i < list.length; ++i) {
								if (list[i].name && list[i].name != "未知设备") {
									let arrNew = arr.filter((item) => {
										return item.deviceId == list[i].deviceId;
									});
									if (arrNew.length == 0) {
										devices.push(list[i]);
									}
								}
							}
			
							that.list = arr.concat(devices);
						});
						that.time = setTimeout(() => {
							// uni.getBluetoothDevices
							uni.getBluetoothDevices({
								success(res2) {
									let devices = [];
									let list = res2.devices;
									for (let i = 0; i < list.length; ++i) {
										if (list[i].name && list[i].name != "未知设备") {
											devices.push(list[i]);
										}
									}
			
									that.list = devices;
								},
							})
							clearTimeout(that.time);
						}, 3000);
					}
				});
			},
			//绑定蓝牙
			bindViewTap(e) {
				let that = this;
				let {
					title
				} = e.currentTarget.dataset;
				let {
					BLEInformation
				} = that.Bluetooth;
				this.handleStopSearch();
				that.serviceId = 0;
				that.writeCharacter = false;
				that.readCharacter = false;
				that.notifyCharacter = false;
				uni.showLoading({
					title: '正在连接',
				})
				uni.createBLEConnection({
					deviceId: title,
					success(res) {
						BLEInformation.deviceId = title;
						that.$store.commit('BLEInformationSet', BLEInformation);
						uni.hideLoading()
						that.getSeviceId()
					},
					fail(e) {
						if (e.errCode === -1) {
							BLEInformation.deviceId = title;
							that.$store.commit('BLEInformationSet', BLEInformation);
							that.getSeviceId()
						}
						that.errorCodeTip(e.errCode);
						uni.hideLoading()
					}
				})
			},
			//获取蓝牙设备所有服务(service)。
			getSeviceId() {
				let that = this;
				let {
					BLEInformation
				} = that.Bluetooth;
				// uni.getBLEDeviceServices
				let t=setTimeout(()=>{
					uni.getBLEDeviceServices({
						deviceId: BLEInformation.deviceId,
						success(res) {
							that.services = res.services;
							that.getCharacteristics()
						},
						fail: function(e) {
							that.errorCodeTip(e.code);	
						}
					})
					clearTimeout(t);
				},1500)
			},
			getCharacteristics() {
				var that = this
				let {
					services: list,
					serviceId: num,
					writeCharacter: write,
					readCharacter: read,
					notifyCharacter: notify
				} = that;
				let {
					BLEInformation
				} = that.Bluetooth;
				// uni.getBLEDeviceCharacteristics
				uni.getBLEDeviceCharacteristics({
					deviceId: BLEInformation.deviceId,
					serviceId: list[num].uuid,
					success(res) {
						for (var i = 0; i < res.characteristics.length; ++i) {
							var properties = res.characteristics[i].properties
							var item = res.characteristics[i].uuid
							if (!notify) {
								if (properties.notify) {
									BLEInformation.notifyCharaterId = item;
									BLEInformation.notifyServiceId = list[num].uuid;
									that.$store.commit('BLEInformationSet', BLEInformation);
									notify = true
								}
							}
							if (!write) {
								if (properties.write) {
									BLEInformation.writeCharaterId = item;
									BLEInformation.writeServiceId = list[num].uuid;
									that.$store.commit('BLEInformationSet', BLEInformation);
									write = true
								}
							}
							if (!read) {
								if (properties.read) {
									BLEInformation.readCharaterId = item;
									BLEInformation.readServiceId = list[num].uuid;
									that.$store.commit('BLEInformationSet', BLEInformation);
									read = true
								}
							}
						}
						if (!write || !notify || !read) {
							num++
							that.writeCharacter = write;
							that.readCharacter = read;
							that.notifyCharacter = notify;
							that.serviceId = num;
							if (num == list.length) {
								uni.showModal({
									title: '提示',
									content: '找不到该读写的特征值',
								})
							} else {
								that.getCharacteristics()
							}
						} else {
							that.openControl()
						}
					},
					fail: function(e) {
						that.errorCodeTip(e.errCode);	
					}
				})
			},
			openControl: function() {
				uni.navigateTo({
					url: '../code-print/code-print?data='+this.detail,
				})
			},
		}
	}

打印

	var tsc = require("../../../utils/ble/tsc.js");
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				canvasWidth: 400,
				canvasHeight: 400,
				looptime: 0,
				currentTime: 1,
				lastData: 0,
				oneTimeData: 0,
				printerNum: 1,
				currentPrint: 1,
				detail:"",// 货品详情
				buffSize: [],
				printNum: [],
				isReceiptSend: false,
				isLabelSend: false
			};
		},
		onReady(){
			let list = []
			let numList = []
			let j = 0
			for (let i = 20; i < 200; i += 10) {
			  list[j] = i;
			  j++
			}
			for (let i = 1; i < 10; i++) {
			  numList[i - 1] = i
			}
			this.buffSize = list;
			this.oneTimeData = list[0];
			this.printNum = numList;
			this.printerNum = numList[0];
		},
		onLoad(option) {
			this.detail = JSON.parse(option.data)
		},
		computed: {...mapState(['sysinfo', 'Bluetooth'])},
		onShow(){
			let that = this;
			const ctx = uni.createCanvasContext("edit_area_canvas", this);
			ctx.font = 'normal bold 20px sans-serif';
			ctx.setFillStyle('#171717'); // 文字颜色
			ctx.translate(0,0)
			ctx.rotate(90*Math.PI/180)
			ctx.fillText(that.detail.name, 20,-15); // 绘制文字
			ctx.draw();
		},
		methods:{
			// 返回
			handleBack(){
				uni.navigateBack({
					delta:3
				})
			},
			//标签测试
			labelTest(){
				let that = this;
				let canvasWidth = that.canvasWidth
				let canvasHeight = that.canvasHeight
				let command = tsc.jpPrinter.createNew()
				command.setSize(14, 40)
				command.setGap(0)
				command.setCls()
				command.setDensity(7)
				// command.setText(80, 40, "TSS24.BF2", 1, 1, "名称:驰腾贴贴乐")
				command.setBarCode(60, 20, "EAN128", 50, 0, 2, 2, that.detail.code)
				uni.canvasGetImageData({
				  canvasId: 'edit_area_canvas',
				  x: 0,
				  y: 0,
				  width: canvasHeight,
				  height: canvasWidth,
				  success: function(res) {
					command.setBitmap(60, 0, 1, res)
				  },
				  complete: function() {
					command.setPagePrint()
					that.isLabelSend = true;
					that.prepareSend(command.getData())
				  }
				})
			},
			//准备发送,根据每次发送字节数来处理分包数量
			prepareSend(buff){
				let that = this
				let time = that.oneTimeData
				let looptime = parseInt(buff.length / time);
				let lastData = parseInt(buff.length % time);
				this.looptime = looptime + 1;
				this.lastData = lastData;
				this.currentTime = 1;
				that.Send(buff)
			},
			//分包发送
			Send(buff){
				let that = this
				let {currentTime,looptime:loopTime,lastData,oneTimeData:onTimeData,printerNum:printerNum,currentPrint}=that;
				let buf;
				let dataView;
				if (currentTime < loopTime) {
				  buf = new ArrayBuffer(onTimeData)
				  dataView = new DataView(buf)
				  for (var i = 0; i < onTimeData; ++i) {
					dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
				  }
				} else {
				  buf = new ArrayBuffer(lastData)
				  dataView = new DataView(buf)
				  for (var i = 0; i < lastData; ++i) {
					dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
				  }
				}
				let {
					BLEInformation
				} = that.Bluetooth;
				uni.writeBLECharacteristicValue({
				  deviceId: BLEInformation.deviceId,
				  serviceId: BLEInformation.writeServiceId,
				  characteristicId: BLEInformation.writeCharaterId,
				  value: buf,
				  complete: function() {
					currentTime++
					if (currentTime <= loopTime) {
					  that.currentTime = currentTime;
					  that.Send(buff)
					} else {
					  if (currentPrint > printerNum) {
						that.looptime = 0;
						that.lastData = 0;
						that.currentTime = 1;
						that.isReceiptSend = false;
						that.isLabelSend = false;
						that.currentPrint = 1;
					  } else {
						uni.showToast({
						  	title: '已打印第' + currentPrint + '张',
						})
						currentPrint++;
						that.currentPrint = currentPrint;
						that.currentTime = 1;
						that.Send(buff)
					  }
					}
				  }
				})
			},
		},
		onUnload() {
			let that = this;
			let {
				BLEInformation
			} = that.Bluetooth;	
		},
	}
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐