收藏
回答

小程序蓝牙连接打印机,发送成功数据却打印不出来?型号HM-T260L

// 授权定位和蓝牙

authorizationBluetooth() {

    wx.getSetting({

        success: (res) => {

            if (res.authSetting.hasOwnProperty('scope.bluetooth')) {

                if (!res.authSetting['scope.bluetooth']) {

                    this.setData({

                        showManual: true

                    })

                } else {

                    this.bluetoothState()

                }

            } else {

                wx.authorize({

                    scope: 'scope.bluetooth',

                    success: () => {

                        // 用户已经同意小程序使用手机蓝牙功能,后续调用 蓝牙 接口不会弹窗询问

                        this.bluetoothState()

                    },

                    fail: () => {

                        // Toast('你已拒绝开启蓝牙功能')

uni.showToast({

title:'你已拒绝开启蓝牙功能'

})

                    }

                })

            }

        }

    })

},

// 第一步,蓝牙初始化

bluetoothState() {

    wx.openBluetoothAdapter({

        mode: 'central',

        success: (res) => {

            console.log('第一步,蓝牙初始化成功', res)

            this.startBluetoothDevicesDiscovery()

        },

        fail: (err) => {

            console.log('蓝牙设备错误', err)

            if (err.errCode == 10001) {

                wx.onBluetoothAdapterStateChange((ress) => {

                    if (ress.available) {

                        this.startBluetoothDevicesDiscovery()

                    } else {

uni.showToast({

title:'蓝牙设备不可用'

})

                    }

                })

            } else {

uni.showToast({

title:'蓝牙设备不可用'

})

            }

        }

    })

},

// 第二步 开始搜索附近的蓝牙设备

startBluetoothDevicesDiscovery() {

    wx.startBluetoothDevicesDiscovery({

        allowDuplicatesKey: false,

        success: (res) => {

            this.onBluetoothDeviceFound()

        },

    })

},

// 第三步 监听发现附近的蓝牙设备

onBluetoothDeviceFound() {

let self = this;

self.deviceList = [];

    wx.showLoading({

        title: '重新搜索中',

        mask: true

    })

    wx.onBluetoothDeviceFound(() => {

        wx.getBluetoothDevices({

            success: res => {

                // let deviceList = []

console.log(res);

                if (res.devices.length > 0) {

                    res.devices.forEach(v => {

                        if (v.RSSI < 0 && v.name != '未知设备') {

console.log(v);

if (!self.deviceList.some(item => {

return item.deviceId === v.deviceId

})) {

console.log(1111111111111111);

self.deviceList.push(v)

}

                        }

                    })

                }

                wx.hideLoading()

                // this.setData({

                //     deviceList

                // })

console.log(deviceList);

            }

        })

    })

},

// 第四步、 建立连接

connectDevice(e) {

console.log(e);

    const item = e

    linkShow =  true;

    activeItem = item;

this.linkBluetooth(item.deviceId).then(res => {

    console.log('蓝牙连接成功', res)

    // Toast('蓝牙连接成功')

    // 更新连接历史记录

    this.updateHisList(this.data.activeItem)

    this.setlinkDeviceId(this.data.activeItem.deviceId)

linkShow = false

}).catch(err => {

    console.log(err.message, err)

    // Toast(err.message)

    this.closeBLEConnection(item.deviceId)

linkShow:false

})

},

// 断开蓝牙连接

closeBLEConnection(deviceId, tip) {

    this.closeBluetooth(deviceId).then(res => {

        this.setlinkDeviceId('')

        if (tip) {

            Toast(tip)

        }

    }).catch(err => {

uni.showToast({

title:'断开连接失败'

})

    })

},

linkBluetooth(deviceId) {

    return new Promise((resolve, reject) => {

        wx.createBLEConnection({

            deviceId: deviceId,

            success: (res) => {

                setTimeout(() => {

                    wx.getBLEDeviceServices({

                        deviceId: deviceId,

                        success: (res) => {

                            for (let i = 0; i < res.services.length; i++) {

                            if (res.services[i].isPrimary) {

                                    let serviceId = res.services[i].uuid

                                    let Iswrite = false

                                    wx.getBLEDeviceCharacteristics({

                                        deviceId,

                                        serviceId,

                                        success: (res) => {

                                            let characteristicId = ''

                                            for (let i = 0; i < res.characteristics.length; i++) {

                                                let item = res.characteristics[i]

                                                //支持写入就行了

                                                if (item.properties.write) {

                                                    Iswrite = true

                                                    characteristicId = item.uuid

                                                }

                                            }

                                            if (Iswrite) {

                                                wx.setStorageSync('linkDeviceId', deviceId)

                                                wx.setStorageSync('serviceId', serviceId)

                                                wx.setStorageSync('characteristicId', characteristicId)

                                                // resolve({

                                                //     message: '蓝牙连接成功'

                                                // })

uni.showToast({

title:'蓝牙连接成功'

})

// this.startPrint();

                                            } else {

                                                // reject({

                                                //     message: '蓝牙服务不支持此功能,已断开'

                                                // })

uni.showToast({

title:'蓝牙服务不支持此功能,已断开'

})

                                            }

                                        },

                                        fail(err) {

                                            // reject({

                                            //     message: '获取蓝牙低功耗设备某个服务中所有特征失败',

                                            //     err

                                            // })

uni.showToast({

title:'获取蓝牙低功耗设备某个服务中所有特征失败'

})

                                        }

                                    })

                                    return

                                }

                            }

                        },

                        fail(err) {

                            // reject({

                            //     message: '获取蓝牙低功耗设备所有服务失败',

                            //     err

                            // })

uni.showToast({

title:'获取蓝牙低功耗设备所有服务失败'

})

                        }

                    })

                }, 3000)

            },

            fail: (err) => {

                // reject({

                //     message: '蓝牙连接失败',

                //     err

                // })

uni.showToast({

title:'蓝牙连接失败'

})

            }

        })

    })

},

// 断开蓝牙连接

closeBluetooth(deviceId) {

    return new Promise((resolve, reject) => {

        wx.closeBLEConnection({

            deviceId: deviceId,

            success: res => {

                wx.removeStorageSync('linkDeviceId')

                wx.removeStorageSync('serviceId')

                wx.removeStorageSync('characteristicId')

                resolve(res)

            },

            fail: err => {

                wx.removeStorageSync('linkDeviceId')

                wx.removeStorageSync('serviceId')

                wx.removeStorageSync('characteristicId')

                reject(err)

            }

        })

    })

},

printGoodsTag(option){

    if (!wx.getStorageSync('linkDeviceId')) {

        wx.showToast({

            title: '请连接打印机',

            icon: 'none',

            mask: true

        })

        return

    }

let goodsName = '测试';

let skuName = '测试11';

let id = '123';

let price = '321';

    let data =

        'SIZE 40 mm,30 mm\n' +

        'GAP 2 mm,0 mm\n' +

        'DIRECTION 1\n' +

        'CLS\n' +

        `TEXT 20,30,"0",0,1,1,"商品名称:${goodsName}"\n` +

        `TEXT 20,80,"0",0,1,1,"规格:${skuName || ''}"\n` +

        `QRCODE 20,130,M,3,M,0,M1,S2,"${id}_1"\n` +

        `TEXT 120,140,"0",0,1,1,"零售价"\n` +

        `TEXT 120,180,"0",0,1.5,1.5,"¥${price || ''}"\n` +

        'PRINT 1,1'

    this.sendDataToDevice(new Uint8Array([...GBK.encode(data), ...[10]]).buffer);

},

ab2hex(buffer) {

const hexArr = Array.prototype.map.call(

new Uint8Array(buffer),

function(bit) {

return ('00' + bit.toString(16)).slice(-2)

}

)

return hexArr.join('')

},

sendDataToDevice(value){

wx.getBLEDeviceCharacteristics({

deviceId: wx.getStorageSync('linkDeviceId'),

serviceId: wx.getStorageSync('serviceId'),

success (res) {

console.log('device getBLEDeviceCharacteristics:', res.characteristics)

}

})

let buffer = new ArrayBuffer(1)

let dataView = new DataView(buffer)

dataView.setUint8(0, 0)

// buffer = this.ab2hex(buffer);

wx.writeBLECharacteristicValue({

    deviceId: wx.getStorageSync('linkDeviceId'),

    characteristicId: wx.getStorageSync('characteristicId'),

    serviceId: wx.getStorageSync('serviceId'),

  // 这里的value是ArrayBuffer类型

value: buffer,

writeType:'write',

success (res) {

console.log('writeBLECharacteristicValue success', res)

},

fail: err => {

console.log('writeBLECharacteristicValue errot',err)

},

})

}

回答关注问题邀请回答
收藏

1 个回答

登录 后发表内容