11"""API to interact with the Open Thread Border Router REST API."""
22
33from __future__ import annotations
4+
5+ from enum import Enum
46from http import HTTPStatus
7+ from typing import Any
58import json
9+ import logging
610
711import aiohttp
812import voluptuous as vol # type: ignore[import]
1317# https://github.com/openthread/openthread/discussions/8567#discussioncomment-4468920
1418PENDING_DATASET_DELAY_TIMER = 5 * 60 * 1000
1519
20+ _LOGGER = logging .getLogger (__name__ )
21+
22+ # OTBR flipped the REST API from PascalCase to camelCase in ot-br-posix
23+ # PR #2514 (Sept 2025). The models speak camelCase internally; this table
24+ # translates both directions at the HTTP boundary for legacy servers.
25+ _CAMEL_TO_PASCAL : dict [str , str ] = {
26+ # Timestamp
27+ "authoritative" : "Authoritative" ,
28+ "seconds" : "Seconds" ,
29+ "ticks" : "Ticks" ,
30+ # SecurityPolicy
31+ "autonomousEnrollment" : "AutonomousEnrollment" ,
32+ "commercialCommissioning" : "CommercialCommissioning" ,
33+ "externalCommissioning" : "ExternalCommissioning" ,
34+ "nativeCommissioning" : "NativeCommissioning" ,
35+ "networkKeyProvisioning" : "NetworkKeyProvisioning" ,
36+ "nonCcmRouters" : "NonCcmRouters" ,
37+ "obtainNetworkKey" : "ObtainNetworkKey" ,
38+ "rotationTime" : "RotationTime" ,
39+ "routers" : "Routers" ,
40+ "tobleLink" : "TobleLink" ,
41+ # ActiveDataSet
42+ "activeTimestamp" : "ActiveTimestamp" ,
43+ "channelMask" : "ChannelMask" ,
44+ "channel" : "Channel" ,
45+ "extPanId" : "ExtPanId" ,
46+ "meshLocalPrefix" : "MeshLocalPrefix" ,
47+ "networkKey" : "NetworkKey" ,
48+ "networkName" : "NetworkName" ,
49+ "panId" : "PanId" ,
50+ "pskc" : "PSKc" ,
51+ "securityPolicy" : "SecurityPolicy" ,
52+ # PendingDataSet
53+ "activeDataset" : "ActiveDataset" ,
54+ "delay" : "Delay" ,
55+ "pendingTimestamp" : "PendingTimestamp" ,
56+ }
57+ _PASCAL_TO_CAMEL : dict [str , str ] = {v : k for k , v in _CAMEL_TO_PASCAL .items ()}
58+
59+
60+ class KeyFormat (Enum ):
61+ """JSON key format used by the OTBR REST API.
62+
63+ PASCAL_CASE is the pre-Sept-2025 wire format (ot-br-posix pre-#2514):
64+ writes are rewritten to PascalCase. CAMEL_CASE covers every post-flip
65+ server, including the Sept-2025..April-2026 window where some keys
66+ (e.g. `Routers` in SecurityPolicy) still came back PascalCase — reads
67+ always run through the PascalCase normalization table so those
68+ stragglers are picked up transparently.
69+ """
70+
71+ CAMEL_CASE = "camel"
72+ PASCAL_CASE = "pascal"
73+
1674
1775class OTBRError (Exception ):
1876 """Raised on error."""
@@ -30,20 +88,69 @@ class ThreadNetworkActiveError(OTBRError):
3088 """Raised on attempts to modify the active dataset when thread network is active."""
3189
3290
91+ def _rewrite_keys (data : Any , mapping : dict [str , str ]) -> Any :
92+ """Recursively rename dict keys according to mapping; pass through others."""
93+ if not isinstance (data , dict ):
94+ return data
95+ return {mapping .get (k , k ): _rewrite_keys (v , mapping ) for k , v in data .items ()}
96+
97+
3398class OTBR : # pylint: disable=too-few-public-methods
3499 """Class to interact with the Open Thread Border Router REST API."""
35100
36101 def __init__ (
37- self , url : str , session : aiohttp .ClientSession , timeout : int = 10
102+ self ,
103+ url : str ,
104+ session : aiohttp .ClientSession ,
105+ timeout : int = 10 ,
106+ * ,
107+ key_format : KeyFormat | None = None ,
38108 ) -> None :
39109 """Initialize."""
40110 self ._session = session
41111 self ._url = url
42112 self ._timeout = timeout
113+ self ._key_format = key_format
114+
115+ async def _maybe_detect_key_format (self ) -> None :
116+ """Probe the OTBR REST API to determine the JSON key format."""
117+ if self ._key_format is not None :
118+ return
119+
120+ response = await self ._session .get (
121+ f"{ self ._url } /api/actions" ,
122+ timeout = aiohttp .ClientTimeout (total = self ._timeout ),
123+ )
124+
125+ if response .status == HTTPStatus .OK :
126+ self ._key_format = KeyFormat .CAMEL_CASE
127+ elif response .status == HTTPStatus .NOT_FOUND :
128+ self ._key_format = KeyFormat .PASCAL_CASE
129+ else :
130+ raise OTBRError (
131+ f"could not detect OTBR version: unexpected http status "
132+ f"{ response .status } "
133+ )
134+
135+ _LOGGER .debug ("Detected OTBR JSON key format: %s" , self ._key_format )
136+
137+ def _encode (self , data : dict ) -> dict :
138+ """Rewrite a camelCase body to the detected wire format."""
139+ if self ._key_format == KeyFormat .PASCAL_CASE :
140+ return _rewrite_keys (data , _CAMEL_TO_PASCAL )
141+ return data
142+
143+ def _decode (self , data : dict ) -> dict :
144+ """Normalize a wire response body to camelCase."""
145+
146+ # Runs unconditionally: camelCase keys aren't in the table so they pass through
147+ # untouched, while any PascalCase stragglers (full legacy or transition-era
148+ # leftovers like `Routers`) get fixed.
149+ return _rewrite_keys (data , _PASCAL_TO_CAMEL )
43150
44151 async def factory_reset (self ) -> None :
45152 """Factory reset the router."""
46-
153+ await self . _maybe_detect_key_format ()
47154 response = await self ._session .delete (
48155 f"{ self ._url } /node" ,
49156 timeout = aiohttp .ClientTimeout (total = 10 ),
@@ -57,6 +164,7 @@ async def factory_reset(self) -> None:
57164
58165 async def get_border_agent_id (self ) -> bytes :
59166 """Get the border agent ID."""
167+ await self ._maybe_detect_key_format ()
60168 response = await self ._session .get (
61169 f"{ self ._url } /node/ba-id" ,
62170 timeout = aiohttp .ClientTimeout (total = self ._timeout ),
@@ -75,7 +183,7 @@ async def get_border_agent_id(self) -> bytes:
75183
76184 async def set_enabled (self , enabled : bool ) -> None :
77185 """Enable or disable the router."""
78-
186+ await self . _maybe_detect_key_format ()
79187 response = await self ._session .put (
80188 f"{ self ._url } /node/state" ,
81189 json = "enable" if enabled else "disable" ,
@@ -91,6 +199,7 @@ async def get_active_dataset(self) -> ActiveDataSet | None:
91199 Returns None if there is no active operational dataset.
92200 Raises if the http status is 400 or higher or if the response is invalid.
93201 """
202+ await self ._maybe_detect_key_format ()
94203 response = await self ._session .get (
95204 f"{ self ._url } /node/dataset/active" ,
96205 timeout = aiohttp .ClientTimeout (total = self ._timeout ),
@@ -103,7 +212,7 @@ async def get_active_dataset(self) -> ActiveDataSet | None:
103212 raise OTBRError (f"unexpected http status { response .status } " )
104213
105214 try :
106- return ActiveDataSet .from_json (await response .json ())
215+ return ActiveDataSet .from_json (self . _decode ( await response .json () ))
107216 except (json .JSONDecodeError , vol .Error ) as exc :
108217 raise OTBRError ("unexpected API response" ) from exc
109218
@@ -113,6 +222,7 @@ async def get_active_dataset_tlvs(self) -> bytes | None:
113222 Returns None if there is no active operational dataset.
114223 Raises if the http status is 400 or higher or if the response is invalid.
115224 """
225+ await self ._maybe_detect_key_format ()
116226 response = await self ._session .get (
117227 f"{ self ._url } /node/dataset/active" ,
118228 headers = {"Accept" : "text/plain" },
@@ -136,6 +246,7 @@ async def get_pending_dataset_tlvs(self) -> bytes | None:
136246 Returns None if there is no pending operational dataset.
137247 Raises if the http status is 400 or higher or if the response is invalid.
138248 """
249+ await self ._maybe_detect_key_format ()
139250 response = await self ._session .get (
140251 f"{ self ._url } /node/dataset/pending" ,
141252 headers = {"Accept" : "text/plain" },
@@ -160,9 +271,10 @@ async def create_active_dataset(self, dataset: ActiveDataSet) -> None:
160271 not set will be automatically set by the open thread border router.
161272 Raises if the http status is 400 or higher or if the response is invalid.
162273 """
274+ await self ._maybe_detect_key_format ()
163275 response = await self ._session .put (
164276 f"{ self ._url } /node/dataset/active" ,
165- json = dataset .as_json (),
277+ json = self . _encode ( dataset .as_json () ),
166278 timeout = aiohttp .ClientTimeout (total = self ._timeout ),
167279 )
168280
@@ -173,6 +285,7 @@ async def create_active_dataset(self, dataset: ActiveDataSet) -> None:
173285
174286 async def delete_active_dataset (self ) -> None :
175287 """Delete active operational dataset."""
288+ await self ._maybe_detect_key_format ()
176289 response = await self ._session .delete (
177290 f"{ self ._url } /node/dataset/active" ,
178291 timeout = aiohttp .ClientTimeout (total = self ._timeout ),
@@ -190,9 +303,10 @@ async def create_pending_dataset(self, dataset: PendingDataSet) -> None:
190303 not set will be automatically set by the open thread border router.
191304 Raises if the http status is 400 or higher or if the response is invalid.
192305 """
306+ await self ._maybe_detect_key_format ()
193307 response = await self ._session .put (
194308 f"{ self ._url } /node/dataset/pending" ,
195- json = dataset .as_json (),
309+ json = self . _encode ( dataset .as_json () ),
196310 timeout = aiohttp .ClientTimeout (total = self ._timeout ),
197311 )
198312
@@ -203,6 +317,7 @@ async def create_pending_dataset(self, dataset: PendingDataSet) -> None:
203317
204318 async def delete_pending_dataset (self ) -> None :
205319 """Delete pending operational dataset."""
320+ await self ._maybe_detect_key_format ()
206321 response = await self ._session .delete (
207322 f"{ self ._url } /node/dataset/pending" ,
208323 timeout = aiohttp .ClientTimeout (total = self ._timeout ),
@@ -218,7 +333,7 @@ async def set_active_dataset_tlvs(self, dataset: bytes) -> None:
218333
219334 Raises if the http status is 400 or higher or if the response is invalid.
220335 """
221-
336+ await self . _maybe_detect_key_format ()
222337 response = await self ._session .put (
223338 f"{ self ._url } /node/dataset/active" ,
224339 data = dataset .hex (),
@@ -258,6 +373,7 @@ async def get_extended_address(self) -> bytes:
258373
259374 Raises if the http status is not 200 or if the response is invalid.
260375 """
376+ await self ._maybe_detect_key_format ()
261377 response = await self ._session .get (
262378 f"{ self ._url } /node/ext-address" ,
263379 headers = {"Accept" : "application/json" },
@@ -277,7 +393,7 @@ async def get_coprocessor_version(self) -> str:
277393
278394 Raises if the http status is not 200 or if the response is invalid.
279395 """
280-
396+ await self . _maybe_detect_key_format ()
281397 response = await self ._session .get (
282398 f"{ self ._url } /node/coprocessor/version" ,
283399 headers = {"Accept" : "application/json" },
0 commit comments