Bladeren bron

feat(mapping): 新增端口映射管理页并修复单端口写卡落盘污染

- 修复单端口写卡把 24 路(含硬件读回卡号与大量 null)全量写入
  dtu_config.port_mappings 的问题:单端口模式只落目标一条
- 清除端口映射改为删除记录(不再写 null),硬件该口照发 0xFF
- 启动时一次性清理历史 null/空端口映射
- 新增 API:GET /api/panel/mappings(列表,含未注册残留组)、
  POST /api/panel/mapping(单口增改删,在线时同步硬件)、
  POST /api/panel/clear_mappings(清空面板映射+硬件)
- 前端新增「端口映射」页 /port-mapping:按面板查看、新增、编辑、
  删除、清空全部;线架管理页操作列加「清空映射」
- 补充 6 个单元测试,全部 152 passed
wenhongquan 2 weken geleden
bovenliggende
commit
1df50f7bf3

+ 310 - 28
backend/app.py

@@ -373,6 +373,48 @@ def _dtu_mapping_overrides(panel_id):
     return overrides
 
 
+def _store_port_mapping(panel_id, port_id, expected_uid):
+    """落盘单条绑定②(端口↔卡号)。
+
+    expected_uid 为 None/空时**删除该端口记录**(而非写入 null),
+    避免 dtu_config 累积大量无意义的 null;硬件那口由调用方下发 0xFF 清空。
+    注意:这不改变 `_dtu_mapping_overrides` 的语义——只有文件里确实存在 null 键时
+    才被当作「显式清除」覆盖硬件基底,删除键则视为「平台未配置」,交由硬件基底保留。
+    """
+    pm = dtu_config.setdefault('port_mappings', {}).setdefault(panel_id, {})
+    key = str(port_id)
+    if expected_uid:
+        pm[key] = expected_uid
+    else:
+        pm.pop(key, None)
+
+
+def _clear_panel_port_mappings(panel_id):
+    """删除某面板全部端口映射(绑定②),返回被删除的条数。"""
+    pm = dtu_config.get('port_mappings', {})
+    entries = pm.pop(panel_id, None)
+    return len(entries) if isinstance(entries, dict) else 0
+
+
+def _prune_null_port_mappings():
+    """启动时一次性清理历史脏数据:删除 port_mappings 里所有 null/空值端口记录。
+
+    旧版单端口写卡接口会把 24 路(含大量 null)整段落盘,导致配置膨胀且语义混乱。
+    仅清理空值条目;非空卡号保留。返回清理掉的条目总数。
+    """
+    removed = 0
+    for panel_id, mappings in list(dtu_config.get('port_mappings', {}).items()):
+        if not isinstance(mappings, dict):
+            continue
+        for key in list(mappings.keys()):
+            if _to_internal_uid_lenient(mappings.get(key)) is None:
+                mappings.pop(key, None)
+                removed += 1
+        if not mappings:
+            dtu_config['port_mappings'].pop(panel_id, None)
+    return removed
+
+
 def get_sorted_panels():
     """按 position 排序返回 panel 列表。"""
     return sorted(panel_config.items(), key=lambda x: x[1].get('position', 0))
@@ -2212,8 +2254,9 @@ def dtu_handle_control(topic, payload):
                 port_state[panel_target][port_id] = {'last_uid': None, 'expected_uid': None, 'alarm_count': 0}
 
             port_state[panel_target][port_id]['expected_uid'] = expected_uid
-            # 持久化期望映射(内部 12 位),保证离线恢复/重启后仍能判定非法连接
-            dtu_config.setdefault('port_mappings', {}).setdefault(panel_target, {})[str(port_id)] = expected_uid
+            # 持久化期望映射(内部 12 位),保证离线恢复/重启后仍能判定非法连接;
+            # expected_uid 为空(清除)时删除记录,不写 null
+            _store_port_mapping(panel_target, port_id, expected_uid)
             save_dtu_config()
 
             # V4: 下发卡号到配线架硬件(24路同时发送;保留其他端口真实硬件值,避免误擦)
@@ -2274,8 +2317,8 @@ def dtu_handle_control(topic, payload):
                     if port_id not in port_state[panel_id]:
                         port_state[panel_id][port_id] = {'last_uid': None, 'expected_uid': None, 'alarm_count': 0}
                     port_state[panel_id][port_id]['expected_uid'] = expected_uid
-                    # 持久化期望映射(内部 12 位)
-                    dtu_config.setdefault('port_mappings', {}).setdefault(panel_id, {})[str(port_id)] = expected_uid
+                    # 持久化期望映射(内部 12 位);清除(空)时删除记录,不写 null
+                    _store_port_mapping(panel_id, port_id, expected_uid)
                 save_dtu_config()
             except Exception as e:
                 response_payload['payload']['success'] = False
@@ -3581,6 +3624,9 @@ def modbus_set_card_mapping():
             return jsonify({'success': False, 'message': '串口未连接'}), 400
 
         card_mappings = data.get('card_mappings')
+        single_port_mode = card_mappings is None
+        target_port_id = None
+        single_target_uid = None
         if card_mappings is None:
             # 单端口模式:构建 24 路数据,避免擦掉其他端口
             # 策略: 先读硬件当前值做基底 → 再用 dtu_config 期望值覆盖 → 最后覆盖目标端口
@@ -3599,6 +3645,11 @@ def modbus_set_card_mapping():
             if port_id is None:
                 return jsonify({'success': False, 'message': '缺少 port_id 或 card_mappings'}), 400
 
+            try:
+                target_port_id = int(port_id)
+            except (ValueError, TypeError):
+                return jsonify({'success': False, 'message': f'port_id 非法: {port_id}'}), 400
+
             # 第一步:读硬件当前 24 路值,作为默认基底(防止擦掉其他端口硬件里真实存在的卡号)
             card_mappings = _hardware_card_base(device_address)
 
@@ -3615,12 +3666,8 @@ def modbus_set_card_mapping():
                 uid = str(card_uid).strip().upper().replace(':', '').replace(' ', '')
                 if len(uid) != 12 or not all(c in _JUMPER_HEX for c in uid):
                     return jsonify({'success': False, 'message': f'卡号必须是12位十六进制: {card_uid}'}), 400
-            else:
-                uid = None
-            try:
-                card_mappings[int(port_id)] = uid
-            except (ValueError, TypeError):
-                return jsonify({'success': False, 'message': f'port_id 非法: {port_id}'}), 400
+                single_target_uid = uid
+            card_mappings[target_port_id] = single_target_uid
 
         # 转换 key 为 int
         normalized = {}
@@ -3655,27 +3702,37 @@ def modbus_set_card_mapping():
         warnings = []
         cards_written = result.get('cards_written', {})
         if panel_target:
-            port_state.setdefault(panel_target, {})
-            for port_id, uid in cards_written.items():
-                port_id = int(port_id)
-                port_state[panel_target].setdefault(port_id, {
+            if single_port_mode:
+                # 单端口模式:硬件帧虽带全 24 口,但平台只记录目标这一条,
+                # 不再把硬件读回的卡号/未用端口灌进配置(修复端口映射污染)。
+                expected_uid = single_target_uid
+                port_state.setdefault(panel_target, {}).setdefault(target_port_id, {
                     'last_uid': None, 'expected_uid': None, 'alarm_count': 0
                 })
-                # 规范化为 12 位大写 hex 或 None
-                if uid:
-                    clean_uid = str(uid).strip().upper().replace(':', '').replace(' ', '')
-                    if len(clean_uid) == 12 and all(c in _JUMPER_HEX for c in clean_uid):
-                        expected_uid = clean_uid
-                    else:
-                        expected_uid = None
-                else:
+                port_state[panel_target][target_port_id]['expected_uid'] = expected_uid
+                _store_port_mapping(panel_target, target_port_id, expected_uid)
+                save_dtu_config()
+                logger.info(
+                    f"卡号设置页 面板{panel_target} 端口{target_port_id} 已同步本地期望: "
+                    f"{expected_uid or '已清除'}"
+                )
+            else:
+                # 完整模式:按提交的 24 路全量落盘;空值用删除语义(不写 null)
+                port_state.setdefault(panel_target, {})
+                for port_id, uid in cards_written.items():
+                    port_id = int(port_id)
                     expected_uid = None
-                port_state[panel_target][port_id]['expected_uid'] = expected_uid
-                # 持久化到 dtu_config.json(内部 12 位)
-                dtu_config.setdefault('port_mappings', {}).setdefault(panel_target, {})
-                dtu_config['port_mappings'][panel_target][str(port_id)] = expected_uid
-            save_dtu_config()
-            logger.info(f"卡号设置页 面板{panel_target} 已同步本地期望值: {len(cards_written)} 路")
+                    if uid:
+                        clean_uid = str(uid).strip().upper().replace(':', '').replace(' ', '')
+                        if len(clean_uid) == 12 and all(c in _JUMPER_HEX for c in clean_uid):
+                            expected_uid = clean_uid
+                    port_state[panel_target].setdefault(port_id, {
+                        'last_uid': None, 'expected_uid': None, 'alarm_count': 0
+                    })
+                    port_state[panel_target][port_id]['expected_uid'] = expected_uid
+                    _store_port_mapping(panel_target, port_id, expected_uid)
+                save_dtu_config()
+                logger.info(f"卡号设置页 面板{panel_target} 已全量同步本地期望: {len(cards_written)} 路")
         else:
             warnings.append(f"未找到 device_address={device_address} 对应的面板,本地期望值未更新(仅硬件已生效)")
 
@@ -4137,6 +4194,222 @@ def panel_unbind():
         return jsonify({'success': False, 'message': str(e)}), 500
 
 
+@app.route('/api/panel/clear_mappings', methods=['POST'])
+def panel_clear_mappings():
+    """清空某面板的全部端口映射(绑定②:端口↔卡号)。
+
+    请求: {"panel_id": "PANEL_dtu_001_1"} 或 {"address": 1}
+    - 删除 dtu_config.port_mappings[panel] 全部记录并落盘
+    - 若面板在线(panel_config 中有地址),同时下发 0x10 把硬件 24 口全部清成 0xFF
+    - 不影响绑定①(devices.json 的地址↔UID)
+    """
+    try:
+        data = request.json or {}
+        addr = data.get('address')
+        panel_id = _resolve_panel_id(data.get('panel_id'))
+        if addr is None and panel_id:
+            cfg = panel_config.get(panel_id)
+            if cfg:
+                addr = cfg.get('address')
+            elif isinstance(panel_id, str) and panel_id.rsplit('_', 1)[-1].isdigit():
+                addr = int(panel_id.rsplit('_', 1)[-1])
+        if not panel_id:
+            if isinstance(addr, int):
+                panel_id = _panel_id_for_address(addr)
+            else:
+                return jsonify({'success': False, 'message': '缺少有效的 address 或 panel_id'}), 400
+
+        removed = _clear_panel_port_mappings(panel_id)
+
+        # 清掉运行态期望与"本会话已同步"标记,下次上线会重新全量同步
+        port_state.pop(panel_id, None)
+        panel_mappings_synced.discard(panel_id)
+        save_dtu_config()
+
+        hw = {'cleared': False}
+        if isinstance(addr, int):
+            try:
+                if not (isinstance(serial_client.get_status(), dict)
+                        and serial_client.get_status().get('connected', False)):
+                    hw = {'cleared': False, 'message': '串口未连接,仅清除了平台记录'}
+                else:
+                    empty = {p: None for p in range(1, 25)}
+                    res = modbus_client.set_card_mapping(addr, empty, timeout=2.0)
+                    if 'error' in res:
+                        hw = {'cleared': False, 'message': f"硬件清空失败: {res['error']}"}
+                    else:
+                        hw = {'cleared': True}
+            except Exception as e:
+                hw = {'cleared': False, 'message': f"硬件清空异常: {e}"}
+
+        logger.info(f"已清空面板 {panel_id} 端口映射 {removed} 条,硬件清空={hw.get('cleared')}")
+        return jsonify({
+            'success': True,
+            'panel_id': panel_id,
+            'address': addr,
+            'removed': removed,
+            'hardware': hw
+        })
+    except Exception as e:
+        logger.error(f"清空面板端口映射失败: {e}")
+        return jsonify({'success': False, 'message': str(e)}), 500
+
+
+@app.route('/api/panel/mappings', methods=['GET'])
+def panel_mappings_list():
+    """返回全部面板的端口映射(绑定②),供映射管理页展示/增改删。
+
+    每面板: {panel_id, address, uid, status, mapping_count,
+             mappings: [{port, uid(12位hex|null)}]}
+    同时包含 dtu_config 里有映射、但当前未注册(无绑定①)的面板组,便于清理。
+    """
+    try:
+        devices = address_config.get_stored_devices()
+        now = time.time()
+        groups = {}
+
+        # 已注册面板
+        for uid, addr in devices.items():
+            pid = _panel_id_for_address(addr)
+            cfg = panel_config.get(pid) or {}
+            ka_miss = panel_keepalive_miss.get(pid, 0)
+            last_seen = device_last_seen.get(pid) or device_last_seen.get(uid)
+            recent = bool(last_seen) and (now - last_seen) < 60
+            if cfg.get('status') == 'offline' or ka_miss >= PANEL_KEEPALIVE_MISS_LIMIT:
+                status = 'offline'
+            elif panel_conflict.get(pid):
+                status = 'conflict'
+            elif ka_miss > 0:
+                status = 'missing'
+            else:
+                status = 'online' if recent else 'offline'
+            groups[pid] = {
+                'panel_id': pid, 'address': addr, 'uid': uid,
+                'registered': True, 'status': status,
+            }
+
+        # 有残留映射但未注册的面板组(地址从 panel_id 末段解析)
+        for pid in (dtu_config.get('port_mappings') or {}):
+            if pid in groups:
+                continue
+            addr = None
+            if isinstance(pid, str) and pid.rsplit('_', 1)[-1].isdigit():
+                addr = int(pid.rsplit('_', 1)[-1])
+            groups[pid] = {
+                'panel_id': pid, 'address': addr, 'uid': None,
+                'registered': False, 'status': 'unbound',
+            }
+
+        result = []
+        for pid, info in groups.items():
+            raw = (dtu_config.get('port_mappings') or {}).get(pid) or {}
+            mappings = []
+            for key, value in raw.items():
+                try:
+                    port = int(key)
+                except (TypeError, ValueError):
+                    continue
+                if 1 <= port <= 24:
+                    mappings.append({'port': port, 'uid': _to_internal_uid_lenient(value)})
+            mappings.sort(key=lambda m: m['port'])
+            result.append({**info, 'mapping_count': len(mappings), 'mappings': mappings})
+
+        result.sort(key=lambda g: (g['address'] is None, g['address'] if g['address'] is not None else 0))
+        return jsonify({'success': True, 'panels': result})
+    except Exception as e:
+        logger.error(f"查询端口映射失败: {e}")
+        return jsonify({'success': False, 'message': str(e)}), 500
+
+
+def _push_single_port_hardware(panel_id, addr, port_id, expected_uid):
+    """单口增改删后,把整帧(硬件基底+平台期望+目标口)下发硬件。返回 (ok, msg)。"""
+    try:
+        if not (isinstance(serial_client.get_status(), dict)
+                and serial_client.get_status().get('connected', False)):
+            return False, '串口未连接'
+        card_mappings = _hardware_card_base(addr)
+        for ant, v in _dtu_mapping_overrides(panel_id).items():
+            card_mappings[ant] = v
+        card_mappings[int(port_id)] = expected_uid
+        res = modbus_client.set_card_mapping(addr, card_mappings, timeout=2.0)
+        if 'error' in res:
+            return False, res['error']
+        return True, None
+    except Exception as e:
+        return False, str(e)
+
+
+@app.route('/api/panel/mapping', methods=['POST'])
+def panel_mapping_upsert_delete():
+    """单端口映射 新增/修改/删除(绑定②)。
+
+    请求: {"panel_id"或"address", "port": 1, "card_uid": "12位hex" 或 null/"" 删除}
+    - 落盘到 dtu_config.port_mappings(删除即移除键,不写 null)
+    - 面板已注册且在线、串口连接时,同步下发硬件(保留其它端口现值)
+    - 硬件下发失败不回滚已保存的期望映射,仅在响应里告警(下次上线会重下)
+    """
+    try:
+        data = request.json or {}
+        panel_id = _resolve_panel_id(data.get('panel_id'))
+        addr = data.get('address')
+        if addr is None and panel_id:
+            cfg = panel_config.get(panel_id)
+            if cfg:
+                addr = cfg.get('address')
+            elif isinstance(panel_id, str) and panel_id.rsplit('_', 1)[-1].isdigit():
+                addr = int(panel_id.rsplit('_', 1)[-1])
+        if not panel_id:
+            if isinstance(addr, int):
+                panel_id = _panel_id_for_address(addr)
+            else:
+                return jsonify({'success': False, 'message': '缺少有效的 address 或 panel_id'}), 400
+
+        try:
+            port_id = int(data.get('port'))
+        except (TypeError, ValueError):
+            return jsonify({'success': False, 'message': 'port 必须是 1-24 的整数'}), 400
+        if not (1 <= port_id <= 24):
+            return jsonify({'success': False, 'message': 'port 必须在 1-24'}), 400
+
+        raw_uid = data.get('card_uid')
+        expected_uid = None
+        if raw_uid not in (None, ''):
+            u = str(raw_uid).strip().upper().replace(':', '').replace(' ', '')
+            if len(u) != 12 or not all(c in _JUMPER_HEX for c in u):
+                return jsonify({'success': False, 'message': '卡号必须是 12 位十六进制'}), 400
+            expected_uid = u
+
+        action = 'delete' if expected_uid is None else 'set'
+        existed = str(port_id) in (dtu_config.get('port_mappings', {}).get(panel_id) or {})
+
+        # 更新运行态期望
+        port_state.setdefault(panel_id, {}).setdefault(
+            port_id, {'last_uid': None, 'expected_uid': None, 'alarm_count': 0})
+        port_state[panel_id][port_id]['expected_uid'] = expected_uid
+        _store_port_mapping(panel_id, port_id, expected_uid)
+        save_dtu_config()
+
+        # 在线则同步硬件
+        hw = {'synced': False}
+        registered = bool(_binding_uid_for_address(addr)) if isinstance(addr, int) else (
+            panel_id in panel_config)
+        if isinstance(addr, int) and registered:
+            ok, msg = _push_single_port_hardware(panel_id, addr, port_id, expected_uid)
+            hw = {'synced': ok, 'message': msg}
+        else:
+            hw = {'synced': False, 'message': '面板未注册,仅保存平台记录'}
+
+        logger.info(f"端口映射 {action}: 面板={panel_id} 端口={port_id} 卡号={expected_uid or '空'} 硬件同步={hw['synced']}")
+        return jsonify({
+            'success': True, 'action': action,
+            'panel_id': panel_id, 'address': addr, 'port': port_id,
+            'card_uid': expected_uid, 'existed': existed, 'hardware': hw,
+        })
+    except Exception as e:
+        logger.error(f"保存端口映射失败: {e}")
+        return jsonify({'success': False, 'message': str(e)}), 500
+
+
 def _run_panel_scan():
     """后台扫描地址段内全部未绑定地址(手动触发,V5 0x80 查询)"""
     global _panel_scan_state
@@ -5704,6 +5977,15 @@ if __name__ == '__main__':
         # 加载DTU配置
         load_dtu_config()
 
+        # 一次性清理历史脏数据:旧版单端口写卡会把 24 路(含大量 null)落盘
+        try:
+            _pruned = _prune_null_port_mappings()
+            if _pruned:
+                save_dtu_config()
+                logger.info(f"已清理 port_mappings 中的空(null)端口映射 {_pruned} 条")
+        except Exception as e:
+            logger.warning(f"清理空端口映射失败: {e}")
+
         # 加载线架绑定表(地址↔UID)
         loaded = load_device_config()
         logger.info(f"已加载 {len(loaded)} 个线架绑定")

+ 152 - 0
backend/tests/test_panel_registration.py

@@ -512,6 +512,158 @@ class TestPanelRegistration:
         app_module.dtu_config['address_range'] = None
         assert app_module._address_range() == (1, 50)
 
+    def test_single_port_write_persists_only_target_port(self):
+        """单端口写卡:硬件帧带全 24 口,但配置只落目标这一条(修复映射污染)。"""
+        client = app.test_client()
+        pid = 'PANEL_dtu_001_8'
+        app_module.panel_config[pid] = {'address': 8, 'position': 8,
+                                        'panel_uid': 'cc' * 12, 'status': 'online'}
+        app_module.dtu_config['port_mappings'] = {}
+        # 硬件基底:4/22/23 口插着卡(这些只应出现在下发帧,不应落盘)
+        self.mock_modbus.read_all_antenna_cards.return_value = read_result(
+            make_cards({4: '04' * 6, 22: '16' * 6, 23: '17' * 6}), addr=8)
+        # set_card_mapping 回 24 路 cards_written(模拟真实实现)
+        written = {p: None for p in range(1, 25)}
+        written[1] = 'aabbccddeeff'
+        written[4] = '040404040404'
+        written[22] = '161616161616'
+        written[23] = '171717171717'
+        self.mock_modbus.set_card_mapping.return_value = {
+            'success': True, 'device_address': 8, 'cards_written': written, 'raw_data': 'T'}
+        with patch.object(app_module.serial_client, 'get_status', return_value={'connected': True}):
+            resp = client.post('/api/modbus/set_card_mapping',
+                               json={'device_address': 8, 'port_id': 1,
+                                     'card_uid': 'AABBCCDDEEFF'})
+        assert resp.status_code == 200 and resp.get_json()['success']
+        saved = app_module.dtu_config['port_mappings'][pid]
+        # 只落目标 1 口;硬件基底里的 4/22/23 不得被灌进配置,也不得出现 null
+        assert saved == {'1': 'AABBCCDDEEFF'}
+        # 下发帧仍带全部端口(目标口是新卡号,其它保留硬件读回值)
+        args, _ = self.mock_modbus.set_card_mapping.call_args
+        assert args[1][1] == 'AABBCCDDEEFF'
+        assert args[1][4] == '040404040404'
+        assert self.mock_save_dtu.called
+
+    def test_single_port_clear_deletes_mapping_key(self):
+        """单端口清除:删除该端口配置键(不写 null),硬件帧目标口发 None。"""
+        client = app.test_client()
+        pid = 'PANEL_dtu_001_8'
+        app_module.panel_config[pid] = {'address': 8, 'position': 8,
+                                        'panel_uid': 'cc' * 12, 'status': 'online'}
+        app_module.dtu_config['port_mappings'] = {pid: {'1': 'AABBCCDDEEFF', '2': '222222222222'}}
+        self.mock_modbus.read_all_antenna_cards.return_value = read_result(make_cards({}), addr=8)
+        self.mock_modbus.set_card_mapping.return_value = {
+            'success': True, 'device_address': 8,
+            'cards_written': {p: None for p in range(1, 25)}, 'raw_data': 'T'}
+        with patch.object(app_module.serial_client, 'get_status', return_value={'connected': True}):
+            resp = client.post('/api/modbus/set_card_mapping',
+                               json={'device_address': 8, 'port_id': 1, 'card_uid': None})
+        assert resp.status_code == 200 and resp.get_json()['success']
+        saved = app_module.dtu_config['port_mappings'][pid]
+        assert '1' not in saved and saved.get('2') == '222222222222'
+        args, _ = self.mock_modbus.set_card_mapping.call_args
+        assert args[1][1] is None  # 硬件目标口清成 0xFF
+
+    def test_prune_null_port_mappings(self):
+        """启动清理:删除 null/空端口,保留有效卡号;面板清空后整组移除。"""
+        app_module.dtu_config['port_mappings'] = {
+            'PANEL_dtu_001_1': {'1': 'AABBCCDDEEFF', '5': None, '10': ''},
+            'PANEL_dtu_001_4': {str(i): None for i in range(1, 24)} | {'24': 'DDAD57F95002'},
+            'PANEL_dtu_001_9': {'1': None, '2': None},
+        }
+        removed = app_module._prune_null_port_mappings()
+        pm = app_module.dtu_config['port_mappings']
+        assert removed == 27  # 2(面板1)+ 23(面板4 的 1..23)+ 2(面板9)
+        assert pm['PANEL_dtu_001_1'] == {'1': 'AABBCCDDEEFF'}
+        assert pm['PANEL_dtu_001_4'] == {'24': 'DDAD57F95002'}
+        assert 'PANEL_dtu_001_9' not in pm
+
+    def test_clear_panel_mappings_api(self):
+        """清空面板映射 API:删配置+在线时硬件 24 口清成 None,不影响绑定①。"""
+        client = app.test_client()
+        uid = '77' * 12
+        pid = 'PANEL_dtu_001_7'
+        app_module.address_config.stored_devices[uid] = 7
+        app_module.panel_config[pid] = {'address': 7, 'position': 7,
+                                        'panel_uid': uid, 'status': 'online'}
+        app_module.dtu_config['port_mappings'] = {pid: {'1': '111111111111', '3': '222222222222'}}
+        self.mock_modbus.set_card_mapping.return_value = {'success': True}
+        with patch.object(app_module.serial_client, 'get_status', return_value={'connected': True}):
+            resp = client.post('/api/panel/clear_mappings', json={'address': 7})
+        data = resp.get_json()
+        assert resp.status_code == 200 and data['success']
+        assert data['removed'] == 2
+        assert pid not in app_module.dtu_config['port_mappings']
+        # 绑定①保留
+        assert app_module.address_config.stored_devices.get(uid) == 7
+        # 硬件整帧清空
+        args, _ = self.mock_modbus.set_card_mapping.call_args
+        assert args[0] == 7 and all(v is None for v in args[1].values())
+
+    def test_mapping_upsert_and_delete_api(self):
+        """映射管理:新增落单口并在线下发;删除移除键且硬件目标口 None。"""
+        client = app.test_client()
+        uid = '88' * 12
+        pid = 'PANEL_dtu_001_6'
+        app_module.address_config.stored_devices[uid] = 6
+        app_module.panel_config[pid] = {'address': 6, 'position': 6,
+                                        'panel_uid': uid, 'status': 'online'}
+        app_module.dtu_config['port_mappings'] = {}
+        self.mock_modbus.read_all_antenna_cards.return_value = read_result(make_cards({}), addr=6)
+        self.mock_modbus.set_card_mapping.return_value = {'success': True}
+        serial_ok = patch.object(app_module.serial_client, 'get_status',
+                                 return_value={'connected': True})
+        serial_ok.start()
+        try:
+            # 新增端口 3
+            resp = client.post('/api/panel/mapping',
+                               json={'address': 6, 'port': 3, 'card_uid': 'aabbccddeeff'})
+            d = resp.get_json()
+            assert resp.status_code == 200 and d['success'] and d['action'] == 'set'
+            assert app_module.dtu_config['port_mappings'][pid] == {'3': 'AABBCCDDEEFF'}
+            # 下发帧目标口为新卡号(规范化大写)
+            args, _ = self.mock_modbus.set_card_mapping.call_args
+            assert args[1][3] == 'AABBCCDDEEFF'
+
+            # 非法卡号被拒
+            bad = client.post('/api/panel/mapping',
+                              json={'address': 6, 'port': 4, 'card_uid': 'zz'})
+            assert bad.status_code == 400
+
+            # 删除端口 3
+            resp = client.post('/api/panel/mapping',
+                               json={'address': 6, 'port': 3, 'card_uid': None})
+            d = resp.get_json()
+            assert resp.status_code == 200 and d['action'] == 'delete'
+            assert '3' not in app_module.dtu_config['port_mappings'].get(pid, {})
+            args, _ = self.mock_modbus.set_card_mapping.call_args
+            assert args[1][3] is None
+        finally:
+            serial_ok.stop()
+
+    def test_mappings_list_includes_unbound_residual(self):
+        """映射列表:包含已注册面板和有残留映射的未注册面板。"""
+        client = app.test_client()
+        uid = '5a' * 12
+        pid1 = 'PANEL_dtu_001_2'
+        app_module.address_config.stored_devices[uid] = 2
+        app_module.panel_config[pid1] = {'address': 2, 'position': 2,
+                                         'panel_uid': uid, 'status': 'online'}
+        app_module.dtu_config['port_mappings'] = {
+            pid1: {'1': '111111111111'},
+            'PANEL_dtu_001_9': {'5': '555555555555', '7': None},
+        }
+        resp = client.get('/api/panel/mappings')
+        d = resp.get_json()
+        assert resp.status_code == 200 and d['success']
+        by_id = {g['panel_id']: g for g in d['panels']}
+        assert by_id[pid1]['registered'] is True
+        assert by_id[pid1]['mappings'] == [{'port': 1, 'uid': '111111111111'}]
+        g9 = by_id['PANEL_dtu_001_9']
+        assert g9['registered'] is False and g9['address'] == 9
+        # null 条目在列表里归一为 None(仍可见,便于清理)
+        assert {m['port']: m['uid'] for m in g9['mappings']} == {5: '555555555555', 7: None}
+
 
 if __name__ == '__main__':
     pytest.main([__file__, '-v'])

+ 4 - 0
frontend/src/App.vue

@@ -65,6 +65,10 @@
             <a-menu-item key="/panel-manage" icon="<cluster />">
               <router-link to="/panel-manage">线架管理</router-link>
             </a-menu-item>
+
+            <a-menu-item key="/port-mapping" icon="<switcher />">
+              <router-link to="/port-mapping">端口映射</router-link>
+            </a-menu-item>
             <a-menu-item key="/alarm-status" icon="<alert />">
               <router-link to="/alarm-status">告警显示</router-link>
             </a-menu-item>

+ 7 - 0
frontend/src/api/apiService.js

@@ -144,6 +144,13 @@ const apiService = {
     // 解除线架绑定(仅解除;线架仍在总线时下轮扫描会重新绑定)
     unbind: (params) => apiClient.post('/panel/unbind', params),
 
+    // 清空某面板全部端口映射(绑定②;在线时同时把硬件 24 口清成无卡)
+    clearMappings: (params) => apiClient.post('/panel/clear_mappings', params),
+
+    // 端口映射管理:查全部面板的端口映射 / 单口增改删
+    getMappings: () => apiClient.get('/panel/mappings'),
+    saveMapping: (params) => apiClient.post('/panel/mapping', params),
+
     // 扫描地址段内未绑定地址,发现新线架
     scan: () => apiClient.post('/panel/scan'),
 

+ 6 - 0
frontend/src/router/index.js

@@ -55,6 +55,12 @@ const routes = [
     meta: { title: '线架管理' }
   },
   {
+    path: '/port-mapping',
+    name: 'PortMapping',
+    component: () => import('../views/PortMapping.vue'),
+    meta: { title: '端口映射' }
+  },
+  {
     path: '/alarm-status',
     name: 'AlarmStatus',
     component: () => import('../views/AlarmStatus.vue'),

+ 41 - 8
frontend/src/views/PanelManage.vue

@@ -87,13 +87,24 @@
                 </a-space>
               </template>
               <template v-else-if="column.key === 'action'">
-                <a-popconfirm
-                  title="确定解除该线架的注册绑定?"
-                  :description="`地址 ${record.address}(UID ${formatUid(record.uid)})。若线架仍在总线上,下一轮扫描会自动重新绑定。`"
-                  @confirm="unbindPanel(record)"
-                >
-                  <a-button type="link" size="small" danger>删除</a-button>
-                </a-popconfirm>
+                <a-space :size="0">
+                  <a-popconfirm
+                    title="清空该线架的全部端口映射?"
+                    :description="`地址 ${record.address}:删除平台保存的端口↔卡号映射;线架在线时会同时把硬件 24 个端口全部清成无卡。不影响线架注册绑定。`"
+                    ok-text="清空"
+                    cancel-text="取消"
+                    @confirm="clearMappings(record)"
+                  >
+                    <a-button type="link" size="small">清空映射</a-button>
+                  </a-popconfirm>
+                  <a-popconfirm
+                    title="确定解除该线架的注册绑定?"
+                    :description="`地址 ${record.address}(UID ${formatUid(record.uid)})。若线架仍在总线上,下一轮扫描会自动重新绑定。`"
+                    @confirm="unbindPanel(record)"
+                  >
+                    <a-button type="link" size="small" danger>删除</a-button>
+                  </a-popconfirm>
+                </a-space>
               </template>
             </template>
           </a-table>
@@ -202,7 +213,7 @@ const columns = [
   { title: '状态', key: 'status', width: 130 },
   { title: '最后响应', key: 'last_seen', width: 180 },
   { title: '端口(已连/总)', key: 'ports', width: 160 },
-  { title: '操作', key: 'action', width: 100 }
+  { title: '操作', key: 'action', width: 180 }
 ]
 
 const onlineCount = computed(() => panels.value.filter(p => p.status === 'online').length)
@@ -401,6 +412,28 @@ async function unbindPanel(record) {
   }
 }
 
+async function clearMappings(record) {
+  try {
+    const res = await apiService.panel.clearMappings({
+      panel_id: record.panel_id,
+      address: record.address
+    })
+    if (res.data.success) {
+      const hw = res.data.hardware || {}
+      if (hw.cleared) {
+        message.success(`已清空 ${res.data.removed} 条端口映射,硬件端口已同步清空`)
+      } else {
+        message.success(`已清空 ${res.data.removed} 条端口映射${hw.message ? '(' + hw.message + ')' : ''}`)
+      }
+      await refreshData()
+    } else {
+      message.error(res.data.message || '清空映射失败')
+    }
+  } catch (e) {
+    message.error((e.response && e.response.data && e.response.data.message) || '清空映射失败')
+  }
+}
+
 onMounted(async () => {
   await refreshData()
   pollTimer = setInterval(loadPanels, 5000)

+ 343 - 0
frontend/src/views/PortMapping.vue

@@ -0,0 +1,343 @@
+<template>
+  <div class="port-mapping">
+    <a-card>
+      <div class="page-bar">
+        <div class="page-title">
+          <span class="title-text">端口映射管理</span>
+          <a-tooltip title="绑定②:每个线架地址下,端口(1-24)↔12位卡号。线架在线、串口连接时,新增/修改/删除会同步下发硬件;离线时仅保存平台记录,线架重新上线会自动下发。">
+            <question-circle-outlined class="tip-icon" />
+          </a-tooltip>
+        </div>
+        <a-space>
+          <a-tag :color="serialConnected ? 'green' : 'red'">
+            串口{{ serialConnected ? '已连接' : '未连接' }}
+          </a-tag>
+          <a-button size="small" :loading="loading" @click="loadData">
+            <reload-outlined /> 刷新
+          </a-button>
+        </a-space>
+      </div>
+      <a-alert
+        type="info"
+        show-icon
+        style="margin-top: 12px"
+        message="说明"
+        description="这里管理的是端口↔卡号映射(绑定②),与「线架管理」里的地址↔线架注册(绑定①)相互独立。删除映射会同时把该线架硬件端口清成无卡;清空全部会下发 24 口全空。卡号为 12 位十六进制(如 AABBCCDDEEFF)。"
+      />
+    </a-card>
+
+    <a-empty
+      v-if="!loading && panels.length === 0"
+      description="暂无线架或映射数据"
+      style="margin-top: 48px"
+    />
+
+    <a-row :gutter="[16, 16]" style="margin-top: 16px">
+      <a-col :xs="24" :md="12" v-for="p in panels" :key="p.panel_id">
+        <a-card size="small">
+          <template #title>
+            <a-space :size="8" wrap>
+              <a-tag color="blue">地址 {{ p.address ?? '--' }}</a-tag>
+              <span class="mono panel-id">{{ p.panel_id }}</span>
+              <a-tag :color="statusColor(p.status)">{{ statusLabel(p.status) }}</a-tag>
+            </a-space>
+          </template>
+          <template #extra>
+            <a-space :size="4">
+              <a-button type="link" size="small" @click="openAdd(p)">新增</a-button>
+              <a-popconfirm
+                title="清空该线架全部端口映射?"
+                description="删除全部平台映射;线架在线时会把硬件 24 口全部清成无卡。"
+                ok-text="清空"
+                @confirm="clearAll(p)"
+              >
+                <a-button type="link" size="small" danger :disabled="p.mapping_count === 0">清空全部</a-button>
+              </a-popconfirm>
+            </a-space>
+          </template>
+
+          <a-table
+            :data-source="p.mappings"
+            :columns="columns"
+            :pagination="false"
+            size="small"
+            row-key="port"
+            :locale="{ emptyText: '未配置任何端口映射' }"
+          >
+            <template #bodyCell="{ column, record }">
+              <template v-if="column.key === 'port'">
+                <a-tag>{{ record.port }}</a-tag>
+              </template>
+              <template v-else-if="column.key === 'uid'">
+                <span class="mono">{{ record.uid || '--' }}</span>
+              </template>
+              <template v-else-if="column.key === 'action'">
+                <a-button type="link" size="small" @click="openEdit(p, record)">编辑</a-button>
+                <a-popconfirm
+                  :title="`删除端口 ${record.port} 的映射?`"
+                  description="线架在线时会同时把硬件该端口清成无卡。"
+                  ok-text="删除"
+                  @confirm="removeMapping(p, record)"
+                >
+                  <a-button type="link" size="small" danger>删除</a-button>
+                </a-popconfirm>
+              </template>
+            </template>
+          </a-table>
+        </a-card>
+      </a-col>
+    </a-row>
+
+    <!-- 新增 / 编辑 弹窗 -->
+    <a-modal
+      v-model:open="modal.open"
+      :title="modal.isEdit ? `编辑映射 - 地址 ${modal.address} 端口 ${modal.port}` : `新增映射 - 地址 ${modal.address}`"
+      :confirm-loading="modal.saving"
+      ok-text="保存"
+      cancel-text="取消"
+      @ok="submit"
+    >
+      <a-form layout="vertical" style="margin-top: 8px">
+        <a-form-item label="端口号" required>
+          <a-select
+            v-model:value="modal.port"
+            :disabled="modal.isEdit"
+            :options="portOptions"
+            placeholder="选择端口 1-24"
+          />
+        </a-form-item>
+        <a-form-item label="卡号(12 位十六进制)" required>
+          <a-input
+            v-model:value="modal.uid"
+            placeholder="如 AABBCCDDEEFF"
+            allow-clear
+            :maxlength="12"
+            class="mono"
+            @press-enter="submit"
+          />
+          <div v-if="modal.uidError" style="color: #cf1322; font-size: 12px; margin-top: 4px">
+            {{ modal.uidError }}
+          </div>
+        </a-form-item>
+        <a-alert
+          v-if="!modal.online"
+          type="warning"
+          show-icon
+          message="该线架当前不在线 / 未注册"
+          description="保存只会更新平台记录;线架重新上线后会自动下发到硬件。"
+        />
+      </a-form>
+    </a-modal>
+  </div>
+</template>
+
+<script setup>
+import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
+import { message } from 'ant-design-vue'
+import {
+  ReloadOutlined,
+  QuestionCircleOutlined
+} from '@ant-design/icons-vue'
+import apiService from '../api/apiService'
+import { useDataStore } from '../stores/dataStore'
+
+const dataStore = useDataStore()
+const loading = ref(false)
+const panels = ref([])
+let timer = null
+
+const columns = [
+  { title: '端口', key: 'port', width: 70 },
+  { title: '卡号', key: 'uid' },
+  { title: '操作', key: 'action', width: 130 }
+]
+
+const modal = reactive({
+  open: false,
+  isEdit: false,
+  panelId: null,
+  address: null,
+  online: false,
+  port: null,
+  uid: '',
+  uidError: '',
+  saving: false,
+  usedPorts: () => []
+})
+
+const serialConnected = computed(() => !!dataStore.serialConnected)
+
+const portOptions = computed(() => {
+  const used = new Set(panels.value
+    .filter(p => p.panel_id === modal.panelId)
+    .flatMap(p => p.mappings.map(m => m.port)))
+  const opts = []
+  for (let i = 1; i <= 24; i++) {
+    opts.push({
+      value: i,
+      label: used.has(i) && i !== modal.port ? `${i}(已配置)` : String(i),
+      disabled: used.has(i) && i !== modal.port
+    })
+  }
+  return opts
+})
+
+function statusLabel(s) {
+  return { online: '在线', missing: '缺失待接管', offline: '离线', conflict: '冲突', unbound: '未注册(有残留映射)' }[s] || s
+}
+function statusColor(s) {
+  return { online: 'green', missing: 'orange', offline: 'default', conflict: 'red', unbound: 'purple' }[s] || 'default'
+}
+
+async function loadData() {
+  loading.value = true
+  try {
+    const res = await apiService.panel.getMappings()
+    if (res.data.success) {
+      panels.value = res.data.panels || []
+    } else {
+      message.error(res.data.message || '加载失败')
+    }
+  } catch (e) {
+    message.error('加载端口映射失败')
+  } finally {
+    loading.value = false
+  }
+}
+
+function openAdd(p) {
+  const used = new Set(p.mappings.map(m => m.port))
+  let firstFree = 1
+  while (used.has(firstFree) && firstFree <= 24) firstFree++
+  Object.assign(modal, {
+    open: true, isEdit: false, panelId: p.panel_id, address: p.address,
+    online: p.status === 'online', port: firstFree <= 24 ? firstFree : null,
+    uid: '', uidError: ''
+  })
+}
+
+function openEdit(p, record) {
+  Object.assign(modal, {
+    open: true, isEdit: true, panelId: p.panel_id, address: p.address,
+    online: p.status === 'online', port: record.port,
+    uid: record.uid || '', uidError: ''
+  })
+}
+
+function validateUid() {
+  const v = (modal.uid || '').trim().toUpperCase()
+  if (!/^[0-9A-F]{12}$/.test(v)) {
+    modal.uidError = '卡号必须是 12 位十六进制字符(0-9 A-F)'
+    return null
+  }
+  modal.uidError = ''
+  return v
+}
+
+async function submit() {
+  if (!modal.port) {
+    message.warning('请选择端口')
+    return
+  }
+  const uid = validateUid()
+  if (uid === null) return
+  modal.saving = true
+  try {
+    const res = await apiService.panel.saveMapping({
+      panel_id: modal.panelId,
+      address: modal.address,
+      port: modal.port,
+      card_uid: uid
+    })
+    if (res.data.success) {
+      const hw = res.data.hardware || {}
+      if (hw.synced) {
+        message.success('已保存并下发硬件')
+      } else {
+        message.success(hw.message ? `已保存(${hw.message})` : '已保存')
+      }
+      modal.open = false
+      await loadData()
+    } else {
+      message.error(res.data.message || '保存失败')
+    }
+  } catch (e) {
+    message.error((e.response && e.response.data && e.response.data.message) || '保存失败')
+  } finally {
+    modal.saving = false
+  }
+}
+
+async function removeMapping(p, record) {
+  try {
+    const res = await apiService.panel.saveMapping({
+      panel_id: p.panel_id, address: p.address,
+      port: record.port, card_uid: null
+    })
+    if (res.data.success) {
+      const hw = res.data.hardware || {}
+      message.success(hw.synced ? '已删除并清空硬件端口' : (hw.message ? `已删除(${hw.message})` : '已删除'))
+      await loadData()
+    } else {
+      message.error(res.data.message || '删除失败')
+    }
+  } catch (e) {
+    message.error((e.response && e.response.data && e.response.data.message) || '删除失败')
+  }
+}
+
+async function clearAll(p) {
+  try {
+    const res = await apiService.panel.clearMappings({
+      panel_id: p.panel_id, address: p.address
+    })
+    if (res.data.success) {
+      const hw = res.data.hardware || {}
+      message.success(hw.cleared ? '已清空并同步硬件' : (hw.message ? `已清空(${hw.message})` : '已清空'))
+      await loadData()
+    } else {
+      message.error(res.data.message || '清空失败')
+    }
+  } catch (e) {
+    message.error((e.response && e.response.data && e.response.data.message) || '清空失败')
+  }
+}
+
+onMounted(async () => {
+  await loadData()
+  timer = setInterval(loadData, 10000)
+})
+
+onUnmounted(() => {
+  if (timer) clearInterval(timer)
+})
+</script>
+
+<style scoped>
+.page-bar {
+  display: flex;
+  align-items: center;
+  justify-content: space-between;
+  flex-wrap: wrap;
+  gap: 12px;
+}
+.page-title {
+  display: flex;
+  align-items: center;
+  gap: 8px;
+}
+.title-text {
+  font-size: 16px;
+  font-weight: 600;
+}
+.tip-icon {
+  color: #999;
+}
+.mono {
+  font-family: monospace;
+}
+.panel-id {
+  font-size: 12px;
+  color: #888;
+}
+</style>