MX11 cat thermal printer android SDK

I have Python code that handles printing, and it works well. Now, I want to implement this functionality in an Android Studio Java project. To do this, I removed all the Bluetooth-related components from the Python code and integrated them into the Android project.now pythoncode only send printing body data packet to the main activity via pyObject

I have analyzed the data packet used by the Python code for printing. The first six packets are for configuration, followed by a 56-byte chunk for the print body (a 1-bit BMP image). After that, additional command byte arrays are included.

However, when I send these data packets from the Android script, the printer only feeds paper and does not print the image. I’m sending the data via Bluetooth Low Energy (BLE) by writing to the PrinterCharacteristic.

   private void runBackgroundTask( ) {
        System.out.println("Task started in background: " + Thread.currentThread());
        try {
            if (!Python.isStarted()) {
                Python.start(new AndroidPlatform(getApplicationContext()));
            }
            Python python = Python.getInstance();
            PyObject pythonModule = python.getModule("printJob");
            PyObject rawResult = pythonModule.callAttr("makeByteArr");
            String result = rawResult.toString().substring(1, rawResult.toString().length()  -1);
            String[] dataBuff=result.split(",");
            byte[][] dataPackets = {
                    {81, 120, (byte) 163, 0, 1, 0, 0, 0, (byte) 255},  //dev status
                    {81, 120, (byte) 164, 0, 1, 0, 51, (byte) 153, (byte) 255}, //dev status
                    {81, 120, (byte) 166, 0, 11, 0, (byte) 170, 85, 23, 56, 68, 95, 95, 95, 68, 56, 44, (byte) 161, (byte) 255}, //ControlLattice
                    {81, 120, (byte) 175, 0, 2, 0, (byte) 224, 46, (byte) 137, (byte) 255}, //ControlLattice
                    {81, 120, (byte) 190, 0, 1, 0, 1, 7, (byte) 255}, //ControlLattice
                    {81, 120, (byte) 189, 0, 1, 0, 35, (byte) 233, (byte) 255}, //ControlLattice
                    {81, 120, (byte) 166, 0, 11, 0, (byte) 170, 85, 23, 0, 0, 0, 0, 0, 0, 0, 23, 17, (byte) 255}, //ControlLattice
                    {81, 120, (byte) 189, 0, 1, 0, 25, 79, (byte) 255}, //ControlLattice
                    {81, 120, (byte) 161, 0, 2, 0, 55, 0, (byte) 146, (byte) 255} //ControlLattice
            };
            byte packeyCount=0;
            byte[] byteArray = new byte[56];
           // Log.d("full","Len "+byteArray.length+" " +packeyCount+" " );
            for (byte[] packet : dataPackets) {
                // Optionally add a delay if needed to avoid flooding the BLE stack
                try {
                   if (packeyCount++==6){
                        int bitCount=0;
                        int i=0;
                        for (  i = 0; i < dataBuff.length; i++) {
                            int value = Integer.parseInt(dataBuff[i].trim()); // Convert string to integer
                            byteArray[bitCount++] = (byte) value; // Convert integer to byte
                            if (bitCount==56) {
                                bitCount = 0;
                                bluetoothHelper.sendData(byteArray);
                               // Log.d("imgsend","Len "+byteArray.length+" " +(i%256)+" "+ Arrays.toString(byteArray));
                                Thread.sleep(5);
                            }

                        }
                    }
                    bluetoothHelper.sendData(packet);

                    //Log.d("dsds","Len "+packet.length+" " +packeyCount+" "+ Arrays.toString(packet));
                    Thread.sleep(1); // 50 ms delay between packets
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    Log.d("Errorble",e.toString());
                }
            }
 
            Thread.sleep(20); // Simulate background work
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            Log.d("Eror",e.toString());
        }
        System.out.println("Task completed.");
    }

actual data packet

first command set
0x51', '0x78', '0xa3', '0x00', '0x01', '0x00', '0x00', '0x00', '0xff', '    dev status
0x51', '0x78', '0xa4', '0x00', '0x01', '0x00', '0x33', '0x99', '0xff', '    setqulty    
0x51', '0x78', '0xa6', '0x00', '0x0b', '0x00', '0xaa', '0x55', '0x17', '0x38', '0x44', '0x5f', '0x5f', '0x5f', '0x44', '0x38', '0x2c', '0xa1', '0xff', ' ControlLattice
0x51', '0x78', '0xaf', '0x00', '0x02', '0x00', '0xe0', '0x2e', '0x89', '0xff', ' SetEnergy
0x51', '0x78', '0xbe', '0x00', '0x01', '0x00', '0x01', '0x07', '0xff', ' DrawingMode
0x51', '0x78', '0xbd', '0x00', '0x01', '0x00', '0x23', '0xe9', '0xff', ' OtherFeedPaper
// bmp message body data
0x51', '0x78', '0xa2', '0x00', '0x30', '0x00', '0x00', '   '0x00', '0x1a', '0x00', '0xa0', '0x01', '0x00', '0x1a', '0x00', '0x00', '0x47', '0xff', '
0x51', '0x78', '0xa2', '0x00', '0x30', '0x00', '0x00', ' 0x0a', '0x00', '0xa0', '0x00', '0x00', '0x0a', '0x00', '0x00', '0x42', '0xff', '
0x51', '0x78', '0xa2', '0x00', '0x30', '0x00', '0x00', '0x00', '0x1e', '0x00', '0xe0', '0x01', '0x00', '0x1e', '0x00', '0x00', '0xc5', '0xff', '
0x51', '0x78', '0xa2', '0x00', '0x30', '0x00', '0x00',  '0xa0', '0x00', '0x00', '0x0a', '0x00', '0x00', '0x42', '0xff', ' 
other command set
0x51', '0x78', '0xa6',  '0x00', '0x00', '0x00', '0x00', '0x17', '0x11', '0xff', '  ControlLattice
0x51', '0x78', '0xbd', '0x00', '0x01', '0x00', '0x19', '0x4f', '0xff', ' OtherFeedPaper
0x51', '0x78', '0xa1', '0x00', '0x02', '0x00', '0x37', '0x00', '0x92', '0xff']  FeedPaper

python code block

#!/usr/bin/env python3
import os
import asyncio
import argparse
import time
import contextlib


import PIL.Image
import PIL.ImageFont
import PIL.ImageDraw
import PIL.ImageChops
import filetype

# CRC8 table extracted from APK, pretty standard though
crc8_table = (
    0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15, 0x38, 0x3f, 0x36, 0x31,
    0x24, 0x23, 0x2a, 0x2d, 0x70, 0x77, 0x7e, 0x79, 0x6c, 0x6b, 0x62, 0x65,
    0x48, 0x4f, 0x46, 0x41, 0x54, 0x53, 0x5a, 0x5d, 0xe0, 0xe7, 0xee, 0xe9,
    0xfc, 0xfb, 0xf2, 0xf5, 0xd8, 0xdf, 0xd6, 0xd1, 0xc4, 0xc3, 0xca, 0xcd,
    0x90, 0x97, 0x9e, 0x99, 0x8c, 0x8b, 0x82, 0x85, 0xa8, 0xaf, 0xa6, 0xa1,
    0xb4, 0xb3, 0xba, 0xbd, 0xc7, 0xc0, 0xc9, 0xce, 0xdb, 0xdc, 0xd5, 0xd2,
    0xff, 0xf8, 0xf1, 0xf6, 0xe3, 0xe4, 0xed, 0xea, 0xb7, 0xb0, 0xb9, 0xbe,
    0xab, 0xac, 0xa5, 0xa2, 0x8f, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9d, 0x9a,
    0x27, 0x20, 0x29, 0x2e, 0x3b, 0x3c, 0x35, 0x32, 0x1f, 0x18, 0x11, 0x16,
    0x03, 0x04, 0x0d, 0x0a, 0x57, 0x50, 0x59, 0x5e, 0x4b, 0x4c, 0x45, 0x42,
    0x6f, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7d, 0x7a, 0x89, 0x8e, 0x87, 0x80,
    0x95, 0x92, 0x9b, 0x9c, 0xb1, 0xb6, 0xbf, 0xb8, 0xad, 0xaa, 0xa3, 0xa4,
    0xf9, 0xfe, 0xf7, 0xf0, 0xe5, 0xe2, 0xeb, 0xec, 0xc1, 0xc6, 0xcf, 0xc8,
    0xdd, 0xda, 0xd3, 0xd4, 0x69, 0x6e, 0x67, 0x60, 0x75, 0x72, 0x7b, 0x7c,
    0x51, 0x56, 0x5f, 0x58, 0x4d, 0x4a, 0x43, 0x44, 0x19, 0x1e, 0x17, 0x10,
    0x05, 0x02, 0x0b, 0x0c, 0x21, 0x26, 0x2f, 0x28, 0x3d, 0x3a, 0x33, 0x34,
    0x4e, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5c, 0x5b, 0x76, 0x71, 0x78, 0x7f,
    0x6a, 0x6d, 0x64, 0x63, 0x3e, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2c, 0x2b,
    0x06, 0x01, 0x08, 0x0f, 0x1a, 0x1d, 0x14, 0x13, 0xae, 0xa9, 0xa0, 0xa7,
    0xb2, 0xb5, 0xbc, 0xbb, 0x96, 0x91, 0x98, 0x9f, 0x8a, 0x8d, 0x84, 0x83,
    0xde, 0xd9, 0xd0, 0xd7, 0xc2, 0xc5, 0xcc, 0xcb, 0xe6, 0xe1, 0xe8, 0xef,
    0xfa, 0xfd, 0xf4, 0xf3
)


def crc8(data):
    crc = 0
    for byte in data:
        crc = crc8_table[(crc ^ byte) & 0xFF]
    return crc & 0xFF


# General message format:
# Magic number: 2 bytes 0x51, 0x78
# Command: 1 byte
# 0x00
# Data length: 1 byte
# 0x00
# Data: Data Length bytes
# CRC8 of Data: 1 byte
# 0xFF
def format_message(command, data):
    data = [0x51, 0x78] + [command] + [0x00] + [len(data)] + [0x00] + data + [crc8(data)] + [0xFF]
    return data


def printer_short(i):
    return [i & 0xFF, (i >> 8) & 0xFF]


# Commands
RetractPaper = 0xA0  # Data: Number of steps to go back  160
FeedPaper = 0xA1  # Data: Number of steps to go forward  161
DrawBitmap = 0xA2  # Data: Line to draw. 0 bit -> don't draw pixel, 1 bit -> draw pixel 162
GetDevState = 0xA3  # Data: 0 163
ControlLattice = 0xA6  # Data: Eleven bytes, all constants. One set used before printing, one after. 166
GetDevInfo = 0xA8  # Data: 0  168
OtherFeedPaper = 0xBD  # Data: one byte, set to a device-specific "Speed" value before printing
#                              and to 0x19 before feeding blank paper  189
DrawingMode = 0xBE  # Data: 1 for Text, 0 for Images  190
SetEnergy = 0xAF  # Data: 1 - 0xFFFF  175
SetQuality = 0xA4  # Data: 0x31 - 0x35. APK always sets 0x33 for GB01 164

PrintLattice = [0xAA, 0x55, 0x17, 0x38, 0x44, 0x5F, 0x5F, 0x5F, 0x44, 0x38, 0x2C]
FinishLattice = [0xAA, 0x55, 0x17, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x17]
XOff = (0x51, 0x78, 0xAE, 0x01, 0x01, 0x00, 0x10, 0x70, 0xFF)
XOn = (0x51, 0x78, 0xAE, 0x01, 0x01, 0x00, 0x00, 0x00, 0xFF)

energy = {
    0: printer_short(8000),
    1: printer_short(12000),
    2: printer_short(17500)
}
contrast = 1

PrinterWidth = 384

ImgPrintSpeed = [0x23]
BlankSpeed = [0x19]

feed_lines = 55
header_lines = 0
scale_feed = False

default_font_name = "/data/data/com.ainven.farmman/files/chaquopy/fonts/iskpota.ttf"

packet_length = 60
throttle = 0.01

address = None

device = None

# show notification data
debug = False






async def connect_and_send(data_iter):

    count=0

    for data in data_iter:
        count=0
        sendBuf=[]
        dataPacketLen = int(len(data)/255)
        if (len(data)/255!=0):
            dataPacketLen=dataPacketLen+1

        return data





def request_status():
    return format_message(GetDevState, [0x00])


def blank_paper(lines):
    # Feed extra paper for image to be visible
    blank_commands = format_message(OtherFeedPaper, BlankSpeed)
    count = lines
    while count:
        feed = min(count, 0xFF)
        blank_commands = blank_commands + format_message(FeedPaper, printer_short(feed))
        count = count - feed
    return blank_commands


def get_wrapped_text(text: str, font: PIL.ImageFont.ImageFont,
                     line_length: int):
    if font.getlength(text) <= line_length:
        return text

    lines = ['']
    for word in text.split():
        line = f'{lines[-1]} {word}'.strip()
        if font.getlength(line) <= line_length:
            lines[-1] = line
        else:
            lines.append(word)
    return 'n'.join(lines)


def trim(im):
    bg = PIL.Image.new(im.mode, im.size, (255,255,255))
    diff = PIL.ImageChops.difference(im, bg)
    diff = PIL.ImageChops.add(diff, diff, 2.0)
    bbox = diff.getbbox()
    if bbox:
        return im.crop((bbox[0],bbox[1],bbox[2],bbox[3]+10)) # don't cut off the end of the image


def convert_text_to_img(text: list[str], font_name=default_font_name, font_size=20):
    img = PIL.Image.new('RGB', (PrinterWidth, 5000), color = (255, 255, 255))
    font = PIL.ImageFont.truetype(font_name, font_size)

    d = PIL.ImageDraw.Draw(img)
    lines = []
    for line in text:
        lines.append(get_wrapped_text(line, font, PrinterWidth))
    lines = "n".join(lines)
    lines = lines.replace("nn", "n")
    d.multiline_text((0,0), text, fill=(0,0,0), align="left", font=font, spacing=0)
    return trim(img)


def render_image(img):
    global header_lines
    global feed_lines
    cmdqueue = []
    if img.width > PrinterWidth:
        # image is wider than printer resolution; scale it down proportionately
        scale = PrinterWidth / img.width
        if scale_feed:
            header_lines = int(header_lines * scale)
            feed_lines = int(feed_lines * scale)
        img = img.resize((PrinterWidth, int(img.height * scale)))
    if img.width < (PrinterWidth // 2):
        # scale up to largest whole multiple
        scale = PrinterWidth // img.width
        if scale_feed:
            header_lines = int(header_lines * scale)
            feed_lines = int(feed_lines * scale)
        img = img.resize((img.width * scale, img.height * scale), resample=PIL.Image.NEAREST)
    # convert image to black-and-white 1bpp color format
    img = img.convert("RGB")
    img = img.convert("1")
    if img.width < PrinterWidth:
        # image is narrower than printer resolution
        # pad it out with white pixels
        pad_amount = (PrinterWidth - img.width) // 2
        padded_image = PIL.Image.new("1", (PrinterWidth, img.height), 1)
        padded_image.paste(img, box=(pad_amount, 0))
        img = padded_image

    if header_lines:
        cmdqueue += blank_paper(header_lines)

    for y in range(0, img.height):
        bmp = []
        bit = 0
        # pack image data into 8 pixels per byte
        for x in range(0, img.width):
            if bit % 8 == 0:
                bmp += [0x00]
            bmp[int(bit / 8)] >>= 1
            if not img.getpixel((x, y)):
                bmp[int(bit / 8)] |= 0x80
            else:
                bmp[int(bit / 8)] |= 0

            bit += 1

        cmdqueue += format_message(DrawBitmap, bmp)

    # finish the lattice, whatever that means
    cmdqueue += format_message(ControlLattice, FinishLattice)

    return cmdqueue



def produce_print_data(eject: bool, no_eject: bool, assume_text: bool, filename: str, ):
    #print_data = request_status()
    print_data=[]
    if not eject:
        image = convert_text_to_img(filename)

        print_data = print_data + render_image(image)
    if not no_eject:
        print_data = print_data + blank_paper(feed_lines)
    return print_data
def makeByteArr():
    print_data = produce_print_data(
        eject=False,
        no_eject=False,
        assume_text=True,
        filename="******************namal",
    )
    return  print_data

    #await client.write_gatt_char(PrinterCharacteristic, formatMessage(FeedPaper, [0, 1]))

makeByteArr()


i followed this steps

text

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật