Metadata-Version: 2.4
Name: sme-sim-common
Version: 1.3.0
Summary: Shared web shell, brand, i18n and Python helpers for the smart-edge simulator family
License: MIT
Project-URL: Homepage, https://github.com/smartedge-tech-dev/sme-sim-common
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: starlette
Requires-Dist: fastapi>=0.110
Requires-Dist: uvicorn[standard]
Requires-Dist: pydantic>=2
Requires-Dist: pyyaml>=6
Requires-Dist: python-multipart
Provides-Extra: xlsx
Requires-Dist: openpyxl>=3.1; extra == "xlsx"
Provides-Extra: mcp
Requires-Dist: mcp<3,>=2.3; extra == "mcp"
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: httpx; extra == "dev"
Requires-Dist: openpyxl>=3.1; extra == "dev"
Requires-Dist: pyinstaller; extra == "dev"
Requires-Dist: mcp<3,>=2.3; extra == "dev"
Dynamic: license-file

# sme-sim-common

**English** | [日本語](README.ja.md) | [简体中文](README.zh-CN.md)

Shared runtime for the smart-edge simulator series (SME BACnetSim, SME ModbusSim, SME OCPPSim,
SME SerialHub): the web shell (header, menus, theme, languages, About), vendor texts, the `common.*`
UI strings, and the protocol-independent Python layer (web helpers, config I/O, behaviors, device
templates, test helpers, PyInstaller hook). The `templates/` directory holds the build-time skeleton
(CI, release, packaging, docs, page) that products copy by hand; it is not part of the wheel.

MIT-licensed, developed by [smart-edge (智届科技)](https://smartedge-tech.com).

## Install

```bash
pip install "sme-sim-common>=1.0,<2"          # in a product's pyproject.toml dependencies
pip install "sme-sim-common[xlsx]>=1.0,<2"    # with the .xlsx import / export helpers (openpyxl)
pip install "sme-sim-common[mcp]>=1.3,<2"     # with the MCP server skeleton (official mcp SDK)
pip install -e ../sme-sim-common              # local development against a checkout
```

Python 3.11 or newer.

## Using it in a product

### Mount the common static files

```python
from fastapi import FastAPI
from sme_sim_common.web import mount_common, mount_product_static

app = FastAPI()
mount_common(app)                          # serves /sme-sim-common/{shell,vendor,i18n,brand}/...
mount_product_static(app, STATIC_DIR)      # the product's own /static (skipped if the directory is missing)
```

The common files live under their own prefix `/sme-sim-common`, never under `/static`: Starlette matches
mounts in registration order, so a nested path would be swallowed by the product's `/static` mount.

### Minimal app

```python
import argparse
from pathlib import Path

from sme_sim_common.cli import add_common_args, run_web
from sme_sim_common.web import make_base_app

ap = add_common_args(argparse.ArgumentParser(), default_http_port=8080, app_name="sme-my-sim")
args = ap.parse_args()
engine = MyEngine(...)                     # follows sme_sim_common.engine.EngineProtocol (or subclass BaseEngine)
app = make_base_app(engine, config_path=args.config, static_dir=Path(__file__).parent / "static")
run_web(app, args)                         # uvicorn on args.host / args.http_port, opens the browser
```

### Page skeleton

Start from `templates/static/index.html`. The load order is fixed:

1. `/sme-sim-common/shell/shell.css` then the product `/static/style.css`
2. `/sme-sim-common/shell/shell.js` in `<head>` with `data-storage="<dist name>"` (localStorage prefix;
   the stored theme is applied before first paint)
3. `/sme-sim-common/vendor/vendor.js`, then `/sme-sim-common/i18n/common.js`
4. the product dictionaries `/static/i18n/en.js`, `ja.js`, `zh.js`, then `/static/app.js`

The common assets carry a `?v=` version query so browsers do not keep stale shell files after an upgrade;
`Shell.version` reports the sme-sim-common version and the About dialog shows it.

### Vendor

`vendor/vendor.js` registers the company preset `Shell.vendors.smartEdge` and the `vendor.*` strings.
Products pass it explicitly:

```js
Shell.init({ ...PRODUCT, vendor: Shell.vendors.smartEdge });
```

Company texts are maintained only here, so a change reaches every product with the next common release.

### i18n prefixes

| Prefix | Owner |
|---|---|
| `shell.*` | sme-sim-common: UI framework (menus, theme, language, help, About) — `shell.js` |
| `vendor.*` | sme-sim-common: company texts — `vendor/vendor.js` |
| `common.*` | sme-sim-common: features provided by the common layer — `i18n/common.js` |
| anything else | the product — `static/i18n/{en,ja,zh}.js` |

Products must not define the three reserved prefixes. Guard it in the product tests:

```python
from sme_sim_common.testing import check_i18n_keys

def test_no_reserved_i18n_keys():
    check_i18n_keys(STATIC_DIR)
```

`common.*` keys are named after the feature, not the menu position, and must be unambiguous in every
product of the series (e.g. `common.backend.connected`, not `ws.on`).

### Accent color

Each product has its own accent color. `shell.css` defaults to the brand blue `#087def`; a product
overrides `--accent`, `--accent-ink` and `--accent-weak` in three blocks of its `style.css`
(`:root`, `:root[data-theme="dark"]` and the `prefers-color-scheme: dark` block) — see
`templates/static/style.css`. The vendor area uses `--vendor-accent` (always brand blue) and must not be
overridden.

### Extension points

All optional; products pass them instead of re-implementing the standard routes.

- Device keys: `key_type` (default: the type of the `device_key` field, `int` or `str`) converts the path
  parameter — `make_base_app(engine, device_key="device_id")` reads `/api/devices/1001/config` as `1001`.
- `create_hook(engine, body) -> dict` completes a new device before validation:
  `create_hook=lambda e, b: {**b, "device_id": b.get("device_id") or free_id(e)}`.
- `duplicate_hook(engine, dev, new_key, body) -> dict` runs before the "already exists" check and may change the
  key: `duplicate_hook=lambda e, d, k, b: {**d, "unit": free_unit(e)}`. Without a hook the copy is keyed
  `{key}_copy` (`str` keys) or largest key + 1 (`int` keys).
- `simulation_hook(engine, rest) -> dict | None` gets the `POST /api/simulation` fields other than `running` /
  `time_scale`; a dict result is merged into the response: `simulation_hook=lambda e, rest: e.apply_set_time(rest)`.
- `TemplateRegistry(..., extra_keys=("identification",))` allows extra top-level keys in user templates;
  `registry.expand_device_extras(dev)` returns them merged with the device's own fields (non-empty device value
  wins, dicts merged shallowly) and `device_as_template` exports them.
- `import_hooks={".csv": import_ede, ".zip": import_ede, ".yaml": import_text}` for `POST /api/config/import`:
  `hook(engine, files: dict[name, bytes]) -> (config | None, messages[, config_text])`; `.xlsx` (and any other
  extension) still goes to the `XlsxSchema`. The event log records the warning count and the first 5 warnings.
- `add_common_args(ap, ..., open_browser=False)`: do not open the browser by default (`--browser` opens it,
  `--no-browser` is kept).
- `engine.wake()`: run one `_on_tick` (scan / push) now, without advancing simulated time or shifting the tick
  schedule; thread-safe: `stack.on_write = lambda *a: engine.wake()`.
- `logger_name = "sme_my_sim.engine"` on a `BaseEngine` subclass names `self.logger`, used for all engine logging.
- `duplicate_hook` with a `src_key` keyword (or `**kwargs`) also gets the source device's key, e.g. "first free
  key after the source": `def dup(engine, dev, new_key, body, *, src_key)`. Hooks without it are called as before;
  `dev` is a fresh copy (source dump + new key), the source device is never passed.
- 404 for an unknown device shows the converted key: `unknown device 1008` (`int` keys unquoted).
- `Sheet(..., open_columns=True)`: on export the scalar fields without a column become dynamic columns (after the
  known ones, in order), so `text_1` ... `text_12` round-trip; `export_rows` may also return
  `(rows, {sheet: [(header, help), ...]})` to name extra columns explicitly (they come first).
- `export_rows` may return `(rows, extra_columns, warnings)` (`extra_columns` may be `None`): the product's own
  export warnings (e.g. a dangling reference) come back from `export_xlsx` before the shared ones (cell limit).
- `Sheet(..., required_headers=("value",))`: the column must exist but cells may be empty (`required` keeps
  "present and non-empty"); `skip_blank=("value",)` silently skips rows whose `value` is empty (key / value
  sheets such as `Network`).

### Config write-back

Write the result of these with `atomic_write_text`; both keep the comments outside the part they change and
fall back to rewriting more when the layout is unusual.

- `replace_yaml_block(text, "network", value)` replaces one top-level block.
- `replace_yaml_list_item(text, "chargers", "id", "0123", item)` replaces only the list item whose `id`
  equals `"0123"` (compared as `str`), appends `item` when there is none, or deletes it with `item=None`;
  the other items keep their lines and comments.

### MCP endpoint, `/healthz`, JSON logs

`pip install "sme-sim-common[mcp]"` adds the official `mcp` SDK (2.x). The product registers tools, usually
one per existing HTTP API operation, and serves them on its own web port at `/mcp` (MCP streamable HTTP,
stateless, JSON responses); there is no extra port.

```python
from sme_sim_common.logs import setup_logging
from sme_sim_common.mcp_server import McpRegistry, ToolError, register_base_tools

setup_logging(verbose=args.verbose, log_format=args.log_format)   # add_common_args(..., log_format=True)
app = make_base_app(engine, ...)

mcp = McpRegistry("sme-ocpp-sim", version=__version__)
register_base_tools(mcp, app)        # get_version, get_state, export_config, set_simulation
mcp.register_http_tool("list_chargers", "List the simulated charge points.", "GET", "/api/chargers")
mcp.register_http_tool("plug_in", "Plug a vehicle into a connector.", "POST",
                       "/api/chargers/{id}/plug", PlugArgs)    # pydantic model -> inputSchema

@mcp.tool(input_schema={"type": "object", "properties": {"id": {"type": "string"}}, "required": ["id"]})
async def charger_meter(args):
    """Current meter value of one charge point (Wh)."""
    cp = engine.find(args["id"])
    if cp is None:
        raise ToolError(f"unknown charge point {args['id']}")
    return {"id": cp.id, "wh": cp.meter_wh}

mcp.mount(app, host=args.host)       # before run_web(app, args)
```

```bash
claude mcp add --transport http sme-ocpp-sim http://127.0.0.1:8082/mcp
```

- `register_tool(name, description, input_schema=None, handler=None, *, read_only=None, destructive=None)`;
  `input_schema` is a JSON schema dict (`type: object`), a pydantic model class (the handler then receives a
  validated instance) or `None`. Handlers may be async. A `str` result is text, a `dict` is JSON text plus
  `structuredContent`.
- Errors: `ToolError`, `bad(...)` / `HTTPException`, `ValueError`, `TypeError`, `LookupError` and argument
  validation errors (pydantic model or JSON schema dict) become MCP tool errors (`isError: true`) with the message; other exceptions are logged
  and returned as tool errors too. An unknown tool name is a JSON-RPC error (`-32602`).
- `register_http_tool(name, description, method, path, input_schema=None, *, body="json")` calls the
  product's own route in-process (same validation and hooks as the web UI). `{param}` in `path` comes from the
  argument of that name; the rest is the JSON body (`body="text"`: the `body` argument as text; `GET`: query
  parameters). A status >= 400 is a tool error.
- `mount(app, path="/mcp", *, host=None)`: on a loopback `host` (the default) requests with a non-loopback
  `Host` / `Origin` header are refused (DNS-rebinding protection of `/mcp` only; the `/api/*` routes are
  unchanged). Pass `args.host`, so `--host 0.0.0.0` (Docker) accepts the LAN host name. Like the web UI, the
  endpoint has no authentication.
- stdio: `await mcp.run_stdio(app)` runs the app lifespan (engine) and serves MCP on stdin/stdout, for
  clients that launch the simulator themselves. Root log handlers on stdout are moved to stderr; the product
  must not `print` to stdout in that mode. Claude Desktop can also reach the
  HTTP endpoint through a stdio bridge such as `npx mcp-remote http://127.0.0.1:8082/mcp`.
- `make_base_app` always serves `GET /healthz` (`{"status": "ok", ...}`, for Docker / k8s probes).
- `logs.setup_logging(verbose=, log_format="text"|"json")` replaces `logging.basicConfig`; `json` writes one
  object per line (`ts`, `level`, `logger`, `message`, `extra` fields, `exc`). `add_common_args(...,
  log_format=True)` adds `--log-format`, and `run_web` then routes uvicorn's logs through the same handler. A
  product that keeps `log_format: json` in its config passes that value to `setup_logging` and sets
  `args.log_format` to it before `run_web`.

### Migration notes

- `state` is an instance attribute of `BaseEngine` (the result of `_build`); a subclass must not define a
  `state()` method.
- `BaseEngine.event_history(limit)` is the common event log; it does not clash with a product's own history
  (e.g. a per-point `history(device_id, key)` API).
- The routes of a FastAPI `APIRouter` passed in `product_routers` are flattened into `app.routes` (no
  `include_router` wrapper); they remain `APIRoute`s, dependency injection works as usual.

### Tests and packaging

- The pytest plugin (asyncio timeout + hang dump) is activated automatically through the `pytest11`
  entry point.
- The PyInstaller hook (`pyinstaller40` entry point) collects the common static files and the uvicorn
  hidden imports, so product spec files list only their own files.

## Series port table

Default web UI ports, so that sibling products can run side by side. New products register here first.

| Product | Default HTTP port |
|---|---|
| SME BACnetSim | 8080 |
| SME ModbusSim | 8081 |
| SME OCPPSim | 8082 |
| SME SerialHub | TBD |

## Series accent table

| Product | `--accent` | `--accent-ink` | `--accent-weak` | Dark theme |
|---|---|---|---|---|
| SME BACnetSim | `#087def` (brand blue, shell default) | `#fff` | `#e7f2fe` | shell default (`#3d9bff` / `#fff` / `#11304f`) |
| SME ModbusSim | `#0f766e` (teal) | `#ffffff` | `#ccfbf1` | `#2dd4bf` / `#042f2e` / `#134e4a` |
| SME OCPPSim | `#b45309` (amber) | `#ffffff` | `#fef3c7` | `#fbbf24` / `#451a03` / `#78350f` |
| SME SerialHub | TBD | TBD | TBD | TBD |

## What belongs in common

Product work never waits for a common release.

- **Product first, promote later.** A new helper starts in the product's own module. It moves into common
  only when a second product needs it; the first product then switches to the common version.
- **Hooks, not protocols.** Common may gain an extension point (a hook, an optional parameter) that a
  product needs. Protocol-specific behavior (BACnet, Modbus, OCPP, ...) stays in the product.
- **Registry changes are docs only.** Adding a row to the port or accent table needs a pull request but no
  release.
- **Core shape changes are a design discussion.** If a product needs a different shape of
  `make_base_app` or `BaseEngine` rather than a new hook, open an issue first instead of patching it in.

## Versioning

- Semantic Versioning, first release `1.0.0`. Within 1.x only backward-compatible additions (new keys,
  new optional parameters, new modules) and fixes; a breaking change would be 2.0 and is avoided.
- Products depend on `sme-sim-common>=1.0,<2`.
- The single version source is `sme_sim_common.__version__`; `Shell.version` carries the same value.

## Templates

See [`templates/CHECKLIST.md`](templates/CHECKLIST.md) for adopting the templates in a new or migrated
product (placeholders, port / accent registration, i18n rules, PyInstaller, PyPI trusted publishing).

## Releasing sme-sim-common

1. Update `__version__` and the `CHANGELOG.md` section `## [x.y.z] - YYYY-MM-DD`.
2. Push the tag `vx.y.z`. `.github/workflows/release.yml` builds the sdist and wheel, checks them with
   `twine`, publishes to PyPI with trusted publishing (environment `pypi`) and creates the GitHub Release
   with the CHANGELOG section as notes. The workflow file name `release.yml` and the environment name
   `pypi` are registered on PyPI; do not rename them.

## License

MIT — see [LICENSE](LICENSE).
