corrigido comunicacao bld
This commit is contained in:
parent
7b21f50513
commit
5a10d30041
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -174,7 +174,7 @@ namespace AgroBase
|
|||
.Select(x => new ListViewItem()
|
||||
{
|
||||
Text =
|
||||
x.FirstOrDefault().PortaCOM + " - " + Enum.GetName(typeof(T_Code), x.Key) + " v" + x.FirstOrDefault().Versao +
|
||||
x.FirstOrDefault().Endereco + " - " + Enum.GetName(typeof(T_Code), x.Key) + " v" + x.FirstOrDefault().Versao +
|
||||
|
||||
(SerialService.DispositivosMultiplos.Contains(x.FirstOrDefault().Dispositivo) ? (" (" + string.Join(", ", x.Where(y => y.Conectado).Select(y => y.Mod_ID)) + ")") :
|
||||
|
||||
|
|
|
|||
|
|
@ -1,10 +1,8 @@
|
|||
using System;
|
||||
using AgroBase.Services;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using static AgroBase.Models.Enums;
|
||||
using static AgroBase.Services.BLD300RService;
|
||||
|
||||
namespace AgroBase.Models
|
||||
{
|
||||
|
|
@ -74,14 +72,14 @@ namespace AgroBase.Models
|
|||
{
|
||||
get
|
||||
{
|
||||
return Convert.ToInt32(ConvertByteArrayToInt(GetParametroValue(0x0056)) * Parametros.First(x => x.Registro == 0x0056).Escala);
|
||||
return Convert.ToInt32(ConvertByteArrayToInt(GetParametroValue(0x0056)) * ((parametros.Any(x => x.Registro == 0x0056) ? parametros.First(x => x.Registro == 0x0056).Escala : BLD300RService.Parametros.First(x => x.Registro == 0x0056).Escala)));
|
||||
}
|
||||
}
|
||||
public int RPM
|
||||
{
|
||||
get
|
||||
{
|
||||
return Convert.ToInt32(ConvertByteArrayToInt(GetParametroValue(0x005F)) * Parametros.First(x => x.Registro == 0x005F).Escala);
|
||||
return Convert.ToInt32(ConvertByteArrayToInt(GetParametroValue(0x005F)) * ((parametros.Any(x => x.Registro == 0x005F) ? parametros.First(x => x.Registro == 0x005F).Escala : BLD300RService.Parametros.First(x => x.Registro == 0x005F).Escala)));
|
||||
}
|
||||
}
|
||||
public bool Ativado
|
||||
|
|
@ -109,7 +107,11 @@ namespace AgroBase.Models
|
|||
{
|
||||
get
|
||||
{
|
||||
var P_V = Parametros.First(x => x.Registro == 0x00C8);
|
||||
var P_V = parametros.FirstOrDefault(x => x.Registro == 0x00C8);
|
||||
if (P_V == null)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
double tensao = ConvertByteArrayToFloat(P_V.Valor);
|
||||
return tensao;
|
||||
}
|
||||
|
|
@ -118,7 +120,11 @@ namespace AgroBase.Models
|
|||
{
|
||||
get
|
||||
{
|
||||
var P_T = Parametros.First(x => x.Registro == 0x00d2);
|
||||
var P_T = parametros.FirstOrDefault(x => x.Registro == 0x00d2);
|
||||
if (P_T == null)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
double temperatura = ConvertByteArrayToFloat(P_T.Valor);
|
||||
return temperatura;
|
||||
}
|
||||
|
|
@ -127,12 +133,16 @@ namespace AgroBase.Models
|
|||
{
|
||||
get
|
||||
{
|
||||
var P_A = Parametros.First(x => x.Registro == 0x0096);
|
||||
var P_A = parametros.FirstOrDefault(x => x.Registro == 0x0096);
|
||||
if (P_A == null)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
double corrente = ConvertByteArrayToFloat(P_A.Valor);
|
||||
return corrente;
|
||||
}
|
||||
}
|
||||
public List<BLDParametrosRequisitar> parametros { get; set; }
|
||||
public List<Services.BLD300RService.BLDParametrosRequisitar> parametros { get; set; }
|
||||
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -234,5 +234,13 @@ namespace AgroBase.Models
|
|||
ArquivoModelo3D = 14,
|
||||
}
|
||||
|
||||
public enum TipoConexao
|
||||
{
|
||||
Desconhecido = 0,
|
||||
PortaCOM = 1,
|
||||
USB = 2,
|
||||
Ethernet = 3,
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -58,6 +58,7 @@ namespace AgroBase.Models
|
|||
public bool AguardaResposta { get; set; } = false;
|
||||
public int TimeoutResposta { get; set; } = 1000;
|
||||
public bool Enviado { get; set; } = false;
|
||||
public bool ErroEnvio { get; set; } = false;
|
||||
}
|
||||
|
||||
public enum ModosOperacao
|
||||
|
|
|
|||
|
|
@ -109,7 +109,7 @@ namespace AgroBase.Services
|
|||
Chave = "Enabled",
|
||||
Descricao = "Verifica/Define o status do motor",
|
||||
Escala = 1,
|
||||
LeituraLoop = true,
|
||||
LeituraLoop = false,
|
||||
LeituraGeral = true,
|
||||
N_Registros = 0x0001,
|
||||
Registro = 0x0066
|
||||
|
|
@ -119,7 +119,7 @@ namespace AgroBase.Services
|
|||
Chave = "Breaked",
|
||||
Descricao = "Verifica/Define o status do freio do motor",
|
||||
Escala = 1,
|
||||
LeituraLoop = true,
|
||||
LeituraLoop = false,
|
||||
LeituraGeral = true,
|
||||
N_Registros = 0x0001,
|
||||
Registro = 0x006A
|
||||
|
|
@ -129,7 +129,7 @@ namespace AgroBase.Services
|
|||
Chave = "Direction",
|
||||
Descricao = "Verifica/Define o sentido de giro do motor",
|
||||
Escala = 1,
|
||||
LeituraLoop = true,
|
||||
LeituraLoop = false,
|
||||
LeituraGeral = true,
|
||||
N_Registros = 0x0001,
|
||||
Registro = 0x006D
|
||||
|
|
@ -259,13 +259,18 @@ namespace AgroBase.Services
|
|||
|
||||
var comando = ModbusService.ComandoGetParametro(Addr, Parametro);
|
||||
|
||||
if (!await EnviarComando(_ethernetService, comando))
|
||||
bool envioBemSucedido = await EnviarComando(_ethernetService, comando);
|
||||
if (!envioBemSucedido)
|
||||
{
|
||||
break;
|
||||
Console.WriteLine($"Falha ao enviar dados para o dispositivo de endereço {Addr}.");
|
||||
continue;
|
||||
}
|
||||
|
||||
// Recebe a resposta via Ethernet
|
||||
var resposta = await _ethernetService.ReceiveDataAsync(7);
|
||||
|
||||
SerialService.MostrarComandoResposta(T_Code.Bld, comando, resposta);
|
||||
|
||||
DecifrarResposta(resposta, Parametro, Addr);
|
||||
|
||||
if (DadosLeitura.Any(x => x.Endereco == Addr && x.Iniciado))
|
||||
|
|
@ -308,19 +313,21 @@ namespace AgroBase.Services
|
|||
{
|
||||
// Envia o comando via Ethernet
|
||||
Comando.ErroEnvio = !await EnviarComando(_ethernetService, comando);
|
||||
Comando.Enviado = true;
|
||||
Comando.Enviado = !Comando.AguardaResposta;
|
||||
|
||||
// Recebe a resposta via Ethernet, independentemente de precisar processá-la ou não
|
||||
byte[] resposta = await _ethernetService.ReceiveDataAsync(7, 1000); // Timeout ajustável, aqui 1 segundo
|
||||
byte[] resposta = await _ethernetService.ReceiveDataAsync(7, Comando.TimeoutResposta); // Timeout ajustável, aqui 1 segundo
|
||||
|
||||
SerialService.MostrarComandoResposta(T_Code.Bld, comando, resposta);
|
||||
|
||||
if (Comando.AguardaResposta)
|
||||
{
|
||||
// Processa a resposta, pois é esperada
|
||||
bool Respondido = DecifrarResposta(resposta, Comando.Parametro, Comando.Endereco);
|
||||
Comando.Enviado = Respondido;
|
||||
if (!Respondido)
|
||||
{
|
||||
RegisrarErrosComunicacao(Comando.Endereco, $"Timeout ou erro ao receber resposta. GET={Comando.Get}, Parametro={Comando.Parametro.Chave}, Valor={Comando.Valor}");
|
||||
Comando.Enviado = false;
|
||||
Comando.Momento = DateTime.Now.AddMilliseconds(500); // Retenta após um pequeno intervalo
|
||||
}
|
||||
}
|
||||
|
|
@ -329,6 +336,8 @@ namespace AgroBase.Services
|
|||
// Descarte da resposta, pois não era esperada
|
||||
Console.WriteLine($"Resposta descartada para comando que não aguardava resposta.");
|
||||
}
|
||||
|
||||
//await Task.Delay(100);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
|
@ -342,30 +351,27 @@ namespace AgroBase.Services
|
|||
|
||||
private static void DefinirDispositivo(List<string> Mod_IDs)
|
||||
{
|
||||
if (Iniciado)
|
||||
foreach (var Mod_ID in Mod_IDs)
|
||||
{
|
||||
foreach (var Mod_ID in Mod_IDs)
|
||||
var Modulo = Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.FirstOrDefault(x => x.Modulo_ID == Mod_ID);
|
||||
byte Addr = Convert.ToByte(Modulo.MovMotor.Endereco.Replace("0x", ""), 16);
|
||||
|
||||
if (DadosLeitura.Any(x => x.Endereco == Addr && !x.Configurado))
|
||||
{
|
||||
var Modulo = Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.FirstOrDefault(x => x.Modulo_ID == Mod_ID);
|
||||
byte Addr = Convert.ToByte(Modulo.MovMotor.Endereco.Replace("0x", ""), 16);
|
||||
ConfigurarDriver(Addr);
|
||||
}
|
||||
|
||||
if (DadosLeitura.Any(x => x.Endereco == Addr && !x.Configurado))
|
||||
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()
|
||||
{
|
||||
ConfigurarDriver(Addr);
|
||||
}
|
||||
|
||||
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()
|
||||
{
|
||||
PortaCOM = _ethernetService != null ? _ethernetService._ipAddress : "N/A",
|
||||
Dispositivo = T_Code.Bld,
|
||||
Erro = leitura.CodigoAlarme > 0,
|
||||
Versao = leitura.Versao.ToString(),
|
||||
Mod_ID = Mod_ID,
|
||||
});
|
||||
}
|
||||
Endereco = _ethernetService != null ? _ethernetService._ipAddress : "N/A",
|
||||
Dispositivo = T_Code.Bld,
|
||||
Erro = leitura.CodigoAlarme > 0,
|
||||
Versao = leitura.Versao.ToString(),
|
||||
Mod_ID = Mod_ID,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -399,20 +405,36 @@ namespace AgroBase.Services
|
|||
DadosLeitura.Add(Leitura);
|
||||
}
|
||||
|
||||
BLDParametrosRequisitar _parametro = Leitura.parametros.FirstOrDefault(x => x.Registro == Parametro.Registro);
|
||||
if (_parametro == null)
|
||||
{
|
||||
_parametro = new BLDParametrosRequisitar()
|
||||
{
|
||||
Registro = Parametro.Registro,
|
||||
Escala = Parametro.Escala,
|
||||
Valor = null
|
||||
};
|
||||
Leitura.parametros.Add(_parametro);
|
||||
}
|
||||
|
||||
if (resposta.Length > 3)
|
||||
{
|
||||
if (Parametros.Any(x => 0x03 == resposta[1]))
|
||||
// GET
|
||||
if (resposta[1] == 0x03)
|
||||
{
|
||||
int num_registros = resposta[2];
|
||||
byte[] bytes_resposta = resposta.Skip(3).Take(num_registros).ToArray();
|
||||
|
||||
Parametro.Valor = bytes_resposta;
|
||||
_parametro.Valor = bytes_resposta;
|
||||
Leitura.UltimoComandoRecebido = DateTime.Now;
|
||||
return true;
|
||||
}
|
||||
else if (Parametros.Any(x => 0x06 == resposta[1]))
|
||||
// SET
|
||||
else if (resposta[1] == 0x06)
|
||||
{
|
||||
Parametro.Valor = resposta.Skip(4).Take(2).ToArray();
|
||||
_parametro.Valor = resposta.Skip(4).Take(2).ToArray();
|
||||
Leitura.UltimoComandoRecebido = DateTime.Now;
|
||||
return true;
|
||||
}
|
||||
|
|
@ -503,7 +525,7 @@ namespace AgroBase.Services
|
|||
AguardaResposta = true,
|
||||
Parametro = Parametro,
|
||||
Get = true,
|
||||
TimeoutResposta = 300
|
||||
TimeoutResposta = 500
|
||||
};
|
||||
AdicionarComandoNaFila(Comando);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -83,9 +83,9 @@ namespace AgroBase.Comum
|
|||
var DispositivosTipo = SerialService.DispositivosMapeados.Where(x => x.Dispositivo == Dispositivo).ToList();
|
||||
for (int i = 0; i < DispositivosTipo.Count(); i++)
|
||||
{
|
||||
if (!cmbPorta.Items.Contains(DispositivosTipo[i].PortaCOM))
|
||||
if (!cmbPorta.Items.Contains(DispositivosTipo[i].Endereco))
|
||||
{
|
||||
string PortaCom = DispositivosTipo[i].PortaCOM;
|
||||
string PortaCom = DispositivosTipo[i].Endereco;
|
||||
var _Porta = new SerialPort() { PortName = PortaCom, BaudRate = 115200 };
|
||||
try
|
||||
{
|
||||
|
|
|
|||
|
|
@ -118,6 +118,7 @@ public class EthernetService
|
|||
{
|
||||
try
|
||||
{
|
||||
await FlushBufferAsync(); // Limpa o buffer antes de enviar
|
||||
await _networkStream.WriteAsync(data, 0, data.Length);
|
||||
await _networkStream.FlushAsync();
|
||||
return true;
|
||||
|
|
@ -138,7 +139,6 @@ public class EthernetService
|
|||
public async Task<byte[]> ReceiveDataAsync(int expectedLength, int timeoutMilliseconds = 1000)
|
||||
{
|
||||
var buffer = new byte[expectedLength];
|
||||
|
||||
try
|
||||
{
|
||||
var readTask = _networkStream.ReadAsync(buffer, 0, expectedLength); // Tarefa de leitura sem o token
|
||||
|
|
@ -165,6 +165,26 @@ public class EthernetService
|
|||
}
|
||||
}
|
||||
|
||||
public async Task FlushBufferAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_networkStream.DataAvailable) // Verifica se há dados pendentes no buffer
|
||||
{
|
||||
var tempBuffer = new byte[1024]; // Buffer temporário para leitura
|
||||
while (_networkStream.DataAvailable)
|
||||
{
|
||||
await _networkStream.ReadAsync(tempBuffer, 0, tempBuffer.Length);
|
||||
}
|
||||
Console.WriteLine("Buffer limpo.");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"Erro ao limpar buffer: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
// Método para verificar a conexão (pode ser usado para um "heartbeat")
|
||||
public async Task<bool> CheckConnectionAsync()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -67,7 +67,7 @@ namespace AgroBase.Services
|
|||
{
|
||||
SerialService.DispositivosMapeados.Add(new SerialService.DispositivoDetalhesModel()
|
||||
{
|
||||
PortaCOM = PortaGPS.PortName,
|
||||
Endereco = PortaGPS.PortName,
|
||||
Dispositivo = T_Code.Gps,
|
||||
Erro = !Iniciado,
|
||||
Versao = "1",
|
||||
|
|
|
|||
|
|
@ -195,7 +195,7 @@ namespace AgroBase.Services
|
|||
{
|
||||
SerialService.DispositivosMapeados.Add(new SerialService.DispositivoDetalhesModel()
|
||||
{
|
||||
PortaCOM = "USB",
|
||||
Endereco = "USB",
|
||||
Dispositivo = T_Code.Knt,
|
||||
Erro = !Iniciado,
|
||||
Versao = "1",
|
||||
|
|
|
|||
|
|
@ -215,7 +215,7 @@ namespace AgroBase.Services
|
|||
{
|
||||
SerialService.DispositivosMapeados.Add(new SerialService.DispositivoDetalhesModel()
|
||||
{
|
||||
PortaCOM = _PortaLoRa.PortName,
|
||||
Endereco = _PortaLoRa.PortName,
|
||||
Dispositivo = T_Code.Lra,
|
||||
Erro = !Iniciado,
|
||||
Versao = "220"
|
||||
|
|
|
|||
|
|
@ -4,7 +4,6 @@ using System.Collections;
|
|||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using static AgroBase.Models.Enums;
|
||||
|
|
@ -98,21 +97,20 @@ namespace AgroBase.Services
|
|||
DataSended = Convert.ToByte("43");
|
||||
|
||||
// Envia comando relevante para verificar o dispositivo
|
||||
bool envioBemSucedido = await SendRelevantData(Addr, QueryCommand[DataSended]);
|
||||
(bool envioBemSucedido, byte[] comando) = await SendRelevantData(Addr, QueryCommand[DataSended]);
|
||||
if (!envioBemSucedido)
|
||||
{
|
||||
Console.WriteLine($"Falha ao enviar dados para o dispositivo de endereço {Addr}.");
|
||||
continue;
|
||||
}
|
||||
|
||||
var resposta = await _ethernetService.ReceiveDataAsync(11);
|
||||
|
||||
await ProcessarDadosRecebidosAsync();
|
||||
SerialService.MostrarComandoResposta(T_Code.Mks, comando, resposta);
|
||||
|
||||
DecifrarResposta(resposta);
|
||||
|
||||
// Aguarda resposta do dispositivo com controle de timeout
|
||||
bool respondido = DadosLeitura.Any(x => x.Endereco == Addr && x.Iniciado);
|
||||
|
||||
if (respondido)
|
||||
if (DadosLeitura.Any(x => x.Endereco == Addr && x.Iniciado))
|
||||
{
|
||||
Mod_IDs.Add(Modulo.Modulo_ID);
|
||||
}
|
||||
|
|
@ -172,7 +170,7 @@ namespace AgroBase.Services
|
|||
{
|
||||
SerialService.DispositivosMapeados.Add(new SerialService.DispositivoDetalhesModel()
|
||||
{
|
||||
PortaCOM = _ethernetService != null ? _ethernetService._ipAddress : "N/A",
|
||||
Endereco = _ethernetService != null ? _ethernetService._ipAddress : "N/A",
|
||||
Dispositivo = T_Code.Mks,
|
||||
Erro = (Leitura.Mensagem ?? "") != "",
|
||||
Versao = (Leitura.FV ?? "").ToString(),
|
||||
|
|
@ -202,12 +200,12 @@ namespace AgroBase.Services
|
|||
return;
|
||||
}
|
||||
|
||||
TaxaAmostragem = Referenciando ? 200 : 1000;
|
||||
TaxaAmostragem = 1000;
|
||||
|
||||
if (Referenciando)
|
||||
{
|
||||
AdicionarComandoNaFila(MontarComandoRequisicaoPulsos(AddrRef));
|
||||
AdicionarComandoNaFila(MontarComandoRequisicaoIO(AddrRef));
|
||||
//AdicionarComandoNaFila(MontarComandoRequisicaoPulsos(AddrRef));
|
||||
//AdicionarComandoNaFila(MontarComandoRequisicaoIO(AddrRef));
|
||||
}
|
||||
else if (Variaveis.OperacaoEmAndamento.DispMvd != null)
|
||||
{
|
||||
|
|
@ -511,74 +509,67 @@ namespace AgroBase.Services
|
|||
|
||||
public static async Task EnviarComandoControle(MKS057ComandoModel Comando)
|
||||
{
|
||||
byte Addr = Comando.Endereco;
|
||||
|
||||
// Configura parâmetros de controle localmente antes de enviar o comando
|
||||
if (!Comando.Get)
|
||||
{
|
||||
if (!_Angulo.ContainsKey(Addr))
|
||||
{
|
||||
_Angulo.Add(Addr, "0");
|
||||
}
|
||||
if (!_Velocidade.ContainsKey(Addr))
|
||||
{
|
||||
_Velocidade.Add(Addr, "0");
|
||||
}
|
||||
if (!_Sentido.ContainsKey(Addr))
|
||||
{
|
||||
_Sentido.Add(Addr, Comando._Sentido);
|
||||
}
|
||||
|
||||
_Angulo[Addr] = ConverterAnguloParaValor(Comando.Angulo).ToString();
|
||||
_Velocidade[Addr] = Comando.Velocidade.ToString();
|
||||
_ModoControle = Comando.ModoControle;
|
||||
_Sentido[Addr] = Comando._Sentido;
|
||||
}
|
||||
|
||||
DataSended = Comando.Comando;
|
||||
|
||||
// Envia o comando via Ethernet
|
||||
bool sucessoEnvio = await SendRelevantData(Addr, QueryCommand[DataSended]);
|
||||
Comando.Enviado = sucessoEnvio;
|
||||
|
||||
if (!sucessoEnvio)
|
||||
{
|
||||
RegisrarErrosComunicacao(Addr, "Erro ao enviar dados via Ethernet");
|
||||
return;
|
||||
}
|
||||
|
||||
await ProcessarDadosRecebidosAsync();
|
||||
|
||||
Respondido = !Comando.AguardaResposta;
|
||||
|
||||
// Se o comando não aguarda resposta, finaliza aqui
|
||||
if (Respondido)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Configura o token de cancelamento para controlar o timeout de resposta
|
||||
var cts = new CancellationTokenSource();
|
||||
cts.CancelAfter(Comando.TimeoutResposta);
|
||||
|
||||
try
|
||||
{
|
||||
while (!Respondido && !cts.Token.IsCancellationRequested)
|
||||
byte Addr = Comando.Endereco;
|
||||
|
||||
// Configura parâmetros de controle localmente antes de enviar o comando
|
||||
if (!Comando.Get)
|
||||
{
|
||||
await Task.Delay(100, cts.Token);
|
||||
if (!_Angulo.ContainsKey(Addr))
|
||||
{
|
||||
_Angulo.Add(Addr, "0");
|
||||
}
|
||||
if (!_Velocidade.ContainsKey(Addr))
|
||||
{
|
||||
_Velocidade.Add(Addr, "0");
|
||||
}
|
||||
if (!_Sentido.ContainsKey(Addr))
|
||||
{
|
||||
_Sentido.Add(Addr, Comando._Sentido);
|
||||
}
|
||||
|
||||
_Angulo[Addr] = ConverterAnguloParaValor(Comando.Angulo).ToString();
|
||||
_Velocidade[Addr] = Comando.Velocidade.ToString();
|
||||
_ModoControle = Comando.ModoControle;
|
||||
_Sentido[Addr] = Comando._Sentido;
|
||||
}
|
||||
|
||||
if (!Respondido)
|
||||
DataSended = Comando.Comando;
|
||||
|
||||
// Envia o comando via Ethernet
|
||||
(bool sucessoEnvio, byte[] comando) = await SendRelevantData(Addr, QueryCommand[DataSended]);
|
||||
Comando.ErroEnvio = !sucessoEnvio;
|
||||
Comando.Enviado = !Comando.AguardaResposta;
|
||||
|
||||
// Recebe a resposta via Ethernet, independentemente de precisar processá-la ou não
|
||||
byte[] resposta = await _ethernetService.ReceiveDataAsync(7, Comando.TimeoutResposta); // Timeout ajustável, aqui 1 segundo
|
||||
|
||||
SerialService.MostrarComandoResposta(T_Code.Bld, comando, resposta);
|
||||
|
||||
if (Comando.AguardaResposta)
|
||||
{
|
||||
RegisrarErrosComunicacao(Addr, $"Timeout ao receber resposta. GET={Comando.Get}, Parametro={Comando.Comando}");
|
||||
Comando.Enviado = false;
|
||||
Comando.Momento = DateTime.Now.AddMilliseconds(500);
|
||||
// Processa a resposta, pois é esperada
|
||||
bool Respondido = DecifrarResposta(resposta);
|
||||
Comando.Enviado = Respondido;
|
||||
if (!Respondido)
|
||||
{
|
||||
RegisrarErrosComunicacao(Addr, $"Timeout ao receber resposta. GET={Comando.Get}, Parametro={Comando.Comando}");
|
||||
Comando.Momento = DateTime.Now.AddMilliseconds(500);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Descarte da resposta, pois não era esperada
|
||||
Console.WriteLine($"Resposta descartada para comando que não aguardava resposta.");
|
||||
}
|
||||
}
|
||||
catch (TaskCanceledException)
|
||||
catch (Exception ex)
|
||||
{
|
||||
RegisrarErrosComunicacao(Addr, "Timeout atingido durante a espera pela resposta do comando");
|
||||
// Log de erro
|
||||
RegisrarErrosComunicacao(Comando.Endereco, $"Erro ao enviar comando: {ex.Message}");
|
||||
Comando.Enviado = false;
|
||||
Comando.Momento = DateTime.Now.AddMilliseconds(500);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -661,56 +652,41 @@ namespace AgroBase.Services
|
|||
|
||||
#region METODOS PRINCIPAIS
|
||||
|
||||
private static async Task<bool> WriteByteToEthernetAsync(byte[] data, byte start, byte length)
|
||||
private static async Task<(bool, byte[])> WriteByteToEthernetAsync(byte[] data, byte start, byte length)
|
||||
{
|
||||
byte Addr = data[1];
|
||||
|
||||
if (_ethernetService == null || !_ethernetService.IsConnected)
|
||||
{
|
||||
RegisrarErrosComunicacao(Addr, "Conexão Ethernet não está definida ou não está conectada");
|
||||
return false;
|
||||
return (false, data);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
bool sucesso = await _ethernetService.SendDataAsync(data.Skip(start).Take(length).ToArray());
|
||||
if (sucesso)
|
||||
{
|
||||
txDisplay(data);
|
||||
}
|
||||
else
|
||||
{
|
||||
RegisrarErrosComunicacao(Addr, "Erro ao enviar dados via Ethernet");
|
||||
}
|
||||
return sucesso;
|
||||
return (sucesso, data);
|
||||
}
|
||||
catch
|
||||
{
|
||||
RegisrarErrosComunicacao(Addr, "Erro ao enviar dados para o dispositivo via Ethernet");
|
||||
return false;
|
||||
return (false, data);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task ProcessarDadosRecebidosAsync()
|
||||
private static bool DecifrarResposta(byte[] resposta)
|
||||
{
|
||||
if (_ethernetService != null && _ethernetService.IsConnected)
|
||||
{
|
||||
SerialBuffer_RX = new byte[11];
|
||||
var resposta = await _ethernetService.ReceiveDataAsync(SerialBuffer_RX.Length, 10000);
|
||||
SerialBuffer_RX = new byte[11];
|
||||
|
||||
Console.WriteLine("resposta: " + resposta?.ToString());
|
||||
|
||||
if (resposta != null && resposta.Length > 0 && resposta.Length <= SerialBuffer_RX.Length)
|
||||
{
|
||||
SerialBuffer_RX = resposta; // Armazena a resposta recebida
|
||||
Data_Number = resposta.Length;
|
||||
Text_display();
|
||||
}
|
||||
}
|
||||
else
|
||||
if (resposta != null && resposta.Length > 0 && resposta.Length <= SerialBuffer_RX.Length)
|
||||
{
|
||||
Console.WriteLine("Ethernet não está conectada ou o serviço não está definido.");
|
||||
SerialBuffer_RX = resposta; // Armazena a resposta recebida
|
||||
Data_Number = resposta.Length;
|
||||
Text_display();
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void Text_display()
|
||||
|
|
@ -1376,7 +1352,7 @@ namespace AgroBase.Services
|
|||
}
|
||||
|
||||
|
||||
private static async Task<bool> SendRelevantData(byte Addr, int data) // Verifica o tipo de dados e envia
|
||||
private static async Task<(bool, byte[])> SendRelevantData(byte Addr, int data) // Verifica o tipo de dados e envia
|
||||
{
|
||||
ushort SpeedText;
|
||||
ushort SpeedText2;
|
||||
|
|
@ -2305,7 +2281,7 @@ namespace AgroBase.Services
|
|||
catch
|
||||
{
|
||||
MessageBox.Show("Erro ao gravar parametros de limite");
|
||||
return false;
|
||||
return (false, Buffer);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -2320,10 +2296,10 @@ namespace AgroBase.Services
|
|||
else
|
||||
{
|
||||
MessageBox.Show("Endereço selecionado é inválido");
|
||||
return false;
|
||||
return (false, Buffer);
|
||||
}
|
||||
|
||||
return true;
|
||||
return (true, Buffer);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
|
|
|||
|
|
@ -85,7 +85,7 @@ namespace AgroBase.Services
|
|||
{
|
||||
SerialService.DispositivosMapeados.Add(new SerialService.DispositivoDetalhesModel()
|
||||
{
|
||||
PortaCOM = ModbusService._PortaModbus.PortName,
|
||||
Endereco = ModbusService._PortaModbus.PortName,
|
||||
Dispositivo = T_Code.Pzm,
|
||||
Erro = !Iniciado,
|
||||
Versao = "17"
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
using AgroBase.Forms;
|
||||
using AgroBase.Models;
|
||||
using OpenCvSharp.Internal.Vectors;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO.Ports;
|
||||
|
|
@ -29,7 +30,29 @@ namespace AgroBase.Services
|
|||
|
||||
public class DispositivoDetalhesModel
|
||||
{
|
||||
public string PortaCOM { get; set; }
|
||||
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; }
|
||||
|
|
@ -76,7 +99,7 @@ namespace AgroBase.Services
|
|||
}
|
||||
else
|
||||
{
|
||||
IDispositivosService dispositivoService = Variaveis.DispositivosConectados.FirstOrDefault(x => x.Dispositivo == Dispositivo && x._Porta.PortName == PortaCOM);
|
||||
IDispositivosService dispositivoService = Variaveis.DispositivosConectados.FirstOrDefault(x => x.Dispositivo == Dispositivo && x._Porta.PortName == Endereco);
|
||||
if (dispositivoService != null)
|
||||
{
|
||||
if (!dispositivoService._Porta.IsOpen)
|
||||
|
|
@ -263,7 +286,7 @@ namespace AgroBase.Services
|
|||
var dispositivosMapeados = DispositivosMapeados.ToList();
|
||||
|
||||
var Portas = SerialPort.GetPortNames();
|
||||
var PortasNaoMapeadas = Portas.Where(x => !dispositivosMapeados.Select(y => y.PortaCOM).Contains(x)).ToList();
|
||||
var PortasNaoMapeadas = Portas.Where(x => !dispositivosMapeados.Select(y => y.Endereco).Contains(x)).ToList();
|
||||
List<string> PortasSemResposta = new List<string>();
|
||||
|
||||
for (int i = 0; i < PortasNaoMapeadas.Count(); i++)
|
||||
|
|
@ -385,7 +408,7 @@ namespace AgroBase.Services
|
|||
await ProcurarDispositivosEthernet();
|
||||
}
|
||||
|
||||
var DispositivosRemovidos = dispositivosMapeados.Where(x => x.PortaCOM != "USB" && !Portas.Contains(x.PortaCOM)).ToList();
|
||||
var DispositivosRemovidos = dispositivosMapeados.Where(x => x.Tipo == TipoConexao.PortaCOM && !Portas.Contains(x.Endereco)).ToList();
|
||||
foreach (var Dispositivo in DispositivosRemovidos)
|
||||
{
|
||||
DispositivosMapeados.Remove(Dispositivo);
|
||||
|
|
@ -465,7 +488,7 @@ namespace AgroBase.Services
|
|||
{
|
||||
DispositivosMapeados.Add(new DispositivoDetalhesModel()
|
||||
{
|
||||
PortaCOM = Porta.PortName,
|
||||
Endereco = Porta.PortName,
|
||||
Dispositivo = Dispositivo,
|
||||
Erro = Verificacao == F_Code.Err,
|
||||
Versao = Versao,
|
||||
|
|
@ -590,7 +613,7 @@ namespace AgroBase.Services
|
|||
return false;
|
||||
}
|
||||
|
||||
if (DispositivosMapeados.Any(x => x.Dispositivo == T_Code.Mvd) && porta.PortName != DispositivosMapeados.First(x => x.Dispositivo == T_Code.Mvd).PortaCOM)
|
||||
if (DispositivosMapeados.Any(x => x.Dispositivo == T_Code.Mvd) && porta.PortName != DispositivosMapeados.First(x => x.Dispositivo == T_Code.Mvd).Endereco)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
|
@ -888,5 +911,14 @@ namespace AgroBase.Services
|
|||
}
|
||||
}
|
||||
|
||||
public static void MostrarComandoResposta(T_Code tipo, byte[] comando, byte[] resposta)
|
||||
{
|
||||
bool showCommands = true;
|
||||
if (showCommands)
|
||||
{
|
||||
Console.WriteLine(tipo.ToString() + " - TX: " + string.Join(" ", comando.Select(x => x.ToString("x"))) + ", RX: " + string.Join(" ", (resposta != null ? resposta : new byte[] { }).Select(x => x.ToString("x"))));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -59,7 +59,7 @@ namespace AgroBase.Services
|
|||
{
|
||||
SerialService.DispositivosMapeados.Add(new SerialService.DispositivoDetalhesModel()
|
||||
{
|
||||
PortaCOM = ModbusService._PortaModbus.PortName,
|
||||
Endereco = ModbusService._PortaModbus.PortName,
|
||||
Dispositivo = T_Code.A05,
|
||||
Erro = !Iniciado,
|
||||
Versao = "1"
|
||||
|
|
|
|||
|
|
@ -100,7 +100,7 @@ namespace AgroBase.Services
|
|||
{
|
||||
SerialService.DispositivosMapeados.Add(new SerialService.DispositivoDetalhesModel()
|
||||
{
|
||||
PortaCOM = ModbusService._PortaModbus.PortName,
|
||||
Endereco = ModbusService._PortaModbus.PortName,
|
||||
Dispositivo = T_Code.Wit,
|
||||
Erro = !Iniciado,
|
||||
Versao = DadosLeitura.Versao,
|
||||
|
|
|
|||
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
|
|
@ -25,7 +25,7 @@
|
|||
<meta name="viewport" content="width=device-width,
|
||||
initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
|
||||
<style>
|
||||
#map_bb24316082a755985574b8eccdf68f8d {
|
||||
#map_fa1fb12b82d67d7b576b4a6c72021b43 {
|
||||
position: relative;
|
||||
width: 100.0%;
|
||||
height: 100.0%;
|
||||
|
|
@ -39,14 +39,14 @@
|
|||
<body>
|
||||
|
||||
|
||||
<div class="folium-map" id="map_bb24316082a755985574b8eccdf68f8d" ></div>
|
||||
<div class="folium-map" id="map_fa1fb12b82d67d7b576b4a6c72021b43" ></div>
|
||||
|
||||
</body>
|
||||
<script>
|
||||
|
||||
|
||||
var map_bb24316082a755985574b8eccdf68f8d = L.map(
|
||||
"map_bb24316082a755985574b8eccdf68f8d",
|
||||
var map_fa1fb12b82d67d7b576b4a6c72021b43 = L.map(
|
||||
"map_fa1fb12b82d67d7b576b4a6c72021b43",
|
||||
{
|
||||
center: [0.0, 0.0],
|
||||
crs: L.CRS.EPSG3857,
|
||||
|
|
@ -60,13 +60,13 @@
|
|||
|
||||
|
||||
|
||||
var tile_layer_ba7df28846484ea0aeeca5cdafc6169c = L.tileLayer(
|
||||
var tile_layer_fc2a48162ee97dadb749ec5c9d4585d1 = 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_ba7df28846484ea0aeeca5cdafc6169c.addTo(map_bb24316082a755985574b8eccdf68f8d);
|
||||
tile_layer_fc2a48162ee97dadb749ec5c9d4585d1.addTo(map_fa1fb12b82d67d7b576b4a6c72021b43);
|
||||
|
||||
</script>
|
||||
|
||||
|
|
@ -87,7 +87,7 @@
|
|||
}
|
||||
trajeto_json_add({"features": []});
|
||||
|
||||
trajeto_json.addTo(map_bb24316082a755985574b8eccdf68f8d);
|
||||
trajeto_json.addTo(map_fa1fb12b82d67d7b576b4a6c72021b43);
|
||||
|
||||
function adicionarGeometria(novaGeometria) {
|
||||
trajeto_json.addData(novaGeometria);
|
||||
|
|
@ -145,7 +145,7 @@
|
|||
|
||||
var marcadorDinamico = L.marker([0, 0], {
|
||||
icon: customIcon
|
||||
}).addTo(map_bb24316082a755985574b8eccdf68f8d);
|
||||
}).addTo(map_fa1fb12b82d67d7b576b4a6c72021b43);
|
||||
|
||||
// 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_bb24316082a755985574b8eccdf68f8d.setView(novaPosicao, map_bb24316082a755985574b8eccdf68f8d.getZoom());
|
||||
map_fa1fb12b82d67d7b576b4a6c72021b43.setView(novaPosicao, map_fa1fb12b82d67d7b576b4a6c72021b43.getZoom());
|
||||
});
|
||||
|
||||
function calcularOrientacao(P1latitude, P1longitude, P2latitude, P2longitude) {
|
||||
|
|
|
|||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loading…
Reference in New Issue