agrobot_base/AgroBase/AgroBase/Models/Modules/SensoriamentoModel.cs

1940 lines
70 KiB
C#
Raw Normal View History

2024-12-03 20:55:25 +00:00
using AgroBase.Forms.IHM;
using AgroBase.Services;
using Newtonsoft.Json;
2023-11-30 00:41:22 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
2024-07-26 19:54:25 +00:00
using static AgroBase.Models.Enums;
2025-04-09 21:11:40 +00:00
using System.IO.Ports;
using System.Globalization;
2023-11-30 00:41:22 +00:00
namespace AgroBase.Models.Modules
{
public class SensoriamentoModel : DispositivoBaseModel
2023-11-30 00:41:22 +00:00
{
2025-04-09 21:11:40 +00:00
public T_Code Dispositivo { get; set; } = T_Code.Sen;
public string Modulo_ID { get; set; } = T_Code.Sen.ToString();
2025-04-09 21:11:40 +00:00
public byte _EnderecoCAN { get; set; } = 0x11;
public int _TaxaAmostragem { get; set; } = 1000;
public bool RequisitarDados { get; set; } = true;
public static int PingsConsiderarConexao { get; set; } = 5;
public static int TempoLimiteConexao
{
2025-04-09 21:11:40 +00:00
get
{
2025-04-09 21:11:40 +00:00
return PingsConsiderarConexao * (Variaveis.OperacaoEmAndamento?.DispSen?._TaxaAmostragem ?? 1000);
}
}
2025-04-09 21:11:40 +00:00
public bool Conectado
{
get
{
2025-04-09 21:11:40 +00:00
return DadosLeitura.UltimoComandoRespondido.AddMilliseconds(TempoLimiteConexao * 2) >= DateTime.Now; // DadosLeitura.Conectado &&
}
}
2025-04-09 21:11:40 +00:00
2024-04-15 10:57:37 +00:00
public static PinoutDataModel Pinout { get; set; }
2024-04-01 11:03:25 +00:00
public static List<FuncoesPinout> Funcoes { get; set; } = new List<FuncoesPinout>()
{
FuncoesPinout.SDA,
FuncoesPinout.SCL,
};
2023-11-30 00:41:22 +00:00
public List<SensorModel> Sensores { get; set; }
2024-07-12 19:44:56 +00:00
public List<SensorSinaleiroModel> Sinaleiros { get; set; }
2024-07-18 18:00:14 +00:00
public List<SensorReleModel> Reles { get; set; }
2024-07-24 20:04:55 +00:00
public List<SensorServoModel> Servos { get; set; }
2024-07-12 19:44:56 +00:00
public string CameraID_Caminho { get; set; } = "";
public List<string> CameraID_Solo { get; set; } = new List<string>();
2024-10-29 19:53:27 +00:00
public UltrasonicA05Configuracoes ConfiguracaoSensorUltrassom { get; set; }
2024-05-24 20:05:51 +00:00
public double BateriaCargaConsumida { get; set; }
public SensoriamentoMensagemJsonModel DadosLeitura { get; set; } = new SensoriamentoMensagemJsonModel();
2025-04-09 21:11:40 +00:00
private SenHandler _SenHandler = new SenHandler();
public LoRaParametrosModel LoRaParametrosBase { get; set; } = new LoRaParametrosModel()
{
address = 0x01,
channel = 0x17,
tranMode = LoRaService.CodigosTipoTransmissao["Fixed"],
baudRate = LoRaService.CodigosBaudRates[9600],
airRate = LoRaService.CodigosAirRates[2.4],
packetSize = LoRaService.CodigosPacketSizes[200],
worCycle = LoRaService.CodigosWorCycles[4000],
power = LoRaService.CodigosPowers[22],
};
2023-11-30 00:41:22 +00:00
public AsyncTaskTimerModel tmrRegistrador;
2024-12-05 12:52:28 +00:00
private int _TempoReconexaoComponentes = 5;
private int _VezesLeituraReconexao = 0;
2023-11-30 00:41:22 +00:00
public static SensoriamentoModel CarregarParametrosIniciais()
{
var obj = new SensoriamentoModel()
2023-11-30 00:41:22 +00:00
{
2025-04-09 21:11:40 +00:00
_EnderecoCAN = 0x11,
_TaxaAmostragem = 1000,
RequisitarDados = true,
CameraID_Caminho = "",
CameraID_Solo = new List<string>(),
Sinaleiros = new List<SensorSinaleiroModel>()
{
new SensorSinaleiroModel()
{
ID = "LEDMN",
2025-04-09 21:11:40 +00:00
ID_Num = 21,
Descricao = "Sinaleiro indicação de modo Manual ativo",
Componente = S_Code.sLED,
Funcoes = new List<FuncoesPinout>()
{
FuncoesPinout.Sinaleiro,
},
2024-07-26 19:54:25 +00:00
Comportamento = VariaveisEquipamento.ComportamentoPorStatus(StatusOperacao.NaoIniciado)
},
new SensorSinaleiroModel()
{
ID = "LEDAT",
2025-04-09 21:11:40 +00:00
ID_Num = 22,
Descricao = "Sinaleiro indicação de modo Automático ativo",
Componente = S_Code.sLED,
Funcoes = new List<FuncoesPinout>()
{
FuncoesPinout.Sinaleiro,
2024-04-26 19:34:58 +00:00
},
2024-07-26 19:54:25 +00:00
Comportamento = VariaveisEquipamento.ComportamentoPorStatus(StatusOperacao.NaoIniciado)
},
new SensorSinaleiroModel()
{
ID = "LEDOP",
2025-04-09 21:11:40 +00:00
ID_Num = 23,
Descricao = "Sinaleiro indicação do status da operação ativa",
Componente = S_Code.sLED,
Funcoes = new List<FuncoesPinout>()
{
FuncoesPinout.Sinaleiro,
2024-04-26 19:34:58 +00:00
},
2024-07-26 19:54:25 +00:00
Comportamento = VariaveisEquipamento.ComportamentoPorStatus(StatusOperacao.NaoIniciado)
},
},
2023-11-30 00:41:22 +00:00
Sensores = new List<SensorModel>()
{
new SensorModel()
{
2024-01-18 19:22:28 +00:00
ID = "TMVET",
Descricao = "Temperatura Motor Esquerdo Trás",
2025-04-09 21:11:40 +00:00
ID_Num = 1,
Componente = S_Code.sTMP,
Aferir = true,
2024-01-18 19:22:28 +00:00
Funcoes = new List<FuncoesPinout>()
{
FuncoesPinout.TMP,
},
2024-01-31 17:23:52 +00:00
UnidadeMedida = "ºC",
2025-04-09 21:11:40 +00:00
Parametros = new List<SensorParametroModel>()
{
2025-04-09 21:11:40 +00:00
new SensorParametroModel()
{
Descricao = "Offset",
Valor = "0",
QtdBytes = 2,
Escalar = false,
Enviar = false,
}
}
2024-01-18 19:22:28 +00:00
},
new SensorModel()
{
ID = "TMVEF",
Descricao = "Temperatura Motor Esquerdo Frente",
2025-04-09 21:11:40 +00:00
ID_Num = 2,
2024-01-18 19:22:28 +00:00
Componente = S_Code.sTMP,
Aferir = true,
Funcoes = new List<FuncoesPinout>()
{
FuncoesPinout.TMP,
},
2024-01-31 17:23:52 +00:00
UnidadeMedida = "ºC",
2025-04-09 21:11:40 +00:00
Parametros = new List<SensorParametroModel>()
{
2025-04-09 21:11:40 +00:00
new SensorParametroModel()
{
Descricao = "Offset",
Valor = "0",
QtdBytes = 2,
Escalar = false,
Enviar = false,
}
}
2024-01-18 19:22:28 +00:00
},
new SensorModel()
{
ID = "TMVDT",
Descricao = "Temperatura Motor Direito Trás",
2025-04-09 21:11:40 +00:00
ID_Num = 3,
2024-01-18 19:22:28 +00:00
Componente = S_Code.sTMP,
Aferir = true,
Funcoes = new List<FuncoesPinout>()
{
FuncoesPinout.TMP,
},
2024-01-31 17:23:52 +00:00
UnidadeMedida = "ºC",
2025-04-09 21:11:40 +00:00
Parametros = new List<SensorParametroModel>()
{
2025-04-09 21:11:40 +00:00
new SensorParametroModel()
{
Descricao = "Offset",
Valor = "0",
QtdBytes = 2,
Escalar = false,
Enviar = false,
}
}
2024-01-18 19:22:28 +00:00
},
new SensorModel()
{
ID = "TMVDF",
Descricao = "Temperatura Motor Direito Frente",
2025-04-09 21:11:40 +00:00
ID_Num = 4,
2024-01-18 19:22:28 +00:00
Componente = S_Code.sTMP,
Aferir = true,
Funcoes = new List<FuncoesPinout>()
{
FuncoesPinout.TMP,
},
2024-01-31 17:23:52 +00:00
UnidadeMedida = "ºC",
2025-04-09 21:11:40 +00:00
Parametros = new List<SensorParametroModel>()
{
new SensorParametroModel()
{
Descricao = "Offset",
Valor = "0",
QtdBytes = 2,
Escalar = false,
Enviar = false,
}
}
},
new SensorModel()
{
ID = "TBAT",
Descricao = "Temperatura da bateria",
ID_Num = 5,
Componente = S_Code.sTMP,
Aferir = false,
Funcoes = new List<FuncoesPinout>()
{
2025-04-09 21:11:40 +00:00
FuncoesPinout.TMP,
},
2025-04-09 21:11:40 +00:00
UnidadeMedida = "ºC",
Parametros = new List<SensorParametroModel>()
{
new SensorParametroModel()
{
Descricao = "Offset",
Valor = "0",
QtdBytes = 2,
Escalar = false,
Enviar = false,
}
}
2024-01-18 19:22:28 +00:00
},
2025-04-09 21:11:40 +00:00
new SensorModel()
2024-01-18 19:22:28 +00:00
{
2024-04-15 10:57:37 +00:00
ID = "AB3V",
Descricao = "Corrente no Barramento 3V",
2025-04-09 21:11:40 +00:00
ID_Num = 11,
2023-11-30 00:41:22 +00:00
Componente = S_Code.sCOR,
2025-04-09 21:11:40 +00:00
Aferir = false,
2023-11-30 00:41:22 +00:00
Funcoes = new List<FuncoesPinout>()
{
FuncoesPinout.I2C,
2024-01-23 17:10:34 +00:00
},
2025-04-09 21:11:40 +00:00
UnidadeMedida = "mA",
Parametros = new List<SensorParametroModel>()
2024-01-23 17:10:34 +00:00
{
2025-04-09 21:11:40 +00:00
new SensorParametroModel()
{
Descricao = "Endereço I2C",
Valor = "0x45",
QtdBytes = 1,
Escalar = false,
Enviar = true
},
new SensorParametroModel()
{
Descricao = "Corrente Máx",
Valor = ((int)INA219Corrente.C_3_2).ToString(),
QtdBytes = 1,
Escalar = false,
Enviar = true
},
}
},
new SensorModel()
{
2024-04-15 10:57:37 +00:00
ID = "AB5V",
Descricao = "Corrente no Barramento 5V",
2025-04-09 21:11:40 +00:00
ID_Num = 12,
Componente = S_Code.sCOR,
Aferir = true,
Funcoes = new List<FuncoesPinout>()
{
FuncoesPinout.I2C,
},
2025-04-09 21:11:40 +00:00
UnidadeMedida = "mA",
Parametros = new List<SensorParametroModel>()
{
2025-04-09 21:11:40 +00:00
new SensorParametroModel()
{
Descricao = "Endereço I2C",
Valor = "0x41",
QtdBytes = 1,
Escalar = false,
Enviar = true
},
new SensorParametroModel()
{
Descricao = "Corrente Máx",
Valor = ((int)INA219Corrente.C_3_2).ToString(),
QtdBytes = 1,
Escalar = false,
Enviar = true
},
}
},
new SensorModel()
{
2024-04-15 10:57:37 +00:00
ID = "AB7V2",
Descricao = "Corrente no Barramento 7,2V",
2025-04-09 21:11:40 +00:00
ID_Num = 13,
Componente = S_Code.sCOR,
Aferir = true,
Funcoes = new List<FuncoesPinout>()
{
FuncoesPinout.I2C,
},
2025-04-09 21:11:40 +00:00
UnidadeMedida = "mA",
Parametros = new List<SensorParametroModel>()
{
2025-04-09 21:11:40 +00:00
new SensorParametroModel()
{
Descricao = "Endereço I2C",
Valor = "0x44",
QtdBytes = 1,
Escalar = false,
Enviar = true
},
new SensorParametroModel()
{
Descricao = "Corrente Máx",
Valor = ((int)INA219Corrente.C_50).ToString(),
QtdBytes = 1,
Escalar = false,
Enviar = true
},
}
},
new SensorModel()
{
2024-04-15 10:57:37 +00:00
ID = "AB12V",
Descricao = "Corrente no Barramento 12V",
2025-04-09 21:11:40 +00:00
ID_Num = 14,
Componente = S_Code.sCOR,
Aferir = true,
Funcoes = new List<FuncoesPinout>()
{
FuncoesPinout.I2C,
},
2025-04-09 21:11:40 +00:00
UnidadeMedida = "mA",
Parametros = new List<SensorParametroModel>()
{
2025-04-09 21:11:40 +00:00
new SensorParametroModel()
{
Descricao = "Endereço I2C",
Valor = "0x40",
QtdBytes = 1,
Escalar = false,
Enviar = true
},
new SensorParametroModel()
{
Descricao = "Corrente Máx",
Valor = ((int)INA219Corrente.C_100).ToString(),
QtdBytes = 1,
Escalar = false,
Enviar = true
},
}
2024-01-24 12:53:39 +00:00
},
2025-04-09 21:11:40 +00:00
2024-07-24 20:04:55 +00:00
/*new SensorModel()
{
ID = "SUESQ",
Descricao = "Sensor Ultrassom Esquerdo",
Prioridade = 2,
Componente = S_Code.sULT,
Aferir = true,
Inicializado = false,
Testando = false,
Funcoes = new List<FuncoesPinout>()
{
FuncoesPinout.Echo,
FuncoesPinout.Trigger,
},
DelayAmostragem = 1000,
UnidadeMedida = "cm",
Parametros = new List<string[]>(),
},
new SensorModel()
{
ID = "SUDIR",
Descricao = "Sensor Ultrassom Direito",
Prioridade = 2,
Componente = S_Code.sULT,
Aferir = true,
Inicializado = false,
Testando = false,
Funcoes = new List<FuncoesPinout>()
{
FuncoesPinout.Echo,
FuncoesPinout.Trigger,
},
DelayAmostragem = 1000,
UnidadeMedida = "cm",
Parametros = new List<string[]>(),
},
2024-03-13 18:33:13 +00:00
new SensorModel()
{
2024-04-26 19:34:58 +00:00
ID = "SMAG",
2024-03-13 18:33:13 +00:00
Descricao = "Sensor Magnetômetro",
Prioridade = 15,
Componente = S_Code.sMAG,
Aferir = true,
Inicializado = false,
Testando = false,
Funcoes = new List<FuncoesPinout>()
{
FuncoesPinout.I2C,
},
DelayAmostragem = 500,
UnidadeMedida = "º",
Parametros = new List<string[]>(),
},
2024-04-15 10:57:37 +00:00
new SensorModel()
{
ID = "SNR_F",
Descricao = "Sensor Sonar Frontal",
Prioridade = 20,
Componente = S_Code.sSNR,
Aferir = true,
Inicializado = false,
Testando = false,
Funcoes = new List<FuncoesPinout>()
{
FuncoesPinout.Echo,
FuncoesPinout.Trigger,
FuncoesPinout.ServoX,
FuncoesPinout.ServoY,
},
DelayAmostragem = 1000,
UnidadeMedida = "cm/º",
Parametros = new List<string[]>()
{
new string[] { "Angulo X Acrescentar", "5" },
new string[] { "Angulo Y Acrescentar", "30" },
},
2024-04-23 11:23:05 +00:00
LimiteMinimo = 40,
LimiteMaximo = 9999,
2024-07-24 20:04:55 +00:00
},*/
2024-04-01 11:03:25 +00:00
},
2024-07-18 18:00:14 +00:00
Reles = new List<SensorReleModel>()
{
new SensorReleModel()
{
ID = "RLLRA",
2025-04-09 21:11:40 +00:00
ID_Num = 31,
2024-07-18 18:00:14 +00:00
Descricao = "Relé modo operação LoRa",
Componente = S_Code.sRLE,
Controlar = true,
AtuacaoNivelAlto = true,
2024-07-18 18:00:14 +00:00
Funcoes = new List<FuncoesPinout>()
{
FuncoesPinout.Rele,
},
StatusControle = Estado.Desligado,
ControleExterno = false,
},
2024-07-24 20:04:55 +00:00
},
Servos = new List<SensorServoModel>()
{
new SensorServoModel()
{
ID = "FRO_ET",
2025-04-09 21:11:40 +00:00
ID_Num = 41,
Descricao = "Freio Motor ET",
Componente = S_Code.sFRO,
Controlar = true,
2024-07-24 20:04:55 +00:00
Funcoes = new List<FuncoesPinout>()
{
FuncoesPinout.ServoFreio,
},
_AnguloControle = 0,
},
new SensorServoModel()
{
ID = "FRO_EF",
2025-04-09 21:11:40 +00:00
ID_Num = 42,
2024-07-24 20:04:55 +00:00
Descricao = "Freio Motor EF",
Componente = S_Code.sFRO,
Controlar = false,
2024-07-24 20:04:55 +00:00
Funcoes = new List<FuncoesPinout>()
{
FuncoesPinout.ServoFreio,
},
_AnguloControle = 0,
},
new SensorServoModel()
{
ID = "FRO_DT",
2025-04-09 21:11:40 +00:00
ID_Num = 43,
2024-07-24 20:04:55 +00:00
Descricao = "Freio Motor DT",
Componente = S_Code.sFRO,
Controlar = true,
2024-07-24 20:04:55 +00:00
Funcoes = new List<FuncoesPinout>()
{
FuncoesPinout.ServoFreio,
},
_AnguloControle = 0,
},
new SensorServoModel()
{
ID = "FRO_DF",
2025-04-09 21:11:40 +00:00
ID_Num = 44,
2024-07-24 20:04:55 +00:00
Descricao = "Freio Motor DF",
Componente = S_Code.sFRO,
Controlar = false,
2024-07-24 20:04:55 +00:00
Funcoes = new List<FuncoesPinout>()
{
FuncoesPinout.ServoFreio,
},
_AnguloControle = 0,
},
2024-07-18 18:00:14 +00:00
}
2023-11-30 00:41:22 +00:00
};
for (int i = 0; i < Variaveis.OperacaoEmAndamento.QuantidadeCamerasSolo; i++)
{
obj.CameraID_Solo.Add("");
}
return obj;
2023-11-30 00:41:22 +00:00
}
2024-12-02 19:12:39 +00:00
public void LimparDados<T>(T _dados)
2024-07-18 18:00:14 +00:00
{
2024-12-02 19:12:39 +00:00
var Dados = _dados as SensoriamentoModel;
Dados.DadosLeitura = new SensoriamentoMensagemJsonModel();
Dados.DadosLeitura.Momento = DateTime.MinValue;
2024-07-24 20:04:55 +00:00
Dados.Reles.ForEach(x =>
{
x.StatusControle = Estado.Desligado;
2024-10-29 19:53:27 +00:00
});
Dados.Servos.ForEach(x =>
{
x._AnguloControle = 0;
2024-10-29 19:53:27 +00:00
});
ReiniciarLeituras(Dados);
}
2024-12-02 19:12:39 +00:00
public void ReiniciarLeituras(SensoriamentoModel Dados)
2024-10-29 19:53:27 +00:00
{
Dados.Reles.ForEach(x =>
{
x.Leitura = null;
2024-07-24 20:04:55 +00:00
});
Dados.Sinaleiros.ForEach(x =>
{
x.Leitura = null;
2024-07-24 20:04:55 +00:00
});
2024-07-18 18:00:14 +00:00
Dados.Sensores.ForEach(x =>
{
x.Leitura = null;
2024-07-18 18:00:14 +00:00
});
2024-07-24 20:04:55 +00:00
Dados.Servos.ForEach(x =>
{
x.Leitura = null;
2024-07-24 20:04:55 +00:00
});
2024-07-18 18:00:14 +00:00
}
2025-04-09 21:11:40 +00:00
public async Task<bool> VerificaPortaSEN(SerialPort porta)
2023-11-30 00:41:22 +00:00
{
2025-04-09 21:11:40 +00:00
if (!CanService.IsConnected)
{
CanService.DefinirPortaCOM(porta);
CanService.RegistrarHandler(Dispositivo, _SenHandler);
}
2025-04-09 21:11:40 +00:00
if (CanService.IsConnected)
{
RequisitarDadosModulo(F_Code.ChkTx);
2025-04-09 21:11:40 +00:00
await Task.Delay(1000);
2025-04-09 21:11:40 +00:00
if (Conectado)
{
DefinirDispositivo();
Variaveis.OperacaoEmAndamento.DispSen?.EnviarProtocolosConfiguracao();
}
}
else
{
return false;
}
2024-07-24 20:04:55 +00:00
2025-04-09 21:11:40 +00:00
if (!CanService.Iniciado)
2024-12-02 19:12:39 +00:00
{
2025-04-09 21:11:40 +00:00
CanService.Fechar();
2024-12-02 19:12:39 +00:00
}
2025-04-09 21:11:40 +00:00
return Conectado;
}
2025-04-09 21:11:40 +00:00
private void DefinirDispositivo()
{
2025-04-09 21:11:40 +00:00
if (!SerialService.DispositivosMapeados.Any(x => x.Dispositivo == Dispositivo && x.Mod_ID == Modulo_ID))
{
SerialService.DispositivosMapeados.Add(new DispositivoDetalhesModel()
{
Endereco = CanService._portName,
Dispositivo = DadosLeitura.Dispositivo,
Erro = false,
Versao = DadosLeitura.Versao.ToString(),
Mod_ID = Modulo_ID,
});
}
}
2025-04-09 21:11:40 +00:00
public void RequisitarDadosModulo(F_Code dado, bool aguardaResposta = true)
{
Variaveis.OperacaoEmAndamento.DispSen?.AdicionarMensagemFila(dado, null, aguardaResposta);
}
2025-04-09 21:11:40 +00:00
public List<byte[]> ProtocoloConfiguracao(bool Conectar)
{
2025-04-09 21:11:40 +00:00
// Inicializar o dicionário
List<byte[]> config = new List<byte[]>();
2024-12-05 17:11:38 +00:00
2025-04-09 21:11:40 +00:00
if (!DadosLeitura.Conectado)
{
// Adicionar configuração do ProtocoloMOD
var protocoloMOD = ModConfig(Conectar);
config.Add(protocoloMOD);
}
2025-04-09 21:11:40 +00:00
// Adicionar configurações dos Sinaleiros
List<byte[]> sinaleirosConfig = SinaleirosConfig(Conectar);
config.AddRange(sinaleirosConfig);
// Adicionar configurações dos Servos
List<byte[]> servosConfig = ServosConfig(Conectar);
config.AddRange(servosConfig);
// Adicionar configurações dos Reles
List<byte[]> relesConfig = RelesConfig(Conectar);
config.AddRange(relesConfig);
// Adicionar configurações dos Sensores que devem ser aferidos
List<byte[]> sensoresConfig = SensoresConfig(Conectar);
config.AddRange(sensoresConfig);
return config;
}
2025-04-09 21:11:40 +00:00
private byte[] ModConfig(bool Conectar)
{
2025-04-09 21:11:40 +00:00
var pinos = PinoutModel.PinoProtocolo(Pinout, Funcoes, false);
2024-12-05 17:11:38 +00:00
2025-04-09 21:11:40 +00:00
var config = new List<byte>
{
(byte)S_Code.sMOD,
(byte)(Conectar ? 1 : 0),
(byte)(_TaxaAmostragem / 10),
(byte)(RequisitarDados ? 1 : 0),
};
config.AddRange(pinos);
2025-04-09 21:11:40 +00:00
return config.ToArray();
}
2025-04-09 21:11:40 +00:00
public List<byte[]> SensoresConfig(bool Conectar)
{
2025-04-09 21:11:40 +00:00
var config = new List<byte[]>();
2024-12-05 17:11:38 +00:00
2025-04-09 21:11:40 +00:00
foreach (var sensor in Sensores.Where(x => x.Aferir && x.Inicializado != Conectar))
{
byte[] payload = sensor.ProtocoloConfiguracao(Pinout, Conectar);
if (payload != null)
{
config.Add(payload);
}
}
2025-04-09 21:11:40 +00:00
return config;
}
2025-04-09 21:11:40 +00:00
private List<byte[]> SinaleirosConfig(bool Conectar)
{
2025-04-09 21:11:40 +00:00
var config = new List<byte[]>();
2024-12-05 17:11:38 +00:00
2025-04-09 21:11:40 +00:00
foreach (var sinaleiro in Sinaleiros.Where(x => x.Inicializado != Conectar))
{
var payload = sinaleiro.ProtocoloConfiguracao(Pinout, Conectar);
if (payload != null)
{
config.Add(payload);
}
}
2025-04-09 21:11:40 +00:00
return config;
2023-11-30 00:41:22 +00:00
}
2025-04-09 21:11:40 +00:00
private List<byte[]> RelesConfig(bool Conectar)
{
2025-04-09 21:11:40 +00:00
var config = new List<byte[]>();
2025-04-09 21:11:40 +00:00
foreach (var rele in Reles.Where(x => x.Controlar /*&& x.Inicializado != Conectar*/))
{
2025-04-09 21:11:40 +00:00
var payload = rele.ProtocoloConfiguracao(Pinout, Conectar);
if (payload != null)
{
config.Add(payload);
}
}
2025-04-09 21:11:40 +00:00
return config;
}
2025-04-09 21:11:40 +00:00
private List<byte[]> ServosConfig(bool Conectar)
2024-07-18 18:00:14 +00:00
{
2025-04-09 21:11:40 +00:00
var config = new List<byte[]>();
foreach (var servo in Servos.Where(x => x.Controlar && x.Inicializado != Conectar))
{
var payload = servo.ProtocoloConfiguracao(Pinout, Conectar);
if (payload != null)
{
config.Add(payload);
}
}
return config;
2024-07-18 18:00:14 +00:00
}
2025-04-09 21:11:40 +00:00
public void RecebeProtocoloModulo(string Protocolo)
2023-11-30 00:41:22 +00:00
{
try
2023-11-30 00:41:22 +00:00
{
if (string.IsNullOrWhiteSpace(Protocolo))
2024-01-18 19:22:28 +00:00
{
Console.WriteLine("Protocolo recebido está vazio ou nulo.");
2024-01-18 19:22:28 +00:00
return;
}
Protocolo = Protocolo.Substring(0, Protocolo.Length - 1);
2024-07-24 20:04:55 +00:00
// Valida se o protocolo possui um formato esperado
if (Protocolo.Length <= 1 || !Protocolo.EndsWith("}"))
2023-11-30 00:41:22 +00:00
{
Console.WriteLine("Protocolo recebido está em um formato inválido.");
2023-11-30 00:41:22 +00:00
return;
}
Console.WriteLine($"JSON recebido: {Protocolo}");
// Tenta desserializar o JSON
var dadosLeitura = JsonConvert.DeserializeObject<SensoriamentoMensagemJsonModel>(Protocolo);
if (dadosLeitura == null)
{
Console.WriteLine("Falha ao desserializar o JSON.");
return;
}
dadosLeitura.Momento = DateTime.Now;
AtualizaDadosComponentes(dadosLeitura);
}
catch (JsonException ex)
{
Console.WriteLine($"Erro ao processar o JSON recebido: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Erro inesperado no processamento do protocolo: {ex.Message}");
}
}
2023-11-30 00:41:22 +00:00
private void AtualizaDadosComponentes(SensoriamentoMensagemJsonModel dadosLeitura)
{
DadosLeitura = dadosLeitura;
2023-11-30 00:41:22 +00:00
if (Variaveis.OperacaoEmAndamento.DispMvd != null)
{
Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.ForEach(Modulo => Modulo.AtualizarSensoresMotor());
2023-11-30 00:41:22 +00:00
}
}
2024-01-03 10:52:37 +00:00
public void IniciarRegistrador()
{
if (!(tmrRegistrador?.IsRunning ?? false))
{
LimparDados(this);
PararRegistrador();
tmrRegistrador = new AsyncTaskTimerModel("tmrRegistrador_" + T_Code.Sen.ToString(), tmrRegistrador_Tick, _TaxaAmostragem);
tmrRegistrador.Start();
}
}
2024-01-03 10:52:37 +00:00
public void PararRegistrador()
{
tmrRegistrador?.Dispose();
2024-01-03 10:52:37 +00:00
}
public async Task tmrRegistrador_Tick()
{
if (Variaveis.Fechando)
{
return;
}
tmrRegistrador.SetInterval(_TaxaAmostragem);
2025-04-09 21:11:40 +00:00
if (false && SerialService.DispositivosMapeados.Any(x => x.Dispositivo == T_Code.Sen) && (_VezesLeituraReconexao >= _TempoReconexaoComponentes))
{
Variaveis.OperacaoEmAndamento.DispSen?.EnviarProtocolosConfiguracao();
_VezesLeituraReconexao = 0;
}
else
{
_VezesLeituraReconexao++;
}
2025-04-09 21:11:40 +00:00
if (DadosLeitura.Conectado)
{
2024-12-03 20:55:25 +00:00
if (RequisitarDados)
{
2025-04-09 21:11:40 +00:00
RequisitarDadosModulo(F_Code.ReqTx, false);
2024-12-03 20:55:25 +00:00
}
VerificaControleLeitura();
}
}
2025-04-09 21:11:40 +00:00
2024-10-03 18:21:30 +00:00
public (bool, List<string>) StatusModulosSEN()
{
var _Sensores = Sensores?.Where(x => x.Aferir).ToList();
var _SensoresComFalha = _Sensores?.Where(x => !x.Inicializado).ToList();
bool _sensoresOperantes = (_SensoresComFalha?.Count() ?? 0) < (_Sensores?.Count() ?? 0);
2024-10-03 18:21:30 +00:00
var _Sinaleiros = Sinaleiros?.ToList();
var _SinaleirosComFalha = _Sinaleiros?.Where(x => !x.Inicializado).ToList();
bool _sinaleirosOperantes = !(_SinaleirosComFalha?.Any() ?? false);
2024-10-03 18:21:30 +00:00
var _Reles = Reles?.Where(x => x.Controlar).ToList();
var _RelesComFalha = _Reles?.Where(x => !x.Inicializado).ToList();
bool _relesOperantes = !(_RelesComFalha?.Any() ?? false);
2024-10-03 18:21:30 +00:00
var _Servos = Servos?.Where(x => x.Controlar).ToList();
var _ServosComFalha = _Servos?.Where(x => !x.Inicializado).ToList();
bool _servosOperantes = !(_ServosComFalha?.Any() ?? false);
2024-10-03 18:21:30 +00:00
bool _sensoriamentoOperante = _sensoresOperantes && _relesOperantes && _servosOperantes;
List<string> ModsComFalha =
(_SensoresComFalha?.Select(x => x.ID) ?? new List<string>())
.Union(_SinaleirosComFalha?.Select(x => x.ID) ?? new List<string>())
.Union(_RelesComFalha?.Select(x => x.ID) ?? new List<string>())
.Union(_ServosComFalha?.Select(x => x.ID) ?? new List<string>())
2024-10-03 18:21:30 +00:00
.ToList();
return (_sensoriamentoOperante, ModsComFalha);
}
2024-12-03 20:55:25 +00:00
private void VerificaControleLeitura()
{
if (!frmDiagnosticos.Diagnosticando)
{
var ledOP = Sinaleiros.FirstOrDefault(x => x.ID == "LEDOP" && x.Inicializado);
var ledAT = Sinaleiros.FirstOrDefault(x => x.ID == "LEDAT" && x.Inicializado);
var ledMN = Sinaleiros.FirstOrDefault(x => x.ID == "LEDMN" && x.Inicializado);
var comportamento = VariaveisEquipamento.ComportamentoPorStatus();
if (ledOP != null && (!ledOP.Comportamento.Equals(comportamento) || (ledOP.LeituraComando != comportamento.statusLED)))
{
GeneralJoystick.EnviarComandoSensoriamento(S_Code.sLED, ledOP.ID, comportamento);
}
var statusLedAt = Variaveis.OperacaoEmAndamento.Modo == ModoOperacao.MapaGPS ? StatusLED.Aceso : StatusLED.Apagado;
if (ledAT != null && (!ledAT.Comportamento.statusLED.Equals(statusLedAt) || (ledAT.LeituraComando != statusLedAt)))
{
ledAT.Comportamento.statusLED = statusLedAt;
GeneralJoystick.EnviarComandoSensoriamento(S_Code.sLED, ledAT.ID, ledAT.Comportamento);
}
var statusLedMn = Variaveis.OperacaoEmAndamento.Modo == ModoOperacao.Manual ? StatusLED.Aceso : StatusLED.Apagado;
if (ledMN != null && (!ledMN.Comportamento.statusLED.Equals(statusLedMn) || (ledMN.LeituraComando != statusLedMn)))
{
ledMN.Comportamento.statusLED = statusLedMn;
GeneralJoystick.EnviarComandoSensoriamento(S_Code.sLED, ledMN.ID, ledMN.Comportamento);
}
foreach (var rele in Reles.Where(x => x.Controlar && x.Inicializado && !x.ControleExterno))
2024-12-03 20:55:25 +00:00
{
2024-12-05 12:52:28 +00:00
if (rele.StatusControle != rele.LeituraEstado)
{
GeneralJoystick.EnviarComandoSensoriamento(S_Code.sRLE, rele.ID, rele.StatusControle);
}
2024-12-03 20:55:25 +00:00
}
2024-12-05 12:52:28 +00:00
foreach (var servo in Servos.Where(x => x.Controlar && x.Inicializado))
2024-12-03 20:55:25 +00:00
{
2024-12-05 12:52:28 +00:00
if (servo._AnguloControle != servo.LeituraAngulo)
{
GeneralJoystick.EnviarComandoSensoriamento(S_Code.sFRO, servo.ID, servo._AnguloControle);
}
2024-12-03 20:55:25 +00:00
}
}
}
2024-10-03 18:21:30 +00:00
2023-11-30 00:41:22 +00:00
}
public class SensorModel
{
public string ID { get; set; }
2025-04-09 21:11:40 +00:00
public int ID_Num { get; set; }
2023-11-30 00:41:22 +00:00
public string Descricao { get; set; }
public S_Code Componente { get; set; }
public bool Aferir { get; set; } = false;
private dynamic _leitura = null;
public dynamic Leitura
{
get
{
switch (Componente)
{
case S_Code.sTMP:
_leitura = Variaveis.OperacaoEmAndamento.DispSen?.Dados?.DadosLeitura?.SensoresTemperatura?.FirstOrDefault(x => x.ID == ID);
break;
case S_Code.sCOR:
_leitura = Variaveis.OperacaoEmAndamento.DispSen?.Dados?.DadosLeitura?.SensoresCorrente?.FirstOrDefault(x => x.ID == ID);
break;
case S_Code.sFLX:
_leitura = Variaveis.OperacaoEmAndamento.DispAtu?.Dados?.DadosLeitura?.SensoresFluxo?.FirstOrDefault(x => x.ID == ID);
break;
case S_Code.sPRS:
_leitura = Variaveis.OperacaoEmAndamento.DispAtu?.Dados?.DadosLeitura?.SensoresPressao?.FirstOrDefault(x => x.ID == ID);
break;
case S_Code.sMAS:
_leitura = Variaveis.OperacaoEmAndamento.DispAtu?.Dados?.DadosLeitura?.SensoresMassa?.FirstOrDefault(x => x.ID == ID);
break;
case S_Code.sPOT:
_leitura = Variaveis.OperacaoEmAndamento.DispSen?.Dados?.DadosLeitura?.SensoresPotenciometro?.FirstOrDefault(x => x.ID == ID);
break;
default:
_leitura = null;
break;
}
return _leitura;
}
set
{
_leitura = value;
}
}
public bool Inicializado
{
get
{
return Leitura?.Iniciado ?? false;
}
}
2023-11-30 00:41:22 +00:00
public List<FuncoesPinout> Funcoes { get; set; }
2025-04-09 21:11:40 +00:00
public List<SensorParametroModel> Parametros { get; set;} = new List<SensorParametroModel>();
2023-11-30 00:41:22 +00:00
public string UnidadeMedida { get; set; }
2024-01-31 17:23:52 +00:00
public double LimiteMaximo { get; set; }
public double LimiteMinimo { get; set; }
2023-11-30 00:41:22 +00:00
public List<SenSensorimanetoGrafico> LogGrafico = new List<SenSensorimanetoGrafico>();
2025-04-09 21:11:40 +00:00
public byte[] ProtocoloConfiguracao(PinoutDataModel Pinout, bool conectar)
2023-11-30 00:41:22 +00:00
{
2025-04-09 21:11:40 +00:00
List<byte> config = new List<byte>
{
(byte)Componente,
(byte)ID_Num,
(byte)(conectar ? 1 : 0),
};
2024-04-15 10:57:37 +00:00
var _pinout = new PinoutDataModel()
{
2025-04-09 21:11:40 +00:00
ExpansorGPIO = Pinout.ExpansorGPIO,
EnderecoGPIO = Pinout.EnderecoGPIO,
2025-03-24 18:36:15 +00:00
ExpansorADS = Pinout.ExpansorADS,
2025-04-09 21:11:40 +00:00
EnderecoADS = Pinout.EnderecoADS,
Pinos = Pinout.Pinos.ToList(),
2024-04-15 10:57:37 +00:00
};
_pinout.Pinos = _pinout.Pinos.Where(x => x.ComponenteID == ID).ToList();
2025-04-09 21:11:40 +00:00
if (_pinout.Pinos.Count > 0)
2024-01-23 17:10:34 +00:00
{
2025-04-09 21:11:40 +00:00
byte[] pinos = PinoutModel.PinoProtocolo(_pinout, Funcoes, true);
config.AddRange(pinos);
2024-01-23 17:10:34 +00:00
}
2025-04-09 21:11:40 +00:00
foreach (var parametro in Parametros)
{
if (parametro.Enviar)
{
byte[] paramBytes = parametro.InterpretarParametro();
config.AddRange(paramBytes);
}
}
return config.ToArray();
2023-11-30 00:41:22 +00:00
}
2025-04-09 21:11:40 +00:00
2023-11-30 00:41:22 +00:00
}
public class SensorSinaleiroModel
{
public string ID { get; set; }
2025-04-09 21:11:40 +00:00
public int ID_Num { get; set; }
public string Descricao { get; set; }
public S_Code Componente { get; set; }
public List<FuncoesPinout> Funcoes { get; set; }
public SensorSinaleiroComportamentoModel Comportamento { get; set; }
private FirmwareSinaleiro _leitura = null;
public FirmwareSinaleiro Leitura
{
get
{
_leitura = Variaveis.OperacaoEmAndamento.DispSen?.Dados?.DadosLeitura?.Sinaleiros?.FirstOrDefault(x => x.ID == ID);
return _leitura;
}
set
{
_leitura = value;
}
}
public bool Inicializado
{
get
{
return Leitura?.Iniciado ?? false;
}
}
2024-12-03 20:55:25 +00:00
public StatusLED LeituraComando
{
get
{
return Leitura?.Comando ?? StatusLED.Apagado;
}
}
public StatusLED LeituraStatus
{
get
{
return Leitura?.Leitura ?? StatusLED.Apagado;
}
}
2025-04-09 21:11:40 +00:00
public byte[] ProtocoloConfiguracao(PinoutDataModel pinout, bool conectar)
{
2025-04-09 21:11:40 +00:00
var pino = pinout.Pinos.FirstOrDefault(p => p.ComponenteID == ID);
List<byte> config = new List<byte>
2024-04-15 10:57:37 +00:00
{
2025-04-09 21:11:40 +00:00
(byte)Componente,
(byte)ID_Num,
(byte)(conectar ? 1 : 0),
(byte)(pino?.Barramento ?? TiposBarramentos.CONTROLADOR),
(byte)(pino?.Pino ?? PinoutUtils.PINO_INVALIDO)
2024-04-15 10:57:37 +00:00
};
2025-04-09 21:11:40 +00:00
return config.ToArray();
}
2025-04-09 21:11:40 +00:00
public (F_Code, byte[]) ProtocoloComando()
{
2025-04-09 21:11:40 +00:00
List<byte> frame = new List<byte>
{
(byte)Componente,
(byte)ID_Num,
(byte)Comportamento.statusLED,
(byte)Comportamento.QtdPiscadas,
(byte)(Comportamento.TempoMs / 10),
(byte)(Comportamento.PausaMs / 10)
};
2025-04-09 21:11:40 +00:00
return (F_Code.CmdTx, frame.ToArray());
}
2024-07-18 18:00:14 +00:00
}
public class SensorReleModel
{
public string ID { get; set; }
2025-04-09 21:11:40 +00:00
public int ID_Num { get; set; }
2024-07-18 18:00:14 +00:00
public string Descricao { get; set; }
public S_Code Componente { get; set; }
public List<FuncoesPinout> Funcoes { get; set; }
public bool ControleExterno { get; set; }
2024-07-24 20:04:55 +00:00
public bool Controlar { get; set; }
public bool AtuacaoNivelAlto { get; set; }
2024-07-18 18:00:14 +00:00
public Estado StatusControle { get; set; }
private FirmwareRele _leitura = null;
public FirmwareRele Leitura
{
get
{
_leitura = Variaveis.OperacaoEmAndamento.DispSen?.Dados?.DadosLeitura?.Reles?.FirstOrDefault(x => x.ID == ID);
return _leitura;
}
set
{
_leitura = value;
if (_leitura != null && ControleExterno)
{
StatusControle = _leitura.Leitura;
}
}
}
public bool Inicializado
{
get
{
return Leitura?.Iniciado ?? false;
}
}
2024-12-03 20:55:25 +00:00
public Estado LeituraEstado
{
get
{
return Leitura?.Leitura ?? Estado.Desligado;
}
}
2024-07-18 18:00:14 +00:00
2025-04-09 21:11:40 +00:00
public byte[] ProtocoloConfiguracao(PinoutDataModel pinout, bool conectar)
2024-07-18 18:00:14 +00:00
{
2025-04-09 21:11:40 +00:00
var pino = pinout.Pinos.FirstOrDefault(p => p.ComponenteID == ID);
List<byte> config = new List<byte>
2024-07-18 18:00:14 +00:00
{
2025-04-09 21:11:40 +00:00
(byte)Componente,
(byte)ID_Num,
(byte)(conectar ? 1 : 0),
(byte)(AtuacaoNivelAlto ? 1 : 0),
(byte)(pino?.Barramento ?? TiposBarramentos.CONTROLADOR),
(byte)(pino?.Pino ?? PinoutUtils.PINO_INVALIDO)
2024-07-18 18:00:14 +00:00
};
2025-04-09 21:11:40 +00:00
return config.ToArray();
2024-07-18 18:00:14 +00:00
}
2025-04-09 21:11:40 +00:00
public (F_Code, byte[]) ProtocoloComando()
2024-07-18 18:00:14 +00:00
{
2025-04-09 21:11:40 +00:00
return (
F_Code.CmdTx,
new byte[]
{
(byte)Componente,
(byte)ID_Num,
(byte)StatusControle
}
);
2024-07-24 20:04:55 +00:00
}
}
public class SensorServoModel
{
public string ID { get; set; }
2025-04-09 21:11:40 +00:00
public int ID_Num { get; set; }
2024-07-24 20:04:55 +00:00
public string Descricao { get; set; }
public S_Code Componente { get; set; }
public List<FuncoesPinout> Funcoes { get; set; }
public bool Controlar { get; set; }
public int _AnguloControle { get; set; }
private FirmwareServoFreio _leitura = null;
public FirmwareServoFreio Leitura
{
get
{
_leitura = Variaveis.OperacaoEmAndamento.DispSen?.Dados?.DadosLeitura?.ServoFreios?.FirstOrDefault(x => x.ID == ID);
return _leitura;
}
set
{
_leitura = value;
}
}
public bool Inicializado
{
get
{
return Leitura?.Iniciado ?? false;
}
}
2024-12-03 20:55:25 +00:00
public double LeituraAngulo
{
get
{
return Leitura?.Angulo ?? 0;
}
}
2024-07-24 20:04:55 +00:00
2025-04-09 21:11:40 +00:00
public byte[] ProtocoloConfiguracao(PinoutDataModel pinout, bool conectar)
2024-07-24 20:04:55 +00:00
{
2025-04-09 21:11:40 +00:00
var pino = pinout.Pinos.FirstOrDefault(p => p.ComponenteID == ID);
2024-11-25 12:14:59 +00:00
2025-04-09 21:11:40 +00:00
// Descobrir se é incremental
2024-11-25 12:14:59 +00:00
bool incremental = true;
var freio = Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.FirstOrDefault(x => ID.Contains(x.Modulo_ID));
if (freio != null)
{
incremental = freio.MovMotor.ConfigFreio.Incremental;
}
2025-04-09 21:11:40 +00:00
List<byte> config = new List<byte>
{
(byte)Componente,
(byte)ID_Num,
(byte)(conectar ? 1 : 0),
(byte)(incremental ? 1 : 0),
(byte)(pino?.Barramento ?? TiposBarramentos.CONTROLADOR),
(byte)(pino?.Pino ?? PinoutUtils.PINO_INVALIDO)
};
return config.ToArray();
2024-07-24 20:04:55 +00:00
}
2025-04-09 21:11:40 +00:00
public (F_Code, byte[]) ProtocoloComando()
2024-07-24 20:04:55 +00:00
{
2025-04-09 21:11:40 +00:00
return (
F_Code.CmdTx,
new byte[]
{
(byte)Componente,
(byte)ID_Num,
(byte)_AnguloControle
}
);
2024-07-18 18:00:14 +00:00
}
}
2024-07-18 18:00:14 +00:00
public class SensorSinaleiroComportamentoModel
{
public StatusLED statusLED { get; set; }
public int QtdPiscadas { get; set; } = 0;
public int TempoMs { get; set; } = 0;
public int PausaMs { get; set; } = 0;
2024-07-18 18:00:14 +00:00
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
SensorSinaleiroComportamentoModel other = (SensorSinaleiroComportamentoModel)obj;
return statusLED == other.statusLED &&
QtdPiscadas == other.QtdPiscadas &&
TempoMs == other.TempoMs &&
PausaMs == other.PausaMs;
}
public override int GetHashCode()
{
unchecked // Permite overflow de inteiros
{
int hash = 17;
hash = hash * 23 + statusLED.GetHashCode();
hash = hash * 23 + QtdPiscadas.GetHashCode();
hash = hash * 23 + TempoMs.GetHashCode();
hash = hash * 23 + PausaMs.GetHashCode();
return hash;
}
}
public static bool operator ==(SensorSinaleiroComportamentoModel left, SensorSinaleiroComportamentoModel right)
{
if (ReferenceEquals(left, right))
{
return true;
}
if ((object)left == null || (object)right == null)
{
return false;
}
return left.Equals(right);
}
public static bool operator !=(SensorSinaleiroComportamentoModel left, SensorSinaleiroComportamentoModel right)
{
return !(left == right);
}
}
2023-11-30 00:41:22 +00:00
public class SenSensorimanetoGrafico
{
public DateTime Momento { get; set; }
public string ComponenteID { get; set; }
public S_Code Componente { get; set; }
public double Leitura1 { get; set; }
public double Leitura2 { get; set; }
public double Leitura3 { get; set; }
public double Leitura4 { get; set; }
public bool AlarmeMaxima { get; set; }
public bool AlarmeMinima { get; set; }
}
2024-04-15 10:57:37 +00:00
2025-04-09 21:11:40 +00:00
public class SensorParametroModel
{
public string Descricao { get; set; }
public string Valor { get; set; }
public int QtdBytes { get; set; }
public bool Escalar { get; set; }
public bool Enviar { get; set; }
public byte[] InterpretarParametro()
{
string valor = Valor.Trim();
// HEX direto
if (valor.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
{
byte parsedHex = Convert.ToByte(valor, 16);
return QtdBytes == 2 ? new byte[] { 0x00, parsedHex } : new byte[] { parsedHex };
}
// FLOAT com ou sem ponto
float f = float.Parse(valor, CultureInfo.InvariantCulture);
ushort final = (ushort)(Escalar ? f * 100 : f);
if (QtdBytes == 1)
return new byte[] { (byte)(final & 0xFF) };
return new byte[] {
(byte)(final >> 8),
(byte)(final & 0xFF)
};
}
}
2025-04-09 21:11:40 +00:00
public class FirmwareSensorTemperatura : IFirmwareSensorBase
{
public string ID { get; set; }
2025-03-06 20:15:56 +00:00
public bool Iniciado { get; set; }
2025-04-09 21:11:40 +00:00
private double _temperatura;
public double Temperatura {
get
{
return _temperatura;
}
set
{
2025-04-09 21:11:40 +00:00
_temperatura = value;
AtualizarExtremos();
}
}
public double ValorMaximo { get; set; }
public double ValorMinimo { get; set; }
public double LimiteMaximo
{
get
{
var sensor = Variaveis.OperacaoEmAndamento.DispSen.Dados.Sensores.FirstOrDefault(x => x.ID == ID);
if (sensor != null)
{
return sensor.LimiteMaximo;
}
return 0;
}
}
public double LimiteMinimo
{
get
{
var sensor = Variaveis.OperacaoEmAndamento.DispSen.Dados.Sensores.FirstOrDefault(x => x.ID == ID);
if (sensor != null)
{
return sensor.LimiteMinimo;
}
return 0;
}
}
private void AtualizarExtremos()
{
2025-04-09 21:11:40 +00:00
if (_temperatura > ValorMaximo)
{
2025-04-09 21:11:40 +00:00
ValorMaximo = _temperatura;
}
2025-04-09 21:11:40 +00:00
if (_temperatura < ValorMinimo || ValorMinimo == 0)
{
2025-04-09 21:11:40 +00:00
ValorMinimo = _temperatura;
}
}
}
2025-04-09 21:11:40 +00:00
public class FirmwareSensorCorrente : IFirmwareSensorBase
{
public string ID { get; set; }
2025-03-06 20:15:56 +00:00
public bool Iniciado { get; set; }
public double BusVoltage { get; set; }
public double ShuntVoltage { get; set; }
public double? Current
{
get
{
return _atual;
}
set
{
_atual = value ?? 0;
AtualizarExtremos();
}
}
public double Power { get; set; }
public double ValorMaximo { get; set; }
public double ValorMinimo { get; set; }
public double LimiteMaximo
{
get
{
var sensor = Variaveis.OperacaoEmAndamento.DispSen.Dados.Sensores.FirstOrDefault(x => x.ID == ID);
if (sensor != null)
{
return sensor.LimiteMaximo;
}
return 0;
}
}
public double LimiteMinimo
{
get
{
var sensor = Variaveis.OperacaoEmAndamento.DispSen.Dados.Sensores.FirstOrDefault(x => x.ID == ID);
if (sensor != null)
{
return sensor.LimiteMinimo;
}
return 0;
}
}
private double _atual = 0;
private void AtualizarExtremos()
{
if (_atual > ValorMaximo)
{
ValorMaximo = _atual;
}
if (_atual < ValorMinimo || ValorMinimo == 0)
{
ValorMinimo = _atual;
}
}
}
2025-04-09 21:11:40 +00:00
public class FirmwareSinaleiro : IFirmwareSensorBase
{
public string ID { get; set; }
2025-03-06 20:15:56 +00:00
public bool Iniciado { get; set; }
public StatusLED Leitura { get; set; }
2024-12-03 20:55:25 +00:00
public StatusLED Comando { get; set; }
}
2025-04-09 21:11:40 +00:00
public class FirmwareRele : IFirmwareSensorBase
{
public string ID { get; set; }
2025-03-06 20:15:56 +00:00
public bool Iniciado { get; set; }
public Estado Leitura { get; set; }
}
2025-04-09 21:11:40 +00:00
public class FirmwareServoFreio : IFirmwareSensorBase
{
public string ID { get; set; }
2025-03-06 20:15:56 +00:00
public bool Iniciado { get; set; }
public int Angulo { get; set; }
}
2025-04-09 21:11:40 +00:00
public class FirmwareSensorFluxo : IFirmwareSensorBase
{
public string ID { get; set; }
2025-03-06 20:15:56 +00:00
public bool Iniciado { get; set; }
2024-12-05 12:52:28 +00:00
public int Pulsos { get; set; }
private int _periodo;
public int Periodo
{
get
{
return _periodo;
}
2024-12-02 19:12:39 +00:00
set
{
2024-12-05 12:52:28 +00:00
_periodo = value;
2024-12-02 19:12:39 +00:00
AtualizarVazao();
}
}
private double _atual;
public double Vazao { get { return _atual; } }
public double ValorMaximo { get; set; }
public double ValorMinimo { get; set; }
public double LimiteMaximo
{
get
{
var sensor = Variaveis.OperacaoEmAndamento.DispAtu.Dados.Sensores.FirstOrDefault(x => x.ID == ID);
if (sensor != null)
{
return sensor.LimiteMaximo;
}
return 0;
}
}
public double LimiteMinimo
{
get
{
var sensor = Variaveis.OperacaoEmAndamento.DispAtu.Dados.Sensores.FirstOrDefault(x => x.ID == ID);
if (sensor != null)
{
return sensor.LimiteMinimo;
}
return 0;
}
}
private void AtualizarVazao()
{
//_atual = Variaveis.OperacaoEmAndamento.DispAtu.Dados.VazaoFluxoMLpS;
if (Periodo == 0)
{
_atual = 0;
}
else
{
2024-12-05 12:52:28 +00:00
double Frequencia = ((double)Pulsos / (double)Periodo * 1000);
2024-12-02 19:12:39 +00:00
//double vazao = (_LeituraPulsos * FatorLeitura) / ((double)_LeituraPeriodo / 1000);
//double vazao = ((double)1 / FatorLeitura) * (60 * 1000 / _LeituraPeriodo);
//double vazao = ((double)_LeituraPulsos / (((double)_LeituraPeriodo / 1000) * 8.1)) + 3;
//double Fator = (double)_LeituraPulsos / (double)_LeituraPeriodo;
//double vazao = ((double)_LeituraPulsos / (double)_LeituraPeriodo * 1000) * ;
//double vazao = Frequencia * 1.22;
double Rh = 0.0047;
double Rt = 0.0037;
double vazao = (Frequencia * 2 * Math.PI * Rh * Math.PI * (Rt * Rt)) * 1000000;
2024-12-05 12:52:28 +00:00
Console.WriteLine("Pulsos: " + Pulsos + " - Periodo: " + Periodo + " ms - Vazão: " + vazao.ToString("0.00000"));
2024-12-02 19:12:39 +00:00
_atual = vazao;
}
AtualizarExtremos();
}
private void AtualizarExtremos()
{
if (_atual > ValorMaximo)
{
ValorMaximo = _atual;
}
if (_atual < ValorMinimo || ValorMinimo == 0)
{
ValorMinimo = _atual;
}
}
}
2025-04-09 21:11:40 +00:00
public class FirmwareSensorMassa : IFirmwareSensorBase
{
public string ID { get; set; }
2025-03-06 20:15:56 +00:00
public bool Iniciado { get; set; }
2024-12-05 12:52:28 +00:00
private double _leitura;
public double Leitura
2024-12-02 19:12:39 +00:00
{
get { return _leitura; }
set
{
_leitura = value;
AtualizarMassa();
}
}
private double _atual;
public double Massa { get { return _atual; } }
public double ValorMaximo { get; set; }
public double ValorMinimo { get; set; }
public double LimiteMaximo
{
get
{
var sensor = Variaveis.OperacaoEmAndamento.DispAtu.Dados.Sensores.FirstOrDefault(x => x.ID == ID);
if (sensor != null)
{
return sensor.LimiteMaximo;
}
return 0;
}
}
public double LimiteMinimo
{
get
{
var sensor = Variaveis.OperacaoEmAndamento.DispAtu.Dados.Sensores.FirstOrDefault(x => x.ID == ID);
if (sensor != null)
{
return sensor.LimiteMinimo;
}
return 0;
}
}
private void AtualizarMassa()
{
if (Variaveis.OperacaoEmAndamento.DispAtu != null)
{
double leituraMassa = _leitura * -1;
leituraMassa += Variaveis.OperacaoEmAndamento.DispAtu.Dados._MassaLeituraExtra;
double FatorLeitura = Variaveis.OperacaoEmAndamento.DispAtu.Dados._MassaRef / Variaveis.OperacaoEmAndamento.DispAtu.Dados._MassaLeituraRef;
_atual = FatorLeitura * leituraMassa;
AtualizarExtremos();
}
}
private void AtualizarExtremos()
{
if (_atual > ValorMaximo)
{
ValorMaximo = _atual;
}
if (_atual < ValorMinimo || ValorMinimo == 0)
{
ValorMinimo = _atual;
}
}
}
2025-04-09 21:11:40 +00:00
public class FirmwareSensorPressao : IFirmwareSensorBase
{
public string ID { get; set; }
2025-03-06 20:15:56 +00:00
public bool Iniciado { get; set; }
2024-12-02 19:12:39 +00:00
public double Leitura { get; set; }
public double Pressao { get; set; }
}
2025-04-09 21:11:40 +00:00
public class FirmwareSensorPotenciometro : IFirmwareSensorBase
{
public string ID { get; set; }
2025-03-06 20:15:56 +00:00
public bool Iniciado { get; set; }
public int Leitura { get; set; }
public double Angulo { get; set; }
public Sentido Sentido { get; set; }
public bool LimiteExcedido { get; set; }
public StatusSensorPotenciometro Status
{
get
{
// Verifica se há um sensor ativo
SensorModel Sensor = Variaveis.OperacaoEmAndamento.DispSen?.Dados?.Sensores?.FirstOrDefault(x => x.ID == ID);
if (Sensor == null)
{
return StatusSensorPotenciometro.Indefinido;
}
// Verifica se os parâmetros necessários existem
2025-04-09 21:11:40 +00:00
/*if (Sensor.Parametros.Count <= 3 || Sensor.Parametros[1].Count() <= 1 || Sensor.Parametros[3].Count() <= 1)
{
return StatusSensorPotenciometro.Indefinido;
2025-04-09 21:11:40 +00:00
}*/
if (LimiteExcedido && Sentido == Sentido.Horario)
{
return StatusSensorPotenciometro.LimiteDireita;
}
if (LimiteExcedido && Sentido == Sentido.Antihorario)
{
return StatusSensorPotenciometro.LimiteEsquerdo;
}
if (Sentido == Sentido.Parado)
{
return StatusSensorPotenciometro.Centro;
}
if (Sentido == Sentido.Antihorario)
{
return StatusSensorPotenciometro.AEsquerda;
}
if (Sentido == Sentido.Horario)
{
return StatusSensorPotenciometro.ADireita;
}
return StatusSensorPotenciometro.Indefinido;
}
}
public double LimiteMaximo
{
get
{
var sensor = Variaveis.OperacaoEmAndamento.DispSen?.Dados?.Sensores?.FirstOrDefault(x => x.ID == ID);
if (sensor != null)
{
return sensor.LimiteMaximo;
}
return 0;
}
}
public double LimiteMinimo
{
get
{
var sensor = Variaveis.OperacaoEmAndamento.DispSen?.Dados?.Sensores?.FirstOrDefault(x => x.ID == ID);
if (sensor != null)
{
return sensor.LimiteMinimo;
}
return 0;
}
}
}
public class SensoriamentoMensagemJsonModel
{
2024-12-05 17:11:38 +00:00
public DateTime Momento { get; set; }
public bool Conectado { get; set; }
2025-04-09 21:11:40 +00:00
public T_Code Dispositivo { get; set; }
public int Versao { get; set; }
public string Mod_ID { get; set; }
2024-12-05 17:11:38 +00:00
public int QualidadeWifi { get; set; }
public int LatenciaLoop { get; set; }
public List<FirmwareSensorTemperatura> SensoresTemperatura { get; set; } = new List<FirmwareSensorTemperatura>();
public List<FirmwareSensorCorrente> SensoresCorrente { get; set; } = new List<FirmwareSensorCorrente>();
public List<FirmwareSinaleiro> Sinaleiros { get; set; } = new List<FirmwareSinaleiro>();
public List<FirmwareRele> Reles { get; set; } = new List<FirmwareRele>();
public List<FirmwareServoFreio> ServoFreios { get; set; } = new List<FirmwareServoFreio>();
public List<FirmwareSensorPotenciometro> SensoresPotenciometro { get; set; } = new List<FirmwareSensorPotenciometro>();
2024-12-19 19:29:21 +00:00
public DateTime UltimoComandoRespondido { get; set; }
}
2025-04-09 21:11:40 +00:00
public class SenHandler : ICanMessageHandler
{
private double ConverterByteParaDouble(byte[] data, int idx)
{
int raw = (data[idx] << 8) | data[idx + 1];
short _short = (short)raw;
double _value = _short / 100.0;
return _value;
}
public void ProcessarMensagem(CanMessage mensagem)
{
F_Code func = (F_Code)mensagem.DataRx[0];
byte id = mensagem.Id;
var data = mensagem.DataRx;
var item = Variaveis.OperacaoEmAndamento.DispSen.Dados.DadosLeitura;
switch (func)
{
case F_Code.ChkRx:
if (data != null && data.Length >= 4)
{
T_Code tipoModulo = (T_Code)data[1];
bool conectado = data[2] == 1;
int versao = data[3];
Console.WriteLine($"[SEN] Resposta {func.ToString()} recebida. Tipo={tipoModulo}, Conectado={conectado}, Versão={versao}");
item.Conectado = conectado;
item.Dispositivo = tipoModulo;
item.Versao = versao;
}
break;
default:
{
S_Code componente = (S_Code)data[0];
int CompID_Num = data[1];
bool Iniciado = data[2] == 1;
Console.WriteLine($"[SEN] Componente={componente.ToString()}, ID_Num={CompID_Num}, Iniciado={Iniciado}");
switch (componente)
{
case S_Code.sTMP:
{
var sensor = Variaveis.OperacaoEmAndamento.DispSen.Dados.Sensores.FirstOrDefault(x => x.ID_Num == CompID_Num);
var _sensor = item.SensoresTemperatura.FirstOrDefault(x => x.ID == sensor.ID);
if (_sensor == null)
{
_sensor = new FirmwareSensorTemperatura()
{
ID = sensor.ID,
Iniciado = Iniciado,
Temperatura = -1,
};
item.SensoresTemperatura.Add(_sensor);
}
double temperatura = ConverterByteParaDouble(data, 3);
if (_sensor != null)
{
_sensor.Temperatura = temperatura;
}
break;
}
case S_Code.sCOR:
{
var sensor = Variaveis.OperacaoEmAndamento.DispSen.Dados.Sensores.FirstOrDefault(x => x.ID_Num == CompID_Num);
var _sensor = item.SensoresCorrente.FirstOrDefault(x => x.ID == sensor.ID);
if (_sensor == null)
{
_sensor = new FirmwareSensorCorrente()
{
ID = sensor.ID,
Iniciado = Iniciado,
BusVoltage = -1,
Current = -1,
Power = -1,
ShuntVoltage = -1,
};
item.SensoresCorrente.Add(_sensor);
}
double busVoltage = ConverterByteParaDouble(data, 3);
double current = ConverterByteParaDouble(data, 5);
//double power = ConverterByteParaDouble(data, 7);
if (_sensor != null)
{
_sensor.BusVoltage = busVoltage;
_sensor.Current = current;
}
break;
}
case S_Code.sLED:
{
var sinaleiro = Variaveis.OperacaoEmAndamento.DispSen.Dados.Sinaleiros.FirstOrDefault(x => x.ID_Num == CompID_Num);
var _sensor = item.Sinaleiros.FirstOrDefault(x => x.ID == sinaleiro.ID);
if (_sensor == null)
{
_sensor = new FirmwareSinaleiro()
{
ID = sinaleiro.ID,
Iniciado = Iniciado,
Leitura = StatusLED.Apagado,
Comando = StatusLED.Apagado
};
item.Sinaleiros.Add(_sensor);
}
StatusLED statusLeitura = (StatusLED)data[3];
StatusLED status = (StatusLED)data[4];
if (_sensor != null)
{
_sensor.Leitura = statusLeitura;
_sensor.Comando = status;
}
break;
}
case S_Code.sRLE:
{
var rele = Variaveis.OperacaoEmAndamento.DispSen.Dados.Reles.FirstOrDefault(x => x.ID_Num == CompID_Num);
var _sensor = item.Reles.FirstOrDefault(x => x.ID == rele.ID);
if (_sensor == null)
{
_sensor = new FirmwareRele()
{
ID = rele.ID,
Iniciado = Iniciado,
Leitura = Estado.Desligado
};
item.Reles.Add(_sensor);
}
Estado estado = (Estado)data[3];
if (_sensor != null)
{
_sensor.Leitura = estado;
}
break;
}
case S_Code.sFRO:
{
var servo = Variaveis.OperacaoEmAndamento.DispSen.Dados.Servos.FirstOrDefault(x => x.ID_Num == CompID_Num);
var _sensor = item.ServoFreios.FirstOrDefault(x => x.ID == servo.ID);
if (_sensor == null)
{
_sensor = new FirmwareServoFreio()
{
ID = servo.ID,
Iniciado = Iniciado,
Angulo = -1,
};
item.ServoFreios.Add(_sensor);
}
int angulo = data[3];
if (_sensor != null)
{
_sensor.Angulo = angulo;
}
break;
}
default:
{
Console.WriteLine($"[SEN] Resposta {func.ToString()} recebida. Parametros nao mapeados: {FuncoesGlobais.ConverterComandoBytesParaTexto(data)}");
break;
}
}
break;
}
}
item.UltimoComandoRespondido = DateTime.Now;
}
}
2023-11-30 00:41:22 +00:00
}