using System.ComponentModel; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using CommunityToolkit.Mvvm.ComponentModel; using LibS7Adv; using CtrEditor.Simulacion; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; using CtrEditor.FuncionesBase; using System.Text.Json.Serialization; using Siemens.Simatic.Simulation.Runtime; namespace CtrEditor.ObjetosSim { /// /// Interaction logic for ucTransporteGuias.xaml /// public partial class osTransporteGuias : osBase, IosBase { private osBase Motor = null; private simTransporte? SimGeometria; private simGuia? Guia_Superior; private simGuia? Guia_Inferior; public static string NombreClase() { return "Transporte con Guías"; } private string nombre = NombreClase(); [property: Category("Identificación")] [property: Description("Nombre identificativo del objeto")] [property: Name("Nombre")] public override string Nombre { get => nombre; set => SetProperty(ref nombre, value); } [ObservableProperty] [property: Category("Simulación")] [property: Description("Velocidad actual del transporte")] [property: Name("Velocidad Actual")] public float velocidadActual; partial void OnVelocidadActualChanged(float value) { SetSpeed(); } [ObservableProperty] [property: Category("Configuración")] [property: Description("Invierte el sentido de movimiento")] [property: Name("Invertir Dirección")] bool invertirDireccion; partial void OnInvertirDireccionChanged(bool value) { SetSpeed(); if (_visualRepresentation is ucTransporteGuias uc) { CrearAnimacionStoryBoardTrasnporte(uc.Transporte, InvertirDireccion); ActualizarAnimacionStoryBoardTransporte(VelocidadActual); } } void SetSpeed() { if (InvertirDireccion) SimGeometria?.SetSpeed(-VelocidadActual); else SimGeometria?.SetSpeed(VelocidadActual); ActualizarAnimacionStoryBoardTransporte(VelocidadActual); } [ObservableProperty] [property: Category("Apariencia")] [property: Description("Color del transporte")] [property: Name("Color")] Color color = Colors.Blue; [ObservableProperty] [property: Category("Enlace PLC")] [property: Description("Tag para activar enlace con motor")] [property: Name("Tag Activación Motor")] string tag_ReleActivatedMotor; [ObservableProperty] [property: Category("Enlace PLC")] [property: Description("Motor enlazado al transporte")] [property: Name("Motor Enlazado")] [property: ItemsSource(typeof(osBaseItemsSource))] string id_Motor; [JsonIgnore] private PropertyChangedEventHandler motorPropertyChangedHandler; partial void OnId_MotorChanged(string value) { if (Motor != null && motorPropertyChangedHandler != null) Motor.PropertyChanged -= motorPropertyChangedHandler; if (_mainViewModel != null && !string.IsNullOrEmpty(value)) { Motor = (osVMmotorSim)_mainViewModel.ObjetosSimulables.FirstOrDefault(s => s is osVMmotorSim motor && motor.Nombre == value); if (Motor != null) { motorPropertyChangedHandler = (sender, e) => { if (e.PropertyName == nameof(osVMmotorSim.Nombre)) { Id_Motor = ((osVMmotorSim)sender).Nombre; } }; Motor.PropertyChanged += motorPropertyChangedHandler; } } } public override void AltoChanged(float value) { ActualizarGeometrias(); } public override void AnchoChanged(float value) { ActualizarGeometrias(); } public override void AnguloChanged(float value) { ActualizarGeometrias(); } [ObservableProperty] [property: Category("Configuración")] [property: Description("Actuar como freno")] [property: Name("Es Freno")] public bool esFreno; partial void OnEsFrenoChanged(bool value) { System.Diagnostics.Debug.WriteLine($"[🔧 FRENO CAMBIO] Transporte '{Nombre}' - EsFreno cambiado a: {value}"); ActualizarGeometrias(); // Verificar que la asignación se realizó correctamente if (SimGeometria != null) { System.Diagnostics.Debug.WriteLine($"[✅ FRENO SYNC] SimGeometria.isBrake = {SimGeometria.isBrake}"); } } [ObservableProperty] [property: Category("Configuración")] [property: Description("Coeficiente de fricción")] [property: Name("Coeficiente Fricción")] public float frictionCoefficient; partial void OnFrictionCoefficientChanged(float value) { ActualizarGeometrias(); } [ObservableProperty] [property: Category("Configuración")] [property: Description("Velocidad máxima a 50Hz")] [property: Name("Velocidad Max 50Hz")] public float velMax50hz; [ObservableProperty] [property: Category("Configuración")] [property: Description("Tiempo de rampa")] [property: Name("Tiempo Rampa")] public float tiempoRampa; [ObservableProperty] [property: Category("Información")] [property: Description("Estado de marcha")] [property: Name("En Marcha")] public bool esMarcha; [ObservableProperty] [property: Category("Información")] [property: Description("Información sobre botellas en el transporte con freno")] [property: Name("Info Botellas Freno")] public string infoBotellasFreno = "Sin información"; /// /// Actualiza la información de botellas en el transporte con freno /// public void ActualizarInfoBotellasFreno() { if (SimGeometria?.isBrake == true && simulationManager != null) { // Contar botellas marcadas como en transporte con freno var botellasEnFreno = simulationManager.Cuerpos .OfType() .Where(b => b.isOnBrakeTransport) .Count(); InfoBotellasFreno = $"Botellas con freno: {botellasEnFreno}"; } else if (SimGeometria?.isBrake == false) { InfoBotellasFreno = "Transporte SIN freno"; } else { InfoBotellasFreno = "Sin información"; } } [ObservableProperty] [property: Category("Configuración")] [property: Description("Distancia entre guías")] [property: Name("Distancia")] private float distance; partial void OnDistanceChanged(float value) { ActualizarGeometrias(); } [ObservableProperty] [property: Category("Configuración")] [property: Description("Alto de las guías")] [property: Name("Alto Guía")] private float altoGuia; partial void OnAltoGuiaChanged(float value) { ActualizarGeometrias(); } private void ActualizarGeometrias() { if (_visualRepresentation is ucTransporteGuias uc) { UpdateRectangle(SimGeometria, uc.Transporte, Alto, Ancho, Angulo); // Actualizar guías con método específico para transporte UpdateTransportGuide(Guia_Superior, uc.GuiaSuperior, isTopGuide: true); UpdateTransportGuide(Guia_Inferior, uc.GuiaInferior, isTopGuide: false); if (SimGeometria != null) { SimGeometria.TransportWithGuides = true; SimGeometria.DistanceGuide2Guide = Distance; SimGeometria.isBrake = EsFreno; // Usar propiedad generada SimGeometria.Friction = FrictionCoefficient; // Usar propiedad generada System.Diagnostics.Debug.WriteLine($"[🔄 ACTUALIZAR GEOMETRIAS] Transporte '{Nombre}' - TransportWithGuides={SimGeometria.TransportWithGuides}, DistanceGuide2Guide={SimGeometria.DistanceGuide2Guide:F3}, isBrake={SimGeometria.isBrake}, Friction={SimGeometria.Friction:F3}, Speed={SimGeometria.Speed:F1}"); // Actualizar información de botellas si es un transporte con freno ActualizarInfoBotellasFreno(); } SetSpeed(); } } /// /// Actualiza una guía específica del transporte (superior o inferior) /// /// Objeto de simulación de la guía /// Rectángulo WPF de la guía /// true para guía superior, false para inferior private void UpdateTransportGuide(simGuia simGuia, System.Windows.Shapes.Rectangle wpfRect, bool isTopGuide) { if (simGuia != null && wpfRect != null) { // Actualizar propiedades específicas de la guía simGuia.UpdateProperties(Ancho, AltoGuia, Angulo); // Calcular posición usando el rectángulo WPF actual var topLeft2D = GetRectangleTopLeft(wpfRect); // Crear/actualizar la guía con las dimensiones correctas simGuia.Create(Ancho, AltoGuia, topLeft2D, Angulo); System.Diagnostics.Debug.WriteLine($"[UpdateTransportGuide] {(isTopGuide ? "Superior" : "Inferior")} - Pos: ({topLeft2D.X:F3}, {topLeft2D.Y:F3}), Ancho: {Ancho:F3}, Alto: {AltoGuia:F3}, Ángulo: {Angulo:F1}°"); } } /// /// Crea una guía específica del transporte (superior o inferior) /// /// Rectángulo WPF de la guía /// true para guía superior, false para inferior /// Objeto simGuia creado private simGuia CreateTransportGuide(System.Windows.Shapes.Rectangle wpfRect, bool isTopGuide) { if (wpfRect != null) { // Calcular posición usando el rectángulo WPF actual var topLeft2D = GetRectangleTopLeft(wpfRect); // Crear la guía con las dimensiones del transporte var simGuia = simulationManager.AddLine(Ancho, AltoGuia, topLeft2D, Angulo); System.Diagnostics.Debug.WriteLine($"[CreateTransportGuide] {(isTopGuide ? "Superior" : "Inferior")} creada - Pos: ({topLeft2D.X:F3}, {topLeft2D.Y:F3}), Ancho: {Ancho:F3}, Alto: {AltoGuia:F3}, Ángulo: {Angulo:F1}°"); return simGuia; } return null; } public override void OnMoveResizeRotate() { ActualizarGeometrias(); } public osTransporteGuias() { Ancho = 1; Alto = 0.10f; AltoGuia = 0.03f; Distance = 0.5f; Tag_ReleActivatedMotor = "1"; } public override void UpdateGeometryStart() { // Se llama antes de la simulacion ActualizarGeometrias(); } public override void SimulationStop() { // Se llama al detener la simulacion ActualizarAnimacionStoryBoardTransporte(VelocidadActual); } public override void UpdatePLC(PLCViewModel plc, int elapsedMilliseconds) { if (Motor != null) if (Motor is osVMmotorSim id_motor) if (LeerBitTag(Tag_ReleActivatedMotor)) VelocidadActual = id_motor.Velocidad; else VelocidadActual = 0; // Actualizar información de botellas en tiempo real si es un transporte con freno if (EsFreno) { ActualizarInfoBotellasFreno(); } } public override void ucLoaded() { // El UserControl ya se ha cargado y podemos obtener las coordenadas para // crear el objeto de simulacion base.ucLoaded(); // El UserControl ya se ha cargado y podemos obtener las coordenadas para // crear el objeto de simulacion if (_visualRepresentation is ucTransporteGuias uc) { SimGeometria = AddRectangle(simulationManager, uc.Transporte, Alto, Ancho, Angulo); // CORREGIR: Asegurar que todas las propiedades se inicialicen correctamente if (SimGeometria != null) { SimGeometria.TransportWithGuides = true; // Siempre true para TransporteGuias SimGeometria.DistanceGuide2Guide = Distance; // Usar Distance en lugar de Alto SimGeometria.isBrake = EsFreno; // Usar propiedad generada SimGeometria.Friction = FrictionCoefficient; // Usar propiedad generada } // Crear guías usando método específico para transporte Guia_Superior = CreateTransportGuide(uc.GuiaSuperior, isTopGuide: true); Guia_Inferior = CreateTransportGuide(uc.GuiaInferior, isTopGuide: false); CrearAnimacionStoryBoardTrasnporte(uc.Transporte, InvertirDireccion); SetSpeed(); // Aplicar velocidad inicial } OnId_MotorChanged(Id_Motor); // Link Id_Motor = Motor } public override void ucUnLoaded() { // El UserControl se esta eliminando // eliminar el objeto de simulacion simulationManager.Remove(SimGeometria); simulationManager.Remove(Guia_Superior); simulationManager.Remove(Guia_Inferior); } } public partial class ucTransporteGuias : UserControl, IDataContainer { public osBase? Datos { get; set; } public int zIndex_fromFrames { get; set; } public ucTransporteGuias() { InitializeComponent(); this.Loaded += OnLoaded; this.Unloaded += OnUnloaded; } private void OnLoaded(object sender, RoutedEventArgs e) { Datos?.ucLoaded(); } private void OnUnloaded(object sender, RoutedEventArgs e) { Datos?.ucUnLoaded(); } public void Highlight(bool State) { } public ZIndexEnum ZIndex_Base() { return ZIndexEnum.Estaticos; } } }