dibd-led-protocol 1.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,189 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Support. While redistributing the Work or
166
+ Derivative Works thereof, You may accept support, warranty, indemnity,
167
+ or other liability obligations and/or rights consistent with this
168
+ License. However, in accepting such obligations, You may act only
169
+ on Your own behalf and on Your sole responsibility, not on behalf
170
+ of any other Contributor, and only if You agree to indemnify,
171
+ defend, and hold each Contributor harmless for any liability
172
+ incurred by, or claims asserted against, such Contributor by reason
173
+ of your accepting any such warranty or support.
174
+
175
+ END OF TERMS AND CONDITIONS
176
+
177
+ Copyright 2026 DabitSol Co., Ltd.
178
+
179
+ Licensed under the Apache License, Version 2.0 (the "License");
180
+ you may not use this file except in compliance with the License.
181
+ You may obtain a copy of the License at
182
+
183
+ http://www.apache.org/licenses/LICENSE-2.0
184
+
185
+ Unless required by applicable law or agreed to in writing, software
186
+ distributed under the License is distributed on an "AS IS" BASIS,
187
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
188
+ implied. See the License for the specific language governing permissions
189
+ and limitations under the License.
@@ -0,0 +1,7 @@
1
+ include LICENSE
2
+ include README.md
3
+ include openrpc.json
4
+ recursive-include dibd *.py *.typed
5
+ exclude *.pyc
6
+ prune __pycache__
7
+ prune *.egg-info
@@ -0,0 +1,104 @@
1
+ Metadata-Version: 2.4
2
+ Name: dibd-led-protocol
3
+ Version: 1.2.0
4
+ Summary: DIBD LED 전광판 JSON-RPC 2.0 envelope client (UDP / TCP / HTTP)
5
+ Author: DabitSol Co., Ltd.
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/DabitSol/dibd-led-protocol
8
+ Project-URL: Repository, https://github.com/DabitSol/dibd-led-protocol
9
+ Project-URL: Documentation, https://github.com/DabitSol/dibd-led-protocol#readme
10
+ Project-URL: Issues, https://github.com/DabitSol/dibd-led-protocol/issues
11
+ Keywords: dibd,led,display,protocol,jsonrpc,openrpc,iot
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Communications
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Classifier: Topic :: System :: Hardware
23
+ Requires-Python: >=3.10
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Provides-Extra: dev
27
+ Requires-Dist: build>=1.0; extra == "dev"
28
+ Requires-Dist: twine>=4.0; extra == "dev"
29
+ Requires-Dist: pytest>=7.0; extra == "dev"
30
+ Dynamic: license-file
31
+
32
+ # dibd-led-protocol — DIBD LED 전광판 공개 표준 프로토콜
33
+
34
+ JSON-RPC 2.0 envelope 정합 + Python SDK + OpenRPC 1.3.2 spec + conformance test 본질 정합.
35
+
36
+ ## 본 repo 영역
37
+
38
+ | 영역 | 위치 |
39
+ |---|---|
40
+ | Python SDK 본문 | `dibd/` (96 method auto-gen, jsonrpc 2.0 envelope, stdlib 한정) |
41
+ | OpenRPC spec | `openrpc.json` (96 method spec, 표준 1.3.2) |
42
+ | 변환 도구 | `../schema_to_openrpc.py` (protocol_schema.json → openrpc.json) |
43
+ | SDK 생성 wrapper | `generate_sdk.py` (openrpc.json → dibd/methods.py) |
44
+ | 빌드 설정 | `pyproject.toml` (setuptools 본문, Python ≥3.10, Apache-2.0) |
45
+ | LICENSE | Apache 2.0 |
46
+
47
+ ## 5분 시작
48
+
49
+ 로컬 설치 (PyPI 부재 영역):
50
+
51
+ ```bash
52
+ cd Controller/tools/python_sdk/
53
+ pip install -e .
54
+ ```
55
+
56
+ 사용:
57
+
58
+ ```python
59
+ from dibd import DibdClient
60
+
61
+ c = DibdClient("192.168.1.211") # UDP default port 50000
62
+ size = c.invoke("display.size.read")
63
+ c.invoke("display.brightness.write", {"level": 50})
64
+ c.close()
65
+ ```
66
+
67
+ 상세 본 본문 = `dibd/README.md`.
68
+
69
+ ## 옛 ASCII frame 호환
70
+
71
+ `raw_ascii()` path 옛 ASCII frame 본문 직접 송신. 옛 다빛채 호환 영역 그대로.
72
+
73
+ ## SDK 재생성 흐름
74
+
75
+ protocol_schema.json 갱신 후:
76
+
77
+ ```bash
78
+ # Step 1: openrpc.json 갱신
79
+ python Controller/tools/schema_to_openrpc.py \
80
+ --schema docs/20_기술_사양/21_DIBD_프로토콜/protocol_schema.json \
81
+ --out Controller/tools/python_sdk/
82
+
83
+ # Step 2: methods.py 자동 생성
84
+ python Controller/tools/python_sdk/generate_sdk.py
85
+ ```
86
+
87
+ `methods.py` 본문 직접 편집 금지 — 본 흐름 본문 재호출 의무.
88
+
89
+ ## 외부 vendor 본 path
90
+
91
+ 본 SDK 본 본문 외부 vendor 본 path 본 path는 별 트랙 `0515x-vendor-integration` 본 본문 적재 예정. 현 trunk 본 본 path 본 본 본 본문 path 한정.
92
+
93
+ GitHub repo `dibd-led-protocol` 공개 본 path는 사용자 GitHub 계정 직접 영역 (gh CLI 또는 web UI).
94
+
95
+ ## SSOT
96
+
97
+ - 펌웨어 본문: `Controller/shared/app/protocol/envelope_v3_lookup.c` (95 method entry)
98
+ - 프로토콜 spec: `docs/20_기술_사양/21_DIBD_프로토콜/protocol_schema.json` (95+ method, 1.2.0)
99
+ - 마감 결정: `docs/00_AI_가이드/Decisions/0514f_protocol_8_areas_standardization.plan.md`
100
+ - conformance test: `tests/conformance/run_conformance.py` (33/33 PASS)
101
+
102
+ ## 라이선스
103
+
104
+ Apache License 2.0. © 2026 DabitSol Co., Ltd.
@@ -0,0 +1,73 @@
1
+ # dibd-led-protocol — DIBD LED 전광판 공개 표준 프로토콜
2
+
3
+ JSON-RPC 2.0 envelope 정합 + Python SDK + OpenRPC 1.3.2 spec + conformance test 본질 정합.
4
+
5
+ ## 본 repo 영역
6
+
7
+ | 영역 | 위치 |
8
+ |---|---|
9
+ | Python SDK 본문 | `dibd/` (96 method auto-gen, jsonrpc 2.0 envelope, stdlib 한정) |
10
+ | OpenRPC spec | `openrpc.json` (96 method spec, 표준 1.3.2) |
11
+ | 변환 도구 | `../schema_to_openrpc.py` (protocol_schema.json → openrpc.json) |
12
+ | SDK 생성 wrapper | `generate_sdk.py` (openrpc.json → dibd/methods.py) |
13
+ | 빌드 설정 | `pyproject.toml` (setuptools 본문, Python ≥3.10, Apache-2.0) |
14
+ | LICENSE | Apache 2.0 |
15
+
16
+ ## 5분 시작
17
+
18
+ 로컬 설치 (PyPI 부재 영역):
19
+
20
+ ```bash
21
+ cd Controller/tools/python_sdk/
22
+ pip install -e .
23
+ ```
24
+
25
+ 사용:
26
+
27
+ ```python
28
+ from dibd import DibdClient
29
+
30
+ c = DibdClient("192.168.1.211") # UDP default port 50000
31
+ size = c.invoke("display.size.read")
32
+ c.invoke("display.brightness.write", {"level": 50})
33
+ c.close()
34
+ ```
35
+
36
+ 상세 본 본문 = `dibd/README.md`.
37
+
38
+ ## 옛 ASCII frame 호환
39
+
40
+ `raw_ascii()` path 옛 ASCII frame 본문 직접 송신. 옛 다빛채 호환 영역 그대로.
41
+
42
+ ## SDK 재생성 흐름
43
+
44
+ protocol_schema.json 갱신 후:
45
+
46
+ ```bash
47
+ # Step 1: openrpc.json 갱신
48
+ python Controller/tools/schema_to_openrpc.py \
49
+ --schema docs/20_기술_사양/21_DIBD_프로토콜/protocol_schema.json \
50
+ --out Controller/tools/python_sdk/
51
+
52
+ # Step 2: methods.py 자동 생성
53
+ python Controller/tools/python_sdk/generate_sdk.py
54
+ ```
55
+
56
+ `methods.py` 본문 직접 편집 금지 — 본 흐름 본문 재호출 의무.
57
+
58
+ ## 외부 vendor 본 path
59
+
60
+ 본 SDK 본 본문 외부 vendor 본 path 본 path는 별 트랙 `0515x-vendor-integration` 본 본문 적재 예정. 현 trunk 본 본 path 본 본 본 본문 path 한정.
61
+
62
+ GitHub repo `dibd-led-protocol` 공개 본 path는 사용자 GitHub 계정 직접 영역 (gh CLI 또는 web UI).
63
+
64
+ ## SSOT
65
+
66
+ - 펌웨어 본문: `Controller/shared/app/protocol/envelope_v3_lookup.c` (95 method entry)
67
+ - 프로토콜 spec: `docs/20_기술_사양/21_DIBD_프로토콜/protocol_schema.json` (95+ method, 1.2.0)
68
+ - 마감 결정: `docs/00_AI_가이드/Decisions/0514f_protocol_8_areas_standardization.plan.md`
69
+ - conformance test: `tests/conformance/run_conformance.py` (33/33 PASS)
70
+
71
+ ## 라이선스
72
+
73
+ Apache License 2.0. © 2026 DabitSol Co., Ltd.
@@ -0,0 +1,30 @@
1
+ """dibd — Python SDK for DIBD LED display protocol (0514f Phase 1 호출 3 산출물)
2
+
3
+ 옛 ASCII path 본문 호환:
4
+ DibdClient.raw_ascii("![00H1!]") → 옛 ASCII frame 본 path 직접 송신.
5
+
6
+ 본 신 path:
7
+ c = DibdClient("192.168.1.211")
8
+ c.invoke("display.size.read")
9
+ c.invoke("display.brightness.write", {"level": 50})
10
+
11
+ SSOT:
12
+ - protocol_schema.json (95+ method)
13
+ - Decisions/0514f_*.plan.md
14
+ """
15
+ from __future__ import annotations
16
+
17
+ from .client import DibdClient
18
+ from .errors import DibdError, ErrorCode
19
+ from .envelope import build_request, parse_response
20
+ from .methods import _MethodCatalog as MethodCatalog
21
+
22
+ __version__ = "1.2.0"
23
+ __all__ = [
24
+ "DibdClient",
25
+ "DibdError",
26
+ "ErrorCode",
27
+ "MethodCatalog",
28
+ "build_request",
29
+ "parse_response",
30
+ ]
@@ -0,0 +1,158 @@
1
+ """client.py — DibdClient (0514f Phase 1 호출 3 산출물).
2
+
3
+ 채널 본문 3건 — UDP / TCP / HTTP envelope POST. 옛 ASCII path 본문 호환 raw_ascii() 별도.
4
+
5
+ 본문 사용:
6
+ c = DibdClient("192.168.1.211", channel="udp", port=50000)
7
+ result = c.invoke("display.size.read")
8
+ c.invoke("display.brightness.write", {"level": 50})
9
+ c.close()
10
+
11
+ 본문 자동 method dispatch path 부재 — 본 path 시점에 invoke() 본 path 박힘. dot-path
12
+ 본문 직접 method 호출은 추가 path (catalog 본문 회수 후 setattr 본 path 박음)."""
13
+ from __future__ import annotations
14
+
15
+ import socket
16
+ import urllib.request
17
+ from typing import Any
18
+
19
+ from .envelope import build_request, parse_response
20
+ from .errors import DibdError
21
+ from .methods import _MethodCatalog
22
+
23
+
24
+ class DibdClient:
25
+ """DIBD 보드 본문 JSON-RPC 2.0 client.
26
+
27
+ Args:
28
+ host: 보드 IP 본문 (예: "192.168.1.211").
29
+ channel: "udp" / "tcp" / "http" 본문 본 path 선택.
30
+ port: UDP/TCP port (default 50000), HTTP port (default 80).
31
+ timeout_s: 응답 대기 timeout (default 2.0).
32
+ hmac_key: 본문 박힐 시 envelope `_dibd.security.sig` 본 영역 적재 (옵션).
33
+ """
34
+
35
+ DEFAULT_UDP_PORT = 50000
36
+ DEFAULT_TCP_PORT = 50000
37
+ DEFAULT_HTTP_PORT = 80
38
+
39
+ def __init__(
40
+ self,
41
+ host: str,
42
+ *,
43
+ channel: str = "udp",
44
+ port: int | None = None,
45
+ timeout_s: float = 2.0,
46
+ hmac_key: bytes | None = None,
47
+ ) -> None:
48
+ self.host = host
49
+ self.channel = channel
50
+ self.timeout_s = timeout_s
51
+ self.hmac_key = hmac_key
52
+ if port is None:
53
+ defaults = {
54
+ "udp": self.DEFAULT_UDP_PORT,
55
+ "tcp": self.DEFAULT_TCP_PORT,
56
+ "http": self.DEFAULT_HTTP_PORT,
57
+ }
58
+ port = defaults.get(channel, self.DEFAULT_UDP_PORT)
59
+ self.port = port
60
+ self._sock: socket.socket | None = None
61
+ self.catalog = _MethodCatalog
62
+
63
+ def _ensure_socket(self) -> socket.socket:
64
+ if self._sock is not None:
65
+ return self._sock
66
+ if self.channel == "udp":
67
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
68
+ elif self.channel == "tcp":
69
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
70
+ s.connect((self.host, self.port))
71
+ else:
72
+ raise DibdError(-32603, f"channel {self.channel} 본 path socket 부재")
73
+ s.settimeout(self.timeout_s)
74
+ self._sock = s
75
+ return s
76
+
77
+ def invoke(
78
+ self,
79
+ method: str,
80
+ params: dict[str, Any] | list[Any] | None = None,
81
+ *,
82
+ notification: bool = False,
83
+ ) -> dict[str, Any] | None:
84
+ """JSON-RPC 2.0 method 본문 본 path 호출. notification=True 시 None 반환."""
85
+ if self.catalog.lookup(method) is None:
86
+ # 본 catalog 부재 method도 호출 허용 (보드 본문 신 method 부재 path).
87
+ pass
88
+ req = build_request(method, params, notification=notification)
89
+ if self.hmac_key is not None:
90
+ req = self._sign(req)
91
+ if notification:
92
+ self._send_only(req)
93
+ return None
94
+ raw = self._send_recv(req)
95
+ body = parse_response(raw)
96
+ return body.get("result")
97
+
98
+ def raw_ascii(self, frame: str | bytes) -> bytes:
99
+ """옛 ASCII frame 본문 직접 송신 path. 본 path = 옛 호환 영역."""
100
+ if isinstance(frame, str):
101
+ frame = frame.encode("ascii")
102
+ return self._send_recv(frame)
103
+
104
+ def _send_only(self, payload: bytes) -> None:
105
+ s = self._ensure_socket()
106
+ if self.channel == "udp":
107
+ s.sendto(payload, (self.host, self.port))
108
+ elif self.channel == "tcp":
109
+ s.sendall(payload)
110
+ else:
111
+ urllib.request.urlopen(
112
+ f"http://{self.host}:{self.port}/jsonrpc",
113
+ data=payload,
114
+ timeout=self.timeout_s,
115
+ )
116
+
117
+ def _send_recv(self, payload: bytes) -> bytes:
118
+ if self.channel == "http":
119
+ req = urllib.request.Request(
120
+ f"http://{self.host}:{self.port}/jsonrpc",
121
+ data=payload,
122
+ headers={"Content-Type": "application/json"},
123
+ )
124
+ with urllib.request.urlopen(req, timeout=self.timeout_s) as resp:
125
+ return resp.read()
126
+ s = self._ensure_socket()
127
+ if self.channel == "udp":
128
+ s.sendto(payload, (self.host, self.port))
129
+ data, _addr = s.recvfrom(4096)
130
+ return data
131
+ # tcp
132
+ s.sendall(payload)
133
+ return s.recv(4096)
134
+
135
+ def _sign(self, payload: bytes) -> bytes:
136
+ """HMAC-SHA256 본문 envelope `_dibd.security.sig` 본 영역 적재.
137
+
138
+ 본 path = client-side 적재 본문 박음. 보드 본문 verify path 별 본문."""
139
+ import hmac
140
+ import hashlib
141
+ import json
142
+
143
+ body = json.loads(payload.decode("utf-8"))
144
+ body.setdefault("_dibd", {}).setdefault("security", {})
145
+ sig = hmac.new(self.hmac_key, payload, hashlib.sha256).hexdigest()
146
+ body["_dibd"]["security"]["sig"] = sig
147
+ return json.dumps(body, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
148
+
149
+ def close(self) -> None:
150
+ if self._sock is not None:
151
+ self._sock.close()
152
+ self._sock = None
153
+
154
+ def __enter__(self) -> "DibdClient":
155
+ return self
156
+
157
+ def __exit__(self, *exc: object) -> None:
158
+ self.close()
@@ -0,0 +1,70 @@
1
+ """envelope.py — JSON-RPC 2.0 envelope encode/decode (0514f Phase 1 호출 3).
2
+
3
+ 본문 책임:
4
+ - build_request: dict → bytes (UTF-8 cJSON, magic byte '{' 본 path 정합).
5
+ - parse_response: bytes → dict (jsonrpc 본문 검사 + DibdError raise path)."""
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import secrets
10
+ from typing import Any
11
+
12
+ from .errors import DibdError
13
+
14
+
15
+ _NEXT_ID = 0
16
+
17
+
18
+ def _next_request_id() -> int:
19
+ global _NEXT_ID
20
+ _NEXT_ID += 1
21
+ return _NEXT_ID
22
+
23
+
24
+ def build_request(
25
+ method: str,
26
+ params: dict[str, Any] | list[Any] | None = None,
27
+ *,
28
+ request_id: int | str | None = None,
29
+ nonce: str | None = None,
30
+ notification: bool = False,
31
+ ) -> bytes:
32
+ """JSON-RPC 2.0 request 본문 본 path 적재.
33
+
34
+ notification=True 시 id 부재 박음 (응답 부재 의무).
35
+ nonce 본문 박힐 시 `_dibd.security.nonce` 본 영역 적재 (replay 방지)."""
36
+ body: dict[str, Any] = {"jsonrpc": "2.0", "method": method}
37
+ if params is not None:
38
+ body["params"] = params
39
+ if not notification:
40
+ body["id"] = request_id if request_id is not None else _next_request_id()
41
+ if nonce is not None:
42
+ body.setdefault("_dibd", {}).setdefault("security", {})["nonce"] = nonce
43
+ return json.dumps(body, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
44
+
45
+
46
+ def parse_response(raw: bytes) -> dict[str, Any]:
47
+ """JSON-RPC 2.0 response 본문 본 path 회수. error 본문 박힐 시 DibdError raise."""
48
+ try:
49
+ body = json.loads(raw.decode("utf-8"))
50
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
51
+ raise DibdError(-32700, f"parse error: {exc}") from exc
52
+
53
+ if not isinstance(body, dict):
54
+ raise DibdError(-32600, "envelope is not an object")
55
+ if body.get("jsonrpc") != "2.0":
56
+ raise DibdError(-32600, f"jsonrpc != 2.0: {body.get('jsonrpc')!r}")
57
+
58
+ if "error" in body:
59
+ err = body["error"]
60
+ raise DibdError(
61
+ int(err.get("code", -32603)),
62
+ str(err.get("message", "unknown error")),
63
+ err.get("data"),
64
+ )
65
+ return body
66
+
67
+
68
+ def fresh_nonce(num_bytes: int = 16) -> str:
69
+ """replay-방지 nonce 본문 (hex 문자열)."""
70
+ return secrets.token_hex(num_bytes)
@@ -0,0 +1,38 @@
1
+ """errors.py — DIBD JSON-RPC 2.0 error code 본 매트릭스 (0514f Phase 1 호출 3).
2
+
3
+ JSON-RPC 표준 -32700~-32603 + DIBD reserved -30000~-30999.
4
+ SSOT: protocol_schema.json `errorCodes` 영역."""
5
+ from __future__ import annotations
6
+
7
+ from enum import IntEnum
8
+
9
+
10
+ class ErrorCode(IntEnum):
11
+ """JSON-RPC 표준 + DIBD reserved range 본문."""
12
+
13
+ PARSE_ERROR = -32700
14
+ INVALID_REQUEST = -32600
15
+ METHOD_NOT_FOUND = -32601
16
+ INVALID_PARAMS = -32602
17
+ INTERNAL_ERROR = -32603
18
+
19
+ ENVELOPE_SIZE_LIMIT = -30000
20
+ BATCH_SIZE_LIMIT = -30001
21
+ CHUNK_FRAGMENT_TIMEOUT = -30002
22
+
23
+ BINARY_CHECKSUM_MISMATCH = -30100
24
+ BINARY_TOO_LARGE = -30101
25
+
26
+ AUTH_HMAC_INVALID = -30200
27
+ AUTH_REPLAY_DETECTED = -30201
28
+ AUTH_NONCE_MISSING = -30202
29
+
30
+
31
+ class DibdError(Exception):
32
+ """DIBD JSON-RPC error 본문 raise path. code/message/data 본문 회수."""
33
+
34
+ def __init__(self, code: int, message: str, data: object | None = None) -> None:
35
+ super().__init__(f"[{code}] {message}")
36
+ self.code = code
37
+ self.message = message
38
+ self.data = data