如何使用struct.pack格式构造字节?

2024-04-25 21:08:59 发布

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

背景

我用python-seabreeze与分光计交谈。一些但不是所有可用的命令都是用python seabreeze实现的。我可以从OceanOptics Flame-T manual中看到以下命令(例如):

.
.
0x09 Request Spectra
0x0A Set Trigger Mode
0x0B Query number of Plug-in Accessories Present
0x0C Query Plug-in Identifiers
0x0D Detect Plug-ins
0x12 LED Status
0x60 General I2C Read
0x61 General I2C Write
0x62 General SPI I/O
0x68 PSOC Read
0x69 PSOC Write
0x6A Write Register Information
0x6B Read Register Information
0x6C Read PCB Temperature
0x6D Read Irradiance Calibration
.
.

seabreeze/pyseabreeze/protocol.py中,我可以看到这些命令的格式如下:

import functools
import struct 

msgs = {
    code: functools.partial(struct.Struct(msg).pack, code)
    for code, msg in {
        0x01: "<B",  # OP_INITIALIZE
        0x02: "<BI",  # OP_ITIME
        0x03: "<BH",  # set Strobe/Lamp enable Line
        0x05: "<BB",  # OP_GETINFO
        0x09: "<B",  # OP_REQUESTSPEC
        0x0A: "<BH",  # OP_SETTRIGMODE
        0x6A: "<BBH",  # OP_WRITE_REGISTER
        0x6B: "<BB",  # OP_READ_REGISTER
        0x71: "<BBB",  # OP_TECENABLE_QE
        0x72: "<B",  # OP_READTEC_QE
        0x73: "<Bh",  # OP_TECSETTEMP_QE
        0xFE: "<B",  # OP_USBMODE
    }.items()
}  # add more here if you implement new features

例如,根据手册,Request Spectra0x09,当它来自python时,会显示一条消息

struct.Struct('<B').pack(0x09)

他被派去了。我试图通过阅读struct format strings来了解发生了什么,我发现<表示“小尾端”B表示无符号字符h表示短字符,等等

问题

人们如何从手册中知道OP_GETINFO格式是<BB,而OP_WRITE_REGISTER格式是<BBH?这里的逻辑是什么?你会为0x6C Read PCB Temperature的格式写什么?为什么


Tags: in命令registerreadrequest格式codestruct
1条回答
网友
1楼 · 发布于 2024-04-25 21:08:59

似乎您需要阅读发送合法命令需要使用的参数,此协议仅定义您希望发送的某些项目,例如:

code_partial_function = functools.partial(struct.Struct(msg).pack, code)
...
0x6B: "<BB",  # OP_READ_REGISTER
...

# used like this later:
# example for register number 1
# final_packed_bytes will contain both the operation id and the register number
final_packed_bytes = code_partial_function(0x1)

对于此操作读取寄存器,protocol.py将创建一个已包含操作id(0x6b)的部分函数,并请求您提供额外的“B”,表示另一个无符号字符,可能是您希望读取的寄存器号

协议仅将ID作为第一个输入提供给pack函数,而将其余值留给用户。 每个操作在操作id之后都需要不同的值,有些需要更多(“BBH”),有些需要更少(“B”)

对于0x6c,我将搜索该格式,并从中了解我还剩下什么来提供这个包函数

相关问题 更多 >