开始实现搜索蓝牙。获取蓝牙设备。连接蓝牙设备等操作。代码如下
<template><view class="content"><button class="btn" type="primary" :loading="isSearching" @tap="startSearch">开始搜索 </button><button class="btn" type="warn" @tap="stopSearch">停止搜索</button><view v-for="(item) in list" :data-title="item.deviceId" :data-name="item.name" :data-advertisData="item.advertisServiceUUIDs":key="item.deviceId" @tap="bindViewTap"><view class="item"><view class="deviceId block">{{item.deviceId}}</view><view class="name block">{{item.name}}</view></view></view></view>
</template><script>import {mapState} from 'vuex';export default {data() {return {isSearching: false, //是否正在搜索中list: [],services: [],serviceId: 0,writeCharacter: false,readCharacter: false,notifyCharacter: false};},computed: mapState(['sysinfo', 'Bluetooth']),onLoad() {// console.log(this.Bluetooth)},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'})}},//开始搜索蓝牙startSearch() {let that = thisuni.openBluetoothAdapter({success(res) {uni.getBluetoothAdapterState({success(res2) {console.log('getBluetoothAdapterState:', 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: '蓝牙初始化失败,请打开蓝牙',})}})},stopSearch() {uni.stopBluetoothDevicesDiscovery({success: (res) => {this.isSearching = false;console.log('stop:', res)},fail: (e) => {console.log('stop:', e)this.errorCodeTip(e.errCode);}})},//校验权限checkPemission() {let that = thislet {BLEInformation} = that.Bluetooth;let platform = BLEInformation.platform;that.getBluetoothDevices();},//获取蓝牙设备信息getBluetoothDevices() {let that = thisthat.list = [];uni.startBluetoothDevicesDiscovery({success(res) {// console.log(res)//蓝牙设备监听 uni.onBluetoothDeviceFoundplus.bluetooth.onBluetoothDeviceFound((result) => {console.log('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;});// console.log('arrNew:',arrNew.length)if (arrNew.length == 0) {devices.push(list[i]);}}}that.list = arr.concat(devices);});that.time = setTimeout(() => {// uni.getBluetoothDevicesplus.bluetooth.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;console.log('getBluetoothDevices:',res2);},})clearTimeout(that.time);}, 3000);}});},//绑定蓝牙bindViewTap(e) {let that = this;let {title} = e.currentTarget.dataset;let {BLEInformation} = that.Bluetooth;this.stopSearch();that.serviceId = 0;that.writeCharacter = false;that.readCharacter = false;that.notifyCharacter = false;uni.showLoading({title: '正在连接',})console.log('deviceId:', title)// uni.createBLEConnectionplus.bluetooth.createBLEConnection({deviceId: title,success(res) {console.log('createBLEConnection success:', res)BLEInformation.deviceId = title;that.$store.commit('BLEInformationSet', BLEInformation);uni.hideLoading()that.getSeviceId()},fail(e) {that.errorCodeTip(e.errCode);uni.hideLoading()}})},//获取蓝牙设备所有服务(service)。getSeviceId() {let that = this;let {BLEInformation} = that.Bluetooth;console.log('BLEInformation.deviceId:',BLEInformation.deviceId)// uni.getBLEDeviceServiceslet t=setTimeout(()=>{plus.bluetooth.getBLEDeviceServices({deviceId: BLEInformation.deviceId,success(res) {console.log('getBLEDeviceServices success:',res)that.services = res.services;that.getCharacteristics()},fail: function(e) {that.errorCodeTip(e.code); console.log('getBLEDeviceServices fail:',e)}})clearTimeout(t);},1500)},getCharacteristics() {var that = thislet {services: list,serviceId: num,writeCharacter: write,readCharacter: read,notifyCharacter: notify} = that;let {BLEInformation} = that.Bluetooth;// uni.getBLEDeviceCharacteristicsplus.bluetooth.getBLEDeviceCharacteristics({deviceId: BLEInformation.deviceId,serviceId: list[num].uuid,success(res) {// console.log(res)for (var i = 0; i < res.characteristics.length; ++i) {var properties = res.characteristics[i].propertiesvar item = res.characteristics[i].uuidif (!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) {console.log("getBLEDeviceCharacteristics fail:",e);that.errorCodeTip(e.errCode); }})},openControl: function() {uni.navigateTo({url: '/pages/sendCommand/sendCommand',})},}}
</script><style lang="less">.btn {margin-top: 50rpx;height: 40px;width: 600rpx;line-height: 40px;}.item {display: block;font-family: Arial, Helvetica, sans-serif;font-size: 14px;margin: 0 30px;margin-top: 10px;background-color: #FFA850;border-radius: 5px;border-bottom: 2px solid #68BAEA;}.block {display: block;color: #ffffff;padding: 5px;}
</style>
在store index.js注入全局所需要监听的而蓝牙设备的信息等
let sysinfo = uni.getSystemInfoSync();
const Bluetooth = {state: {//蓝牙信息BLEInformation: {platform: sysinfo.platform || "",deviceId: "",writeCharaterId: "",writeServiceId: "",notifyCharaterId: "",notifyServiceId: "",readCharaterId: "",readServiceId: "",}},mutations:{BLEInformationSet(state, info){state.BLEInformation = info;}}
}export default Bluetooth;
在就是实现打印的操作。对指令进行操作(有js转化指令,js包在资源管理中自行下载)实现小票功能(一般打印机初始字节是20)。因为是动态小票在此是接收模板string.利用eval()转化为js实现。
<template><view class="content"><view class="body"><view style='margin-top:4%;display: flex;flex-direction: row;'><button type='primary' @tap='receiptTest' :loading='isReceiptSend' :disabled='isReceiptSend'>打印</button></view></view></view>
</template><script>import { mapActions } from 'vuex';var tsc = require("../compontents/ble/tsc.js");var esc = require("../compontents/ble/esc.js");var encode = require("../compontents/ble/encoding.js");import {mapState} from 'vuex';export default {data() {return {sendContent: "",looptime: 0,currentTime: 1,lastData: 0,oneTimeData: 20,buffSize: [],buffIndex: 0,printNum: [],printerNum: 1,currentPrint: 1,isReceiptSend: false,moudlestr:'',};},computed: mapState(['sysinfo', 'Bluetooth']),onLoad(options) {let that = this;let {BLEInformation} = that.Bluetooth;that.getStr()that.printData=JSON.parse(decodeURIComponent(options.obj))},onUnload() {let that = this;let {BLEInformation} = that.Bluetooth;},methods:{...mapActions(['majax', 'goout']),getStr(){ this.majax({ url: this.$local + 'system/bluetooth/mould/getInfoByDjlx', params: { djlx: 'SPYCD' }, method: 'get' }).then(res => {console.log('res',res)if (res.code == 0) {console.log('res',res)this.moudlestr=res.data.mouldStr}})},//票据测试receiptTest(){var that = this;// var canvasWidth = that.canvasWidth// var canvasHeight = that.canvasHeight// var command = esc.jpPrinter.createNew()// command.init()let data = that.printDataeval(this.moudlestr)command.setPrintAndFeedRow(3);that.isReceiptSend = true;console.log(command.getData())that.prepareSend(command.getData());},//准备发送,根据每次发送字节数来处理分包数量prepareSend(buff){console.log(buff);let that = thisthat.tryTimes=10000;let time = that.oneTimeDatalet looptime = parseInt(buff.length / time);let lastData = parseInt(buff.length % time);console.log(looptime + "---" + lastData)this.looptime = looptime + 1;this.lastData = lastData;this.currentTime = 1;that.Send(buff)},//查询打印机状态queryStatus(){let command = esc.jpPrinter.Query();command.getRealtimeStatusTransmission(1);},//分包发送Send(buff){let that = thislet {currentTime,looptime:loopTime,lastData,oneTimeData:onTimeData,printerNum:printNum,currentPrint,tryTimes:tryTimes}=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])}}console.log("第" + currentTime + "次发送数据大小为:" + buf.byteLength)let {BLEInformation} = that.Bluetooth;console.log(BLEInformation.deviceId)plus.bluetooth.writeBLECharacteristicValue({deviceId: BLEInformation.deviceId,serviceId: BLEInformation.writeServiceId,characteristicId: BLEInformation.writeCharaterId,value: buf,success: function(res) {console.log(res)currentTime++if (currentTime <= loopTime) {that.currentTime = currentTime;that.Send(buff)} else {uni.showToast({title: '已打印第' + currentPrint + '张',})if (currentPrint == printNum) {that.looptime = 0;that.lastData = 0;that.currentTime = 1;that.isReceiptSend = false;that.currentPrint = 1;} else {currentPrint++;that.currentPrint = currentPrint;that.currentTime = 1;that.Send(buff)}}},fail: function(e) {console.log('fail',e)if(tryTimes>0){that.Send(buff)}},complete: function(e) {tryTimes--console.log('fail',e)}})},}}
</script><style lang="less"></style>
具体是参考
Android、IOS 佳博 蓝牙小票 、标签 打印模板 - DCloud 插件市场