Files
busbar-designer/app.py
T
wenil dfef1453aa holder: fit-check — translucent max-box + manual enclosure overlay
The hex_cell.scad echoes its computed dimensions (pack_height_holder,
total_*_holder, box_total_*) to stderr. Capture those and surface them
in the viewer so the user can sanity-check whether the assembled
battery will fit in a target case.

Backend:
- holder.py: render_stl() now returns (stl_bytes, dims) where dims is
  a {name: float} dict parsed from openscad ECHO lines.
- app.py: /api/holder/render emits the dims dict as an
  X-Holder-Dimensions response header (JSON) with the matching
  Access-Control-Expose-Headers entry so fetch() can read it under
  any proxy / future CORS setup.

Viewer (holder-viewer.js):
- New setGhostBox(name, {w,d,h}, {visible,color}) and clearGhostBox(name)
  helpers. Each ghost is a Group of a translucent BoxGeometry mesh +
  matching EdgesGeometry wireframe, positioned to match how the STL
  mesh is placed (centred XY, bottom on Z=0).

UI (holder.html / holder.css):
- New "Fit check" panel under Status with two sections:
    • Show max bounding box (auto, from ECHO — defaults to box_total_*
      dims, falls back to total_*_holder + pack_height_holder).
    • Show enclosure (manual W × D × H inputs in mm).
- Verdict line under the enclosure inputs: "✓ fits" green or
  "✗ too small — battery won't fit" red.

Controller (holder-app.js):
- Reads X-Holder-Dimensions after each render, updates the max-box
  ghost in blue, prints the dimensions label.
- Watches enclosure inputs + toggles, drives the enclosure ghost
  (green if it fits, red if smaller than the max box on any axis).
- Fit comparison is orientation-independent in the XY plane (sorted
  W,D pair) but strict on Z (height).
2026-05-25 12:19:31 +03:00

253 lines
7.3 KiB
Python

"""Flask entrypoint for Busbar Designer.
Serves the static frontend, the /api/export/<fmt> CAD endpoints (build123d →
STEP/DXF/SVG), and the /api/projects, /api/presets, /api/snapshots persistence
endpoints (SQLite via storage.py).
Run:
python app.py
"""
from __future__ import annotations
import json
import os
import sys
import traceback
from flask import Flask, Response, jsonify, request, send_from_directory
from busbar_export import WRITERS
import storage
import holder
APP_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_DIR = os.path.join(APP_DIR, "static")
app = Flask(__name__, static_folder=STATIC_DIR, static_url_path="")
storage.init_db()
# ---------------------------------------------------------------------------
# Static + health
# ---------------------------------------------------------------------------
@app.get("/")
def index():
return send_from_directory(STATIC_DIR, "index.html")
@app.get("/holder")
def holder_page():
return send_from_directory(STATIC_DIR, "holder.html")
@app.get("/api/health")
def health():
return jsonify({"status": "ok", "openscad": holder.openscad_available()})
# ---------------------------------------------------------------------------
# Hex holder designer (OpenSCAD-backed)
# ---------------------------------------------------------------------------
@app.get("/api/holder/params")
def holder_params():
"""Schema for the parameter form + their defaults."""
return jsonify({
"params": holder.schema_dict(),
"defaults": holder.default_params(),
"max_cells": holder.MAX_CELLS,
})
@app.post("/api/holder/render")
def holder_render():
"""Render STL for the supplied parameter overrides."""
body = request.get_json(silent=True) or {}
try:
data, dims = holder.render_stl(body.get("params", {}))
except ValueError as e:
return jsonify({"error": str(e)}), 400
except (FileNotFoundError, RuntimeError) as e:
return jsonify({"error": str(e)}), 500
return Response(
data,
mimetype="model/stl",
headers={
"Content-Disposition": 'attachment; filename="hex_holder.stl"',
# ECHO values from hex_cell.scad (pack/box dimensions). Used by
# the viewer to draw a max-bounding-box ghost for fit-check.
"X-Holder-Dimensions": json.dumps(dims),
# Make the custom header visible to fetch() in any CORS/proxy
# setup (Access-Control-Expose-Headers; harmless on same-origin).
"Access-Control-Expose-Headers": "X-Holder-Dimensions",
},
)
@app.post("/api/holder/cells")
def holder_cells():
"""Cell-center coordinates for the supplied parameters (no OpenSCAD needed)."""
body = request.get_json(silent=True) or {}
try:
cells = holder.compute_cells(body.get("params", {}))
except ValueError as e:
return jsonify({"error": str(e)}), 400
return jsonify({"cells": cells, "count": len(cells)})
# ---------------------------------------------------------------------------
# CAD export (unchanged contract)
# ---------------------------------------------------------------------------
@app.post("/api/export/<fmt>")
def export(fmt: str):
fmt = fmt.lower()
if fmt not in WRITERS:
return jsonify({"error": f"unsupported format: {fmt}"}), 400
payload = request.get_json(silent=True) or {}
writer, mimetype, ext = WRITERS[fmt]
try:
data = writer(payload)
except ValueError as e:
return jsonify({"error": str(e)}), 400
except Exception as e:
traceback.print_exc()
return jsonify({"error": f"{type(e).__name__}: {e}"}), 500
filename = f"busbars.{ext}"
return Response(
data,
mimetype=mimetype,
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
)
# ---------------------------------------------------------------------------
# Projects
# ---------------------------------------------------------------------------
@app.get("/api/projects")
def projects_index():
return jsonify(storage.list_projects())
@app.post("/api/projects")
def projects_create():
body = request.get_json(silent=True) or {}
name = (body.get("name") or "Untitled").strip() or "Untitled"
data = body.get("data") or {}
pid = storage.create_project(name, data)
return jsonify({"id": pid, "name": name})
@app.get("/api/projects/<int:pid>")
def projects_show(pid: int):
p = storage.get_project(pid)
if p is None:
return jsonify({"error": "not found"}), 404
return jsonify(p)
@app.put("/api/projects/<int:pid>")
def projects_update(pid: int):
body = request.get_json(silent=True) or {}
ok = storage.update_project(
pid,
name=body.get("name"),
data=body.get("data"),
snapshot=bool(body.get("snapshot", False)),
note=body.get("note"),
)
if not ok:
return jsonify({"error": "not found"}), 404
return jsonify({"ok": True})
@app.delete("/api/projects/<int:pid>")
def projects_delete(pid: int):
storage.delete_project(pid)
return jsonify({"ok": True})
# ---------------------------------------------------------------------------
# Snapshots
# ---------------------------------------------------------------------------
@app.get("/api/projects/<int:pid>/snapshots")
def snapshots_index(pid: int):
return jsonify(storage.list_snapshots(pid))
@app.get("/api/snapshots/<int:sid>")
def snapshot_show(sid: int):
snap = storage.get_snapshot(sid)
if snap is None:
return jsonify({"error": "not found"}), 404
return jsonify(snap)
@app.post("/api/snapshots/<int:sid>/restore")
def snapshot_restore(sid: int):
if not storage.restore_snapshot(sid):
return jsonify({"error": "not found"}), 404
return jsonify({"ok": True})
# ---------------------------------------------------------------------------
# Presets
# ---------------------------------------------------------------------------
@app.get("/api/presets")
def presets_index():
return jsonify(storage.list_presets())
@app.post("/api/presets")
def presets_create():
body = request.get_json(silent=True) or {}
name = (body.get("name") or "").strip()
if not name:
return jsonify({"error": "name required"}), 400
pid = storage.create_preset(name, body.get("params") or {})
if pid is None:
return jsonify({"error": "name already in use"}), 409
return jsonify({"id": pid, "name": name})
@app.put("/api/presets/<int:pid>")
def presets_update(pid: int):
body = request.get_json(silent=True) or {}
ok = storage.update_preset(pid, name=body.get("name"), params=body.get("params"))
if not ok:
return jsonify({"error": "not found or name conflict"}), 404
return jsonify({"ok": True})
@app.delete("/api/presets/<int:pid>")
def presets_delete(pid: int):
storage.delete_preset(pid)
return jsonify({"ok": True})
# ---------------------------------------------------------------------------
# Boot
# ---------------------------------------------------------------------------
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
host = os.environ.get("HOST", "127.0.0.1")
debug = os.environ.get("FLASK_DEBUG", "1") == "1"
print(f" * Busbar Designer running on http://{host}:{port}", file=sys.stderr)
app.run(host=host, port=port, debug=debug)