0

我正在使用 Python 构造库来解析蓝牙协议。图书馆的链接在这里

由于协议非常复杂,我将解析细分为多个阶段,而不是构建一个巨大的结构。现在我已经将大原始数据解析成这个结构:

Container({'CRC': 'd\xcbT',
 'CRC_OK': 1,
 'Channel': 38,
 'RSSI': 43,
 'access_addr': 2391391958L,
 'header': Container({'TxAdd': False, 'PDU_length': 34, 'PDU_Type': 'ADV_IND', 'RxAdd': False}),
 'payload': '2\x15\x00a\x02\x00\x02\x01\x06\x07\x03\x03\x18\x02\x18\x04\x18\x03\x19\x00\x02\x02\n\xfe\t\tAS-D1532'})

如您所见,有效负载的长度表示为 PDU_length,即 34。有效负载具有以下结构:

[前6个八位组:AdvertAddress][0-31个八位组的其余数据:AdvertData]

但是,当我开始将有效负载解析为独立结构时,我在有效负载构造的上下文中丢失了 34 的长度。如何创建一个将前 6 个八位字节解析为 AdvertAddress 并将其余数据分组为 AdvertData 的构造?

我目前的解决方案如下所示:

length = len(payload) #I didn't use PDU_length but len(payload) gives me back 34 also.
ADVERT_PAYLOAD = Struct("ADVERT_PAYLOAD",
    Field("AdvertAddress",6),
    Field("AdvertData",length-6),
)
print ADVERT_PAYLOAD.parse(payload)

这给出了正确的输出。但显然并非所有有效载荷的大小都是 34。这种方法需要我在ADVERT_PAYLOAD需要解析新的有效载荷时构造这个。

我多次阅读文档,但找不到任何相关内容。我无法将有效负载长度的知识传递到 的上下文中ADVERT_PAYLOAD,也无法获取传递给parse方法的参数的长度。

Maybe there is no solutions to this problem. But then, how do most people parse such protocol data? As you go further into the payload, it subdivides into more types and you need more more smaller constructs to parse them. Should I build a parent construct, embedding smaller constructs which embed even smaller constructs? I can't imagine how to go about building such a big thing.

Thanks in advance.

4

1 回答 1

1

GreedyRange will get a list of char, and JoinAdapter will join all the char together:

class JoinAdapter(Adapter):
    def _decode(self, obj, context):
        return "".join(obj)

ADVERT_PAYLOAD = Struct("ADVERT_PAYLOAD",
    Field("AdvertAddress",6),
    JoinAdapter(GreedyRange(Field("AdvertData", 1)))
)

payload = '2\x15\x00a\x02\x00\x02\x01\x06\x07\x03\x03\x18\x02\x18\x04\x18\x03\x19\x00\x02\x02\n\xfe\t\tAS-D1532'
print ADVERT_PAYLOAD.parse(payload)

output:

Container:
    AdvertAddress = '2\x15\x00a\x02\x00'
    AdvertData = '\x02\x01\x06\x07\x03\x03\x18\x02\x18\x04\x18\x03\x19\x00\x02\x02\n\xfe\t\tAS-D1532'
于 2013-03-21T05:06:55.017 回答