updated to multiple cared on nfc

This commit is contained in:
2026-06-13 10:30:53 +03:00
parent 916e35b22b
commit 61ae9b2431
3 changed files with 136 additions and 48 deletions
@@ -189,27 +189,34 @@ class OlimexESP32C6EVBPn532Driver(BoardDriver):
def set_nfc_config(
self,
board: "Board",
auth_uid: str = "",
auth_uids: list[str] | None = None,
auth_uid: str = "", # legacy single-UID shim — ignored if auth_uids given
relay_num: int = 1,
pulse_ms: int = 3000,
pulse_ms: int = 0,
) -> bool:
"""Push NFC access-control config to the board.
auth_uid: authorized card UID (e.g. "04:AB:CD:EF"); empty = no card authorized.
auth_uids: list of authorized card UIDs (up to 10); empty list = clear all.
relay_num: which relay to open on a matching card (1-4).
pulse_ms: absence timeout — relay closes this many ms after card is removed (100-60000).
pulse_ms: absence timeout ms; 0 = use board default (5 s).
"""
if auth_uids is None:
# backwards-compat: single uid string → list
auth_uids = [auth_uid.upper().strip()] if auth_uid.strip() else []
uids_clean = [u.upper().strip() for u in auth_uids if u.strip()][:10]
uids_param = urllib.parse.quote(",".join(uids_clean))
url = (
f"{board.base_url}/nfc/config"
f"?auth_uid={urllib.parse.quote(auth_uid.upper())}"
f"?auth_uids={uids_param}"
f"&relay={relay_num}"
f"&pulse_ms={pulse_ms}"
)
result = _post(url, _auth(board, "POST", url))
if result:
logger.info(
"NFC config pushed to board '%s': uid='%s' relay=%d pulse=%dms",
board.name, auth_uid, relay_num, pulse_ms,
"NFC config pushed to board '%s': uids=%s relay=%d pulse=%dms",
board.name, uids_clean, relay_num, pulse_ms,
)
else:
logger.warning("NFC config push failed for board '%s'", board.name)
+67 -7
View File
@@ -318,6 +318,7 @@ def nfc_status_json(board_id: int):
@boards_bp.route("/<int:board_id>/nfc/config", methods=["POST"])
@login_required
def nfc_config_save(board_id: int):
"""Save relay/timeout settings and optionally add a new authorized UID."""
if not current_user.is_admin():
abort(403)
board = db.get_or_404(Board, board_id)
@@ -328,9 +329,9 @@ def nfc_config_save(board_id: int):
flash("NFC driver not available.", "danger")
return redirect(url_for("boards.nfc_management", board_id=board_id))
auth_uid = request.form.get("auth_uid", "").strip().upper()
relay_num = int(request.form.get("relay_num", 1))
pulse_ms = int(request.form.get("pulse_ms", 0))
new_uid = request.form.get("new_uid", "").strip().upper()
if relay_num < 1 or relay_num > board.num_relays:
flash(f"Relay number must be 1{board.num_relays}.", "danger")
@@ -339,10 +340,21 @@ def nfc_config_save(board_id: int):
flash("Release delay must be between 0 and 60 000 ms.", "danger")
return redirect(url_for("boards.nfc_management", board_id=board_id))
ok = driver.set_nfc_config(board, auth_uid=auth_uid, relay_num=relay_num, pulse_ms=pulse_ms)
# Fetch current list from board so we can append
current_cfg = driver.get_nfc_config(board) or {}
current_uids: list[str] = current_cfg.get("auth_uids") or (
[current_cfg["auth_uid"]] if current_cfg.get("auth_uid") else []
)
if new_uid:
if new_uid not in current_uids:
if len(current_uids) >= 10:
flash("Maximum 10 authorized cards reached. Remove one before adding.", "danger")
return redirect(url_for("boards.nfc_management", board_id=board_id))
current_uids.append(new_uid)
ok = driver.set_nfc_config(board, auth_uids=current_uids, relay_num=relay_num, pulse_ms=pulse_ms)
if ok:
uid_display = auth_uid if auth_uid else "(any card)"
flash(f"NFC config saved — authorized UID: {uid_display}, relay: {relay_num}, timeout: {pulse_ms} ms", "success")
flash(f"NFC config saved — {len(current_uids)} card(s) authorized, relay: {relay_num}, timeout: {pulse_ms} ms", "success")
else:
flash("Failed to push NFC config — board unreachable.", "danger")
return redirect(url_for("boards.nfc_management", board_id=board_id))
@@ -351,7 +363,7 @@ def nfc_config_save(board_id: int):
@boards_bp.route("/<int:board_id>/nfc/enroll", methods=["POST"])
@login_required
def nfc_enroll(board_id: int):
"""Read the last-seen UID from the board and immediately authorize it."""
"""Read the last-seen UID from the board and add it to the authorized list."""
if not current_user.is_admin():
abort(403)
board = db.get_or_404(Board, board_id)
@@ -375,14 +387,62 @@ def nfc_enroll(board_id: int):
relay_num = int(request.form.get("relay_num", status.get("relay_num", 1)))
pulse_ms = int(request.form.get("pulse_ms", status.get("pulse_ms", 0)))
ok = driver.set_nfc_config(board, auth_uid=uid, relay_num=relay_num, pulse_ms=pulse_ms)
# Fetch current list and append
current_cfg = driver.get_nfc_config(board) or {}
current_uids: list[str] = current_cfg.get("auth_uids") or (
[current_cfg["auth_uid"]] if current_cfg.get("auth_uid") else []
)
if uid in current_uids:
flash(f"Card already enrolled — UID: {uid}", "info")
return redirect(url_for("boards.nfc_management", board_id=board_id))
if len(current_uids) >= 10:
flash("Maximum 10 authorized cards reached. Remove one before enrolling.", "danger")
return redirect(url_for("boards.nfc_management", board_id=board_id))
current_uids.append(uid)
ok = driver.set_nfc_config(board, auth_uids=current_uids, relay_num=relay_num, pulse_ms=pulse_ms)
if ok:
flash(f"Card enrolled — UID: {uid}, relay: {relay_num}, timeout: {pulse_ms} ms", "success")
flash(f"Card enrolled — UID: {uid} ({len(current_uids)} card(s) total), relay: {relay_num}, timeout: {pulse_ms} ms", "success")
else:
flash("Card read OK but failed to push config to board.", "danger")
return redirect(url_for("boards.nfc_management", board_id=board_id))
@boards_bp.route("/<int:board_id>/nfc/remove_card", methods=["POST"])
@login_required
def nfc_remove_card(board_id: int):
"""Remove one UID from the authorized list."""
if not current_user.is_admin():
abort(403)
board = db.get_or_404(Board, board_id)
if board.board_type not in _NFC_DRIVER_IDS:
abort(404)
driver = registry.get(board.board_type)
if not driver:
flash("NFC driver not available.", "danger")
return redirect(url_for("boards.nfc_management", board_id=board_id))
uid_to_remove = request.form.get("uid", "").strip().upper()
if not uid_to_remove:
flash("No UID specified.", "danger")
return redirect(url_for("boards.nfc_management", board_id=board_id))
current_cfg = driver.get_nfc_config(board) or {}
current_uids: list[str] = current_cfg.get("auth_uids") or (
[current_cfg["auth_uid"]] if current_cfg.get("auth_uid") else []
)
relay_num = int(current_cfg.get("relay_num", 1))
pulse_ms = int(current_cfg.get("pulse_ms", 0))
new_uids = [u for u in current_uids if u != uid_to_remove]
ok = driver.set_nfc_config(board, auth_uids=new_uids, relay_num=relay_num, pulse_ms=pulse_ms)
if ok:
flash(f"Card removed — UID: {uid_to_remove} ({len(new_uids)} card(s) remaining)", "success")
else:
flash("Failed to push updated config — board unreachable.", "danger")
return redirect(url_for("boards.nfc_management", board_id=board_id))
@boards_bp.route("/<int:board_id>/nfc/enable", methods=["POST"])
@login_required
def nfc_enable(board_id: int):
+50 -29
View File
@@ -75,15 +75,31 @@
</div>
</div>
<!-- Current authorized UID -->
<!-- Authorized cards list -->
<div class="mb-3">
<div class="small text-secondary mb-1">Authorized card UID</div>
{% if nfc.get('auth_uid') %}
<code id="auth-uid-display" class="fs-6 fw-bold text-success">{{ nfc.get('auth_uid') }}</code>
<div class="small text-secondary mb-1">Authorized cards
<span class="badge text-bg-secondary ms-1" id="card-count-badge">{{ (nfc.get('auth_uids') or ([nfc['auth_uid']] if nfc.get('auth_uid') else [])) | length }}/10</span>
</div>
<div id="auth-uid-list">
{% set uids = nfc.get('auth_uids') or ([nfc['auth_uid']] if nfc.get('auth_uid') else []) %}
{% if uids %}
{% for uid in uids %}
<span class="badge text-bg-success font-monospace me-1 mb-1 d-inline-flex align-items-center gap-1">
{{ uid }}
<form method="POST" action="{{ url_for('boards.nfc_remove_card', board_id=board.id) }}" class="d-inline m-0 p-0">
<input type="hidden" name="uid" value="{{ uid }}">
<button type="submit" class="btn btn-sm p-0 border-0 text-white lh-1"
style="background:none;font-size:14px;line-height:1"
onclick="return confirm('Remove card {{ uid }}?')"
title="Remove">&times;</button>
</form>
</span>
{% endfor %}
{% else %}
<span id="auth-uid-display" class="text-danger small"><i class="bi bi-exclamation-triangle me-1"></i>None — no card enrolled yet</span>
<span class="text-danger small"><i class="bi bi-exclamation-triangle me-1"></i>None — no card enrolled yet</span>
{% endif %}
</div>
</div>
<!-- Current relay & timeout -->
<dl class="row mb-0 small">
@@ -187,19 +203,26 @@
<!-- ── Manual Config ────────────────────────────────────────────────── -->
<div class="card border-0 rounded-4">
<div class="card-header bg-transparent fw-semibold pt-3">
<i class="bi bi-sliders me-1 text-warning"></i> Manual Settings
<i class="bi bi-sliders me-1 text-warning"></i> Settings &amp; Add Card
</div>
<div class="card-body">
<form method="POST" action="{{ url_for('boards.nfc_config_save', board_id=board.id) }}">
<div class="row g-3">
<div class="col-12">
<label class="form-label small text-secondary mb-1">Authorized card UID <span class="text-muted">(leave empty to clear authorization)</span></label>
<input type="text" name="auth_uid" id="manual-uid"
<label class="form-label small text-secondary mb-1">
Add authorized card UID
<span class="text-muted">(leave empty to only update relay/timeout)</span>
</label>
<div class="input-group">
<input type="text" name="new_uid" id="manual-uid"
class="form-control font-monospace text-uppercase"
placeholder="e.g. 04:AB:CD:EF"
value="{{ nfc.get('auth_uid', '') }}"
placeholder="e.g. 04:AB:CD:EF — max 10 cards"
maxlength="31"
oninput="this.value=this.value.toUpperCase()">
<button type="submit" class="btn btn-success">
<i class="bi bi-plus-circle me-1"></i>Add &amp; Save
</button>
</div>
</div>
<div class="col-sm-6">
<label class="form-label small text-secondary mb-1">Trigger relay</label>
@@ -210,21 +233,15 @@
</select>
</div>
<div class="col-sm-6">
<label class="form-label small text-secondary mb-1">Release delay (ms)</label>
<label class="form-label small text-secondary mb-1">Absent timeout (ms)</label>
<input type="number" name="pulse_ms" class="form-control"
min="0" max="60000" value="{{ nfc.get('pulse_ms', 0) }}">
<div class="form-text">Relay turns off this many ms after the card is removed (0 = immediately).</div>
<div class="form-text">Relay turns off after card absent this long (0 = use board default 5 s).</div>
</div>
<div class="col-12 d-flex gap-2">
<div class="col-12">
<button type="submit" class="btn btn-primary">
<i class="bi bi-floppy me-1"></i>Save config
<i class="bi bi-floppy me-1"></i>Save relay &amp; timeout only
</button>
{% if nfc.get('auth_uid') %}
<button type="submit" class="btn btn-outline-danger"
onclick="document.getElementById('manual-uid').value=''">
<i class="bi bi-x-circle me-1"></i>Clear authorization
</button>
{% endif %}
</div>
</div>
</form>
@@ -272,15 +289,18 @@ function loadStatus() {
if (useBtn) useBtn.disabled = !d.last_uid;
const enrollBtn = document.getElementById('enroll-btn');
if (enrollBtn) enrollBtn.disabled = !d.last_uid;
// authorized UID display
const authEl = document.getElementById('auth-uid-display');
if (authEl) {
if (d.auth_uid) {
authEl.className = 'fs-6 fw-bold text-success';
authEl.textContent = d.auth_uid;
// authorized cards list
const authList = document.getElementById('auth-uid-list');
if (authList) {
const uids = d.auth_uids || (d.auth_uid ? [d.auth_uid] : []);
const countBadge = document.getElementById('card-count-badge');
if (countBadge) countBadge.textContent = uids.length + '/10';
if (uids.length === 0) {
authList.innerHTML = '<span class="text-danger small"><i class="bi bi-exclamation-triangle me-1"></i>None — no card enrolled yet</span>';
} else {
authEl.className = 'text-danger small';
authEl.innerHTML = '<i class="bi bi-exclamation-triangle me-1"></i>None — no card enrolled yet';
authList.innerHTML = uids.map(uid =>
`<span class="badge text-bg-success font-monospace me-1 mb-1">${uid}</span>`
).join('');
}
}
// relay & timeout summary
@@ -307,8 +327,9 @@ function useLastUID() {
if (uid && uid !== '—') {
const manualUid = document.getElementById('manual-uid');
if (manualUid) {
manualUid.value = uid;
manualUid.value = uid.toUpperCase();
manualUid.scrollIntoView({ behavior: 'smooth', block: 'center' });
manualUid.focus();
}
}
}