评论

小程序蓝牙打印爬坑,使用TSPL指令集

使用TSPL指令集的蓝牙打印全过程,借鉴与CSDN上各位大神

说明:1把尺子、一个支持TSPL指令集的手持蓝牙打印机
以3058标签纸和芯烨打印机举例 1mm等于dots,所以整个标签纸宽高分别为
30
7 和 58*7。用尺子判断默认大小的英文字体为2mm,中文字体为3mm

爬坑过程全靠CSDN各位大神,结合CSDN多家神之精华完成。除了打印图片慢或者直接不能打印外,其他玩起来的感觉都能流畅。tsc.js中需要的encoding.js和encoding-indexes.js可以去CSDN中找

tsc.js --------------------
var app = getApp();
var encode = require("./encoding.js");
var util = require(’…/utils/util.js’)
var jpPrinter = {
createNew: function() {
var jpPrinter = {};
var data = “”;
var command = []

jpPrinter.name = "蓝牙打印机";

jpPrinter.init = function() {};

jpPrinter.addCommand = function(content) { //将指令转成数组装起
  var code = new encode.TextEncoder('gb18030', {NONSTANDARD_allowLegacyEncoding: true}).encode(content)
  for (var i = 0; i < code.length; ++i) {
    command.push(code[i])
  }
}
//SIZE mmm, nmm ;mmm:标签纸的宽度,单位为毫米;nmm:标签纸的高度,单位为毫米。
jpPrinter.setSize = function(pageWidght, pageHeight) { //设置页面大小
  data = "SIZE " + pageWidght.toString() + " mm" + "," + pageHeight.toString() + " mm" + "\r\n";
  jpPrinter.addCommand(data)
};

jpPrinter.setSpeed = function(printSpeed) { //设置打印机速度
  data = "SPEED " + printSpeed.toString() + "\r\n";
  jpPrinter.addCommand(data)
};

jpPrinter.setDensity = function(printDensity) { //设置打印机浓度
  data = "DENSITY " + printDensity.toString() + "\r\n";
  jpPrinter.addCommand(data)
};
//mmm:标签间的垂直间距,单位为毫米。GAP mmm
jpPrinter.setGap = function(printGap) { //传感器
  data = "GAP " + printGap.toString() + " mm\r\n";
  jpPrinter.addCommand(data)
};

jpPrinter.setBline = function(printBline) { //黑标纸
  data = "BLINE " + printBline.toString() + " mm,0 mm\r\n";
  jpPrinter.addCommand(data)
};

jpPrinter.setCountry = function(country) { //选择国际字符集
  data = "COUNTRY " + country + "\r\n";
  jpPrinter.addCommand(data)
};

jpPrinter.setCodepage = function(codepage) { //选择国际代码页
  data = "CODEPAGE " + codepage + "\r\n";
  jpPrinter.addCommand(data)
}

jpPrinter.setCls = function() { //清除打印机缓存
  data = "CLS\r\n";
  jpPrinter.addCommand(data)
};

jpPrinter.setFeed = function(feed) { //将纸向前推出n
  data = "FEED " + feed + "\r\n";
  jpPrinter.addCommand(data)
};

jpPrinter.setBackFeed = function(backup) { //将纸向后回拉n
  data = "BACKFEED " + backup + "\r\n";
  jpPrinter.addCommand(data)
}

jpPrinter.setDirection = function(direction) { //设置打印方向,参考编程手册  
  data = "DIRECTION " + direction + "\r\n";
  jpPrinter.addCommand(data)
};

jpPrinter.setReference = function(x, y) { //设置坐标原点,与打印方向有关
  data = "REFERENCE " + x + "," + y + "\r\n";
  jpPrinter.addCommand(data)
};

jpPrinter.setFromfeed = function() { //根据Size进一张标签纸
  data = "FORMFEED\r\n";
  jpPrinter.addCommand(data)
};

jpPrinter.setHome = function() { //根据Size找到下一张标签纸的位置
  data = "HOME\r\n";
  jpPrinter.addCommand(data)
};

jpPrinter.setSound = function(level, interval) { //控制蜂鸣器
  data = "SOUND " + level + "," + interval + "\r\n";
  jpPrinter.addCommand(data)
};

jpPrinter.setLimitfeed = function(limit) { // 检测垂直间距
  data = "LIMITFEED " + limit + "\r\n";
  jpPrinter.addCommand(data)
};

jpPrinter.setBar = function(x, y, width, height) { //绘制线条
  data = "BAR " + x + "," + y + "," + width + "," + height + "\r\n"
  jpPrinter.addCommand(data)
};

jpPrinter.setBox = function(x_start, y_start, x_end, y_end, thickness) { //绘制方框
  data = "BOX " + x_start + "," + y_start + "," + x_end + "," + y_end + "," + thickness + "\r\n";
  jpPrinter.addCommand(data)
};

jpPrinter.setErase = function(x_start, y_start, x_width, y_height) { //清除指定区域的数据
  data = "ERASE " + x_start + "," + y_start + "," + x_width + "," + y_height + "\r\n";
  jpPrinter.addCommand(data)
};

jpPrinter.setReverse = function(x_start, y_start, x_width, y_height) { //将指定的区域反相打印
  data = "REVERSE " + x_start + "," + y_start + "," + x_width + "," + y_height + "\r\n";
  jpPrinter.addCommand(data)
};
//TEXT x,y,"font",rotation,x-multiplication,y-multiplication,"content"
// x:文本X方向起始点坐标。
// y:文本Y方向起始点坐标。
// "font":字体名称和大小,如"TSS24.BF2"表示简体中文24x24字体。
// rotation:文本旋转角度,以度为单位。
// x-multiplication 和 y-multiplication:文本在X和Y方向上的放大倍率。
// "content":要打印的文本内容。
jpPrinter.setText = function(x, y, font, x_, y_, str) { //打印文字
  data = "TEXT " + x + "," + y + ",\"" + font + "\"," + 0 + "," + x_ + "," + y_ + "," + "\"" + str + "\"\r\n"
  jpPrinter.addCommand(data)
};

jpPrinter.setQR = function(x, y, level, width, mode, content) { //打印二维码
  data = "QRCODE " + x + "," + y + "," + level + "," + width + "," + mode + "," + 0 + ",\"" + content + "\"\r\n"
  jpPrinter.addCommand(data)
};
//BARCODE X, Y, "code type", height, human readable, rotation, narrow, wide, "code"
// X 和 Y:条形码左上角的X和Y坐标值。
// "code type":条形码类型,如CODE39、CODE128等。
// height:条形码的高度。
// human readable:是否在条形码下方显示可读的文本,一般为"Y"或"N"。
// rotation:条形码的旋转角度。
// narrow 和 wide:定义条形码中窄条和宽条的宽度比例。
// "code":要编码的文本内容。
jpPrinter.setBarCode = function(x, y, codetype, height, readable, narrow, wide, content) { //打印条形码
  data = "BARCODE " + x + "," + y + ",\"" + codetype + "\"," + height + "," + readable + "," + 0 + "," + narrow + "," + wide + ",\"" + content + "\"\r\n"
  jpPrinter.addCommand(data)
};

jpPrinter.setBitmap = function(x, y, mode, res) { //添加图片,res为画布参数
  console.log(res)
  var width = parseInt((res.width + 7) / 8 * 8 / 8)
  var height = res.height;
  var time = 1;
  var temp = res.data.length - width * 32;
  var pointList = []
  var inverted_Data = []
  var correct_Data = []
  console.log(width + "--" + height)
  data = "BITMAP " + x + "," + y + "," + width + "," + height + "," + mode + ","
  jpPrinter.addCommand(data)
  for (var i = 0; i < height; ++i) {
    console.log(temp)
    for (var j = 0; j < width; ++j) {
      for (var k = 0; k < 32; k += 4) {
        if (res.data[temp] == 0 && res.data[temp + 1] == 0 && res.data[temp + 2] == 0 && res.data[temp + 3] == 0) {
          pointList.push(1)
        } else {
          pointList.push(0)
        }
        temp += 4
      }
    }
    time++
    temp = res.data.length - width * 32 * time
  }
  for (var i = 0; i < pointList.length; i += 8) {
    var p = pointList[i] * 128 + pointList[i + 1] * 64 + pointList[i + 2] * 32 + pointList[i + 3] * 16 + pointList[i + 4] * 8 + pointList[i + 5] * 4 + pointList[i + 6] * 2 + pointList[i + 7]
    inverted_Data.push(p)
    correct_Data.push(p)
  }
  for (var i = height; i > 0; i--) {
    for (var j = 0; j < width; ++j) {
      correct_Data[(height - i - 1) * width + j] = inverted_Data[i * width + j]
    }
  }
  for (var i = 0; i < correct_Data.length; ++i) {
    command.push(correct_Data[i])
  }
}

jpPrinter.setPagePrint = function() { //打印页面
  data = "PRINT 1,1\r\n"
  jpPrinter.addCommand(data)
};
//获取打印数据
jpPrinter.getData = function() {
  return command;
};  
return jpPrinter; 

}
};
function PrintTextCenter(x, data, y) {
let len = util.getByteLength3040(data, y)
let res = (x - len - 2) / 2 * 7 //-2是标签两边边距
return res.toFixed(0)
}
function PrintTextLeft(x, data, y, z) {
let len = util.getByteLength3040(data)
let res = (x - len - 2 - z - y) * 7 //-2是标签两边边距,y是距离左侧距离,z是如果左侧有数据就+上左侧数据距离左侧边距的距离
return res.toFixed(0)
}
function PrintTextRight(x, data, y) {
let len = util.getByteLength3040(data, y) //y是否放大倍数
let res = (x - len - 2) * 7
return res.toFixed(0)
}

// function StockSeal3058(detailBase){
// let command = jpPrinter.createNew();
// command.setSize(58, 30);
// command.setDirection(1);
// command.setGap(2);
// command.setCls();
// command.setText(176, 7.5, ‘TSS24.BF2’, 1, 1, ‘库存封箱’); //高度30
// command.setText(173, 37.5, ‘TSS24.BF2’, 1, 1, ‘库存封箱’); //高度30
// command.setText(8, 184.5, ‘TSS24.BF2’, 1, 1, ‘库存封箱’); //高度30
// command.setText(342, 184.5, ‘TSS24.BF2’, 1, 1, ‘库存封箱’); //高度30
// command.setPagePrint()

// return command
// }

function errCode(code){
if( code == 10000 ){
return “未初始化蓝牙适配器”
}
if( code == 10001 ){
return “当前蓝牙适配器不可用”
}
if( code == 10002 ){
return “未找到指定设备”
}
if( code == 10003 ){
return “连接失败”
}
if( code == 10005 ){
return “没有找到指定特征”
}
if( code == 10004 ){
return “没有找到指定服务”
}
if( code == 10009 ){
return “Android 系统特有,系统版本低于 4.3 不支持 BLE”
}
if( code == 10006 ){
return “当前连接已断开”
}
if( code == 10012 ){
return “连接超时”
}
}
module.exports = {
jpPrinter,
errCode,
StockSeal3058
}

index.js 打印页面-----------------
data:{
looptime: 0,
currentTime: 1,
lastData: 0,
buffSize: [],
printNum: [],
printerNum: 1,
currentPrint: 1,
isReceiptSend: false,
isLabelSend: false,
detailBase: ‘’,
}
onShow() {
//这一段代码一定要放在onshow里面
const bleInfo = wx.getStorageSync(‘bleItem’);
this.setData({
bleInfo: bleInfo ? bleInfo : {}
}, () => {
// 如果已经有连接的蓝牙设备,直接连接
if (Object.keys(this.data.bleInfo).length !== 0) {
this.createBLEConnectionWithDeviceId()
}
})
},
// 创建连接
_createBLEConnection(deviceId, item) {
const that = this;
wx.createBLEConnection({
deviceId: deviceId,
success: function (res) {
console.log(res)
wx.setStorageSync(‘bleItem’, item);
// that.getSeviceId(deviceId)
},
fail: function (e) {
console.log(‘createBLEConnection fail’, e)
},
complete: function (e) {
wx.hideLoading()
}
})
},
// 创建蓝牙连接
// 小程序在之前已有搜索过某个蓝牙设备,并成功建立连接,可直接传入之前搜索获取的 deviceId 直接尝试连接该设备
createBLEConnectionWithDeviceId() {
const device = this.data.bleInfo;
if (!device) {
return;
}
const deviceId = device.deviceId;
console.log(‘createBLEConnectionWithDeviceId’, deviceId)
wx.openBluetoothAdapter({
success: (res) => {
console.log(‘openBluetoothAdapter success’, res)
this._createBLEConnection(deviceId, device)
},
fail: (res) => {
console.log(‘openBluetoothAdapter fail’, res)
if (res.errCode === 10001) {
wx.showModal({
title: ‘错误’,
content: ‘未找到蓝牙设备, 请打开蓝牙后重试。’,
showCancel: false
})
wx.onBluetoothAdapterStateChange((res) => {
console.log(‘onBluetoothAdapterStateChange’, res)
// 蓝牙适配器是否可用
if (res.available) {
// 取消监听,否则stopBluetoothDevicesDiscovery后仍会继续触发onBluetoothAdapterStateChange,
// 导致再次调用startBluetoothDevicesDiscovery
wx.onBluetoothAdapterStateChange(() => {});
this._createBLEConnection(deviceId, device)
}
})
}
}
})
},
onReady: function () {
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.setData({
buffSize: list,
oneTimeData: list[0],
printNum: numList,
printerNum: numList[0]
})
},
// 标签打印
labelPrint() {
//如果未连接打印机,跳转到连接打印机页面
if (Object.keys(this.data.bleInfo).length === 0) {
wx.showModal({
title: ‘温馨提示’,
content: ‘当前蓝牙设备未连接’,
confirmText: ‘去连接’,
complete: (res) => {
if (res.confirm) {
wx.navigateTo({
url: “…/…/…/yg/pages/connect/connect”
})
}
}
})
return;
}
let self = this;
let detailBase = self.data.detailBase
detailBase.time = util.formatTime(new Date())
let command = tsc.StockSeal3058(detailBase)
self.setData({
isLabelSend: true
})
self.prepareSend(command.getData())
},
//准备发送,根据每次发送字节数来处理分包数量
prepareSend: function (buff) {
console.log(buff)
let self = this;
let time = self.data.oneTimeData;
let looptime = parseInt(buff.length / time);
let lastData = parseInt(buff.length % time);
console.log(looptime + ‘—’ + lastData)
self.setData({
looptime: looptime + 1,
lastData: lastData,
currentTime: 1,
})
self.Send(buff)
},
//分包发送
Send: function (buff) {
let self = this;
let currentTime = self.data.currentTime;
let loopTime = self.data.looptime;
let lastData = self.data.lastData;
let onTimeData = self.data.oneTimeData;
let printNum = self.data.printerNum;
let currentPrint = self.data.currentPrint;
let buf;
let dataView;
if (currentTime < loopTime) {
buf = new ArrayBuffer(onTimeData)
dataView = new DataView(buf)
for (let i = 0; i < onTimeData; ++i) {
dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
}
} else {
buf = new ArrayBuffer(lastData)
dataView = new DataView(buf)
for (let i = 0; i < lastData; ++i) {
dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
}
}

const bleWriteInfo = wx.getStorageSync('bleWriteInfo');
console.log(bleWriteInfo, 'bleWriteInfo=====')
wx.writeBLECharacteristicValue({
  deviceId: this.data.bleInfo.deviceId,
  serviceId: bleWriteInfo.writeServiceId,
  characteristicId: bleWriteInfo.writeCharaterId,
  value: buf,
  success: function (res) {
    currentTime++
    if (currentTime <= loopTime) {
      self.setData({
        currentTime: currentTime
      })
      self.Send(buff)
    } else {
      wx.hideLoading()
      self.wc()
      if (currentPrint == printNum) {
        self.setData({
          looptime: 0,
          lastData: 0,
          currentTime: 1,
          isReceiptSend: false,
          isLabelSend: false,
          currentPrint: 1
        })
      } else {
        currentPrint++
        self.setData({
          currentPrint: currentPrint,
          currentTime: 1,
        })
        self.Send(buff)
      }
    }
  },
  fail: function (e) {
    
    wx.showModal({
      title: '打印失败',
      content: '请检查打印机状态并重连',
      confirmText: '去重连',
      complete: (res) => {
        if (res.confirm) {
          wx.navigateTo({
            url: '../../../yg/pages/connect/connect',
          })
        }
      }
    })
  }
})

},
save(){
let self = this
let detailBase = self.data.detailBase //打印资源
self.setData({
detailBase
}, () => {
self.labelPrint()
})

}

connect.js //蓝牙链接页面js
let app = getApp()
Page({

/**

  • 页面的初始数据
    */
    data: {
    list: [],
    services: [],
    serviceId: 0,
    writeCharacter: false,
    readCharacter: false,
    notifyCharacter: false,
    isScanning: false
    },
    // 点击按钮开始搜索
    startSearch: function () {
    let that = this;
    if (!wx.openBluetoothAdapter) {
    wx.showModal({
    title: ‘提示’,
    content: ‘当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。’
    })
    return
    }
    // 初始化蓝牙设备
    wx.openBluetoothAdapter({
    success: function (res) {
    console.log(‘第一步,蓝牙初始化成功’, res)
    // 获取本机蓝牙适配器状态
    wx.getBluetoothAdapterState({
    success: function (res) {
    // 蓝牙适配器是否可用
    if (res.available) {
    // 是否正在搜索设备
    if (res.discovering) {
    // 停止搜寻附近的蓝牙外围设备。若已经找到需要的蓝牙设备并不需要继续搜索时,建议调用该接口停止蓝牙搜索。
    wx.stopBluetoothDevicesDiscovery({
    success: function (res) {
    console.log(res)
    }
    })
    }
    that.checkPemission()
    } else {
    wx.showModal({
    title: ‘提示’,
    content: ‘本机蓝牙不可用’,
    })
    }
    },
    })
    },
    fail: function (e) {
    console.log(‘startSearch失败----’+e)
    wx.showModal({
    title: ‘提示’,
    content: ‘蓝牙初始化失败,请打开蓝牙后重试’,
    })
    }
    })
    },
    checkPemission: function () { //android 6.0以上需授权地理位置权限
    let that = this;
    wx.getSetting({
    success: function (res) {
    console.log(res)
    if (!res.authSetting[‘scope.userLocation’]) {
    wx.authorize({
    scope: ‘scope.userLocation’,
    complete: function (res) {
    that.getBluetoothDevices()
    }
    })
    } else {
    that.getBluetoothDevices()
    }
    }
    })
    },
    getBluetoothDevices: function () { //获取蓝牙设备信息
    let that = this;
    wx.showLoading({
    title: ‘正在加载’
    })
    that.setData({
    isScanning: true
    })
    // 开始搜寻附近的蓝牙外围设备。
    wx.startBluetoothDevicesDiscovery({
    success: function (res) {
    console.log(res)
    setTimeout(function () {
    wx.getBluetoothDevices({
    success: function (res) {
    let devices = []
    let num = 0
    for (let i = 0; i < res.devices.length; ++i) {
    if (res.devices[i].name != ‘未知设备’) {
    devices[num] = res.devices[i]
    num++
    }
    }
    that.setData({
    list: devices,
    isScanning: false
    })
    wx.hideLoading()
    wx.stopPullDownRefresh()
    },
    fail:(r=>{
    wx.showModal({
    title: ‘提示’,
    content: ‘搜索失败,请确认系统设置里面是否已授权微信所有的蓝牙权限’,
    showCancel:false
    })
    })
    })
    }, 3000)
    },
    })
    },
    // 连接蓝牙设备
    bindViewTap: function (e) {
    // 先清除之前已连接蓝牙设备数据缓存
    wx.removeStorageSync(‘bleItem’);
    wx.removeStorageSync(‘bleWriteInfo’);
    wx.removeStorageSync(‘bleNotifyInfo’);
    let that = this;
    // 停止搜寻附近的蓝牙外围设备。若已经找到需要的蓝牙设备并不需要继续搜索时,建议调用该接口停止蓝牙搜索
    wx.stopBluetoothDevicesDiscovery({
    success: function (res) {
    console.log(res)
    },
    })
that.setData({
  serviceId: 0,
  writeCharacter: false,
  readCharacter: false,
  notifyCharacter: false
})

wx.showLoading({
  title: '正在连接'
})


const {
  title,
  item
} = e.currentTarget.dataset;
this._createBLEConnection(title, item)

},
// 连接蓝牙低功耗设备。
// 若小程序在之前已有搜索过某个蓝牙设备,并成功建立连接,可直接传入之前搜索获取的 deviceId 直接尝试连接该设备,无需再次进行搜索操作。
_createBLEConnection(deviceId, item) {
const that = this;
wx.createBLEConnection({
deviceId: deviceId,
success: function (res) {
console.log(res)
app.BLEInformation.deviceId = deviceId;
// 把已连接的蓝牙设备存入缓存
wx.setStorageSync(‘bleItem’, item);
that.getSeviceId()

  },
  fail: function (e) {
    console.log(e, '_createBLEConnection连接失败')
    wx.hideLoading()
    wx.removeStorageSync('bleItem')
    wx.showModal({
      title: '提示',
      content: '连接失败,请检查设备是否未开机、低电量或已被其他设备连接',
      showCancel:false
    })
    console.log(e)
  },
  complete: function (e) {
    console.log(e)
    wx.hideLoading()
  }
})

},
// 获取蓝牙低功耗设备所有服务 (service)。
getSeviceId: function () {
let that = this
wx.getBLEDeviceServices({
deviceId: app.BLEInformation.deviceId,
success: function (res) {
console.log(res)
that.setData({
services: res.services
})

    that.getCharacteristics()
  },
  fail: function (e) {
    wx.hideLoading()
    console.log('getSeviceId失败----'+e)
  },
  complete: function (e) {
    console.log(e)
  }
})

},
getCharacteristics: function () {
let that = this;
let list = that.data.services;
let num = that.data.serviceId;
let write = that.data.writeCharacter;
let read = that.data.readCharacter;
let notify = that.data.notifyCharacter;
// 获取蓝牙低功耗设备某个服务中所有特征 (characteristic)。
wx.getBLEDeviceCharacteristics({
deviceId: app.BLEInformation.deviceId,
serviceId: list[num].uuid,
success: function (res) {
console.log(res)
for (let i = 0; i < res.characteristics.length; ++i) {
let properties = res.characteristics[i].properties;
let item = res.characteristics[i].uuid;
if (!notify) {
if (properties.notify) {
app.BLEInformation.notifyCharaterId = item
app.BLEInformation.notifyServiceId = list[num].uuid;
const bleNotifyInfo = {
notifyCharaterId: item,
notifyServiceId: list[num].uuid
}
wx.setStorageSync(‘bleNotifyInfo’, bleNotifyInfo);
notify = true
}
}
if (!write) {
if (properties.write) {
app.BLEInformation.writeCharaterId = item;
app.BLEInformation.writeServiceId = list[num].uuid;
const bleWriteInfo = {
writeCharaterId: item,
writeServiceId: list[num].uuid
}
wx.setStorageSync(‘bleWriteInfo’, bleWriteInfo);
write = true;
}
}
if (!read) {
if (properties.read) {
app.BLEInformation.readCharaterId = item;
app.BLEInformation.readServiceId = list[num].uuid;
read = true
}
}
}
if (!write || !notify || !read) {
num++
that.setData({
writeCharacter: write,
readCharacter: read,
notifyCharacter: notify,
serviceId: num
})
if (num == list.length) {
wx.showModal({
title: ‘提示’,
content: ‘找不到该读写的特征值’,
})
} else {
that.getCharacteristics()
}
} else {
that.openControl()
}
},
fail: function (e) {
wx.hideLoading()
console.log(‘getCharacteristics失败----’+e)
},
complete: function (e) {
console.log(‘write:’ + app.BLEInformation.writeCharaterId)
console.log(‘read:’ + app.BLEInformation.readCharaterId)
console.log(‘notify:’ + app.BLEInformation.notifyCharaterId)
}
})
},
openControl: function () {
wx.hideLoading()
wx.showToast({
title: ‘连接成功’,
icon: ‘success’,
duration: 2000
})
wx.navigateBack({
delta: 1
})
},
createBLEConnectionWithDeviceId(e) {
// 小程序在之前已有搜索过某个蓝牙设备,并成功建立连接,可直接传入之前搜索获取的 deviceId 直接尝试连接该设备
const device = this.data.lastDevice;
if (!device) {
return
}
const deviceId = device.deviceId;
console.log(‘createBLEConnectionWithDeviceId’, deviceId)
wx.openBluetoothAdapter({
success: (res) => {
wx.showLoading()
console.log(‘openBluetoothAdapter success’, res)
this._createBLEConnection(deviceId, device)
},
fail: (res) => {
console.log(‘openBluetoothAdapter fail’, res)
if (res.errCode === 10001) {
wx.showModal({
title: ‘错误’,
content: ‘未找到蓝牙设备, 请打开蓝牙后重试。’,
showCancel: false
})
wx.onBluetoothAdapterStateChange((res) => {
console.log(‘onBluetoothAdapterStateChange’, res)
if (res.available) {
// 取消监听
wx.onBluetoothAdapterStateChange(() => {});
this._createBLEConnection(deviceId, device)
}
})
}else{
wx.closeBLEConnection({
deviceId: this.data.bleInfo.deviceId,
success: function(res) {
console.log(“关闭蓝牙成功”)
},
})

    }
  }
})

},
onLoad: function (options) {
const lastDevice = wx.getStorageSync(‘bleItem’);
this.setData({
lastDevice: lastDevice
})
},

onPullDownRefresh: function () {
let that = this
wx.startPullDownRefresh({})
that.startSearch()
},
})
// connect wxml
<view class=“Bluetooth”>
<view class=“startSearch”>
<button bindtap=“startSearch”>开始搜索</button>
<view class=“findText”>已发现{{list.length}}个外围设备<text class=“colord00” wx:if="{{!list.length}}">(点击上方按钮开始搜索蓝牙设备)</text></view>
</view>
<view class=“findDetected” wx:if="{{list.length}}">
<view class=“equipment”>
<view class=“equipment1” wx:for="{{list}}" wx:key=“unique”>
<view>{{item.name}}</view>
<view class=“button” data-title="{{item.deviceId}}" data-name="{{item.name}}" data-advertisData="{{item.advertisServiceUUIDs}}" data-item="{{item}}" wx:key="{{item.deviceId}}" bindtap=“bindViewTap”>连接</view>
</view>
</view>
</view>
<view class=“findDetected” wx:if="{{lastDevice}}">
<view class=“findText”>最近连接的设备</view>
<view class=“equipment”>
<view class=“equipment1”>
<view>{{lastDevice.name}}</view>
<view data-deviceId="{{lastDevice.deviceId}}" class=“button” data-item="{{lastDevice}}" bindtap=“createBLEConnectionWithDeviceId”>直接连接</view>
</view>
</view>
</view>
</view>

最后一次编辑于  08-09  
点赞 0
收藏
评论

1 个评论

  • 王伟
    王伟
    11-06

    你好,我需要在小程序里实现蓝牙打印功能,但官方代码也无法打印,输出信息显示打印成功,但打印机没反应。能交流一下吗?感谢!

    11-06
    赞同
    回复
登录 后发表内容