从ESC/POS状态cod解释单个位

2024-06-16 15:44:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我承认,我正在从事的这个项目,并不是一个关于如何使用Python迈出第一步的教科书式的例子,但我现在就在这里。你知道吗

设置

一种ESC/POS打印机,与RaspberryPi本地连接(以太网、插座),远程接收打印作业(通过AMQP)。你知道吗

问题

连接到AMQP代理和打印机以及打印工作正常。我正在努力解决的是用ctypes处理打印机状态码。你知道吗

当我在互联网上搜索最佳方法时,我看到了一篇关于位操作的pythonwiki文章(link),其中提到对于像我这样的用法,建议使用ctype。这看起来确实是一种很棒的干净方法,所以我立即将其应用到我的代码中(下面是它的简化版本)。你知道吗

import socket
import ctypes

class PrinterStatus_bits( ctypes.LittleEndianStructure ):
    _fields_ = [
                ("fix0",        c_uint8, 1 ),  # asByte & 1
                ("fix1",        c_uint8, 1 ),  # asByte & 2
                ("drawer",      c_uint8, 1 ),  # asByte & 4
                ("offline",     c_uint8, 1 ),  # asByte & 8
                ("fix4",        c_uint8, 1 ),  # asByte & 16
                ("recovery",    c_uint8, 1 ),  # asByte & 32
                ("feed",        c_uint8, 1 ),  # asByte & 64
                ("fix7",        c_uint8, 1 ),  # asByte & 128
               ]

class Flags( ctypes.Union ):
    _anonymous_ = ("bit",)
    _fields_ = [
                ("bit",    PrinterStatus_bits),
                ("asByte", c_uint8           )
               ]


sock            = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address  = ('123.123.123.123', 9100)
c_uint8         = ctypes.c_uint8          
flags           = Flags()
msg             = b'\x10\x04\x01'

print('connecting to %s port %s' % server_address)
sock.connect(server_address)

print('requesting printer status')
sock.sendall(msg)
data           = sock.recv(1)
flags.asByte   = ord(data)

有意识地设置1字节的接收长度,因为这是响应的固定长度。然而,问题是,这只是第一个(四个)一般状态代码。你知道吗

我很想通过flags对象获得所有这些状态代码,只是不知道如何使用联合。你知道吗

如果我这样做:

class PrinterStatus_bits( ctypes.LittleEndianStructure ):
class PrinterOffline_bits( ctypes.LittleEndianStructure ):
class PrinterError_bits( ctypes.LittleEndianStructure ):
class PrinterPaper_bits( ctypes.LittleEndianStructure ):

class Flags( ctypes.Union ):
    _anonymous_ = ("status",)
    _fields_ = [
                ("status",   PrinterStatus_bits),
                ("offline",  PrinterOffline_bits),
                ("error",    PrinterError_bits),
                ("paper",    PrinterPaper_bits ),
                ("asByte",   c_uint8    )
               ]

我怎么给相应的类分配合适的值呢?你知道吗

附言。 所有4个状态码的长度总是正好为1字节

p.p.s.公司 我并没有下定决心使用ctypes,如果在这种情况下它不是一种有效的方法,我会很好地使用它,我只会遍历所有4个响应并将这些值赋给一个0/1数组,但是我的好奇心战胜了我,我想知道这样做是否可行


Tags: 方法代码fields状态打印机socketctypesclass