微信小程序 - 蓝牙打印机、支持账单模式、标签模式、查询打印机状态、分包发送

CSS

/**index.wxss**/
page {
	background-color: #EDF0F5;
}

.pages {
	margin: 20px;
}

.printbtn {
	margin-top: 20px;
	width: 100%;
	height: 80rpx;
	border-radius: 66rpx;
	background-color: #42C1AC;
	color: white;
	text-align: center;
	line-height: 80rpx;
}

.text{
	margin-top: 20px;
}

.input{
	background-color: #fff;
	height: 80rpx;
	margin-top: 20px;
	padding: 10px;
}


.device_list {
  margin: 20px 5px;
  border-radius: 5px;
  width: auto;
}
.device_item {
  border: 1px solid #AAA;
  padding: 10px;
  color: #666;
}

.device_item div{
	display: block;
}

HTML

<!--index.wxml-->

<view class="pages">

	<button class="printbtn" type="primary" bindtap="searchBluetooth" loading='{{isScanning}}'> 开始搜索 </button>

	<view class="device_list">
		<view wx:for="{{devicesList}}" wx:key="key" wx:for-index="index" wx:for-item="item" bindtap="connectBluetoothSettings" data-index="{{index}}" class="device_item">
			<div class="deviceId">deviceId:{{item.deviceId}}</div>
			<div class="name">name:{{item.name}}</div>
		</view>
	</view>

	<button class="printbtn" type='primary' bindtap='labelTest' loading='{{isLabelSend}}' disabled='{{isLabelSend}}'>标签测试</button>

	<view class="text">发送数据大小:</view>
	<textarea class="input" bindinput="inputEvent" value="{{oneTimeData}}" />

	<canvas canvas-id="edit_area_canvas"></canvas>

</view>

JS

//index.js
//获取应用实例
const app = getApp();

let tsc = require('../../components/gprint/tsc.js')
let esc = require('../../components/gprint/esc.js')

Page({
  data: {
    
    devicesList: [],
    services: [],
    serviceId: 0,
    writeCharacter: false,
    readCharacter: false,
    notifyCharacter: false,
    isScanning: false,

    looptime: 0,
    currentTime: 1,
    lastData: 0,
    oneTimeData: 20,//发送数据大小,测试正常,不能太多
    returnResult: "returnResult",
    canvasWidth: 80,
    canvasHeight: 80,
    printNum: 1,
    currentPrint: 1,
    isReceiptSend: false,
    isLabelSend: false
  },
  /**
   * 监听数据输入
   */
  inputEvent: function(e) { 
    this.setData({
      oneTimeData: e.detail.value
    })
    console.log('oneTimeData: ', this.data.oneTimeData)
  },
  /**
   * 蓝牙搜索
   */
  searchBluetooth: function () {
    var that = this
    //判断蓝牙是否打开
    wx.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: '蓝牙初始化失败,请打开蓝牙',
        })
      }
    })
  },
  /**
   * android 6.0以上需授权地理位置权限
   */
  checkPemission: function () {
    var that = this;
    var systemInfo = wx.getSystemInfoSync();
    var platform = systemInfo.platform;
    if (platform == "ios") {
      that.getBluetoothDevices()
    } else if (platform == "android") {
      let system = systemInfo.system;
      let system_no = system.replace('android', '');
      system_no = system.replace('Android', '');
      if (Number(system_no) > 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 = this
    console.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 = 0
              for (var i = 0; i < res.devices.length; ++i) {
                if (res.devices[i].name != "未知设备") {
                  devices[num] = res.devices[i]
                  num++
                }
              }
              that.setData({
                devicesList: devices,
                isScanning: false
              })
              wx.hideLoading()
              wx.stopPullDownRefresh()
            },
          })
        }, 3000)
      },
    })
  },
  /**
   * 开始连接蓝牙设置
   */
  connectBluetoothSettings: function (e) {
    var that = this;
    let index = e.currentTarget.dataset.index;
    let deviceId = that.data.devicesList[index].deviceId;
    wx.stopBluetoothDevicesDiscovery({
      success: function (res) {
        console.log(res)
      },
    })
    that.setData({
      serviceId: 0,
      writeCharacter: false,
      readCharacter: false,
      notifyCharacter: false
    })
    console.log(deviceId)
    wx.showLoading({
      title: '正在连接',
    })
    wx.createBLEConnection({
      deviceId: deviceId,
      success: function (res) {
        console.log(res)
        app.globalData.bluetoothDeviceId = deviceId
        that.getBLEDeviceServices();
      },
      fail: function (e) {
        wx.showModal({
          title: '提示',
          content: '连接失败',
        })
        console.log(e)
        wx.hideLoading()
      },
      complete: function (e) {
        console.log(e)
      }
    })
  },
  /**
   * 获取蓝牙设备所有服务
   */
  getBLEDeviceServices: function () {
    var that = this
    console.log(app.globalData.bluetoothDeviceId)
    wx.getBLEDeviceServices({
      deviceId: app.globalData.bluetoothDeviceId,
      success: function (res) {
        console.log(res)
        that.setData({
          services: res.services
        })
        that.getBLEDeviceCharacteristics()
      },
      fail: function (e) {
        console.log(e)
      },
      complete: function (e) {
        console.log(e)
      }
    })
  },
  /**
   * 获取蓝牙设备某个服务中所有特征值
   */
  getBLEDeviceCharacteristics: function () {
    var that = this
    var list = that.data.services
    var num = that.data.serviceId
    var write = that.data.writeCharacter
    var read = that.data.readCharacter
    var notify = that.data.notifyCharacter
    wx.getBLEDeviceCharacteristics({
      deviceId: app.globalData.bluetoothDeviceId,
      serviceId: list[num].uuid,
      success: function (res) {
        console.log(res)
        for (var i = 0; i < res.characteristics.length; ++i) {
          var properties = res.characteristics[i].properties
          var item = res.characteristics[i].uuid
          if (!notify) {
            if (properties.notify) {
              app.globalData.notifyCharaterId = item
              app.globalData.notifyServiceId = list[num].uuid
              notify = true
            }
          }
          if (!write) {
            if (properties.write) {
              app.globalData.writeCharaterId = item
              app.globalData.writeServiceId = list[num].uuid
              write = true
            }
          }
          if (!read) {
            if (properties.read) {
              app.globalData.readCharaterId = item
              app.globalData.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.getBLEDeviceCharacteristics()
          }
        } else {
          that.notifyBLECharacteristicValueChange()
        }
      },
      fail: function (e) {
        console.log(e)
      },
      complete: function (e) {
        console.log("write:" + app.globalData.writeCharaterId)
        console.log("read:" + app.globalData.readCharaterId)
        console.log("notify:" + app.globalData.notifyCharaterId)
      }
    })
  },
  /**
   * 启用低功耗蓝牙设备特征值变化时的 notify 功能
   */
  notifyBLECharacteristicValueChange: function () {
    console.log("deviceId:" + app.globalData.bluetoothDeviceId)
    console.log("serviceId:" + app.globalData.notifyServiceId)
    console.log("notifyCharaterId:" + app.globalData.notifyCharaterId)
    wx.hideLoading();
    wx.notifyBLECharacteristicValueChange({
      deviceId: app.globalData.bluetoothDeviceId,
      serviceId: app.globalData.notifyServiceId,
      characteristicId: app.globalData.notifyCharaterId,
      state: true,
      success: function(res) {
        wx.onBLECharacteristicValueChange(function(r) {
          // console.log(`characteristic ${r.characteristicId} has changed, now is ${r}`)
          console.log('onBLECharacteristicValueChange=', r);
        })
      },
      fail: function(e) {
        console.log('fail', e)
      },
      complete: function(e) {
        console.log('complete', e)
      }
    })
  },
  /**
   * 账单模式
   */
  sendData: function() { 
    var data = "好好学习,天天向上\n"
    var that = this;
    var command = tsc.jpPrinter.createNew()
    command.setGap(0)
    command.setCls()
    command.setText(40, 60, "TSS24.BF2", 1, 1, data)
    command.setPagePrint()
    that.prepareSend(command.getData())
  },
  /**
   * 标签模式
   */
  labelTest: function() { 
    var that = this;
    var canvasWidth = that.data.canvasWidth
    var canvasHeight = that.data.canvasHeight
    var command = tsc.jpPrinter.createNew()
    command.setSize(40, 60)
    command.setGap(0)
    command.setCls() //需要设置这个,不然内容和上一次重复
    command.setQR(1, 120, "L", 5, "A", "poso2o.com")
    command.setText(60, 90, "TSS24.BF2", 1, 1, "POSO2O打印机")
    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())
      }
    })

  },
  /**
   * 准备发送数据
   */
  prepareSend: function(buff) { 
    console.log('buff', buff)
    var that = this
    var time = that.data.oneTimeData
    var 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)
  },
  /**
   * 查询打印机状态
   */
  queryPrinterStatus: function() {
    var command = esc.jpPrinter.Query();
    command.getRealtimeStatusTransmission(1);
    this.setData({
      returnResult: "查询成功"
    })
  },
  /**
   * 分包发送
   */
  Send: function(buff) {
    var that = this
    var currentTime = that.data.currentTime;
    var loopTime = that.data.looptime;
    var lastData = that.data.lastData;
    var onTimeData = that.data.oneTimeData;
    var printNum = that.data.printNum; //打印多少份
    var currentPrint = that.data.currentPrint;
    var buf
    var 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);
    console.log("deviceId:" + app.globalData.bluetoothDeviceId)
    console.log("serviceId:" + app.globalData.writeServiceId)
    console.log("characteristicId:" + app.globalData.writeCharaterId)

    wx.writeBLECharacteristicValue({
      deviceId: app.globalData.bluetoothDeviceId,
      serviceId: app.globalData.writeServiceId,
      characteristicId: app.globalData.writeCharaterId,
      value: buf,
      success: function(res) {
        console.log('写入成功', res)
      },
      fail: function(e) {
        console.error('写入失败', 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)
          }
        }
      }
    })
  },
  onLoad: function(options) {
    var that = this;
    
  },

})

下载连接:

https://download.csdn.net/download/luolinyin/12846611

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值