wangfukang 3 years ago
parent
commit
e6f1579e5c
  1. 38
      components/kk-printer/index.vue
  2. 64
      components/kk-printer/utils/bluetoolth.js

38
components/kk-printer/index.vue

@ -125,18 +125,15 @@
uni.getSystemInfo({ uni.getSystemInfo({
success(res) { success(res) {
that.deviceType = res.osName that.deviceType = res.osName
console.log('设备类型', res.osName)
} }
}) })
// 初始化蓝牙模块 // 初始化蓝牙模块
wx.openBluetoothAdapter({ //111 wx.openBluetoothAdapter({ //111
mode: 'central', mode: 'central',
success: (res2) => { success: (res2) => {
console.log('初始化蓝牙模块', res2)
that.sousuo() that.sousuo()
}, },
fail: (res) => { fail: (res) => {
console.log('初始化蓝牙模块', res)
that.tui.toast('初始化失败', res) that.tui.toast('初始化失败', res)
this.isShowSearch = true this.isShowSearch = true
uni.hideLoading(); uni.hideLoading();
@ -149,16 +146,14 @@
let that = this; let that = this;
wx.startBluetoothDevicesDiscovery({ //222 wx.startBluetoothDevicesDiscovery({ //222
success(res3) { success(res3) {
console.log('获取设备成功', res3)
that.jiantingshebei() that.jiantingshebei()
}, },
fail(err) { fail(err) {
console.log('获取设备失败', err)
that.tui.toast('获取设备失败', err) that.tui.toast('获取设备失败', err)
wx.closeBLEConnection({ wx.closeBLEConnection({
deviceId: uni.getStorageSync('deviceId'), deviceId: uni.getStorageSync('deviceId'),
success(res) { success(res) {
console.log(res)
} }
}) })
uni.removeStorageSync('deviceId'); uni.removeStorageSync('deviceId');
@ -180,16 +175,13 @@
jiantingshebei() { jiantingshebei() {
let that = this; let that = this;
if (uni.getStorageSync('deviceId')) { if (uni.getStorageSync('deviceId')) {
console.log("111")
// that.huoqufuwu(uni.getStorageSync('deviceId')) // that.huoqufuwu(uni.getStorageSync('deviceId'))
that.lianejieshebei(uni.getStorageSync('deviceId')) that.lianejieshebei(uni.getStorageSync('deviceId'))
} else { } else {
console.log("222")
uni.hideLoading(); uni.hideLoading();
this.isShowSearch = true this.isShowSearch = true
// 监听扫描到新设备事件 // 监听扫描到新设备事件
wx.onBluetoothDeviceFound((res4) => { //333 wx.onBluetoothDeviceFound((res4) => { //333
console.log('监听新设备列表,拿到想要的就自动停止', res4)
res4.devices.forEach((device) => { res4.devices.forEach((device) => {
if (!device.name && !device.localName) { if (!device.name && !device.localName) {
return return
@ -207,11 +199,9 @@
deviceId: deviceId, // 搜索到设备的 deviceId deviceId: deviceId, // 搜索到设备的 deviceId
success: () => { success: () => {
that.isShowSearch = false that.isShowSearch = false
console.log('连接设备成功')
that.huoqufuwu(deviceId) that.huoqufuwu(deviceId)
}, },
fail: (res) => { fail: (res) => {
console.log('连接设备失败', res)
that.tui.toast('连接设备失败', res) that.tui.toast('连接设备失败', res)
if (uni.getStorageSync('deviceId')) { if (uni.getStorageSync('deviceId')) {
that.huoqufuwu(uni.getStorageSync('deviceId')) that.huoqufuwu(uni.getStorageSync('deviceId'))
@ -219,7 +209,7 @@
wx.closeBLEConnection({ wx.closeBLEConnection({
deviceId: uni.getStorageSync('deviceId'), deviceId: uni.getStorageSync('deviceId'),
success(res) { success(res) {
console.log(res)
} }
}) })
uni.removeStorageSync('deviceId') uni.removeStorageSync('deviceId')
@ -237,16 +227,16 @@
wx.getBLEDeviceServices({ //666 wx.getBLEDeviceServices({ //666
deviceId: deviceId, // 搜索到设备的 deviceId deviceId: deviceId, // 搜索到设备的 deviceId
success: (res5) => { success: (res5) => {
console.log('获取服务成功', res5)
that.duxietezhengzhi(deviceId, res5) that.duxietezhengzhi(deviceId, res5)
}, },
fail: (res) => { fail: (res) => {
console.log(res)
that.tui.toast('获取服务失败', res) that.tui.toast('获取服务失败', res)
wx.closeBLEConnection({ wx.closeBLEConnection({
deviceId: uni.getStorageSync('deviceId'), deviceId: uni.getStorageSync('deviceId'),
success(res1) { success(res1) {
console.log(res1)
} }
}) })
that.isShowSearch = true that.isShowSearch = true
@ -261,11 +251,11 @@
deviceId: deviceId, // 搜索到设备的 deviceId deviceId: deviceId, // 搜索到设备的 deviceId
serviceId: res5.services[0].uuid, // 上一步中找到的某个服务 serviceId: res5.services[0].uuid, // 上一步中找到的某个服务
success: (res6) => { success: (res6) => {
console.log('读写特征值成功', res6)
for (let i = 0; i < res6.characteristics.length; i++) { for (let i = 0; i < res6.characteristics.length; i++) {
let item = res6.characteristics[i] let item = res6.characteristics[i]
if (item.properties.write) { // 该特征值可写 if (item.properties.write) { // 该特征值可写
console.log('该特征值可写')
uni.setStorageSync('deviceId', deviceId); uni.setStorageSync('deviceId', deviceId);
uni.setStorageSync('serviceId', res5.services[0].uuid); uni.setStorageSync('serviceId', res5.services[0].uuid);
uni.setStorageSync('characteristicId', item.uuid); uni.setStorageSync('characteristicId', item.uuid);
@ -279,7 +269,7 @@
wx.closeBLEConnection({ wx.closeBLEConnection({
deviceId: uni.getStorageSync('deviceId'), deviceId: uni.getStorageSync('deviceId'),
success(res) { success(res) {
console.log(res)
} }
}) })
that.isShowSearch = true that.isShowSearch = true
@ -297,7 +287,7 @@
} else { } else {
that.$emit('onPrint'); that.$emit('onPrint');
} }
console.log('查看数据是否正确', that.bufferData)
that.$nextTick(() => { that.$nextTick(() => {
var dataStr = '' var dataStr = ''
for (let m = 0; m < that.bufferData.length; m++) { for (let m = 0; m < that.bufferData.length; m++) {
@ -323,19 +313,19 @@
characteristicId: uni.getStorageSync('characteristicId'), characteristicId: uni.getStorageSync('characteristicId'),
value: buffer, value: buffer,
success(res) { success(res) {
console.log('打印buffer', buffer)
console.log('writeBLECharacteristicValue success', res)
}, },
fail(res) { fail(res) {
console.log('writeBLECharacteristicValue fail', res)
wx.closeBLEConnection({ wx.closeBLEConnection({
deviceId: uni.getStorageSync('deviceId'), deviceId: uni.getStorageSync('deviceId'),
success(res) { success(res) {
console.log(res)
} }
}) })
if (uni.getStorageSync('deviceId')) { if (uni.getStorageSync('deviceId')) {
console.log("111")
that.xierushuju() that.xierushuju()
} else { } else {
that.jiantingshebei() that.jiantingshebei()

64
components/kk-printer/utils/bluetoolth.js

@ -33,7 +33,7 @@ export function openBlue() {
//搜索蓝牙设备 //搜索蓝牙设备
export function startBluetoothDevicesDiscovery(option) { export function startBluetoothDevicesDiscovery(option) {
uniAsyncPromise('startBluetoothDevicesDiscovery', option).then((res) => { uniAsyncPromise('startBluetoothDevicesDiscovery', option).then((res) => {
console.log('正在搜寻蓝牙设备', res);
}); });
} }
@ -52,7 +52,7 @@ export function onfindBlueDevices(getDevices) {
uni.onBluetoothDeviceFound((devices)=>{ uni.onBluetoothDeviceFound((devices)=>{
//获取在蓝牙模块生效期间所有已发现的蓝牙设备 //获取在蓝牙模块生效期间所有已发现的蓝牙设备
uniAsyncPromise('getBluetoothDevices').then((res) => { uniAsyncPromise('getBluetoothDevices').then((res) => {
console.log('res这里',res.devices)
getDevices && getDevices(res.devices); getDevices && getDevices(res.devices);
}); });
}); });
@ -65,7 +65,7 @@ export function onfindBlueDevices(getDevices) {
export function stopBlueDevicesDiscovery() { export function stopBlueDevicesDiscovery() {
//监听寻找到新设备的事件 //监听寻找到新设备的事件
return uniAsyncPromise('stopBluetoothDevicesDiscovery').then((res) => { return uniAsyncPromise('stopBluetoothDevicesDiscovery').then((res) => {
console.log('停止搜寻蓝牙设备', res);
}); });
} }
@ -85,13 +85,13 @@ export function createBLEConnection(deviceId, sucess, fail) {
.then(res => { .then(res => {
//连接成功可选择停止搜索蓝牙 //连接成功可选择停止搜索蓝牙
//stopBlueDevicesDiscovery(); //stopBlueDevicesDiscovery();
console.log('连接成功');
sucess && sucess({ sucess && sucess({
res: res, res: res,
}); });
}) })
.catch(res => { .catch(res => {
console.log('连接设备异常' + JSON.stringify(res));
fail && fail({ fail && fail({
res: res, res: res,
}); });
@ -104,31 +104,31 @@ export function closeBLEConnection(deviceId) {
deviceId deviceId
}) })
.then(res => { .then(res => {
console.log('BLEDisconnect complete', res);
}) })
.catch(res => { .catch(res => {
console.log('断开设备异常' + res);
}) })
} }
//四、连接成功后, 获取蓝牙设备的service服务 //四、连接成功后, 获取蓝牙设备的service服务
// uniAsyncPromise("getBLEDeviceServices",{deviceId:""}).then(res=>{}) // uniAsyncPromise("getBLEDeviceServices",{deviceId:""}).then(res=>{})
export function getBLEDeviceServices(deviceId, success, fail) { export function getBLEDeviceServices(deviceId, success, fail) {
console.log('获取ServiceId', deviceId);
//加延迟避免取不到service //加延迟避免取不到service
setTimeout(()=>{ setTimeout(()=>{
uniAsyncPromise("getBLEDeviceServices", { uniAsyncPromise("getBLEDeviceServices", {
deviceId: uni.getStorageSync('deviceId')?uni.getStorageSync('deviceId'):deviceId deviceId: uni.getStorageSync('deviceId')?uni.getStorageSync('deviceId'):deviceId
}) })
.then(res => { .then(res => {
console.log('服务', res);
success && success({ success && success({
serviceId: res.services, serviceId: res.services,
}); });
}) })
.catch((res) => { .catch((res) => {
//getBLEDeviceServices(deviceId, success, fail); //getBLEDeviceServices(deviceId, success, fail);
console.log('获取ServiceId异常' + res);
fail && fail({ fail && fail({
res: res, res: res,
}); });
@ -147,10 +147,10 @@ export function getBLEDeviceServices(deviceId, success, fail) {
*/ */
export function getDeviceCharacteristics(deviceId, services, success, fail) { export function getDeviceCharacteristics(deviceId, services, success, fail) {
//services = services.slice(0); //services = services.slice(0);
console.log('获取Characteristics', deviceId, services);
if (services.length) { if (services.length) {
const serviceId = services.shift().uuid; const serviceId = services.shift().uuid;
console.log('ServceID ', serviceId);
uniAsyncPromise('getBLEDeviceCharacteristics', { uniAsyncPromise('getBLEDeviceCharacteristics', {
deviceId, deviceId,
serviceId, serviceId,
@ -197,15 +197,15 @@ export function getDeviceCharacteristics(deviceId, services, success, fail) {
* @param {function} onChange 监听蓝牙设备传递数据回调函数 * @param {function} onChange 监听蓝牙设备传递数据回调函数
*/ */
export function onGetBLECharacteristicValueChange(options, onChange = function() {}) { export function onGetBLECharacteristicValueChange(options, onChange = function() {}) {
console.log('deviceId ', options.deviceId);
console.log('serviceId ', options.serviceId);
console.log('characteristicId ', options.characteristicId);
console.log('苹果手机看这里');
uniAsyncPromise('notifyBLECharacteristicValueChange', { uniAsyncPromise('notifyBLECharacteristicValueChange', {
state: true, state: true,
...options, ...options,
}).then((res) => { }).then((res) => {
console.log('onBLECharacteristicValueChange ');
uni.onBLECharacteristicValueChange(onChange); uni.onBLECharacteristicValueChange(onChange);
}); });
} }
@ -228,26 +228,26 @@ export function sendDataToDevice(options) {
let byteLength = options.value.byteLength; let byteLength = options.value.byteLength;
//这里默认一次20个字节发送 //这里默认一次20个字节发送
const speed = options.onceLength; //20; const speed = options.onceLength; //20;
console.log(options);
if (byteLength > 0) { if (byteLength > 0) {
uniAsyncPromise('writeBLECharacteristicValue', { uniAsyncPromise('writeBLECharacteristicValue', {
...options, ...options,
value: options.value.slice(0, byteLength > speed ? speed : byteLength), value: options.value.slice(0, byteLength > speed ? speed : byteLength),
}) })
.then((res) => { .then((res) => {
console.log('发送数据成功了',res)
if (byteLength > speed) { if (byteLength > speed) {
sendDataToDevice({ sendDataToDevice({
...options, ...options,
value: options.value.slice(speed, byteLength), value: options.value.slice(speed, byteLength),
}); });
} else { } else {
console.log("打印完成")
options.lasterSuccess && options.lasterSuccess(); options.lasterSuccess && options.lasterSuccess();
} }
}) })
.catch((res) => { .catch((res) => {
console.log('打印错误了',res)
uni.showToast({ uni.showToast({
title: res, title: res,
icon: 'none' icon: 'none'
@ -373,10 +373,10 @@ export function printImage(opt = {}, imageInfo = {}) {
writeArray.push(new Uint8Array(tempArr)); writeArray.push(new Uint8Array(tempArr));
} }
writeArray.push(new Uint8Array(enter)); writeArray.push(new Uint8Array(enter));
//console.log(writeArray);
const print = (options, writeArray) => { const print = (options, writeArray) => {
if (writeArray.length) { if (writeArray.length) {
console.log("send");
sendDataToDevice({ sendDataToDevice({
...options, ...options,
value: writeArray.shift().buffer, value: writeArray.shift().buffer,
@ -390,7 +390,7 @@ export function printImage(opt = {}, imageInfo = {}) {
}); });
} }
}; };
console.log("start print");
print(opt, writeArray); print(opt, writeArray);
} }
@ -434,7 +434,7 @@ export function CreatCPCLPage(width, height, printNum, rotation, offset = 0) {
* content: 文字内容 * content: 文字内容
*/ */
export function addCPCLText(x, y, fontName, fontSize, rotation, content) { export function addCPCLText(x, y, fontName, fontSize, rotation, content) {
//console.log(fontName,fontSize,rotation, content);
// alert(content); // alert(content);
var strCmd = ''; var strCmd = '';
if (rotation == 1) { if (rotation == 1) {
@ -582,7 +582,7 @@ export function addCPCLBACKGROUND(level) {
* content: 文字内容 * content: 文字内容
*/ */
export function addCPCLBKVText(x, y, fontName, fontSize, rotation, content) { export function addCPCLBKVText(x, y, fontName, fontSize, rotation, content) {
//console.log(fontName,fontSize,rotation, content);
var strCmd = ''; var strCmd = '';
if (rotation == 1) { if (rotation == 1) {
strCmd += 'BKT90 '; strCmd += 'BKT90 ';
@ -649,16 +649,16 @@ export function addCPCLImageCmd(x, y, data) {
let myBitmapWidth = data.width, let myBitmapWidth = data.width,
myBitmapHeight = data.height; myBitmapHeight = data.height;
let len = parseInt((myBitmapWidth + 7) / 8); //一行的数据长度 let len = parseInt((myBitmapWidth + 7) / 8); //一行的数据长度
//console.log('len=',len);
//console.log('myBitmapWidth=',myBitmapWidth);
//console.log('myBitmapHeight=',myBitmapHeight);
let ndata = 0; let ndata = 0;
let i = 0; let i = 0;
let j = 0; let j = 0;
let sendImageData = new ArrayBuffer(len * myBitmapHeight); let sendImageData = new ArrayBuffer(len * myBitmapHeight);
sendImageData = new Uint8Array(sendImageData); sendImageData = new Uint8Array(sendImageData);
let pix = data.imageData; let pix = data.imageData;
console.log('pix=', pix);
for (i = 0; i < myBitmapHeight; i++) { for (i = 0; i < myBitmapHeight; i++) {
for (j = 0; j < len; j++) { for (j = 0; j < len; j++) {
@ -672,14 +672,14 @@ export function addCPCLImageCmd(x, y, data) {
} }
ndata += len; ndata += len;
} }
//console.log('sendImageData=',sendImageData);
//CPCL指令图片数据 //CPCL指令图片数据
strImgCmd += 'EG ' + len + ' ' + myBitmapHeight + ' ' + x + ' ' + y + ' '; strImgCmd += 'EG ' + len + ' ' + myBitmapHeight + ' ' + x + ' ' + y + ' ';
for (i = 0; i < sendImageData.length; i++) { for (i = 0; i < sendImageData.length; i++) {
strImgCmd += Hex2Str(sendImageData[i]); strImgCmd += Hex2Str(sendImageData[i]);
} }
strImgCmd += '\n'; strImgCmd += '\n';
//console.log(strImgCmd);
return strImgCmd; return strImgCmd;
} }
/** /**

Loading…
Cancel
Save