Skip to main content

CSP Common Library - 模組化工具集

Project description

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 sentinelCommand.p_target / q_target 支援 NO_CHANGE,策略可宣告「此軸不變更」,CommandRouter 跳過對應軸寫入,多策略 cascade 正確組合(v0.8.0)
  • Event-driven TriggerSystemController.attach_read_trigger(device_id) 綁定設備讀完即觸發策略,搭配 TRIGGERED/HYBRID 模式消除 phase drift(v0.8.0)
  • ContextMapping param_key:直接從 RuntimeParameters 注入 context 欄位,不需手動搬入 extra(v0.8.0)
  • Fluent BuilderSystemControllerConfig.builder() 鏈式配置
  • Operator PatternReconciler 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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

csp0924_lib-0.9.1.tar.gz (390.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

csp0924_lib-0.9.1-py3-none-any.whl (540.4 kB view details)

Uploaded Python 3

File details

Details for the file csp0924_lib-0.9.1.tar.gz.

File metadata

  • Download URL: csp0924_lib-0.9.1.tar.gz
  • Upload date:
  • Size: 390.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.13

File hashes

Hashes for csp0924_lib-0.9.1.tar.gz
Algorithm Hash digest
SHA256 bb303b135bdfd678303f9a83e90a698afb89fe12766047dfddead7fe742e89f0
MD5 d3aaedef9fdd34b1665f5b7b1dcc6c46
BLAKE2b-256 d45579c8ae859c19b9495e887361a2d4129e867a1f9781027a6cda606e12f9a8

See more details on using hashes here.

Provenance

The following attestation bundles were made for csp0924_lib-0.9.1.tar.gz:

Publisher: release.yml on csp0924/csplib

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file csp0924_lib-0.9.1-py3-none-any.whl.

File metadata

  • Download URL: csp0924_lib-0.9.1-py3-none-any.whl
  • Upload date:
  • Size: 540.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.13

File hashes

Hashes for csp0924_lib-0.9.1-py3-none-any.whl
Algorithm Hash digest
SHA256 214ca388c126be5e6eaa4c7f2311d5c188387c1a0555a33a13eac7b68fe51947
MD5 7a9eec15b721552990ab9ac97fc66516
BLAKE2b-256 2edb9ec1ebcf55642ebb0a73681cb1d7a7a2b417f27e93f949bbad333abc45bb

See more details on using hashes here.

Provenance

The following attestation bundles were made for csp0924_lib-0.9.1-py3-none-any.whl:

Publisher: release.yml on csp0924/csplib

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page