微信小程序之蓝牙打印

蓝牙打印

蓝牙打印热敏纸是我工作第一个小程序项目时用到的,当时啃下这块硬骨头是真的感觉好难,这篇文章我将监听蓝牙特征这部分删减掉了,减少难度,而且我个人使用中感觉也不是那么必须。
微信开发者文档-蓝牙

app.js

// 全局变量,蓝牙对象模板,但是在初始化蓝牙之前需要删除数据。
 globalData: {
    btDevices: [
      {
        id: 1,
        rssi: -40,  // 信号
        name: 'BT626',  // 蓝牙设备名称
        devId: '0',   // 蓝牙序列id
        img: '/imgs/scan/2.png',  // 蓝牙图标
      },
    ],
 }

首先:判断是Android还是iOS

    if(app.globalData.platform == 'ios'){
   		console.log('ios bt')
   	}else{
   		console.log('android bt')
   	}

第一阶段

第一步:初始化蓝牙设备
wx.openBluetoothAdapter({
      success: function (res) {},
      fail:function(res){
		console.log("蓝牙未开启!");
	  }
})
第二步:搜索附近蓝牙设备
wx.startBluetoothDevicesDiscovery({
          success: function (res) {
})
第三步:监听寻找到新设备的事件
wx.onBluetoothDeviceFound(function(devices) {})
第四步:获取已搜素到的蓝牙设备列表
wx.getBluetoothDevices({
				success: function (res) {
					var ln = 0;
					console.log(res,that.data.btDevices.length)
					if(that.data.btDevices.length != null)
						ln = that.data.btDevices.length
					for (var i = ln; i < res.devices.length; ++i)	{
						var rssi_level_img;
						if(res.devices[i].RSSI > 0 || res.devices[i].name == '未知设备'){
							continue;
						}
						if(res.devices[i].RSSI > -40)	{
							rssi_level_img = '/imgs/scan/5.png'
						}	else if(res.devices[i].RSSI > -50){
							rssi_level_img = '/imgs/scan/4.png'
						}	else if(res.devices[i].RSSI > -60){
							rssi_level_img = '/imgs/scan/3.png'
						}	else if(res.devices[i].RSSI > -70){
							rssi_level_img = '/imgs/scan/2.png'
						}else{
							rssi_level_img = '/imgs/scan/1.png'
						}
						var newBtDevice = [{
							rssi : res.devices[i].RSSI,
							name : res.devices[i].name,
							devId : res.devices[i].deviceId,
							img : rssi_level_img,
						}];
						for (var k = 0; k < that.data.btDevices.length; ++k){
							if(res.devices[i].deviceId == that.data.btDevices[k].devId){
								that.data.btDevices.splice(k,1);
								break;
							}
						}
						that.data.btDevices = that.data.btDevices.concat(newBtDevice)
					}
					that.setData({
						btDevices : that.data.btDevices
					});
					app.globalData.btDevices = that.data.btDevices
				}
			})
下拉刷新
	// 下拉清空记录,并重新搜索
	onPullDownRefresh: function() {
		var that = this
    //停止当前页面下拉刷新
		wx.stopPullDownRefresh()
		wx.stopBluetoothDevicesDiscovery({
		success: function (res) {
      //关闭蓝牙模块
			wx.closeBluetoothAdapter({
			success: function (res) {
				console.log("关闭蓝牙模块")
				var num = that.data.btDevices.length
				that.data.btDevices.splice(0,num)
				that.setData({
					btDevices : that.data.btDevices
				});	
        //蓝牙模块初始化		
				wx.openBluetoothAdapter({
					success: function (res) {
						console.log("蓝牙模块初始化")
						wx.startBluetoothDevicesDiscovery({
						//services: ['FFF0'],
						success: function (res) {
							console.log("搜索附近蓝牙设备")
						}
						})
					},
					fail:function(res){
						console.log("蓝牙未开启!下拉!");
				}
				})
			}
			})
		}
		})
	},

第二阶段

这是蓝牙打印最终重要的三个数据。

	// 蓝牙设备id
	devId: openid.devId,
	// 蓝牙打印设备服务id
    writeServiceId: '', 
    //蓝牙打印设备特征值id
    writeCharacteristicId: '',
    // 蓝牙打印设备服务序列
    writeServiceSearchIndex: 0,

第五步:连接蓝牙设备

 wx.createBLEConnection({
 // 这里的 deviceId需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取,这个devId是你点击选择连接的蓝牙
	deviceId: app.globalData.btDevices[i].devId,
 });

第六步: 获取蓝牙服务

 wx.getBLEDeviceServices({
 	deviceId: app.globalData.btDevices[i].devId,
 })

第七步: 获取蓝牙设备某个服务中所有特征值

	wx.getBLEDeviceCharacteristics({
		 // 这里的 devId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
        deviceId: app.globalData.btDevices[i].devId,
        // 这里的 writeServiceId 需要在 getBLEDeviceServices 接口中获取
        serviceId: that.data.services[that.data.writeServiceSearchIndex].uuid
        complete: function () {
          //递归调用自身直到找到write特征或遍历完所有特征
          that.seekFirstWriteCharacteristic()
        },
        success: function (res) {
          console.log('device getBLEDeviceCharacteristics:', res.characteristics)
          for (var n = 0; n < res.characteristics.length && that.data.writeCharacteristicId == 'invalid'; ++n) {
            if (res.characteristics[n].properties.write == true) {
              that.data.writeCharacteristicId = res.characteristics[n].uuid

            }
          }
        }
	})

第八步:打印

需要一个cpcl文件,要将服务器的值传到 utils/cpcl.js里去。通过字符串操作赋值。

	//将字符串转成arrayBuffer
 	base64Str = gbToBase64.encode64(sendData)
    arrayBuffer = wx.base64ToArrayBuffer(base64Str);
	if (app.globalData.platform == 'ios') {
        wx.writeBLECharacteristicValue({
          // 这里的 devId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
          deviceId: that.data.devId,
          // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
          serviceId: that.data.writeServiceId,
          // 这里的 writeCharacteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
          characteristicId: that.data.writeCharacteristicId,
          // 这里的value是ArrayBuffer类型
          value: arrayBuffer,
          success: function (res) {
            wx.showToast({
              title: '发送成功',
              icon: 'success',
              duration: 2000
            })
            that.setData({
              block:"block",
              block1: "none"
            })
            console.log('writeBLECharacteristicValue success', res.errMsg)
          },
          fail: function (res) {
            console.log('writeBLECharacteristicValue fail', res.errMsg)
          }
        })
      } else {
        let dataView1 = new DataView(arrayBuffer)
        var length = dataView1.byteLength
        var size = 100
        var package_count = Math.round(length / size + 0.5);
        this.writeFuction(that, arrayBuffer, package_count, size);
      }
	writeFuction(that, data, count, size) {
    let dataView_temp1 = new DataView(data);
    var packages = Math.round(dataView_temp1.byteLength / size + 0.5)
    var yushu = dataView_temp1.byteLength % size
    let buffer = null
    let dataView_temp2 = null
    if (yushu != 0 && count == 1) {
      buffer = new ArrayBuffer(yushu)
      dataView_temp2 = new DataView(buffer)
      for (var i = 0; i < dataView_temp2.byteLength; i++) {
        dataView_temp2.setUint8(i, dataView_temp1.getUint8((packages - count) * size + i))
      }
    } else {
      buffer = new ArrayBuffer(size)
      dataView_temp2 = new DataView(buffer)
      for (var i = 0; i < dataView_temp2.byteLength; i++) {
        dataView_temp2.setUint8(i, dataView_temp1.getUint8((packages - count) * size + i))
      }
    }
    wx.writeBLECharacteristicValue({
      // 这里的 devId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
      deviceId: that.data.devId,
      // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
      serviceId: that.data.writeServiceId,
      // 这里的 writeCharacteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
      characteristicId: that.data.writeCharacteristicId,
      // 这里的value是ArrayBuffer类型
      value: buffer,
      // value: arrayBuffer,
      success: function (res) {
        if (count != 0) {
          that.writeFuction(that, data, count, size)
        } else {
          wx.showToast({
            title: '发送成功',
            icon: 'success',
            duration: 2000
          })
          that.setData({
            block: "block",
            block1: "none"
          })
        }
      },
      complete: function (res) {
        console.log(res);
      }
    })
    count--;
    return 0;
  },

关于cpcl介绍

exports.val = "! 0 200 200 1030 1\r\n" +
  "PAGE - WIDTH 576\r\n" +
  "UNDERLINE OFF\r\n" +
  "SETBOLD 1\r\n" +
  "SETMAG 2 2\r\n" +
  "T 20 0 0 25 HC慧驰速递\r\n" +
  "UNDERLINE OFF\r\n" +
  "SETBOLD 1\r\n" +
  "SETMAG 1 1\r\n" +
  "{df}"+
  "T 25 0 445 950 已验视\r\n" +
  "UNDERLINE OFF\r\n" +
  "SETBOLD 0\r\n" +
  "SETMAG 1 1\r\n" +
  "LINE 0 1000 566 1000 4\r\n" +
  // "FORM\r\n"+
  "PRINT\r\n";
  • 5
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 16
    评论
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值