Skip to content

Commit

Permalink
Add support for encoding a TLV string
Browse files Browse the repository at this point in the history
  • Loading branch information
emontnemery committed May 29, 2023
1 parent ea673a7 commit 04ddc4c
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
25 changes: 25 additions & 0 deletions python_otbr_api/tlv_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from __future__ import annotations

from enum import IntEnum
import struct


class TLVError(Exception):
Expand Down Expand Up @@ -53,6 +54,30 @@ class MeshcopTLVType(IntEnum):
JOINERADVERTISEMENT = 241


def _encode_item(tag: MeshcopTLVType, data: str) -> bytes:
"""Encode a dataset item to TLV format."""
if tag == MeshcopTLVType.NETWORKNAME:
data_bytes = bytes(data, "utf-8")
else:
data_bytes = bytes.fromhex(data)

data_len = len(data_bytes)
return struct.pack(f"!BB{data_len}s", tag, data_len, data_bytes)


def encode_tlv(items: dict[MeshcopTLVType, str]) -> str:
"""Encode a TLV encoded dataset to a hex string.
Raises if the TLV is invalid.
"""
result = b""

for item_type, item in items.items():
result += _encode_item(item_type, item)

return result.hex()


def _parse_item(tag: MeshcopTLVType, data: bytes) -> str:
"""Parse a TLV encoded dataset item."""
if tag == MeshcopTLVType.NETWORKNAME:
Expand Down
27 changes: 26 additions & 1 deletion tests/test_tlv_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,32 @@

import pytest

from python_otbr_api.tlv_parser import MeshcopTLVType, TLVError, parse_tlv
from python_otbr_api.tlv_parser import MeshcopTLVType, TLVError, encode_tlv, parse_tlv


def test_encode_tlv() -> None:
"""Test the TLV parser."""
dataset = {
MeshcopTLVType.ACTIVETIMESTAMP: "0000000000010000",
MeshcopTLVType.CHANNEL: "00000f",
MeshcopTLVType.CHANNELMASK: "0004001fffe0",
MeshcopTLVType.EXTPANID: "1111111122222222",
MeshcopTLVType.MESHLOCALPREFIX: "fdad70bfe5aa15dd",
MeshcopTLVType.NETWORKKEY: "00112233445566778899aabbccddeeff",
MeshcopTLVType.NETWORKNAME: "OpenThreadDemo",
MeshcopTLVType.PANID: "1234",
MeshcopTLVType.PSKC: "445f2b5ca6f2a93a55ce570a70efeecb",
MeshcopTLVType.SECURITYPOLICY: "02a0f7f8",
}
dataset_tlv = encode_tlv(dataset)
assert (
dataset_tlv
== (
"0E080000000000010000000300000F35060004001FFFE0020811111111222222220708FDAD"
"70BFE5AA15DD051000112233445566778899AABBCCDDEEFF030E4F70656E54687265616444"
"656D6F010212340410445F2B5CA6F2A93A55CE570A70EFEECB0C0402A0F7F8"
).lower()
)


def test_parse_tlv() -> None:
Expand Down

0 comments on commit 04ddc4c

Please sign in to comment.