pyhj212 0.1.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.
pyhj212-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Weinan Chen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
pyhj212-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,154 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyhj212
3
+ Version: 0.1.0
4
+ Summary: A Python library for HJ212 protocol encoding, decoding, validation, and communication.
5
+ Author-email: tinychen <weinanmay@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/tinychen/pyhj212
8
+ Project-URL: Repository, https://github.com/tinychen/pyhj212
9
+ Project-URL: Issues, https://github.com/tinychen/pyhj212/issues
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Provides-Extra: dev
21
+ Requires-Dist: pytest>=8.0; extra == "dev"
22
+ Requires-Dist: pytest-cov>=5.0; extra == "dev"
23
+ Requires-Dist: hypothesis>=6.0; extra == "dev"
24
+ Requires-Dist: ruff>=0.6.0; extra == "dev"
25
+ Requires-Dist: mypy>=1.0; extra == "dev"
26
+ Dynamic: license-file
27
+
28
+ # pyhj212
29
+
30
+ HJ 212-2017 协议核心协议的 Python 实现,提供消息编解码、CRC 校验、协议验证、TCP 流帧解码以及 CP 字段解析功能。
31
+
32
+ ## 特性
33
+
34
+ | 功能 | 状态 |
35
+ |------|------|
36
+ | 消息解析 | ✅ |
37
+ | 消息编码 | ✅ |
38
+ | CRC-16 计算与校验 | ✅ |
39
+ | CP 字段解析与编码 | ✅ |
40
+ | 协议验证 | ✅ |
41
+ | TCP 流帧解码(粘包/分包) | ✅ |
42
+ | Dataclass 数据模型 | ✅ |
43
+
44
+ ## 快速开始
45
+
46
+ ### 安装
47
+
48
+ ```bash
49
+ # 使用 uv 安装开发依赖
50
+ uv sync --all-extras
51
+
52
+ # 或直接安装
53
+ pip install -e .
54
+ ```
55
+
56
+ ### 解析消息
57
+
58
+ ```python
59
+ from pyhj212.protocol.parser import Parser
60
+
61
+ raw = (
62
+ "##0101QN=20160801085857223;ST=32;CN=1062;PW=100000;"
63
+ "MN=010000A8900016F000169DC0;Flag=5;CP=&&RtdInterval=30&&"
64
+ "1C80\r\n"
65
+ )
66
+
67
+ parser = Parser()
68
+ msg = parser.parse(raw)
69
+
70
+ print(msg.header.cn) # "1062"
71
+ print(msg.header.mn) # "010000A8900016F000169DC0"
72
+ print(msg.data) # "RtdInterval=30"
73
+ print(msg.crc) # "1C80"
74
+ ```
75
+
76
+ ### 编码消息
77
+
78
+ ```python
79
+ from pyhj212.models.header import Header
80
+ from pyhj212.models.message import Message
81
+ from pyhj212.protocol.encoder import Encoder
82
+
83
+ header = Header(
84
+ qn="20160801085857223", st="32", cn="1062", pw="100000",
85
+ mn="010000A8900016F000169DC0", flag=5, pno=0,
86
+ )
87
+ message = Message(header=header, data="RtdInterval=30")
88
+
89
+ encoder = Encoder()
90
+ raw = encoder.encode(message)
91
+ # "##0101QN=20160801085857223;ST=32;CN=1062;PW=100000;..."
92
+ ```
93
+
94
+ ### 验证消息
95
+
96
+ ```python
97
+ from pyhj212.protocol.validator import Validator
98
+
99
+ validator = Validator()
100
+ result = validator.validate(raw)
101
+
102
+ if not result.is_valid:
103
+ for error in result.errors:
104
+ print(f"错误: {error}")
105
+ ```
106
+
107
+ ### TCP 流解码
108
+
109
+ ```python
110
+ from pyhj212.protocol.stream import StreamDecoder
111
+
112
+ decoder = StreamDecoder()
113
+
114
+ # 分包场景
115
+ decoder.feed(b"##0030QN=...;F")
116
+ decoder.feed(b"lag=5;CP=&&RtdInterval=30&&1C80\r\n")
117
+
118
+ # 粘包场景
119
+ decoder.feed(b"##0030...&&1C80\r\n##0030...&&2A3B\r\n")
120
+ ```
121
+
122
+ ### CP 字段解析
123
+
124
+ ```python
125
+ from pyhj212.cp.parser import CPParser
126
+
127
+ parser = CPParser()
128
+ fields = parser.parse("PNO=000000004;DataTime=20260902082000;a01001-Rtd=24.4")
129
+
130
+ for f in fields:
131
+ print(f"{f.key} = {f.value}")
132
+ ```
133
+
134
+ ## 开发
135
+
136
+ 参见 [DEVELOPMENT.md](DEVELOPMENT.md)。
137
+
138
+ ```bash
139
+ # 运行测试
140
+ uv run pytest
141
+
142
+ # 代码检查
143
+ uv run ruff check src/pyhj212 tests
144
+ uv run ruff format src/pyhj212 tests
145
+ uv run mypy src/pyhj212
146
+ ```
147
+
148
+ ## 协议
149
+
150
+ - HJ 212-2017 《污染物在线监控(监测)系统数据传输标准》
151
+
152
+ ## License
153
+
154
+ MIT
@@ -0,0 +1,127 @@
1
+ # pyhj212
2
+
3
+ HJ 212-2017 协议核心协议的 Python 实现,提供消息编解码、CRC 校验、协议验证、TCP 流帧解码以及 CP 字段解析功能。
4
+
5
+ ## 特性
6
+
7
+ | 功能 | 状态 |
8
+ |------|------|
9
+ | 消息解析 | ✅ |
10
+ | 消息编码 | ✅ |
11
+ | CRC-16 计算与校验 | ✅ |
12
+ | CP 字段解析与编码 | ✅ |
13
+ | 协议验证 | ✅ |
14
+ | TCP 流帧解码(粘包/分包) | ✅ |
15
+ | Dataclass 数据模型 | ✅ |
16
+
17
+ ## 快速开始
18
+
19
+ ### 安装
20
+
21
+ ```bash
22
+ # 使用 uv 安装开发依赖
23
+ uv sync --all-extras
24
+
25
+ # 或直接安装
26
+ pip install -e .
27
+ ```
28
+
29
+ ### 解析消息
30
+
31
+ ```python
32
+ from pyhj212.protocol.parser import Parser
33
+
34
+ raw = (
35
+ "##0101QN=20160801085857223;ST=32;CN=1062;PW=100000;"
36
+ "MN=010000A8900016F000169DC0;Flag=5;CP=&&RtdInterval=30&&"
37
+ "1C80\r\n"
38
+ )
39
+
40
+ parser = Parser()
41
+ msg = parser.parse(raw)
42
+
43
+ print(msg.header.cn) # "1062"
44
+ print(msg.header.mn) # "010000A8900016F000169DC0"
45
+ print(msg.data) # "RtdInterval=30"
46
+ print(msg.crc) # "1C80"
47
+ ```
48
+
49
+ ### 编码消息
50
+
51
+ ```python
52
+ from pyhj212.models.header import Header
53
+ from pyhj212.models.message import Message
54
+ from pyhj212.protocol.encoder import Encoder
55
+
56
+ header = Header(
57
+ qn="20160801085857223", st="32", cn="1062", pw="100000",
58
+ mn="010000A8900016F000169DC0", flag=5, pno=0,
59
+ )
60
+ message = Message(header=header, data="RtdInterval=30")
61
+
62
+ encoder = Encoder()
63
+ raw = encoder.encode(message)
64
+ # "##0101QN=20160801085857223;ST=32;CN=1062;PW=100000;..."
65
+ ```
66
+
67
+ ### 验证消息
68
+
69
+ ```python
70
+ from pyhj212.protocol.validator import Validator
71
+
72
+ validator = Validator()
73
+ result = validator.validate(raw)
74
+
75
+ if not result.is_valid:
76
+ for error in result.errors:
77
+ print(f"错误: {error}")
78
+ ```
79
+
80
+ ### TCP 流解码
81
+
82
+ ```python
83
+ from pyhj212.protocol.stream import StreamDecoder
84
+
85
+ decoder = StreamDecoder()
86
+
87
+ # 分包场景
88
+ decoder.feed(b"##0030QN=...;F")
89
+ decoder.feed(b"lag=5;CP=&&RtdInterval=30&&1C80\r\n")
90
+
91
+ # 粘包场景
92
+ decoder.feed(b"##0030...&&1C80\r\n##0030...&&2A3B\r\n")
93
+ ```
94
+
95
+ ### CP 字段解析
96
+
97
+ ```python
98
+ from pyhj212.cp.parser import CPParser
99
+
100
+ parser = CPParser()
101
+ fields = parser.parse("PNO=000000004;DataTime=20260902082000;a01001-Rtd=24.4")
102
+
103
+ for f in fields:
104
+ print(f"{f.key} = {f.value}")
105
+ ```
106
+
107
+ ## 开发
108
+
109
+ 参见 [DEVELOPMENT.md](DEVELOPMENT.md)。
110
+
111
+ ```bash
112
+ # 运行测试
113
+ uv run pytest
114
+
115
+ # 代码检查
116
+ uv run ruff check src/pyhj212 tests
117
+ uv run ruff format src/pyhj212 tests
118
+ uv run mypy src/pyhj212
119
+ ```
120
+
121
+ ## 协议
122
+
123
+ - HJ 212-2017 《污染物在线监控(监测)系统数据传输标准》
124
+
125
+ ## License
126
+
127
+ MIT
@@ -0,0 +1,73 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "pyhj212"
7
+ version = "0.1.0"
8
+ description = "A Python library for HJ212 protocol encoding, decoding, validation, and communication."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.10"
12
+ authors = [
13
+ {name = "tinychen", email = "weinanmay@gmail.com"},
14
+ ]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.10",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Topic :: Software Development :: Libraries :: Python Modules",
23
+ ]
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/tinychen/pyhj212"
27
+ Repository = "https://github.com/tinychen/pyhj212"
28
+ Issues = "https://github.com/tinychen/pyhj212/issues"
29
+
30
+ [project.optional-dependencies]
31
+ dev = [
32
+ "pytest>=8.0",
33
+ "pytest-cov>=5.0",
34
+ "hypothesis>=6.0",
35
+ "ruff>=0.6.0",
36
+ "mypy>=1.0",
37
+ ]
38
+
39
+ [tool.setuptools.packages.find]
40
+ where = ["src"]
41
+
42
+ [tool.ruff]
43
+ target-version = "py310"
44
+ line-length = 100
45
+
46
+ [tool.ruff.lint]
47
+ select = ["E", "F", "W", "I", "N", "UP", "B", "SIM", "C9"]
48
+ ignore = ["E501"]
49
+
50
+ [tool.ruff.lint.isort]
51
+ known-first-party = ["pyhj212"]
52
+
53
+ [tool.mypy]
54
+ python_version = "3.10"
55
+ strict = true
56
+ warn_return_any = true
57
+ warn_unused_configs = true
58
+ disallow_untyped_defs = true
59
+ disallow_incomplete_defs = true
60
+ check_untyped_defs = true
61
+ no_implicit_optional = true
62
+ warn_redundant_casts = true
63
+ warn_unused_ignores = true
64
+ packages = ["pyhj212"]
65
+
66
+ [tool.pytest.ini_options]
67
+ testpaths = ["tests"]
68
+ python_files = ["test_*.py"]
69
+ python_classes = ["Test*"]
70
+ python_functions = ["test_*"]
71
+
72
+ [tool.hypothesis]
73
+ database = ".hypothesis"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ # PyHJ212 - HJ 212-2017 Protocol Library
2
+
3
+ """A Python library for HJ212 protocol encoding, decoding, validation, and communication."""
@@ -0,0 +1,25 @@
1
+ """Protocol constants for HJ 212-2017."""
2
+
3
+ from __future__ import annotations
4
+
5
+ # Message delimiters
6
+ START_DELIMITER = "##"
7
+ END_DELIMITER = "\r\n"
8
+
9
+ # CRC configuration
10
+ CRC_POLYNOMIAL = 0xA001
11
+ CRC_INITIAL = 0xFFFF
12
+
13
+ # Message length limits
14
+ MAX_DATA_LENGTH = 9999
15
+ MIN_DATA_LENGTH = 0
16
+
17
+ # CP command types
18
+ CP_CMD_READ = "READ"
19
+ CP_CMD_WRITE = "WRITE"
20
+ CP_CMD_ACK = "ACK"
21
+ CP_CMD_NACK = "NACK"
22
+
23
+ # Message types
24
+ MSG_TYPE_REQUEST = "REQUEST"
25
+ MSG_TYPE_RESPONSE = "RESPONSE"
@@ -0,0 +1,11 @@
1
+ """CP (Command Parameter) field parsing and encoding."""
2
+
3
+ from pyhj212.cp.encoder import CPEncoder
4
+ from pyhj212.cp.models import CPField
5
+ from pyhj212.cp.parser import CPParser
6
+
7
+ __all__ = [
8
+ "CPParser",
9
+ "CPEncoder",
10
+ "CPField",
11
+ ]
@@ -0,0 +1,26 @@
1
+ """CP field encoder for HJ 212-2017 protocol."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pyhj212.cp.models import CPField
6
+
7
+
8
+ class CPEncoder:
9
+ """Encodes CPField objects back into CP field strings."""
10
+
11
+ def encode(self, fields: list[CPField]) -> str:
12
+ """Encode a list of CPField objects into a CP string.
13
+
14
+ Args:
15
+ fields: List of CPField objects to encode.
16
+
17
+ Returns:
18
+ Semicolon-separated CP field string.
19
+ """
20
+ parts: list[str] = []
21
+ for field_item in fields:
22
+ if field_item.value:
23
+ parts.append(f"{field_item.key}={field_item.value}")
24
+ else:
25
+ parts.append(field_item.key)
26
+ return ";".join(parts)
@@ -0,0 +1,39 @@
1
+ """CP field data models."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class CPField:
10
+ """Represents a parsed CP (Command Parameter) field.
11
+
12
+ CP fields contain key-value pairs and nested data groups
13
+ used for transmitting monitoring data and control commands.
14
+
15
+ Attributes:
16
+ key: The CP field identifier (e.g., 'w01001-Rtd').
17
+ value: The field value string.
18
+ children: Nested child fields for grouped data.
19
+ raw: Original raw field string for preservation.
20
+ """
21
+
22
+ key: str
23
+ value: str = ""
24
+ children: list[CPField] = field(default_factory=list, repr=False)
25
+ raw: str = field(default="", repr=False, compare=False)
26
+
27
+ def get_child(self, key: str) -> CPField | None:
28
+ """Find a child field by key.
29
+
30
+ Args:
31
+ key: The child field key to search for.
32
+
33
+ Returns:
34
+ The matching CPField, or None if not found.
35
+ """
36
+ for child in self.children:
37
+ if child.key == key:
38
+ return child
39
+ return None
@@ -0,0 +1,41 @@
1
+ """CP field parser for HJ 212-2017 protocol."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pyhj212.cp.models import CPField
6
+
7
+
8
+ class CPParser:
9
+ """Parses CP (Command Parameter) field strings.
10
+
11
+ CP fields use semicolons to separate key-value pairs,
12
+ and commas to separate grouped data fields.
13
+ """
14
+
15
+ def parse(self, cp_string: str) -> list[CPField]:
16
+ """Parse a CP field string into a list of CPField objects.
17
+
18
+ Args:
19
+ cp_string: The raw CP field string (e.g., 'w01001-Rtd=12.5;w01002-Rtd=34.0').
20
+
21
+ Returns:
22
+ List of parsed CPField objects.
23
+ """
24
+ if not cp_string:
25
+ return []
26
+
27
+ fields: list[CPField] = []
28
+ parts = cp_string.split(";")
29
+
30
+ for part in parts:
31
+ part = part.strip()
32
+ if not part:
33
+ continue
34
+
35
+ if "=" in part:
36
+ key, value = part.split("=", 1)
37
+ fields.append(CPField(key=key, value=value, raw=part))
38
+ else:
39
+ fields.append(CPField(key=part, raw=part))
40
+
41
+ return fields
@@ -0,0 +1,35 @@
1
+ """Custom exceptions for the HJ 212-2017 protocol library."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class PyHJ212Error(Exception):
7
+ """Base exception for all PyHJ212 errors."""
8
+
9
+
10
+ class ParseError(PyHJ212Error):
11
+ """Raised when message parsing fails."""
12
+
13
+ def __init__(self, message: str, position: int = 0) -> None:
14
+ super().__init__(message)
15
+ self.position = position
16
+
17
+
18
+ class EncodeError(PyHJ212Error):
19
+ """Raised when message encoding fails."""
20
+
21
+
22
+ class ValidationError(PyHJ212Error):
23
+ """Raised when protocol validation fails."""
24
+
25
+ def __init__(self, message: str, errors: list[str] | None = None) -> None:
26
+ super().__init__(message)
27
+ self.errors = errors or []
28
+
29
+
30
+ class ChecksumError(ValidationError):
31
+ """Raised when CRC verification fails."""
32
+
33
+
34
+ class CPError(ParseError):
35
+ """Raised when CP field parsing fails."""
@@ -0,0 +1,11 @@
1
+ """Data models for HJ 212-2017 protocol messages."""
2
+
3
+ from pyhj212.models.header import Header
4
+ from pyhj212.models.message import Message
5
+ from pyhj212.models.validation import ValidationResult
6
+
7
+ __all__ = [
8
+ "Header",
9
+ "Message",
10
+ "ValidationResult",
11
+ ]
@@ -0,0 +1,59 @@
1
+ """Message header model for HJ 212-2017 protocol."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class Header:
10
+ """Represents the header section of an HJ 212-2017 message.
11
+
12
+ The header contains metadata about the message including the
13
+ protocol version, message type, and routing information.
14
+
15
+ All fields are stored as strings to preserve the original format.
16
+
17
+ Attributes:
18
+ qn: Request number (请求编号), 17-char timestamp format.
19
+ st: System type, identifies the equipment category.
20
+ cn: Command number, identifies the message type.
21
+ pw: Password for authentication, typically 6 characters.
22
+ mn: Device number (monitoring station), typically 24 characters.
23
+ flag: Message flag indicating encryption and packaging.
24
+ pno: Packet number for multi-part messages.
25
+ """
26
+
27
+ flag: str = ""
28
+ pno: str = ""
29
+
30
+ qn: str = ""
31
+ st: str = ""
32
+ cn: str = ""
33
+ pw: str = ""
34
+ mn: str = ""
35
+
36
+ raw: str = field(default="", repr=False, compare=False)
37
+
38
+ def to_string(self) -> str:
39
+ """Serialize the header to HJ 212-2017 format.
40
+
41
+ Returns:
42
+ The formatted header string.
43
+ """
44
+ parts = []
45
+ if self.qn:
46
+ parts.append(f"QN={self.qn}")
47
+ if self.st:
48
+ parts.append(f"ST={self.st}")
49
+ if self.cn:
50
+ parts.append(f"CN={self.cn}")
51
+ if self.pw:
52
+ parts.append(f"PW={self.pw}")
53
+ if self.mn:
54
+ parts.append(f"MN={self.mn}")
55
+ if self.flag:
56
+ parts.append(f"Flag={self.flag}")
57
+ if self.pno:
58
+ parts.append(f"PNO={self.pno}")
59
+ return ";".join(parts)
@@ -0,0 +1,26 @@
1
+ """Message model for HJ 212-2017 protocol."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+ from pyhj212.models.header import Header
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class Message:
12
+ """Represents a complete HJ 212-2017 protocol message.
13
+
14
+ Attributes:
15
+ header: Message header containing routing and type info.
16
+ data: Raw data payload string.
17
+ cp: CP field content (command parameters).
18
+ crc: CRC checksum value from the message.
19
+ raw: Original raw message string for preservation.
20
+ """
21
+
22
+ header: Header
23
+ data: str = ""
24
+ cp: str = ""
25
+ crc: str = ""
26
+ raw: str = field(default="", repr=False, compare=False)
@@ -0,0 +1,29 @@
1
+ """Validation result model for protocol validation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+
8
+ @dataclass
9
+ class ValidationResult:
10
+ """Result of validating an HJ 212-2017 message.
11
+
12
+ Attributes:
13
+ is_valid: Whether the message passed all validation checks.
14
+ errors: List of validation error messages.
15
+ warnings: List of non-critical warnings.
16
+ """
17
+
18
+ is_valid: bool = True
19
+ errors: list[str] = field(default_factory=list)
20
+ warnings: list[str] = field(default_factory=list)
21
+
22
+ def add_error(self, message: str) -> None:
23
+ """Add a validation error."""
24
+ self.is_valid = False
25
+ self.errors.append(message)
26
+
27
+ def add_warning(self, message: str) -> None:
28
+ """Add a validation warning."""
29
+ self.warnings.append(message)
@@ -0,0 +1,16 @@
1
+ """Protocol parsing, encoding, and validation modules."""
2
+
3
+ from pyhj212.protocol.checksum import calculate_crc, verify_crc
4
+ from pyhj212.protocol.encoder import Encoder
5
+ from pyhj212.protocol.parser import Parser
6
+ from pyhj212.protocol.stream import StreamDecoder
7
+ from pyhj212.protocol.validator import Validator
8
+
9
+ __all__ = [
10
+ "Parser",
11
+ "Encoder",
12
+ "Validator",
13
+ "calculate_crc",
14
+ "verify_crc",
15
+ "StreamDecoder",
16
+ ]
@@ -0,0 +1,41 @@
1
+ """CRC-16 calculation for HJ 212-2017 protocol."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pyhj212.constants import CRC_INITIAL, CRC_POLYNOMIAL
6
+
7
+
8
+ def calculate_crc(data: str) -> int:
9
+ """Calculate CRC-16 checksum for HJ 212-2017 message data.
10
+
11
+ Algorithm: reflected CRC-16 with polynomial 0xA001, initial value
12
+ 0xFFFF, and per-byte high-byte folding (crc >> 8) ^ byte.
13
+
14
+ Args:
15
+ data: The message data string to calculate CRC for.
16
+
17
+ Returns:
18
+ The CRC-16 value as an integer.
19
+ """
20
+ crc = CRC_INITIAL
21
+ for byte in data.encode("ascii"):
22
+ crc = (crc >> 8) ^ byte
23
+ for _ in range(8):
24
+ if crc & 0x0001:
25
+ crc = (crc >> 1) ^ CRC_POLYNOMIAL
26
+ else:
27
+ crc >>= 1
28
+ return crc & 0xFFFF
29
+
30
+
31
+ def verify_crc(data: str, expected_crc: int) -> bool:
32
+ """Verify CRC-16 checksum against expected value.
33
+
34
+ Args:
35
+ data: The message data string.
36
+ expected_crc: The expected CRC value to verify against.
37
+
38
+ Returns:
39
+ True if the calculated CRC matches the expected value.
40
+ """
41
+ return calculate_crc(data) == expected_crc
@@ -0,0 +1,51 @@
1
+ """Message encoder for HJ 212-2017 protocol."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pyhj212.constants import END_DELIMITER, START_DELIMITER
6
+ from pyhj212.exceptions import EncodeError
7
+ from pyhj212.models.message import Message
8
+ from pyhj212.protocol.checksum import calculate_crc
9
+
10
+
11
+ class Encoder:
12
+ """Encodes HJ 212-2017 Message objects into raw protocol strings.
13
+
14
+ The encoder handles the complete message format:
15
+ - Start delimiter (##)
16
+ - Data length field (4 digits, zero-padded)
17
+ - Header fields
18
+ - Data content with CP fields
19
+ - CRC checksum (4 hex digits, uppercase)
20
+ - End delimiter (\\r\\n)
21
+ """
22
+
23
+ def encode(self, message: Message) -> str:
24
+ """Encode a Message object into a raw HJ 212-2017 string.
25
+
26
+ Args:
27
+ message: The Message object to encode.
28
+
29
+ Returns:
30
+ The complete encoded message string.
31
+
32
+ Raises:
33
+ EncodeError: If the message cannot be encoded.
34
+ """
35
+ header_str = message.header.to_string()
36
+ body = message.data
37
+ content = f"{header_str};CP=&&{body}&&"
38
+
39
+ crc = calculate_crc(content)
40
+ crc_str = f"{crc:04X}"
41
+
42
+ length = len(content)
43
+ if length > 9999:
44
+ raise EncodeError(
45
+ f"Data length {length} exceeds maximum of 9999",
46
+ )
47
+
48
+ length_str = f"{length:04d}"
49
+
50
+ raw = f"{START_DELIMITER}{length_str}{content}{crc_str}{END_DELIMITER}"
51
+ return raw
@@ -0,0 +1,130 @@
1
+ """Message parser for HJ 212-2017 protocol."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pyhj212.constants import START_DELIMITER
6
+ from pyhj212.exceptions import ParseError
7
+ from pyhj212.models.header import Header
8
+ from pyhj212.models.message import Message
9
+
10
+
11
+ class Parser:
12
+ """Parses raw HJ 212-2017 message strings into structured objects.
13
+
14
+ Message format: ``##LLLL<Data><CRC>\\r\\n``
15
+
16
+ - ``##``: Start delimiter (2 chars)
17
+ - ``LLLL``: Data length (4 digits, zero-padded)
18
+ - ``<Data>``: Header + ``&&`` + CP data (LLLL chars)
19
+ - ``<CRC>``: CRC-16 checksum (4 hex chars, uppercase)
20
+ - ``\\r\\n``: End delimiter
21
+
22
+ The parser handles the complete message format:
23
+ - Start delimiter (##)
24
+ - Data length field
25
+ - Header fields
26
+ - Data content with CP fields
27
+ - CRC checksum
28
+ - End delimiter (\\r\\n)
29
+ """
30
+
31
+ def parse(self, raw: str) -> Message:
32
+ """Parse a raw HJ 212-2017 message string.
33
+
34
+ Args:
35
+ raw: The complete raw message string.
36
+
37
+ Returns:
38
+ A Message object with parsed components.
39
+
40
+ Raises:
41
+ ParseError: If the message format is invalid.
42
+ """
43
+ if not raw.startswith(START_DELIMITER):
44
+ raise ParseError(
45
+ f"Message must start with '{START_DELIMITER}'",
46
+ position=0,
47
+ )
48
+
49
+ # After ##: LLLL<Data><CRC>\r\n
50
+ payload = raw[len(START_DELIMITER):]
51
+
52
+ # Extract declared length (4 digits)
53
+ if len(payload) < 4:
54
+ raise ParseError("Message too short: missing length field", position=2)
55
+
56
+ try:
57
+ declared_length = int(payload[:4])
58
+ except ValueError as exc:
59
+ raise ParseError(
60
+ f"Invalid length field: {payload[:4]!r}",
61
+ position=2,
62
+ ) from exc
63
+
64
+ # Full content = length + data + crc
65
+ # Data starts at position 4, CRC is last 4 chars before \r\n
66
+ min_len = 4 + declared_length + 4 + 2 # LLLL + data + CRC + \r\n
67
+ if len(payload) < min_len:
68
+ raise ParseError(
69
+ f"Message too short: need {min_len}, got {len(payload)}",
70
+ )
71
+
72
+ data_section = payload[4 : 4 + declared_length]
73
+ crc_str = payload[4 + declared_length : 4 + declared_length + 4]
74
+
75
+ # Parse header (before first &&)
76
+ header_end = data_section.find("&&")
77
+ if header_end == -1:
78
+ raise ParseError("Missing data separator '&&'")
79
+
80
+ header_str = data_section[:header_end]
81
+ header = self._parse_header(header_str)
82
+
83
+ # Extract data body (between first && and optional trailing &&)
84
+ cp_data = data_section[header_end + 2 :]
85
+ # Strip trailing && if present (closing delimiter before CRC)
86
+ if cp_data.endswith("&&"):
87
+ cp_data = cp_data[:-2]
88
+
89
+ return Message(
90
+ header=header,
91
+ data=cp_data,
92
+ raw=raw,
93
+ crc=crc_str,
94
+ )
95
+
96
+ def _parse_header(self, header_str: str) -> Header:
97
+ """Parse header fields from semicolon-separated string.
98
+
99
+ Args:
100
+ header_str: Semicolon-separated header fields.
101
+
102
+ Returns:
103
+ A Header dataclass with parsed fields.
104
+
105
+ Raises:
106
+ ParseError: If required fields are missing.
107
+ """
108
+ fields: dict[str, str] = {}
109
+ for part in header_str.split(";"):
110
+ if "=" not in part:
111
+ raise ParseError(f"Invalid header field: {part!r}")
112
+ key, value = part.split("=", 1)
113
+ fields[key] = value
114
+
115
+ cn = fields.get("CN", "")
116
+ pw = fields.get("PW", "")
117
+
118
+ if not cn:
119
+ raise ParseError("CN (command number) is required")
120
+
121
+ return Header(
122
+ qn=fields.get("QN", ""),
123
+ st=fields.get("ST", ""),
124
+ cn=cn,
125
+ pw=pw,
126
+ mn=fields.get("MN", ""),
127
+ flag=fields.get("Flag", ""),
128
+ pno=fields.get("PNO", ""),
129
+ raw=header_str,
130
+ )
@@ -0,0 +1,80 @@
1
+ """TCP stream decoder for HJ 212-2017 protocol."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pyhj212.constants import END_DELIMITER, START_DELIMITER
6
+ from pyhj212.exceptions import ParseError
7
+ from pyhj212.models.message import Message
8
+ from pyhj212.protocol.parser import Parser
9
+
10
+
11
+ class StreamDecoder:
12
+ """Decodes HJ 212-2017 messages from a TCP byte stream.
13
+
14
+ Handles:
15
+ - Message framing with start/end delimiters
16
+ - Stream concatenation (multiple messages in one buffer)
17
+ - Message fragmentation (partial messages across reads)
18
+ """
19
+
20
+ def __init__(self) -> None:
21
+ """Initialize the stream decoder with an empty buffer."""
22
+ self._buffer = ""
23
+ self._parser = Parser()
24
+
25
+ def feed(self, data: bytes) -> list[Message]:
26
+ """Feed raw bytes into the decoder and return complete messages.
27
+
28
+ Args:
29
+ data: Raw bytes from the TCP stream.
30
+
31
+ Returns:
32
+ List of fully parsed Message objects.
33
+ """
34
+ self._buffer += data.decode("ascii", errors="replace")
35
+ messages = self._extract_messages()
36
+ return messages
37
+
38
+ def _extract_messages(self) -> list[Message]:
39
+ """Extract complete messages from the buffer.
40
+
41
+ Returns:
42
+ List of parsed Message objects.
43
+ """
44
+ messages: list[Message] = []
45
+
46
+ while True:
47
+ start_idx = self._buffer.find(START_DELIMITER)
48
+ if start_idx == -1:
49
+ self._buffer = ""
50
+ break
51
+
52
+ # Remove garbage before start delimiter
53
+ if start_idx > 0:
54
+ self._buffer = self._buffer[start_idx:]
55
+
56
+ end_idx = self._buffer.find(END_DELIMITER)
57
+ if end_idx == -1:
58
+ # Incomplete message, wait for more data
59
+ break
60
+
61
+ raw_message = self._buffer[: end_idx + len(END_DELIMITER)]
62
+ self._buffer = self._buffer[end_idx + len(END_DELIMITER) :]
63
+
64
+ try:
65
+ message = self._parser.parse(raw_message)
66
+ messages.append(message)
67
+ except ParseError:
68
+ # Skip malformed messages
69
+ continue
70
+
71
+ return messages
72
+
73
+ @property
74
+ def pending(self) -> str:
75
+ """Return the current buffer of incomplete data."""
76
+ return self._buffer
77
+
78
+ def reset(self) -> None:
79
+ """Clear the decoder buffer."""
80
+ self._buffer = ""
@@ -0,0 +1,91 @@
1
+ """Protocol validator for HJ 212-2017 messages."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pyhj212.constants import END_DELIMITER, START_DELIMITER
6
+ from pyhj212.models.message import Message
7
+ from pyhj212.models.validation import ValidationResult
8
+ from pyhj212.protocol.checksum import verify_crc
9
+
10
+
11
+ class Validator:
12
+ """Validates HJ 212-2017 messages for protocol compliance.
13
+
14
+ Checks include:
15
+ - Message format and delimiters
16
+ - Data length field accuracy
17
+ - CRC checksum verification
18
+ - Required header fields
19
+ - Data field constraints
20
+ """
21
+
22
+ def validate(self, raw: str) -> ValidationResult:
23
+ """Validate a raw HJ 212-2017 message.
24
+
25
+ Args:
26
+ raw: The raw message string to validate.
27
+
28
+ Returns:
29
+ ValidationResult indicating validity and any errors/warnings.
30
+ """
31
+ result = ValidationResult()
32
+
33
+ if not raw.startswith(START_DELIMITER):
34
+ result.add_error(
35
+ f"Message must start with '{START_DELIMITER}'"
36
+ )
37
+ return result
38
+
39
+ if not raw.endswith(END_DELIMITER):
40
+ result.add_error(
41
+ f"Message must end with {END_DELIMITER!r}"
42
+ )
43
+ return result
44
+
45
+ # Extract content: strip ## prefix and \r\n suffix
46
+ content = raw[len(START_DELIMITER) : -len(END_DELIMITER)]
47
+
48
+ # Extract and validate length
49
+ try:
50
+ declared_length = int(content[:4])
51
+ except ValueError:
52
+ result.add_error("Invalid length field")
53
+ return result
54
+
55
+ actual_content = content[4:-4] # Skip length and CRC
56
+ if len(actual_content) != declared_length:
57
+ result.add_error(
58
+ f"Length mismatch: declared {declared_length}, actual {len(actual_content)}",
59
+ )
60
+
61
+ # Validate CRC
62
+ crc_str = content[-4:]
63
+ try:
64
+ expected_crc = int(crc_str, 16)
65
+ except ValueError:
66
+ result.add_error(f"Invalid CRC format: {crc_str!r}")
67
+ return result
68
+
69
+ if not verify_crc(actual_content, expected_crc):
70
+ result.add_error("CRC verification failed")
71
+
72
+ return result
73
+
74
+ def validate_message(self, message: Message) -> ValidationResult:
75
+ """Validate a parsed Message object.
76
+
77
+ Args:
78
+ message: The parsed Message to validate.
79
+
80
+ Returns:
81
+ ValidationResult indicating validity and any errors/warnings.
82
+ """
83
+ result = ValidationResult()
84
+
85
+ if not message.header.cn:
86
+ result.add_error("CN (command number) is required")
87
+
88
+ if message.data and len(message.data) > 9999:
89
+ result.add_error("Data length exceeds maximum of 9999")
90
+
91
+ return result
@@ -0,0 +1,4 @@
1
+ """Version information for PyHJ212."""
2
+
3
+ __version__ = "0.1.0"
4
+ __version_tuple__ = (0, 1, 0)
@@ -0,0 +1,154 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyhj212
3
+ Version: 0.1.0
4
+ Summary: A Python library for HJ212 protocol encoding, decoding, validation, and communication.
5
+ Author-email: tinychen <weinanmay@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/tinychen/pyhj212
8
+ Project-URL: Repository, https://github.com/tinychen/pyhj212
9
+ Project-URL: Issues, https://github.com/tinychen/pyhj212/issues
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Provides-Extra: dev
21
+ Requires-Dist: pytest>=8.0; extra == "dev"
22
+ Requires-Dist: pytest-cov>=5.0; extra == "dev"
23
+ Requires-Dist: hypothesis>=6.0; extra == "dev"
24
+ Requires-Dist: ruff>=0.6.0; extra == "dev"
25
+ Requires-Dist: mypy>=1.0; extra == "dev"
26
+ Dynamic: license-file
27
+
28
+ # pyhj212
29
+
30
+ HJ 212-2017 协议核心协议的 Python 实现,提供消息编解码、CRC 校验、协议验证、TCP 流帧解码以及 CP 字段解析功能。
31
+
32
+ ## 特性
33
+
34
+ | 功能 | 状态 |
35
+ |------|------|
36
+ | 消息解析 | ✅ |
37
+ | 消息编码 | ✅ |
38
+ | CRC-16 计算与校验 | ✅ |
39
+ | CP 字段解析与编码 | ✅ |
40
+ | 协议验证 | ✅ |
41
+ | TCP 流帧解码(粘包/分包) | ✅ |
42
+ | Dataclass 数据模型 | ✅ |
43
+
44
+ ## 快速开始
45
+
46
+ ### 安装
47
+
48
+ ```bash
49
+ # 使用 uv 安装开发依赖
50
+ uv sync --all-extras
51
+
52
+ # 或直接安装
53
+ pip install -e .
54
+ ```
55
+
56
+ ### 解析消息
57
+
58
+ ```python
59
+ from pyhj212.protocol.parser import Parser
60
+
61
+ raw = (
62
+ "##0101QN=20160801085857223;ST=32;CN=1062;PW=100000;"
63
+ "MN=010000A8900016F000169DC0;Flag=5;CP=&&RtdInterval=30&&"
64
+ "1C80\r\n"
65
+ )
66
+
67
+ parser = Parser()
68
+ msg = parser.parse(raw)
69
+
70
+ print(msg.header.cn) # "1062"
71
+ print(msg.header.mn) # "010000A8900016F000169DC0"
72
+ print(msg.data) # "RtdInterval=30"
73
+ print(msg.crc) # "1C80"
74
+ ```
75
+
76
+ ### 编码消息
77
+
78
+ ```python
79
+ from pyhj212.models.header import Header
80
+ from pyhj212.models.message import Message
81
+ from pyhj212.protocol.encoder import Encoder
82
+
83
+ header = Header(
84
+ qn="20160801085857223", st="32", cn="1062", pw="100000",
85
+ mn="010000A8900016F000169DC0", flag=5, pno=0,
86
+ )
87
+ message = Message(header=header, data="RtdInterval=30")
88
+
89
+ encoder = Encoder()
90
+ raw = encoder.encode(message)
91
+ # "##0101QN=20160801085857223;ST=32;CN=1062;PW=100000;..."
92
+ ```
93
+
94
+ ### 验证消息
95
+
96
+ ```python
97
+ from pyhj212.protocol.validator import Validator
98
+
99
+ validator = Validator()
100
+ result = validator.validate(raw)
101
+
102
+ if not result.is_valid:
103
+ for error in result.errors:
104
+ print(f"错误: {error}")
105
+ ```
106
+
107
+ ### TCP 流解码
108
+
109
+ ```python
110
+ from pyhj212.protocol.stream import StreamDecoder
111
+
112
+ decoder = StreamDecoder()
113
+
114
+ # 分包场景
115
+ decoder.feed(b"##0030QN=...;F")
116
+ decoder.feed(b"lag=5;CP=&&RtdInterval=30&&1C80\r\n")
117
+
118
+ # 粘包场景
119
+ decoder.feed(b"##0030...&&1C80\r\n##0030...&&2A3B\r\n")
120
+ ```
121
+
122
+ ### CP 字段解析
123
+
124
+ ```python
125
+ from pyhj212.cp.parser import CPParser
126
+
127
+ parser = CPParser()
128
+ fields = parser.parse("PNO=000000004;DataTime=20260902082000;a01001-Rtd=24.4")
129
+
130
+ for f in fields:
131
+ print(f"{f.key} = {f.value}")
132
+ ```
133
+
134
+ ## 开发
135
+
136
+ 参见 [DEVELOPMENT.md](DEVELOPMENT.md)。
137
+
138
+ ```bash
139
+ # 运行测试
140
+ uv run pytest
141
+
142
+ # 代码检查
143
+ uv run ruff check src/pyhj212 tests
144
+ uv run ruff format src/pyhj212 tests
145
+ uv run mypy src/pyhj212
146
+ ```
147
+
148
+ ## 协议
149
+
150
+ - HJ 212-2017 《污染物在线监控(监测)系统数据传输标准》
151
+
152
+ ## License
153
+
154
+ MIT
@@ -0,0 +1,26 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/pyhj212/__init__.py
5
+ src/pyhj212/constants.py
6
+ src/pyhj212/exceptions.py
7
+ src/pyhj212/version.py
8
+ src/pyhj212.egg-info/PKG-INFO
9
+ src/pyhj212.egg-info/SOURCES.txt
10
+ src/pyhj212.egg-info/dependency_links.txt
11
+ src/pyhj212.egg-info/requires.txt
12
+ src/pyhj212.egg-info/top_level.txt
13
+ src/pyhj212/cp/__init__.py
14
+ src/pyhj212/cp/encoder.py
15
+ src/pyhj212/cp/models.py
16
+ src/pyhj212/cp/parser.py
17
+ src/pyhj212/models/__init__.py
18
+ src/pyhj212/models/header.py
19
+ src/pyhj212/models/message.py
20
+ src/pyhj212/models/validation.py
21
+ src/pyhj212/protocol/__init__.py
22
+ src/pyhj212/protocol/checksum.py
23
+ src/pyhj212/protocol/encoder.py
24
+ src/pyhj212/protocol/parser.py
25
+ src/pyhj212/protocol/stream.py
26
+ src/pyhj212/protocol/validator.py
@@ -0,0 +1,7 @@
1
+
2
+ [dev]
3
+ pytest>=8.0
4
+ pytest-cov>=5.0
5
+ hypothesis>=6.0
6
+ ruff>=0.6.0
7
+ mypy>=1.0
@@ -0,0 +1 @@
1
+ pyhj212