ajustes can ethernet para mks

This commit is contained in:
Diego Freitas 2026-06-08 10:42:52 -03:00
parent 42fbf5924b
commit 746ca24ee2
1 changed files with 47 additions and 6 deletions

View File

@ -53,6 +53,9 @@ namespace AgroBase.Services
private readonly ConcurrentDictionary<uint, bool> _roteadoresRegistrados = new ConcurrentDictionary<uint, bool>();
private readonly List<CanMessage> MensagensPendentes = new List<CanMessage>();
private readonly ConcurrentDictionary<uint, DateTime> _cooldownPorId = new ConcurrentDictionary<uint, DateTime>();
private static readonly TimeSpan COOLDOWN_MKS = TimeSpan.FromMilliseconds(20);
private uint? _ultimoIdEnviado = null;
private bool DebugMode = false;
@ -302,6 +305,21 @@ namespace AgroBase.Services
return baseLista.Where(x => x.IdTx == proximoId).OrderBy(x => x.Momento).FirstOrDefault();
}
private bool PodeEnviarAgora(CanMessage m)
{
if (m.Dispositivo != T_Code.Mks)
return true;
var now = DateTime.UtcNow;
var due = _cooldownPorId.GetOrAdd(m.IdTx, DateTime.MinValue);
if (now < due)
return false;
_cooldownPorId[m.IdTx] = now + COOLDOWN_MKS;
return true;
}
private async Task EnviarCAN()
{
if (!IsConnected) return;
@ -316,6 +334,12 @@ namespace AgroBase.Services
var msg = ObterProximaMensagem();
if (msg == null) break;
if (sent > 0 && msg.Dispositivo == T_Code.Mks)
break;
if (!PodeEnviarAgora(msg))
break;
byte[] packet = CriarPacoteUsrStandard(msg);
if (!EnviarPacote(packet, msg.IdTx))
@ -552,12 +576,28 @@ namespace AgroBase.Services
lock (_LockMensagens)
{
mensagem = MensagensPendentes.FirstOrDefault(x =>
x.Enviado &&
!x.Respondido &&
x.Dispositivo == dispositivo &&
x.IdRx == id &&
x.DataTx != null &&
(db || data.Length < 2 || x.DataTx.Length < 2 || x.DataTx[1] == data[1]));
{
if (!x.Enviado) return false;
if (x.Respondido) return false;
if (x.Dispositivo != dispositivo) return false;
if (x.IdRx != id) return false;
if (x.DataTx == null || x.DataTx.Length == 0) return false;
if (db)
return true;
// MKS: a resposta deve casar pelo function code.
// TX: [code, ..., crc]
// RX: [code, ..., crc]
if (x.Dispositivo == T_Code.Mks)
return data.Length > 0 && x.funcCodeRx == data[0];
// Demais protocolos antigos
if (data.Length < 2 || x.DataTx.Length < 2)
return true;
return x.DataTx[1] == data[1];
});
}
if (mensagem == null)
@ -565,6 +605,7 @@ namespace AgroBase.Services
mensagem = new CanMessage
{
Dispositivo = dispositivo,
IdTx = id,
IdRx = id,
funcCodeRx = fCodeRx,
DataRx = data,