• 微信小程序连接标签打印机,打印标签


    授权蓝牙并且搜索蓝牙设备

    // 授权定位和蓝牙
    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('你已拒绝开启蓝牙功能')
                        }
                    })
                }
            }
        })
    },
    // 第一步,蓝牙初始化
    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 {
                            Toast('蓝牙设备不可用')
                        }
                    })
                } else {
                    Toast('蓝牙设备不可用')
                }
            }
        })
    },
    // 第二步 开始搜索附近的蓝牙设备
    startBluetoothDevicesDiscovery() {
        wx.startBluetoothDevicesDiscovery({
            allowDuplicatesKey: false,
            success: (res) => {
                this.onBluetoothDeviceFound()
            },
        })
    },
    // 第三步 监听发现附近的蓝牙设备
    onBluetoothDeviceFound() {
        wx.showLoading({
            title: '重新搜索中',
            mask: true
        })
        wx.onBluetoothDeviceFound(() => {
            wx.getBluetoothDevices({
                success: res => {
                    let deviceList = []
                    if (res.devices.length > 0) {
                        res.devices.forEach(v => {
                            if (v.RSSI < 0 && v.name != '未知设备') {
                                deviceList.push(v)
                            }
                        })
                    }
                    wx.hideLoading()
                    this.setData({
                        deviceList
                    })
                }
            })
        })
    },
    
    
    // 第四步、 建立连接
    connectDevice(e) {
        const item = e.currentTarget.dataset.item
        this.setData({
            linkShow: true,
            activeItem: item
        }, () => {
            app.linkBluetooth(item.deviceId).then(res => {
                console.log('蓝牙连接成功', res)
                Toast('蓝牙连接成功')
                // 更新连接历史记录
                this.updateHisList(this.data.activeItem)
                this.setlinkDeviceId(this.data.activeItem.deviceId)
                this.setData({
                    linkShow: false
                })
            }).catch(err => {
                console.log(err.message, err)
                Toast(err.message)
                this.closeBLEConnection(item.deviceId)
                this.setData({
                    linkShow: false,
                })
            })
        })
    },
    // 断开蓝牙连接
    closeBLEConnection(deviceId, tip) {
        app.closeBluetooth(deviceId).then(res => {
            this.setlinkDeviceId('')
            if (tip) {
                Toast(tip)
            }
        }).catch(err => {
            Toast('断开连接失败')
        })
    },
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124

    连接断开方法

    // 连接蓝牙
    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: '蓝牙连接成功'
                                                    })
                                                } else {
                                                    reject({
                                                        message: '蓝牙服务不支持此功能,已断开'
                                                    })
                                                }
                                            },
                                            fail(err) {
                                                reject({
                                                    message: '获取蓝牙低功耗设备某个服务中所有特征失败',
                                                    err
                                                })
                                            }
                                        })
                                        return
                                    }
                                }
                            },
                            fail(err) {
                                reject({
                                    message: '获取蓝牙低功耗设备所有服务失败',
                                    err
                                })
                            }
                        })
                    }, 3000)
                },
                fail: (err) => {
                    reject({
                        message: '蓝牙连接失败',
                        err
                    })
                }
            })
        })
    },
    // 断开蓝牙连接
    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)
                }
            })
        })
    },
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89

    打印命令

    // GBK的方法随便找一个就行
    import GBK from './gbk.min.js';
    
    // 打印商品标签
    export const printGoodsTag = (option) => {
        if (!wx.getStorageSync('linkDeviceId')) {
            wx.showToast({
                title: '请连接打印机',
                icon: 'none',
                mask: true
            })
            return
        }
        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,"商品名称:${option.goodsName}"\n` +
            `TEXT 20,80,"0",0,1,1,"规格:${option.skuName || ''}"\n` +
            `QRCODE 20,130,M,3,M,0,M1,S2,"${option.id}_1"\n` +
            `TEXT 120,140,"0",0,1,1,"零售价"\n` +
            `TEXT 120,180,"0",0,1.5,1.5,"¥${option.price || ''}"\n` +
            'PRINT 1,1'
        sendDataToDevice(new Uint8Array([...GBK.encode(data), ...[10]]).buffer);
    }
    // 打印维修单标签
    export const printRepairTag = (option) => {
        if (!wx.getStorageSync('linkDeviceId')) {
            wx.showToast({
                title: '请连接打印机',
                icon: 'none',
                mask: true
            })
            return
        }
        let data =
            'SIZE 40 mm,30 mm\n' +
            'GAP 2 mm,0 mm\n' +
            'DIRECTION 1\n' +
            'CLS\n' +
            `QRCODE 20,30,M,3,M,0,M1,S2,"${option.id}_2"\n` +
            `TEXT 110,30,"0",0,1,1,"${option.equModel || ''}"\n` +
            `TEXT 110,60,"0",0,1,1,"${option.okey || ''}"\n` +
            `TEXT 110,90,"0",0,1,1,"${option.imei || ''}"\n`
        let str = option.reason || ''
        if (str) {
            let length = str.length
            let maxNum = 12
            let top = 130
            for (let i = 0, len = length; i <= len; i += 12) {
                let text = str.slice(i, maxNum)
                data = data + `TEXT 20,${top},"0",0,1,1,"${text}"\n`
                maxNum += 12
                top += 30
            }
        }
        data = data + 'PRINT 1,1'
        sendDataToDevice(new Uint8Array([...GBK.encode(data), ...[10]]).buffer);
    }
    
    const sendDataToDevice = value => {
        let byteLength = value.byteLength;
        const speed = 20;
        if (byteLength > 0) {
            wx.writeBLECharacteristicValue({
                deviceId: wx.getStorageSync('linkDeviceId'),
                characteristicId: wx.getStorageSync('characteristicId'),
                serviceId: wx.getStorageSync('serviceId'),
                value: value.slice(0, byteLength > speed ? speed : byteLength),
                success: res => {
                    if (byteLength > speed) {
                        sendDataToDevice(value.slice(speed, byteLength));
                    } else {
                        console.log('已完成打印   laster success', res);
                    }
                },
                fail: err => {
                    console.log(err)
                },
            });
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
  • 相关阅读:
    小程序云开发笔记一
    Linux vi和vim
    erlang开发环境搭建(Intellij IDEA)
    MySQL8修改密码(linux环境)
    肥泽-酒店辅助订购系统
    ovn metadata (by quqi99)
    核心交换机、汇聚层交换机、接入层交换机的区别和特点
    Azure KeyVault(三)通过 Microsoft.Azure.KeyVault 类库在 .NET Core 上获取 Secrets
    涉及第三方支付接口,怎么测?
    37岁更要坚定,竞争从阿里的Java高并发操作手册开始
  • 原文地址:https://blog.csdn.net/weixin_43788115/article/details/132713957