Skip to main content

CSP Library

License Python PyPI PyPI Downloads

CSP Common Library 是一個模組化的 Python 工具集,專為能源管理系統與工業設備通訊設計。

特點

  • 8 層分層架構:Core → Modbus/CAN → Equipment → Controller → Manager → Integration → Storage → Additional
  • Async-first:所有設備 I/O 與管理器皆採用 asyncio
  • 多協議支援:Modbus TCP/RTU 與 CAN Bus 雙協議設備抽象
  • 策略引擎:PQ/QV/FP/Droop/Island/PVSmooth/LoadShedding/RampStop 等 10+ 內建策略
  • 功率補償:前饋 + 積分閉環補償(PowerCompensator),含 FF Table 自動學習
  • 動態保護:DynamicSOCProtection / GridLimitProtection 從 RuntimeParameters 即時讀取參數
  • 功率分配:Equal / Proportional / SOCBalancing 多機分配,含硬體限制 + 溢出轉移
  • Modbus TCP Gateway:宣告式暫存器映射、寫入驗證、資料同步,對接 EMS/SCADA
  • 韌性機制:CircuitBreaker(指數退避 + jitter)+ RetryPolicy
  • Event-driven:設備事件系統 + WeakRef 自動清理
  • 精度控制:ExecutionConfig.interval_seconds 支援 float(sub-second 策略如 DReg 0.3 s);StrategyExecutor work-first + 絕對時間錨定漂移補償(v0.8.0)
  • NO_CHANGE sentinel:Command.p_target / q_target 支援 NO_CHANGE,策略可宣告「此軸不變更」,CommandRouter 跳過對應軸寫入,多策略 cascade 正確組合(v0.8.0)
  • Event-driven Trigger:SystemController.attach_read_trigger(device_id) 綁定設備讀完即觸發策略,搭配 TRIGGERED/HYBRID 模式消除 phase drift(v0.8.0)
  • ContextMapping param_key:直接從 RuntimeParameters 注入 context 欄位,不需手動搬入 extra(v0.8.0)
  • Fluent Builder:SystemControllerConfig.builder() 鏈式配置
  • Operator Pattern:Reconciler Protocol + TypeRegistry + YAML Site Manifest,K8s 風宣告式站點配置與自我修復調和迴圈(v0.9.0)
  • 按需安裝:Optional dependencies 避免引入不必要的套件

安裝

# 基本安裝
pip install csp0924_lib

# 按需安裝
pip install csp0924_lib[modbus]     # Modbus 通訊
pip install csp0924_lib[can]        # CAN Bus 通訊
pip install csp0924_lib[mongo]      # MongoDB
pip install csp0924_lib[redis]      # Redis(含 Sentinel + TLS)
pip install csp0924_lib[monitor]    # 系統監控
pip install csp0924_lib[cluster]    # 分散式叢集
pip install csp0924_lib[gui]        # FastAPI Web GUI
pip install csp0924_lib[manifest]   # YAML Site Manifest(pyyaml)
pip install csp0924_lib[all]        # 所有功能

架構

┌─────────────────────────────────────────────────────────────┐
│  Layer 8  Additional                                         │
│  Cluster · Monitor · Notification · ModbusServer · Gateway   │
│  Statistics · GUI                                            │
├──────────────────────────────┬──────────────────────────────┤
│  Layer 7  Storage            │  Layer 6  Integration         │
│  MongoDB · Redis             │  Registry · SystemController  │
│                              │  ContextBuilder · CommandRouter│
├──────────────────────────────┤  Distributor · Orchestrator   │
│  Layer 5  Manager            ├──────────────────────────────┤
│  Unified · Alarm · Command   │  Layer 4  Controller          │
│  DataUpload · StateSync      │  Strategies · Executor        │
│                              │  Protection · Compensator     │
├──────────────────────────────┴──────────────────────────────┤
│  Layer 3  Equipment                                          │
│  AsyncModbusDevice · Points · Alarms · Transport · Pipeline  │
├─────────────────────────────────────────────────────────────┤
│  Layer 2  Modbus / CAN                                       │
│  DataTypes · Codec · Clients (TCP/RTU/Shared) · CAN Bus      │
├─────────────────────────────────────────────────────────────┤
│  Layer 1  Core                                               │
│  Logging · Lifecycle · Errors · Health · Resilience           │
│  RuntimeParameters                                           │
└─────────────────────────────────────────────────────────────┘

依賴方向:下層 → 上層(下層不可 import 上層)

Quick Start

import asyncio
from csp_lib.modbus import PymodbusTcpClient, ModbusTcpConfig, Float32, UInt16
from csp_lib.equipment.core import ReadPoint, WritePoint
from csp_lib.equipment.device import AsyncModbusDevice, DeviceConfig

device = AsyncModbusDevice(
    config=DeviceConfig(device_id="inverter_001", unit_id=1),
    client=PymodbusTcpClient(ModbusTcpConfig(host="192.168.1.100")),
    always_points=[
        ReadPoint(name="voltage", address=0, data_type=Float32()),
        ReadPoint(name="power", address=2, data_type=UInt16()),
    ],
)

async def main():
    async with device:
        values = await device.read_all()
        print(f"Voltage: {values['voltage']}V, Power: {values['power']}W")

asyncio.run(main())

更多範例見 examples/ 目錄。

模組總覽

層 模組 說明 文件
L1 core Logging · Lifecycle · Errors · Health · Resilience · RuntimeParameters →
L2 modbus 資料型別 · Codec · TCP/RTU/Shared 客戶端 →
L2 can CAN Bus 客戶端 · 配置 · 例外 →
L3 equipment AsyncModbusDevice · Points · Alarms · Transport · Transforms →
L4 controller 10+ 策略 · Executor · Protection · Compensator · Calibration →
L5 manager Unified · Alarm · Command · DataUpload · StateSync →
L6 integration Registry · SystemController · ContextBuilder · CommandRouter · Distributor →
L7 mongo MongoConfig · MongoBatchUploader →
L7 redis RedisClient(Standalone/Sentinel/TLS)· Pub/Sub →
L8 cluster Leader Election · State Sync · HA Controller →
L8 monitor 系統指標收集 · 告警評估 · Redis 發佈 →
L8 notification 多通道告警分發(Telegram/LINE/自訂) →
L8 modbus_server Modbus TCP 模擬伺服器(測試用) →
L8 modbus_gateway Modbus TCP Gateway(EMS/SCADA 介面) →
L8 statistics 能源統計(累計度數、運行時數) —
L8 gui FastAPI Web 介面 —

控制流程

設備讀取 → ContextBuilder → StrategyContext
                                ↓
                    StrategyExecutor(策略由 ModeManager 決定)
                                ↓
                    Command → ProtectionGuard → CommandProcessor
                                ↓
                    PowerDistributor → CommandRouter → 設備寫入

範例

檔案 說明
01_basic_device.py 基本設備讀寫
03_control_strategies.py 控制策略使用
05_system_controller.py SystemController 進階控制
14_power_distributor.py 多機功率分配
15_modbus_gateway.py Modbus TCP Gateway
demo_ess_dreg.py ESS Droop 調頻 + 補償 + 校準
demo_full_system.py 完整系統端到端整合

完整範例列表見 examples/。

開發

# 安裝所有依賴
uv sync --all-groups --all-extras

# 測試
uv run python -m pytest tests/ -v

# Lint + Format + Type Check
uv run ruff check .
uv run ruff format .
uv run mypy csp_lib/

授權

Apache License 2.0 — Copyright 2024-2026 Cheng Sin Pang(鄭善淜)

引用

@software{csp_library,
  title = {CSP Library},
  author = {Cheng Sin Pang (鄭善淜)},
  year = {2024},
  url = {https://github.com/csp0924/csp_lib},
  version = {0.9.1}, % x-release-please-version
  license = {Apache-2.0}
}

詳見 CITATION.cff · CHANGELOG.md

Metadata

Release files for csp0924-lib 0.9.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 csp0924-lib 0.9.1
File Size Uploaded Provenance Actions
csp0924_lib-0.9.1.tar.gz 390.6 kB With provenance Details for csp0924_lib-0.9.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for csp0924-lib 0.9.1
File Interpreter ABI Platform Actions
csp0924_lib-0.9.1-py3-none-any.whl Python 3 none any Details for csp0924_lib-0.9.1-py3-none-any.whl

Total release size: 931.0 kB

Release files / csp0924_lib-0.9.1.tar.gz

Download URL csp0924_lib-0.9.1.tar.gz
Size 390.6 kB
Tags Source
SHA-256 checksum
How to use checksums
bb303b135bdfd678303f9a83e90a698afb89fe12766047dfddead7fe742e89f0
BLAKE2b-256 checksum
How to use checksums
d45579c8ae859c19b9495e887361a2d4129e867a1f9781027a6cda606e12f9a8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.13

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Apr 21, 2026.

Transparency log

Release files / csp0924_lib-0.9.1-py3-none-any.whl

Download URL csp0924_lib-0.9.1-py3-none-any.whl
Size 540.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
214ca388c126be5e6eaa4c7f2311d5c188387c1a0555a33a13eac7b68fe51947
BLAKE2b-256 checksum
How to use checksums
2edb9ec1ebcf55642ebb0a73681cb1d7a7a2b417f27e93f949bbad333abc45bb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.13

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Apr 21, 2026.

Transparency log

Security for csp0924-lib 0.9.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.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for csp0924_lib-0.9.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Apr 21, 2026.

Transparency log

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.

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