implantado protocolo mqtt nos modulos atuador e sensoriamento
This commit is contained in:
parent
9c90bec1d6
commit
89b47567a1
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -421,6 +421,7 @@
|
|||
<Compile Include="Models\CameraCaminhoModel.cs" />
|
||||
<Compile Include="Models\CameraModel.cs" />
|
||||
<Compile Include="Models\CameraSoloModel.cs" />
|
||||
<Compile Include="Models\DispositivosModel.cs" />
|
||||
<Compile Include="Models\GPSModel.cs" />
|
||||
<Compile Include="Models\GraficoInterativoModel.cs" />
|
||||
<Compile Include="Models\KinectModel.cs" />
|
||||
|
|
|
|||
|
|
@ -98,9 +98,8 @@ namespace AgroBase.Forms
|
|||
ArquivoVersao.Versao
|
||||
},
|
||||
cameraSolo.VideoPorta,
|
||||
cameraSolo.VideoUrl,
|
||||
cameraSolo.MqttTopico,
|
||||
cameraSolo.tmrProcesso
|
||||
cameraSolo.VideoUrl,
|
||||
cameraSolo.MqttTopico
|
||||
);
|
||||
|
||||
tmrLeitura = new AsyncTaskTimerModel("tmrLeitura", tmrLeitura_Tick, 200);
|
||||
|
|
|
|||
|
|
@ -722,16 +722,16 @@ namespace AgroBase.Forms.IHM
|
|||
bool Sucesso = false;
|
||||
while (!Sucesso && Inicio.AddMilliseconds(Timeout) > DateTime.Now)
|
||||
{
|
||||
Dispositivo.Dados.RequisitarDadosComponente(ServoFreio.Componente, ServoFreio.ID);
|
||||
Dispositivo.Dados.RequisitarDadosModulo();
|
||||
await Task.Delay(1000);
|
||||
|
||||
Sucesso =
|
||||
Teste.ComplementoValorPadrao == "<" ? ServoFreio._AnguloLeitura < Teste.ValorPadrao :
|
||||
Teste.ComplementoValorPadrao == ">" ? ServoFreio._AnguloLeitura > Teste.ValorPadrao :
|
||||
ServoFreio._AnguloLeitura == Teste.ValorPadrao;
|
||||
Teste.ComplementoValorPadrao == "<" ? (((FirmwareServoFreio)ServoFreio.Leitura)?.Angulo ?? 0) < Teste.ValorPadrao :
|
||||
Teste.ComplementoValorPadrao == ">" ? (((FirmwareServoFreio)ServoFreio.Leitura)?.Angulo ?? 0) > Teste.ValorPadrao :
|
||||
(((FirmwareServoFreio)ServoFreio.Leitura)?.Angulo ?? 0) == Teste.ValorPadrao;
|
||||
}
|
||||
|
||||
Teste.ValorAferido = ServoFreio._AnguloLeitura;
|
||||
Teste.ValorAferido = (((FirmwareServoFreio)ServoFreio.Leitura)?.Angulo ?? 0);
|
||||
|
||||
return Sucesso;
|
||||
}
|
||||
|
|
@ -1036,18 +1036,18 @@ namespace AgroBase.Forms.IHM
|
|||
bool SenIniciado = Modulo_Sen.Conectado;
|
||||
idx = PreencheDadosLinha(grid, Testes, idx, SenIniciado ? 1 : 0);
|
||||
|
||||
var S5V = Modulo_Sen.Sensores.FirstOrDefault(x => x.ID == "AB5V");
|
||||
double Tensao5V = S5V != null && S5V.Leituras.Count() > 1 ? S5V.Leituras[1] : -1;
|
||||
var S5V = Modulo_Sen.DadosLeitura.SensoresCorrente.FirstOrDefault(x => x.ID == "AB5V");
|
||||
double Tensao5V = S5V != null ? (double)S5V.Current : -1;
|
||||
idx = PreencheDadosLinha(grid, Testes, idx, Tensao5V);
|
||||
|
||||
double Corrente5V = S5V != null && S5V.Leituras.Count() > 0 ? S5V.Leituras[0] : -1;
|
||||
double Corrente5V = S5V != null ? (double)S5V.Current : -1;
|
||||
idx = PreencheDadosLinha(grid, Testes, idx, Corrente5V);
|
||||
|
||||
var S12V = Modulo_Sen.Sensores.FirstOrDefault(x => x.ID == "AB12V");
|
||||
double Tensao12V = S12V != null && S12V.Leituras.Count() > 1 ? S12V.Leituras[1] : -1;
|
||||
var S12V = Modulo_Sen.DadosLeitura.SensoresCorrente.FirstOrDefault(x => x.ID == "AB12V");
|
||||
double Tensao12V = S12V != null ? (double)S12V.Current : -1;
|
||||
idx = PreencheDadosLinha(grid, Testes, idx, Tensao12V);
|
||||
|
||||
double Corrente12V = S12V != null && S12V.Leituras.Count() > 0 ? S12V.Leituras[0] : -1;
|
||||
double Corrente12V = S12V != null ? (double)S12V.Current : -1;
|
||||
idx = PreencheDadosLinha(grid, Testes, idx, Corrente12V);
|
||||
|
||||
bool WitConectado = SerialService.DispositivosMapeados.Any(x => x.Dispositivo == Enums.T_Code.Wit);
|
||||
|
|
@ -1176,12 +1176,12 @@ namespace AgroBase.Forms.IHM
|
|||
|
||||
await EnviarComandoRele(Dispositivo, ReleLra, true, 1000);
|
||||
|
||||
bool RlStatus = RlInicializado && ReleLra.StatusLeitura == Estado.Ligado;
|
||||
bool RlStatus = RlInicializado && (((FirmwareRele)ReleLra.Leitura)?.Leitura ?? Estado.Desligado) == Estado.Ligado;
|
||||
idx = PreencheDadosLinha(grid, Testes, idx, RlStatus ? 1 : 0);
|
||||
|
||||
await EnviarComandoRele(Dispositivo, ReleLra, false, 1000);
|
||||
|
||||
RlStatus = RlInicializado && ReleLra.StatusLeitura == Estado.Ligado;
|
||||
RlStatus = RlInicializado && (((FirmwareRele)ReleLra.Leitura)?.Leitura ?? Estado.Desligado) == Estado.Ligado;
|
||||
idx = PreencheDadosLinha(grid, Testes, idx, !RlStatus ? 0 : 1);
|
||||
|
||||
bool Conectado = SerialService.DispositivosMapeados.Any(x => x.Dispositivo == T_Code.Lra);
|
||||
|
|
@ -1213,7 +1213,7 @@ namespace AgroBase.Forms.IHM
|
|||
var novoEstado = Ligar ? Estado.Ligado : Estado.Desligado;
|
||||
GeneralJoystick.EnviarComandoSensoriamento(S_Code.sRLE, Rele.ID, novoEstado);
|
||||
await Task.Delay(Delay);
|
||||
Dispositivo.Dados.RequisitarDadosComponente(Rele.Componente, Rele.ID);
|
||||
Dispositivo.Dados.RequisitarDadosModulo();
|
||||
await Task.Delay(Delay);
|
||||
}
|
||||
|
||||
|
|
@ -1476,7 +1476,7 @@ namespace AgroBase.Forms.IHM
|
|||
await EnviarComandoSinaleiro(Dispositivo, Sinaleiro, true, 1000);
|
||||
}
|
||||
|
||||
StatusLED Status = Sinaleiro.StatusLED;
|
||||
StatusLED Status = (((FirmwareSinaleiro)Sinaleiro.Leitura)?.Leitura ?? StatusLED.Apagado);
|
||||
idx = PreencheDadosLinha(grid, Testes, idx, Iniciado && Status == StatusLED.Aceso ? 1 : 0);
|
||||
|
||||
if (Iniciado)
|
||||
|
|
@ -1484,7 +1484,7 @@ namespace AgroBase.Forms.IHM
|
|||
await EnviarComandoSinaleiro(Dispositivo, Sinaleiro, false, 1000);
|
||||
}
|
||||
|
||||
Status = Sinaleiro.StatusLED;
|
||||
Status = (((FirmwareSinaleiro)Sinaleiro.Leitura)?.Leitura ?? StatusLED.Apagado);
|
||||
idx = PreencheDadosLinha(grid, Testes, idx, Iniciado && Status == StatusLED.Apagado ? 0 : 1);
|
||||
}
|
||||
|
||||
|
|
@ -1499,7 +1499,7 @@ namespace AgroBase.Forms.IHM
|
|||
Comportamento.statusLED = Ligar ? StatusLED.Aceso : StatusLED.Apagado;
|
||||
GeneralJoystick.EnviarComandoSensoriamento(S_Code.sLED, Sinaleiro.ID, Comportamento);
|
||||
await Task.Delay(Delay);
|
||||
Dispositivo.Dados.RequisitarDadosComponente(Sinaleiro.Componente, Sinaleiro.ID);
|
||||
Dispositivo.Dados.RequisitarDadosModulo();
|
||||
await Task.Delay(Delay);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ namespace AgroBase.Forms.IHM
|
|||
});
|
||||
FuncoesGlobais.DefinirEventosPicBtn(picManual, "Erro ao carregar modo de controle manual!", async () =>
|
||||
{
|
||||
Variaveis.OperacaoEmAndamento = OperacaoModel.CarregarParametrosOperacaoPadrao(ModoOperacao.Manual);
|
||||
OperacaoModel.CarregarParametrosOperacaoPadrao(ModoOperacao.Manual);
|
||||
if (Variaveis.OperacaoEmAndamento.OperacaoLiberada)
|
||||
{
|
||||
frmDialogoMapa frm = new frmDialogoMapa();
|
||||
|
|
@ -145,11 +145,6 @@ namespace AgroBase.Forms.IHM
|
|||
}
|
||||
});
|
||||
|
||||
if (SerialService.DispositivosMapeados.Count == 0)
|
||||
{
|
||||
Variaveis.DispositivosConectados.Where(x => x.Dados.GetStatusConexao()).ToList().ForEach(x => x.AcaoDesconectar());
|
||||
}
|
||||
|
||||
bool mqttConectado = Variaveis.MqttService.StatusConexao();
|
||||
lblMqtt.Text = "MQTT: " + (mqttConectado ? "Conectado" : "Desconectado");
|
||||
lblMqtt.ForeColor = mqttConectado ? Color.Green : Color.Red;
|
||||
|
|
|
|||
|
|
@ -28,9 +28,9 @@
|
|||
/// </summary>
|
||||
private void InitializeComponent()
|
||||
{
|
||||
System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea3 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
|
||||
System.Windows.Forms.DataVisualization.Charting.Legend legend3 = new System.Windows.Forms.DataVisualization.Charting.Legend();
|
||||
System.Windows.Forms.DataVisualization.Charting.Series series3 = new System.Windows.Forms.DataVisualization.Charting.Series();
|
||||
System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
|
||||
System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();
|
||||
System.Windows.Forms.DataVisualization.Charting.Series series1 = new System.Windows.Forms.DataVisualization.Charting.Series();
|
||||
this.pnlCamerasSolo = new System.Windows.Forms.Panel();
|
||||
this.pnlCameraSoloE = new System.Windows.Forms.Panel();
|
||||
this.pnlCameraSoloD = new System.Windows.Forms.Panel();
|
||||
|
|
@ -149,17 +149,17 @@
|
|||
//
|
||||
this.chartGraficos.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
|
||||
| System.Windows.Forms.AnchorStyles.Right)));
|
||||
chartArea3.Name = "ChartArea1";
|
||||
this.chartGraficos.ChartAreas.Add(chartArea3);
|
||||
legend3.Name = "Legend1";
|
||||
this.chartGraficos.Legends.Add(legend3);
|
||||
chartArea1.Name = "ChartArea1";
|
||||
this.chartGraficos.ChartAreas.Add(chartArea1);
|
||||
legend1.Name = "Legend1";
|
||||
this.chartGraficos.Legends.Add(legend1);
|
||||
this.chartGraficos.Location = new System.Drawing.Point(640, 7);
|
||||
this.chartGraficos.Margin = new System.Windows.Forms.Padding(2);
|
||||
this.chartGraficos.Name = "chartGraficos";
|
||||
series3.ChartArea = "ChartArea1";
|
||||
series3.Legend = "Legend1";
|
||||
series3.Name = "Series1";
|
||||
this.chartGraficos.Series.Add(series3);
|
||||
series1.ChartArea = "ChartArea1";
|
||||
series1.Legend = "Legend1";
|
||||
series1.Name = "Series1";
|
||||
this.chartGraficos.Series.Add(series1);
|
||||
this.chartGraficos.Size = new System.Drawing.Size(591, 318);
|
||||
this.chartGraficos.TabIndex = 2;
|
||||
this.chartGraficos.Text = "chart1";
|
||||
|
|
|
|||
|
|
@ -391,10 +391,10 @@ namespace AgroBase.Forms.Operacoes
|
|||
|
||||
private void AtualizarInformacoesGerais()
|
||||
{
|
||||
var AB3V = Variaveis.OperacaoEmAndamento.DispSen.Dados.Sensores.FirstOrDefault(x => x.ID == "AB3V");
|
||||
var AB5V = Variaveis.OperacaoEmAndamento.DispSen.Dados.Sensores.FirstOrDefault(x => x.ID == "AB5V");
|
||||
var AB7V2 = Variaveis.OperacaoEmAndamento.DispSen.Dados.Sensores.FirstOrDefault(x => x.ID == "AB7V2");
|
||||
var AB12V = Variaveis.OperacaoEmAndamento.DispSen.Dados.Sensores.FirstOrDefault(x => x.ID == "AB12V");
|
||||
var AB3V = Variaveis.OperacaoEmAndamento.DispSen.Dados.DadosLeitura.SensoresCorrente.FirstOrDefault(x => x.ID == "AB3V");
|
||||
var AB5V = Variaveis.OperacaoEmAndamento.DispSen.Dados.DadosLeitura.SensoresCorrente.FirstOrDefault(x => x.ID == "AB5V");
|
||||
var AB7V2 = Variaveis.OperacaoEmAndamento.DispSen.Dados.DadosLeitura.SensoresCorrente.FirstOrDefault(x => x.ID == "AB7V2");
|
||||
var AB12V = Variaveis.OperacaoEmAndamento.DispSen.Dados.DadosLeitura.SensoresCorrente.FirstOrDefault(x => x.ID == "AB12V");
|
||||
|
||||
gridDados.Rows[0].Cells[1].Value = Variaveis.OperacaoEmAndamento.Tempo.Hours.ToString("00") + ":" + Variaveis.OperacaoEmAndamento.Tempo.Minutes.ToString("00") + ":" + Variaveis.OperacaoEmAndamento.Tempo.Seconds.ToString("00");
|
||||
gridDados.Rows[1].Cells[1].Value = TimeSpan.FromSeconds(Variaveis.OperacaoEmAndamento.DispMvd.Dados.TempoEmAtividade).ToString(@"hh\:mm\:ss");
|
||||
|
|
@ -403,14 +403,14 @@ namespace AgroBase.Forms.Operacoes
|
|||
gridDados.Rows[4].Cells[1].Value = (PZEMService.Iniciado && PZEMService.UltimaLeitura != null ? Variaveis.OperacaoEmAndamento.Sensoriamento.PorcentagemBateria.ToString("00.00") : "");
|
||||
gridDados.Rows[5].Cells[1].Value = (PZEMService.Iniciado && PZEMService.UltimaLeitura != null ? PZEMService.UltimaLeitura.Tensao.ToString("0.00") : "");
|
||||
gridDados.Rows[6].Cells[1].Value = (PZEMService.Iniciado && PZEMService.UltimaLeitura != null ? PZEMService.UltimaLeitura.Corrente.ToString("0.00") : "");
|
||||
gridDados.Rows[7].Cells[1].Value = (AB3V != null && AB3V.Leituras != null && AB3V.Leituras.Count() > 0 ? AB3V.Leituras[0] : 0).ToString("0.00");
|
||||
gridDados.Rows[8].Cells[1].Value = (AB3V != null && AB3V.Leituras != null && AB3V.Leituras.Count() > 1 ? AB3V.Leituras[1] : 0).ToString("0.00");
|
||||
gridDados.Rows[9].Cells[1].Value = (AB5V != null && AB5V.Leituras != null && AB5V.Leituras.Count() > 0 ? AB5V.Leituras[0] : 0).ToString("0.00");
|
||||
gridDados.Rows[10].Cells[1].Value = (AB5V != null && AB5V.Leituras != null && AB5V.Leituras.Count() > 1 ? AB5V.Leituras[1] : 0).ToString("0.00");
|
||||
gridDados.Rows[11].Cells[1].Value = (AB7V2 != null && AB7V2.Leituras != null && AB7V2.Leituras.Count() > 0 ? AB7V2.Leituras[0] : 0).ToString("0.00");
|
||||
gridDados.Rows[12].Cells[1].Value = (AB7V2 != null && AB7V2.Leituras != null && AB7V2.Leituras.Count() > 1 ? AB7V2.Leituras[1] : 0).ToString("0.00");
|
||||
gridDados.Rows[13].Cells[1].Value = (AB12V != null && AB12V.Leituras != null && AB12V.Leituras.Count() > 0 ? AB12V.Leituras[0] : 0).ToString("0.00");
|
||||
gridDados.Rows[14].Cells[1].Value = (AB12V != null && AB12V.Leituras != null && AB12V.Leituras.Count() > 1 ? AB12V.Leituras[1] : 0).ToString("0.00");
|
||||
gridDados.Rows[7].Cells[1].Value = (AB3V != null ? AB3V.BusVoltage : 0).ToString("0.00");
|
||||
gridDados.Rows[8].Cells[1].Value = (AB3V != null ? (double)AB3V.Current : 0).ToString("0.00");
|
||||
gridDados.Rows[9].Cells[1].Value = (AB5V != null ? AB5V.BusVoltage : 0).ToString("0.00");
|
||||
gridDados.Rows[10].Cells[1].Value = (AB5V != null ? (double)AB5V.Current : 0).ToString("0.00");
|
||||
gridDados.Rows[11].Cells[1].Value = (AB7V2 != null ? AB7V2.BusVoltage : 0).ToString("0.00");
|
||||
gridDados.Rows[12].Cells[1].Value = (AB7V2 != null ? (double)AB7V2.Current : 0).ToString("0.00");
|
||||
gridDados.Rows[13].Cells[1].Value = (AB12V != null ? AB12V.BusVoltage : 0).ToString("0.00");
|
||||
gridDados.Rows[14].Cells[1].Value = (AB12V != null ? (double)AB12V.Current : 0).ToString("0.00");
|
||||
gridDados.Rows[15].Cells[1].Value = Variaveis.OperacaoEmAndamento.DispAtu.Dados.PercentualReservatorio.ToString("00.00");
|
||||
gridDados.Rows[16].Cells[1].Value = Variaveis.OperacaoEmAndamento.DispAtu.Dados.VolumeReservatorio.ToString("0.000");
|
||||
gridDados.Rows[17].Cells[1].Value = Variaveis.OperacaoEmAndamento.DispAtu.Dados.PressaoLinha.ToString("0.00");
|
||||
|
|
|
|||
|
|
@ -53,10 +53,10 @@ namespace AgroBase.Forms.Operacoes
|
|||
|
||||
private void AtualizarDispositivos()
|
||||
{
|
||||
chbMOVativo.Checked = Variaveis.OperacaoEmAndamento.DispMvd != null && Variaveis.OperacaoEmAndamento.DispMvd._Porta.IsOpen && Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.Any(x => x.MovMotor.Inicializado);
|
||||
chbDIRativo.Checked = Variaveis.OperacaoEmAndamento.DispMvd != null && Variaveis.OperacaoEmAndamento.DispMvd._Porta.IsOpen && Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.Any(x => x.DirMotor.Inicializado);
|
||||
chbATUativo.Checked = Variaveis.OperacaoEmAndamento.DispAtu != null && Variaveis.OperacaoEmAndamento.DispAtu._Porta.IsOpen;
|
||||
chbGPSativo.Checked = GPSService.PortaGPS != null && GPSService.PortaGPS.IsOpen;
|
||||
chbMOVativo.Checked = Variaveis.OperacaoEmAndamento.DispMvd?.Dados?.Modulos?.Any(x => x.MovMotor.Inicializado) ?? false;
|
||||
chbDIRativo.Checked = Variaveis.OperacaoEmAndamento.DispMvd?.Dados?.Modulos?.Any(x => x.DirMotor.Inicializado) ?? false;
|
||||
chbATUativo.Checked = Variaveis.OperacaoEmAndamento.DispAtu?.Dados.Conectado ?? false;
|
||||
chbGPSativo.Checked = GPSService.PortaGPS?.IsOpen ?? false;
|
||||
Variaveis.OperacaoEmAndamento.chartGraficos = chartGraficos;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ namespace AgroBase.Forms.Operacoes
|
|||
List<DirSensoriamentoLogModel> LogsDirecional = new List<DirSensoriamentoLogModel>();
|
||||
List<MovSensoriamentoLogModel> LogsMovimentacao = new List<MovSensoriamentoLogModel>();
|
||||
List<AtuSensoriamentoLogModel> LogsAtuador = new List<AtuSensoriamentoLogModel>();
|
||||
List<SenSensoriamentoLogModel> LogsSensoriamento = new List<SenSensoriamentoLogModel>();
|
||||
List<SensoriamentoMensagemJsonModel> LogsSensoriamento = new List<SensoriamentoMensagemJsonModel>();
|
||||
List<PzmSensoriamentoLogModel> LogsPzem = new List<PzmSensoriamentoLogModel>();
|
||||
List<WitSensoriamentoLogModel> LogsWt901C = new List<WitSensoriamentoLogModel>();
|
||||
List<UltrasonicA05Model> LogsA05 = new List<UltrasonicA05Model>();
|
||||
|
|
@ -132,7 +132,7 @@ namespace AgroBase.Forms.Operacoes
|
|||
LogsDirecional = JsonConvert.DeserializeObject<DirSensoriamentoLogModel[]>(DeserializarDadosOperacao(ofd.FileName, data.dir ?? Enums.T_Code.Dir.ToString())).ToList();
|
||||
LogsMovimentacao = JsonConvert.DeserializeObject<MovSensoriamentoLogModel[]>(DeserializarDadosOperacao(ofd.FileName, data.mov ?? Enums.T_Code.Mov.ToString())).ToList();
|
||||
LogsAtuador = JsonConvert.DeserializeObject<AtuSensoriamentoLogModel[]>(DeserializarDadosOperacao(ofd.FileName, data.atu ?? Enums.T_Code.Atu.ToString())).ToList();
|
||||
LogsSensoriamento = JsonConvert.DeserializeObject<SenSensoriamentoLogModel[]>(DeserializarDadosOperacao(ofd.FileName, data.sen ?? Enums.T_Code.Sen.ToString())).ToList();
|
||||
LogsSensoriamento = JsonConvert.DeserializeObject<SensoriamentoMensagemJsonModel[]>(DeserializarDadosOperacao(ofd.FileName, data.sen ?? Enums.T_Code.Sen.ToString())).ToList();
|
||||
LogsPzem = JsonConvert.DeserializeObject<PzmSensoriamentoLogModel[]>(DeserializarDadosOperacao(ofd.FileName, data.pzm ?? Enums.T_Code.Pzm.ToString())).ToList();
|
||||
LogsWt901C = JsonConvert.DeserializeObject<WitSensoriamentoLogModel[]>(DeserializarDadosOperacao(ofd.FileName, data.wit ?? Enums.T_Code.Wit.ToString())).ToList();
|
||||
LogsA05 = JsonConvert.DeserializeObject<UltrasonicA05Model[]>(DeserializarDadosOperacao(ofd.FileName, data.a05 ?? Enums.T_Code.A05.ToString())).ToList();
|
||||
|
|
@ -394,49 +394,49 @@ namespace AgroBase.Forms.Operacoes
|
|||
new GraficoInterativoSerieModel()
|
||||
{
|
||||
Titulo = "V 3v3",
|
||||
Valores = LogsSensoriamento.Select(x => x?.Barramento3v3Tensao ?? 0).ToList(),
|
||||
Valores = LogsSensoriamento.Select(x => x?.SensoresCorrente?.FirstOrDefault(y => y.ID.Contains("3v")).BusVoltage ?? 0).ToList(),
|
||||
Visivel = false,
|
||||
},
|
||||
new GraficoInterativoSerieModel()
|
||||
{
|
||||
Titulo = "A 3v3",
|
||||
Valores = LogsSensoriamento.Select(x => x?.Barramento3v3Corrente ?? 0).ToList(),
|
||||
Valores = LogsSensoriamento.Select(x => x?.SensoresCorrente?.FirstOrDefault(y => y.ID.Contains("3v")).Current ?? 0).ToList(),
|
||||
Visivel = false,
|
||||
},
|
||||
new GraficoInterativoSerieModel()
|
||||
{
|
||||
Titulo = "V 5v0",
|
||||
Valores = LogsSensoriamento.Select(x => x?.Barramento5vTensao ?? 0).ToList(),
|
||||
Valores = LogsSensoriamento.Select(x => x?.SensoresCorrente?.FirstOrDefault(y => y.ID.Contains("5v")).BusVoltage ?? 0).ToList(),
|
||||
Visivel = false,
|
||||
},
|
||||
new GraficoInterativoSerieModel()
|
||||
{
|
||||
Titulo = "A 5v0",
|
||||
Valores = LogsSensoriamento.Select(x => x?.Barramento5vCorrente ?? 0).ToList(),
|
||||
Valores = LogsSensoriamento.Select(x => x?.SensoresCorrente?.FirstOrDefault(y => y.ID.Contains("5v")).Current ?? 0).ToList(),
|
||||
Visivel = false,
|
||||
},
|
||||
new GraficoInterativoSerieModel()
|
||||
{
|
||||
Titulo = "V 7v2",
|
||||
Valores = LogsSensoriamento.Select(x => x?.Barramento7v2Tensao ?? 0).ToList(),
|
||||
Valores = LogsSensoriamento.Select(x => x?.SensoresCorrente?.FirstOrDefault(y => y.ID.Contains("7v2")).BusVoltage ?? 0).ToList(),
|
||||
Visivel = false,
|
||||
},
|
||||
new GraficoInterativoSerieModel()
|
||||
{
|
||||
Titulo = "A 7v2",
|
||||
Valores = LogsSensoriamento.Select(x => x?.Barramento7v2Corrente ?? 0).ToList(),
|
||||
Valores = LogsSensoriamento.Select(x => x?.SensoresCorrente?.FirstOrDefault(y => y.ID.Contains("7v2")).Current ?? 0).ToList(),
|
||||
Visivel = false,
|
||||
},
|
||||
new GraficoInterativoSerieModel()
|
||||
{
|
||||
Titulo = "V 12v",
|
||||
Valores = LogsSensoriamento.Select(x => x?.Barramento12vTensao ?? 0).ToList(),
|
||||
Valores = LogsSensoriamento.Select(x => x?.SensoresCorrente?.FirstOrDefault(y => y.ID.Contains("12v")).BusVoltage ?? 0).ToList(),
|
||||
Visivel = true,
|
||||
},
|
||||
new GraficoInterativoSerieModel()
|
||||
{
|
||||
Titulo = "A 12v",
|
||||
Valores = LogsSensoriamento.Select(x => x?.Barramento12vCorrente ?? 0).ToList(),
|
||||
Valores = LogsSensoriamento.Select(x => x?.SensoresCorrente?.FirstOrDefault(y => y.ID.Contains("12v")).Current ?? 0).ToList(),
|
||||
Visivel = true,
|
||||
},
|
||||
new GraficoInterativoSerieModel()
|
||||
|
|
@ -907,10 +907,10 @@ namespace AgroBase.Forms.Operacoes
|
|||
var Log = LogsMovimentacao.FirstOrDefault(x => x.Momento == MomentoAtual && x.Modulo_ID == ID);
|
||||
var Log_Sen = LogsSensoriamento.FirstOrDefault(x => x.Momento == MomentoAtual);
|
||||
bool freio =
|
||||
(ID.Contains("ET") && Log_Sen.AnguloFreioET > 0 && Log_Sen.AnguloFreioET < 180) ||
|
||||
(ID.Contains("DT") && Log_Sen.AnguloFreioDT > 0 && Log_Sen.AnguloFreioDT < 180) ||
|
||||
(ID.Contains("EF") && Log_Sen.AnguloFreioEF > 0 && Log_Sen.AnguloFreioEF < 180) ||
|
||||
(ID.Contains("DF") && Log_Sen.AnguloFreioDF > 0 && Log_Sen.AnguloFreioDF < 180);
|
||||
(ID.Contains("ET") && Log_Sen.ServoFreios?.FirstOrDefault(x => x.ID.Contains("ET"))?.Angulo > 0 && Log_Sen.ServoFreios?.FirstOrDefault(x => x.ID.Contains("ET"))?.Angulo < 180) ||
|
||||
(ID.Contains("DT") && Log_Sen.ServoFreios?.FirstOrDefault(x => x.ID.Contains("DT"))?.Angulo > 0 && Log_Sen.ServoFreios?.FirstOrDefault(x => x.ID.Contains("DT"))?.Angulo < 180) ||
|
||||
(ID.Contains("EF") && Log_Sen.ServoFreios?.FirstOrDefault(x => x.ID.Contains("EF"))?.Angulo > 0 && Log_Sen.ServoFreios?.FirstOrDefault(x => x.ID.Contains("EF"))?.Angulo < 180) ||
|
||||
(ID.Contains("DF") && Log_Sen.ServoFreios?.FirstOrDefault(x => x.ID.Contains("DF"))?.Angulo > 0 && Log_Sen.ServoFreios?.FirstOrDefault(x => x.ID.Contains("DF"))?.Angulo < 180);
|
||||
|
||||
GroupBox gpbRpm = FuncoesGlobais.FindControlRecursive<GroupBox>(tabMovGreal, "gpbMOV_Geral_" + ID);
|
||||
gpbRpm.ForeColor = !Log.Inicializado ? Color.Red : Color.Black;
|
||||
|
|
@ -983,9 +983,9 @@ namespace AgroBase.Forms.Operacoes
|
|||
txtPressao.Text = LogWit.Pressao + " Pa (" + (LogWit.Pressao / 101300.0).ToString("0.00") + " atm)";
|
||||
|
||||
var LogSen = LogsSensoriamento.FirstOrDefault(x => x.Momento == MomentoAtual);
|
||||
pnlManual.BackColor = LogSen.StatusSinaleiroMN == Enums.StatusLED.Aceso ? Color.Yellow : Color.Gold;
|
||||
pnlAutomatico.BackColor = LogSen.StatusSinaleiroAT == Enums.StatusLED.Aceso ? Color.Yellow : Color.Gold;
|
||||
pnlOperacao.BackColor = LogSen.StatusSinaleiroOP == Enums.StatusLED.Aceso ? Color.Green : Color.DarkGreen;
|
||||
pnlManual.BackColor = LogSen.Sinaleiros?.FirstOrDefault(x => x.ID.Contains("MN"))?.Leitura == Enums.StatusLED.Aceso ? Color.Yellow : Color.Gold;
|
||||
pnlAutomatico.BackColor = LogSen.Sinaleiros?.FirstOrDefault(x => x.ID.Contains("AT"))?.Leitura == Enums.StatusLED.Aceso ? Color.Yellow : Color.Gold;
|
||||
pnlOperacao.BackColor = LogSen.Sinaleiros?.FirstOrDefault(x => x.ID.Contains("OP"))?.Leitura == Enums.StatusLED.Aceso ? Color.Green : Color.DarkGreen;
|
||||
|
||||
var LogA05 = LogsA05.FirstOrDefault(x => x.Momento == MomentoAtual);
|
||||
|
||||
|
|
|
|||
|
|
@ -58,10 +58,9 @@
|
|||
this.cmbSoloEsq = new System.Windows.Forms.ComboBox();
|
||||
this.lblCaminho = new System.Windows.Forms.Label();
|
||||
this.cmbCaminho = new System.Windows.Forms.ComboBox();
|
||||
this.btnFreio = new System.Windows.Forms.Button();
|
||||
this.cmbModFreio = new System.Windows.Forms.ComboBox();
|
||||
this.label1 = new System.Windows.Forms.Label();
|
||||
this.chbRequisitarDados = new System.Windows.Forms.CheckBox();
|
||||
this.lblIP = new System.Windows.Forms.Label();
|
||||
this.txtIP = new System.Windows.Forms.TextBox();
|
||||
((System.ComponentModel.ISupportInitialize)(this.gridsTEN)).BeginInit();
|
||||
((System.ComponentModel.ISupportInitialize)(this.gridsCOR)).BeginInit();
|
||||
((System.ComponentModel.ISupportInitialize)(this.gridsTMP)).BeginInit();
|
||||
|
|
@ -95,7 +94,7 @@
|
|||
// btnSalvar
|
||||
//
|
||||
this.btnSalvar.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
|
||||
this.btnSalvar.Location = new System.Drawing.Point(867, 575);
|
||||
this.btnSalvar.Location = new System.Drawing.Point(863, 566);
|
||||
this.btnSalvar.Name = "btnSalvar";
|
||||
this.btnSalvar.Size = new System.Drawing.Size(75, 23);
|
||||
this.btnSalvar.TabIndex = 3;
|
||||
|
|
@ -213,10 +212,10 @@
|
|||
//
|
||||
// btnBateriaVer
|
||||
//
|
||||
this.btnBateriaVer.Location = new System.Drawing.Point(8, 54);
|
||||
this.btnBateriaVer.Location = new System.Drawing.Point(8, 59);
|
||||
this.btnBateriaVer.Margin = new System.Windows.Forms.Padding(2);
|
||||
this.btnBateriaVer.Name = "btnBateriaVer";
|
||||
this.btnBateriaVer.Size = new System.Drawing.Size(135, 19);
|
||||
this.btnBateriaVer.Size = new System.Drawing.Size(135, 25);
|
||||
this.btnBateriaVer.TabIndex = 16;
|
||||
this.btnBateriaVer.Text = "Ver valor";
|
||||
this.btnBateriaVer.UseVisualStyleBackColor = true;
|
||||
|
|
@ -226,7 +225,7 @@
|
|||
//
|
||||
this.cmbBateriaParametro.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
|
||||
this.cmbBateriaParametro.FormattingEnabled = true;
|
||||
this.cmbBateriaParametro.Location = new System.Drawing.Point(7, 30);
|
||||
this.cmbBateriaParametro.Location = new System.Drawing.Point(8, 34);
|
||||
this.cmbBateriaParametro.Margin = new System.Windows.Forms.Padding(2);
|
||||
this.cmbBateriaParametro.Name = "cmbBateriaParametro";
|
||||
this.cmbBateriaParametro.Size = new System.Drawing.Size(137, 21);
|
||||
|
|
@ -235,7 +234,7 @@
|
|||
// label2
|
||||
//
|
||||
this.label2.AutoSize = true;
|
||||
this.label2.Location = new System.Drawing.Point(5, 15);
|
||||
this.label2.Location = new System.Drawing.Point(5, 18);
|
||||
this.label2.Name = "label2";
|
||||
this.label2.Size = new System.Drawing.Size(55, 13);
|
||||
this.label2.TabIndex = 19;
|
||||
|
|
@ -243,7 +242,7 @@
|
|||
//
|
||||
// nudBateriaValor
|
||||
//
|
||||
this.nudBateriaValor.Location = new System.Drawing.Point(8, 79);
|
||||
this.nudBateriaValor.Location = new System.Drawing.Point(8, 88);
|
||||
this.nudBateriaValor.Margin = new System.Windows.Forms.Padding(2);
|
||||
this.nudBateriaValor.Name = "nudBateriaValor";
|
||||
this.nudBateriaValor.Size = new System.Drawing.Size(64, 20);
|
||||
|
|
@ -252,7 +251,7 @@
|
|||
//
|
||||
// btnBateriaDefinir
|
||||
//
|
||||
this.btnBateriaDefinir.Location = new System.Drawing.Point(76, 78);
|
||||
this.btnBateriaDefinir.Location = new System.Drawing.Point(76, 87);
|
||||
this.btnBateriaDefinir.Margin = new System.Windows.Forms.Padding(2);
|
||||
this.btnBateriaDefinir.Name = "btnBateriaDefinir";
|
||||
this.btnBateriaDefinir.Size = new System.Drawing.Size(67, 19);
|
||||
|
|
@ -273,17 +272,17 @@
|
|||
this.gpbBateria.Margin = new System.Windows.Forms.Padding(2);
|
||||
this.gpbBateria.Name = "gpbBateria";
|
||||
this.gpbBateria.Padding = new System.Windows.Forms.Padding(2);
|
||||
this.gpbBateria.Size = new System.Drawing.Size(154, 121);
|
||||
this.gpbBateria.Size = new System.Drawing.Size(154, 147);
|
||||
this.gpbBateria.TabIndex = 22;
|
||||
this.gpbBateria.TabStop = false;
|
||||
this.gpbBateria.Text = "Bateria";
|
||||
//
|
||||
// btnBateriaCalibrar
|
||||
//
|
||||
this.btnBateriaCalibrar.Location = new System.Drawing.Point(8, 99);
|
||||
this.btnBateriaCalibrar.Location = new System.Drawing.Point(8, 112);
|
||||
this.btnBateriaCalibrar.Margin = new System.Windows.Forms.Padding(2);
|
||||
this.btnBateriaCalibrar.Name = "btnBateriaCalibrar";
|
||||
this.btnBateriaCalibrar.Size = new System.Drawing.Size(135, 19);
|
||||
this.btnBateriaCalibrar.Size = new System.Drawing.Size(135, 23);
|
||||
this.btnBateriaCalibrar.TabIndex = 22;
|
||||
this.btnBateriaCalibrar.Text = "Calibrar";
|
||||
this.btnBateriaCalibrar.UseVisualStyleBackColor = true;
|
||||
|
|
@ -302,17 +301,17 @@
|
|||
this.gpbCameras.Margin = new System.Windows.Forms.Padding(2);
|
||||
this.gpbCameras.Name = "gpbCameras";
|
||||
this.gpbCameras.Padding = new System.Windows.Forms.Padding(2);
|
||||
this.gpbCameras.Size = new System.Drawing.Size(197, 121);
|
||||
this.gpbCameras.Size = new System.Drawing.Size(197, 147);
|
||||
this.gpbCameras.TabIndex = 23;
|
||||
this.gpbCameras.TabStop = false;
|
||||
this.gpbCameras.Text = "Câmeras";
|
||||
//
|
||||
// btnAtualizarCameras
|
||||
//
|
||||
this.btnAtualizarCameras.Location = new System.Drawing.Point(64, 99);
|
||||
this.btnAtualizarCameras.Location = new System.Drawing.Point(64, 112);
|
||||
this.btnAtualizarCameras.Margin = new System.Windows.Forms.Padding(2);
|
||||
this.btnAtualizarCameras.Name = "btnAtualizarCameras";
|
||||
this.btnAtualizarCameras.Size = new System.Drawing.Size(129, 19);
|
||||
this.btnAtualizarCameras.Size = new System.Drawing.Size(129, 23);
|
||||
this.btnAtualizarCameras.TabIndex = 26;
|
||||
this.btnAtualizarCameras.Text = "Atualizar";
|
||||
this.btnAtualizarCameras.UseVisualStyleBackColor = true;
|
||||
|
|
@ -372,55 +371,43 @@
|
|||
this.cmbCaminho.Size = new System.Drawing.Size(129, 21);
|
||||
this.cmbCaminho.TabIndex = 20;
|
||||
//
|
||||
// btnFreio
|
||||
//
|
||||
this.btnFreio.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
|
||||
this.btnFreio.Location = new System.Drawing.Point(867, 543);
|
||||
this.btnFreio.Name = "btnFreio";
|
||||
this.btnFreio.Size = new System.Drawing.Size(75, 23);
|
||||
this.btnFreio.TabIndex = 24;
|
||||
this.btnFreio.Text = "Freio";
|
||||
this.btnFreio.UseVisualStyleBackColor = true;
|
||||
this.btnFreio.Click += new System.EventHandler(this.btnFreio_Click);
|
||||
//
|
||||
// cmbModFreio
|
||||
//
|
||||
this.cmbModFreio.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
|
||||
this.cmbModFreio.FormattingEnabled = true;
|
||||
this.cmbModFreio.Location = new System.Drawing.Point(867, 500);
|
||||
this.cmbModFreio.Margin = new System.Windows.Forms.Padding(2);
|
||||
this.cmbModFreio.Name = "cmbModFreio";
|
||||
this.cmbModFreio.Size = new System.Drawing.Size(75, 21);
|
||||
this.cmbModFreio.TabIndex = 27;
|
||||
//
|
||||
// label1
|
||||
//
|
||||
this.label1.AutoSize = true;
|
||||
this.label1.Location = new System.Drawing.Point(864, 485);
|
||||
this.label1.Name = "label1";
|
||||
this.label1.Size = new System.Drawing.Size(42, 13);
|
||||
this.label1.TabIndex = 27;
|
||||
this.label1.Text = "Módulo";
|
||||
//
|
||||
// chbRequisitarDados
|
||||
//
|
||||
this.chbRequisitarDados.AutoSize = true;
|
||||
this.chbRequisitarDados.Location = new System.Drawing.Point(15, 584);
|
||||
this.chbRequisitarDados.Location = new System.Drawing.Point(853, 508);
|
||||
this.chbRequisitarDados.Name = "chbRequisitarDados";
|
||||
this.chbRequisitarDados.Size = new System.Drawing.Size(107, 17);
|
||||
this.chbRequisitarDados.TabIndex = 28;
|
||||
this.chbRequisitarDados.Text = "Requisitar Dados";
|
||||
this.chbRequisitarDados.UseVisualStyleBackColor = true;
|
||||
//
|
||||
// lblIP
|
||||
//
|
||||
this.lblIP.AutoSize = true;
|
||||
this.lblIP.Location = new System.Drawing.Point(850, 459);
|
||||
this.lblIP.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
|
||||
this.lblIP.Name = "lblIP";
|
||||
this.lblIP.Size = new System.Drawing.Size(17, 13);
|
||||
this.lblIP.TabIndex = 145;
|
||||
this.lblIP.Text = "IP";
|
||||
//
|
||||
// txtIP
|
||||
//
|
||||
this.txtIP.Location = new System.Drawing.Point(853, 476);
|
||||
this.txtIP.Margin = new System.Windows.Forms.Padding(2);
|
||||
this.txtIP.Name = "txtIP";
|
||||
this.txtIP.Size = new System.Drawing.Size(85, 20);
|
||||
this.txtIP.TabIndex = 144;
|
||||
this.txtIP.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
|
||||
//
|
||||
// frmSenConfig
|
||||
//
|
||||
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
|
||||
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
|
||||
this.ClientSize = new System.Drawing.Size(954, 606);
|
||||
this.ClientSize = new System.Drawing.Size(961, 606);
|
||||
this.Controls.Add(this.lblIP);
|
||||
this.Controls.Add(this.txtIP);
|
||||
this.Controls.Add(this.chbRequisitarDados);
|
||||
this.Controls.Add(this.label1);
|
||||
this.Controls.Add(this.cmbModFreio);
|
||||
this.Controls.Add(this.btnFreio);
|
||||
this.Controls.Add(this.gpbCameras);
|
||||
this.Controls.Add(this.gpbBateria);
|
||||
this.Controls.Add(this.lblUltrassom);
|
||||
|
|
@ -491,9 +478,8 @@
|
|||
private System.Windows.Forms.ComboBox cmbCaminho;
|
||||
private System.Windows.Forms.Button btnBateriaCalibrar;
|
||||
private System.Windows.Forms.Button btnAtualizarCameras;
|
||||
private System.Windows.Forms.Button btnFreio;
|
||||
private System.Windows.Forms.ComboBox cmbModFreio;
|
||||
private System.Windows.Forms.Label label1;
|
||||
private System.Windows.Forms.CheckBox chbRequisitarDados;
|
||||
private System.Windows.Forms.Label lblIP;
|
||||
private System.Windows.Forms.TextBox txtIP;
|
||||
}
|
||||
}
|
||||
|
|
@ -4,7 +4,6 @@ using AgroBase.Models.Modules;
|
|||
using AgroBase.Services;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
|
|
@ -47,12 +46,14 @@ namespace AgroBase.Forms.Sensoriamento
|
|||
case T_Code.Atu:
|
||||
{
|
||||
Sensores = ((AtuadorModel)Disp.Dados).Sensores.ToList();
|
||||
chbRequisitarDados.Checked = false;
|
||||
chbRequisitarDados.Checked = ((AtuadorModel)Disp.Dados).RequisitarDados;
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
txtIP.Text = Disp.Dados.GetIP();
|
||||
|
||||
PopulaParametrosSensor();
|
||||
|
||||
PreencheParametrosSensores();
|
||||
|
|
@ -61,10 +62,6 @@ namespace AgroBase.Forms.Sensoriamento
|
|||
cmbBateriaParametro.Items.Add("Carga Consumida");
|
||||
cmbBateriaParametro.Items.AddRange(PZEMService.Parametros.Keys.ToArray());
|
||||
cmbBateriaParametro.SelectedIndex = 0;
|
||||
|
||||
cmbModFreio.Items.Clear();
|
||||
cmbModFreio.Items.AddRange(Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.Select(x => x.Modulo_ID).ToArray());
|
||||
cmbModFreio.SelectedIndex = 0;
|
||||
}
|
||||
|
||||
private void AtualizarCameras()
|
||||
|
|
@ -199,6 +196,7 @@ namespace AgroBase.Forms.Sensoriamento
|
|||
case T_Code.Sen:
|
||||
{
|
||||
var _Disp = (DispositivosService<SensoriamentoModel>)Variaveis.DispositivosConectados.FirstOrDefault(x => x.Dispositivo == Dispositivo);
|
||||
_Disp.Dados.IP = txtIP.Text;
|
||||
_Disp.Dados.RequisitarDados = chbRequisitarDados.Checked;
|
||||
_Disp.Dados.Sensores = Sensores.ToList();
|
||||
_Disp.Dados.CameraID_Caminho = cmbCaminho.Text;
|
||||
|
|
@ -210,6 +208,8 @@ namespace AgroBase.Forms.Sensoriamento
|
|||
case T_Code.Atu:
|
||||
{
|
||||
var _Disp = (DispositivosService<AtuadorModel>)Variaveis.DispositivosConectados.FirstOrDefault(x => x.Dispositivo == Dispositivo);
|
||||
_Disp.Dados.IP = txtIP.Text;
|
||||
_Disp.Dados.RequisitarDados = chbRequisitarDados.Checked;
|
||||
_Disp.Dados.Sensores = Sensores.ToList();
|
||||
_Disp.SalvarParametros(_Disp.Dados);
|
||||
break;
|
||||
|
|
@ -275,30 +275,5 @@ namespace AgroBase.Forms.Sensoriamento
|
|||
ModbusService.AdicionarComandoNaFila(Comando);
|
||||
}
|
||||
|
||||
private void btnFreio_Click(object sender, EventArgs e)
|
||||
{
|
||||
string Mod_ID = cmbModFreio.Text;
|
||||
var Modulo = Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.First(x => x.Modulo_ID == Mod_ID);
|
||||
var ServoFreio = Variaveis.OperacaoEmAndamento.DispSen.Dados.Servos.FirstOrDefault(x => x.ID.Contains(Modulo.Modulo_ID) && x.Inicializado);
|
||||
if (ServoFreio != null)
|
||||
{
|
||||
if (!Modulo.MovMotor.ConfigFreio.Controle)
|
||||
{
|
||||
(bool atuar, int angulo) = Modulo.MovMotor.ConfigFreio.AtualizarDadosFreio(true, 0, -1, 5);
|
||||
if (atuar)
|
||||
{
|
||||
GeneralJoystick.EnviarComandoSensoriamento(S_Code.sFRO, ServoFreio.ID, angulo);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
(bool atuar, int angulo) = Modulo.MovMotor.ConfigFreio.AtualizarDadosFreio(false);
|
||||
if (atuar)
|
||||
{
|
||||
GeneralJoystick.EnviarComandoSensoriamento(S_Code.sFRO, ServoFreio.ID, angulo);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -69,24 +69,24 @@ namespace AgroBase.Forms
|
|||
}
|
||||
if (Variaveis.OperacaoEmAndamento.DispSen.Dados.Conectado)
|
||||
{
|
||||
AtualizarDadosSensor("AB3V", lblB3V);
|
||||
AtualizarDadosSensor("AB5V", lblB5V);
|
||||
AtualizarDadosSensor("AB7V2", lblB7V2);
|
||||
AtualizarDadosSensor("AB12V", lblB12V);
|
||||
AtualizarDadosSensorCorrente("AB3V", lblB3V);
|
||||
AtualizarDadosSensorCorrente("AB5V", lblB5V);
|
||||
AtualizarDadosSensorCorrente("AB7V2", lblB7V2);
|
||||
AtualizarDadosSensorCorrente("AB12V", lblB12V);
|
||||
}
|
||||
}
|
||||
|
||||
private void AtualizarDadosSensor(string id, Label lbl)
|
||||
private void AtualizarDadosSensorCorrente(string id, Label lbl)
|
||||
{
|
||||
var sensor = Variaveis.OperacaoEmAndamento.DispSen.Dados.Sensores.FirstOrDefault(x => x.ID == id);
|
||||
double d0 = 0;
|
||||
double d1 = 0;
|
||||
if (sensor != null && sensor.Inicializado && sensor.Leituras != null && sensor.Leituras.Count() > 0)
|
||||
var sensor = Variaveis.OperacaoEmAndamento.DispSen.Dados.DadosLeitura.SensoresCorrente.FirstOrDefault(x => x.ID == id);
|
||||
if (sensor != null)
|
||||
{
|
||||
d0 = sensor.Leituras?[0] ?? 0;
|
||||
d1 = sensor.Leituras?[1] ?? 0;
|
||||
double d0 = (double)sensor.Current;
|
||||
double d1 = sensor.BusVoltage;
|
||||
|
||||
lbl.Text = id.Replace("AB", "Barramento ") + ": " + d1.ToString("0.00") + " V " + d0.ToString("0.00") + " mA";
|
||||
lbl.ForeColor = sensor.Iniciado ? Color.Green : Color.Red;
|
||||
}
|
||||
lbl.Text = id.Replace("AB", "Barramento ") + ": " + d1.ToString("0.00") + " V " + d0.ToString("0.00") + " mA";
|
||||
}
|
||||
|
||||
private void AtualzarDadosMovimentacao()
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ namespace AgroBase.Forms
|
|||
public frmInstancial()
|
||||
{
|
||||
InitializeComponent();
|
||||
FilaService.IniciarRotinas();
|
||||
//FilaService.IniciarRotinas();
|
||||
//BLD300RService.IniciarRotinas();
|
||||
//MKS057DService.IniciarRotinas();
|
||||
//ModbusService.IniciarRotinas();
|
||||
|
|
@ -72,13 +72,13 @@ namespace AgroBase.Forms
|
|||
control = frmIHM;
|
||||
}
|
||||
|
||||
tmrVarreduraDispositivos = new AsyncTaskTimerModel("tmrVarreduraDispositivos", tmrVarreduraDispositivos_Tick, SerialService.InteraloVerificacao, control);
|
||||
tmrVarreduraDispositivos = new AsyncTaskTimerModel("tmrVarreduraDispositivos", tmrVarreduraDispositivos_Tick, SerialService.InteraloVerificacao, null, 15000);
|
||||
tmrVarreduraDispositivos.Start();
|
||||
}
|
||||
|
||||
private static async Task tmrVarreduraDispositivos_Tick()
|
||||
{
|
||||
await FuncoesGlobais.SafeExecuteAsync(async () => await SerialService.RealizarVarreduraPortasUSB());
|
||||
await SerialService.RealizarVarreduraPortasUSB();
|
||||
}
|
||||
|
||||
private async void IniciarConexaoMqtt()
|
||||
|
|
@ -94,10 +94,7 @@ namespace AgroBase.Forms
|
|||
|
||||
foreach (var Disp in Variaveis.DispositivosConectados)
|
||||
{
|
||||
if (Disp._Porta.IsOpen)
|
||||
{
|
||||
Disp.btnConectar_Click(new object(), new EventArgs());
|
||||
}
|
||||
Disp.EnviarProtocolosConfiguracao(false);
|
||||
Disp.SalvarParametros(Disp.Dados);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -120,21 +120,6 @@ namespace AgroBase
|
|||
{
|
||||
AtualizaDadosGerais();
|
||||
|
||||
if (SerialService.DispositivosMapeados.Count == 0)
|
||||
{
|
||||
Variaveis.DispositivosConectados.Where(x => x.Dados.GetStatusConexao()).ToList().ForEach(x => x.AcaoDesconectar());
|
||||
}
|
||||
else
|
||||
{
|
||||
Variaveis.DispositivosConectados.ForEach(x =>
|
||||
{
|
||||
if (x.Dados.GetStatusConexao())
|
||||
{
|
||||
x.AcaoConexao();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
lblStripMqtt.Text = "MQTT: " + (Variaveis.MqttService.StatusConexao() ? "Conectado" : "Desconectado");
|
||||
|
||||
bool opLiberada = Variaveis.OperacaoEmAndamento.OperacaoLiberada;
|
||||
|
|
@ -144,30 +129,20 @@ namespace AgroBase
|
|||
|
||||
public void AtualizaDadosGerais()
|
||||
{
|
||||
bool PrimeiraExecucao = !Variaveis.DispositivosConectados.Any();
|
||||
|
||||
SerialService.DispositivosConexaoInicial.ForEach(Dispositivo =>
|
||||
if (Variaveis.DispositivosConectados.Any() && pnlLateral.Controls.Count == 7)
|
||||
{
|
||||
IDispositivosService dispositivoService = Variaveis.DispositivosConectados.FirstOrDefault(x => x.Dispositivo == Dispositivo);
|
||||
if (dispositivoService == null)
|
||||
SerialService.DispositivosConexaoInicial.ForEach(Dispositivo =>
|
||||
{
|
||||
dispositivoService = DispositivosServiceFactory.CreateDispositivoService(
|
||||
Dispositivo,
|
||||
"Nome: " + Enum.GetName(typeof(T_Code), Dispositivo),
|
||||
"Descrição: " + string.Join(", ", SerialService.DispositivosMapeados.Where(x => x.Dispositivo == Dispositivo).Select(x => x.Mod_ID).ToArray()),
|
||||
new SerialPort()
|
||||
);
|
||||
Variaveis.DispositivosConectados.Add(dispositivoService);
|
||||
|
||||
Control controle = dispositivoService.InstanciarDispositivo(Variaveis.DispositivosConectados.Count - 1);
|
||||
controle.Location = new System.Drawing.Point(controle.Location.X, controle.Location.Y + (Variaveis.DispositivosConectados.Count * 50));
|
||||
pnlLateral.Controls.Add(controle);
|
||||
cmbDispositivos.Items.Add(dispositivoService._Descricao);
|
||||
}
|
||||
});
|
||||
if (PrimeiraExecucao)
|
||||
{
|
||||
Variaveis.OperacaoEmAndamento = OperacaoModel.CarregarParametrosOperacaoPadrao(ModoOperacao.Manual);
|
||||
IDispositivosService dispositivoService = Variaveis.DispositivosConectados.FirstOrDefault(x => x.Dispositivo == Dispositivo);
|
||||
if (dispositivoService != null)
|
||||
{
|
||||
int idx = SerialService.DispositivosConexaoInicial.IndexOf(dispositivoService.Dispositivo);
|
||||
Control controle = dispositivoService.InstanciarDispositivo(idx);
|
||||
controle.Location = new Point(controle.Location.X, controle.Location.Y + (idx * 50));
|
||||
pnlLateral.Controls.Add(controle);
|
||||
cmbDispositivos.Items.Add(dispositivoService._Descricao);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -224,7 +199,7 @@ namespace AgroBase
|
|||
|
||||
private void cmbModoOperacao_SelectedIndexChanged(object sender, EventArgs e)
|
||||
{
|
||||
Variaveis.OperacaoEmAndamento = OperacaoModel.CarregarParametrosOperacaoPadrao((ModoOperacao)cmbModoOperacao.SelectedIndex);
|
||||
OperacaoModel.CarregarParametrosOperacaoPadrao((ModoOperacao)cmbModoOperacao.SelectedIndex);
|
||||
}
|
||||
|
||||
private void btnIniciarOperacao_Click(object sender, EventArgs e)
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
|
|
@ -59,6 +60,8 @@ namespace AgroBase.Models
|
|||
/// </summary>
|
||||
public TimeSpan TimeTick => endTask - beginTask;
|
||||
|
||||
private bool _Ticking = false;
|
||||
|
||||
private bool DebugMessages = true;
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -172,6 +175,21 @@ namespace AgroBase.Models
|
|||
{
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
lock (_timersLock)
|
||||
{
|
||||
if (Timers.Any(x => x.Id == "tmrVarreduraDispositivos" && !x.IsRunning))
|
||||
{
|
||||
Timers.First(x => x.Id == "tmrVarreduraDispositivos").Restart();
|
||||
}
|
||||
}
|
||||
|
||||
if (_Ticking)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_Ticking = true;
|
||||
|
||||
beginTask = DateTime.Now;
|
||||
|
||||
try
|
||||
|
|
@ -197,6 +215,7 @@ namespace AgroBase.Models
|
|||
{
|
||||
// Timeout atingido
|
||||
ExibirConsole($"TIMEOUT - tarefa excedeu {_timeout}ms");
|
||||
//Restart();
|
||||
}
|
||||
|
||||
endTask = DateTime.Now;
|
||||
|
|
@ -217,6 +236,7 @@ namespace AgroBase.Models
|
|||
{
|
||||
// Garante que o intervalo é respeitado entre execuções
|
||||
await Task.Delay(_interval, cancellationToken);
|
||||
_Ticking = false;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -14,7 +14,6 @@ namespace AgroBase.Models
|
|||
{
|
||||
public class CameraCaminhoModel
|
||||
{
|
||||
public AsyncTaskTimerModel tmrProcesso;
|
||||
public AsyncTaskTimerModel tmrLeitura;
|
||||
public Bitmap bitmapSegmentado;
|
||||
|
||||
|
|
@ -47,7 +46,7 @@ namespace AgroBase.Models
|
|||
public double AnguloDireito { get; set; }
|
||||
|
||||
public DateTime UltimoEnvio { get; set; } = DateTime.MinValue;
|
||||
private int DelayEnvio { get; set; } = 100;
|
||||
private int DelayEnvio { get; set; } = 500;
|
||||
|
||||
|
||||
public CameraCaminhoModel()
|
||||
|
|
@ -59,19 +58,7 @@ namespace AgroBase.Models
|
|||
{
|
||||
List<AsyncTaskTimerModel> timers = new List<AsyncTaskTimerModel>();
|
||||
|
||||
lock (AsyncTaskTimerModel._timersLock)
|
||||
{
|
||||
timers = AsyncTaskTimerModel.Timers.Where(x => x.StackTrace.Contains("CameraCaminhoModel") && x.Id.Contains(ID)).ToList();
|
||||
}
|
||||
|
||||
foreach (var timer in timers)
|
||||
{
|
||||
timer.Dispose();
|
||||
}
|
||||
|
||||
tmrProcesso = new AsyncTaskTimerModel("tmrProcesso_" + ID, tmrProcesso_Tick, 500);
|
||||
tmrProcesso.Start();
|
||||
|
||||
tmrLeitura?.Dispose();
|
||||
tmrLeitura = new AsyncTaskTimerModel("tmrLeitura_" + ID, tmrLeitura_Tick, 100);
|
||||
tmrLeitura.Start();
|
||||
}
|
||||
|
|
@ -81,7 +68,6 @@ namespace AgroBase.Models
|
|||
try
|
||||
{
|
||||
tmrLeitura?.Dispose();
|
||||
tmrProcesso?.Dispose();
|
||||
|
||||
Iniciada = false;
|
||||
Variaveis.MqttService.Topicos.Remove(camera._mqttTopico);
|
||||
|
|
@ -102,33 +88,6 @@ namespace AgroBase.Models
|
|||
}
|
||||
}
|
||||
|
||||
private async Task tmrProcesso_Tick()
|
||||
{
|
||||
if (camera._mqttTopico != null)
|
||||
{
|
||||
var Mensagem = camera._mqttTopico.Mensagens.FirstOrDefault(y => y.Momento > camera.IniciadoEm && y.Mensagem == "OK");
|
||||
if (Mensagem != null)
|
||||
{
|
||||
camera.ProntoEm = Mensagem.Momento;
|
||||
|
||||
if (browser == null)
|
||||
{
|
||||
Iniciada = true;
|
||||
if (panel != null)
|
||||
{
|
||||
panel.GetType().GetMethod("SetStyle", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).Invoke(panel, new object[] { ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true });
|
||||
panel.BackgroundImageLayout = ImageLayout.Zoom;
|
||||
/*browser = new ChromiumWebBrowser(camera.URLcamera);
|
||||
panel.Controls.Add(browser);
|
||||
browser.Dock = DockStyle.Fill;*/
|
||||
}
|
||||
}
|
||||
|
||||
tmrProcesso.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task tmrLeitura_Tick()
|
||||
{
|
||||
if (Iniciada)
|
||||
|
|
@ -137,18 +96,19 @@ namespace AgroBase.Models
|
|||
// Se ja passou 5 segundos sem ter enviado uma mensagem
|
||||
if (UltimoEnvio.AddMilliseconds(5000) < Agora)
|
||||
{
|
||||
Bitmap bitmap = null;
|
||||
lock (KinectService._lockBitmapRGB)
|
||||
{
|
||||
bitmap = (Bitmap)KinectService.bitmapRGB.Clone();
|
||||
}
|
||||
await EnviarBitmapParaProcessamento(bitmap);
|
||||
await EnviarBitmapParaProcessamento();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async Task EnviarBitmapParaProcessamento(Bitmap bitmap)
|
||||
public async Task EnviarBitmapParaProcessamento()
|
||||
{
|
||||
Bitmap bitmap = null;
|
||||
lock (KinectService._lockBitmapRGB)
|
||||
{
|
||||
bitmap = (Bitmap)KinectService.bitmapRGB.Clone();
|
||||
}
|
||||
|
||||
//Console.WriteLine("Enviando bitmap para segmentacao...");
|
||||
// Converta o Bitmap para um array de bytes no formato JPEG
|
||||
byte[] bitmapBytes;
|
||||
|
|
@ -158,13 +118,17 @@ namespace AgroBase.Models
|
|||
bitmapBytes = ms.ToArray();
|
||||
}
|
||||
|
||||
// Publique o array de bytes via MQTT
|
||||
await Variaveis.MqttService.PublishAsync(
|
||||
Variaveis.MqttService.Topicos.First(x => x.Topico == CamerasVaraiveisModel.TopicoEnvioBitmap),
|
||||
bitmapBytes
|
||||
);
|
||||
var topico = Variaveis.MqttService.Topicos.FirstOrDefault(x => x.Topico == CamerasVaraiveisModel.TopicoEnvioBitmap);
|
||||
if (topico != null)
|
||||
{
|
||||
// Publique o array de bytes via MQTT
|
||||
await Variaveis.MqttService.PublishAsync(
|
||||
topico,
|
||||
bitmapBytes
|
||||
);
|
||||
|
||||
UltimoEnvio = DateTime.Now;
|
||||
UltimoEnvio = DateTime.Now;
|
||||
}
|
||||
}
|
||||
|
||||
public Bitmap ExtraiImagemDaMensagem(string message)
|
||||
|
|
@ -200,12 +164,7 @@ namespace AgroBase.Models
|
|||
Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(DelayEnvio);
|
||||
Bitmap bitmapEnvio = null;
|
||||
lock (KinectService._lockBitmapRGB)
|
||||
{
|
||||
bitmapEnvio = (Bitmap)KinectService.bitmapRGB.Clone();
|
||||
}
|
||||
await EnviarBitmapParaProcessamento(bitmapEnvio);
|
||||
await EnviarBitmapParaProcessamento();
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,9 +1,4 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace AgroBase.Models
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,49 +1,17 @@
|
|||
using AgroBase.Services;
|
||||
using CefSharp.WinForms;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace AgroBase.Models
|
||||
{
|
||||
public class CameraSoloModel
|
||||
{
|
||||
public AsyncTaskTimerModel tmrProcesso;
|
||||
|
||||
public CameraSoloModel()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public void IniciarRotinaProcesso()
|
||||
{
|
||||
tmrProcesso = new AsyncTaskTimerModel("tmrProcesso", tmrProcesso_Tick, 500);
|
||||
tmrProcesso.Start();
|
||||
}
|
||||
|
||||
private async Task tmrProcesso_Tick()
|
||||
{
|
||||
if (camera._mqttTopico != null)
|
||||
{
|
||||
var Mensagem = camera._mqttTopico.Mensagens.FirstOrDefault(y => y.Momento > camera.IniciadoEm && y.Mensagem == "OK");
|
||||
if (Mensagem != null)
|
||||
{
|
||||
camera.ProntoEm = Mensagem.Momento;
|
||||
|
||||
if (browser == null)
|
||||
{
|
||||
Iniciada = true;
|
||||
browser = new ChromiumWebBrowser(camera.URLcamera);
|
||||
panel.Controls.Add(browser);
|
||||
browser.Dock = DockStyle.Fill;
|
||||
}
|
||||
|
||||
tmrProcesso.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void DesligarCamera()
|
||||
{
|
||||
try
|
||||
|
|
|
|||
|
|
@ -0,0 +1,98 @@
|
|||
using AgroBase.Services;
|
||||
using System.Linq;
|
||||
using static AgroBase.Models.Enums;
|
||||
|
||||
namespace AgroBase.Models
|
||||
{
|
||||
public class DispositivosModel
|
||||
{
|
||||
}
|
||||
|
||||
public class DispositivoDetalhesModel
|
||||
{
|
||||
public string Endereco { get; set; }
|
||||
public TipoConexao Tipo
|
||||
{
|
||||
get
|
||||
{
|
||||
if (Endereco.Contains("USB"))
|
||||
{
|
||||
return TipoConexao.USB;
|
||||
}
|
||||
else if (Endereco.Contains("COM"))
|
||||
{
|
||||
return TipoConexao.PortaCOM;
|
||||
}
|
||||
else if (Endereco.Contains("."))
|
||||
{
|
||||
return TipoConexao.Ethernet;
|
||||
}
|
||||
else
|
||||
{
|
||||
return TipoConexao.Desconhecido;
|
||||
}
|
||||
}
|
||||
}
|
||||
public T_Code Dispositivo { get; set; }
|
||||
public bool Erro { get; set; }
|
||||
public string Versao { get; set; }
|
||||
public string Mod_ID { get; set; }
|
||||
public bool Conectado
|
||||
{
|
||||
get
|
||||
{
|
||||
bool DispositivoConectado = false;
|
||||
|
||||
if (Dispositivo == T_Code.Gps)
|
||||
{
|
||||
DispositivoConectado = GPSService.Iniciado;
|
||||
}
|
||||
else if (Dispositivo == T_Code.Pzm)
|
||||
{
|
||||
DispositivoConectado = PZEMService.Iniciado;
|
||||
}
|
||||
else if (Dispositivo == T_Code.A05)
|
||||
{
|
||||
DispositivoConectado = UltrasonicA05Service.Iniciado;
|
||||
}
|
||||
else if (Dispositivo == T_Code.Lra)
|
||||
{
|
||||
DispositivoConectado = LoRaService.Iniciado;
|
||||
}
|
||||
else if (Dispositivo == T_Code.Wit)
|
||||
{
|
||||
DispositivoConectado = WT901CService.Iniciado;
|
||||
}
|
||||
else if (Dispositivo == T_Code.Knt)
|
||||
{
|
||||
DispositivoConectado = KinectService.Iniciado;
|
||||
}
|
||||
else if (Dispositivo == T_Code.Bld)
|
||||
{
|
||||
var Modulo = Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.FirstOrDefault(x => x.Modulo_ID == Mod_ID);
|
||||
DispositivoConectado = Modulo?.MovMotor?.BLD_Inicializado ?? false;
|
||||
}
|
||||
else if (Dispositivo == T_Code.Mks)
|
||||
{
|
||||
var Modulo = Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.FirstOrDefault(x => x.Modulo_ID == Mod_ID);
|
||||
DispositivoConectado = Modulo?.DirMotor?.MKS_Inicializado ?? false;
|
||||
}
|
||||
else
|
||||
{
|
||||
IDispositivosService dispositivoService = Variaveis.DispositivosConectados.FirstOrDefault(x => x.Dispositivo == Dispositivo && x.Dados.GetIP() == Endereco);
|
||||
if (dispositivoService != null)
|
||||
{
|
||||
return dispositivoService.Dados.GetStatusConexao();
|
||||
}
|
||||
else
|
||||
{
|
||||
DispositivoConectado = false;
|
||||
}
|
||||
}
|
||||
|
||||
return DispositivoConectado;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -64,6 +64,7 @@ namespace AgroBase.Models
|
|||
Cam = 112,
|
||||
Knt = 113,
|
||||
A05 = 114,
|
||||
Mod = 115,
|
||||
}
|
||||
|
||||
public enum F_Code
|
||||
|
|
|
|||
|
|
@ -64,7 +64,7 @@ namespace AgroBase
|
|||
{
|
||||
Func<bool> funcAtt = new Func<bool>(() =>
|
||||
{
|
||||
DispCon = Variaveis.DispositivosConectados.Where(x => x._Porta.IsOpen).ToList();
|
||||
DispCon = Variaveis.DispositivosConectados.Where(x => x.Dados.GetStatusConexao()).ToList();
|
||||
frmInstancial.frmJoystick.lblDispositivo.Text = "Dispositivos: " + (DispCon.Count == 0 ? "N/A" : string.Join(", ", DispCon.Select(x => x._Descricao + " (" + Enum.GetName(typeof(T_Code), x.Dispositivo) + ")").ToArray()));
|
||||
frmInstancial.frmPrincipal.cmbJoysticks.Items.Clear();
|
||||
|
||||
|
|
@ -505,12 +505,6 @@ namespace AgroBase
|
|||
Comando.IDcontrolar = ComandosDisp[ComandosDisp.Count - 1].IDcontrolar;
|
||||
DirecaoAtual = Direcao.Parado;
|
||||
Pressionado = true;
|
||||
|
||||
var _disp = DispCon.FirstOrDefault(x => x.Dispositivo == Comando.Dispositivo);
|
||||
if (_disp != null)
|
||||
{
|
||||
_disp.LimparBufferSerial(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Controle de Velocidade (MOV RPM SP)
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
using AgroBase.Services;
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
|
|
@ -12,18 +13,9 @@ namespace AgroBase.Models.Modules
|
|||
public class AtuadorModel : DispositivoBaseModel
|
||||
{
|
||||
public string Modulo_ID { get; set; } = T_Code.Atu.ToString();
|
||||
public string IP { get; set; } = "192.168.105.13";
|
||||
public bool RequisitarDados { get; set; } = false;
|
||||
private bool _MensagemConexaoRecebida { get; set; } = false;
|
||||
public bool MensagemConexaoRecebida(bool Reset = false)
|
||||
{
|
||||
if (Reset)
|
||||
{
|
||||
_MensagemConexaoRecebida = false;
|
||||
}
|
||||
return _MensagemConexaoRecebida;
|
||||
}
|
||||
|
||||
public static int _TaxaAmostragem { get; set; } = 500;
|
||||
public static int _TaxaAmostragem { get; set; } = 1000;
|
||||
public bool Conectado { get; set; } = false;
|
||||
public DateTime UltimoProtocoloRecebido { get; set; } = DateTime.MaxValue.AddDays(-1);
|
||||
public static PinoutDataModel Pinout { get; set; }
|
||||
|
|
@ -36,11 +28,21 @@ namespace AgroBase.Models.Modules
|
|||
public double DensidadeHerbicida { get; set; } = 1.1;
|
||||
public bool AtuacaoNivelAlto { get; set; } = true;
|
||||
public List<AtuadorBicoModel> BicosPulverizadores { get; set; } = new List<AtuadorBicoModel>();
|
||||
public AtuadorBombaModel BombaPressurizadora { get; set; } = new AtuadorBombaModel();
|
||||
public List<AtuadorBombaModel> BombasPressurizadoras { get; set; } = new List<AtuadorBombaModel>();
|
||||
public List<SensorModel> Sensores { get; set; } = new List<SensorModel>();
|
||||
public AtuadorBombaModel BombaPressurizadora
|
||||
{
|
||||
get
|
||||
{
|
||||
return BombasPressurizadoras.FirstOrDefault();
|
||||
}
|
||||
}
|
||||
public string ScriptDeteccaoErvas { get; set; } = PythonService.ScriptWeedDetector;
|
||||
|
||||
public AsyncTaskTimerModel tmrRegistrador;
|
||||
private int _TempoReconexaoComponentes = 60;
|
||||
private int _VezesLeituraReconexao = 0;
|
||||
public AtuadorMensagemJsonModel DadosLeitura { get; set; } = new AtuadorMensagemJsonModel();
|
||||
|
||||
#region MASSA
|
||||
public double _MassaRef { get; set; } = 0.8;
|
||||
|
|
@ -184,22 +186,24 @@ namespace AgroBase.Models.Modules
|
|||
QuantidadeBicos = 10,
|
||||
Conectado = false,
|
||||
BicosPulverizadores = new List<AtuadorBicoModel>(),
|
||||
BombaPressurizadora = new AtuadorBombaModel()
|
||||
BombasPressurizadoras = new List<AtuadorBombaModel>()
|
||||
{
|
||||
ID = "BOMBA",
|
||||
Comandar = false,
|
||||
Ligado = false,
|
||||
Inicializado = false,
|
||||
Pressao = 0,
|
||||
//PressaoSP = 80,
|
||||
Testando = false,
|
||||
Funcoes = new List<FuncoesPinout>()
|
||||
new AtuadorBombaModel()
|
||||
{
|
||||
FuncoesPinout.ENA,
|
||||
FuncoesPinout.CS,
|
||||
FuncoesPinout.INA,
|
||||
FuncoesPinout.INB,
|
||||
FuncoesPinout.PWM,
|
||||
ID = "BOMBA",
|
||||
Componente = S_Code.sBMB,
|
||||
Comandar = false,
|
||||
Ligado = false,
|
||||
Pressao = 0,
|
||||
Testando = false,
|
||||
Funcoes = new List<FuncoesPinout>()
|
||||
{
|
||||
FuncoesPinout.ENA,
|
||||
FuncoesPinout.CS,
|
||||
FuncoesPinout.INA,
|
||||
FuncoesPinout.INB,
|
||||
FuncoesPinout.PWM,
|
||||
}
|
||||
}
|
||||
},
|
||||
Sensores = new List<SensorModel>()
|
||||
|
|
@ -211,7 +215,6 @@ namespace AgroBase.Models.Modules
|
|||
Prioridade = 23,
|
||||
Componente = S_Code.sFLX,
|
||||
Aferir = false,
|
||||
Inicializado = false,
|
||||
Testando = false,
|
||||
Funcoes = new List<FuncoesPinout>()
|
||||
{
|
||||
|
|
@ -228,7 +231,6 @@ namespace AgroBase.Models.Modules
|
|||
Prioridade = 3,
|
||||
Componente = S_Code.sMAS,
|
||||
Aferir = false,
|
||||
Inicializado = false,
|
||||
Testando = false,
|
||||
Funcoes = new List<FuncoesPinout>()
|
||||
{
|
||||
|
|
@ -246,7 +248,6 @@ namespace AgroBase.Models.Modules
|
|||
Prioridade = 3,
|
||||
Componente = S_Code.sPRS,
|
||||
Aferir = false,
|
||||
Inicializado = false,
|
||||
Testando = false,
|
||||
Funcoes = new List<FuncoesPinout>()
|
||||
{
|
||||
|
|
@ -268,6 +269,7 @@ namespace AgroBase.Models.Modules
|
|||
Atuador.BicosPulverizadores.Add(new AtuadorBicoModel()
|
||||
{
|
||||
ID = "B" + (i + 1).ToString("00"),
|
||||
Componente = S_Code.sBIC,
|
||||
Posicao = i + 1,
|
||||
Comandar = false,
|
||||
Atuado = false,
|
||||
|
|
@ -285,18 +287,8 @@ namespace AgroBase.Models.Modules
|
|||
public static void LimparDados(AtuadorModel Dados)
|
||||
{
|
||||
Dados.Conectado = false;
|
||||
|
||||
Dados.BicosPulverizadores.ForEach(x =>
|
||||
{
|
||||
x.Inicializado = false;
|
||||
});
|
||||
|
||||
Dados.Sensores.ForEach(x =>
|
||||
{
|
||||
x.Inicializado = false;
|
||||
});
|
||||
|
||||
Dados.BombaPressurizadora.Inicializado = false;
|
||||
Dados.DadosLeitura = new AtuadorMensagemJsonModel();
|
||||
Dados.DadosLeitura.Momento = DateTime.MinValue;
|
||||
|
||||
ReiniciarLeituras(Dados);
|
||||
}
|
||||
|
|
@ -305,6 +297,11 @@ namespace AgroBase.Models.Modules
|
|||
{
|
||||
Dados.PressaoLinha = 0;
|
||||
|
||||
Dados.Sensores.ForEach(x =>
|
||||
{
|
||||
x.Leitura = null;
|
||||
});
|
||||
|
||||
Dados.BicosPulverizadores.ForEach(x =>
|
||||
{
|
||||
x.Atuado = false;
|
||||
|
|
@ -312,19 +309,18 @@ namespace AgroBase.Models.Modules
|
|||
x.Atuacoes = 0;
|
||||
x.TempoAtuado = 0;
|
||||
x.InicioAtuacao = DateTime.MinValue;
|
||||
x.Leitura = null;
|
||||
});
|
||||
|
||||
Dados.Sensores.ForEach(x =>
|
||||
Dados.BombasPressurizadoras.ForEach(x =>
|
||||
{
|
||||
x.Leituras = new List<double>();
|
||||
x.ValorMinimo = 0;
|
||||
x.ValorMaximo = 0;
|
||||
x.Leitura = null;
|
||||
x.Pressao = 0;
|
||||
x.BombaAtuada = false;
|
||||
x.Ligado = false;
|
||||
x.Potencia = 0;
|
||||
});
|
||||
|
||||
Dados.BombaPressurizadora.Pressao = 0;
|
||||
Dados.BombaPressurizadora.BombaAtuada = false;
|
||||
Dados.BombaPressurizadora.Ligado = false;
|
||||
Dados.BombaPressurizadora.Potencia = 0;
|
||||
Dados.VolumeVazaoAferido = 0;
|
||||
Dados.VolumeVazaoML = 0;
|
||||
Dados.TempoAtuado = 0;
|
||||
|
|
@ -340,44 +336,90 @@ namespace AgroBase.Models.Modules
|
|||
// Inicializar o dicionário
|
||||
var configDictionary = new Dictionary<string, List<string>>() { { Modulo_ID, new List<string>() } };
|
||||
|
||||
// Adicionar configurações dos Bicos Pulverizadores
|
||||
var bicosConfig = BicosPulverizadores.Where(x => x.Comandar).Select(x => x.ProtocoloConfiguracaoBico(Conectar)).ToList();
|
||||
configDictionary[Modulo_ID].AddRange(bicosConfig);
|
||||
|
||||
// Adicionar configuração da Bomba Pressurizadora
|
||||
if (BombaPressurizadora.Comandar)
|
||||
{
|
||||
string bombaConfig = BombaPressurizadora.ProtocoloConfiguracaoBomba(Conectar);
|
||||
configDictionary[Modulo_ID].Add(bombaConfig);
|
||||
}
|
||||
|
||||
// Adicionar configurações dos Sensores
|
||||
var sensoresConfig = Sensores.Where(x => x.Aferir).Select(x => x.ProtocoloConfiguracaoSensor(Pinout, Conectar)).ToList();
|
||||
// Adicionar configurações dos Sensores que devem ser aferidos
|
||||
var sensoresConfig = SensoresConfig(Conectar);
|
||||
configDictionary[Modulo_ID].AddRange(sensoresConfig);
|
||||
|
||||
// Adicionar configurações dos Bicos Pulverizadores
|
||||
var bicosConfig = BicosConfig(Conectar);
|
||||
configDictionary[Modulo_ID].AddRange(bicosConfig);
|
||||
|
||||
// Adicionar configurações das Bombas Pressurizadoras
|
||||
var bombasConfig = BombasConfig(Conectar);
|
||||
configDictionary[Modulo_ID].AddRange(bombasConfig);
|
||||
|
||||
// Adicionar configuração do ProtocoloMOD
|
||||
string protocoloMOD =
|
||||
((int)F_Code.Cfg).ToString() + SerialService.SplitMessage +
|
||||
"MD" + SerialService.SplitParams +
|
||||
(Conectar ? "1" : "0") + SerialService.SplitParams +
|
||||
_TaxaAmostragem.ToString() + SerialService.SplitParams +
|
||||
(AtuacaoNivelAlto ? "1" : "0") + SerialService.SplitParams +
|
||||
(RequisitarDados ? "1" : "0");
|
||||
|
||||
var protocoloMOD = ModConfig(Conectar);
|
||||
configDictionary[Modulo_ID].Add(protocoloMOD);
|
||||
|
||||
configDictionary[Modulo_ID].Add(ProtocoloVerificacao(false));
|
||||
|
||||
return configDictionary;
|
||||
}
|
||||
|
||||
|
||||
private string ModConfig(bool Conectar)
|
||||
{
|
||||
string protocoloMOD =
|
||||
((int)F_Code.Cfg).ToString() + SerialService.SplitMessage +
|
||||
((int)T_Code.Mod).ToString() + SerialService.SplitParams +
|
||||
(Conectar ? "1" : "0") + SerialService.SplitParams +
|
||||
_TaxaAmostragem.ToString() + SerialService.SplitParams +
|
||||
(RequisitarDados ? "1" : "0") + SerialService.SplitParams +
|
||||
PinoutModel.PinoProtocolo(Pinout, Funcoes, SerialService.SplitParams);
|
||||
|
||||
return protocoloMOD;
|
||||
}
|
||||
|
||||
private string[] SensoresConfig(bool Conectar)
|
||||
{
|
||||
var sensoresConfig = Sensores
|
||||
.Where(x => x.Aferir && x.Inicializado != Conectar)
|
||||
.GroupBy(x => x.Componente)
|
||||
.Select(x =>
|
||||
((int)F_Code.Cfg).ToString() + SerialService.SplitMessage +
|
||||
((int)T_Code.Atu).ToString() + SerialService.SplitParams +
|
||||
((int)x.Key).ToString() + SerialService.SplitParams +
|
||||
string.Join(SerialService.SplitConfig, x.Select(y => y.ProtocoloConfiguracao(Pinout, Conectar)))
|
||||
).ToArray();
|
||||
|
||||
return sensoresConfig;
|
||||
}
|
||||
|
||||
private string[] BicosConfig(bool Conectar)
|
||||
{
|
||||
var relesConfig = BicosPulverizadores
|
||||
.Where(x => x.Comandar && x.Inicializado != Conectar)
|
||||
.GroupBy(x => x.Componente)
|
||||
.Select(x =>
|
||||
((int)F_Code.Cfg).ToString() + SerialService.SplitMessage +
|
||||
((int)T_Code.Atu).ToString() + SerialService.SplitParams +
|
||||
((int)x.Key).ToString() + SerialService.SplitParams +
|
||||
string.Join(SerialService.SplitConfig, x.Select(y => y.ProtocoloConfiguracao(Pinout, Conectar)))
|
||||
).ToArray();
|
||||
|
||||
return relesConfig;
|
||||
}
|
||||
|
||||
private string[] BombasConfig(bool Conectar)
|
||||
{
|
||||
var servosConfig = BombasPressurizadoras
|
||||
.Where(x => x.Comandar && x.Inicializado != Conectar)
|
||||
.GroupBy(x => x.Componente)
|
||||
.Select(x =>
|
||||
((int)F_Code.Cfg).ToString() + SerialService.SplitMessage +
|
||||
((int)T_Code.Atu).ToString() + SerialService.SplitParams +
|
||||
((int)x.Key).ToString() + SerialService.SplitParams +
|
||||
string.Join(SerialService.SplitConfig, x.Select(y => y.ProtocoloConfiguracao(Pinout, Conectar)))
|
||||
).ToArray();
|
||||
|
||||
return servosConfig;
|
||||
}
|
||||
|
||||
public string ProtocoloVerificacao(bool Completo)
|
||||
{
|
||||
if (Completo)
|
||||
{
|
||||
string ProtocoloCheck =
|
||||
SerialService.BeginLine +
|
||||
0 + SerialService.SplitMessage +
|
||||
//SerialService.BeginLine +
|
||||
"0" + SerialService.SplitMessage +
|
||||
Modulo_ID + SerialService.SplitMessage +
|
||||
((int)F_Code.Chk).ToString() + SerialService.SplitMessage +
|
||||
"check" +
|
||||
|
|
@ -387,278 +429,66 @@ namespace AgroBase.Models.Modules
|
|||
}
|
||||
else
|
||||
{
|
||||
string ProtocoloCheck =
|
||||
((int)F_Code.Chk).ToString() + SerialService.SplitMessage +
|
||||
"check";
|
||||
string ProtocoloCheck = ((int)F_Code.Chk).ToString() + SerialService.SplitMessage + "check";
|
||||
|
||||
return ProtocoloCheck;
|
||||
}
|
||||
}
|
||||
|
||||
public void RecebeProtocoloSerial(string Protocolo)
|
||||
private string ProtocoloAquisicaoDados()
|
||||
{
|
||||
UltimoProtocoloRecebido = DateTime.Now;
|
||||
string ProtocoloReq = ((int)F_Code.Req).ToString() + SerialService.SplitMessage + "req";
|
||||
return ProtocoloReq;
|
||||
}
|
||||
|
||||
string Mod_ID = Protocolo.Split(SerialService.SplitMessage[0])[0];
|
||||
string mensagem = Protocolo.Substring(Mod_ID.Length + 1, Protocolo.Length - Mod_ID.Length - 1);
|
||||
if (!string.IsNullOrEmpty(Protocolo) && mensagem[0].ToString() == SerialService.BeginSensor)
|
||||
public void RecebeProtocoloModulo(string Protocolo)
|
||||
{
|
||||
try
|
||||
{
|
||||
string[] Dados = mensagem.Replace(SerialService.BeginSensor, "").Split(SerialService.EndLine[0])[0].Split(';');
|
||||
string _id = Dados[1].Trim();
|
||||
S_Code TipoSensor = (S_Code)(int.Parse(Dados[0]));
|
||||
/*AtuadorBicoModel Bico = BicosPulverizadores.FirstOrDefault(x => x.ID.Trim() == _id);
|
||||
SensorModel Sensor = Sensores.FirstOrDefault(x => x.ID.Trim() == _id);
|
||||
AtuadorBombaModel Bomba = _id == BombaPressurizadora.ID.Trim() ? BombaPressurizadora : null;
|
||||
if (Bico == null && Sensor == null && Bomba == null)
|
||||
if (string.IsNullOrWhiteSpace(Protocolo))
|
||||
{
|
||||
if (_id == "MD")
|
||||
{
|
||||
Conectado = Dados[2] == "1";
|
||||
_MensagemConexaoRecebida = true;
|
||||
}
|
||||
Console.WriteLine("Protocolo recebido está vazio ou nulo.");
|
||||
return;
|
||||
}*/
|
||||
try
|
||||
{
|
||||
switch (TipoSensor)
|
||||
{
|
||||
/*case S_Code.sCFG:
|
||||
{
|
||||
bool Inicializado = Dados[2] == "1";
|
||||
if (Bico != null)
|
||||
{
|
||||
Bico.Inicializado = Inicializado;
|
||||
}
|
||||
if (Sensor != null)
|
||||
{
|
||||
Sensor.Inicializado = Inicializado;
|
||||
}
|
||||
if (Bomba != null)
|
||||
{
|
||||
Bomba.Inicializado = Inicializado;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case S_Code.sTST:
|
||||
{
|
||||
bool Testando = Dados[1] == "1";
|
||||
if (Bico != null)
|
||||
{
|
||||
Bico.Testando = Testando;
|
||||
}
|
||||
if (Sensor != null)
|
||||
{
|
||||
Sensor.Testando = Testando;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case S_Code.sBIC:
|
||||
{
|
||||
bool StatusBico = Dados[2] == "1";
|
||||
Bico.StatusBico = StatusBico;
|
||||
break;
|
||||
}
|
||||
case S_Code.sFLX:
|
||||
{
|
||||
int pulsos = 0;
|
||||
int.TryParse(Dados[2].Replace(".", ","), out pulsos);
|
||||
int tempo = 0;
|
||||
int.TryParse(Dados[3].Replace(".", ","), out tempo);
|
||||
|
||||
_LeituraPulsos = pulsos;
|
||||
_LeituraPeriodo = tempo;
|
||||
|
||||
if (VazaoFluxoMLpS > 0)
|
||||
{
|
||||
foreach (var bico in BicosPulverizadores.Where(x => x.Atuado))
|
||||
{
|
||||
bico.MediaNivelFluxo = VazaoFluxoMLpS / BicosPulverizadores.Count(y => y.Atuado);
|
||||
};
|
||||
|
||||
double periodoAtual = Sensor.Leituras.Any() ? (double)_LeituraPeriodo - Sensor.Leituras[1] : (double)_LeituraPeriodo;
|
||||
VolumeVazaoML += (VazaoFluxoMLpS) * (periodoAtual / 1000);
|
||||
|
||||
Variaveis.OperacaoEmAndamento.OpMapaGPS.Sensoriamento.HerbicidaConsumido = (VolumeVazaoML / 1000);
|
||||
}
|
||||
|
||||
Sensor.Leituras = new List<double>()
|
||||
{
|
||||
pulsos,
|
||||
tempo
|
||||
};
|
||||
break;
|
||||
}
|
||||
case S_Code.sMAS:
|
||||
{
|
||||
double massa = 0;
|
||||
double.TryParse(Dados[2].Replace(".", ","), out massa);
|
||||
_MassaLeitura = massa;
|
||||
|
||||
Sensor.Leituras = new List<double>()
|
||||
{
|
||||
massa
|
||||
};
|
||||
break;
|
||||
}
|
||||
case S_Code.sPRS:
|
||||
{
|
||||
double pressao = 0;
|
||||
double.TryParse(Dados[2].Replace(".", ","), out pressao);
|
||||
double leitura = 0;
|
||||
double.TryParse(Dados[3].Replace(".", ","), out leitura);
|
||||
|
||||
PressaoLinha = pressao;
|
||||
_LeituraPressao = leitura;
|
||||
|
||||
BombaPressurizadora.Pressao = PressaoLinha;
|
||||
|
||||
Sensor.Leituras = new List<double>()
|
||||
{
|
||||
pressao,
|
||||
};
|
||||
break;
|
||||
}
|
||||
case S_Code.sBMB:
|
||||
{
|
||||
bool Ligado = Dados[2] == "1";
|
||||
Bomba.Ligado = Ligado;
|
||||
double potencia = 0;
|
||||
double.TryParse(Dados[3].Replace(".", ","), out potencia);
|
||||
Bomba.Potencia = potencia;
|
||||
break;
|
||||
}
|
||||
*/
|
||||
case S_Code.sATU:
|
||||
{
|
||||
#region BICOS
|
||||
|
||||
BicosPulverizadores.FirstOrDefault(x => x.ID.Contains("1")).Inicializado = Dados[2] == "1";
|
||||
BicosPulverizadores.FirstOrDefault(x => x.ID.Contains("1")).StatusBico = Dados[3] == "1";
|
||||
|
||||
BicosPulverizadores.FirstOrDefault(x => x.ID.Contains("2")).Inicializado = Dados[4] == "1";
|
||||
BicosPulverizadores.FirstOrDefault(x => x.ID.Contains("2")).StatusBico = Dados[5] == "1";
|
||||
|
||||
BicosPulverizadores.FirstOrDefault(x => x.ID.Contains("3")).Inicializado = Dados[6] == "1";
|
||||
BicosPulverizadores.FirstOrDefault(x => x.ID.Contains("3")).StatusBico = Dados[7] == "1";
|
||||
|
||||
BicosPulverizadores.FirstOrDefault(x => x.ID.Contains("4")).Inicializado = Dados[8] == "1";
|
||||
BicosPulverizadores.FirstOrDefault(x => x.ID.Contains("4")).StatusBico = Dados[9] == "1";
|
||||
|
||||
#endregion
|
||||
|
||||
#region BOMBA
|
||||
|
||||
BombaPressurizadora.Inicializado = Dados[10] == "1";
|
||||
BombaPressurizadora.Ligado = Dados[11] == "1";
|
||||
double.TryParse(Dados[12], out double p);
|
||||
BombaPressurizadora.Potencia = p;
|
||||
|
||||
#endregion
|
||||
|
||||
#region FLUXO
|
||||
|
||||
var SenFlx = Sensores.FirstOrDefault(x => x.Componente == S_Code.sFLX);
|
||||
if (SenFlx != null)
|
||||
{
|
||||
SenFlx.Inicializado = Dados[13] == "1";
|
||||
int.TryParse(Dados[14].Replace(".", ","), out int pulsos);
|
||||
int.TryParse(Dados[15].Replace(".", ","), out int tempo);
|
||||
_LeituraPulsos = pulsos;
|
||||
_LeituraPeriodo = tempo;
|
||||
|
||||
if (VazaoFluxoMLpS > 0)
|
||||
{
|
||||
foreach (var bico in BicosPulverizadores.Where(x => x.Atuado))
|
||||
{
|
||||
bico.MediaNivelFluxo = VazaoFluxoMLpS / BicosPulverizadores.Count(y => y.Atuado);
|
||||
};
|
||||
|
||||
double periodoAtual = SenFlx.Leituras.Any() ? (double)_LeituraPeriodo - SenFlx.Leituras[1] : (double)_LeituraPeriodo;
|
||||
VolumeVazaoML += (VazaoFluxoMLpS) * (periodoAtual / 1000);
|
||||
|
||||
Variaveis.OperacaoEmAndamento.OpMapaGPS.Sensoriamento.HerbicidaConsumido = (VolumeVazaoML / 1000);
|
||||
}
|
||||
SenFlx.Leituras = new List<double>()
|
||||
{
|
||||
pulsos,
|
||||
tempo
|
||||
};
|
||||
|
||||
DefineLimitesSensor(SenFlx);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region MASSA
|
||||
|
||||
var SenMas = Sensores.FirstOrDefault(x => x.Componente == S_Code.sMAS);
|
||||
if (SenMas != null)
|
||||
{
|
||||
SenMas.Inicializado = Dados[16] == "1";
|
||||
double.TryParse(Dados[17].Replace(".", ","), out double massa);
|
||||
_MassaLeitura = massa;
|
||||
|
||||
SenMas.Leituras = new List<double>()
|
||||
{
|
||||
massa
|
||||
};
|
||||
}
|
||||
|
||||
DefineLimitesSensor(SenMas);
|
||||
|
||||
#endregion
|
||||
|
||||
#region PRSSAO
|
||||
|
||||
var SenPrs = Sensores.FirstOrDefault(x => x.Componente == S_Code.sPRS);
|
||||
if (SenPrs != null)
|
||||
{
|
||||
SenPrs.Inicializado = Dados[18] == "1";
|
||||
double.TryParse(Dados[19].Replace(".", ","), out double pressao);
|
||||
double.TryParse(Dados[20].Replace(".", ","), out double leitura);
|
||||
|
||||
PressaoLinha = pressao;
|
||||
_LeituraPressao = leitura;
|
||||
|
||||
BombaPressurizadora.Pressao = PressaoLinha;
|
||||
|
||||
SenPrs.Leituras = new List<double>()
|
||||
{
|
||||
pressao,
|
||||
};
|
||||
|
||||
DefineLimitesSensor(SenPrs);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/*if (Sensor != null)
|
||||
{
|
||||
DefineLimitesSensor(Sensor);
|
||||
}*/
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
Protocolo = Protocolo.Substring(0, Protocolo.Length - 1);
|
||||
|
||||
// Valida se o protocolo possui um formato esperado
|
||||
if (Protocolo.Length <= 1 || !Protocolo.EndsWith("}"))
|
||||
{
|
||||
Console.WriteLine(ex.Message);
|
||||
Console.WriteLine("Protocolo recebido está em um formato inválido.");
|
||||
return;
|
||||
}
|
||||
|
||||
//Console.WriteLine($"JSON recebido: {Protocolo}");
|
||||
|
||||
// Tenta desserializar o JSON
|
||||
var dadosLeitura = JsonConvert.DeserializeObject<AtuadorMensagemJsonModel>(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}");
|
||||
}
|
||||
}
|
||||
|
||||
private void DefineLimitesSensor(SensorModel Sensor)
|
||||
private void AtualizaDadosComponentes(AtuadorMensagemJsonModel dadosLeitura)
|
||||
{
|
||||
if (Sensor.Leituras[0] > Sensor.ValorMaximo)
|
||||
{
|
||||
Sensor.ValorMaximo = Sensor.Leituras[0];
|
||||
}
|
||||
else if (Sensor.Leituras[0] < Sensor.ValorMinimo)
|
||||
{
|
||||
Sensor.ValorMinimo = Sensor.Leituras[0];
|
||||
}
|
||||
DadosLeitura = dadosLeitura;
|
||||
|
||||
DefineStatusConexao(Modulo_ID, true);
|
||||
}
|
||||
|
||||
public void DefineStatusConexao(string Mod_ID, bool conecatdo)
|
||||
|
|
@ -666,11 +496,11 @@ namespace AgroBase.Models.Modules
|
|||
if (Mod_ID == Modulo_ID)
|
||||
{
|
||||
Conectado = conecatdo;
|
||||
|
||||
Variaveis.OperacaoEmAndamento.DispAtu.AcaoConexao();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
public string GetTaxaAmostragem()
|
||||
{
|
||||
return _TaxaAmostragem.ToString("00000");
|
||||
|
|
@ -685,10 +515,15 @@ namespace AgroBase.Models.Modules
|
|||
{
|
||||
return Conectado;
|
||||
}
|
||||
|
||||
public string GetIP()
|
||||
{
|
||||
return IP;
|
||||
}
|
||||
|
||||
public void IniciarRegistrador()
|
||||
{
|
||||
if (!tmrRegistrador?.IsRunning ?? false)
|
||||
if (!(tmrRegistrador?.IsRunning ?? false))
|
||||
{
|
||||
LimparDados(this);
|
||||
|
||||
|
|
@ -708,18 +543,45 @@ namespace AgroBase.Models.Modules
|
|||
{
|
||||
tmrRegistrador.SetInterval(_TaxaAmostragem);
|
||||
|
||||
bool _conectado = DadosLeitura.Conectado && DadosLeitura.Momento.AddMilliseconds(10 * _TaxaAmostragem) >= DateTime.Now;
|
||||
DefineStatusConexao(Modulo_ID, _conectado);
|
||||
|
||||
Conectado = UltimoProtocoloRecebido.AddMilliseconds(10 * _TaxaAmostragem) >= DateTime.Now;
|
||||
|
||||
if (SerialService.DispositivosMapeados.Any(x => x.Dispositivo == T_Code.Atu) && (_VezesLeituraReconexao >= _TempoReconexaoComponentes || !Conectado))
|
||||
{
|
||||
Variaveis.OperacaoEmAndamento.DispAtu?.EnviarProtocolosConfiguracao();
|
||||
|
||||
_VezesLeituraReconexao = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
_VezesLeituraReconexao++;
|
||||
}
|
||||
|
||||
|
||||
if (Conectado && RequisitarDados)
|
||||
{
|
||||
RequisitarDadosModulo();
|
||||
}
|
||||
}
|
||||
|
||||
public void RequisitarDadosModulo()
|
||||
{
|
||||
if (Variaveis.OperacaoEmAndamento.DispAtu != null)
|
||||
{
|
||||
string ProtocoloAquisicao = ProtocoloAquisicaoDados();
|
||||
Variaveis.OperacaoEmAndamento.DispAtu.AdicionarMensagemFila(Modulo_ID, ProtocoloAquisicao, true, false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public (bool, List<string>) StatusModulosATU()
|
||||
{
|
||||
var Bicos = BicosPulverizadores.Where(x => x.Comandar).ToList();
|
||||
var BicosComFalha = Bicos.Where(x => !x.Inicializado).ToList();
|
||||
bool _bicosOperantes = !BicosComFalha.Any();
|
||||
|
||||
bool _bombaOperante = BombaPressurizadora.Inicializado;
|
||||
|
||||
var _bomba = BombaPressurizadora;
|
||||
var _sensorFluxo = Sensores.FirstOrDefault(x => x.Componente == S_Code.sFLX);
|
||||
bool _sensorFluxoOperante = (!_sensorFluxo?.Aferir ?? false) || ((_sensorFluxo?.Aferir ?? false) && (_sensorFluxo?.Inicializado ?? false));
|
||||
var _sensorMassa = Sensores.FirstOrDefault(x => x.Componente == S_Code.sMAS);
|
||||
|
|
@ -729,9 +591,11 @@ namespace AgroBase.Models.Modules
|
|||
|
||||
List<string> ModsComFalha = BicosComFalha.Select(x => x.ID).ToList();
|
||||
|
||||
bool _bombaOperante = _bomba?.Inicializado ?? false;
|
||||
|
||||
if (!_bombaOperante)
|
||||
{
|
||||
ModsComFalha.Add(BombaPressurizadora.ID);
|
||||
ModsComFalha.Add(_bomba?.ID);
|
||||
}
|
||||
if (!_sensorFluxoOperante)
|
||||
{
|
||||
|
|
@ -757,6 +621,8 @@ namespace AgroBase.Models.Modules
|
|||
{
|
||||
public string ID { get; set; }
|
||||
public int Posicao { get; set; }
|
||||
public S_Code Componente { get; set; } = S_Code.sBIC;
|
||||
public bool AtuacaoNivelAlto { get; set; }
|
||||
private bool _atuado;
|
||||
public bool Atuado
|
||||
{
|
||||
|
|
@ -772,56 +638,59 @@ namespace AgroBase.Models.Modules
|
|||
}
|
||||
}
|
||||
public bool Comandar { get; set; }
|
||||
public bool Inicializado { get; set; }
|
||||
public bool Testando { get; set; }
|
||||
public List<FuncoesPinout> Funcoes { get; set; }
|
||||
public bool StatusBico { get; set; }
|
||||
public double MediaNivelFluxo { get; set; }
|
||||
private FirmwareRele _leitura = null;
|
||||
public FirmwareRele Leitura
|
||||
{
|
||||
get
|
||||
{
|
||||
_leitura = Variaveis.OperacaoEmAndamento.DispAtu?.Dados?.DadosLeitura?.BicosPulverizadores?.FirstOrDefault(x => x.ID == ID);
|
||||
return _leitura;
|
||||
}
|
||||
set
|
||||
{
|
||||
_leitura = value;
|
||||
}
|
||||
}
|
||||
public bool Inicializado
|
||||
{
|
||||
get
|
||||
{
|
||||
return Leitura?.Iniciado ?? false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public string ProtocoloConfiguracaoBico(bool Conectar)
|
||||
public string ProtocoloConfiguracao(PinoutDataModel Pinout, bool Conectar)
|
||||
{
|
||||
var _pinout = new PinoutDataModel()
|
||||
{
|
||||
ExpansorGPIO = AtuadorModel.Pinout.ExpansorGPIO,
|
||||
EnderecoExpansor = AtuadorModel.Pinout.EnderecoExpansor,
|
||||
Pinos = AtuadorModel.Pinout.Pinos.ToList(),
|
||||
ExpansorGPIO = Pinout.ExpansorGPIO,
|
||||
EnderecoExpansor = Pinout.EnderecoExpansor,
|
||||
Pinos = Pinout.Pinos.ToList(),
|
||||
};
|
||||
_pinout.Pinos = _pinout.Pinos.Where(x => x.ComponenteID == ID).ToList();
|
||||
string Protocolo = ((int)F_Code.Cfg).ToString() + SerialService.SplitMessage +
|
||||
ID + SerialService.SplitParams +
|
||||
(Conectar ? "1" : "0") + SerialService.SplitParams +
|
||||
(Comandar ? "1" : "0") + SerialService.SplitParams +
|
||||
Posicao.ToString() + SerialService.SplitParams +
|
||||
PinoutModel.PinoProtocolo(_pinout, Funcoes);
|
||||
string Protocolo =
|
||||
ID + SerialService.SplitSubParams +
|
||||
(Conectar ? "1" : "0") + SerialService.SplitSubParams +
|
||||
(AtuacaoNivelAlto ? "1" : "0") + SerialService.SplitSubParams +
|
||||
PinoutModel.PinoProtocolo(_pinout, Funcoes, SerialService.SplitSubParams);
|
||||
|
||||
return Protocolo;
|
||||
}
|
||||
|
||||
public string ProtocoloComando()
|
||||
{
|
||||
if (Comandar)
|
||||
{
|
||||
string ProtocoloBico =
|
||||
((int)F_Code.Cmd).ToString() + SerialService.SplitMessage +
|
||||
string ProtocoloRele =
|
||||
((int)F_Code.Cmd).ToString() + SerialService.SplitMessage +
|
||||
ID + SerialService.SplitParams +
|
||||
(Atuado ? "1" : "0");
|
||||
((int)Componente) + SerialService.SplitParams +
|
||||
(int)(StatusBico ? Estado.Ligado : Estado.Desligado);
|
||||
|
||||
return ProtocoloBico;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
public string ProtocoloTeste()
|
||||
{
|
||||
if (Comandar)
|
||||
{
|
||||
string ProtocoloBico =
|
||||
((int)F_Code.Tst).ToString() + SerialService.SplitMessage +
|
||||
ID;
|
||||
return ProtocoloBico;
|
||||
}
|
||||
return "";
|
||||
return ProtocoloRele;
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -863,7 +732,6 @@ namespace AgroBase.Models.Modules
|
|||
Posicao = this.Posicao,
|
||||
Atuado = this.Atuado,
|
||||
Comandar = this.Comandar,
|
||||
Inicializado = this.Inicializado,
|
||||
Testando = this.Testando,
|
||||
Funcoes = this.Funcoes,
|
||||
StatusBico = this.StatusBico,
|
||||
|
|
@ -878,61 +746,66 @@ namespace AgroBase.Models.Modules
|
|||
{
|
||||
public string ID { get; set; }
|
||||
public bool BombaAtuada { get; set; }
|
||||
public S_Code Componente { get; set; } = S_Code.sBMB;
|
||||
public bool Ligado { get; set; }
|
||||
public bool Comandar { get; set; }
|
||||
public bool Inicializado { get; set; }
|
||||
public bool Testando { get; set; }
|
||||
public List<FuncoesPinout> Funcoes { get; set; } = new List<FuncoesPinout>();
|
||||
//public double PressaoSP { get; set; }
|
||||
public double Pressao { get; set; }
|
||||
public double Potencia { get; set; }
|
||||
|
||||
private FirmwareBombaPressurizadora _leitura = null;
|
||||
public FirmwareBombaPressurizadora Leitura
|
||||
{
|
||||
get
|
||||
{
|
||||
_leitura = Variaveis.OperacaoEmAndamento.DispAtu?.Dados?.DadosLeitura?.BombasPressurizadoras?.FirstOrDefault(x => x.ID == ID);
|
||||
return _leitura;
|
||||
}
|
||||
set
|
||||
{
|
||||
_leitura = value;
|
||||
}
|
||||
}
|
||||
public bool Inicializado
|
||||
{
|
||||
get
|
||||
{
|
||||
return Leitura?.Iniciado ?? false;
|
||||
}
|
||||
}
|
||||
|
||||
public string ProtocoloConfiguracaoBomba(bool Conectar)
|
||||
|
||||
|
||||
public string ProtocoloConfiguracao(PinoutDataModel Pinout, bool Conectar)
|
||||
{
|
||||
var _pinout = new PinoutDataModel()
|
||||
{
|
||||
ExpansorGPIO = AtuadorModel.Pinout.ExpansorGPIO,
|
||||
EnderecoExpansor = AtuadorModel.Pinout.EnderecoExpansor,
|
||||
Pinos = AtuadorModel.Pinout.Pinos.ToList(),
|
||||
ExpansorGPIO = Pinout.ExpansorGPIO,
|
||||
EnderecoExpansor = Pinout.EnderecoExpansor,
|
||||
Pinos = Pinout.Pinos.ToList(),
|
||||
};
|
||||
_pinout.Pinos = _pinout.Pinos.Where(x => x.ComponenteID == ID).ToList();
|
||||
string Protocolo = ((int)F_Code.Cfg).ToString() + SerialService.SplitMessage +
|
||||
ID + SerialService.SplitParams +
|
||||
(Conectar ? "1" : "0") + SerialService.SplitParams +
|
||||
(Comandar ? "1" : "0") + SerialService.SplitParams +
|
||||
//PressaoSP.ToString("000") + SerialService.SplitParams +
|
||||
Variaveis.OperacaoEmAndamento.Controle.PressaoLinha.ToString() + SerialService.SplitParams +
|
||||
PinoutModel.PinoProtocolo(_pinout, Funcoes);
|
||||
PinoutModel.PinoProtocolo(_pinout, Funcoes, SerialService.SplitParams);
|
||||
|
||||
return Protocolo;
|
||||
}
|
||||
|
||||
public string ProtocoloComando()
|
||||
{
|
||||
if (Comandar)
|
||||
{
|
||||
string ProtocoloBomba =
|
||||
((int)F_Code.Cmd).ToString() + SerialService.SplitMessage +
|
||||
ID.PadRight(5, ' ') + SerialService.SplitParams +
|
||||
(BombaAtuada ? "1" : "0") + SerialService.SplitParams +
|
||||
//PressaoSP.ToString();
|
||||
Variaveis.OperacaoEmAndamento.Controle.PressaoLinha.ToString();
|
||||
return ProtocoloBomba;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
string ProtocoloBomba =
|
||||
((int)F_Code.Cmd).ToString() + SerialService.SplitMessage +
|
||||
ID + SerialService.SplitParams +
|
||||
((int)Componente) + SerialService.SplitParams +
|
||||
(int)(BombaAtuada ? Estado.Ligado : Estado.Desligado) + SerialService.SplitParams +
|
||||
Variaveis.OperacaoEmAndamento.Controle.PressaoLinha;
|
||||
|
||||
public string ProtocoloTeste()
|
||||
{
|
||||
if (Comandar)
|
||||
{
|
||||
string ProtocoloBomba =
|
||||
((int)F_Code.Tst).ToString() + SerialService.SplitMessage +
|
||||
ID;
|
||||
return ProtocoloBomba;
|
||||
}
|
||||
return "";
|
||||
return ProtocoloBomba;
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -943,7 +816,6 @@ namespace AgroBase.Models.Modules
|
|||
ID = this.ID,
|
||||
Ligado = this.Ligado,
|
||||
Comandar = this.Comandar,
|
||||
Inicializado = this.Inicializado,
|
||||
Testando = this.Testando,
|
||||
Funcoes = this.Funcoes,
|
||||
Pressao = this.Pressao,
|
||||
|
|
@ -1122,4 +994,31 @@ namespace AgroBase.Models.Modules
|
|||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
public class FirmwareBombaPressurizadora
|
||||
{
|
||||
public string ID { get; set; }
|
||||
public bool Iniciado { get; set; }
|
||||
public Estado Estado { get; set; }
|
||||
public double Potencia { get; set; }
|
||||
public double Pressao { get; set; }
|
||||
}
|
||||
|
||||
public class AtuadorMensagemJsonModel
|
||||
{
|
||||
public bool Conectado { get; set; }
|
||||
public string Mod_ID { get; set; }
|
||||
public DateTime Momento { get; set; }
|
||||
public List<FirmwareRele> BicosPulverizadores { get; set; } = new List<FirmwareRele>();
|
||||
public List<FirmwareBombaPressurizadora> BombasPressurizadoras { get; set; } = new List<FirmwareBombaPressurizadora>();
|
||||
public List<FirmwareSensorFluxo> SensoresFluxo { get; set; } = new List<FirmwareSensorFluxo>();
|
||||
public List<FirmwareSensorMassa> SensoresMassa { get; set; } = new List<FirmwareSensorMassa>();
|
||||
public List<FirmwareSensorPressao> SensoresPressao { get; set; } = new List<FirmwareSensorPressao>();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,14 +4,16 @@ namespace AgroBase.Models
|
|||
{
|
||||
public interface DispositivoBaseModel
|
||||
{
|
||||
void RecebeProtocoloSerial(string Protocolo);
|
||||
void RecebeProtocoloModulo(string Protocolo);
|
||||
void DefineStatusConexao(string Mod_ID, bool conectado);
|
||||
string GetTaxaAmostragem();
|
||||
void SetTaxaAmostragem(int TaxaAmostragem);
|
||||
bool GetStatusConexao();
|
||||
Dictionary<string, List<string>> ProtocoloConfiguracao(bool Conectar);
|
||||
string ProtocoloVerificacao(bool completo);
|
||||
void IniciarRegistrador();
|
||||
void PararRegistrador();
|
||||
string GetIP();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -162,7 +162,12 @@ namespace AgroBase.Models.Modules
|
|||
return Config;
|
||||
}
|
||||
|
||||
public void RecebeProtocoloSerial(string Protocolo)
|
||||
public string ProtocoloVerificacao(bool Completo)
|
||||
{
|
||||
return "";
|
||||
}
|
||||
|
||||
public void RecebeProtocoloModulo(string Protocolo)
|
||||
{
|
||||
string Mod_ID = Protocolo.Split(SerialService.SplitMessage[0])[0];
|
||||
string mensagem = Protocolo.Substring(Mod_ID.Length + 1, Protocolo.Length - Mod_ID.Length - 1);
|
||||
|
|
@ -353,8 +358,6 @@ namespace AgroBase.Models.Modules
|
|||
if (Modulo != null)
|
||||
{
|
||||
//Modulo.Conectado = conecatdo;
|
||||
|
||||
Variaveis.OperacaoEmAndamento.DispMvd.AcaoConexao();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -373,9 +376,14 @@ namespace AgroBase.Models.Modules
|
|||
return Conectado;
|
||||
}
|
||||
|
||||
public string GetIP()
|
||||
{
|
||||
return IP_Bld;
|
||||
}
|
||||
|
||||
public void IniciarRegistrador()
|
||||
{
|
||||
if (!tmrRegistrador?.IsRunning ?? false)
|
||||
if (!(tmrRegistrador?.IsRunning ?? false))
|
||||
{
|
||||
LimparDados(this);
|
||||
|
||||
|
|
@ -536,7 +544,7 @@ namespace AgroBase.Models.Modules
|
|||
(Conectar ? "1" : "0") + SerialService.SplitParams +
|
||||
MovimentacaoUnificadaModel._TaxaAmostragem.ToString() + SerialService.SplitParams +
|
||||
(RequisitarDados ? "1" : "0") + SerialService.SplitParams +
|
||||
PinoutModel.PinoProtocolo(_pinout, Funcoes);
|
||||
PinoutModel.PinoProtocolo(_pinout, Funcoes, SerialService.SplitParams);
|
||||
|
||||
if (Conectar)
|
||||
{
|
||||
|
|
@ -596,40 +604,45 @@ namespace AgroBase.Models.Modules
|
|||
}
|
||||
|
||||
|
||||
public void AtualizarSensoresMotor(SensorModel Sensor)
|
||||
public void AtualizarSensoresMotor()
|
||||
{
|
||||
bool Computar = true;
|
||||
double leitura0 = Sensor.Leituras.Count() > 0 ? Sensor.Leituras[0] : 0;
|
||||
switch (Sensor.Componente)
|
||||
var sensorTmp = Variaveis.OperacaoEmAndamento.DispSen.Dados.DadosLeitura.SensoresTemperatura.FirstOrDefault(x => x.ID.Contains(Modulo_ID));
|
||||
if (sensorTmp != null)
|
||||
{
|
||||
case S_Code.sTMP:
|
||||
MovMotor.Temperatura = leitura0;
|
||||
break;
|
||||
case S_Code.sCOR:
|
||||
MovMotor.Corrente = Sensor.Leituras[0];
|
||||
MovMotor.Tensao = Sensor.Leituras[1];
|
||||
break;
|
||||
default:
|
||||
Computar = false;
|
||||
break;
|
||||
MovMotor.Temperatura = sensorTmp.Temperatura;
|
||||
|
||||
AlarmeModel _Alarme = new AlarmeModel()
|
||||
{
|
||||
Tipo = S_Code.sTMP,
|
||||
Valor = sensorTmp.Temperatura,
|
||||
Maximo = sensorTmp.Temperatura > sensorTmp.LimiteMaximo,
|
||||
Minimo = sensorTmp.Temperatura < sensorTmp.LimiteMinimo,
|
||||
ParaMaximo = false,
|
||||
ParaMinimo = false
|
||||
};
|
||||
VerificarAlarme(_Alarme);
|
||||
}
|
||||
|
||||
|
||||
if (!Computar)
|
||||
var sensorCor = Variaveis.OperacaoEmAndamento.DispSen.Dados.DadosLeitura.SensoresCorrente.FirstOrDefault(x => x.ID.Contains(Modulo_ID));
|
||||
if (sensorCor != null)
|
||||
{
|
||||
return;
|
||||
MovMotor.Corrente = (double)sensorCor.Current;
|
||||
MovMotor.Tensao = sensorCor.BusVoltage;
|
||||
|
||||
AlarmeModel _Alarme = new AlarmeModel()
|
||||
{
|
||||
Tipo = S_Code.sCOR,
|
||||
Valor = (double)sensorCor.Current,
|
||||
Maximo = (double)sensorCor.Current > sensorCor.LimiteMaximo,
|
||||
Minimo = (double)sensorCor.Current < sensorCor.LimiteMinimo,
|
||||
ParaMaximo = false,
|
||||
ParaMinimo = false
|
||||
};
|
||||
VerificarAlarme(_Alarme);
|
||||
}
|
||||
}
|
||||
|
||||
AlarmeModel _Alarme = new AlarmeModel()
|
||||
{
|
||||
Tipo = Sensor.Componente,
|
||||
Valor = leitura0,
|
||||
Maximo = leitura0 > Sensor.LimiteMaximo,
|
||||
Minimo = leitura0 < Sensor.LimiteMinimo,
|
||||
ParaMaximo = false,
|
||||
ParaMinimo = false
|
||||
};
|
||||
|
||||
private void VerificarAlarme(AlarmeModel _Alarme)
|
||||
{
|
||||
bool Adicionado = false;
|
||||
var Alm = MovMotor.Alarmes.FirstOrDefault(x => x.Tipo == _Alarme.Tipo);
|
||||
if (Alm == null)
|
||||
|
|
@ -843,7 +856,7 @@ namespace AgroBase.Models.Modules
|
|||
NumeroPolos + SerialService.SplitParams +
|
||||
Rampa + SerialService.SplitParams +
|
||||
Variaveis.OperacaoEmAndamento.DispMvd.Dados.RPM_Max_MotorBLDC + SerialService.SplitParams +
|
||||
PinoutModel.PinoProtocolo(_pinout, Funcoes);
|
||||
PinoutModel.PinoProtocolo(_pinout, Funcoes, SerialService.SplitParams);
|
||||
|
||||
return Protocolo;
|
||||
}
|
||||
|
|
@ -1124,7 +1137,7 @@ namespace AgroBase.Models.Modules
|
|||
(Conectar ? "1" : "0") + SerialService.SplitParams +
|
||||
//(Estabilizar ? "1" : "0") + SerialService.SplitParams +
|
||||
Angulo_Offset.ToString() + SerialService.SplitParams +
|
||||
PinoutModel.PinoProtocolo(_pinout, Funcoes);
|
||||
PinoutModel.PinoProtocolo(_pinout, Funcoes, SerialService.SplitParams);
|
||||
|
||||
return Protocolo;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -285,7 +285,7 @@ namespace AgroBase.Models.Modules
|
|||
File.WriteAllText(nomeArquivo, JsonConvert.SerializeObject(newPinout));
|
||||
}
|
||||
|
||||
public static string PinoProtocolo(PinoutDataModel _pinout, List<FuncoesPinout> _funcoes)
|
||||
public static string PinoProtocolo(PinoutDataModel _pinout, List<FuncoesPinout> _funcoes, string splitparms)
|
||||
{
|
||||
string Pinos = "";
|
||||
int i = 0;
|
||||
|
|
@ -293,22 +293,23 @@ namespace AgroBase.Models.Modules
|
|||
{
|
||||
if (i > 0)
|
||||
{
|
||||
Pinos += SerialService.SplitParams;
|
||||
Pinos += splitparms;
|
||||
}
|
||||
var pino = _pinout.Pinos.FirstOrDefault(x => x.Funcao == funcao);
|
||||
if (pino != null && (pino.Barramento == TiposBarramentos.CONTROLADOR || (pino.Barramento == TiposBarramentos.EXPANSORI2C && _pinout.ExpansorGPIO)))
|
||||
{
|
||||
Pinos += ((int)pino.Barramento).ToString() + SerialService.SplitParams + pino.Pino.ToString();
|
||||
Pinos += ((int)pino.Barramento).ToString() + splitparms + pino.Pino.ToString();
|
||||
}
|
||||
else
|
||||
{
|
||||
Pinos += ((int)TiposBarramentos.CONTROLADOR).ToString() + SerialService.SplitParams + "-1";
|
||||
Pinos += ((int)TiposBarramentos.CONTROLADOR).ToString() + splitparms + "-1";
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return Pinos;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
public enum TiposControladores
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -17,6 +17,7 @@ using System.Text;
|
|||
using System.Windows.Forms.DataVisualization.Charting;
|
||||
using AgroBase.Forms.IHM;
|
||||
using OpenHardwareMonitor.Hardware;
|
||||
using CefSharp.WinForms;
|
||||
|
||||
namespace AgroBase.Models
|
||||
{
|
||||
|
|
@ -391,7 +392,7 @@ namespace AgroBase.Models
|
|||
|
||||
var Parametros = JsonConvert.DeserializeObject<OperacaoParametrosModel>(ParametrosJson);
|
||||
|
||||
Variaveis.OperacaoEmAndamento = CarregarParametrosOperacaoPadrao(Parametros.Modo);
|
||||
CarregarParametrosOperacaoPadrao(Parametros.Modo);
|
||||
|
||||
OperacaoControleModel controle = new OperacaoControleModel()
|
||||
{
|
||||
|
|
@ -527,7 +528,7 @@ namespace AgroBase.Models
|
|||
|
||||
|
||||
|
||||
public static OperacaoModel CarregarParametrosOperacaoPadrao(ModoOperacao Modo)
|
||||
public static void CarregarParametrosOperacaoPadrao(ModoOperacao Modo)
|
||||
{
|
||||
var SenConectado = (DispositivosService<SensoriamentoModel>)Variaveis.DispositivosConectados.FirstOrDefault(x => x.Dispositivo == T_Code.Sen);
|
||||
var AtuConectado = (DispositivosService<AtuadorModel>)Variaveis.DispositivosConectados.FirstOrDefault(x => x.Dispositivo == T_Code.Atu);
|
||||
|
|
@ -535,7 +536,7 @@ namespace AgroBase.Models
|
|||
|
||||
tmrLogs?.Stop();
|
||||
|
||||
OperacaoModel OperacaoCarregar = new OperacaoModel(Modo)
|
||||
Variaveis.OperacaoEmAndamento = new OperacaoModel(Modo)
|
||||
{
|
||||
Iniciado = false,
|
||||
TimestampInicio = 0,
|
||||
|
|
@ -551,8 +552,8 @@ namespace AgroBase.Models
|
|||
{
|
||||
case ModoOperacao.Manual:
|
||||
//OperacaoCarregar.frmOperacao = (Form)Activator.CreateInstance(Variaveis.OperacaoEmAndamento.OpManual.frmOperacao.GetType());
|
||||
OperacaoCarregar.frmOperacao = new frmOperacaoManual();
|
||||
OperacaoCarregar.Controle = new OperacaoControleModel()
|
||||
Variaveis.OperacaoEmAndamento.frmOperacao = new frmOperacaoManual();
|
||||
Variaveis.OperacaoEmAndamento.Controle = new OperacaoControleModel()
|
||||
{
|
||||
RPM_Max = 100,
|
||||
RPM_Min = 15,
|
||||
|
|
@ -584,7 +585,7 @@ namespace AgroBase.Models
|
|||
}
|
||||
},
|
||||
};
|
||||
OperacaoCarregar.ModulosMandatorios = new List<OperacaoModulosMandatoriosModel>()
|
||||
Variaveis.OperacaoEmAndamento.ModulosMandatorios = new List<OperacaoModulosMandatoriosModel>()
|
||||
{
|
||||
new OperacaoModulosMandatoriosModel()
|
||||
{
|
||||
|
|
@ -602,7 +603,7 @@ namespace AgroBase.Models
|
|||
Mandatorio = false
|
||||
}
|
||||
};
|
||||
OperacaoCarregar.ParametrosMandatorios = new List<OperacaoParametrosMandatoriosModel>()
|
||||
Variaveis.OperacaoEmAndamento.ParametrosMandatorios = new List<OperacaoParametrosMandatoriosModel>()
|
||||
{
|
||||
new OperacaoParametrosMandatoriosModel()
|
||||
{
|
||||
|
|
@ -614,9 +615,9 @@ namespace AgroBase.Models
|
|||
break;
|
||||
case ModoOperacao.MapaGPS:
|
||||
//OperacaoCarregar.frmOperacao = (Form)Activator.CreateInstance(Variaveis.OperacaoEmAndamento.OpMapaGPS.frmOperacao.GetType());
|
||||
OperacaoCarregar.frmOperacao = new frmOperacaoMapaGPS();
|
||||
OperacaoCarregar.ControleAnterior = new OperacaoControleModel();
|
||||
OperacaoCarregar.Controle = new OperacaoControleModel()
|
||||
Variaveis.OperacaoEmAndamento.frmOperacao = new frmOperacaoMapaGPS();
|
||||
Variaveis.OperacaoEmAndamento.ControleAnterior = new OperacaoControleModel();
|
||||
Variaveis.OperacaoEmAndamento.Controle = new OperacaoControleModel()
|
||||
{
|
||||
RPM_Max = 100,
|
||||
RPM_Min = 15,
|
||||
|
|
@ -648,7 +649,7 @@ namespace AgroBase.Models
|
|||
},
|
||||
},
|
||||
};
|
||||
OperacaoCarregar.ModulosMandatorios = new List<OperacaoModulosMandatoriosModel>()
|
||||
Variaveis.OperacaoEmAndamento.ModulosMandatorios = new List<OperacaoModulosMandatoriosModel>()
|
||||
{
|
||||
new OperacaoModulosMandatoriosModel()
|
||||
{
|
||||
|
|
@ -686,7 +687,7 @@ namespace AgroBase.Models
|
|||
Mandatorio = true,
|
||||
}
|
||||
};
|
||||
OperacaoCarregar.ParametrosMandatorios = new List<OperacaoParametrosMandatoriosModel>()
|
||||
Variaveis.OperacaoEmAndamento.ParametrosMandatorios = new List<OperacaoParametrosMandatoriosModel>()
|
||||
{
|
||||
new OperacaoParametrosMandatoriosModel()
|
||||
{
|
||||
|
|
@ -704,40 +705,38 @@ namespace AgroBase.Models
|
|||
Mandatorio = true,
|
||||
}
|
||||
};
|
||||
OperacaoCarregar.OpMapaGPS.Sensoriamento = new OperacaoMapaGPSSensoriamentoModel();
|
||||
Variaveis.OperacaoEmAndamento.OpMapaGPS.Sensoriamento = new OperacaoMapaGPSSensoriamentoModel();
|
||||
break;
|
||||
}
|
||||
|
||||
OperacaoCarregar.OpMapaGPS.Sensoriamento.ReiniciarLeituras();
|
||||
Variaveis.OperacaoEmAndamento.OpMapaGPS.Sensoriamento.ReiniciarLeituras();
|
||||
|
||||
OperacaoCarregar.AtualizaListaCameras(null, new List<Panel>(), false);
|
||||
Variaveis.OperacaoEmAndamento.AtualizaListaCameras(null, new List<Panel>(), false);
|
||||
|
||||
if (OperacaoCarregar.DispSen != null)
|
||||
if (Variaveis.OperacaoEmAndamento.DispSen != null)
|
||||
{
|
||||
if (OperacaoCarregar.DispSen.Dados.ConfiguracaoSensorUltrassom == null)
|
||||
if (Variaveis.OperacaoEmAndamento.DispSen.Dados.ConfiguracaoSensorUltrassom == null)
|
||||
{
|
||||
OperacaoCarregar.DispSen.Dados.ConfiguracaoSensorUltrassom = UltrasonicA05Helper.CarregarConfiguracaoPadrao(ConfiguracaoSensorUltrassonico.NaoUtilizado);
|
||||
Variaveis.OperacaoEmAndamento.DispSen.Dados.ConfiguracaoSensorUltrassom = UltrasonicA05Helper.CarregarConfiguracaoPadrao(ConfiguracaoSensorUltrassonico.NaoUtilizado);
|
||||
}
|
||||
|
||||
if (OperacaoCarregar.DispSen.Dados.Conectado)
|
||||
if (Variaveis.OperacaoEmAndamento.DispSen.Dados.Conectado)
|
||||
{
|
||||
OperacaoCarregar.DispSen.Dados.Sinaleiros.ForEach(x => x.Comportamento = VariaveisEquipamento.ComportamentoPorStatus(StatusOperacao.NaoIniciado));
|
||||
Variaveis.OperacaoEmAndamento.DispSen.Dados.Sinaleiros.ForEach(x => x.Comportamento = VariaveisEquipamento.ComportamentoPorStatus(StatusOperacao.NaoIniciado));
|
||||
|
||||
OperacaoCarregar.DispSen.Dados.Sinaleiros.First(x => x.ID == (Modo == ModoOperacao.Manual ? "LEDMN" : "LEDAT")).Comportamento.statusLED = StatusLED.Aceso;
|
||||
OperacaoCarregar.DispSen.Dados.Sinaleiros.First(x => x.ID == "LEDOP").Comportamento = VariaveisEquipamento.ComportamentoPorStatus();
|
||||
Variaveis.OperacaoEmAndamento.DispSen.Dados.Sinaleiros.First(x => x.ID == (Modo == ModoOperacao.Manual ? "LEDMN" : "LEDAT")).Comportamento.statusLED = StatusLED.Aceso;
|
||||
Variaveis.OperacaoEmAndamento.DispSen.Dados.Sinaleiros.First(x => x.ID == "LEDOP").Comportamento = VariaveisEquipamento.ComportamentoPorStatus();
|
||||
|
||||
//OperacaoCarregar.DispSen.Dados.Sinaleiros.ForEach(x => OperacaoCarregar.DispSen.AdicionarMensagemFila(OperacaoCarregar.DispSen.Dados.Modulo_ID, x.ProtocoloComando(), true, false));
|
||||
foreach (var Sinaleiro in OperacaoCarregar.DispSen.Dados.Sinaleiros)
|
||||
foreach (var Sinaleiro in Variaveis.OperacaoEmAndamento.DispSen.Dados.Sinaleiros)
|
||||
{
|
||||
GeneralJoystick.EnviarComandoSensoriamento(S_Code.sLED, Sinaleiro.ID, Sinaleiro.Comportamento);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
OperacaoCarregar.Controle.Angulo = OperacaoCarregar.Controle.Angulo_Max;
|
||||
OperacaoCarregar.Controle.PercentualVelocidadeSP = OperacaoCarregar.Controle.PercentualVelocidadeMin;
|
||||
|
||||
return OperacaoCarregar;
|
||||
Variaveis.OperacaoEmAndamento.Controle.Angulo = Variaveis.OperacaoEmAndamento.Controle.Angulo_Max;
|
||||
Variaveis.OperacaoEmAndamento.Controle.PercentualVelocidadeSP = Variaveis.OperacaoEmAndamento.Controle.PercentualVelocidadeMin;
|
||||
}
|
||||
|
||||
public static void SalvarOperacaoPersonalizada(OperacaoModel Operacao)
|
||||
|
|
@ -760,12 +759,13 @@ namespace AgroBase.Models
|
|||
{
|
||||
string modoOpStr = nomeArquivo.Split('\\')[nomeArquivo.Split('\\').Length - 1].Replace("operacao", "").Split('.')[0];
|
||||
ModoOperacao modo = (ModoOperacao)Enum.Parse(typeof(ModoOperacao), modoOpStr);
|
||||
return CarregarParametrosOperacaoPadrao(modo);
|
||||
CarregarParametrosOperacaoPadrao(modo);
|
||||
return Variaveis.OperacaoEmAndamento;
|
||||
|
||||
OperacaoModel Operacao = new OperacaoModel(modo);
|
||||
if (!File.Exists(nomeArquivo))
|
||||
{
|
||||
Operacao = CarregarParametrosOperacaoPadrao(modo);
|
||||
//Operacao = CarregarParametrosOperacaoPadrao(modo);
|
||||
SalvarOperacaoPersonalizada(Operacao);
|
||||
}
|
||||
|
||||
|
|
@ -985,7 +985,7 @@ namespace AgroBase.Models
|
|||
ArquivoLeitura = "ervas_" + CamNome + ".json",
|
||||
browser = null,
|
||||
camera = new CameraService(),
|
||||
CameraSelecionada = DispSen.Dados.CameraID_Solo[i],
|
||||
CameraSelecionada = DispSen.Dados.CameraID_Solo.Count > i ? DispSen.Dados.CameraID_Solo[i] : null,
|
||||
combo = new ComboBox(),
|
||||
MaxLeituras = 10,
|
||||
VideoPorta = (VariaveisPortas.CameraSolo + CamerasSolo.Count()).ToString(),
|
||||
|
|
@ -1032,7 +1032,7 @@ namespace AgroBase.Models
|
|||
{
|
||||
VersaoArquivoModel ArquivoVersao = VersionamentoService.ArquivoModeloWeedDetector;
|
||||
|
||||
CameraSolo.IniciarRotinaProcesso();
|
||||
//CameraSolo.IniciarRotinaProcesso();
|
||||
|
||||
CameraSolo.camera.IniciarCamera(
|
||||
Variaveis.OperacaoEmAndamento.DispAtu.Dados.ScriptDeteccaoErvas,
|
||||
|
|
@ -1049,7 +1049,26 @@ namespace AgroBase.Models
|
|||
CameraSolo.VideoPorta,
|
||||
CameraSolo.VideoUrl,
|
||||
CameraSolo.MqttTopico,
|
||||
CameraSolo.tmrProcesso
|
||||
async (Mensagem) =>
|
||||
{
|
||||
if (Mensagem.Momento > CameraSolo.camera.IniciadoEm && Mensagem.Mensagem == "OK")
|
||||
{
|
||||
CameraSolo.camera.ProntoEm = Mensagem.Momento;
|
||||
|
||||
if (CameraSolo.browser == null)
|
||||
{
|
||||
CameraSolo.Iniciada = true;
|
||||
CameraSolo.browser = new ChromiumWebBrowser(CameraSolo.camera.URLcamera);
|
||||
CameraSolo.browser.Dock = DockStyle.Fill;
|
||||
|
||||
CameraSolo.panel.Invoke(new Action(() =>
|
||||
{
|
||||
CameraSolo.panel.Controls.Add(CameraSolo.browser);
|
||||
CameraSolo.panel.Refresh();
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
else
|
||||
|
|
@ -1084,7 +1103,35 @@ namespace AgroBase.Models
|
|||
cameraCaminho.VideoPorta,
|
||||
cameraCaminho.VideoUrl,
|
||||
CamerasVaraiveisModel.TopicoRecebimentoBitmap,
|
||||
cameraCaminho.tmrProcesso
|
||||
async (Mensagem) =>
|
||||
{
|
||||
if (Mensagem.Momento > cameraCaminho.camera.IniciadoEm && Mensagem.Mensagem == "OK")
|
||||
{
|
||||
cameraCaminho.camera.ProntoEm = Mensagem.Momento;
|
||||
|
||||
if (cameraCaminho.browser == null)
|
||||
{
|
||||
cameraCaminho.Iniciada = true;
|
||||
if (cameraCaminho.panel != null)
|
||||
{
|
||||
cameraCaminho.panel.GetType().GetMethod("SetStyle", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).Invoke(cameraCaminho.panel, new object[] { ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true });
|
||||
cameraCaminho.panel.BackgroundImageLayout = ImageLayout.Zoom;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (Mensagem.Mensagem != "OK")
|
||||
{
|
||||
try
|
||||
{
|
||||
Bitmap bitmap = Variaveis.OperacaoEmAndamento.CameraCaminhoKinect.ExtraiImagemDaMensagem(Mensagem.Mensagem);
|
||||
Variaveis.OperacaoEmAndamento.CameraCaminhoKinect.AtualizarBitmapTela(bitmap);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"Erro ao processar a mensagem MQTT: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1474,7 +1521,7 @@ namespace AgroBase.Models
|
|||
return;
|
||||
}
|
||||
|
||||
var MqttTopico = Variaveis.MqttService.Topicos.FirstOrDefault(x => x.Topico == CamerasVaraiveisModel.TopicoRecebimentoBitmap);
|
||||
var MqttTopico = cameraCaminho.camera._mqttTopico;
|
||||
if (MqttTopico != null && MqttTopico.Mensagens.Any(x => x.Momento > cameraCaminho.camera.IniciadoEm))
|
||||
{
|
||||
try
|
||||
|
|
@ -1933,27 +1980,17 @@ namespace AgroBase.Models
|
|||
};
|
||||
SalvarLog(T_Code.Atu.ToString(), logAtu, false);
|
||||
|
||||
SenSensoriamentoLogModel logSen = new SenSensoriamentoLogModel()
|
||||
var senLeitura = Variaveis.OperacaoEmAndamento.DispSen.Dados.DadosLeitura;
|
||||
SensoriamentoMensagemJsonModel logSen = new SensoriamentoMensagemJsonModel()
|
||||
{
|
||||
Momento = Agora,
|
||||
Inicializado = Variaveis.OperacaoEmAndamento.DispSen.Dados.Conectado,
|
||||
Barramento3v3Corrente = Variaveis.OperacaoEmAndamento.DispSen.Dados.Sensores.FirstOrDefault(x => x.ID == "AB3V" && x.Inicializado && x.Leituras != null && x.Leituras.Count() > 0)?.Leituras?[0] ?? -1,
|
||||
Barramento3v3Tensao = Variaveis.OperacaoEmAndamento.DispSen.Dados.Sensores.FirstOrDefault(x => x.ID == "AB3V" && x.Inicializado && x.Leituras != null && x.Leituras.Count() > 1)?.Leituras?[1] ?? -1,
|
||||
Barramento5vCorrente = Variaveis.OperacaoEmAndamento.DispSen.Dados.Sensores.FirstOrDefault(x => x.ID == "AB5V" && x.Inicializado && x.Leituras != null && x.Leituras.Count() > 0)?.Leituras?[0] ?? -1,
|
||||
Barramento5vTensao = Variaveis.OperacaoEmAndamento.DispSen.Dados.Sensores.FirstOrDefault(x => x.ID == "AB5V" && x.Inicializado && x.Leituras != null && x.Leituras.Count() > 1)?.Leituras?[1] ?? -1,
|
||||
Barramento7v2Corrente = Variaveis.OperacaoEmAndamento.DispSen.Dados.Sensores.FirstOrDefault(x => x.ID == "AB7V2" && x.Inicializado && x.Leituras != null && x.Leituras.Count() > 0)?.Leituras?[0] ?? -1,
|
||||
Barramento7v2Tensao = Variaveis.OperacaoEmAndamento.DispSen.Dados.Sensores.FirstOrDefault(x => x.ID == "AB7V2" && x.Inicializado && x.Leituras != null && x.Leituras.Count() > 1)?.Leituras?[1] ?? -1,
|
||||
Barramento12vCorrente = Variaveis.OperacaoEmAndamento.DispSen.Dados.Sensores.FirstOrDefault(x => x.ID == "AB12V" && x.Inicializado && x.Leituras != null && x.Leituras.Count() > 0)?.Leituras?[0] ?? -1,
|
||||
Barramento12vTensao = Variaveis.OperacaoEmAndamento.DispSen.Dados.Sensores.FirstOrDefault(x => x.ID == "AB12V" && x.Inicializado && x.Leituras != null && x.Leituras.Count() > 1)?.Leituras?[1] ?? -1,
|
||||
OrientacaoMagnetica = Variaveis.OperacaoEmAndamento.DispSen.Dados.Sensores.FirstOrDefault(x => x.ID == "SMAG" && x.Inicializado && x.Leituras != null && x.Leituras.Count() > 0)?.Leituras?[0] ?? -1,
|
||||
StatusSinaleiroMN = Variaveis.OperacaoEmAndamento.DispSen.Dados.Sinaleiros.FirstOrDefault(x => x.ID == "LEDMN" && x.Inicializado)?.StatusLED ?? StatusLED.Apagado,
|
||||
StatusSinaleiroAT = Variaveis.OperacaoEmAndamento.DispSen.Dados.Sinaleiros.FirstOrDefault(x => x.ID == "LEDAT" && x.Inicializado)?.StatusLED ?? StatusLED.Apagado,
|
||||
StatusSinaleiroOP = Variaveis.OperacaoEmAndamento.DispSen.Dados.Sinaleiros.FirstOrDefault(x => x.ID == "LEDOP" && x.Inicializado)?.StatusLED ?? StatusLED.Apagado,
|
||||
StatusReleLoRa = Variaveis.OperacaoEmAndamento.DispSen.Dados.Reles.FirstOrDefault(x => x.ID == "RLLRA" && x.Inicializado)?.StatusLeitura ?? Estado.Desligado,
|
||||
AnguloFreioET = Variaveis.OperacaoEmAndamento.DispSen.Dados.Servos.FirstOrDefault(x => x.ID == "FRO_ET" && x.Inicializado)?._AnguloLeitura ?? -1,
|
||||
AnguloFreioEF = Variaveis.OperacaoEmAndamento.DispSen.Dados.Servos.FirstOrDefault(x => x.ID == "FRO_EF" && x.Inicializado)?._AnguloLeitura ?? -1,
|
||||
AnguloFreioDT = Variaveis.OperacaoEmAndamento.DispSen.Dados.Servos.FirstOrDefault(x => x.ID == "FRO_DT" && x.Inicializado)?._AnguloLeitura ?? -1,
|
||||
AnguloFreioDF = Variaveis.OperacaoEmAndamento.DispSen.Dados.Servos.FirstOrDefault(x => x.ID == "FRO_DF" && x.Inicializado)?._AnguloLeitura ?? -1,
|
||||
Momento = Agora,
|
||||
Conectado = senLeitura.Conectado,
|
||||
Mod_ID = senLeitura.Mod_ID,
|
||||
Reles = new List<FirmwareRele>(senLeitura.Reles),
|
||||
SensoresCorrente = new List<FirmwareSensorCorrente>(senLeitura.SensoresCorrente),
|
||||
SensoresTemperatura = new List<FirmwareSensorTemperatura>(senLeitura.SensoresTemperatura),
|
||||
ServoFreios = new List<FirmwareServoFreio>(senLeitura.ServoFreios),
|
||||
Sinaleiros = new List<FirmwareSinaleiro>(senLeitura.Sinaleiros),
|
||||
};
|
||||
SalvarLog(T_Code.Sen.ToString(), logSen, false);
|
||||
|
||||
|
|
@ -3126,29 +3163,6 @@ namespace AgroBase.Models
|
|||
public double TempoAtuado { get; set; }
|
||||
}
|
||||
|
||||
public class SenSensoriamentoLogModel
|
||||
{
|
||||
public DateTime Momento { get; set; }
|
||||
public bool Inicializado { get; set; }
|
||||
public double Barramento3v3Tensao { get; set; }
|
||||
public double Barramento3v3Corrente { get; set; }
|
||||
public double Barramento5vTensao { get; set; }
|
||||
public double Barramento5vCorrente { get; set; }
|
||||
public double Barramento7v2Tensao { get; set; }
|
||||
public double Barramento7v2Corrente { get; set; }
|
||||
public double Barramento12vTensao { get; set; }
|
||||
public double Barramento12vCorrente { get; set; }
|
||||
public double OrientacaoMagnetica { get; set; }
|
||||
public StatusLED StatusSinaleiroMN { get; set; }
|
||||
public StatusLED StatusSinaleiroAT { get; set; }
|
||||
public StatusLED StatusSinaleiroOP { get; set; }
|
||||
public Estado StatusReleLoRa { get; set; }
|
||||
public int AnguloFreioET { get; set; }
|
||||
public int AnguloFreioEF { get; set; }
|
||||
public int AnguloFreioDT { get; set; }
|
||||
public int AnguloFreioDF { get; set; }
|
||||
}
|
||||
|
||||
public class CamSoloSensoriamentoLogModel
|
||||
{
|
||||
public DateTime Momento { get; set; }
|
||||
|
|
|
|||
|
|
@ -745,7 +745,22 @@ namespace AgroBase.Models
|
|||
{
|
||||
if (controle.InvokeRequired)
|
||||
{
|
||||
await (Task)controle.Invoke(new Func<Task>(() => acao()));
|
||||
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
|
||||
|
||||
controle.BeginInvoke(new Action(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await acao();
|
||||
tcs.SetResult(null);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
tcs.SetException(ex);
|
||||
}
|
||||
}));
|
||||
|
||||
await tcs.Task;
|
||||
}
|
||||
else
|
||||
{
|
||||
|
|
@ -753,23 +768,34 @@ namespace AgroBase.Models
|
|||
}
|
||||
}
|
||||
|
||||
|
||||
public static T ExecutarMetodoComVerificacaoCrossThread<T>(Control controle, Func<T> acao)
|
||||
{
|
||||
if (controle == null)
|
||||
throw new ArgumentNullException(nameof(controle));
|
||||
|
||||
if (controle.InvokeRequired)
|
||||
try
|
||||
{
|
||||
return (T)controle.Invoke(new Func<T>(() => acao()));
|
||||
if (controle.InvokeRequired)
|
||||
{
|
||||
return (T)controle.Invoke(new Func<T>(() => acao()));
|
||||
}
|
||||
else
|
||||
{
|
||||
return acao();
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
return acao();
|
||||
// Log ou tratamento da exceção
|
||||
Console.WriteLine($"Erro em ExecutarMetodoComVerificacaoCrossThread: {ex.Message}");
|
||||
throw; // Relançar a exceção para quem chamou lidar com ela, se necessário
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
public static string MontarStringPerformance(float? gpuLoad, float? cpuLoad, float? ramUsage, float? cpuTemp, float? gpuTemp)
|
||||
{
|
||||
return $"GPU: {gpuLoad?.ToString("0.0") ?? "N/A"}% " +
|
||||
|
|
|
|||
|
|
@ -373,7 +373,7 @@ namespace AgroBase.Services
|
|||
if (!SerialService.DispositivosMapeados.Any(x => x.Dispositivo == T_Code.Bld && x.Mod_ID == Mod_ID))
|
||||
{
|
||||
var leitura = DadosLeitura.FirstOrDefault(x => x.Endereco == Addr);
|
||||
SerialService.DispositivosMapeados.Add(new SerialService.DispositivoDetalhesModel()
|
||||
SerialService.DispositivosMapeados.Add(new DispositivoDetalhesModel()
|
||||
{
|
||||
Endereco = _ethernetService != null ? _ethernetService._ipAddress : "N/A",
|
||||
Dispositivo = T_Code.Bld,
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ using System;
|
|||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Management;
|
||||
using System.Threading.Tasks;
|
||||
using static MqttService;
|
||||
|
||||
namespace AgroBase.Services
|
||||
|
|
@ -25,31 +26,21 @@ namespace AgroBase.Services
|
|||
public string URLcamera = "";
|
||||
|
||||
|
||||
public void IniciarCamera(string Script, string[] Argumentos, string FlaskPorta, string FlaskUrl, string MqttTopico, AsyncTaskTimerModel tmrProcesso)
|
||||
public void IniciarCamera(string Script, string[] Argumentos, string FlaskPorta, string FlaskUrl, string MqttTopico, Func<MqttTopicosMensagensModel, Task> mqttCallback = null)
|
||||
{
|
||||
if (_mqttTopico == null)
|
||||
Task.Run(async () =>
|
||||
{
|
||||
_mqttTopico = new MqttTopicosModel()
|
||||
{
|
||||
Topico = MqttTopico,
|
||||
Mensagens = new List<MqttTopicosMensagensModel>(),
|
||||
Inscrever = true,
|
||||
MensagensManter = 10
|
||||
};
|
||||
}
|
||||
Variaveis.MqttService.Topicos.Add(_mqttTopico);
|
||||
Variaveis.MqttService.SubscribeAsync(_mqttTopico).ConfigureAwait(false);
|
||||
_mqttTopico = await Variaveis.MqttService.AdicionarNovoTopico(MqttTopico, true, 1, mqttCallback);
|
||||
|
||||
tmrProcesso.Start();
|
||||
pythonProcess = new Process();
|
||||
pythonProcess = PythonService.RunScript(Script, Argumentos);
|
||||
pythonProcess.Exited += PythonProcess_Exited;
|
||||
IniciadoEm = DateTime.Now;
|
||||
pythonProcess = new Process();
|
||||
pythonProcess = PythonService.RunScript(Script, Argumentos);
|
||||
IniciadoEm = DateTime.Now;
|
||||
|
||||
URLcamera = "http://" + Endereco + ":" + FlaskPorta + "/" + FlaskUrl +
|
||||
"?conf_threshold=" + conf_threshold.ToString().Replace(",", ".") +
|
||||
"&nms_threshold=" + nms_threshold.ToString().Replace(",", ".") +
|
||||
"&camera_index=" + (selectedCamera - 1);
|
||||
URLcamera = "http://" + Endereco + ":" + FlaskPorta + "/" + FlaskUrl +
|
||||
"?conf_threshold=" + conf_threshold.ToString().Replace(",", ".") +
|
||||
"&nms_threshold=" + nms_threshold.ToString().Replace(",", ".") +
|
||||
"&camera_index=" + (selectedCamera - 1);
|
||||
});
|
||||
}
|
||||
|
||||
private void PythonProcess_Exited(object sender, EventArgs e)
|
||||
|
|
|
|||
|
|
@ -8,12 +8,11 @@ using Newtonsoft.Json;
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Ports;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using static AgroBase.Models.Enums;
|
||||
using static MqttService;
|
||||
|
||||
namespace AgroBase.Comum
|
||||
{
|
||||
|
|
@ -23,14 +22,9 @@ namespace AgroBase.Comum
|
|||
public string _Nome { get; set; }
|
||||
public string _Descricao { get; set; }
|
||||
public DateTime _CriadoEm { get; set; }
|
||||
public SerialPort _Porta { get; set; } = null;
|
||||
public GroupBox gpbItem { get; set; }
|
||||
public ComboBox cmbPorta { get; set; }
|
||||
public ComboBox cmbBaudRate { get; set; }
|
||||
public NumericUpDown nudAmostragem { get; set; }
|
||||
public Label lblStatus { get; set; }
|
||||
public Button btnConectar { get; set; }
|
||||
public Button btnAtualizar { get; set; }
|
||||
public TextBox txtEnvios { get; set; }
|
||||
public RichTextBox txaConsole { get; set; }
|
||||
public int _index { get; set; }
|
||||
|
|
@ -43,189 +37,106 @@ namespace AgroBase.Comum
|
|||
set { this.Dados = (T)value; } // Isso pode lançar uma exceção se o valor não for do tipo T
|
||||
}
|
||||
public Form frmConfig { get; set; }
|
||||
public Form frmPlot { get; set; }
|
||||
public Form frmPin { get; set; }
|
||||
private AsyncTaskTimerModel tmrLogsDispositivo;
|
||||
|
||||
|
||||
public AsyncTaskTimerModel tmrLimpeza;
|
||||
public int Ticks { get; set; } = 0;
|
||||
|
||||
public int TempoConectado { get; set; } = 0;
|
||||
|
||||
private int _baudRate;
|
||||
public int BaudRate()
|
||||
public MqttTopicosModel MqttTopicoEnvioComandos;
|
||||
public MqttTopicosModel MqttTopicoRecebimentoDados;
|
||||
|
||||
|
||||
public async Task GerenciarMqttTopicos()
|
||||
{
|
||||
return _baudRate;
|
||||
/*if (cmbBaudRate.SelectedIndex < 0)
|
||||
MqttTopicoEnvioComandos = await Variaveis.MqttService.AdicionarNovoTopico($"disp/tx/{Dispositivo.ToString()}");
|
||||
MqttTopicoRecebimentoDados = await Variaveis.MqttService.AdicionarNovoTopico($"disp/rx/{Dispositivo.ToString()}", true, 1, async (Mensagem) =>
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
return Convert.ToInt32(cmbBaudRate.SelectedItem.ToString());*/
|
||||
}
|
||||
|
||||
private string _portName;
|
||||
public string PortaCOM()
|
||||
{
|
||||
return _portName;
|
||||
/*if (cmbPorta.SelectedIndex < 0)
|
||||
{
|
||||
return "";
|
||||
}
|
||||
return cmbPorta.SelectedItem.ToString();*/
|
||||
}
|
||||
|
||||
public string StatusPorta()
|
||||
{
|
||||
string _status = _Porta.IsOpen ? "Conectado" : "Desconectado";
|
||||
//frmInstancial.frmPrincipal.lblStripErro.Text = _status;
|
||||
return _status;
|
||||
}
|
||||
|
||||
public void AtualizarPortas()
|
||||
{
|
||||
var DispositivosTipo = SerialService.DispositivosMapeados.Where(x => x.Dispositivo == Dispositivo).ToList();
|
||||
for (int i = 0; i < DispositivosTipo.Count(); i++)
|
||||
{
|
||||
FuncoesGlobais.ExecutarMetodoComVerificacaoCrossThread<bool>(frmInstancial.frmPrincipal, () =>
|
||||
{
|
||||
if (cmbPorta != null)
|
||||
{
|
||||
if (!cmbPorta.Items.Contains(DispositivosTipo[i].Endereco))
|
||||
{
|
||||
string PortaCom = DispositivosTipo[i].Endereco;
|
||||
var _Porta = new SerialPort() { PortName = PortaCom, BaudRate = 115200 };
|
||||
try
|
||||
{
|
||||
_Porta.Open();
|
||||
_Porta.Close();
|
||||
|
||||
cmbPorta.Items.Add(PortaCom);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
FuncoesGlobais.ExecutarMetodoComVerificacaoCrossThread<bool>(frmInstancial.frmPrincipal, () =>
|
||||
{
|
||||
if (cmbPorta != null)
|
||||
{
|
||||
if (!DispositivosTipo.Any())
|
||||
{
|
||||
cmbPorta.Items.Clear();
|
||||
cmbPorta.Text = "";
|
||||
}
|
||||
if (cmbPorta.Items.Count > 1)
|
||||
cmbPorta.SelectedIndex = 1;
|
||||
else if (cmbPorta.Items.Count > 0)
|
||||
cmbPorta.SelectedIndex = 0;
|
||||
|
||||
if (cmbPorta.Text != "")
|
||||
{
|
||||
_baudRate = 115200;
|
||||
_portName = cmbPorta.Text;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
ReceberDadosMqtt(Mensagem);
|
||||
});
|
||||
}
|
||||
|
||||
public void AtualizarBauds()
|
||||
private void ReceberDadosMqtt(MqttTopicosMensagensModel Mensagem)
|
||||
{
|
||||
cmbBaudRate.Items.Clear();
|
||||
cmbBaudRate.Text = "";
|
||||
Dados.IniciarRegistrador();
|
||||
|
||||
cmbBaudRate.Items.Add("9600");
|
||||
cmbBaudRate.Items.Add("34800");
|
||||
cmbBaudRate.Items.Add("115200");
|
||||
string Recebido = Mensagem.Mensagem;
|
||||
string mensagem = "";
|
||||
|
||||
cmbBaudRate.SelectedIndex = 2;
|
||||
}
|
||||
Console.WriteLine(Recebido);
|
||||
|
||||
|
||||
public bool ConectarPortaSerial()
|
||||
{
|
||||
try
|
||||
bool RespostaMensagem = false;
|
||||
if (Recebido.Contains(SerialService.SplitMessage))
|
||||
{
|
||||
_Porta.PortName = PortaCOM();
|
||||
_Porta.BaudRate = BaudRate();
|
||||
//_Porta = new SerialPort(PortaCOM(), BaudRate());
|
||||
_Porta.ReadBufferSize = 16384;
|
||||
_Porta.WriteBufferSize = 8192;
|
||||
|
||||
if (_Porta.IsOpen)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
_Porta.Open();
|
||||
|
||||
LimparBufferSerial(false);
|
||||
|
||||
lblStatus.Text = StatusPorta();
|
||||
|
||||
return _Porta.IsOpen;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
frmInstancial.frmPrincipal.lblStripErro.Text = "Erro ao conectar na porta '" + PortaCOM() + "' - " + ex.Message;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public bool DesconectarPortaSerial()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!_Porta.IsOpen)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
LimparBufferSerial(false);
|
||||
|
||||
Task.Run(() =>
|
||||
string Mod_ID = Recebido.Split(SerialService.SplitMessage[0])[0];
|
||||
mensagem = Recebido.Substring(Mod_ID.Length + 1, Recebido.Length - Mod_ID.Length - 1);
|
||||
var DadosMensagem = mensagem.Split(SerialService.SplitMessage[0]);
|
||||
if (DadosMensagem.Length > 2 && int.TryParse(DadosMensagem[0], out int val))
|
||||
{
|
||||
try
|
||||
{
|
||||
_Porta.Close();
|
||||
F_Code funcao = (F_Code)(val);
|
||||
switch (funcao)
|
||||
{
|
||||
case F_Code.Msg:
|
||||
{
|
||||
int _id = int.Parse(DadosMensagem[1]);
|
||||
FilaService.MarcarMensagemRecebida(_id);
|
||||
RespostaMensagem = true;
|
||||
break;
|
||||
}
|
||||
case F_Code.Chk:
|
||||
{
|
||||
bool conectado = DadosMensagem[3] == "1";
|
||||
Dados.DefineStatusConexao(Mod_ID, conectado);
|
||||
RespostaMensagem = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
catch
|
||||
{
|
||||
// Log ou trate a exceção conforme necessário
|
||||
MessageBox.Show($"Erro ao fechar a porta serial: {ex.Message}");
|
||||
|
||||
}
|
||||
});
|
||||
|
||||
lblStatus.Text = StatusPorta();
|
||||
|
||||
return !_Porta.IsOpen;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
lock (_logsLock)
|
||||
{
|
||||
frmInstancial.frmPrincipal.lblStripErro.Text = "Erro ao desconectar da porta '" + PortaCOM() + "' - " + ex.Message;
|
||||
return false;
|
||||
Logs.Add(new DispositivoLogModel()
|
||||
{
|
||||
Momento = DateTime.Now,
|
||||
Enviado = false,
|
||||
Protocolo = Recebido,
|
||||
});
|
||||
}
|
||||
|
||||
//AtualizarConsole("< " + DateTime.Now.ToString("HH:mm:ss:fff") + " - " + Recebido);
|
||||
|
||||
if (!RespostaMensagem && mensagem.Trim().EndsWith(SerialService.EndLine))
|
||||
{
|
||||
Dados.RecebeProtocoloModulo(mensagem.Trim());
|
||||
}
|
||||
}
|
||||
|
||||
public void EnviarDadosSerial(string Dados)
|
||||
public async Task EnviarDadosMQTT(string Dados)
|
||||
{
|
||||
if (!_Porta.IsOpen || string.IsNullOrEmpty(Dados))
|
||||
if (MqttTopicoEnvioComandos == null || string.IsNullOrEmpty(Dados))
|
||||
{
|
||||
throw new Exception("A porta " + _Porta.PortName + " não está aberta");
|
||||
throw new Exception("O tópico de envio de comandos não foi iniciado ou não foi enviado dados para envio");
|
||||
}
|
||||
|
||||
AtualizarConsole("> " + DateTime.Now.ToString("HH:mm:ss:fff") + " - " + Dados);
|
||||
//AtualizarConsole("> " + DateTime.Now.ToString("HH:mm:ss:fff") + " - " + Dados);
|
||||
|
||||
try
|
||||
{
|
||||
bool erroEnvio = !SerialService.EnviarDadosPortaSerial(_Porta, Dados);
|
||||
// Publique o array de bytes via MQTT
|
||||
await Variaveis.MqttService.PublishAsync(
|
||||
MqttTopicoEnvioComandos,
|
||||
Dados
|
||||
);
|
||||
|
||||
//Console.WriteLine("Dados enviados: " + Dados);
|
||||
lock (_logsLock)
|
||||
{
|
||||
|
|
@ -234,40 +145,52 @@ namespace AgroBase.Comum
|
|||
Momento = DateTime.Now,
|
||||
Enviado = true,
|
||||
Protocolo = Dados,
|
||||
ErroEnvio = erroEnvio,
|
||||
ErroEnvio = false,
|
||||
});
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine("Erro ao enviar comando para a porta: " + _Porta.PortName + " - " + ex.Message);
|
||||
Console.WriteLine("Erro ao enviar comando para o tópico: " + MqttTopicoEnvioComandos.Topico + " - " + ex.Message);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
public MqttTopicosModel GetMqttTopico(bool Envio)
|
||||
{
|
||||
return Envio ? MqttTopicoEnvioComandos : MqttTopicoRecebimentoDados;
|
||||
}
|
||||
|
||||
public void AdicionarMensagemFila(string Mod_ID, string mensagem, bool _prioridade, bool _aguardaCallback)
|
||||
{
|
||||
if (_Porta.IsOpen && Mod_ID != "" && mensagem != "")
|
||||
if (Mod_ID != "" && mensagem != "")
|
||||
{
|
||||
FilaService.AdicionarMensagemFila(Mod_ID, Dispositivo, mensagem, _prioridade, _aguardaCallback);
|
||||
string comandoEnviar =
|
||||
"0" +
|
||||
SerialService.SplitMessage +
|
||||
Mod_ID +
|
||||
SerialService.SplitMessage +
|
||||
mensagem +
|
||||
SerialService.EndLine;
|
||||
//FilaService.AdicionarMensagemFila(Mod_ID, Dispositivo, mensagem, _prioridade, _aguardaCallback);
|
||||
Task.Run(async () =>
|
||||
{
|
||||
await EnviarDadosMQTT(comandoEnviar);
|
||||
Console.WriteLine("Comando enviado: " + comandoEnviar);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public Control InstanciarDispositivo(int index)
|
||||
{
|
||||
CarregarParametrosModulos();
|
||||
|
||||
((dynamic)Dados).Conectado = false;
|
||||
|
||||
frmPin = new frmPinout(Dispositivo);
|
||||
|
||||
_Porta.DataReceived -= _Porta_DataReceived;
|
||||
_Porta.DataReceived += _Porta_DataReceived;
|
||||
|
||||
gpbItem = new GroupBox()
|
||||
{
|
||||
Name = "gpb" + _Nome,
|
||||
Text = _Descricao,
|
||||
Text = _Nome,
|
||||
Location = new System.Drawing.Point() { X = 13, Y = 0 },
|
||||
Size = new System.Drawing.Size() { Height = 251, Width = 580 },
|
||||
};
|
||||
|
|
@ -279,15 +202,6 @@ namespace AgroBase.Comum
|
|||
Location = new System.Drawing.Point() { X = 28, Y = 27 },
|
||||
Size = new System.Drawing.Size() { Height = 17, Width = 42 }
|
||||
};
|
||||
cmbPorta = new ComboBox()
|
||||
{
|
||||
Name = "cmb" + _Nome + "Por",
|
||||
Text = "",
|
||||
Location = new System.Drawing.Point() { X = 31, Y = 47 },
|
||||
Size = new System.Drawing.Size() { Height = 24, Width = 89 },
|
||||
DropDownStyle = ComboBoxStyle.DropDownList
|
||||
};
|
||||
AtualizarPortas();
|
||||
Label lblBaudRate = new Label()
|
||||
{
|
||||
Name = "lbl" + _Nome + "Bau",
|
||||
|
|
@ -295,15 +209,6 @@ namespace AgroBase.Comum
|
|||
Location = new System.Drawing.Point() { X = 28, Y = 74 },
|
||||
Size = new System.Drawing.Size() { Height = 17, Width = 75 }
|
||||
};
|
||||
cmbBaudRate = new ComboBox()
|
||||
{
|
||||
Name = "cmb" + _Nome + "Bau",
|
||||
Text = "",
|
||||
Location = new System.Drawing.Point() { X = 31, Y = 94 },
|
||||
Size = new System.Drawing.Size() { Height = 24, Width = 89 },
|
||||
DropDownStyle = ComboBoxStyle.DropDownList
|
||||
};
|
||||
AtualizarBauds();
|
||||
Label lblAmostragem = new Label()
|
||||
{
|
||||
Name = "lbl" + _Nome + "Amo",
|
||||
|
|
@ -322,28 +227,10 @@ namespace AgroBase.Comum
|
|||
};
|
||||
nudAmostragem.ValueChanged -= nudAmostragem_ValueChanged;
|
||||
nudAmostragem.ValueChanged += nudAmostragem_ValueChanged;
|
||||
btnAtualizar = new Button()
|
||||
{
|
||||
Name = "btn" + _Nome + "Att",
|
||||
Text = "Atualizar",
|
||||
Location = new System.Drawing.Point() { X = 31, Y = 170 },
|
||||
Size = new System.Drawing.Size() { Height = 24, Width = 89 }
|
||||
};
|
||||
btnAtualizar.Click -= btnAtualizar_Click;
|
||||
btnAtualizar.Click += btnAtualizar_Click;
|
||||
btnConectar = new Button()
|
||||
{
|
||||
Name = "btn" + _Nome + "Con",
|
||||
Text = "Conectar",
|
||||
Location = new System.Drawing.Point() { X = 31, Y = 201 },
|
||||
Size = new System.Drawing.Size() { Height = 24, Width = 89 }
|
||||
};
|
||||
btnConectar.Click -= btnConectar_Click;
|
||||
btnConectar.Click += btnConectar_Click;
|
||||
lblStatus = new Label()
|
||||
{
|
||||
Name = "lbl" + _Nome + "Sta",
|
||||
Text = _Porta.IsOpen ? "Conectado" : "Desconectado",
|
||||
Text = Dados.GetStatusConexao() ? "Conectado" : "Desconectado",
|
||||
Location = new System.Drawing.Point() { X = 28, Y = 231 },
|
||||
Size = new System.Drawing.Size() { Height = 17, Width = 100 }
|
||||
};
|
||||
|
|
@ -390,8 +277,12 @@ namespace AgroBase.Comum
|
|||
else if (Dados is AtuadorModel atuModel && Dispositivo == T_Code.Atu)
|
||||
{
|
||||
clbDispositivos.Items.Clear();
|
||||
clbDispositivos.Items.Add(atuModel.BombaPressurizadora.ID.ToString());
|
||||
clbDispositivos.SetItemChecked(clbDispositivos.Items.Count - 1, atuModel.BombaPressurizadora.Comandar);
|
||||
var Bombas = atuModel.BombasPressurizadoras.ToList();
|
||||
foreach (var Bomba in Bombas)
|
||||
{
|
||||
clbDispositivos.Items.Add(Bomba.ID.ToString());
|
||||
clbDispositivos.SetItemChecked(clbDispositivos.Items.Count - 1, Bomba.Comandar);
|
||||
}
|
||||
var Bicos = atuModel.BicosPulverizadores.ToList();
|
||||
foreach (var Bico in Bicos)
|
||||
{
|
||||
|
|
@ -436,15 +327,6 @@ namespace AgroBase.Comum
|
|||
};
|
||||
txtEnvios.KeyDown -= txtEnvios_KeyDown;
|
||||
txtEnvios.KeyDown += txtEnvios_KeyDown;
|
||||
Button btnLimpar = new Button()
|
||||
{
|
||||
Name = "btn" + _Nome + "Lim",
|
||||
Text = "Limpar",
|
||||
Location = new System.Drawing.Point() { X = 480, Y = 47 },
|
||||
Size = new System.Drawing.Size() { Height = 24, Width = 70 },
|
||||
};
|
||||
btnLimpar.Click -= btnLimpar_Click;
|
||||
btnLimpar.Click += btnLimpar_Click;
|
||||
Label lblRecebidos = new Label()
|
||||
{
|
||||
Name = "lbl" + _Nome + "Rec",
|
||||
|
|
@ -460,7 +342,6 @@ namespace AgroBase.Comum
|
|||
Size = new System.Drawing.Size() { Height = 141, Width = 300 },
|
||||
ReadOnly = true
|
||||
};
|
||||
tmrLimpeza = new AsyncTaskTimerModel("tmrLimpeza_" + Dispositivo.ToString(), tmrLimpeza_Tick, 1000, frmInstancial.frmPrincipal);
|
||||
|
||||
Button btnConfig = new Button()
|
||||
{
|
||||
|
|
@ -472,15 +353,6 @@ namespace AgroBase.Comum
|
|||
btnConfig.Click -= btnConfig_Click;
|
||||
btnConfig.Click += btnConfig_Click;
|
||||
btnConfig.Enabled = frmConfig != null;
|
||||
/*Button btnPlot = new Button()
|
||||
{
|
||||
Name = "btn" + _Nome + "Plot",
|
||||
Text = "Plotagem",
|
||||
Location = new System.Drawing.Point() { X = 135, Y = 201 },
|
||||
Size = new System.Drawing.Size() { Height = 24, Width = 89 }
|
||||
};
|
||||
btnPlot.Click -= btnPlot_Click;
|
||||
btnPlot.Click += btnPlot_Click;*/
|
||||
Button btnPinout = new Button()
|
||||
{
|
||||
Name = "btn" + _Nome + "Pinout",
|
||||
|
|
@ -491,25 +363,21 @@ namespace AgroBase.Comum
|
|||
btnPinout.Click -= btnPinout_Click;
|
||||
btnPinout.Click += btnPinout_Click;
|
||||
|
||||
tmrLogsDispositivo = new AsyncTaskTimerModel("tmrLogsDispositivo", tmrLogsDispositivo_Tick, 1000);
|
||||
tmrLogsDispositivo.Start();
|
||||
|
||||
gpbItem.Controls.Add(lblPorta);
|
||||
gpbItem.Controls.Add(cmbPorta);
|
||||
gpbItem.Controls.Add(lblBaudRate);
|
||||
gpbItem.Controls.Add(cmbBaudRate);
|
||||
gpbItem.Controls.Add(lblAmostragem);
|
||||
gpbItem.Controls.Add(nudAmostragem);
|
||||
gpbItem.Controls.Add(lblDispositivos);
|
||||
gpbItem.Controls.Add(clbDispositivos);
|
||||
gpbItem.Controls.Add(btnAtualizar);
|
||||
gpbItem.Controls.Add(btnConectar);
|
||||
gpbItem.Controls.Add(lblStatus);
|
||||
gpbItem.Controls.Add(lblEnvio);
|
||||
gpbItem.Controls.Add(txtEnvios);
|
||||
gpbItem.Controls.Add(btnLimpar);
|
||||
gpbItem.Controls.Add(lblRecebidos);
|
||||
gpbItem.Controls.Add(txaConsole);
|
||||
gpbItem.Controls.Add(btnConfig);
|
||||
//gpbItem.Controls.Add(btnPlot);
|
||||
gpbItem.Controls.Add(btnPinout);
|
||||
|
||||
return gpbItem;
|
||||
|
|
@ -524,14 +392,6 @@ namespace AgroBase.Comum
|
|||
}
|
||||
}
|
||||
|
||||
private void btnPlot_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (frmPlot != null)
|
||||
{
|
||||
frmPlot.Show();
|
||||
}
|
||||
}
|
||||
|
||||
private void btnConfig_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (frmConfig != null)
|
||||
|
|
@ -540,12 +400,8 @@ namespace AgroBase.Comum
|
|||
}
|
||||
}
|
||||
|
||||
private async Task tmrLimpeza_Tick()
|
||||
private async Task tmrLogsDispositivo_Tick()
|
||||
{
|
||||
if (Ticks % 5 == 0)
|
||||
{
|
||||
LimparBufferSerial(true);
|
||||
}
|
||||
if (Ticks >= 30)
|
||||
{
|
||||
SalvarLog();
|
||||
|
|
@ -628,7 +484,7 @@ namespace AgroBase.Comum
|
|||
{
|
||||
atuModel.BicosPulverizadores.ForEach(x => x.Comandar = false);
|
||||
atuModel.Sensores.ForEach(x => x.Aferir = false);
|
||||
atuModel.BombaPressurizadora.Comandar = false;
|
||||
atuModel.BombasPressurizadoras.ForEach(x => x.Comandar = false);
|
||||
foreach (var Item in ((CheckedListBox)sender).CheckedItems)
|
||||
{
|
||||
if (atuModel.BicosPulverizadores.Any(x => x.ID == Item.ToString()))
|
||||
|
|
@ -639,9 +495,9 @@ namespace AgroBase.Comum
|
|||
{
|
||||
atuModel.Sensores.FirstOrDefault(x => x.ID == Item.ToString()).Aferir = true;
|
||||
}
|
||||
else if (atuModel.BombaPressurizadora.ID == Item.ToString())
|
||||
else if (atuModel.BombasPressurizadoras.Any(x => x.ID == Item.ToString()))
|
||||
{
|
||||
atuModel.BombaPressurizadora.Comandar = true;
|
||||
atuModel.BombasPressurizadoras.FirstOrDefault(x => x.ID == Item.ToString()).Comandar = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -678,32 +534,6 @@ namespace AgroBase.Comum
|
|||
Dados.SetTaxaAmostragem((Convert.ToInt32(((NumericUpDown)sender).Value)));
|
||||
}
|
||||
|
||||
private void btnLimpar_Click(object sender, EventArgs e)
|
||||
{
|
||||
LimparBufferSerial(true);
|
||||
}
|
||||
|
||||
public void LimparBufferSerial(bool LimparConsole)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (LimparConsole)
|
||||
{
|
||||
txaConsole.Text = "";
|
||||
}
|
||||
|
||||
if (_Porta.IsOpen)
|
||||
{
|
||||
_Porta.DiscardInBuffer();
|
||||
_Porta.DiscardOutBuffer();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine("Erro ao limpar buffer da porta " + _Porta.PortName);
|
||||
}
|
||||
}
|
||||
|
||||
private void txtEnvios_KeyDown(object sender, KeyEventArgs e)
|
||||
{
|
||||
if (e.KeyCode == Keys.Enter && txtEnvios.Text != "")
|
||||
|
|
@ -722,208 +552,16 @@ namespace AgroBase.Comum
|
|||
gpbItem.Location = new System.Drawing.Point() { X = gpbItem.Location.X, Y = (220 + (_index * 210)) };
|
||||
}
|
||||
|
||||
private void _Porta_DataReceived(object sender, SerialDataReceivedEventArgs e)
|
||||
public void EnviarProtocolosConfiguracao(bool Conectar = true)
|
||||
{
|
||||
Dados.IniciarRegistrador();
|
||||
|
||||
string Recebido = "";
|
||||
try
|
||||
Dictionary<string, List<string>> Config = Dados.ProtocoloConfiguracao(Conectar);
|
||||
foreach (var ProtocoloConfiguracao in Config)
|
||||
{
|
||||
Recebido = SerialService.ReadLineWithTimeout(_Porta, 2000);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine("Erro ao receber dados da porta " + _Porta.PortName + " - " + ex.Message);
|
||||
}
|
||||
if (Recebido == "")
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
string mensagem = "";
|
||||
//Console.WriteLine(Recebido);
|
||||
|
||||
if (Recebido.Contains(SerialService.SplitMessage))
|
||||
{
|
||||
string Mod_ID = Recebido.Split(SerialService.SplitMessage[0])[0];
|
||||
mensagem = Recebido.Substring(Mod_ID.Length + 1, Recebido.Length - Mod_ID.Length - 1);
|
||||
var DadosMensagem = mensagem.Split(SerialService.SplitMessage[0]);
|
||||
if (DadosMensagem.Length > 2 && int.TryParse(DadosMensagem[0], out int val))
|
||||
if (ProtocoloConfiguracao.Key != "" && ProtocoloConfiguracao.Value.Any())
|
||||
{
|
||||
try
|
||||
{
|
||||
F_Code funcao = (F_Code)(val);
|
||||
switch (funcao)
|
||||
{
|
||||
case F_Code.Msg:
|
||||
{
|
||||
int _id = int.Parse(DadosMensagem[1]);
|
||||
FilaService.MarcarMensagemRecebida(_id);
|
||||
break;
|
||||
}
|
||||
case F_Code.Chk:
|
||||
{
|
||||
bool conectado = DadosMensagem[3] == "1";
|
||||
Dados.DefineStatusConexao(Mod_ID, conectado);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
ProtocoloConfiguracao.Value.ForEach(x => AdicionarMensagemFila(ProtocoloConfiguracao.Key, x, true, true));
|
||||
}
|
||||
}
|
||||
|
||||
lock (_logsLock)
|
||||
{
|
||||
Logs.Add(new DispositivoLogModel()
|
||||
{
|
||||
Momento = DateTime.Now,
|
||||
Enviado = false,
|
||||
Protocolo = Recebido,
|
||||
});
|
||||
}
|
||||
|
||||
AtualizarConsole("< " + DateTime.Now.ToString("HH:mm:ss:fff") + " - " + Recebido);
|
||||
|
||||
if (mensagem != "" && mensagem[0].ToString() == SerialService.BeginSensor && !EqualityComparer<T>.Default.Equals(Dados, default(T)))
|
||||
{
|
||||
Dados.RecebeProtocoloSerial(Recebido);
|
||||
}
|
||||
}
|
||||
|
||||
public void btnConectar_Click(object sender, EventArgs e)
|
||||
{
|
||||
var dispositivosConexaoInicial = SerialService.DispositivosMapeados
|
||||
.Where(x => SerialService.DispositivosConexaoInicial.Contains(x.Dispositivo))
|
||||
.ToList();
|
||||
|
||||
var Config = new Dictionary<string, List<string>>();
|
||||
|
||||
if (_Porta.IsOpen)
|
||||
{
|
||||
LimparBufferSerial(false);
|
||||
|
||||
Config = Dados.ProtocoloConfiguracao(false);
|
||||
foreach (var ProtocoloConfiguracao in Config)
|
||||
{
|
||||
if (ProtocoloConfiguracao.Key != "" && ProtocoloConfiguracao.Value.Any())
|
||||
{
|
||||
ProtocoloConfiguracao.Value.ForEach(x => AdicionarMensagemFila(ProtocoloConfiguracao.Key, x, true, true));
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (ConectarPortaSerial())
|
||||
{
|
||||
LimparBufferSerial(false);
|
||||
|
||||
Config = Dados.ProtocoloConfiguracao(true);
|
||||
foreach (var ProtocoloConfiguracao in Config)
|
||||
{
|
||||
if (ProtocoloConfiguracao.Key != "" && ProtocoloConfiguracao.Value.Any())
|
||||
{
|
||||
ProtocoloConfiguracao.Value.ForEach(x => AdicionarMensagemFila(ProtocoloConfiguracao.Key, x, true, true));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void AcaoConexao()
|
||||
{
|
||||
if (!Dados.GetStatusConexao())
|
||||
{
|
||||
if (DesconectarPortaSerial())
|
||||
{
|
||||
AcaoDesconectar();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
AcaoConectar();
|
||||
}
|
||||
}
|
||||
|
||||
public void AcaoDesconectar()
|
||||
{
|
||||
if (cmbPorta != null)
|
||||
{
|
||||
// Verifica se a invocação é necessária
|
||||
if (cmbPorta.InvokeRequired)
|
||||
{
|
||||
// Invoca a ação na thread de UI
|
||||
cmbPorta.Invoke(new Action(AcaoDesconectar));
|
||||
}
|
||||
else
|
||||
{
|
||||
// Código que altera as propriedades dos componentes
|
||||
cmbPorta.Enabled = true;
|
||||
cmbBaudRate.Enabled = true;
|
||||
btnAtualizar.Enabled = true;
|
||||
nudAmostragem.Enabled = true;
|
||||
txtEnvios.ReadOnly = true;
|
||||
txtEnvios.Text = "";
|
||||
btnConectar.Text = "Conectar";
|
||||
|
||||
tmrLimpeza.Stop();
|
||||
|
||||
SalvarLog();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void AcaoConectar()
|
||||
{
|
||||
// Verifica se a invocação é necessária
|
||||
if (cmbPorta.InvokeRequired)
|
||||
{
|
||||
// Invoca a ação na thread de UI
|
||||
cmbPorta.Invoke(new Action(AcaoConectar));
|
||||
}
|
||||
else
|
||||
{
|
||||
// Código que altera as propriedades dos componentes
|
||||
cmbPorta.Enabled = false;
|
||||
cmbBaudRate.Enabled = false;
|
||||
btnAtualizar.Enabled = false;
|
||||
nudAmostragem.Enabled = false;
|
||||
txtEnvios.ReadOnly = false;
|
||||
txtEnvios.Text = "";
|
||||
btnConectar.Text = "Desconectar";
|
||||
tmrLimpeza.Start();
|
||||
}
|
||||
}
|
||||
|
||||
private void btnAtualizar_Click(object sender, EventArgs e)
|
||||
{
|
||||
AtualizarPortas();
|
||||
}
|
||||
|
||||
|
||||
|
||||
private void AtualizarConsole(string texto)
|
||||
{
|
||||
if (frmInstancial.Fechando)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
texto += Environment.NewLine;
|
||||
|
||||
FuncoesGlobais.ExecutarMetodoComVerificacaoCrossThread(txaConsole, () =>
|
||||
{
|
||||
if (txaConsole.IsDisposed || txaConsole.Disposing)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
txaConsole.Text += texto;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
private T CarregarParametros(dynamic empty)
|
||||
|
|
|
|||
|
|
@ -23,7 +23,6 @@ namespace AgroBase.Services
|
|||
Dispositivo = tipoDispositivo,
|
||||
_Nome = nome,
|
||||
_Descricao = descricao,
|
||||
_Porta = porta,
|
||||
_CriadoEm = DateTime.Now,
|
||||
};
|
||||
case T_Code.Atu:
|
||||
|
|
@ -32,7 +31,6 @@ namespace AgroBase.Services
|
|||
Dispositivo = tipoDispositivo,
|
||||
_Nome = nome,
|
||||
_Descricao = descricao,
|
||||
_Porta = porta,
|
||||
_CriadoEm = DateTime.Now,
|
||||
};
|
||||
case T_Code.Mvd:
|
||||
|
|
@ -41,7 +39,6 @@ namespace AgroBase.Services
|
|||
Dispositivo = tipoDispositivo,
|
||||
_Nome = nome,
|
||||
_Descricao = descricao,
|
||||
_Porta = porta,
|
||||
_CriadoEm = DateTime.Now,
|
||||
};
|
||||
default:
|
||||
|
|
|
|||
|
|
@ -47,22 +47,32 @@ namespace AgroBase.Services
|
|||
|
||||
public static void AdicionarMensagemFila(string Modulo_ID, T_Code Dispositivo, string Mensagem, bool _prioridade, bool _aguardaCallback)
|
||||
{
|
||||
var _Mensagem = new MensagemFilaModel()
|
||||
{
|
||||
Id = _counter,
|
||||
ID_Modulo = Modulo_ID,
|
||||
Dispositivo = Dispositivo,
|
||||
Mensagem = Mensagem,
|
||||
AdicionadoEm = DateTime.Now,
|
||||
Enviado = false,
|
||||
Recebido = false,
|
||||
Prioridade = _prioridade,
|
||||
AguardaCallback = _aguardaCallback,
|
||||
Reenvios = 0,
|
||||
};
|
||||
|
||||
RealizarEnvio(_Mensagem);
|
||||
|
||||
return;
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
MensagensFila.Add(new MensagemFilaModel()
|
||||
if (!MensagensFila.Any(x => !x.Enviado && x.Dispositivo == Dispositivo && x.ID_Modulo == Modulo_ID && x.Mensagem == Mensagem))
|
||||
{
|
||||
Id = _counter,
|
||||
ID_Modulo = Modulo_ID,
|
||||
Dispositivo = Dispositivo,
|
||||
Mensagem = Mensagem,
|
||||
AdicionadoEm = DateTime.Now,
|
||||
Enviado = false,
|
||||
Recebido = false,
|
||||
Prioridade = _prioridade,
|
||||
AguardaCallback = _aguardaCallback,
|
||||
Reenvios = 0,
|
||||
});
|
||||
_counter++;
|
||||
MensagensFila.Add(_Mensagem);
|
||||
|
||||
_counter++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -124,8 +134,8 @@ namespace AgroBase.Services
|
|||
var Dispositivo = Variaveis.DispositivosConectados.FirstOrDefault(x => x.Dispositivo == Mensagem.Dispositivo);
|
||||
if (Dispositivo == null) return false;
|
||||
|
||||
Dispositivo.EnviarDadosSerial(
|
||||
SerialService.BeginLine +
|
||||
Dispositivo.EnviarDadosMQTT(
|
||||
//SerialService.BeginLine +
|
||||
Mensagem.Id +
|
||||
SerialService.SplitMessage +
|
||||
Mensagem.ID_Modulo +
|
||||
|
|
@ -134,6 +144,8 @@ namespace AgroBase.Services
|
|||
SerialService.EndLine
|
||||
);
|
||||
|
||||
MarcarMensagemRecebida(Mensagem.Id);
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
|
@ -173,18 +185,10 @@ namespace AgroBase.Services
|
|||
|
||||
public static async Task tmrFila_Tick()
|
||||
{
|
||||
var timeoutCts = new CancellationTokenSource(5000); // Timeout de 5 segundos por tick
|
||||
try
|
||||
{
|
||||
await ExecutarTickAsync(timeoutCts.Token);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
Console.WriteLine("Timeout ao executar tmrFila_Tick.");
|
||||
}
|
||||
await ExecutarTickAsync();
|
||||
}
|
||||
|
||||
private static async Task ExecutarTickAsync(CancellationToken token)
|
||||
private static async Task ExecutarTickAsync()
|
||||
{
|
||||
RemoverDuplicatas();
|
||||
|
||||
|
|
@ -193,18 +197,6 @@ namespace AgroBase.Services
|
|||
var Filas = MensagensFila.Where(x => !x.Enviado).GroupBy(x => x.Dispositivo);
|
||||
foreach (var Fila in Filas)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
var Dispositivo = Variaveis.DispositivosConectados.FirstOrDefault(x => x.Dispositivo == Fila.Key);
|
||||
if (!Dispositivo?._Porta.IsOpen ?? true)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
MensagensFila.RemoveAll(x => x.Dispositivo == Fila.Key);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (FilaLiberada(Fila.Key))
|
||||
{
|
||||
MensagemFilaModel Mensagem = null;
|
||||
|
|
|
|||
|
|
@ -65,7 +65,7 @@ namespace AgroBase.Services
|
|||
{
|
||||
if (Iniciado)
|
||||
{
|
||||
SerialService.DispositivosMapeados.Add(new SerialService.DispositivoDetalhesModel()
|
||||
SerialService.DispositivosMapeados.Add(new DispositivoDetalhesModel()
|
||||
{
|
||||
Endereco = PortaGPS.PortName,
|
||||
Dispositivo = T_Code.Gps,
|
||||
|
|
@ -763,10 +763,7 @@ namespace AgroBase.Services
|
|||
{
|
||||
double Angulo = 0.0;
|
||||
|
||||
if (
|
||||
WT901CService.Iniciado ||
|
||||
(Variaveis.OperacaoEmAndamento.DispSen._Porta.IsOpen && Variaveis.OperacaoEmAndamento.DispSen.Dados.Sensores.Any(x => x.Componente == S_Code.sMAG && x.Inicializado))
|
||||
)
|
||||
if (WT901CService.Iniciado || (Variaveis.OperacaoEmAndamento.DispSen?.Dados?.Sensores?.Any(x => x.Componente == S_Code.sMAG && x.Inicializado) ?? false))
|
||||
{
|
||||
Angulo = Variaveis.OperacaoEmAndamento.Sensoriamento.AnguloCarroBussola;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
using AgroBase.Models;
|
||||
using System;
|
||||
using System.IO.Ports;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using static AgroBase.Models.Enums;
|
||||
using static MqttService;
|
||||
|
||||
namespace AgroBase.Services
|
||||
{
|
||||
|
|
@ -11,23 +12,17 @@ namespace AgroBase.Services
|
|||
T_Code Dispositivo { get; set; }
|
||||
string _Nome { get; set; }
|
||||
string _Descricao { get; set; }
|
||||
SerialPort _Porta { get; set; }
|
||||
DispositivoBaseModel Dados { get; set; }
|
||||
int TempoConectado { get; set; }
|
||||
GroupBox gpbItem { get; set; }
|
||||
|
||||
void AtualizarPortas();
|
||||
string PortaCOM();
|
||||
string StatusPorta();
|
||||
Task GerenciarMqttTopicos();
|
||||
Task EnviarDadosMQTT(string Protocolo);
|
||||
MqttTopicosModel GetMqttTopico(bool Envio);
|
||||
Control InstanciarDispositivo(int index);
|
||||
void AtualizaIndex(int index);
|
||||
void AcaoConexao();
|
||||
void AcaoDesconectar();
|
||||
void SalvarParametros(DispositivoBaseModel dados);
|
||||
void LimparBufferSerial(bool LimparConsole);
|
||||
void AdicionarMensagemFila(string Mod_ID, string Protocolo, bool _prioridade, bool _aguardaCallback);
|
||||
void EnviarDadosSerial(string Protocolo);
|
||||
void btnConectar_Click(object sender, EventArgs e);
|
||||
void EnviarProtocolosConfiguracao(bool Conectar = true);
|
||||
void CarregarParametrosModulos();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -199,7 +199,7 @@ namespace AgroBase.Services
|
|||
{
|
||||
if (Iniciado && !SerialService.DispositivosMapeados.Any(x => x.Dispositivo == T_Code.Knt))
|
||||
{
|
||||
SerialService.DispositivosMapeados.Add(new SerialService.DispositivoDetalhesModel()
|
||||
SerialService.DispositivosMapeados.Add(new DispositivoDetalhesModel()
|
||||
{
|
||||
Endereco = "USB",
|
||||
Dispositivo = T_Code.Knt,
|
||||
|
|
|
|||
|
|
@ -206,7 +206,7 @@ namespace AgroBase.Services
|
|||
|
||||
private static void DefinirDispositivo()
|
||||
{
|
||||
SerialService.DispositivosMapeados.Add(new SerialService.DispositivoDetalhesModel()
|
||||
SerialService.DispositivosMapeados.Add(new DispositivoDetalhesModel()
|
||||
{
|
||||
Endereco = _PortaLoRa.PortName,
|
||||
Dispositivo = T_Code.Lra,
|
||||
|
|
|
|||
|
|
@ -177,7 +177,7 @@ namespace AgroBase.Services
|
|||
var Leitura = DadosLeitura.FirstOrDefault(x => x.Endereco == Addr);
|
||||
if (Leitura != null)
|
||||
{
|
||||
SerialService.DispositivosMapeados.Add(new SerialService.DispositivoDetalhesModel()
|
||||
SerialService.DispositivosMapeados.Add(new DispositivoDetalhesModel()
|
||||
{
|
||||
Endereco = _ethernetService != null ? _ethernetService._ipAddress : "N/A",
|
||||
Dispositivo = T_Code.Mks,
|
||||
|
|
|
|||
|
|
@ -1,12 +1,10 @@
|
|||
using AgroBase.Forms;
|
||||
using AgroBase.Models;
|
||||
using AgroBase.Models;
|
||||
using AgroBase.Services;
|
||||
using MQTTnet;
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Client.Options;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
|
@ -17,34 +15,7 @@ public class MqttService
|
|||
private IMqttClientOptions _options;
|
||||
private AsyncTaskTimerModel tmrCheck;
|
||||
|
||||
public List<MqttTopicosModel> Topicos = new List<MqttTopicosModel>()
|
||||
{
|
||||
new MqttTopicosModel()
|
||||
{
|
||||
Topico = MapasVariaveisModel.TopicoCoordenadasGPS,
|
||||
Mensagens = new List<MqttTopicosMensagensModel>(),
|
||||
Inscrever = false
|
||||
},
|
||||
new MqttTopicosModel()
|
||||
{
|
||||
Topico = MapasVariaveisModel.TopicoSelecaoRuasMapa,
|
||||
Mensagens = new List < MqttTopicosMensagensModel>(),
|
||||
Inscrever = true,
|
||||
MensagensManter = 10
|
||||
},
|
||||
new MqttTopicosModel()
|
||||
{
|
||||
Topico = MapasVariaveisModel.TopicoTrajetoriaDinamica,
|
||||
Mensagens = new List<MqttTopicosMensagensModel>(),
|
||||
Inscrever = false
|
||||
},
|
||||
new MqttTopicosModel()
|
||||
{
|
||||
Topico = CamerasVaraiveisModel.TopicoEnvioBitmap,
|
||||
Mensagens = new List<MqttTopicosMensagensModel>(),
|
||||
Inscrever = false
|
||||
}
|
||||
};
|
||||
public List<MqttTopicosModel> Topicos;
|
||||
|
||||
public MqttService(string brokerAddress, int brokerPort)
|
||||
{
|
||||
|
|
@ -59,11 +30,6 @@ public class MqttService
|
|||
_client.UseConnectedHandler(async e =>
|
||||
{
|
||||
Console.WriteLine("Connected to MQTT Broker.");
|
||||
// Exemplo de inscrição em um tópico
|
||||
foreach (var topic in Topicos)
|
||||
{
|
||||
await SubscribeAsync(topic);
|
||||
}
|
||||
});
|
||||
|
||||
_client.UseDisconnectedHandler(e =>
|
||||
|
|
@ -73,19 +39,20 @@ public class MqttService
|
|||
|
||||
_client.UseApplicationMessageReceivedHandler(e =>
|
||||
{
|
||||
string message = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
|
||||
string message = Encoding.UTF8.GetString((e.ApplicationMessage.Payload == null) ? new byte[] { } : e.ApplicationMessage.Payload);
|
||||
//Console.WriteLine($"Message received on topic {e.ApplicationMessage.Topic}");
|
||||
// Aqui você pode adicionar o código para lidar com a mensagem recebida
|
||||
|
||||
var topico = Topicos.FirstOrDefault(x => x.Topico == e.ApplicationMessage.Topic);
|
||||
if (topico != null)
|
||||
{
|
||||
topico.Mensagens.Add(new MqttTopicosMensagensModel()
|
||||
var Mensagem = new MqttTopicosMensagensModel()
|
||||
{
|
||||
Momento = DateTime.Now,
|
||||
Cliente = e.ClientId,
|
||||
Mensagem = message
|
||||
});
|
||||
};
|
||||
topico.Mensagens.Add(Mensagem);
|
||||
|
||||
// Limitar o número de mensagens mantidas, removendo as mais antigas se necessário
|
||||
while (topico.Mensagens.Count > topico.MensagensManter)
|
||||
|
|
@ -93,25 +60,22 @@ public class MqttService
|
|||
topico.Mensagens.RemoveAt(0); // Remove a mensagem mais antiga (index 0)
|
||||
}
|
||||
|
||||
if (topico.Topico == MapasVariaveisModel.TopicoSelecaoRuasMapa)
|
||||
if (topico.Callback != null)
|
||||
{
|
||||
Variaveis.OperacaoEmAndamento.OpMapaGPS.AtualizarRuasSelecionadas();
|
||||
}
|
||||
else if (topico.Topico == CamerasVaraiveisModel.TopicoRecebimentoBitmap && message != "OK")
|
||||
{
|
||||
try
|
||||
{
|
||||
Bitmap bitmap = Variaveis.OperacaoEmAndamento.CameraCaminhoKinect.ExtraiImagemDaMensagem(message);
|
||||
Variaveis.OperacaoEmAndamento.CameraCaminhoKinect.AtualizarBitmapTela(bitmap);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"Erro ao processar a mensagem MQTT: {ex.Message}");
|
||||
}
|
||||
Task.Run(async () => await FuncoesGlobais.SafeExecuteAsync(async () => await topico.Callback(Mensagem)));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Topicos = new List<MqttTopicosModel>();
|
||||
Task.Run(async () =>
|
||||
{
|
||||
await AdicionarNovoTopico(MapasVariaveisModel.TopicoCoordenadasGPS);
|
||||
await AdicionarNovoTopico(MapasVariaveisModel.TopicoSelecaoRuasMapa, true, 1, async (message) => { Variaveis.OperacaoEmAndamento.OpMapaGPS.AtualizarRuasSelecionadas(); });
|
||||
await AdicionarNovoTopico(MapasVariaveisModel.TopicoTrajetoriaDinamica);
|
||||
await AdicionarNovoTopico(CamerasVaraiveisModel.TopicoEnvioBitmap);
|
||||
});
|
||||
|
||||
tmrCheck = new AsyncTaskTimerModel("tmrCheck", tmrCheck_Tick, 1000);
|
||||
tmrCheck.Start();
|
||||
}
|
||||
|
|
@ -185,10 +149,6 @@ public class MqttService
|
|||
|
||||
public async Task SubscribeAsync(MqttTopicosModel topic)
|
||||
{
|
||||
if (!topic.Inscrever)
|
||||
{
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
if (!_client.IsConnected)
|
||||
|
|
@ -225,6 +185,45 @@ public class MqttService
|
|||
}
|
||||
}
|
||||
|
||||
public async Task<MqttTopicosModel> AdicionarNovoTopico(string topico, bool inscrever = false, int mensagensManter = 2, Func<MqttTopicosMensagensModel, Task> callback = null)
|
||||
{
|
||||
var _mqttTopico = new MqttTopicosModel()
|
||||
{
|
||||
Topico = topico,
|
||||
Mensagens = new List<MqttTopicosMensagensModel>(),
|
||||
Inscrever = inscrever,
|
||||
MensagensManter = mensagensManter,
|
||||
Callback = callback
|
||||
};
|
||||
if (!Topicos.Any(x => x.Topico == _mqttTopico.Topico))
|
||||
{
|
||||
Topicos.Add(_mqttTopico);
|
||||
}
|
||||
|
||||
if (_mqttTopico.Inscrever)
|
||||
{
|
||||
await SubscribeAsync(_mqttTopico);
|
||||
}
|
||||
|
||||
await LimparMensagensRetidas(_mqttTopico.Topico);
|
||||
|
||||
return _mqttTopico;
|
||||
}
|
||||
|
||||
public async Task LimparMensagensRetidas(string topico)
|
||||
{
|
||||
if (_client.IsConnected)
|
||||
{
|
||||
var mensagem = new MqttApplicationMessageBuilder()
|
||||
.WithTopic(topico)
|
||||
.WithPayload(string.Empty) // Mensagem vazia
|
||||
.WithRetainFlag(true) // Marca como retained
|
||||
.Build();
|
||||
|
||||
await _client.PublishAsync(mensagem);
|
||||
Console.WriteLine($"Mensagem retida limpa para o tópico: {topico}");
|
||||
}
|
||||
}
|
||||
|
||||
public class MqttTopicosModel
|
||||
{
|
||||
|
|
@ -232,6 +231,7 @@ public class MqttService
|
|||
public int MensagensManter { get; set; } = 30;
|
||||
public List<MqttTopicosMensagensModel> Mensagens { get; set; }
|
||||
public bool Inscrever { get; set; }
|
||||
public Func<MqttTopicosMensagensModel, Task> Callback { get; set; }
|
||||
}
|
||||
|
||||
public class MqttTopicosMensagensModel
|
||||
|
|
|
|||
|
|
@ -83,7 +83,7 @@ namespace AgroBase.Services
|
|||
{
|
||||
if (Iniciado)
|
||||
{
|
||||
SerialService.DispositivosMapeados.Add(new SerialService.DispositivoDetalhesModel()
|
||||
SerialService.DispositivosMapeados.Add(new DispositivoDetalhesModel()
|
||||
{
|
||||
Endereco = ModbusService._PortaModbus.PortName,
|
||||
Dispositivo = T_Code.Pzm,
|
||||
|
|
|
|||
|
|
@ -16,104 +16,20 @@ namespace AgroBase.Services
|
|||
{
|
||||
public static int InteraloVerificacao = 5000;
|
||||
|
||||
public static string BeginLine = "@";
|
||||
public static string BreakLine = "&";
|
||||
public static string EndLine = "$";
|
||||
public static string BeginSensor = "#";
|
||||
public static string SplitMessage = ";";
|
||||
public static string SplitParams = ",";
|
||||
public static readonly string BeginLine = "@";
|
||||
public static readonly string BreakLine = "&";
|
||||
public static readonly string EndLine = "$";
|
||||
public static readonly string BeginSensor = "#";
|
||||
public static readonly string SplitMessage = ";";
|
||||
public static readonly string SplitParams = ",";
|
||||
public static readonly string SplitConfig = "*";
|
||||
public static readonly string SplitSubParams = "~";
|
||||
public static List<T_Code> DispositivosMotores = new List<T_Code>() { T_Code.Mov, T_Code.Dir };
|
||||
public static List<T_Code> DispositivosConexaoInicial = new List<T_Code>() { T_Code.Mvd, T_Code.Atu, T_Code.Sen };
|
||||
public static List<T_Code> DispositivosProprios = new List<T_Code>() { T_Code.Atu, T_Code.Sen };
|
||||
public static List<T_Code> DispositivosModbus = new List<T_Code>() { T_Code.Pzm, T_Code.Wit, T_Code.A05 };
|
||||
public static List<T_Code> DispositivosMultiplos = new List<T_Code>() { T_Code.Bld, T_Code.Mks, T_Code.Mvd };
|
||||
|
||||
public class DispositivoDetalhesModel
|
||||
{
|
||||
public string Endereco { get; set; }
|
||||
public TipoConexao Tipo
|
||||
{
|
||||
get
|
||||
{
|
||||
if (Endereco.Contains("USB"))
|
||||
{
|
||||
return TipoConexao.USB;
|
||||
}
|
||||
else if (Endereco.Contains("COM"))
|
||||
{
|
||||
return TipoConexao.PortaCOM;
|
||||
}
|
||||
else if (Endereco.Contains("."))
|
||||
{
|
||||
return TipoConexao.Ethernet;
|
||||
}
|
||||
else
|
||||
{
|
||||
return TipoConexao.Desconhecido;
|
||||
}
|
||||
}
|
||||
}
|
||||
public T_Code Dispositivo { get; set; }
|
||||
public bool Erro { get; set; }
|
||||
public string Versao { get; set; }
|
||||
public string Mod_ID { get; set; }
|
||||
public bool Conectado
|
||||
{
|
||||
get
|
||||
{
|
||||
bool DispositivoConectado = false;
|
||||
|
||||
if (Dispositivo == T_Code.Gps)
|
||||
{
|
||||
DispositivoConectado = GPSService.Iniciado;
|
||||
}
|
||||
else if (Dispositivo == T_Code.Pzm)
|
||||
{
|
||||
DispositivoConectado = PZEMService.Iniciado;
|
||||
}
|
||||
else if (Dispositivo == T_Code.A05)
|
||||
{
|
||||
DispositivoConectado = UltrasonicA05Service.Iniciado;
|
||||
}
|
||||
else if (Dispositivo == T_Code.Lra)
|
||||
{
|
||||
DispositivoConectado = LoRaService.Iniciado;
|
||||
}
|
||||
else if (Dispositivo == T_Code.Wit)
|
||||
{
|
||||
DispositivoConectado = WT901CService.Iniciado;
|
||||
}
|
||||
else if (Dispositivo == T_Code.Knt)
|
||||
{
|
||||
DispositivoConectado = KinectService.Iniciado;
|
||||
}
|
||||
else if (Dispositivo == T_Code.Bld)
|
||||
{
|
||||
var Modulo = Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.FirstOrDefault(x => x.Modulo_ID == Mod_ID);
|
||||
DispositivoConectado = Modulo?.MovMotor?.BLD_Inicializado ?? false;
|
||||
}
|
||||
else if (Dispositivo == T_Code.Mks)
|
||||
{
|
||||
var Modulo = Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.FirstOrDefault(x => x.Modulo_ID == Mod_ID);
|
||||
DispositivoConectado = Modulo?.DirMotor?.MKS_Inicializado ?? false;
|
||||
}
|
||||
else
|
||||
{
|
||||
IDispositivosService dispositivoService = Variaveis.DispositivosConectados.FirstOrDefault(x => x.Dispositivo == Dispositivo && x._Porta.PortName == Endereco);
|
||||
if (dispositivoService != null)
|
||||
{
|
||||
return dispositivoService._Porta != null && dispositivoService._Porta.IsOpen && dispositivoService.Dados.GetStatusConexao();
|
||||
}
|
||||
else
|
||||
{
|
||||
DispositivoConectado = false;
|
||||
}
|
||||
}
|
||||
|
||||
return DispositivoConectado;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static List<DispositivoDetalhesModel> DispositivosMapeados = new List<DispositivoDetalhesModel>();
|
||||
private static Dictionary<string, int> TentativasPortas = new Dictionary<string, int>();
|
||||
private static bool VarreduraEmAndamento = false;
|
||||
|
|
@ -328,7 +244,7 @@ namespace AgroBase.Services
|
|||
|
||||
_Porta.Open();
|
||||
|
||||
if (!PortaDispositivoProprio && !DispositivosMapeados.Any(x => x.Dispositivo == T_Code.Atu))
|
||||
/*if (!PortaDispositivoProprio && !DispositivosMapeados.Any(x => x.Dispositivo == T_Code.Atu))
|
||||
{
|
||||
ProtocoloCheck = Variaveis.OperacaoEmAndamento.DispAtu.Dados.ProtocoloVerificacao(true);
|
||||
|
||||
|
|
@ -363,7 +279,7 @@ namespace AgroBase.Services
|
|||
{
|
||||
AtualizarConsole("Dispositivo SEN encontrado");
|
||||
}
|
||||
}
|
||||
}*/
|
||||
if (!PortaDispositivoProprio && !GPSService.Iniciado)
|
||||
{
|
||||
AtualizarConsole("Procurando dispositivo GPS");
|
||||
|
|
@ -551,24 +467,28 @@ namespace AgroBase.Services
|
|||
|
||||
public static void AtualizarDispositivos()
|
||||
{
|
||||
var Portas = SerialPort.GetPortNames().ToList();
|
||||
bool PrimeiraExecucao = !Variaveis.DispositivosConectados.Any();
|
||||
DispositivosConexaoInicial.ForEach(Dispositivo =>
|
||||
{
|
||||
IDispositivosService dispositivoService = Variaveis.DispositivosConectados.FirstOrDefault(x => x.Dispositivo == Dispositivo);
|
||||
|
||||
if (dispositivoService != null)
|
||||
if (dispositivoService == null)
|
||||
{
|
||||
dispositivoService.AtualizarPortas();
|
||||
|
||||
if (
|
||||
Portas.Contains(dispositivoService.PortaCOM()) &&
|
||||
(!dispositivoService._Porta.IsOpen || (dispositivoService._Porta.IsOpen && !dispositivoService.Dados.GetStatusConexao()))
|
||||
)
|
||||
{
|
||||
dispositivoService.btnConectar_Click(new object(), new EventArgs());
|
||||
}
|
||||
dispositivoService = DispositivosServiceFactory.CreateDispositivoService(
|
||||
Dispositivo,
|
||||
"Nome: " + Enum.GetName(typeof(T_Code), Dispositivo),
|
||||
"Descrição: " + string.Join(", ", DispositivosMapeados.Where(x => x.Dispositivo == Dispositivo).Select(x => x.Mod_ID).ToArray()),
|
||||
new SerialPort()
|
||||
);
|
||||
dispositivoService.CarregarParametrosModulos();
|
||||
Task.Run(async () => await dispositivoService.GerenciarMqttTopicos());
|
||||
Variaveis.DispositivosConectados.Add(dispositivoService);
|
||||
}
|
||||
});
|
||||
if (PrimeiraExecucao)
|
||||
{
|
||||
OperacaoModel.CarregarParametrosOperacaoPadrao(ModoOperacao.Manual);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<bool> TentarIdentificarDispositivo(SerialPort porta)
|
||||
|
|
@ -763,6 +683,15 @@ namespace AgroBase.Services
|
|||
{
|
||||
bool ethernetEncontrado = false;
|
||||
|
||||
foreach (T_Code disp in DispositivosProprios)
|
||||
{
|
||||
bool proprio = await ProcuraDispositivoProprio(disp);
|
||||
if (proprio)
|
||||
{
|
||||
ethernetEncontrado = true;
|
||||
}
|
||||
}
|
||||
|
||||
bool DispBld = await ProcuraDispositivoBLD();
|
||||
if (DispBld)
|
||||
{
|
||||
|
|
@ -781,6 +710,78 @@ namespace AgroBase.Services
|
|||
return false;
|
||||
}
|
||||
|
||||
private static async Task<bool> ProcuraDispositivoProprio(T_Code Disp)
|
||||
{
|
||||
if (!DispositivosMapeados.Any(x => x.Dispositivo == Disp))
|
||||
{
|
||||
var Modulo = Variaveis.DispositivosConectados.FirstOrDefault(x => x.Dispositivo == Disp);
|
||||
string ProtocoloCheck = Modulo.Dados.ProtocoloVerificacao(true);
|
||||
|
||||
AtualizarConsole($"Procurando dispositivo {Disp.ToString()}");
|
||||
|
||||
DateTime MomentoEnvio = DateTime.Now;
|
||||
await Modulo.EnviarDadosMQTT(ProtocoloCheck);
|
||||
|
||||
await Task.Delay(1000);
|
||||
|
||||
var topicoRx = Modulo.GetMqttTopico(false);
|
||||
|
||||
var Recebido = topicoRx.Mensagens.FirstOrDefault(x => x.Momento >= MomentoEnvio);
|
||||
|
||||
if (Recebido != null && Recebido.Mensagem.Length > 2)
|
||||
{
|
||||
T_Code Dispositivo = T_Code.Vzo;
|
||||
F_Code Verificacao = F_Code.Nda;
|
||||
string Versao = "0";
|
||||
|
||||
var Dados = Recebido.Mensagem.Split(SplitMessage[0]);
|
||||
|
||||
if (Dados.Length <= 1)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
string Mod_ID = Dados[0];
|
||||
|
||||
int.TryParse(Dados[1], out int check);
|
||||
|
||||
if (check == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
Verificacao = (F_Code)check;
|
||||
|
||||
if (Verificacao == F_Code.Msg)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
Dispositivo = (T_Code)(int.Parse(Dados[2]));
|
||||
|
||||
Versao = Dados[3];
|
||||
|
||||
if (Dispositivo != T_Code.Vzo && !DispositivosMapeados.Any(x => x.Dispositivo == Dispositivo && x.Mod_ID == Mod_ID))
|
||||
{
|
||||
DispositivosMapeados.Add(new DispositivoDetalhesModel()
|
||||
{
|
||||
Endereco = Modulo.Dados.GetIP(),
|
||||
Dispositivo = Dispositivo,
|
||||
Erro = Verificacao == F_Code.Err,
|
||||
Versao = Versao,
|
||||
Mod_ID = Mod_ID,
|
||||
});
|
||||
}
|
||||
|
||||
AtualizarConsole($"Dispositivo {Disp.ToString()} encontrado");
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static async Task<bool> ProcuraDispositivoBLD()
|
||||
{
|
||||
if (!BLD300RService.Iniciado || BLD300RService.DadosLeitura.Any(x => !x.Iniciado))
|
||||
|
|
|
|||
|
|
@ -57,7 +57,7 @@ namespace AgroBase.Services
|
|||
{
|
||||
if (Iniciado)
|
||||
{
|
||||
SerialService.DispositivosMapeados.Add(new SerialService.DispositivoDetalhesModel()
|
||||
SerialService.DispositivosMapeados.Add(new DispositivoDetalhesModel()
|
||||
{
|
||||
Endereco = ModbusService._PortaModbus.PortName,
|
||||
Dispositivo = T_Code.A05,
|
||||
|
|
|
|||
|
|
@ -98,7 +98,7 @@ namespace AgroBase.Services
|
|||
{
|
||||
if (Iniciado)
|
||||
{
|
||||
SerialService.DispositivosMapeados.Add(new SerialService.DispositivoDetalhesModel()
|
||||
SerialService.DispositivosMapeados.Add(new DispositivoDetalhesModel()
|
||||
{
|
||||
Endereco = ModbusService._PortaModbus.PortName,
|
||||
Dispositivo = T_Code.Wit,
|
||||
|
|
|
|||
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large
Load Diff
|
|
@ -8747,3 +8747,7 @@
|
|||
18/11/2024 16:58:18:060 - Endereço 4 (192.168.0.7): Conexão Ethernet não está definida ou não está conectada
|
||||
19/11/2024 08:34:53:402 - Endereço 105 (192.168.0.7): Dados recebidos de um endereço inválido: [111 105 18 18 18 18 111 105]
|
||||
19/11/2024 08:36:18:843 - Endereço 105 (192.168.0.7): Dados recebidos de um endereço inválido: [111 105]
|
||||
28/11/2024 12:37:16:749 - Endereço 7 (192.168.105.11): Conexão Ethernet não está definida ou não está conectada
|
||||
28/11/2024 12:37:16:789 - Endereço 6 (192.168.105.11): Conexão Ethernet não está definida ou não está conectada
|
||||
28/11/2024 12:37:16:802 - Endereço 8 (192.168.105.11): Conexão Ethernet não está definida ou não está conectada
|
||||
28/11/2024 12:54:39:677 - Endereço 32 (192.168.105.11): Dados recebidos de um endereço inválido: [251 32 130 255]
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
{"tmrRegistrador":null,"Modulo_ID":"Atu","RequisitarDados":false,"Conectado":false,"UltimoProtocoloRecebido":"9999-12-30T23:59:59.9999999","QuantidadeBicos":4,"DensidadeHerbicida":1.05,"AtuacaoNivelAlto":true,"BicosPulverizadores":[{"ID":"B01","Posicao":1,"Atuado":false,"Comandar":true,"Inicializado":false,"Testando":false,"Funcoes":[21],"StatusBico":false,"MediaNivelFluxo":0.0,"Atuacoes":0,"InicioAtuacao":"0001-01-01T00:00:00","TempoAtuado":0.0},{"ID":"B02","Posicao":2,"Atuado":false,"Comandar":true,"Inicializado":false,"Testando":false,"Funcoes":[21],"StatusBico":false,"MediaNivelFluxo":0.0,"Atuacoes":0,"InicioAtuacao":"0001-01-01T00:00:00","TempoAtuado":0.0},{"ID":"B03","Posicao":3,"Atuado":false,"Comandar":true,"Inicializado":false,"Testando":false,"Funcoes":[21],"StatusBico":false,"MediaNivelFluxo":0.0,"Atuacoes":0,"InicioAtuacao":"0001-01-01T00:00:00","TempoAtuado":0.0},{"ID":"B04","Posicao":4,"Atuado":false,"Comandar":true,"Inicializado":false,"Testando":false,"Funcoes":[21],"StatusBico":false,"MediaNivelFluxo":0.0,"Atuacoes":0,"InicioAtuacao":"0001-01-01T00:00:00","TempoAtuado":0.0}],"BombaPressurizadora":{"ID":"BOMBA","BombaAtuada":false,"Ligado":false,"Comandar":true,"Inicializado":false,"Testando":false,"Funcoes":[14,35,36,37,5],"Pressao":0.0,"Potencia":0.0},"Sensores":[{"LogGrafico":[],"ID":"FLXLN","Prioridade":23,"Descricao":"Fluxo na linha principal","Componente":198,"Aferir":true,"DelayAmostragem":300,"Inicializado":false,"Testando":false,"Funcoes":[25],"Parametros":[],"UnidadeMedida":"mL/s","Leituras":[],"ValorMinimo":0.0,"ValorMaximo":0.0,"LimiteMaximo":0.0,"LimiteMinimo":0.0},{"LogGrafico":[],"ID":"MASRS","Prioridade":3,"Descricao":"Massa do reservatório de herbicida","Componente":532,"Aferir":true,"DelayAmostragem":1000,"Inicializado":false,"Testando":false,"Funcoes":[22,23],"Parametros":[],"UnidadeMedida":"Kg","Leituras":[],"ValorMinimo":0.0,"ValorMaximo":0.0,"LimiteMaximo":50.0,"LimiteMinimo":5.0},{"LogGrafico":[],"ID":"PRSLN","Prioridade":3,"Descricao":"Pressão na linha principal","Componente":333,"Aferir":true,"DelayAmostragem":1000,"Inicializado":false,"Testando":false,"Funcoes":[24],"Parametros":[["Vmin","000.00"],["Vmax","004.50"],["Pmax","174.04"]],"UnidadeMedida":"psi","Leituras":[],"ValorMinimo":0.0,"ValorMaximo":0.0,"LimiteMaximo":120.0,"LimiteMinimo":60.0}],"ScriptDeteccaoErvas":"weed_detector-1_0.py","_MassaRef":0.8,"_MassaLeituraRef":40876.37,"_MassaLeituraExtra":1895800.0,"_MassaLeitura":1895800.0,"MassaReservatorio":0.0,"VolumeReservatorio":0.0,"PercentualReservatorio":0.0,"VolumeVazaoAferido":0.0,"_FluxoMlRef":102.0,"_FluxoPulsoRef":80.0,"_LeituraPulsos":0,"_LeituraPeriodo":0,"VazaoFluxoMLpS":0.0,"VolumeVazaoML":0.0,"InicioAtuacao":"0001-01-01T00:00:00","TempoAtuado":0.0,"_PressaoVmin":0.0,"_PressaoVmax":4.5,"_PressaoMax":174.045,"_LeituraPressao":0.0,"PressaoLinha":0.0,"PressaoLinhaCalc":0.0}
|
||||
{"tmrRegistrador":{"State":2,"IsRunning":false,"IsStopped":true,"IsCreated":false,"Interval":2000,"StackTrace":"AtuadorModel.IniciarRegistrador","Id":"tmrRegistrador_Atu","TimeTick":"00:00:00"},"Modulo_ID":"Atu","IP":"192.168.99.113","RequisitarDados":true,"Conectado":true,"UltimoProtocoloRecebido":"9999-12-30T23:59:59.9999999","QuantidadeBicos":4,"DensidadeHerbicida":1.05,"AtuacaoNivelAlto":true,"BicosPulverizadores":[{"ID":"B01","Posicao":1,"Componente":422,"AtuacaoNivelAlto":false,"Atuado":false,"Comandar":true,"Testando":false,"Funcoes":[21],"StatusBico":false,"MediaNivelFluxo":0.0,"Leitura":{"ID":"B01","Iniciado":true,"Leitura":0},"Inicializado":true,"Atuacoes":0,"InicioAtuacao":"0001-01-01T00:00:00","TempoAtuado":0.0},{"ID":"B02","Posicao":2,"Componente":422,"AtuacaoNivelAlto":false,"Atuado":false,"Comandar":true,"Testando":false,"Funcoes":[21],"StatusBico":false,"MediaNivelFluxo":0.0,"Leitura":{"ID":"B02","Iniciado":true,"Leitura":0},"Inicializado":true,"Atuacoes":0,"InicioAtuacao":"0001-01-01T00:00:00","TempoAtuado":0.0},{"ID":"B03","Posicao":3,"Componente":422,"AtuacaoNivelAlto":false,"Atuado":false,"Comandar":true,"Testando":false,"Funcoes":[21],"StatusBico":false,"MediaNivelFluxo":0.0,"Leitura":{"ID":"B03","Iniciado":true,"Leitura":0},"Inicializado":true,"Atuacoes":0,"InicioAtuacao":"0001-01-01T00:00:00","TempoAtuado":0.0},{"ID":"B04","Posicao":4,"Componente":422,"AtuacaoNivelAlto":false,"Atuado":false,"Comandar":true,"Testando":false,"Funcoes":[21],"StatusBico":false,"MediaNivelFluxo":0.0,"Leitura":{"ID":"B04","Iniciado":true,"Leitura":0},"Inicializado":true,"Atuacoes":0,"InicioAtuacao":"0001-01-01T00:00:00","TempoAtuado":0.0}],"BombasPressurizadoras":[],"Sensores":[{"LogGrafico":[],"ID":"FLXLN","Prioridade":23,"Descricao":"Fluxo na linha principal","Componente":198,"Aferir":true,"DelayAmostragem":300,"Leitura":{"ID":"FLXLN","Iniciado":true,"Pulsos":0,"Periodo":0},"Inicializado":true,"Testando":false,"Funcoes":[25],"Parametros":[],"UnidadeMedida":"mL/s","LimiteMaximo":0.0,"LimiteMinimo":0.0},{"LogGrafico":[],"ID":"MASRS","Prioridade":3,"Descricao":"Massa do reservatório de herbicida","Componente":532,"Aferir":true,"DelayAmostragem":1000,"Leitura":{"ID":"MASRS","Iniciado":true,"Leitura":0},"Inicializado":true,"Testando":false,"Funcoes":[22,23],"Parametros":[],"UnidadeMedida":"Kg","LimiteMaximo":50.0,"LimiteMinimo":5.0},{"LogGrafico":[],"ID":"PRSLN","Prioridade":3,"Descricao":"Pressão na linha principal","Componente":333,"Aferir":true,"DelayAmostragem":1000,"Leitura":{"ID":"PRSLN","Iniciado":true,"Leitura":179,"Pressao":5.074508},"Inicializado":true,"Testando":false,"Funcoes":[24],"Parametros":[["Vmin","000.00"],["Vmax","004.50"],["Pmax","174.04"]],"UnidadeMedida":"psi","LimiteMaximo":120.0,"LimiteMinimo":60.0}],"BombaPressurizadora":null,"ScriptDeteccaoErvas":"weed_detector-1_0.py","DadosLeitura":{"Conectado":true,"Mod_ID":"Atu","Momento":"2024-11-29T17:26:36.3024846-03:00","BicosPulverizadores":[{"ID":"B01","Iniciado":true,"Leitura":0},{"ID":"B02","Iniciado":true,"Leitura":0},{"ID":"B03","Iniciado":true,"Leitura":0},{"ID":"B04","Iniciado":true,"Leitura":0}],"BombasPressurizadoras":[],"SensoresFluxo":[{"ID":"FLXLN","Iniciado":true,"Pulsos":0,"Periodo":0}],"SensoresMassa":[{"ID":"MASRS","Iniciado":true,"Leitura":0}],"SensoresPressao":[{"ID":"PRSLN","Iniciado":true,"Leitura":179,"Pressao":5.074508}]},"_MassaRef":0.8,"_MassaLeituraRef":40876.37,"_MassaLeituraExtra":1895800.0,"_MassaLeitura":1895800.0,"MassaReservatorio":0.0,"VolumeReservatorio":0.0,"PercentualReservatorio":0.0,"VolumeVazaoAferido":0.0,"_FluxoMlRef":102.0,"_FluxoPulsoRef":80.0,"_LeituraPulsos":0,"_LeituraPeriodo":0,"VazaoFluxoMLpS":0.0,"VolumeVazaoML":0.0,"InicioAtuacao":"0001-01-01T00:00:00","TempoAtuado":0.0,"_PressaoVmin":0.0,"_PressaoVmax":4.5,"_PressaoMax":174.045,"_LeituraPressao":0.0,"PressaoLinha":0.0,"PressaoLinhaCalc":0.0}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -1 +1 @@
|
|||
{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"Id":"1517","Name":"26_11_2024_12_20_32","Length":0.0,"Dist1":0.0,"Dist2":0.0},"geometry":{"id":null,"type":"LineString","coordinates":[[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0]]}}]}
|
||||
{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"Id":"1517","Name":"28_11_2024_15_35_23","Length":0.0,"Dist1":0.0,"Dist2":0.0},"geometry":{"id":null,"type":"LineString","coordinates":[[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0]]}}]}
|
||||
|
|
@ -1,60 +1,60 @@
|
|||
[
|
||||
{
|
||||
"timestamp": 1730295218.2382877,
|
||||
"timestamp": 1732895725.747677,
|
||||
"x_max": 640.0,
|
||||
"y_max": 480.0,
|
||||
"objetos": []
|
||||
},
|
||||
{
|
||||
"timestamp": 1730295218.269745,
|
||||
"timestamp": 1732895725.784762,
|
||||
"x_max": 640.0,
|
||||
"y_max": 480.0,
|
||||
"objetos": []
|
||||
},
|
||||
{
|
||||
"timestamp": 1730295218.2992513,
|
||||
"timestamp": 1732895725.816886,
|
||||
"x_max": 640.0,
|
||||
"y_max": 480.0,
|
||||
"objetos": []
|
||||
},
|
||||
{
|
||||
"timestamp": 1730295218.3407083,
|
||||
"timestamp": 1732895725.8538463,
|
||||
"x_max": 640.0,
|
||||
"y_max": 480.0,
|
||||
"objetos": []
|
||||
},
|
||||
{
|
||||
"timestamp": 1730295218.3711867,
|
||||
"timestamp": 1732895725.886399,
|
||||
"x_max": 640.0,
|
||||
"y_max": 480.0,
|
||||
"objetos": []
|
||||
},
|
||||
{
|
||||
"timestamp": 1730295218.40322,
|
||||
"timestamp": 1732895725.9184465,
|
||||
"x_max": 640.0,
|
||||
"y_max": 480.0,
|
||||
"objetos": []
|
||||
},
|
||||
{
|
||||
"timestamp": 1730295218.434695,
|
||||
"timestamp": 1732895725.9584076,
|
||||
"x_max": 640.0,
|
||||
"y_max": 480.0,
|
||||
"objetos": []
|
||||
},
|
||||
{
|
||||
"timestamp": 1730295218.4676962,
|
||||
"timestamp": 1732895726.024402,
|
||||
"x_max": 640.0,
|
||||
"y_max": 480.0,
|
||||
"objetos": []
|
||||
},
|
||||
{
|
||||
"timestamp": 1730295218.4993818,
|
||||
"timestamp": 1732895726.0578566,
|
||||
"x_max": 640.0,
|
||||
"y_max": 480.0,
|
||||
"objetos": []
|
||||
},
|
||||
{
|
||||
"timestamp": 1730295218.535353,
|
||||
"timestamp": 1732895726.0988536,
|
||||
"x_max": 640.0,
|
||||
"y_max": 480.0,
|
||||
"objetos": []
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@
|
|||
<meta name="viewport" content="width=device-width,
|
||||
initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
|
||||
<style>
|
||||
#map_fb7fae76b8912b825bfcbacefba64a99 {
|
||||
#map_dc6a670eee0d32ea276e81aef291c321 {
|
||||
position: relative;
|
||||
width: 100.0%;
|
||||
height: 100.0%;
|
||||
|
|
@ -39,14 +39,14 @@
|
|||
<body>
|
||||
|
||||
|
||||
<div class="folium-map" id="map_fb7fae76b8912b825bfcbacefba64a99" ></div>
|
||||
<div class="folium-map" id="map_dc6a670eee0d32ea276e81aef291c321" ></div>
|
||||
|
||||
</body>
|
||||
<script>
|
||||
|
||||
|
||||
var map_fb7fae76b8912b825bfcbacefba64a99 = L.map(
|
||||
"map_fb7fae76b8912b825bfcbacefba64a99",
|
||||
var map_dc6a670eee0d32ea276e81aef291c321 = L.map(
|
||||
"map_dc6a670eee0d32ea276e81aef291c321",
|
||||
{
|
||||
center: [0.0, 0.0],
|
||||
crs: L.CRS.EPSG3857,
|
||||
|
|
@ -60,13 +60,13 @@
|
|||
|
||||
|
||||
|
||||
var tile_layer_044fd806725958f2ceba8a29674a1581 = L.tileLayer(
|
||||
var tile_layer_30270c49899730f99704b9b12149c283 = L.tileLayer(
|
||||
"https://tile.openstreetmap.org/{z}/{x}/{y}.png",
|
||||
{"attribution": "\u0026copy; \u003ca href=\"https://www.openstreetmap.org/copyright\"\u003eOpenStreetMap\u003c/a\u003e contributors", "detectRetina": false, "maxNativeZoom": 19, "maxZoom": 19, "minZoom": 0, "noWrap": false, "opacity": 1, "subdomains": "abc", "tms": false}
|
||||
);
|
||||
|
||||
|
||||
tile_layer_044fd806725958f2ceba8a29674a1581.addTo(map_fb7fae76b8912b825bfcbacefba64a99);
|
||||
tile_layer_30270c49899730f99704b9b12149c283.addTo(map_dc6a670eee0d32ea276e81aef291c321);
|
||||
|
||||
</script>
|
||||
|
||||
|
|
@ -87,7 +87,7 @@
|
|||
}
|
||||
trajeto_json_add({"features": []});
|
||||
|
||||
trajeto_json.addTo(map_fb7fae76b8912b825bfcbacefba64a99);
|
||||
trajeto_json.addTo(map_dc6a670eee0d32ea276e81aef291c321);
|
||||
|
||||
function adicionarGeometria(novaGeometria) {
|
||||
trajeto_json.addData(novaGeometria);
|
||||
|
|
@ -145,7 +145,7 @@
|
|||
|
||||
var marcadorDinamico = L.marker([0, 0], {
|
||||
icon: customIcon
|
||||
}).addTo(map_fb7fae76b8912b825bfcbacefba64a99);
|
||||
}).addTo(map_dc6a670eee0d32ea276e81aef291c321);
|
||||
|
||||
// Conectar ao broker MQTT
|
||||
const client = mqtt.connect('ws://localhost:9001'); // Use wss para conexão segura
|
||||
|
|
@ -183,7 +183,7 @@
|
|||
marcadorDinamico.setRotationAngle(angulo);
|
||||
|
||||
adicionarCoordenada("Tj", [novaLongitude, novaLatitude]);
|
||||
map_fb7fae76b8912b825bfcbacefba64a99.setView(novaPosicao, map_fb7fae76b8912b825bfcbacefba64a99.getZoom());
|
||||
map_dc6a670eee0d32ea276e81aef291c321.setView(novaPosicao, map_dc6a670eee0d32ea276e81aef291c321.getZoom());
|
||||
});
|
||||
|
||||
function calcularOrientacao(P1latitude, P1longitude, P2latitude, P2longitude) {
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@
|
|||
<meta name="viewport" content="width=device-width,
|
||||
initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
|
||||
<style>
|
||||
#map_3a6ee7bba36940e9d499b3e1146ba342 {
|
||||
#map_53ce8720218d52238cdd29ed0f14d1d7 {
|
||||
position: relative;
|
||||
width: 100.0%;
|
||||
height: 100.0%;
|
||||
|
|
@ -39,14 +39,14 @@
|
|||
<body>
|
||||
|
||||
|
||||
<div class="folium-map" id="map_3a6ee7bba36940e9d499b3e1146ba342" ></div>
|
||||
<div class="folium-map" id="map_53ce8720218d52238cdd29ed0f14d1d7" ></div>
|
||||
|
||||
</body>
|
||||
<script>
|
||||
|
||||
|
||||
var map_3a6ee7bba36940e9d499b3e1146ba342 = L.map(
|
||||
"map_3a6ee7bba36940e9d499b3e1146ba342",
|
||||
var map_53ce8720218d52238cdd29ed0f14d1d7 = L.map(
|
||||
"map_53ce8720218d52238cdd29ed0f14d1d7",
|
||||
{
|
||||
center: [0.0, 0.0],
|
||||
crs: L.CRS.EPSG3857,
|
||||
|
|
@ -60,13 +60,13 @@
|
|||
|
||||
|
||||
|
||||
var tile_layer_271f980a40f4791484e27c8be9426593 = L.tileLayer(
|
||||
var tile_layer_3df9392fccfe2147fc64ffe6284be957 = L.tileLayer(
|
||||
"https://tile.openstreetmap.org/{z}/{x}/{y}.png",
|
||||
{"attribution": "\u0026copy; \u003ca href=\"https://www.openstreetmap.org/copyright\"\u003eOpenStreetMap\u003c/a\u003e contributors", "detectRetina": false, "maxNativeZoom": 19, "maxZoom": 19, "minZoom": 0, "noWrap": false, "opacity": 1, "subdomains": "abc", "tms": false}
|
||||
);
|
||||
|
||||
|
||||
tile_layer_271f980a40f4791484e27c8be9426593.addTo(map_3a6ee7bba36940e9d499b3e1146ba342);
|
||||
tile_layer_3df9392fccfe2147fc64ffe6284be957.addTo(map_53ce8720218d52238cdd29ed0f14d1d7);
|
||||
|
||||
|
||||
|
||||
|
|
@ -82,7 +82,7 @@
|
|||
}*/
|
||||
});
|
||||
}
|
||||
function geo_json_38566299a76c70c481ab3e83d466df2d_onEachFeature(feature, layer) {
|
||||
function geo_json_7d887aeb2bc37f011af812f038ebb19a_onEachFeature(feature, layer) {
|
||||
layer.on({
|
||||
|
||||
click: function(e) {
|
||||
|
|
@ -118,20 +118,20 @@
|
|||
}*/
|
||||
});
|
||||
};
|
||||
var geo_json_38566299a76c70c481ab3e83d466df2d = L.geoJson(null, {
|
||||
onEachFeature: geo_json_38566299a76c70c481ab3e83d466df2d_onEachFeature,
|
||||
var geo_json_7d887aeb2bc37f011af812f038ebb19a = L.geoJson(null, {
|
||||
onEachFeature: geo_json_7d887aeb2bc37f011af812f038ebb19a_onEachFeature,
|
||||
|
||||
});
|
||||
|
||||
function geo_json_38566299a76c70c481ab3e83d466df2d_add (data) {
|
||||
geo_json_38566299a76c70c481ab3e83d466df2d
|
||||
function geo_json_7d887aeb2bc37f011af812f038ebb19a_add (data) {
|
||||
geo_json_7d887aeb2bc37f011af812f038ebb19a
|
||||
.addData(data);
|
||||
}
|
||||
geo_json_38566299a76c70c481ab3e83d466df2d_add({"features": [{"geometry": {"coordinates": [[0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0]], "id": null, "type": "LineString"}, "id": 0, "properties": {"Dist1": 0.0, "Dist2": 0.0, "Id": "1517", "Length": 0.0, "Name": "26_11_2024_12_20_32"}, "type": "Feature"}], "type": "FeatureCollection"});
|
||||
geo_json_7d887aeb2bc37f011af812f038ebb19a_add({"features": [{"geometry": {"coordinates": [[0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0]], "id": null, "type": "LineString"}, "id": 0, "properties": {"Dist1": 0.0, "Dist2": 0.0, "Id": "1517", "Length": 0.0, "Name": "28_11_2024_15_35_23"}, "type": "Feature"}], "type": "FeatureCollection"});
|
||||
|
||||
|
||||
|
||||
geo_json_38566299a76c70c481ab3e83d466df2d.addTo(map_3a6ee7bba36940e9d499b3e1146ba342);
|
||||
geo_json_7d887aeb2bc37f011af812f038ebb19a.addTo(map_53ce8720218d52238cdd29ed0f14d1d7);
|
||||
|
||||
</script>
|
||||
|
||||
|
|
@ -152,7 +152,7 @@
|
|||
}
|
||||
trajeto_json_add({"features": []});
|
||||
|
||||
trajeto_json.addTo(map_3a6ee7bba36940e9d499b3e1146ba342);
|
||||
trajeto_json.addTo(map_53ce8720218d52238cdd29ed0f14d1d7);
|
||||
|
||||
function adicionarGeometria(novaGeometria) {
|
||||
trajeto_json.addData(novaGeometria);
|
||||
|
|
@ -210,7 +210,7 @@
|
|||
}
|
||||
trajeto_dinamico_json_add({"features": []});
|
||||
|
||||
trajeto_dinamico_json.addTo(map_3a6ee7bba36940e9d499b3e1146ba342);
|
||||
trajeto_dinamico_json.addTo(map_53ce8720218d52238cdd29ed0f14d1d7);
|
||||
|
||||
function adicionarGeometriaDinamica(novaGeometria) {
|
||||
trajeto_dinamico_json.addData(novaGeometria);
|
||||
|
|
@ -263,9 +263,9 @@
|
|||
|
||||
var marcadorEquipamento = L.marker([0, 0], {
|
||||
icon: customIcon
|
||||
}).addTo(map_3a6ee7bba36940e9d499b3e1146ba342);
|
||||
}).addTo(map_53ce8720218d52238cdd29ed0f14d1d7);
|
||||
|
||||
var marcadorBase = L.marker([0, 0], {}).addTo(map_3a6ee7bba36940e9d499b3e1146ba342);
|
||||
var marcadorBase = L.marker([0, 0], {}).addTo(map_53ce8720218d52238cdd29ed0f14d1d7);
|
||||
var icon = L.AwesomeMarkers.icon(
|
||||
{"extraClasses": "fa-rotate-0", "icon": "info-sign", "iconColor": "white", "markerColor": "red", "prefix": "glyphicon"}
|
||||
);
|
||||
|
|
@ -347,7 +347,7 @@
|
|||
}
|
||||
|
||||
if (foco) {
|
||||
map_3a6ee7bba36940e9d499b3e1146ba342.setView(novaPosicao, map_3a6ee7bba36940e9d499b3e1146ba342.getZoom());
|
||||
map_53ce8720218d52238cdd29ed0f14d1d7.setView(novaPosicao, map_53ce8720218d52238cdd29ed0f14d1d7.getZoom());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -364,7 +364,7 @@
|
|||
function atualizarSelecaoRuas(selecionadas) {
|
||||
selecionadas = JSON.parse(selecionadas);
|
||||
RuasSelecionadas = Array.isArray(selecionadas) ? [...selecionadas] : [];
|
||||
geo_json_38566299a76c70c481ab3e83d466df2d.eachLayer(function (layer) {
|
||||
geo_json_7d887aeb2bc37f011af812f038ebb19a.eachLayer(function (layer) {
|
||||
if (RuasSelecionadas.includes(parseInt(layer.feature.id))) {
|
||||
layer.setStyle({ color: 'blue' });
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
6f15a8df374baad6de514ad6cb80ffc96b3aa44597c56799d518e1cfd400d9aa
|
||||
c0dc644741f90cfbc6e195d6355a1e380c1e960cefff1b211bf55e3dbd91e24f
|
||||
|
|
|
|||
Binary file not shown.
Binary file not shown.
|
|
@ -0,0 +1,8 @@
|
|||
{
|
||||
// Use IntelliSense to learn about possible attributes.
|
||||
// Hover to view descriptions of existing attributes.
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,330 @@
|
|||
// Dispositivo: Atuador
|
||||
// Versão Firmware: 8
|
||||
// Ultima atualização: 29/11/2024
|
||||
// Atualização: Implementado MQTT
|
||||
|
||||
#include <ArduinoJson.h>
|
||||
#include "C:\ZendionInc\agrobot_base\Firmware\Modulos\MqttService.h"
|
||||
#include "C:\ZendionInc\agrobot_base\Firmware\Modulos\WifiService.h"
|
||||
#include "C:\ZendionInc\agrobot_base\Firmware\Modulos\EepromService.h"
|
||||
#include "C:\ZendionInc\agrobot_base\Firmware\Modulos\SerialService.h"
|
||||
#include "C:\ZendionInc\agrobot_base\Firmware\Modulos\Utils.h"
|
||||
#include "C:\ZendionInc\agrobot_base\Firmware\Modulos\Pinout.h"
|
||||
#include "C:\ZendionInc\agrobot_base\Firmware\Modulos\ReleModel.h"
|
||||
#include "C:\ZendionInc\agrobot_base\Firmware\Modulos\BombaPressurizadoraModel.h"
|
||||
#include "C:\ZendionInc\agrobot_base\Firmware\Modulos\SensorFluxoModel.h"
|
||||
#include "C:\ZendionInc\agrobot_base\Firmware\Modulos\SensorMassaModel.h"
|
||||
#include "C:\ZendionInc\agrobot_base\Firmware\Modulos\SensorPressaoModel.h"
|
||||
|
||||
|
||||
// Configurações do IP estático
|
||||
IPAddress local_IP(192, 168, 99, 113); // IP fixo para o ESP
|
||||
IPAddress gateway(192, 168, 99, 1); // Gateway padrão
|
||||
IPAddress subnet(255, 255, 255, 0); // Máscara de sub-rede
|
||||
IPAddress primaryDNS(8, 8, 8, 8); // Servidor DNS primário (opcional)
|
||||
|
||||
// Instancia o serviço MQTT
|
||||
MqttService mqttService;
|
||||
|
||||
#define D_Code Atu
|
||||
#define VERSION 8
|
||||
const String Mod_ID = "Atu";
|
||||
|
||||
#define _pinoLED RGB_BUILTIN
|
||||
|
||||
long _baudRate = 115200;
|
||||
|
||||
bool Conectado = false;
|
||||
bool Verificando = false;
|
||||
|
||||
int _TaxaAmostragem = 500;
|
||||
volatile bool RequisitarDados = false;
|
||||
|
||||
static double _PressaoAtual = 0.0;
|
||||
|
||||
|
||||
|
||||
std::vector<Rele*> listaBicos;
|
||||
std::vector<BombaPressurizadora*> listaBombas;
|
||||
std::vector<SensorFluxo*> listaSensoresFluxo;
|
||||
std::vector<SensorMassa*> listaSensoresMassa;
|
||||
std::vector<SensorPressao*> listaSensoresPressao;
|
||||
|
||||
|
||||
|
||||
void InicializarComunicacaoMQTT(bool RenovarConexao) {
|
||||
if (RenovarConexao) {
|
||||
mqttService.unsubscribe(TopicoRecepcao);
|
||||
delay(1000);
|
||||
}
|
||||
mqttService.setModID(Mod_ID);
|
||||
mqttService.InicializarComunicacaoMqtt();
|
||||
mqttService.setMessageCallback(ProcessarProtocolo);
|
||||
}
|
||||
|
||||
|
||||
void setup() {
|
||||
Serial.begin(_baudRate);
|
||||
|
||||
InicializarConexaoWifi(local_IP, gateway, subnet, primaryDNS);
|
||||
|
||||
if (!WifiIsConnected) {
|
||||
String newSSID = "WIFI-AGROBOTICS";
|
||||
String newPassword = "agro4321";
|
||||
|
||||
saveWiFiCredentials(newSSID.c_str(), newPassword.c_str());
|
||||
|
||||
connectToWiFi();
|
||||
|
||||
if (WifiIsConnected) {
|
||||
PrintTela("Conectado com sucesso");
|
||||
ESP.restart();
|
||||
}
|
||||
else {
|
||||
PrintTela("Erro ao se conectar ao wifi");
|
||||
while(true);
|
||||
}
|
||||
}
|
||||
|
||||
delay(100);
|
||||
|
||||
if (WifiIsConnected) {
|
||||
InicializarComunicacaoMQTT(false);
|
||||
}
|
||||
}
|
||||
|
||||
void loop() {
|
||||
if (!RequisitarDados) {
|
||||
enviarLogsPeriodicamente();
|
||||
}
|
||||
|
||||
mqttService.loop();
|
||||
|
||||
for (auto* bomba : listaBombas) {
|
||||
bomba->Loop();
|
||||
}
|
||||
for (auto* sensor : listaSensoresFluxo) {
|
||||
sensor->Loop();
|
||||
}
|
||||
|
||||
delay(1);
|
||||
}
|
||||
|
||||
|
||||
// Função para enviar logs do sensor periodicamente via MQTT
|
||||
unsigned long ultimoEnvioLogs = 0;
|
||||
const unsigned long intervaloEnvioLogs = 1000; // 1 segundo
|
||||
void enviarLogsPeriodicamente() {
|
||||
unsigned long tempoAtual = millis();
|
||||
// Verifica se o intervalo de 5 segundos já passou
|
||||
if (tempoAtual - ultimoEnvioLogs >= intervaloEnvioLogs) {
|
||||
ultimoEnvioLogs = tempoAtual; // Atualiza o tempo do último envio
|
||||
|
||||
enviarDadosSensores(); // Chama o método que já envia os dados do sensor via MQTT
|
||||
}
|
||||
}
|
||||
|
||||
void enviarDadosSensores() {
|
||||
if (Conectado && !Verificando) {
|
||||
PrintTela("Atualizando dados dos sensores...");
|
||||
|
||||
// Aferir dados dos sensores
|
||||
for (auto* bico : listaBicos) {
|
||||
bico->AtualizarLeitura();
|
||||
}
|
||||
|
||||
// Aferir dados dos sensores
|
||||
for (auto* sensor : listaSensoresFluxo) {
|
||||
sensor->AtualizarLeitura();
|
||||
}
|
||||
|
||||
// Aferir dados dos sensores
|
||||
for (auto* sensor : listaSensoresMassa) {
|
||||
sensor->RequisitarDados();
|
||||
}
|
||||
|
||||
// Aferir dados dos sensores
|
||||
for (auto* sensor : listaSensoresPressao) {
|
||||
sensor->RequisitarDados();
|
||||
}
|
||||
|
||||
String jsonString = MontarMensagemSensores() + String(EndLine);
|
||||
|
||||
mqttService.EnviarDados(Mod_ID, jsonString);
|
||||
}
|
||||
}
|
||||
|
||||
String MontarMensagemSensores() {
|
||||
// Criação de um objeto JSON dinâmico com tamanho adequado
|
||||
DynamicJsonDocument jsonDoc(2048);
|
||||
|
||||
// Adicionar campos gerais
|
||||
jsonDoc["Conectado"] = Conectado;
|
||||
jsonDoc["Mod_ID"] = Mod_ID;
|
||||
|
||||
// Array JSON para bicos pulverizadores
|
||||
JsonArray bicosArray = jsonDoc.createNestedArray("BicosPulverizadores");
|
||||
for (const auto* sensor : listaBicos) {
|
||||
JsonObject sensorData = bicosArray.createNestedObject();
|
||||
sensorData["Id"] = sensor->_ID;
|
||||
sensorData["Iniciado"] = sensor->Iniciado;
|
||||
sensorData["Leitura"] = sensor->_Status;
|
||||
}
|
||||
|
||||
// Array JSON para bombas pressurizadoras
|
||||
JsonArray bombasArray = jsonDoc.createNestedArray("BombasPressurizadoras");
|
||||
for (const auto* sensor : listaBombas) {
|
||||
JsonObject sensorData = bombasArray.createNestedObject();
|
||||
sensorData["Id"] = sensor->_ID;
|
||||
sensorData["Iniciado"] = sensor->Iniciado;
|
||||
sensorData["Estado"] = sensor->EstadoLeitura;
|
||||
sensorData["Potencia"] = sensor->PotenciaLeitura;
|
||||
sensorData["Pressao"] = sensor->_PressaoAtual;
|
||||
}
|
||||
|
||||
// Array JSON para sensores de fluxo
|
||||
JsonArray sensoresFluxoArray = jsonDoc.createNestedArray("SensoresFluxo");
|
||||
for (const auto* sensor : listaSensoresFluxo) {
|
||||
JsonObject sensorData = sensoresFluxoArray.createNestedObject();
|
||||
sensorData["Id"] = sensor->_ID;
|
||||
sensorData["Iniciado"] = sensor->Iniciado;
|
||||
sensorData["Pulsos"] = sensor->_PulsosLeitura;
|
||||
sensorData["Periodo"] = sensor->_PeriodoTotalLeitura;
|
||||
}
|
||||
|
||||
// Array JSON para sensores de massa
|
||||
JsonArray sensoresMassaArray = jsonDoc.createNestedArray("SensoresMassa");
|
||||
for (const auto* sensor : listaSensoresMassa) {
|
||||
JsonObject sensorData = sensoresMassaArray.createNestedObject();
|
||||
sensorData["Id"] = sensor->_ID;
|
||||
sensorData["Iniciado"] = sensor->Iniciado;
|
||||
sensorData["Leitura"] = sensor->leituraMassa;
|
||||
}
|
||||
|
||||
// Array JSON para sensores de pressao
|
||||
JsonArray sensoresPressaoArray = jsonDoc.createNestedArray("SensoresPressao");
|
||||
for (const auto* sensor : listaSensoresPressao) {
|
||||
JsonObject sensorData = sensoresPressaoArray.createNestedObject();
|
||||
sensorData["Id"] = sensor->_ID;
|
||||
sensorData["Iniciado"] = sensor->Iniciado;
|
||||
sensorData["Pressao"] = sensor->Pressao;
|
||||
sensorData["Leitura"] = sensor->leitura;
|
||||
}
|
||||
|
||||
// Serializa o JSON para uma string
|
||||
String jsonString;
|
||||
serializeJson(jsonDoc, jsonString);
|
||||
|
||||
int messageSize = jsonString.length();
|
||||
PrintTela("Tamanho da mensagem: ", false);
|
||||
PrintTela((String)messageSize);
|
||||
|
||||
return jsonString;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
void ProcessarProtocolo(ProtocoloSerial Mensagem) {
|
||||
switch (Mensagem.funcao) {
|
||||
case Chk:
|
||||
ProcessarChk(Mensagem);
|
||||
break;
|
||||
case Cfg:
|
||||
ProcessarCfg(Mensagem);
|
||||
break;
|
||||
case Cmd:
|
||||
ProcessarCmd(Mensagem);
|
||||
break;
|
||||
case Req:
|
||||
ProcessarReq(Mensagem);
|
||||
break;
|
||||
}
|
||||
|
||||
if (Mensagem.idMensagem > 0) {
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloMensagemRecebida(Mensagem.idMensagem));
|
||||
}
|
||||
}
|
||||
|
||||
void ProcessarChk(ProtocoloSerial Mensagem) {
|
||||
Verificando = true;
|
||||
mqttService.EnviarDados(Mod_ID, MontarProtocoloVerificacao(D_Code, VERSION, Conectado));
|
||||
delay(2000);
|
||||
Verificando = false;
|
||||
}
|
||||
|
||||
void ProcessarCfg(ProtocoloSerial Mensagem) {
|
||||
std::vector<String> Partes = SplitString(Mensagem.protocolo, SplitParams);
|
||||
T_Code Tipo = (T_Code)(Partes[0].toInt());
|
||||
if (Tipo == Mod) {
|
||||
bool Conectar = Partes[1] == "1";
|
||||
_TaxaAmostragem = Partes[2].toInt();
|
||||
RequisitarDados = Partes[3] == "1";
|
||||
|
||||
vTaskDelay(pdMS_TO_TICKS(100));
|
||||
Conectado = Conectar;
|
||||
Verificando = false;
|
||||
|
||||
enviarDadosSensores();
|
||||
}
|
||||
else {
|
||||
S_Code componente = (S_Code)Partes[1].toInt();
|
||||
String config = Partes[2];
|
||||
|
||||
switch (componente) {
|
||||
case sBIC: {
|
||||
Rele::InicializarLista(listaBicos, config, Mod_ID);
|
||||
break;
|
||||
}
|
||||
case sBMB: {
|
||||
BombaPressurizadora::InicializarLista(listaBombas, config, Mod_ID);
|
||||
break;
|
||||
}
|
||||
case sFLX: {
|
||||
SensorFluxo::InicializarLista(listaSensoresFluxo, config, Mod_ID);
|
||||
break;
|
||||
}
|
||||
case sMAS: {
|
||||
SensorMassa::InicializarLista(listaSensoresMassa, config, Mod_ID);
|
||||
break;
|
||||
}
|
||||
case sPRS: {
|
||||
SensorPressao::InicializarLista(listaSensoresPressao, config, Mod_ID);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ProcessarCmd(ProtocoloSerial Mensagem) {
|
||||
std::vector<String> Partes = SplitString(Mensagem.protocolo, SplitParams);
|
||||
String ID = Partes[0];
|
||||
S_Code componente = (S_Code)Partes[1].toInt();
|
||||
|
||||
switch (componente) {
|
||||
case sBIC: {
|
||||
for (auto* _rele : listaBicos) {
|
||||
if (_rele->_ID == ID) {
|
||||
Estado novoEstado = (Estado)Partes[2].toInt();
|
||||
_rele->AtualizarStatus(novoEstado);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case sBMB: {
|
||||
for (auto* _bomba : listaBombas) {
|
||||
if (_bomba->_ID == ID) {
|
||||
_bomba->_EstadoControle = (Estado)(Partes[2].toInt());
|
||||
_bomba->_PressaoSP = Partes[3].toDouble();
|
||||
_bomba->AlterarStatusBomba();
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ProcessarReq(ProtocoloSerial Mensagem) {
|
||||
enviarDadosSensores();
|
||||
}
|
||||
|
||||
|
|
@ -1,5 +1,25 @@
|
|||
{
|
||||
"files.associations": {
|
||||
"cstddef": "cpp"
|
||||
"cstddef": "cpp",
|
||||
"vector": "cpp",
|
||||
"bit": "cpp",
|
||||
"compare": "cpp",
|
||||
"concepts": "cpp",
|
||||
"cstdint": "cpp",
|
||||
"cstdio": "cpp",
|
||||
"cstdlib": "cpp",
|
||||
"cstring": "cpp",
|
||||
"cwchar": "cpp",
|
||||
"exception": "cpp",
|
||||
"initializer_list": "cpp",
|
||||
"limits": "cpp",
|
||||
"new": "cpp",
|
||||
"tuple": "cpp",
|
||||
"type_traits": "cpp",
|
||||
"utility": "cpp",
|
||||
"xmemory": "cpp",
|
||||
"xstddef": "cpp",
|
||||
"xtr1common": "cpp",
|
||||
"xutility": "cpp"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,199 @@
|
|||
#include "SerialService.h"
|
||||
#include "Pinout.h"
|
||||
#include "Utils.h"
|
||||
#include <PID_v1.h>
|
||||
|
||||
#ifndef BombaPressurizadoraModel
|
||||
#define BombaPressurizadoraModel
|
||||
|
||||
class BombaPressurizadora {
|
||||
public:
|
||||
|
||||
static void InicializarLista(std::vector<BombaPressurizadora*>& lista, const String& parametros, const String& Mod_ID);
|
||||
|
||||
BombaPressurizadora(String _modID, String _id) {
|
||||
Mod_ID = _modID;
|
||||
_ID = _id;
|
||||
}
|
||||
|
||||
String Mod_ID;
|
||||
String _ID;
|
||||
PinoModel _pinoEN;
|
||||
PinoModel _pinoCS;
|
||||
PinoModel _pinoINA;
|
||||
PinoModel _pinoINB;
|
||||
PinoModel _pinoPWM;
|
||||
int _canal = 0;
|
||||
|
||||
double _Kp = 3.0;
|
||||
double _Ki = 2.2;
|
||||
double _Kd = 0.5;
|
||||
const int histerese = -5;
|
||||
bool bombaDesligadaPorPressao = false;
|
||||
PID* _PID = nullptr;
|
||||
|
||||
int ZeroRampa = 0;
|
||||
int RampaMax = 1023;
|
||||
|
||||
bool Iniciado = false;
|
||||
|
||||
// Consumo
|
||||
Estado EstadoLeitura = Desligado;
|
||||
double PotenciaLeitura = 0;
|
||||
double _PressaoAtual = 0.0;
|
||||
|
||||
// Entrada de dados
|
||||
Estado _EstadoControle = Desligado;
|
||||
double _PressaoSP = 0;
|
||||
|
||||
void Inicializar() {
|
||||
if (Iniciado) {
|
||||
PrintTela(_ID + " ja inicializado");
|
||||
return;
|
||||
}
|
||||
|
||||
_EstadoControle = Desligado;
|
||||
_pinoEN.Conectar(_EstadoControle);
|
||||
AtualizarLeitura();
|
||||
_pinoCS.Conectar();
|
||||
_pinoINA.Conectar(false);
|
||||
_pinoINB.Conectar(true);
|
||||
if (_pinoPWM.Definido()) {
|
||||
ledcSetup(_canal, 1000, 10);
|
||||
ledcAttachPin(_pinoPWM.num, _canal);
|
||||
PotenciaLeitura = 0;
|
||||
_PressaoSP = 0;
|
||||
ledcWrite(_canal, _PressaoSP);
|
||||
}
|
||||
|
||||
_PID = new PID(&_PressaoAtual, &PotenciaLeitura, &_PressaoSP, _Kp, _Ki, _Kd, DIRECT);
|
||||
_PID->SetOutputLimits(ZeroRampa, RampaMax);
|
||||
_PID->SetMode(AUTOMATIC);
|
||||
|
||||
PrintTela(_ID + " Iniciado");
|
||||
|
||||
Iniciado = true;
|
||||
}
|
||||
|
||||
void Desligar() {
|
||||
if (!Iniciado) {
|
||||
PrintTela(_ID + " nao esta inicializado");
|
||||
return;
|
||||
}
|
||||
|
||||
delete _PID;
|
||||
_PID = nullptr;
|
||||
|
||||
// Redefinir as configurações para os valores iniciais
|
||||
_pinoPWM.Desconectar();
|
||||
_pinoEN.Desconectar();
|
||||
_pinoCS.Desconectar();
|
||||
_pinoINA.Desconectar();
|
||||
_pinoINB.Desconectar();
|
||||
_pinoPWM.Desconectar();
|
||||
|
||||
PrintTela(_ID + " Desligado");
|
||||
|
||||
Iniciado = false;
|
||||
}
|
||||
|
||||
void AtualizarLeitura() {
|
||||
EstadoLeitura = _pinoEN.get() == 1 ? Ligado : Desligado;
|
||||
}
|
||||
|
||||
void AlterarStatusBomba() {
|
||||
bool status = _EstadoControle == Ligado;
|
||||
|
||||
_pinoEN.set(status);
|
||||
|
||||
AtualizarLeitura();
|
||||
}
|
||||
|
||||
void Loop() {
|
||||
if (Iniciado) {
|
||||
// Supondo que PressaoAtual seja atualizado em AtualizarStatusSensor()
|
||||
if (_PressaoAtual >= (_PressaoSP + histerese)) {
|
||||
// Desliga a bomba se a pressão estiver acima do set point + histerese
|
||||
bombaDesligadaPorPressao = true;
|
||||
} else if (_PressaoAtual <= (_PressaoSP - histerese) && bombaDesligadaPorPressao) {
|
||||
// Permite que o PID atue novamente se a pressão cair abaixo do set point - histerese
|
||||
bombaDesligadaPorPressao = false;
|
||||
}
|
||||
|
||||
if (_EstadoControle == Desligado || bombaDesligadaPorPressao) {
|
||||
PotenciaLeitura = ZeroRampa;
|
||||
} else {
|
||||
_PID->Compute();
|
||||
// Ajusta PotenciaAtual com base no PID
|
||||
}
|
||||
|
||||
ledcWrite(_canal, PotenciaLeitura);
|
||||
|
||||
AtualizarLeitura();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
};
|
||||
|
||||
|
||||
// Função para inicializar as bombas pressurizadoras com IDs e pinos específicos
|
||||
void BombaPressurizadora::InicializarLista(std::vector<BombaPressurizadora*>& lista, const String& parametros, const String& Mod_ID) {
|
||||
// Verifica se há sensores já na lista
|
||||
if (!lista.empty()) {
|
||||
PrintTela("Limpando lista de bombas pressurizadoras existente...");
|
||||
|
||||
for (auto* sensor : lista) {
|
||||
sensor->Desligar(); // Desliga cada sensor antes de remover
|
||||
PrintTela("Bomba Pressurizadora " + sensor->_ID + " desligada.");
|
||||
delete sensor;
|
||||
}
|
||||
|
||||
lista.clear(); // Limpa a lista após desligar todos os itens
|
||||
}
|
||||
|
||||
if (parametros.length() > 0) {
|
||||
std::vector<String> _config = SplitString(parametros, SplitConfig); // Divide a configuração por vírgulas
|
||||
|
||||
for (const String& config : _config) {
|
||||
std::vector<String> partes = SplitString(config, SplitSubParams); // Divide cada configuração pelo '-'
|
||||
|
||||
if (partes.size() == 13) {
|
||||
String id = partes[0];
|
||||
bool conectar = partes[1] == "1";
|
||||
double pressaoSP = partes[2].toDouble();
|
||||
TiposBarramentos enB = (TiposBarramentos)partes[3].toInt();
|
||||
int pinoEN = partes[4].toInt();
|
||||
TiposBarramentos csB = (TiposBarramentos)partes[5].toInt();
|
||||
int pinoCS = partes[6].toInt();
|
||||
TiposBarramentos inaB = (TiposBarramentos)partes[7].toInt();
|
||||
int pinoINA = partes[8].toInt();
|
||||
TiposBarramentos inbB = (TiposBarramentos)partes[9].toInt();
|
||||
int pinoINB = partes[10].toInt();
|
||||
TiposBarramentos pwmB = (TiposBarramentos)partes[11].toInt();
|
||||
int pinoPWM = partes[12].toInt();
|
||||
|
||||
if (conectar) {
|
||||
BombaPressurizadora* bomba = new BombaPressurizadora(Mod_ID, id);
|
||||
bomba->_PressaoSP = pressaoSP;
|
||||
bomba->_pinoEN = PinoModel(pinoEN, enB, _OUTPUT);
|
||||
bomba->_pinoCS = PinoModel(pinoCS, csB, _INPUT, DIGITAL);
|
||||
bomba->_pinoINA = PinoModel(pinoINA, inaB, _OUTPUT);
|
||||
bomba->_pinoINB = PinoModel(pinoINB, inbB, _OUTPUT);
|
||||
bomba->_pinoPWM = PinoModel(pinoPWM, pwmB, _PWM);
|
||||
|
||||
bomba->Inicializar();
|
||||
lista.push_back(bomba);
|
||||
PrintTela("Bomba " + id + " inicializado com pressao SP" + String(pressaoSP));
|
||||
}
|
||||
} else {
|
||||
PrintTela("Configuração inválida para bomba pressurizadora: " + config);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
PrintTela("Configuração de bomba pressurizadora não encontrada.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#endif
|
||||
|
|
@ -0,0 +1,88 @@
|
|||
#include "SerialService.h"
|
||||
#include <EEPROM.h>
|
||||
|
||||
#ifndef EepromService
|
||||
#define EepromService
|
||||
|
||||
#define WIFI_SSID_ADDR 0 // Endereço inicial para o SSID na EEPROM
|
||||
#define WIFI_PASS_ADDR 32 // Endereço inicial para a senha na EEPROM
|
||||
#define MAX_SSID_LEN 32 // Tamanho máximo do SSID
|
||||
#define MAX_PASS_LEN 32 // Tamanho máximo da senha
|
||||
#define MOD_ID_ADDR 500
|
||||
|
||||
const int EEPROM_SIZE = 512;
|
||||
|
||||
|
||||
void saveWiFiCredentials(const char* ssid, const char* password) {
|
||||
EEPROM.begin(EEPROM_SIZE);
|
||||
|
||||
for (int i = 0; i < MAX_SSID_LEN; i++) {
|
||||
EEPROM.write(WIFI_SSID_ADDR + i, ssid[i]);
|
||||
}
|
||||
for (int i = 0; i < MAX_PASS_LEN; i++) {
|
||||
EEPROM.write(WIFI_PASS_ADDR + i, password[i]);
|
||||
}
|
||||
EEPROM.commit();
|
||||
PrintTela("Credenciais salvas.");
|
||||
}
|
||||
|
||||
void loadWiFiCredentials(char* ssid, char* password) {
|
||||
EEPROM.begin(EEPROM_SIZE);
|
||||
|
||||
for (int i = 0; i < MAX_SSID_LEN; i++) {
|
||||
ssid[i] = EEPROM.read(WIFI_SSID_ADDR + i);
|
||||
}
|
||||
ssid[MAX_SSID_LEN - 1] = '\0';
|
||||
|
||||
for (int i = 0; i < MAX_PASS_LEN; i++) {
|
||||
password[i] = EEPROM.read(WIFI_PASS_ADDR + i);
|
||||
}
|
||||
password[MAX_PASS_LEN - 1] = '\0';
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Função para salvar a configuração no EEPROM
|
||||
void salvarConfiguracaoEEPROM(const String& configuracao, int addr) {
|
||||
EEPROM.begin(EEPROM_SIZE); // Inicializa o EEPROM
|
||||
|
||||
for (int i = 0; i < configuracao.length(); i++) {
|
||||
EEPROM.write(addr + i, configuracao[i]);
|
||||
}
|
||||
EEPROM.write(addr + configuracao.length(), '\0'); // Adiciona terminador nulo
|
||||
EEPROM.commit();
|
||||
|
||||
PrintTela("Configuração salva no EEPROM: " + configuracao);
|
||||
}
|
||||
|
||||
// Função para carregar a configuração do EEPROM
|
||||
String carregarConfiguracaoEEPROM(int addr) {
|
||||
EEPROM.begin(EEPROM_SIZE);
|
||||
String configuracao;
|
||||
char ch;
|
||||
|
||||
for (int i = addr; (ch = EEPROM.read(i)) != '\0' && i < EEPROM_SIZE; i++) {
|
||||
configuracao += ch;
|
||||
}
|
||||
|
||||
PrintTela("Configuração carregada do EEPROM: " + configuracao);
|
||||
return configuracao;
|
||||
}
|
||||
|
||||
|
||||
|
||||
void limparEEPROM() {
|
||||
EEPROM.begin(EEPROM_SIZE); // Inicializa o EEPROM
|
||||
|
||||
// Limpa todos os bytes na EEPROM
|
||||
for (int i = 0; i < EEPROM_SIZE; i++) {
|
||||
EEPROM.write(i, 0); // Escreve 0 em cada posição
|
||||
}
|
||||
|
||||
EEPROM.commit(); // Salva as alterações
|
||||
EEPROM.end(); // Encerra a sessão de EEPROM
|
||||
|
||||
PrintTela("EEPROM limpa. Todas as configurações foram resetadas.");
|
||||
}
|
||||
|
||||
#endif
|
||||
|
|
@ -16,6 +16,9 @@ enum T_Code {
|
|||
Mbs = 110,
|
||||
Mks = 111,
|
||||
Cam = 112,
|
||||
Knt = 113,
|
||||
A05 = 114,
|
||||
Mod = 115,
|
||||
};
|
||||
|
||||
enum F_Code {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,148 @@
|
|||
#include "SerialService.h"
|
||||
#include <WiFi.h>
|
||||
#include <PubSubClient.h>
|
||||
|
||||
#ifndef MqttService_h
|
||||
#define MqttService_h
|
||||
|
||||
const String TopicoRecepcao = "disp/tx/";
|
||||
const String TopicoTransmissao = "disp/rx/";
|
||||
|
||||
class MqttService {
|
||||
private:
|
||||
const char* server = "192.168.99.105";
|
||||
int port = 1883;
|
||||
const char* user = "zendion";
|
||||
const char* password = "Z210203!";
|
||||
String mqtt_mod_id; // Alterado para String
|
||||
WiFiClient wifiClient;
|
||||
PubSubClient mqttClient;
|
||||
|
||||
// Ponteiros para funções de callback
|
||||
void (*messageCallback)(ProtocoloSerial) = nullptr;
|
||||
|
||||
public:
|
||||
bool MqttIsConnected = false;
|
||||
|
||||
MqttService() : mqttClient(wifiClient) {
|
||||
mqttClient.setServer(server, port);
|
||||
mqttClient.setBufferSize(1024);
|
||||
mqttClient.setCallback([this](char* topic, byte* payload, unsigned int length) {
|
||||
this->processMessage(topic, payload, length);
|
||||
});
|
||||
}
|
||||
|
||||
void setModID(const String& mqtt_id) {
|
||||
mqtt_mod_id = mqtt_id; // Atribui diretamente a String
|
||||
}
|
||||
|
||||
void setMessageCallback(void (*callback)(ProtocoloSerial)) {
|
||||
messageCallback = callback;
|
||||
}
|
||||
|
||||
bool InicializarComunicacaoMqtt() {
|
||||
connect();
|
||||
if (MqttIsConnected) {
|
||||
PrintTela("Tamanho máximo de mensagens: " + String(mqttClient.getBufferSize()));
|
||||
subscribe(TopicoRecepcao);
|
||||
}
|
||||
return MqttIsConnected;
|
||||
}
|
||||
|
||||
void connect() {
|
||||
while (!mqttClient.connected()) {
|
||||
PrintTela("Conectando ao broker MQTT...", false);
|
||||
//if (mqttClient.connect(mqtt_mod_id.c_str(), user, password)) {
|
||||
if (mqttClient.connect(mqtt_mod_id.c_str())) {
|
||||
PrintTela("Conectado ao broker MQTT!");
|
||||
MqttIsConnected = true;
|
||||
} else {
|
||||
PrintTela("Falha ao conectar, rc=", false);
|
||||
PrintTela((String)mqttClient.state());
|
||||
MqttIsConnected = false;
|
||||
delay(2000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void subscribe(String topico) {
|
||||
String fullTopic = topico + mqtt_mod_id; // Concatena o ID ao tópico base
|
||||
mqttClient.subscribe(fullTopic.c_str());
|
||||
PrintTela("Inscrito no tópico: ", false);
|
||||
PrintTela(fullTopic);
|
||||
}
|
||||
|
||||
void unsubscribe(String topico) {
|
||||
String fullTopic = topico + mqtt_mod_id; // Concatena o ID ao tópico base
|
||||
mqttClient.unsubscribe(fullTopic.c_str()); // Remove a inscrição de cada tópico
|
||||
PrintTela("Desinscrito do tópico: ", false);
|
||||
PrintTela(fullTopic);
|
||||
}
|
||||
|
||||
bool publish(String message) {
|
||||
String fullTopic = TopicoTransmissao + mqtt_mod_id; // Concatena o ID ao tópico base
|
||||
|
||||
// Verifica se está conectado ao broker antes de tentar publicar
|
||||
if (mqttClient.connected()) {
|
||||
bool success = mqttClient.publish(fullTopic.c_str(), message.c_str(), true); // Publica a mensagem
|
||||
if (success) {
|
||||
PrintTela("Mensagem enviada com sucesso para ", false);
|
||||
} else {
|
||||
PrintTela("Falha ao enviar mensagem para ", false);
|
||||
}
|
||||
PrintTela(fullTopic, false); // Imprime o tópico completo para verificação
|
||||
PrintTela(": ", false);
|
||||
PrintTela(message);
|
||||
|
||||
return success;
|
||||
} else {
|
||||
PrintTela("Erro: Conexão com o broker MQTT perdida. Tentando reconectar...");
|
||||
InicializarComunicacaoMqtt(); // Tenta reconectar
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void loop() {
|
||||
if (MqttIsConnected) {
|
||||
mqttClient.loop();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void EnviarDados(String Mod_ID, String Mensagem) {
|
||||
if (MqttIsConnected) {
|
||||
String ProtocoloEnvio = Mod_ID + SplitMessage + Mensagem;
|
||||
publish(ProtocoloEnvio);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Processa a mensagem recebida e aciona o callback correspondente
|
||||
void processMessage(char* topic, byte* payload, unsigned int length) {
|
||||
String topicStr(topic);
|
||||
String message;
|
||||
for (unsigned int i = 0; i < length; i++) {
|
||||
message += (char)payload[i];
|
||||
}
|
||||
PrintTela("Mensagem recebida no tópico ", false);
|
||||
PrintTela(topicStr, false);
|
||||
PrintTela(": ", false);
|
||||
PrintTela(message);
|
||||
|
||||
if (topicStr == TopicoRecepcao + mqtt_mod_id) {
|
||||
std::vector<String> Partes = SplitString(message, SplitMessage);
|
||||
if (Partes.size() == 4) {
|
||||
ProtocoloSerial objeto;
|
||||
objeto.idMensagem = Partes[0].toInt();
|
||||
objeto.Mod_ID = Partes[1];
|
||||
objeto.funcao = (F_Code)(Partes[2].toInt());
|
||||
objeto.protocolo = Partes[3];
|
||||
if (mqtt_mod_id == objeto.Mod_ID && messageCallback) {
|
||||
messageCallback(objeto);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
@ -88,24 +88,27 @@ class PinoModel {
|
|||
};
|
||||
|
||||
void iniciarMCP(T_Code Modulo, String Mod_ID, int sda, int scl, byte endereco, bool Mandatorio = false) {
|
||||
Serial.println("Iniciando MCP23X17...");
|
||||
PrintTela("Iniciando MCP23X17...");
|
||||
if (!mcpInicializado) {
|
||||
bool init = Wire.begin(sda, scl);
|
||||
String str = "SDA " + (String)sda + " SCL " + (String)scl + " Res " + init;
|
||||
Serial.print(str);
|
||||
PrintTela(str, false);
|
||||
|
||||
if (!mcp.begin_I2C(endereco, &Wire)) {
|
||||
mcpInicializado = false;
|
||||
Serial.println("Erro ao iniciar MCP23X17!");
|
||||
PrintTela("Erro ao iniciar MCP23X17!");
|
||||
if (Mandatorio) {
|
||||
Serial.println("Conexão obrigatória, tentando novamente em 5 segundos...");
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloErro(Modulo));
|
||||
PrintTela("Conexão obrigatória, tentando novamente em 5 segundos...");
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloErro(Modulo));
|
||||
delay(5000);
|
||||
iniciarMCP(Modulo, Mod_ID, sda, scl, endereco, Mandatorio);
|
||||
}
|
||||
else {
|
||||
PrintTela("MCP nao mandatorio, continuando o fluxo...");
|
||||
}
|
||||
}
|
||||
else {
|
||||
Serial.println("MCP23X17 iniciado com sucesso!");
|
||||
PrintTela("MCP23X17 iniciado com sucesso!");
|
||||
mcpInicializado = true;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,9 @@
|
|||
class Rele {
|
||||
public:
|
||||
|
||||
Rele(String _modID, String _id, int _taxaAmostragem = 2000) {
|
||||
static void InicializarLista(std::vector<Rele*>& lista, const String& parametros, const String& Mod_ID);
|
||||
|
||||
Rele(String _modID, String _id) {
|
||||
Mod_ID = _modID;
|
||||
_ID = _id;
|
||||
}
|
||||
|
|
@ -18,42 +20,48 @@ class Rele {
|
|||
PinoModel _pino;
|
||||
bool Iniciado = false;
|
||||
|
||||
bool AtuacaoNivelAlto = true;
|
||||
|
||||
Estado _Status = Desligado;
|
||||
|
||||
void Inicializar() {
|
||||
if (Iniciado) {
|
||||
//EnviarDadosSerial(_ID + " ja inicializado");
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
PrintTela(_ID + " ja inicializado");
|
||||
return;
|
||||
}
|
||||
|
||||
if (_pino.Definido()) {
|
||||
_pino.Conectar(false);
|
||||
_pino.Conectar(!AtuacaoNivelAlto);
|
||||
Iniciado = true;
|
||||
}
|
||||
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
PrintTela(_ID + " iniciado");
|
||||
}
|
||||
}
|
||||
|
||||
void Desligar() {
|
||||
if (!Iniciado) {
|
||||
//EnviarDadosSerial(_ID + " nao esta inicializado");
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
PrintTela(_ID + " nao esta inicializado");
|
||||
return;
|
||||
}
|
||||
|
||||
// Redefinir as configurações para os valores iniciais
|
||||
_pino.Desconectar();
|
||||
|
||||
//EnviarDadosSerial(_ID + " Desligado");
|
||||
PrintTela(_ID + " Desligado");
|
||||
|
||||
Iniciado = false;
|
||||
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
}
|
||||
|
||||
void AtualizarStatus(Estado novoEstado) {
|
||||
bool status = novoEstado == Ligado;
|
||||
if (!AtuacaoNivelAlto) {
|
||||
status = !status;
|
||||
}
|
||||
|
||||
PrintTela("Atualizando status do rele de ", false);
|
||||
PrintTela(String(_Status), false);
|
||||
PrintTela(" para ", false);
|
||||
PrintTela(String(novoEstado));
|
||||
_pino.set(status);
|
||||
_Status = (Estado)_pino.get();
|
||||
}
|
||||
|
|
@ -64,9 +72,52 @@ class Rele {
|
|||
|
||||
void RequisitarDados() {
|
||||
AtualizarLeitura();
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sRLE, _ID, MontarDadosProtocoloRele(Iniciado, _Status)));
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
// Função para inicializar os reles com IDs e pinos específicos
|
||||
void Rele::InicializarLista(std::vector<Rele*>& lista, const String& parametros, const String& Mod_ID) {
|
||||
// Verifica se há sensores já na lista
|
||||
if (!lista.empty()) {
|
||||
PrintTela("Limpando lista de reles existente...");
|
||||
|
||||
for (auto* sensor : lista) {
|
||||
sensor->Desligar(); // Desliga cada sensor antes de remover
|
||||
PrintTela("Rele " + sensor->_ID + " desligado.");
|
||||
delete sensor;
|
||||
}
|
||||
|
||||
lista.clear(); // Limpa a lista após desligar todos os itens
|
||||
}
|
||||
|
||||
if (parametros.length() > 0) {
|
||||
std::vector<String> _config = SplitString(parametros, SplitConfig); // Divide a configuração por vírgulas
|
||||
|
||||
for (const String& config : _config) {
|
||||
std::vector<String> partes = SplitString(config, SplitSubParams); // Divide cada configuração pelo '-'
|
||||
|
||||
if (partes.size() == 5) {
|
||||
String id = partes[0];
|
||||
bool conectar = partes[1] == "1";
|
||||
bool atuacaoAlto = partes[2] == "1";
|
||||
TiposBarramentos pinoB = (TiposBarramentos)partes[3].toInt();
|
||||
int pino = partes[4].toInt();
|
||||
|
||||
if (conectar) {
|
||||
Rele* sensor = new Rele(Mod_ID, id);
|
||||
sensor->_pino = PinoModel(pino, pinoB, _OUTPUT);
|
||||
sensor->Inicializar();
|
||||
lista.push_back(sensor);
|
||||
PrintTela("Rele " + id + " inicializado no pino " + String(pino));
|
||||
}
|
||||
} else {
|
||||
PrintTela("Configuração inválida para rele: " + config);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
PrintTela("Configuração de rele não encontrada.");
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
|
@ -9,6 +9,8 @@
|
|||
class SensorCorrente {
|
||||
public:
|
||||
|
||||
static void InicializarLista(std::vector<SensorCorrente*>& lista, const String& parametros, const String& Mod_ID);
|
||||
|
||||
SensorCorrente(String _modID, String _id) {
|
||||
Mod_ID = _modID;
|
||||
_ID = _id;
|
||||
|
|
@ -20,7 +22,6 @@ class SensorCorrente {
|
|||
// Definições
|
||||
String Mod_ID = "";
|
||||
String _ID;
|
||||
S_Code _componente = sCOR;
|
||||
byte _Endereco;
|
||||
double _A_Shunt;
|
||||
|
||||
|
|
@ -32,8 +33,7 @@ class SensorCorrente {
|
|||
|
||||
void Inicializar() {
|
||||
if (Iniciado) {
|
||||
//EnviarDadosSerial(_ID + " ja inicializado");
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
PrintTela(_ID + " ja inicializado");
|
||||
return;
|
||||
}
|
||||
if (_Endereco > 0x00) {
|
||||
|
|
@ -56,25 +56,22 @@ class SensorCorrente {
|
|||
}
|
||||
else {
|
||||
Iniciado = false;
|
||||
EnviarDadosSerial(Mod_ID, _ID + " nao iniciado, endereco " + _Endereco + " nao encontrado!");
|
||||
PrintTela(_ID + " nao iniciado, endereco " + _Endereco + " nao encontrado!");
|
||||
}
|
||||
}
|
||||
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
PrintTela(_ID + " iniciado");
|
||||
}
|
||||
|
||||
void Desligar() {
|
||||
if (!Iniciado) {
|
||||
//EnviarDadosSerial(_ID + " nao esta inicializado");
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
PrintTela(_ID + " nao esta inicializado");
|
||||
return;
|
||||
}
|
||||
|
||||
//EnviarDadosSerial(_ID + " Desligado");
|
||||
PrintTela(_ID + " Desligado");
|
||||
|
||||
Iniciado = false;
|
||||
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
}
|
||||
|
||||
void AferirCorrente() {
|
||||
|
|
@ -86,10 +83,52 @@ class SensorCorrente {
|
|||
|
||||
void RequisitarDados() {
|
||||
AferirCorrente();
|
||||
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCOR, _ID, MontarDadosProtocoloINA226(busVoltage, shuntVoltage, current, power)));
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
// Função para inicializar os sensores de corrente com IDs e pinos específicos
|
||||
void SensorCorrente::InicializarLista(std::vector<SensorCorrente*>& lista, const String& parametros, const String& Mod_ID) {
|
||||
// Verifica se há sensores já na lista
|
||||
if (!lista.empty()) {
|
||||
PrintTela("Limpando lista de sensores de corrente existente...");
|
||||
|
||||
for (auto* sensor : lista) {
|
||||
sensor->Desligar(); // Desliga cada sensor antes de remover
|
||||
PrintTela("Sensor de Corrente " + sensor->_ID + " desligado.");
|
||||
delete sensor;
|
||||
}
|
||||
|
||||
lista.clear(); // Limpa a lista após desligar todos os itens
|
||||
}
|
||||
|
||||
if (parametros.length() > 0) {
|
||||
std::vector<String> _config = SplitString(parametros, SplitConfig); // Divide a configuração por vírgulas
|
||||
|
||||
for (const String& config : _config) {
|
||||
std::vector<String> partes = SplitString(config, SplitSubParams); // Divide cada configuração pelo '-'
|
||||
|
||||
if (partes.size() >= 6) {
|
||||
String id = partes[0];
|
||||
bool conectar = partes[1] == "1";
|
||||
String _endereco = partes[4];
|
||||
int _a_max = partes[5].toDouble();
|
||||
|
||||
if (conectar) {
|
||||
SensorCorrente* sensor = new SensorCorrente(Mod_ID, id);
|
||||
sensor->_Endereco = stringToByte(_endereco);
|
||||
sensor->_A_Shunt = _a_max;
|
||||
sensor->Inicializar();
|
||||
lista.push_back(sensor);
|
||||
PrintTela("Sensor de corrente " + id + " inicializado no endereco " + _endereco);
|
||||
}
|
||||
} else {
|
||||
PrintTela("Configuração inválida para sensor de corrente: " + config);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
PrintTela("Configuração de sensor de corrente não encontrada.");
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
#include "SerialService.h"
|
||||
#include "Pinout.h"
|
||||
#include <Bounce2.h>
|
||||
|
||||
#ifndef SensorFluxoModel
|
||||
#define SensorFluxoModel
|
||||
|
|
@ -7,6 +8,8 @@
|
|||
class SensorFluxo {
|
||||
public:
|
||||
|
||||
static void InicializarLista(std::vector<SensorFluxo*>& lista, const String& parametros, const String& Mod_ID);
|
||||
|
||||
SensorFluxo(String _modID, String _id) {
|
||||
Mod_ID = _modID;
|
||||
_ID = _id;
|
||||
|
|
@ -17,127 +20,151 @@ class SensorFluxo {
|
|||
String _ID;
|
||||
S_Code _componente = sFLX;
|
||||
PinoModel _pino;
|
||||
int _TaxaAmostragem = 2000;
|
||||
int _delayAmostragem;
|
||||
int _prioridade;
|
||||
float _calibragem;
|
||||
|
||||
Bounce bouncer; // Gerenciador de debounce
|
||||
unsigned long tempoAnterior = 0;
|
||||
unsigned int _Pulsos = 0;
|
||||
unsigned long _PeriodoTotal = 0;
|
||||
unsigned long primeiroMillis = millis();
|
||||
|
||||
bool Iniciado = false;
|
||||
bool Checando = false;
|
||||
|
||||
// Consumo
|
||||
volatile int ultimaLeitura = 0;
|
||||
volatile unsigned int tempoAnterior = 0;
|
||||
volatile int _Pulsos = 0;
|
||||
volatile long _PeriodoTotal = 0;
|
||||
volatile float _Fluxo = 0;
|
||||
unsigned int _PulsosLeitura = 0;
|
||||
unsigned long _PeriodoTotalLeitura = 0;
|
||||
|
||||
void Inicializar() {
|
||||
if (Iniciado) {
|
||||
//EnviarDadosSerial(_ID + " ja inicializado");
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
PrintTela(_ID + " ja inicializado");
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
return;
|
||||
}
|
||||
|
||||
_pino.Conectar();
|
||||
ultimaLeitura = _pino.get();
|
||||
tempoAnterior = 0;
|
||||
_Pulsos = 0;
|
||||
_PeriodoTotal = 0;
|
||||
_Fluxo = 0;
|
||||
|
||||
if (SFTaskHandle == NULL) {
|
||||
xTaskCreatePinnedToCore(&SensorFluxo::SFTaskWrapper, "SFTask", 10000, this, _prioridade, &SFTaskHandle, tskNO_AFFINITY);
|
||||
}
|
||||
bouncer.attach(_pino.num);
|
||||
bouncer.interval(10);
|
||||
|
||||
//EnviarDadosSerial(_ID + " Iniciado");
|
||||
ResetarEstado();
|
||||
|
||||
PrintTela(_ID + " Iniciado");
|
||||
|
||||
Iniciado = true;
|
||||
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
}
|
||||
|
||||
void Desligar() {
|
||||
if (!Iniciado) {
|
||||
//EnviarDadosSerial(_ID + " nao esta inicializado");
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
PrintTela(_ID + " nao esta inicializado");
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
return;
|
||||
}
|
||||
|
||||
// Parar a execução das tarefas
|
||||
vTaskDelete(SFTaskHandle);
|
||||
SFTaskHandle = NULL;
|
||||
|
||||
delay(50); // Aguarda um tempo para garantir o desligamento da tarefa
|
||||
|
||||
// Redefinir as configurações para os valores iniciais
|
||||
_pino.Desconectar();
|
||||
|
||||
//EnviarDadosSerial(_ID + " Desligado");
|
||||
ResetarEstado();
|
||||
|
||||
PrintTela(_ID + " Desligado");
|
||||
|
||||
Iniciado = false;
|
||||
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
}
|
||||
|
||||
void AtualizarLeitura() {
|
||||
_PulsosLeitura = _Pulsos;
|
||||
_PeriodoTotalLeitura = _PeriodoTotal;
|
||||
|
||||
private:
|
||||
TaskHandle_t SFTaskHandle = NULL;
|
||||
static void SFTaskWrapper(void *pvParameters) {
|
||||
SensorFluxo *sensor = static_cast<SensorFluxo*>(pvParameters);
|
||||
sensor->SFTask();
|
||||
ReiniciarAmostragem();
|
||||
}
|
||||
|
||||
void SFTask() {
|
||||
unsigned long firstMilis = millis();
|
||||
volatile int pulsosA = 0;
|
||||
volatile float periodo = 0;
|
||||
|
||||
while (1)
|
||||
{
|
||||
if (!Iniciado) {
|
||||
// Caso não esteja conectado, aguarda 1 segundo até a próxima verificação, liberando uso de CPU
|
||||
vTaskDelay(pdMS_TO_TICKS(1000));
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
bool Leitura = _pino.get() == 1;
|
||||
if (Leitura != ultimaLeitura) {
|
||||
ultimaLeitura = Leitura;
|
||||
_Pulsos++;
|
||||
// Método principal de leitura
|
||||
void Loop() {
|
||||
if (!Iniciado) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Calcular o período em microssegundos
|
||||
unsigned long tempoAtual = micros();
|
||||
unsigned long periodoUs = _Pulsos == 1 ? 0 : (tempoAtual - tempoAnterior);
|
||||
periodo = periodoUs / 1000.0; // Converte de us para ms (2300 us para 2,3 ms)
|
||||
_PeriodoTotal += periodo;
|
||||
// Atualiza debounce
|
||||
bouncer.update();
|
||||
|
||||
//CalcularFluxo(periodo);
|
||||
// Detecta transição
|
||||
if (bouncer.fell()) { // Transição de HIGH para LOW
|
||||
unsigned long tempoAtual = millis();
|
||||
unsigned long intervalo = tempoAtual - tempoAnterior;
|
||||
tempoAnterior = tempoAtual;
|
||||
|
||||
tempoAnterior = tempoAtual;
|
||||
}
|
||||
|
||||
long intMillis = (millis() - firstMilis);
|
||||
|
||||
int Tempo = _TaxaAmostragem + _delayAmostragem;
|
||||
// A cada _TaxaAmostragem, enviar os dados para o software
|
||||
if (intMillis >= Tempo) {
|
||||
if (_Pulsos == pulsosA) {
|
||||
_PeriodoTotal = 0;
|
||||
_Pulsos = 0;
|
||||
}
|
||||
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sFLX, _ID, MontarDadosProtocoloFluxo(pulsos, periodoTotal)));
|
||||
|
||||
pulsosA = _Pulsos;
|
||||
firstMilis = millis();
|
||||
}
|
||||
|
||||
// Aguarda metade do menor período possível entre leituras
|
||||
vTaskDelay(pdMS_TO_TICKS(1));
|
||||
_Pulsos++;
|
||||
_PeriodoTotal += intervalo;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
// Reseta o estado do sensor
|
||||
void ResetarEstado() {
|
||||
_Pulsos = 0;
|
||||
_PeriodoTotal = 0;
|
||||
tempoAnterior = 0;
|
||||
}
|
||||
|
||||
// Reinicia amostragem
|
||||
void ReiniciarAmostragem() {
|
||||
//Serial.println("Pulsos: " + String(_Pulsos) + ", Período Total: " + String(_PeriodoTotal) + " ms");
|
||||
|
||||
// Reseta os valores para a próxima amostragem
|
||||
_Pulsos = 0;
|
||||
_PeriodoTotal = 0;
|
||||
}
|
||||
|
||||
|
||||
};
|
||||
|
||||
|
||||
// Função para inicializar os sensores de fluxo com IDs e pinos específicos
|
||||
void SensorFluxo::InicializarLista(std::vector<SensorFluxo*>& lista, const String& parametros, const String& Mod_ID) {
|
||||
// Verifica se há sensores já na lista
|
||||
if (!lista.empty()) {
|
||||
PrintTela("Limpando lista de sensores de fluxo existente...");
|
||||
|
||||
for (auto* sensor : lista) {
|
||||
sensor->Desligar(); // Desliga cada sensor antes de remover
|
||||
PrintTela("Sensor de Fluxo " + sensor->_ID + " desligado.");
|
||||
delete sensor;
|
||||
}
|
||||
|
||||
lista.clear(); // Limpa a lista após desligar todos os itens
|
||||
}
|
||||
|
||||
if (parametros.length() > 0) {
|
||||
std::vector<String> _config = SplitString(parametros, SplitConfig); // Divide a configuração por vírgulas
|
||||
|
||||
for (const String& config : _config) {
|
||||
std::vector<String> partes = SplitString(config, SplitSubParams); // Divide cada configuração pelo '-'
|
||||
|
||||
if (partes.size() == 4) {
|
||||
String id = partes[0];
|
||||
bool conectar = partes[1] == "1";
|
||||
TiposBarramentos pinoB = (TiposBarramentos)partes[2].toInt();
|
||||
int pino = partes[3].toInt();
|
||||
|
||||
if (conectar) {
|
||||
SensorFluxo* sensor = new SensorFluxo(Mod_ID, id);
|
||||
sensor->_pino = PinoModel(pino, pinoB, _INPUT, DIGITAL);
|
||||
sensor->Inicializar();
|
||||
|
||||
lista.push_back(sensor);
|
||||
PrintTela("Sensor de fluxo " + id + " inicializado no pino " + String(pino));
|
||||
}
|
||||
} else {
|
||||
PrintTela("Configuração inválida para sensor de fluxo: " + config);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
PrintTela("Configuração de sensor de fluxo não encontrada.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#endif
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ class SensorMagnetometro {
|
|||
void Inicializar() {
|
||||
if (Iniciado) {
|
||||
//EnviarDadosSerial(_ID + " ja inicializado");
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -36,13 +36,13 @@ class SensorMagnetometro {
|
|||
|
||||
Iniciado = true;
|
||||
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
}
|
||||
|
||||
void Desligar() {
|
||||
if (!Iniciado) {
|
||||
//EnviarDadosSerial(_ID + " nao esta inicializado");
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -50,7 +50,7 @@ class SensorMagnetometro {
|
|||
|
||||
Iniciado = false;
|
||||
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
}
|
||||
|
||||
void AferirOrientacao() {
|
||||
|
|
@ -62,7 +62,7 @@ class SensorMagnetometro {
|
|||
void RequisitarDados() {
|
||||
AferirOrientacao();
|
||||
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sMAG, _ID, MontarDadosProtocoloMagnetometro(x, y, z, orientacao)));
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sMAG, _ID, MontarDadosProtocoloMagnetometro(x, y, z, orientacao)));
|
||||
}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,124 @@
|
|||
#include "SerialService.h"
|
||||
#include "Pinout.h"
|
||||
#include "Utils.h"
|
||||
#include "HX711.h"
|
||||
#include <SimpleKalmanFilter.h>
|
||||
|
||||
#ifndef SensorMassaModel
|
||||
#define SensorMassaModel
|
||||
|
||||
class SensorMassa {
|
||||
public:
|
||||
|
||||
static void InicializarLista(std::vector<SensorMassa*>& lista, const String& parametros, const String& Mod_ID);
|
||||
|
||||
SensorMassa(String _modID, String _id) {
|
||||
Mod_ID = _modID;
|
||||
_ID = _id;
|
||||
}
|
||||
|
||||
String Mod_ID;
|
||||
String _ID;
|
||||
PinoModel _pinoDT;
|
||||
PinoModel _pinoSCK;
|
||||
|
||||
HX711 balanca = HX711();
|
||||
SimpleKalmanFilter filtro = SimpleKalmanFilter(2, 2, 0.01);
|
||||
|
||||
double leituraMassa = 0;
|
||||
|
||||
bool Iniciado = false;
|
||||
|
||||
void Inicializar() {
|
||||
if (Iniciado) {
|
||||
PrintTela(_ID + " ja inicializado");
|
||||
return;
|
||||
}
|
||||
|
||||
if (_pinoDT.Definido() && _pinoSCK.Definido()) {
|
||||
balanca.begin(_pinoDT.num, _pinoSCK.num);
|
||||
balanca.set_scale();
|
||||
//balanca->tare();
|
||||
|
||||
Iniciado = true;
|
||||
|
||||
PrintTela(_ID + " Iniciado");
|
||||
}
|
||||
}
|
||||
|
||||
void Desligar() {
|
||||
if (!Iniciado) {
|
||||
PrintTela(_ID + " nao esta inicializado");
|
||||
return;
|
||||
}
|
||||
|
||||
// Redefinir as configurações para os valores iniciais
|
||||
_pinoDT.Desconectar();
|
||||
_pinoSCK.Desconectar();
|
||||
|
||||
PrintTela(_ID + " Desligado");
|
||||
|
||||
Iniciado = false;
|
||||
}
|
||||
|
||||
void AferirMassa() {
|
||||
float leitura = balanca.get_units(5);
|
||||
leituraMassa = filtro.updateEstimate(leitura);
|
||||
}
|
||||
|
||||
void RequisitarDados() {
|
||||
AferirMassa();
|
||||
}
|
||||
|
||||
|
||||
};
|
||||
|
||||
|
||||
// Função para inicializar os sensores de massa com IDs e pinos específicos
|
||||
void SensorMassa::InicializarLista(std::vector<SensorMassa*>& lista, const String& parametros, const String& Mod_ID) {
|
||||
// Verifica se há sensores já na lista
|
||||
if (!lista.empty()) {
|
||||
PrintTela("Limpando lista de sensores de massa existente...");
|
||||
|
||||
for (auto* sensor : lista) {
|
||||
sensor->Desligar(); // Desliga cada sensor antes de remover
|
||||
PrintTela("Sensor de Massa " + sensor->_ID + " desligado.");
|
||||
delete sensor;
|
||||
}
|
||||
|
||||
lista.clear(); // Limpa a lista após desligar todos os itens
|
||||
}
|
||||
|
||||
if (parametros.length() > 0) {
|
||||
std::vector<String> _config = SplitString(parametros, SplitConfig); // Divide a configuração por vírgulas
|
||||
|
||||
for (const String& config : _config) {
|
||||
std::vector<String> partes = SplitString(config, SplitSubParams); // Divide cada configuração pelo '-'
|
||||
|
||||
if (partes.size() == 6) {
|
||||
String id = partes[0];
|
||||
bool conectar = partes[1] == "1";
|
||||
TiposBarramentos pinoDtB = (TiposBarramentos)partes[2].toInt();
|
||||
int pinoDt = partes[3].toInt();
|
||||
TiposBarramentos pinoSckB = (TiposBarramentos)partes[4].toInt();
|
||||
int pinoSck = partes[5].toInt();
|
||||
|
||||
if (conectar) {
|
||||
SensorMassa* sensor = new SensorMassa(Mod_ID, id);
|
||||
sensor->_pinoDT = PinoModel(pinoDt, pinoDtB, _INPUT, DIGITAL);
|
||||
sensor->_pinoSCK = PinoModel(pinoSck, pinoSckB, _INPUT, DIGITAL);
|
||||
sensor->Inicializar();
|
||||
|
||||
lista.push_back(sensor);
|
||||
PrintTela("Sensor de massa " + id + " inicializado nos pinos " + String(pinoDt) + " e " + String(pinoSck));
|
||||
}
|
||||
} else {
|
||||
PrintTela("Configuração inválida para sensor de massa: " + config);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
PrintTela("Configuração de sensor de massa não encontrada.");
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
|
@ -28,7 +28,7 @@ class SensorNivel {
|
|||
|
||||
void Inicializar() {
|
||||
if (Iniciado) {
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, "1"));
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, "1"));
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -37,19 +37,19 @@ class SensorNivel {
|
|||
_pino.Conectar(); // Conecta o pino antes de criar a tarefa
|
||||
|
||||
Iniciado = true;
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, "1"));
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, "1"));
|
||||
}
|
||||
|
||||
void Desligar() {
|
||||
if (!Iniciado) {
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, "0"));
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, "0"));
|
||||
return;
|
||||
}
|
||||
|
||||
_pino.Desconectar(); // Desconecta o pino
|
||||
|
||||
Iniciado = false;
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, "0"));
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, "0"));
|
||||
}
|
||||
|
||||
void AferirNivel() {
|
||||
|
|
|
|||
|
|
@ -8,6 +8,8 @@
|
|||
class SensorPressao {
|
||||
public:
|
||||
|
||||
static void InicializarLista(std::vector<SensorPressao*>& lista, const String& parametros, const String& Mod_ID);
|
||||
|
||||
SensorPressao(String _modID, String _id) {
|
||||
Mod_ID = _modID;
|
||||
_ID = _id;
|
||||
|
|
@ -16,17 +18,22 @@ class SensorPressao {
|
|||
// Definições
|
||||
String Mod_ID = "";
|
||||
String _ID;
|
||||
S_Code _componente = sPRS;
|
||||
PinoModel _pino;
|
||||
|
||||
double _Vmin = 0.0;
|
||||
double _Vmax = 4.5;
|
||||
double _Pmax = 174.045;
|
||||
|
||||
double leitura = 0;
|
||||
double Pressao = 0;
|
||||
|
||||
SimpleKalmanFilter filtro = SimpleKalmanFilter(2, 2, 0.01);
|
||||
|
||||
bool Iniciado = false;
|
||||
bool Checando = false;
|
||||
|
||||
void Inicializar() {
|
||||
if (Iniciado) {
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, "1"));
|
||||
PrintTela(_ID + " ja inicializado");
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -35,32 +42,87 @@ class SensorPressao {
|
|||
_pino.Conectar(); // Conecta o pino antes de criar a tarefa
|
||||
|
||||
Iniciado = true;
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, "1"));
|
||||
|
||||
PrintTela(_ID + " Iniciado");
|
||||
}
|
||||
|
||||
void Desligar() {
|
||||
if (!Iniciado) {
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, "0"));
|
||||
PrintTela(_ID + " nao esta inicializado");
|
||||
return;
|
||||
}
|
||||
|
||||
_pino.Desconectar(); // Desconecta o pino
|
||||
|
||||
Iniciado = false;
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, "0"));
|
||||
|
||||
PrintTela(_ID + " Desligado");
|
||||
}
|
||||
|
||||
void AferirPressao() {
|
||||
leitura = _pino.get();
|
||||
double leituraPressao = filtro.updateEstimate(leitura);
|
||||
|
||||
double tensao = fmap(leituraPressao, 0.0, 4095.0, 0.0, 3300.0) / 1000.0;
|
||||
Pressao = fmap(tensao, _Vmin, _Vmax, 0.0, _Pmax);
|
||||
}
|
||||
|
||||
void RequisitarDados() {
|
||||
AferirPressao();
|
||||
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sPRS, _ID, MontarDadosProtocoloPressao(Iniciado, leitura)));
|
||||
}
|
||||
|
||||
|
||||
};
|
||||
|
||||
|
||||
// Função para inicializar os sensores de pressao com IDs e pinos específicos
|
||||
void SensorPressao::InicializarLista(std::vector<SensorPressao*>& lista, const String& parametros, const String& Mod_ID) {
|
||||
// Verifica se há sensores já na lista
|
||||
if (!lista.empty()) {
|
||||
PrintTela("Limpando lista de sensores de pressao existente...");
|
||||
|
||||
for (auto* sensor : lista) {
|
||||
sensor->Desligar(); // Desliga cada sensor antes de remover
|
||||
PrintTela("Sensor de Pressao " + sensor->_ID + " desligado.");
|
||||
delete sensor;
|
||||
}
|
||||
|
||||
lista.clear(); // Limpa a lista após desligar todos os itens
|
||||
}
|
||||
|
||||
if (parametros.length() > 0) {
|
||||
std::vector<String> _config = SplitString(parametros, SplitConfig); // Divide a configuração por vírgulas
|
||||
|
||||
for (const String& config : _config) {
|
||||
std::vector<String> partes = SplitString(config, SplitSubParams); // Divide cada configuração pelo '-'
|
||||
|
||||
if (partes.size() == 7) {
|
||||
String id = partes[0];
|
||||
bool conectar = partes[1] == "1";
|
||||
TiposBarramentos pinoB = (TiposBarramentos)partes[2].toInt();
|
||||
int pino = partes[3].toInt();
|
||||
double Vmin = partes[4].toDouble();
|
||||
double Vmax = partes[5].toDouble();
|
||||
double Pmax = partes[6].toDouble();
|
||||
|
||||
if (conectar) {
|
||||
SensorPressao* sensor = new SensorPressao(Mod_ID, id);
|
||||
sensor->_Vmin = Vmin;
|
||||
sensor->_Vmax = Vmax;
|
||||
sensor->_Pmax = Pmax;
|
||||
sensor->_pino = PinoModel(pino, pinoB, _INPUT, ANALOGICO);
|
||||
sensor->Inicializar();
|
||||
|
||||
lista.push_back(sensor);
|
||||
PrintTela("Sensor de pressao " + id + " inicializado no pino " + String(pino));
|
||||
}
|
||||
} else {
|
||||
PrintTela("Configuração inválida para sensor de pressao: " + config);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
PrintTela("Configuração de sensor de pressao não encontrada.");
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
|
@ -39,7 +39,7 @@ class SensorSonar {
|
|||
void Inicializar() {
|
||||
if (Iniciado) {
|
||||
//EnviarDadosSerial(_ID + " ja inicializado");
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -60,13 +60,13 @@ class SensorSonar {
|
|||
|
||||
Iniciado = true;
|
||||
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
}
|
||||
|
||||
void Desligar() {
|
||||
if (!Iniciado) {
|
||||
//EnviarDadosSerial(_ID + " nao esta inicializado");
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -88,11 +88,11 @@ class SensorSonar {
|
|||
|
||||
Iniciado = false;
|
||||
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
}
|
||||
|
||||
void RequisitarDados() {
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sSNR, _ID, MontarDadosProtocoloSonar(_distancia, _angulo, _posicao)));
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sSNR, _ID, MontarDadosProtocoloSonar(_distancia, _angulo, _posicao)));
|
||||
}
|
||||
|
||||
private:
|
||||
|
|
|
|||
|
|
@ -8,6 +8,8 @@
|
|||
class SensorTemperatura {
|
||||
public:
|
||||
|
||||
static void InicializarLista(std::vector<SensorTemperatura*>& lista, const String& parametros, const String& Mod_ID);
|
||||
|
||||
SensorTemperatura(String _modID, String _id) {
|
||||
Mod_ID = _modID;
|
||||
_ID = _id;
|
||||
|
|
@ -16,7 +18,6 @@ class SensorTemperatura {
|
|||
// Definições
|
||||
String Mod_ID = "";
|
||||
String _ID;
|
||||
S_Code _componente = sTMP;
|
||||
PinoModel _pino;
|
||||
|
||||
double leitura = 0;
|
||||
|
|
@ -26,7 +27,7 @@ class SensorTemperatura {
|
|||
|
||||
void Inicializar() {
|
||||
if (Iniciado) {
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, "1"));
|
||||
PrintTela(_ID + " ja inicializado");
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -35,19 +36,21 @@ class SensorTemperatura {
|
|||
_pino.Conectar(); // Conecta o pino antes de criar a tarefa
|
||||
|
||||
Iniciado = true;
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, "1"));
|
||||
|
||||
PrintTela(_ID + " iniciado");
|
||||
}
|
||||
|
||||
void Desligar() {
|
||||
if (!Iniciado) {
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, "0"));
|
||||
PrintTela(_ID + " nao esta inicializado");
|
||||
return;
|
||||
}
|
||||
|
||||
_pino.Desconectar(); // Desconecta o pino
|
||||
|
||||
PrintTela(_ID + " Desligado");
|
||||
|
||||
Iniciado = false;
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, "0"));
|
||||
}
|
||||
|
||||
void AferirTemperatura() {
|
||||
|
|
@ -56,12 +59,53 @@ class SensorTemperatura {
|
|||
|
||||
void RequisitarDados() {
|
||||
AferirTemperatura();
|
||||
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sTMP, _ID, MontarDadosProtocoloTemperatura(Iniciado, leitura)));
|
||||
}
|
||||
|
||||
|
||||
|
||||
};
|
||||
|
||||
// Função para inicializar os sensores de temperatura com IDs e pinos específicos
|
||||
void SensorTemperatura::InicializarLista(std::vector<SensorTemperatura*>& lista, const String& parametros, const String& Mod_ID) {
|
||||
// Verifica se há sensores já na lista
|
||||
if (!lista.empty()) {
|
||||
PrintTela("Limpando lista de sensores de temperatura existente...");
|
||||
|
||||
for (auto* sensor : lista) {
|
||||
sensor->Desligar(); // Desliga cada sensor antes de remover
|
||||
PrintTela("Sensor de Temperatura " + sensor->_ID + " desligado.");
|
||||
delete sensor;
|
||||
}
|
||||
|
||||
lista.clear(); // Limpa a lista após desligar todos os itens
|
||||
}
|
||||
|
||||
if (parametros.length() > 0) {
|
||||
std::vector<String> _config = SplitString(parametros, SplitConfig); // Divide a configuração por vírgulas
|
||||
|
||||
for (const String& config : _config) {
|
||||
std::vector<String> partes = SplitString(config, SplitSubParams); // Divide cada configuração pelo '-'
|
||||
|
||||
if (partes.size() >= 4) {
|
||||
String id = partes[0];
|
||||
bool conectar = partes[1] == "1";
|
||||
TiposBarramentos pinoB = (TiposBarramentos)partes[2].toInt();
|
||||
int pino = partes[3].toInt();
|
||||
|
||||
if (conectar) {
|
||||
SensorTemperatura* sensor = new SensorTemperatura(Mod_ID, id);
|
||||
sensor->_pino = PinoModel(pino, pinoB, _INPUT, ANALOGICO);
|
||||
sensor->Inicializar();
|
||||
lista.push_back(sensor);
|
||||
PrintTela("Sensor de temperatura " + id + " inicializado no pino " + String(pino));
|
||||
}
|
||||
} else {
|
||||
PrintTela("Configuração inválida para sensor de temperatura: " + config);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
PrintTela("Configuração de sensor de temperatura não encontrada.");
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
|
@ -30,7 +30,7 @@ class SensorUltrassom {
|
|||
void Inicializar() {
|
||||
if (Iniciado) {
|
||||
//EnviarDadosSerial(_ID + " ja inicializado");
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -41,13 +41,13 @@ class SensorUltrassom {
|
|||
|
||||
Iniciado = true;
|
||||
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
}
|
||||
|
||||
void Desligar() {
|
||||
if (!Iniciado) {
|
||||
//EnviarDadosSerial(_ID + " nao esta inicializado");
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -59,7 +59,7 @@ class SensorUltrassom {
|
|||
|
||||
Iniciado = false;
|
||||
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
}
|
||||
|
||||
void AferirDistancia() {
|
||||
|
|
@ -75,7 +75,7 @@ class SensorUltrassom {
|
|||
void RequisitarDados() {
|
||||
AferirDistancia();
|
||||
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sULT, _ID, MontarDadosProtocoloUltrassom(distanceCm, duration)));
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sULT, _ID, MontarDadosProtocoloUltrassom(distanceCm, duration)));
|
||||
}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -9,6 +9,8 @@
|
|||
class ServoFreio {
|
||||
public:
|
||||
|
||||
static void InicializarLista(std::vector<ServoFreio*>& lista, const String& parametros, const String& Mod_ID);
|
||||
|
||||
ServoFreio(String _modID, String _id) {
|
||||
Mod_ID = _modID;
|
||||
_ID = _id;
|
||||
|
|
@ -28,25 +30,23 @@ class ServoFreio {
|
|||
|
||||
void Inicializar() {
|
||||
if (Iniciado) {
|
||||
//EnviarDadosSerial(_ID + " ja inicializado");
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
PrintTela(_ID + " ja inicializado");
|
||||
return;
|
||||
}
|
||||
|
||||
if (_pino.Definido()) {
|
||||
_Servo.attach(_pino.num);
|
||||
_Servo.write(Incremental ? 0 : 180);
|
||||
_Servo.write(Incremental ? 0 : 180);\
|
||||
|
||||
Iniciado = true;
|
||||
|
||||
PrintTela(_ID + " iniciado");
|
||||
}
|
||||
|
||||
Iniciado = true;
|
||||
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
}
|
||||
|
||||
void Desligar() {
|
||||
if (!Iniciado) {
|
||||
//EnviarDadosSerial(_ID + " nao esta inicializado");
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
PrintTela(_ID + " nao esta inicializado");
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -55,11 +55,9 @@ class ServoFreio {
|
|||
_Servo.detach();
|
||||
}
|
||||
|
||||
//EnviarDadosSerial(_ID + " Desligado");
|
||||
PrintTela(_ID + " Desligado");
|
||||
|
||||
Iniciado = false;
|
||||
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
}
|
||||
|
||||
void AtualizarAngulo(int novoAngulo) {
|
||||
|
|
@ -69,9 +67,55 @@ class ServoFreio {
|
|||
}
|
||||
|
||||
void RequisitarDados() {
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sFRO, _ID, MontarDadosProtocoloFreio(Iniciado, _Angulo)));
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
|
||||
// Função para inicializar os servo freios com IDs e pinos específicos
|
||||
void ServoFreio::InicializarLista(std::vector<ServoFreio*>& lista, const String& parametros, const String& Mod_ID) {
|
||||
// Verifica se há sensores já na lista
|
||||
if (!lista.empty()) {
|
||||
PrintTela("Limpando lista de servo freios existente...");
|
||||
|
||||
for (auto* sensor : lista) {
|
||||
sensor->Desligar(); // Desliga cada sensor antes de remover
|
||||
PrintTela("Servo Freio " + sensor->_ID + " desligado.");
|
||||
delete sensor;
|
||||
}
|
||||
|
||||
lista.clear(); // Limpa a lista após desligar todos os itens
|
||||
}
|
||||
|
||||
if (parametros.length() > 0) {
|
||||
std::vector<String> _config = SplitString(parametros, SplitConfig); // Divide a configuração por vírgulas
|
||||
|
||||
for (const String& config : _config) {
|
||||
std::vector<String> partes = SplitString(config, SplitSubParams); // Divide cada configuração pelo '-'
|
||||
|
||||
if (partes.size() == 5) {
|
||||
String id = partes[0];
|
||||
bool conectar = partes[1] == "1";
|
||||
bool inc = partes[2] == "1";
|
||||
TiposBarramentos pinoB = (TiposBarramentos)partes[3].toInt();
|
||||
int pino = partes[4].toInt();
|
||||
|
||||
if (conectar) {
|
||||
ServoFreio* sensor = new ServoFreio(Mod_ID, id);
|
||||
sensor->Incremental = inc;
|
||||
sensor->_pino = PinoModel(pino, pinoB, _OUTPUT);
|
||||
sensor->Inicializar();
|
||||
lista.push_back(sensor);
|
||||
PrintTela("Servo Freio " + id + " inicializado no pino " + String(pino));
|
||||
}
|
||||
} else {
|
||||
PrintTela("Configuração inválida para servo freio: " + config);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
PrintTela("Configuração de servo freio não encontrada.");
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
|
@ -8,6 +8,8 @@
|
|||
class Sinaleiro {
|
||||
public:
|
||||
|
||||
static void InicializarLista(std::vector<Sinaleiro*>& lista, const String& parametros, const String& Mod_ID);
|
||||
|
||||
Sinaleiro(String _modID, String _id, int _taxaAmostragem = 2000) {
|
||||
Mod_ID = _modID;
|
||||
_ID = _id;
|
||||
|
|
@ -26,8 +28,7 @@ class Sinaleiro {
|
|||
|
||||
void Inicializar() {
|
||||
if (Iniciado) {
|
||||
//EnviarDadosSerial(_ID + " ja inicializado");
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
PrintTela(_ID + " ja inicializado");
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -35,17 +36,14 @@ class Sinaleiro {
|
|||
|
||||
xTaskCreatePinnedToCore(&Sinaleiro::LEDTaskWrapper, "LEDTask", 5000, this, 6, &LEDTaskHandle, tskNO_AFFINITY);
|
||||
|
||||
//EnviarDadosSerial(_ID + " Iniciado");
|
||||
PrintTela(_ID + " Iniciado");
|
||||
|
||||
Iniciado = true;
|
||||
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
}
|
||||
|
||||
void Desligar() {
|
||||
if (!Iniciado) {
|
||||
//EnviarDadosSerial(_ID + " nao esta inicializado");
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
PrintTela(_ID + " nao esta inicializado");
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -55,11 +53,9 @@ class Sinaleiro {
|
|||
// Redefinir as configurações para os valores iniciais
|
||||
_pino.Desconectar();
|
||||
|
||||
//EnviarDadosSerial(_ID + " Desligado");
|
||||
PrintTela(_ID + " Desligado");
|
||||
|
||||
Iniciado = false;
|
||||
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, Iniciado ? "1" : "0"));
|
||||
}
|
||||
|
||||
void AtualizarLeitura() {
|
||||
|
|
@ -68,8 +64,6 @@ class Sinaleiro {
|
|||
|
||||
void RequisitarDados() {
|
||||
AtualizarLeitura();
|
||||
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sLED, _ID, MontarDadosProtocoloLED(Iniciado, _StatusLeitura)));
|
||||
}
|
||||
|
||||
private:
|
||||
|
|
@ -121,4 +115,48 @@ class Sinaleiro {
|
|||
|
||||
};
|
||||
|
||||
|
||||
// Função para inicializar os sinaleiros com IDs e pinos específicos
|
||||
void Sinaleiro::InicializarLista(std::vector<Sinaleiro*>& lista, const String& parametros, const String& Mod_ID) {
|
||||
// Verifica se há sensores já na lista
|
||||
if (!lista.empty()) {
|
||||
PrintTela("Limpando lista de sinaleiros existente...");
|
||||
|
||||
for (auto* sensor : lista) {
|
||||
sensor->Desligar(); // Desliga cada sensor antes de remover
|
||||
PrintTela("Sinaleiro " + sensor->_ID + " desligado.");
|
||||
delete sensor;
|
||||
}
|
||||
|
||||
lista.clear(); // Limpa a lista após desligar todos os itens
|
||||
}
|
||||
|
||||
if (parametros.length() > 0) {
|
||||
std::vector<String> _config = SplitString(parametros, SplitConfig); // Divide a configuração por vírgulas
|
||||
|
||||
for (const String& config : _config) {
|
||||
std::vector<String> partes = SplitString(config, SplitSubParams); // Divide cada configuração pelo '-'
|
||||
|
||||
if (partes.size() == 4) {
|
||||
String id = partes[0];
|
||||
bool conectar = partes[1] == "1";
|
||||
TiposBarramentos pinoB = (TiposBarramentos)partes[2].toInt();
|
||||
int pino = partes[3].toInt();
|
||||
|
||||
if (conectar) {
|
||||
Sinaleiro* sensor = new Sinaleiro(Mod_ID, id);
|
||||
sensor->_pino = PinoModel(pino, pinoB, _OUTPUT);
|
||||
sensor->Inicializar();
|
||||
lista.push_back(sensor);
|
||||
PrintTela("Sinaleiro " + id + " inicializado no pino " + String(pino));
|
||||
}
|
||||
} else {
|
||||
PrintTela("Configuração inválida para sinaleiro: " + config);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
PrintTela("Configuração de sinaleiro não encontrada.");
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
|
@ -33,7 +33,7 @@ class Solenoide {
|
|||
|
||||
void Inicializar() {
|
||||
if (Iniciado) {
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, "1"));
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, "1"));
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -47,12 +47,12 @@ class Solenoide {
|
|||
StatusSolenoide = _pinoSolenoide.get() == (AtuacaoNivelAlto ? 1 : 0);
|
||||
|
||||
Iniciado = true;
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, "1"));
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, "1"));
|
||||
}
|
||||
|
||||
void Desligar() {
|
||||
if (!Iniciado) {
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, "0"));
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, "0"));
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -62,7 +62,7 @@ class Solenoide {
|
|||
delay(50); // Pequeno delay para garantir a liberação do pino
|
||||
|
||||
Iniciado = false;
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, "0"));
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, _ID, "0"));
|
||||
}
|
||||
|
||||
void AlterarStatusSolenoide(bool status) {
|
||||
|
|
@ -77,7 +77,7 @@ class Solenoide {
|
|||
|
||||
void RequisitarDados() {
|
||||
AtualizarLeitura();
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sRLE, _ID, MontarDadosProtocoloRele(Iniciado, _Status)));
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sRLE, _ID, MontarDadosProtocoloRele(Iniciado, _Status)));
|
||||
}
|
||||
|
||||
};
|
||||
|
|
|
|||
|
|
@ -0,0 +1,81 @@
|
|||
#include <WiFi.h>
|
||||
#include <HTTPClient.h>
|
||||
#include "EepromService.h"
|
||||
#include "SerialService.h"
|
||||
|
||||
#ifndef WifiService
|
||||
#define WifiService
|
||||
|
||||
|
||||
bool WifiIsConnected = false;
|
||||
|
||||
bool connectToWiFi() {
|
||||
char ssid[MAX_SSID_LEN];
|
||||
char password[MAX_PASS_LEN];
|
||||
loadWiFiCredentials(ssid, password);
|
||||
|
||||
PrintTela("Conectando a ", false);
|
||||
PrintTela(ssid);
|
||||
|
||||
WiFi.begin(ssid, password);
|
||||
int timeout = 10000; // Tempo máximo de espera
|
||||
int startTime = millis();
|
||||
|
||||
while (WiFi.status() != WL_CONNECTED && millis() - startTime < timeout) {
|
||||
delay(500);
|
||||
PrintTela(".", false);
|
||||
}
|
||||
|
||||
if (WiFi.status() == WL_CONNECTED) {
|
||||
PrintTela("\nWiFi conectado! IP: ", false);
|
||||
PrintTela(WiFi.localIP().toString().c_str());
|
||||
WifiIsConnected = true;
|
||||
return true;
|
||||
} else {
|
||||
PrintTela("\nFalha na conexão.");
|
||||
WifiIsConnected = false;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void InicializarConexaoWifi(IPAddress ip, IPAddress gateway, IPAddress subnet, IPAddress dns) {
|
||||
EEPROM.begin(EEPROM_SIZE); // Iniciar EEPROM com espaço para SSID e senha
|
||||
|
||||
// Carregar credenciais e tentar conectar
|
||||
char ssid[MAX_SSID_LEN];
|
||||
char password[MAX_PASS_LEN];
|
||||
|
||||
loadWiFiCredentials(ssid, password);
|
||||
|
||||
PrintTela(ssid);
|
||||
|
||||
// Configurar IP fixo
|
||||
if (!WiFi.config(ip, gateway, subnet, dns)) {
|
||||
Serial.println("Falha ao configurar IP estático!");
|
||||
}
|
||||
|
||||
if (ssid[0] != '\0') { // Verificar se há SSID salvo
|
||||
WifiIsConnected = connectToWiFi();
|
||||
}
|
||||
}
|
||||
|
||||
bool verificaInternet() {
|
||||
if (WiFi.status() != WL_CONNECTED) {
|
||||
PrintTela("Wi-Fi não está conectado.");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Teste de conexão com um servidor externo
|
||||
WiFiClient client;
|
||||
if (client.connect("www.google.com", 80)) { // Tenta conectar ao Google na porta 80
|
||||
client.stop(); // Fecha a conexão imediatamente após verificar
|
||||
PrintTela("Conexão com a Internet ativa.");
|
||||
return true;
|
||||
} else {
|
||||
PrintTela("Falha na conexão com a Internet.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#endif
|
||||
|
|
@ -58,7 +58,7 @@ void inicializarSensoresTemperatura(String configSensores) {
|
|||
for (const String& config : temperaturaConfigs) {
|
||||
std::vector<String> partes = SplitString(config, SplitSubParams); // Divide cada configuração pelo '-'
|
||||
|
||||
if (partes.size() == 5) {
|
||||
if (partes.size() >= 3) {
|
||||
String id = partes[0];
|
||||
TiposBarramentos pinoB = (TiposBarramentos)partes[1].toInt();
|
||||
int pino = partes[2].toInt();
|
||||
|
|
@ -99,10 +99,10 @@ void inicializarSensoresCorrente(String configSensores) {
|
|||
for (const String& config : correnteConfigs) {
|
||||
std::vector<String> partes = SplitString(config, SplitSubParams); // Divide cada configuração pelo '-'
|
||||
|
||||
if (partes.size() == 5) {
|
||||
if (partes.size() >= 5) {
|
||||
String id = partes[0];
|
||||
String _endereco = partes[1];
|
||||
int _a_max = partes[2].toDouble();
|
||||
String _endereco = partes[3];
|
||||
int _a_max = partes[4].toDouble();
|
||||
|
||||
SensorCorrente* sensor = new SensorCorrente(Mod_ID, id);
|
||||
sensor->_Endereco = stringToByte(_endereco);
|
||||
|
|
@ -311,54 +311,58 @@ void enviarDadosSensores() {
|
|||
|
||||
String MontarMensagemSensores() {
|
||||
// Criação de um objeto JSON dinâmico com tamanho adequado
|
||||
DynamicJsonDocument jsonDoc(1024);
|
||||
DynamicJsonDocument jsonDoc(2048);
|
||||
|
||||
// Adicionar campos gerais
|
||||
jsonDoc["Conectado"] = Conectado;
|
||||
jsonDoc["Mod_ID"] = Mod_ID;
|
||||
|
||||
// Array JSON para sensores de temperatura
|
||||
JsonArray sensoresTemperaturaArray = jsonDoc.createNestedArray("sensores_temperatura");
|
||||
JsonArray sensoresTemperaturaArray = jsonDoc.createNestedArray("SensoresTemperatura");
|
||||
for (const auto* sensor : listaSensoresTemperatura) {
|
||||
JsonObject sensorData = sensoresTemperaturaArray.createNestedObject();
|
||||
sensorData["id"] = sensor->_ID;
|
||||
sensorData["iniciado"] = sensor->Iniciado;
|
||||
sensorData["leitura"] = sensor->leitura;
|
||||
sensorData["Id"] = sensor->_ID;
|
||||
sensorData["Iniciado"] = sensor->Iniciado;
|
||||
sensorData["Leitura"] = sensor->leitura;
|
||||
}
|
||||
|
||||
// Array JSON para sensores de corrente
|
||||
JsonArray sensoresCorrenteArray = jsonDoc.createNestedArray("sensores_corrente");
|
||||
JsonArray sensoresCorrenteArray = jsonDoc.createNestedArray("SensoresCorrente");
|
||||
for (const auto* sensor : listaSensoresCorrente) {
|
||||
JsonObject sensorData = sensoresCorrenteArray.createNestedObject();
|
||||
sensorData["id"] = sensor->_ID;
|
||||
sensorData["iniciado"] = sensor->Iniciado;
|
||||
sensorData["busVoltage"] = sensor->busVoltage;
|
||||
sensorData["shuntVoltage"] = sensor->shuntVoltage;
|
||||
sensorData["current"] = sensor->current;
|
||||
sensorData["power"] = sensor->power;
|
||||
sensorData["Id"] = sensor->_ID;
|
||||
sensorData["Iniciado"] = sensor->Iniciado;
|
||||
sensorData["BusVoltage"] = sensor->busVoltage;
|
||||
sensorData["ShuntVoltage"] = sensor->shuntVoltage;
|
||||
sensorData["Current"] = sensor->current;
|
||||
sensorData["Power"] = sensor->power;
|
||||
}
|
||||
|
||||
// Array JSON para sinaleiros
|
||||
JsonArray sinaleirosArray = jsonDoc.createNestedArray("sinaleiros");
|
||||
JsonArray sinaleirosArray = jsonDoc.createNestedArray("Sinaleiros");
|
||||
for (const auto* sensor : listaSinaleiros) {
|
||||
JsonObject sensorData = sinaleirosArray.createNestedObject();
|
||||
sensorData["id"] = sensor->_ID;
|
||||
sensorData["iniciado"] = sensor->Iniciado;
|
||||
sensorData["leitura"] = sensor->_StatusLeitura;
|
||||
sensorData["Id"] = sensor->_ID;
|
||||
sensorData["Iniciado"] = sensor->Iniciado;
|
||||
sensorData["Leitura"] = sensor->_StatusLeitura;
|
||||
}
|
||||
|
||||
// Array JSON para reles
|
||||
JsonArray relesArray = jsonDoc.createNestedArray("reles");
|
||||
JsonArray relesArray = jsonDoc.createNestedArray("Reles");
|
||||
for (const auto* sensor : listaReles) {
|
||||
JsonObject sensorData = relesArray.createNestedObject();
|
||||
sensorData["id"] = sensor->_ID;
|
||||
sensorData["iniciado"] = sensor->Iniciado;
|
||||
sensorData["leitura"] = sensor->_Status;
|
||||
sensorData["Id"] = sensor->_ID;
|
||||
sensorData["Iniciado"] = sensor->Iniciado;
|
||||
sensorData["Leitura"] = sensor->_Status;
|
||||
}
|
||||
|
||||
// Array JSON para servo freios
|
||||
JsonArray servoFreiosArray = jsonDoc.createNestedArray("servo_freios");
|
||||
JsonArray servoFreiosArray = jsonDoc.createNestedArray("ServoFreios");
|
||||
for (const auto* sensor : listaServoFreios) {
|
||||
JsonObject sensorData = servoFreiosArray.createNestedObject();
|
||||
sensorData["id"] = sensor->_ID;
|
||||
sensorData["iniciado"] = sensor->Iniciado;
|
||||
sensorData["angulo"] = sensor->_Angulo;
|
||||
sensorData["Id"] = sensor->_ID;
|
||||
sensorData["Iniciado"] = sensor->Iniciado;
|
||||
sensorData["Angulo"] = sensor->_Angulo;
|
||||
}
|
||||
|
||||
// Serializa o JSON para uma string
|
||||
|
|
@ -402,10 +406,10 @@ void ProcessarChk(ProtocoloSerial Mensagem) {
|
|||
}
|
||||
|
||||
void ProcessarCfg(ProtocoloSerial Mensagem) {
|
||||
std::vector<String> Partes = SplitString(Mensagem.protocolo, (char*)",");
|
||||
String ID = Partes[0];
|
||||
bool Conectar = Partes[1] == "1";
|
||||
if (ID == "MD") {
|
||||
std::vector<String> Partes = SplitString(Mensagem.protocolo, SplitParams);
|
||||
T_Code Tipo = (T_Code)(Partes[0].toInt());
|
||||
if (Tipo == Mod) {
|
||||
bool Conectar = Partes[1] == "1";
|
||||
_TaxaAmostragem = Partes[2].toInt();
|
||||
RequisitarDados = Partes[3] == "1";
|
||||
TiposBarramentos pinoSDAB = (TiposBarramentos)Partes[4].toInt();
|
||||
|
|
@ -420,13 +424,13 @@ void ProcessarCfg(ProtocoloSerial Mensagem) {
|
|||
Wire.begin(_pinoSDA.num, _pinoSCL.num);
|
||||
}
|
||||
|
||||
EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, "MD", Conectar ? "1" : "0"));
|
||||
//EnviarDadosSerial(Mod_ID, MontarProtocoloSensor(sCFG, "MD", Conectar ? "1" : "0"));
|
||||
vTaskDelay(pdMS_TO_TICKS(100));
|
||||
Conectado = Conectar;
|
||||
}
|
||||
else {
|
||||
S_Code componente = (S_Code)Partes[2].toInt();
|
||||
String config = Partes[3];
|
||||
S_Code componente = (S_Code)Partes[1].toInt();
|
||||
String config = Partes[2];
|
||||
|
||||
switch (componente) {
|
||||
case sTMP: {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,8 @@
|
|||
{
|
||||
// Use IntelliSense to learn about possible attributes.
|
||||
// Hover to view descriptions of existing attributes.
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,345 @@
|
|||
// Dispositivo: Sensoriamento
|
||||
// Versão Firmware: 13
|
||||
// Ultima atualização: 29/11/2024
|
||||
// Atualização: Implementado MQTT
|
||||
|
||||
#include <ArduinoJson.h>
|
||||
#include "C:\ZendionInc\agrobot_base\Firmware\Modulos\MqttService.h"
|
||||
#include "C:\ZendionInc\agrobot_base\Firmware\Modulos\WifiService.h"
|
||||
#include "C:\ZendionInc\agrobot_base\Firmware\Modulos\EepromService.h"
|
||||
#include "C:\ZendionInc\agrobot_base\Firmware\Modulos\SerialService.h"
|
||||
#include "C:\ZendionInc\agrobot_base\Firmware\Modulos\Utils.h"
|
||||
#include "C:\ZendionInc\agrobot_base\Firmware\Modulos\Pinout.h"
|
||||
#include "C:\ZendionInc\agrobot_base\Firmware\Modulos\SensorTemperaturaModel.h"
|
||||
#include "C:\ZendionInc\agrobot_base\Firmware\Modulos\SensorCorrenteModel.h"
|
||||
#include "C:\ZendionInc\agrobot_base\Firmware\Modulos\SinaleiroModel.h"
|
||||
#include "C:\ZendionInc\agrobot_base\Firmware\Modulos\ReleModel.h"
|
||||
#include "C:\ZendionInc\agrobot_base\Firmware\Modulos\ServoFreioModel.h"
|
||||
|
||||
|
||||
// Configurações do IP estático
|
||||
IPAddress local_IP(192, 168, 99, 112); // IP fixo para o ESP
|
||||
IPAddress gateway(192, 168, 99, 1); // Gateway padrão
|
||||
IPAddress subnet(255, 255, 255, 0); // Máscara de sub-rede
|
||||
IPAddress primaryDNS(8, 8, 8, 8); // Servidor DNS primário (opcional)
|
||||
|
||||
// Instancia o serviço MQTT
|
||||
MqttService mqttService;
|
||||
|
||||
#define D_Code Sen
|
||||
#define VERSION 13
|
||||
String Mod_ID = "Sen";
|
||||
|
||||
#define _pinoLED RGB_BUILTIN
|
||||
|
||||
long _baudRate = 115200;
|
||||
|
||||
bool Conectado = false;
|
||||
bool Verificando = false;
|
||||
|
||||
int _TaxaAmostragem = 1000;
|
||||
volatile bool RequisitarDados = false;
|
||||
|
||||
PinoModel _pinoSDA = PinoModel(21, CONTROLADOR, _INPUT);
|
||||
PinoModel _pinoSCL = PinoModel(22, CONTROLADOR, _INPUT);
|
||||
|
||||
|
||||
std::vector<SensorTemperatura*> listaSensoresTemperatura;
|
||||
std::vector<SensorCorrente*> listaSensoresCorrente;
|
||||
std::vector<Sinaleiro*> listaSinaleiros;
|
||||
std::vector<Rele*> listaReles;
|
||||
std::vector<ServoFreio*> listaServoFreios;
|
||||
|
||||
|
||||
void InicializarComunicacaoMQTT(bool RenovarConexao) {
|
||||
if (RenovarConexao) {
|
||||
mqttService.unsubscribe(TopicoRecepcao);
|
||||
delay(1000);
|
||||
}
|
||||
mqttService.setModID(Mod_ID);
|
||||
mqttService.InicializarComunicacaoMqtt();
|
||||
mqttService.setMessageCallback(ProcessarProtocolo);
|
||||
}
|
||||
|
||||
|
||||
|
||||
void setup() {
|
||||
Serial.begin(_baudRate);
|
||||
iniciarMCP(D_Code, Mod_ID, _pinoSDA.num, _pinoSCL.num, 0x20, false);
|
||||
|
||||
InicializarConexaoWifi(local_IP, gateway, subnet, primaryDNS);
|
||||
|
||||
if (!WifiIsConnected) {
|
||||
String newSSID = "WIFI-AGROBOTICS";
|
||||
String newPassword = "agro4321";
|
||||
|
||||
saveWiFiCredentials(newSSID.c_str(), newPassword.c_str());
|
||||
|
||||
connectToWiFi();
|
||||
|
||||
if (WifiIsConnected) {
|
||||
PrintTela("Conectado com sucesso");
|
||||
ESP.restart();
|
||||
}
|
||||
else {
|
||||
PrintTela("Erro ao se conectar ao wifi");
|
||||
while(true);
|
||||
}
|
||||
}
|
||||
|
||||
delay(100);
|
||||
|
||||
if (WifiIsConnected) {
|
||||
InicializarComunicacaoMQTT(false);
|
||||
}
|
||||
}
|
||||
|
||||
void loop() {
|
||||
if (!RequisitarDados) {
|
||||
enviarLogsPeriodicamente();
|
||||
}
|
||||
|
||||
mqttService.loop();
|
||||
|
||||
delay(1);
|
||||
}
|
||||
|
||||
// Função para enviar logs do sensor periodicamente via MQTT
|
||||
unsigned long ultimoEnvioLogs = 0;
|
||||
const unsigned long intervaloEnvioLogs = 1000; // 1 segundo
|
||||
void enviarLogsPeriodicamente() {
|
||||
unsigned long tempoAtual = millis();
|
||||
// Verifica se o intervalo de 5 segundos já passou
|
||||
if (tempoAtual - ultimoEnvioLogs >= intervaloEnvioLogs) {
|
||||
ultimoEnvioLogs = tempoAtual; // Atualiza o tempo do último envio
|
||||
|
||||
enviarDadosSensores(); // Chama o método que já envia os dados do sensor via MQTT
|
||||
}
|
||||
}
|
||||
|
||||
void enviarDadosSensores() {
|
||||
if (Conectado && !Verificando) {
|
||||
PrintTela("Atualizando dados dos sensores...");
|
||||
|
||||
// Aferir dados dos sensores
|
||||
for (auto* sensor : listaSensoresTemperatura) {
|
||||
sensor->AferirTemperatura();
|
||||
}
|
||||
|
||||
// Aferir dados dos sensores
|
||||
for (auto* sensor : listaSensoresCorrente) {
|
||||
sensor->AferirCorrente();
|
||||
}
|
||||
|
||||
// Aferir dados dos sensores
|
||||
for (auto* sensor : listaSinaleiros) {
|
||||
sensor->AtualizarLeitura();
|
||||
}
|
||||
|
||||
// Aferir dados dos sensores
|
||||
for (auto* sensor : listaReles) {
|
||||
sensor->AtualizarLeitura();
|
||||
}
|
||||
|
||||
String jsonString = MontarMensagemSensores() + String(EndLine);
|
||||
|
||||
mqttService.EnviarDados(Mod_ID, jsonString);
|
||||
}
|
||||
}
|
||||
|
||||
String MontarMensagemSensores() {
|
||||
// Criação de um objeto JSON dinâmico com tamanho adequado
|
||||
DynamicJsonDocument jsonDoc(2048);
|
||||
|
||||
// Adicionar campos gerais
|
||||
jsonDoc["Conectado"] = Conectado;
|
||||
jsonDoc["Mod_ID"] = Mod_ID;
|
||||
|
||||
// Array JSON para sensores de temperatura
|
||||
JsonArray sensoresTemperaturaArray = jsonDoc.createNestedArray("SensoresTemperatura");
|
||||
for (const auto* sensor : listaSensoresTemperatura) {
|
||||
JsonObject sensorData = sensoresTemperaturaArray.createNestedObject();
|
||||
sensorData["Id"] = sensor->_ID;
|
||||
sensorData["Iniciado"] = sensor->Iniciado;
|
||||
sensorData["Leitura"] = sensor->leitura;
|
||||
}
|
||||
|
||||
// Array JSON para sensores de corrente
|
||||
JsonArray sensoresCorrenteArray = jsonDoc.createNestedArray("SensoresCorrente");
|
||||
for (const auto* sensor : listaSensoresCorrente) {
|
||||
JsonObject sensorData = sensoresCorrenteArray.createNestedObject();
|
||||
sensorData["Id"] = sensor->_ID;
|
||||
sensorData["Iniciado"] = sensor->Iniciado;
|
||||
sensorData["BusVoltage"] = sensor->busVoltage;
|
||||
sensorData["ShuntVoltage"] = sensor->shuntVoltage;
|
||||
sensorData["Current"] = sensor->current;
|
||||
sensorData["Power"] = sensor->power;
|
||||
}
|
||||
|
||||
// Array JSON para sinaleiros
|
||||
JsonArray sinaleirosArray = jsonDoc.createNestedArray("Sinaleiros");
|
||||
for (const auto* sensor : listaSinaleiros) {
|
||||
JsonObject sensorData = sinaleirosArray.createNestedObject();
|
||||
sensorData["Id"] = sensor->_ID;
|
||||
sensorData["Iniciado"] = sensor->Iniciado;
|
||||
sensorData["Leitura"] = sensor->_StatusLeitura;
|
||||
}
|
||||
|
||||
// Array JSON para reles
|
||||
JsonArray relesArray = jsonDoc.createNestedArray("Reles");
|
||||
for (const auto* sensor : listaReles) {
|
||||
JsonObject sensorData = relesArray.createNestedObject();
|
||||
sensorData["Id"] = sensor->_ID;
|
||||
sensorData["Iniciado"] = sensor->Iniciado;
|
||||
sensorData["Leitura"] = sensor->_Status;
|
||||
}
|
||||
|
||||
// Array JSON para servo freios
|
||||
JsonArray servoFreiosArray = jsonDoc.createNestedArray("ServoFreios");
|
||||
for (const auto* sensor : listaServoFreios) {
|
||||
JsonObject sensorData = servoFreiosArray.createNestedObject();
|
||||
sensorData["Id"] = sensor->_ID;
|
||||
sensorData["Iniciado"] = sensor->Iniciado;
|
||||
sensorData["Angulo"] = sensor->_Angulo;
|
||||
}
|
||||
|
||||
// Serializa o JSON para uma string
|
||||
String jsonString;
|
||||
serializeJson(jsonDoc, jsonString);
|
||||
|
||||
int messageSize = jsonString.length();
|
||||
PrintTela("Tamanho da mensagem: ", false);
|
||||
PrintTela((String)messageSize);
|
||||
|
||||
return jsonString;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
void ProcessarProtocolo(ProtocoloSerial Mensagem) {
|
||||
switch (Mensagem.funcao) {
|
||||
case Chk:
|
||||
ProcessarChk(Mensagem);
|
||||
break;
|
||||
case Cfg:
|
||||
ProcessarCfg(Mensagem);
|
||||
break;
|
||||
case Cmd:
|
||||
ProcessarCmd(Mensagem);
|
||||
break;
|
||||
case Req:
|
||||
ProcessarReq(Mensagem);
|
||||
break;
|
||||
}
|
||||
|
||||
if (Mensagem.idMensagem > 0) {
|
||||
mqttService.EnviarDados(Mod_ID, MontarProtocoloMensagemRecebida(Mensagem.idMensagem));
|
||||
}
|
||||
}
|
||||
|
||||
void ProcessarChk(ProtocoloSerial Mensagem) {
|
||||
Verificando = true;
|
||||
mqttService.EnviarDados(Mod_ID, MontarProtocoloVerificacao(D_Code, VERSION, Conectado));
|
||||
delay(2000);
|
||||
Verificando = false;
|
||||
}
|
||||
|
||||
void ProcessarCfg(ProtocoloSerial Mensagem) {
|
||||
std::vector<String> Partes = SplitString(Mensagem.protocolo, SplitParams);
|
||||
T_Code Tipo = (T_Code)(Partes[0].toInt());
|
||||
if (Tipo == Mod) {
|
||||
bool Conectar = Partes[1] == "1";
|
||||
_TaxaAmostragem = Partes[2].toInt();
|
||||
RequisitarDados = Partes[3] == "1";
|
||||
TiposBarramentos pinoSDAB = (TiposBarramentos)Partes[4].toInt();
|
||||
int pinoSDA = Partes[5].toInt();
|
||||
TiposBarramentos pinoSCLB = (TiposBarramentos)Partes[6].toInt();
|
||||
int pinoSCL = Partes[7].toInt();
|
||||
|
||||
if (pinoSDA > -1 && pinoSCL > -1) {
|
||||
_pinoSDA = PinoModel(pinoSDA, pinoSDAB, _INPUT);
|
||||
_pinoSCL = PinoModel(pinoSCL, pinoSCLB, _INPUT);
|
||||
Wire.end();
|
||||
Wire.begin(_pinoSDA.num, _pinoSCL.num);
|
||||
}
|
||||
|
||||
vTaskDelay(pdMS_TO_TICKS(100));
|
||||
Conectado = Conectar;
|
||||
Verificando = false;
|
||||
|
||||
enviarDadosSensores();
|
||||
}
|
||||
else {
|
||||
S_Code componente = (S_Code)Partes[1].toInt();
|
||||
String config = Partes[2];
|
||||
|
||||
switch (componente) {
|
||||
case sTMP: {
|
||||
SensorTemperatura::InicializarLista(listaSensoresTemperatura, config, Mod_ID);
|
||||
break;
|
||||
}
|
||||
case sCOR: {
|
||||
SensorCorrente::InicializarLista(listaSensoresCorrente, config, Mod_ID);
|
||||
break;
|
||||
}
|
||||
case sLED: {
|
||||
Sinaleiro::InicializarLista(listaSinaleiros, config, Mod_ID);
|
||||
break;
|
||||
}
|
||||
case sRLE: {
|
||||
Rele::InicializarLista(listaReles, config, Mod_ID);
|
||||
break;
|
||||
}
|
||||
case sFRO: {
|
||||
ServoFreio::InicializarLista(listaServoFreios, config, Mod_ID);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ProcessarCmd(ProtocoloSerial Mensagem) {
|
||||
std::vector<String> Partes = SplitString(Mensagem.protocolo, SplitParams);
|
||||
String ID = Partes[0];
|
||||
S_Code componente = (S_Code)Partes[1].toInt();
|
||||
|
||||
switch (componente) {
|
||||
case sLED: {
|
||||
for (auto* _led : listaSinaleiros) {
|
||||
if (_led->_ID == ID) {
|
||||
_led->_Status = (StatusLED)Partes[2].toInt();
|
||||
_led->_Qtd = Partes[3].toInt();
|
||||
_led->_TempoMs = Partes[4].toInt();
|
||||
_led->_PausaMs = Partes[5].toInt();
|
||||
return;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case sRLE: {
|
||||
for (auto* _rele : listaReles) {
|
||||
if (_rele->_ID == ID) {
|
||||
Estado novoEstado = (Estado)Partes[2].toInt();
|
||||
_rele->AtualizarStatus(novoEstado);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case sFRO: {
|
||||
for (auto* _freio : listaServoFreios) {
|
||||
if (_freio->_ID == ID) {
|
||||
int novoAngulo = Partes[2].toInt();
|
||||
_freio->AtualizarAngulo(novoAngulo);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ProcessarReq(ProtocoloSerial Mensagem) {
|
||||
enviarDadosSensores();
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,89 @@
|
|||
#include <UIPEthernet.h>
|
||||
|
||||
// Configurações do IP estático
|
||||
IPAddress local_IP(192, 168, 105, 12); // Endereço IP fixo
|
||||
IPAddress gateway(192, 168, 105, 1); // Gateway padrão
|
||||
IPAddress subnet(255, 255, 255, 0); // Máscara de sub-rede
|
||||
IPAddress primaryDNS(8, 8, 8, 8); // Servidor DNS primário (opcional)
|
||||
IPAddress secondaryDNS(8, 8, 4, 4); // Servidor DNS secundário (opcional)
|
||||
|
||||
// Configuração do servidor Ethernet
|
||||
EthernetServer server(80); // Porta TCP 80 (HTTP ou customizada)
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
Serial.println("Inicializando...");
|
||||
|
||||
// MAC Address para a placa Ethernet
|
||||
uint8_t mac[6] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05};
|
||||
|
||||
// Inicializa a conexão Ethernet com IP estático
|
||||
Serial.println("Configurando IP estático...");
|
||||
Ethernet.init(5);
|
||||
Ethernet.begin(mac, local_IP, primaryDNS, gateway, subnet);
|
||||
|
||||
// Verifica se a inicialização foi bem-sucedida
|
||||
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
|
||||
Serial.println("Nenhuma placa Ethernet detectada. Verifique a conexão.");
|
||||
while (true) {
|
||||
delay(1); // Fica preso aqui
|
||||
}
|
||||
}
|
||||
|
||||
if (Ethernet.linkStatus() == LinkOFF) {
|
||||
Serial.println("Cabo Ethernet desconectado ou problema no link físico.");
|
||||
while (true) {
|
||||
delay(1); // Fica preso aqui
|
||||
}
|
||||
}
|
||||
|
||||
// Aguardar inicialização e exibir informações da rede
|
||||
delay(1000);
|
||||
Serial.println("Configuração de rede concluída:");
|
||||
Serial.print("IP Address: ");
|
||||
Serial.println(Ethernet.localIP());
|
||||
Serial.print("Subnet Mask: ");
|
||||
Serial.println(Ethernet.subnetMask());
|
||||
Serial.print("Gateway: ");
|
||||
Serial.println(Ethernet.gatewayIP());
|
||||
Serial.print("DNS Server: ");
|
||||
Serial.println(Ethernet.dnsServerIP());
|
||||
|
||||
// Inicia o servidor Ethernet
|
||||
server.begin();
|
||||
Serial.println("Servidor iniciado. Aguardando conexões...");
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// Verifica se há um cliente conectado
|
||||
EthernetClient client = server.available();
|
||||
|
||||
if (client) {
|
||||
Serial.println("Cliente conectado!");
|
||||
|
||||
// Enquanto o cliente estiver conectado
|
||||
while (client.connected()) {
|
||||
if (client.available()) {
|
||||
// Lê os dados enviados pelo cliente
|
||||
String request = client.readStringUntil('\r');
|
||||
Serial.print("Recebido: ");
|
||||
Serial.println(request);
|
||||
|
||||
// Envia uma resposta ao cliente
|
||||
client.println("HTTP/1.1 200 OK");
|
||||
client.println("Content-Type: text/plain");
|
||||
client.println("Connection: close");
|
||||
client.println();
|
||||
client.println("ESP32 Servidor Ethernet");
|
||||
client.println("Mensagem recebida com sucesso!");
|
||||
|
||||
break; // Finaliza o loop para desconectar
|
||||
}
|
||||
}
|
||||
|
||||
// Finaliza a conexão com o cliente
|
||||
delay(1);
|
||||
client.stop();
|
||||
Serial.println("Cliente desconectado.");
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue