uniapp连接佳博打印机实现蓝牙打印票据功能

news/2024/11/29 2:29:09/

开始实现搜索蓝牙。获取蓝牙设备。连接蓝牙设备等操作。代码如下 

<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 插件市场


http://www.ppmy.cn/news/653841.html

相关文章

Android 关于佳博和汉印蓝牙热敏打印机开发,安卓databinding

PrinterHelper.SetMag(“1”, “1”); PrinterHelper.SetBold(“0”); PrinterHelper.InverseLine(“0”, “0”, “700”, 《Android学习笔记总结最新移动架构视频大厂安卓面试真题项目实战源码讲义》 【docs.qq.com/doc/DSkNLaERkbnFoS0ZF】 完整内容开源分享 “0”, “100…

收银技术周刊第三期硬件篇--如何调整佳博打印机IP地址

目前市面上生产用于厨房热敏打印机的厂家有&#xff1a;佳博、芯烨、思普瑞特等厂家&#xff0c;我们今天讲解佳博打印机如何调整IP。 A&#xff1a;准备工作&#xff1a;1-3&#xff1a; 1、门店路由器要开启DHCP服务&#xff0c;以192.168.1.x段的地址来看&#xff0c;建议DH…

java使用佳博打印机打印标签

文章目录 1.前言1.1打印机型号及驱动说明1.2背景概要 2.填坑3.上代码1.项目截图2.中文打印需要注意两点3.项目源码 4.总结 1.前言 1.1打印机型号及驱动说明 打印机型号&#xff1a;佳博GP-3120TU打印机 标签纸规格&#xff1a;40mm*30mm 间隔2mm 驱动&#xff1a;佳博条码打…

Uniapp Android 佳博 小票打印机 插件

Uniapp Android 佳博 小票打印机 插件 Uniapp Android 佳博小票打印机插件: 支持图片、条型码、二维码 打印。 1. 实例化插件 const gp uni.requireNativePlugin(Html5App-Gprinter); 2.本插件包含4个方法 一、打开蓝牙搜索界面&#xff0c;搜索蓝牙打印机 ,setBackgrou…

佳博/芯桦打票机对接(含USB和网口)

佳博/芯桦打票机对接&#xff08;含USB和网口&#xff09; 记录一下最近实现的一个需求&#xff0c;用PHP远程连接芯桦、佳博打票机&#xff0c;代码还未进行优化&#xff0c;基本功能已经实现打印&#xff0c;具体打印指令需要查看佳博/芯桦的打票机指令&#xff0c;USB口打印…

佳博热敏条码打印机修改ip_佳博打印机修改IP教程.doc

佳博打印机修改IP教程.doc 佳博打印机修改IP教程本教程适用于80系列打印机及3150,9035打印自检测试页查看打印机的Ip步骤如下:GP80250以上系列打印机打印自检测试页:把打印机关机,按住FEED键再开机,等3秒左右,ERROR灯灭了放手即可GPL80160系列打印机打印自检测试页:把打…

【Android】Android 集成佳博80打印机打印票据

文章目录 【Android】Android 集成佳博80打印机打印票据1、集成佳博80打印机依赖2、规范调用接口3、使用到的相关对象以及工具类4、MainActivity初始化接口5、Uniapp调用方法 技术分享区 【Android】Android 集成佳博80打印机打印票据 1、集成佳博80打印机依赖 相关依赖在佳博…

JAVA使用springboot整合佳博标签打印机(一)

呕心沥血啊,这个打印机真好玩(反话)! 佳博打印机官网:http://cn.gainscha.com/gjxz.html 1.标题打印机品牌:佳博打印机 佳博有个官网,二次开发文件可以去管网下载,需要注意的是,他的示例只有一个条形码打印示例(不带下面的编号) 2.标签纸规格 左边条形码标签纸规格:10mm40mm…