feat: implementacion completa de 8 modulos, sincronizador centinel, mcp y bitacora de errores
This commit is contained in:
@@ -1,18 +1,342 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../theme.dart';
|
||||
import '../services/centinel_service.dart';
|
||||
|
||||
class DispositivosPage extends StatelessWidget {
|
||||
/// Página de gestión y control de dispositivos de seguridad electrónica.
|
||||
/// Soporta terminales Hikvision ISAPI (Digest Auth) y cerraduras Tuya Smart IoT.
|
||||
/// Permite diagnóstico en vivo (test) y apertura remota de puertas.
|
||||
class DispositivosPage extends StatefulWidget {
|
||||
const DispositivosPage({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
State<DispositivosPage> createState() => _DispositivosPageState();
|
||||
}
|
||||
|
||||
class _DispositivosPageState extends State<DispositivosPage> {
|
||||
final _centinel = CentinelService.instance;
|
||||
List<Map<String, dynamic>> _dispositivos = [];
|
||||
bool _cargando = true;
|
||||
String _filtroTexto = '';
|
||||
String _filtroEstado = 'todos'; // todos | online | offline
|
||||
|
||||
final Map<int, bool> _probandoConexion = {};
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_cargarDispositivos();
|
||||
}
|
||||
|
||||
// Comentario explicativo: Carga los dispositivos disponibles desde CentinelService
|
||||
Future<void> _cargarDispositivos() async {
|
||||
setState(() => _cargando = true);
|
||||
final lista = await _centinel.getDevices();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_dispositivos = lista;
|
||||
_cargando = false;
|
||||
});
|
||||
}
|
||||
|
||||
// Comentario explicativo: Realiza ping y telemetría de diagnóstico en vivo hacia el dispositivo
|
||||
Future<void> _probarConexion(int id, String nombre) async {
|
||||
setState(() => _probandoConexion[id] = true);
|
||||
final resultado = await _centinel.testDevice(id);
|
||||
if (!mounted) return;
|
||||
setState(() => _probandoConexion[id] = false);
|
||||
|
||||
final ok = resultado['ok'] == true;
|
||||
final ms = resultado['latencyMs'] ?? 0;
|
||||
final msg = resultado['message'] ?? (ok ? 'Dispositivo responde correctamente' : 'Fallo de conexión');
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
backgroundColor: ok ? const Color(0xFF1B5E20) : const Color(0xFFB71C1C),
|
||||
content: Row(children: [
|
||||
Icon(ok ? Icons.check_circle : Icons.error, color: Colors.white),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'$nombre: $msg ${ok ? "($ms ms)" : ""}',
|
||||
style: appLabel(size: 13, color: Colors.white),
|
||||
),
|
||||
),
|
||||
]),
|
||||
duration: const Duration(seconds: 4),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Diálogo modal de confirmación para apertura remota de puertas de alta seguridad
|
||||
Future<void> _confirmarApertura(int id, String nombre) async {
|
||||
final confirmar = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
backgroundColor: AppColors.surfaceHigh,
|
||||
title: Row(children: [
|
||||
const Icon(Icons.lock_open, color: AppColors.alarmaEscalada),
|
||||
const SizedBox(width: 10),
|
||||
Text('Apertura Remota', style: appHeadline(size: 18, color: AppColors.onSurface)),
|
||||
]),
|
||||
content: Text(
|
||||
'¿Confirmas la apertura remota de la puerta en "$nombre"? Esta acción quedará registrada en la auditoría de la central.',
|
||||
style: appLabel(size: 14, color: AppColors.onSurfaceVariant),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx, false),
|
||||
child: Text('Cancelar', style: appLabel(size: 14, color: AppColors.outline)),
|
||||
),
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: AppColors.primaryContainer,
|
||||
foregroundColor: AppColors.primary,
|
||||
),
|
||||
onPressed: () => Navigator.pop(ctx, true),
|
||||
child: Text('Confirmar Apertura', style: appHeadline(size: 14, color: AppColors.primary)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (confirmar != true) return;
|
||||
|
||||
final res = await _centinel.openDoor(id);
|
||||
if (!mounted) return;
|
||||
|
||||
final ok = res['ok'] == true;
|
||||
final msg = res['message'] ?? 'Comando ejecutado';
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
backgroundColor: ok ? const Color(0xFF004D40) : const Color(0xFFB71C1C),
|
||||
content: Row(children: [
|
||||
Icon(ok ? Icons.vpn_key : Icons.warning, color: Colors.white),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(child: Text('$nombre: $msg', style: appLabel(size: 13, color: Colors.white))),
|
||||
]),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
List<Map<String, dynamic>> get _dispositivosFiltrados {
|
||||
return _dispositivos.where((d) {
|
||||
final nombre = (d['name'] ?? '').toString().toLowerCase();
|
||||
final ip = (d['ip'] ?? '').toString().toLowerCase();
|
||||
final marca = (d['brand'] ?? '').toString().toLowerCase();
|
||||
final query = _filtroTexto.toLowerCase();
|
||||
|
||||
final coincideTexto = query.isEmpty || nombre.contains(query) || ip.contains(query) || marca.contains(query);
|
||||
|
||||
final status = (d['status'] ?? 'offline').toString().toLowerCase();
|
||||
final coincideEstado = _filtroEstado == 'todos' || status == _filtroEstado;
|
||||
|
||||
return coincideTexto && coincideEstado;
|
||||
}).toList();
|
||||
}
|
||||
|
||||
IconData _iconoPorTipo(String tipo) {
|
||||
final t = tipo.toLowerCase();
|
||||
if (t.contains('facial') || t.contains('biométrico')) return Icons.face;
|
||||
if (t.contains('vehicular') || t.contains('barrera')) return Icons.directions_car;
|
||||
if (t.contains('cerradura')) return Icons.lock;
|
||||
return Icons.door_front_door_outlined;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SingleChildScrollView(
|
||||
primary: false,
|
||||
padding: const EdgeInsets.all(32),
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text('Dispositivos', style: appHeadline(size: 28, weight: FontWeight.w800)),
|
||||
const SizedBox(height: 8),
|
||||
Text('Dispositivos Hikvision registrados en Centinel', style: appLabel(size: 14)),
|
||||
// Encabezado
|
||||
Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
|
||||
Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text('Dispositivos de Seguridad', style: appHeadline(size: 26, weight: FontWeight.w800)),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'Control de acceso Hikvision ISAPI y cerraduras inteligentes Tuya vía Centinel',
|
||||
style: appLabel(size: 14),
|
||||
),
|
||||
]),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.refresh, color: AppColors.primary),
|
||||
tooltip: 'Actualizar telemetría',
|
||||
onPressed: _cargarDispositivos,
|
||||
),
|
||||
]),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// Filtros y búsqueda
|
||||
Row(children: [
|
||||
Expanded(
|
||||
child: TextField(
|
||||
decoration: InputDecoration(
|
||||
hintText: 'Buscar por nombre, IP o marca...',
|
||||
hintStyle: appLabel(size: 13, color: AppColors.outline),
|
||||
prefixIcon: const Icon(Icons.search, color: AppColors.outline, size: 20),
|
||||
filled: true,
|
||||
fillColor: AppColors.surfaceLow,
|
||||
isDense: true,
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: BorderSide.none),
|
||||
),
|
||||
style: appLabel(size: 13, color: AppColors.onSurface),
|
||||
onChanged: (v) => setState(() => _filtroTexto = v),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
DropdownButton<String>(
|
||||
value: _filtroEstado,
|
||||
dropdownColor: AppColors.surfaceHigh,
|
||||
underline: const SizedBox(),
|
||||
items: const [
|
||||
DropdownMenuItem(value: 'todos', child: Text('Todos los estados')),
|
||||
DropdownMenuItem(value: 'online', child: Text('En línea (Online)')),
|
||||
DropdownMenuItem(value: 'offline', child: Text('Desconectados')),
|
||||
],
|
||||
style: appLabel(size: 13, color: AppColors.onSurface),
|
||||
onChanged: (v) {
|
||||
if (v != null) setState(() => _filtroEstado = v);
|
||||
},
|
||||
),
|
||||
]),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Contenido
|
||||
if (_cargando)
|
||||
const Center(child: Padding(padding: EdgeInsets.all(48), child: CircularProgressIndicator()))
|
||||
else if (_dispositivosFiltrados.isEmpty)
|
||||
Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(48),
|
||||
child: Column(children: [
|
||||
const Icon(Icons.devices_other, size: 48, color: AppColors.outline),
|
||||
const SizedBox(height: 12),
|
||||
Text('No se encontraron dispositivos', style: appHeadline(size: 16)),
|
||||
]),
|
||||
),
|
||||
)
|
||||
else
|
||||
LayoutBuilder(builder: (ctx, constraints) {
|
||||
// Diseño adaptativo de tarjetas
|
||||
final columnas = constraints.maxWidth > 900 ? 2 : 1;
|
||||
return GridView.builder(
|
||||
primary: false,
|
||||
shrinkWrap: true,
|
||||
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
|
||||
crossAxisCount: columnas,
|
||||
crossAxisSpacing: 16,
|
||||
mainAxisSpacing: 16,
|
||||
childAspectRatio: constraints.maxWidth > 900 ? 2.6 : 2.2,
|
||||
),
|
||||
itemCount: _dispositivosFiltrados.length,
|
||||
itemBuilder: (ctx, i) {
|
||||
final dev = _dispositivosFiltrados[i];
|
||||
final id = dev['id'] as int;
|
||||
final nombre = dev['name'] ?? 'Dispositivo #$id';
|
||||
final marca = dev['brand'] ?? 'Hikvision';
|
||||
final ip = dev['ip'] ?? '0.0.0.0';
|
||||
final puerto = dev['port'] ?? 8000;
|
||||
final tipo = dev['deviceType'] ?? 'Acceso';
|
||||
final status = (dev['status'] ?? 'offline').toString().toLowerCase();
|
||||
final isOnline = status == 'online';
|
||||
final ultima = dev['lastConnection'] ?? 'N/A';
|
||||
final probando = _probandoConexion[id] == true;
|
||||
|
||||
return Card(
|
||||
color: AppColors.surfaceLow,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
side: BorderSide(
|
||||
color: isOnline ? AppColors.clienteOk.withOpacity(0.3) : AppColors.outlineVariant,
|
||||
width: 1,
|
||||
),
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Row(children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
color: isOnline ? AppColors.primaryContainer : AppColors.surfaceHighest,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Icon(_iconoPorTipo(tipo), color: isOnline ? AppColors.primary : AppColors.outline, size: 22),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text(nombre, style: appHeadline(size: 15), overflow: TextOverflow.ellipsis),
|
||||
const SizedBox(height: 2),
|
||||
Text('$tipo · $marca', style: appLabel(size: 12)),
|
||||
]),
|
||||
),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: isOnline ? AppColors.clienteOk.withOpacity(0.15) : AppColors.outlineVariant.withOpacity(0.3),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Row(mainAxisSize: MainAxisSize.min, children: [
|
||||
Container(
|
||||
width: 8,
|
||||
height: 8,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: isOnline ? AppColors.clienteOk : AppColors.outline,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Text(
|
||||
isOnline ? 'ONLINE' : 'OFFLINE',
|
||||
style: appHeadline(size: 11, color: isOnline ? AppColors.clienteOk : AppColors.outline),
|
||||
),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
const Spacer(),
|
||||
// Comentario explicativo: Optimización con const en iconos para evitar reconstrucciones innecesarias según reglas de linter.
|
||||
Row(children: [
|
||||
const Icon(Icons.lan_outlined, size: 14, color: AppColors.outline),
|
||||
const SizedBox(width: 4),
|
||||
Text('$ip:$puerto', style: appLabel(size: 12)),
|
||||
const SizedBox(width: 16),
|
||||
const Icon(Icons.access_time, size: 14, color: AppColors.outline),
|
||||
const SizedBox(width: 4),
|
||||
Text(ultima, style: appLabel(size: 12)),
|
||||
]),
|
||||
const SizedBox(height: 12),
|
||||
Row(mainAxisAlignment: MainAxisAlignment.end, children: [
|
||||
OutlinedButton.icon(
|
||||
style: OutlinedButton.styleFrom(
|
||||
side: const BorderSide(color: AppColors.outlineVariant),
|
||||
visualDensity: VisualDensity.compact,
|
||||
),
|
||||
icon: probando
|
||||
? const SizedBox(width: 12, height: 12, child: CircularProgressIndicator(strokeWidth: 2))
|
||||
: const Icon(Icons.network_check, size: 15, color: AppColors.secondary),
|
||||
label: Text('Test', style: appLabel(size: 12, color: AppColors.secondary)),
|
||||
onPressed: probando ? null : () => _probarConexion(id, nombre),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
ElevatedButton.icon(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: isOnline ? AppColors.primaryContainer : AppColors.surfaceHighest,
|
||||
foregroundColor: isOnline ? AppColors.primary : AppColors.outline,
|
||||
visualDensity: VisualDensity.compact,
|
||||
),
|
||||
icon: const Icon(Icons.lock_open, size: 15),
|
||||
label: Text('Abrir Puerta', style: appHeadline(size: 12)),
|
||||
onPressed: isOnline ? () => _confirmarApertura(id, nombre) : null,
|
||||
),
|
||||
]),
|
||||
]),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user