Skip to main content

CSP Common Library - 模組化工具集

Project description

CSP Library

License Python Version 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 自動清理
  • Fluent BuilderSystemControllerConfig.builder() 鏈式配置
  • 按需安裝: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[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.7.2},
  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.7.2.tar.gz (316.4 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.7.2-py3-none-any.whl (447.9 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for csp0924_lib-0.7.2.tar.gz
Algorithm Hash digest
SHA256 fb7486cd4af3fef269449caa38d1bc006af0ca1e77acf280e49f739eb46983df
MD5 ffe89b47e112126c946d48275e5f5292
BLAKE2b-256 f9e04733e416e360c3fa035e3a0167e1192854fae70305aec12f0a60bebdb55e

See more details on using hashes here.

Provenance

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

Publisher: build-wheels.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.7.2-py3-none-any.whl.

File metadata

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

File hashes

Hashes for csp0924_lib-0.7.2-py3-none-any.whl
Algorithm Hash digest
SHA256 c904d65bc3ad0b649d0960c5b7b82799c7d2c9e1682fb6f015ae52a6a8c3df4d
MD5 0dd6002e74f7acf3761618ec95368fe2
BLAKE2b-256 9779e72c41cb5f0a0daf3ff93d4c842305f5e1eeb1df4e674e41358ec68bc308

See more details on using hashes here.

Provenance

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

Publisher: build-wheels.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