小程序低功耗蓝牙连接打印机

效果图
效果打印图

打印机型号:TSC Alpha-3RB

*****核心代码*******

**注:打印机接收数据为 gbk转byte数组类型** 

/**
     * 传输数据
     * @param buffer
     */
    writeBLECharacteristicValue(buffer){
        let _this=this;

        if (this.maxLength>=buffer.length) {
            wx.showToast({title: '传输完成'});
            this.closeBLEConnection();
        }
        else{
            wx.writeBLECharacteristicValue({
                deviceId: _this.deviceId,
                serviceId: TSCPRINTER_SERVICE_UUID,
                characteristicId: WRITE_TO_TSCPRINTER_CHARACTERISTIC_UUID,
                value: buffer[this.maxLength],
                success: function (res) {
                    console.log("Success",buffer.length,_this.maxLength ,res);
                    setTimeout(()=>{
                        _this.writeBLECharacteristicValue(buffer);
                        _this.maxLength++;
                    },50)

                },
                fail: function (res) {
                    console.log("Fail", res);
                    _this.closeBLEConnection();
                }
            })
        }

    }

 //分包  
    cutCommand (arr:Array<number>) {
        let sendData64 = [];
        let packageLength = 20;
        debug("arr:",arr);
        //arr = [83,73,90,69,32,52,48,32,109,109,44,51,48,32,109,109,13,10,71,65,80,32,50,32,109,109,44,48,32,109,109,13,10,67,76,83,13,10,84,69,88,84,32,53,48,44,50,54,44,34,70,79,78,84,48,48,49,34,44,57,48,44,49,44,49,44,49,44,34,206,162,208,197,201,168,210,187,201,168,32,193,162,188,180,202,212,180,169,34,13,10,81,82,67,79,68,69,32,50,50,48,44,52,56,44,72,44,51,44,65,44,57,48,44,77,50,44,34,99,115,100,102,50,51,52,53,114,101,119,102,100,115,99,120,101,119,100,115,99,120,100,115,102,100,115,103,102,100,103,114,119,34,13,10,66,76,79,67,75,32,50,55,48,44,50,48,44,50,51,48,44,52,50,44,34,50,46,69,70,84,34,44,57,48,44,49,44,49,44,34,101,119,100,115,99,120,101,34,13,10,84,69,88,84,32,51,48,48,44,50,48,44,34,82,79,77,65,78,46,84,84,70,34,44,57,48,44,49,48,44,49,48,44,34,101,119,100,115,99,122,120,100,115,99,120,34,13,10,80,82,73,78,84,32,49,44,49,13,10];
        for (let i = 0; i < Math.ceil(arr.length / packageLength); i++) {
            sendData64[i] = str1ab(arr.slice(i * packageLength, (i+1) * packageLength));
        }
        debug("-------str2ab--------------",sendData64);
        return sendData64
    }


function str1ab(arr){
    let buffer = new ArrayBuffer(arr.length);
    let dataView = new Uint8Array(buffer);
    for (let i=0;i<arr.length;i++) {
        dataView[i] = arr[i]
    }
    return buffer;
}
 

猜你喜欢

转载自blog.csdn.net/weixin_39685861/article/details/88388237