Skip to main content

pyhj212

HJ 212-2017 协议核心协议的 Python 实现,提供消息编解码、CRC 校验、协议验证、TCP 流帧解码以及 CP 字段解析功能。

特性

功能 状态
消息解析 ✅
消息编码 ✅
CRC-16 计算与校验 ✅
CP 字段解析与编码 ✅
协议验证 ✅
TCP 流帧解码(粘包/分包) ✅
Dataclass 数据模型 ✅

快速开始

从 PyPI 安装

pip install pyhj212

项目地址:https://pypi.org/project/pyhj212/

从源码安装(开发模式)

git clone https://github.com/tinychen/pyhj212.git
cd pyhj212
uv sync --all-extras   # 或 pip install -e ".[dev]"

解析消息

from pyhj212.protocol.parser import Parser

raw = (
    "##0101QN=20160801085857223;ST=32;CN=1062;PW=100000;"
    "MN=010000A8900016F000169DC0;Flag=5;CP=&&RtdInterval=30&&"
    "1C80\r\n"
)

parser = Parser()
msg = parser.parse(raw)

print(msg.header.cn)   # "1062"
print(msg.header.mn)   # "010000A8900016F000169DC0"
print(msg.data)        # "RtdInterval=30"
print(msg.crc)         # "1C80"

编码消息

from pyhj212.models.header import Header
from pyhj212.models.message import Message
from pyhj212.protocol.encoder import Encoder

header = Header(
    qn="20160801085857223", st="32", cn="1062", pw="100000",
    mn="010000A8900016F000169DC0", flag="5",
)
message = Message(header=header, data="RtdInterval=30")

encoder = Encoder()
raw = encoder.encode(message)
# "##0101QN=20160801085857223;ST=32;CN=1062;PW=100000;..."

验证消息

from pyhj212.protocol.validator import Validator

validator = Validator()
result = validator.validate(raw)

if not result.is_valid:
    for error in result.errors:
        print(f"错误: {error}")

TCP 流解码

from pyhj212.protocol.stream import StreamDecoder

decoder = StreamDecoder()

# 分包场景
decoder.feed(b"##0030QN=...;F")
decoder.feed(b"lag=5;CP=&&RtdInterval=30&&1C80\r\n")

# 粘包场景
decoder.feed(b"##0030...&&1C80\r\n##0030...&&2A3B\r\n")

CP 字段解析

CP 数据区由 ; 分隔的键值对组成,, 分隔的逗号段属于同一监测因子的多个属性。

扁平解析

from pyhj212.cp.parser import CPParser

parser = CPParser()
fields = parser.parse("PNO=000000004;DataTime=20260902082000;a01001-Rtd=24.4")

for f in fields:
    print(f"{f.key} = {f.value}")
# PNO = 000000004
# DataTime = 20260902082000
# a01001-Rtd = 24.4

归组解析

将同一监测因子(tn0112、w01001 等)的多个属性合并为一个父节点:

cp = "DataTime=20261118134500;tn0112-Rtd=228.200,tn0112-Flag=N"
fields = parser.parse_grouped(cp)

for f in fields:
    if f.children:
        print(f"{f.key}:")
        for c in f.children:
            print(f"  {c.key} = {c.value}")
    else:
        print(f"{f.key} = {f.value}")
# DataTime = 20261118134500
# tn0112:
#   Rtd = 228.200
#   Flag = N

序列化 JSON

import json

data = [f.to_dict() for f in fields]
print(json.dumps(data, ensure_ascii=False, indent=2))
# [
#   {"DataTime": "20261118134500"},
#   {"tn0112": {"Rtd": "228.200", "Flag": "N"}}
# ]

开发

参见 DEVELOPMENT.md。

# 运行测试
uv run pytest

# 代码检查
uv run ruff check src/pyhj212 tests
uv run ruff format src/pyhj212 tests
uv run mypy src/pyhj212

协议

  • HJ 212-2017 《污染物在线监控(监测)系统数据传输标准》

License

MIT

Metadata

Release files for pyhj212 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pyhj212 0.1.1
File Size Uploaded Provenance Actions
pyhj212-0.1.1.tar.gz 13.7 kB Without provenance Details for pyhj212-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pyhj212 0.1.1
File Interpreter ABI Platform Actions
pyhj212-0.1.1-py3-none-any.whl Python 3 none any Details for pyhj212-0.1.1-py3-none-any.whl

Total release size: 29.9 kB

Release files / pyhj212-0.1.1.tar.gz

Download URL pyhj212-0.1.1.tar.gz
Size 13.7 kB
Tags Source
SHA-256 checksum
How to use checksums
c5e39b2a3db44b039fe81bec2b5515218b865794453a8fb4f4fce52a3d0c1b76
BLAKE2b-256 checksum
How to use checksums
7a038b8c6a91377bec22bd2ee4a5594fb1f18a7684178c9ac0fd870155454fe3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.8.20

Release files / pyhj212-0.1.1-py3-none-any.whl

Download URL pyhj212-0.1.1-py3-none-any.whl
Size 16.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
09f61f2900b716d908f1b7a7ac14c8390a7dd5b13799c2171d8de1213b6939f2
BLAKE2b-256 checksum
How to use checksums
49cbc88f107c4be58e37cf741fc5819118d5cd9ad25b0150ddc24ae1be0bac52
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.8.20

Security for pyhj212 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page