|
@@ -373,6 +373,48 @@ def _dtu_mapping_overrides(panel_id):
|
|
|
return overrides
|
|
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():
|
|
def get_sorted_panels():
|
|
|
"""按 position 排序返回 panel 列表。"""
|
|
"""按 position 排序返回 panel 列表。"""
|
|
|
return sorted(panel_config.items(), key=lambda x: x[1].get('position', 0))
|
|
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] = {'last_uid': None, 'expected_uid': None, 'alarm_count': 0}
|
|
|
|
|
|
|
|
port_state[panel_target][port_id]['expected_uid'] = expected_uid
|
|
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()
|
|
save_dtu_config()
|
|
|
|
|
|
|
|
# V4: 下发卡号到配线架硬件(24路同时发送;保留其他端口真实硬件值,避免误擦)
|
|
# V4: 下发卡号到配线架硬件(24路同时发送;保留其他端口真实硬件值,避免误擦)
|
|
@@ -2274,8 +2317,8 @@ def dtu_handle_control(topic, payload):
|
|
|
if port_id not in port_state[panel_id]:
|
|
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] = {'last_uid': None, 'expected_uid': None, 'alarm_count': 0}
|
|
|
port_state[panel_id][port_id]['expected_uid'] = expected_uid
|
|
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()
|
|
save_dtu_config()
|
|
|
except Exception as e:
|
|
except Exception as e:
|
|
|
response_payload['payload']['success'] = False
|
|
response_payload['payload']['success'] = False
|
|
@@ -3581,6 +3624,9 @@ def modbus_set_card_mapping():
|
|
|
return jsonify({'success': False, 'message': '串口未连接'}), 400
|
|
return jsonify({'success': False, 'message': '串口未连接'}), 400
|
|
|
|
|
|
|
|
card_mappings = data.get('card_mappings')
|
|
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:
|
|
if card_mappings is None:
|
|
|
# 单端口模式:构建 24 路数据,避免擦掉其他端口
|
|
# 单端口模式:构建 24 路数据,避免擦掉其他端口
|
|
|
# 策略: 先读硬件当前值做基底 → 再用 dtu_config 期望值覆盖 → 最后覆盖目标端口
|
|
# 策略: 先读硬件当前值做基底 → 再用 dtu_config 期望值覆盖 → 最后覆盖目标端口
|
|
@@ -3599,6 +3645,11 @@ def modbus_set_card_mapping():
|
|
|
if port_id is None:
|
|
if port_id is None:
|
|
|
return jsonify({'success': False, 'message': '缺少 port_id 或 card_mappings'}), 400
|
|
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 路值,作为默认基底(防止擦掉其他端口硬件里真实存在的卡号)
|
|
# 第一步:读硬件当前 24 路值,作为默认基底(防止擦掉其他端口硬件里真实存在的卡号)
|
|
|
card_mappings = _hardware_card_base(device_address)
|
|
card_mappings = _hardware_card_base(device_address)
|
|
|
|
|
|
|
@@ -3615,12 +3666,8 @@ def modbus_set_card_mapping():
|
|
|
uid = str(card_uid).strip().upper().replace(':', '').replace(' ', '')
|
|
uid = str(card_uid).strip().upper().replace(':', '').replace(' ', '')
|
|
|
if len(uid) != 12 or not all(c in _JUMPER_HEX for c in uid):
|
|
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
|
|
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
|
|
# 转换 key 为 int
|
|
|
normalized = {}
|
|
normalized = {}
|
|
@@ -3655,27 +3702,37 @@ def modbus_set_card_mapping():
|
|
|
warnings = []
|
|
warnings = []
|
|
|
cards_written = result.get('cards_written', {})
|
|
cards_written = result.get('cards_written', {})
|
|
|
if panel_target:
|
|
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
|
|
'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
|
|
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:
|
|
else:
|
|
|
warnings.append(f"未找到 device_address={device_address} 对应的面板,本地期望值未更新(仅硬件已生效)")
|
|
warnings.append(f"未找到 device_address={device_address} 对应的面板,本地期望值未更新(仅硬件已生效)")
|
|
|
|
|
|
|
@@ -4137,6 +4194,222 @@ def panel_unbind():
|
|
|
return jsonify({'success': False, 'message': str(e)}), 500
|
|
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():
|
|
def _run_panel_scan():
|
|
|
"""后台扫描地址段内全部未绑定地址(手动触发,V5 0x80 查询)"""
|
|
"""后台扫描地址段内全部未绑定地址(手动触发,V5 0x80 查询)"""
|
|
|
global _panel_scan_state
|
|
global _panel_scan_state
|
|
@@ -5704,6 +5977,15 @@ if __name__ == '__main__':
|
|
|
# 加载DTU配置
|
|
# 加载DTU配置
|
|
|
load_dtu_config()
|
|
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)
|
|
# 加载线架绑定表(地址↔UID)
|
|
|
loaded = load_device_config()
|
|
loaded = load_device_config()
|
|
|
logger.info(f"已加载 {len(loaded)} 个线架绑定")
|
|
logger.info(f"已加载 {len(loaded)} 个线架绑定")
|