微信小程序-蓝牙打印机demo
生活随笔
收集整理的這篇文章主要介紹了
微信小程序-蓝牙打印机demo
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
對于藍牙有寫入數據的話,需要時低功耗的藍牙。向低功耗藍牙設備特征值中寫入二進制數據。注意:必須設備的特征值支持 write 才可以成功調用。
https://developers.weixin.qq.com/miniprogram/dev/api/device/bluetooth-ble/wx.writeBLECharacteristicValue.html
先搜索藍牙設備
wxml
<button class="btn" type="primary" bindtap="startSearch" loading='{{isScanning}}'> 開始搜索 </button><view wx:for="{{list}}" wx:for-item="item" data-title="{{item.deviceId}}" data-name="{{item.name}}" data-advertisData="{{item.advertisServiceUUIDs}}" wx:key="{{item.deviceId}}"bindtap="bindViewTap"><view class="item"><div class="deviceId block">{{item.deviceId}}</div><div class="name block">{{item.name}}</div></view> </view>js
app.BLEInformation.platform = getApp().getPlatform()
data: {list: [],services: [],serviceId: 0,writeCharacter: false,readCharacter: false,notifyCharacter: false,isScanning:false},startSearch: function () {var that = thiswx.openBluetoothAdapter({success: function (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 () {wx.showModal({title: '提示',content: '藍牙初始化失敗,請打開藍牙',})}})},checkPemission: function () { //android 6.0以上需授權地理位置權限var that = thisvar platform = app.BLEInformation.platformif (platform == "ios") {app.globalData.platform = "ios"that.getBluetoothDevices()} else if (platform == "android") {app.globalData.platform = "android"console.log(app.getSystem().substring(app.getSystem().length - (app.getSystem().length - 8), app.getSystem().length - (app.getSystem().length - 8) + 1))if (app.getSystem().substring(app.getSystem().length - (app.getSystem().length - 8), app.getSystem().length - (app.getSystem().length - 8) + 1) > 5) {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 () { //獲取藍牙設備信息var that = thisconsole.log("start search")wx.showLoading({title: '正在加載',})that.setData({isScanning:true})wx.startBluetoothDevicesDiscovery({success: function (res) {console.log(res)setTimeout(function () {wx.getBluetoothDevices({success: function (res) {var devices = []var num = 0for (var 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()},})}, 3000)},})},bindViewTap: function (e) {var that = thiswx.stopBluetoothDevicesDiscovery({success: function (res) { console.log(res) },})that.setData({serviceId: 0,writeCharacter: false,readCharacter: false,notifyCharacter: false})console.log(e.currentTarget.dataset.title)wx.showLoading({title: '正在連接',})wx.createBLEConnection({deviceId: e.currentTarget.dataset.title,success: function (res) {console.log(res)app.BLEInformation.deviceId = e.currentTarget.dataset.titlethat.getSeviceId()}, fail: function (e) {wx.showModal({title: '提示',content: '連接失敗',})console.log(e)wx.hideLoading()}, complete: function (e) {console.log(e)}})},getSeviceId: function () {var that = thisvar platform = app.BLEInformation.platformconsole.log(app.BLEInformation.deviceId)wx.getBLEDeviceServices({deviceId: app.BLEInformation.deviceId,success: function (res) {console.log(res)that.setData({services: res.services})that.getCharacteristics()}, fail: function (e) {console.log(e)}, complete: function (e) {console.log(e)}})},getCharacteristics: function () {var that = thisvar list = that.data.servicesvar num = that.data.serviceIdvar write = that.data.writeCharactervar read = that.data.readCharactervar notify = that.data.notifyCharacterwx.getBLEDeviceCharacteristics({deviceId: app.BLEInformation.deviceId,serviceId: list[num].uuid,success: function (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) {app.BLEInformation.notifyCharaterId = itemapp.BLEInformation.notifyServiceId = list[num].uuidnotify = true}}if (!write) {if (properties.write) {app.BLEInformation.writeCharaterId = itemapp.BLEInformation.writeServiceId = list[num].uuidwrite = true}}if (!read) {if (properties.read) {app.BLEInformation.readCharaterId = itemapp.BLEInformation.readServiceId = list[num].uuidread = 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) {console.log(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.navigateTo({url: '../startPrint/startPrint',})},然后打印
下面就是startPrint的代碼
wxml
下面是 js 的代碼,首先是設置變量
data: {sendContent: "",looptime: 0,currentTime: 1,lastData: 0,oneTimeData: 0,returnResult: "returnResult",canvasWidth: 80,canvasHeight: 80,buffSize: [],buffIndex: 0,printNum: [],printNumIndex: 0,printerNum: 1,currentPrint: 1,isReceiptSend: false,isLabelSend: false},command.setCls() ,需要設置這個,不然內容和上一次重復
onLoad: function(options) {var that = this;wx.notifyBLECharacteristicValueChange({deviceId: app.BLEInformation.deviceId,serviceId: app.BLEInformation.notifyServiceId,characteristicId: app.BLEInformation.notifyCharaterId,state: true,success: function(res) {wx.onBLECharacteristicValueChange(function(r) {console.log(`characteristic ${r.characteristicId} has changed, now is ${r}`)})},fail: function(e) {console.log('fail', e)},complete: function(e) {console.log('complete', e)}})},inputEvent: function(e) { this.setData({sendContent: e.detail.value})console.log('sendContent: ', this.sendContent)},sendData: function() { var data = this.data.sendContent + "\n"var that = this;var command = tsc.jpPrinter.createNew()command.setGap(0)command.setCls()command.setText(60, 90, "TSS24.BF2", 1, 1, data)command.setPagePrint()that.prepareSend(command.getData())},labelTest: function() { var that = this;var canvasWidth = that.data.canvasWidthvar canvasHeight = that.data.canvasHeightvar command = tsc.jpPrinter.createNew()command.setSize(48, 40)command.setGap(0)command.setCls() //需要設置這個,不然內容和上一次重復command.setQR(1, 120, "L", 5, "A", "airenao.com")command.setText(60, 90, "TSS24.BF2", 1, 1, "成都愛熱鬧")command.setText(170, 50, "TSS24.BF2", 1, 1, "小程序測試")command.setText(170, 90, "TSS24.BF2", 1, 1, "測試數字12345678")command.setText(170, 120, "TSS24.BF2", 1, 1, "測試英文abcdefg")command.setText(170, 150, "TSS24.BF2", 1, 1, "測試符號/*-+!@#$")wx.canvasGetImageData({canvasId: 'edit_area_canvas',x: 0,y: 0,width: canvasWidth,height: canvasHeight,success: function(res) {command.setBitmap(60, 0, 0, res)},complete: function() {command.setPagePrint()that.setData({isLabelSend: true})that.prepareSend(command.getData())}})},準備發送內容, printNum 這個是需要打印多少份,buff 是每次打印多少字節數
prepareSend: function(buff) { console.log('buff', buff)var that = thisvar time = that.data.oneTimeDatavar looptime = parseInt(buff.length / time);var lastData = parseInt(buff.length % time);console.log(looptime + "---" + lastData)that.setData({looptime: looptime + 1,lastData: lastData,currentTime: 1,})that.Send(buff)},queryStatus: function() { //查詢打印機狀態var command = esc.jpPrinter.Query();command.getRealtimeStatusTransmission(1);this.setData({returnResult: "查詢成功"})},Send: function(buff) { //分包發送var that = thisvar currentTime = that.data.currentTimevar loopTime = that.data.looptimevar lastData = that.data.lastDatavar onTimeData = that.data.oneTimeDatavar printNum = that.data.printerNum //打印多少份var currentPrint = that.data.currentPrintvar bufvar dataViewif (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)wx.writeBLECharacteristicValue({deviceId: app.BLEInformation.deviceId,serviceId: app.BLEInformation.writeServiceId,characteristicId: app.BLEInformation.writeCharaterId,value: buf,success: function(res) {console.log('寫入成功', res)},fail: function(e) {console.fail('寫入失敗', e)},complete: function() {currentTime++if (currentTime <= loopTime) {that.setData({currentTime: currentTime})that.Send(buff)} else {wx.showToast({title: '已打印第' + currentPrint + '張',})if (currentPrint == printNum) {that.setData({looptime: 0,lastData: 0,currentTime: 1,isReceiptSend: false,isLabelSend: false,currentPrint: 1})} else {currentPrint++that.setData({currentPrint: currentPrint,currentTime: 1,})console.log("開始打印")that.Send(buff)}}}})},最后的成品樣子
總結
以上是生活随笔為你收集整理的微信小程序-蓝牙打印机demo的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 快速探索,音视频技术不再神秘
- 下一篇: 小程序分享功能实现结果回调以及页面传参