From 746ca24ee29cea8a3b9cfb8cb92b413fcd3812e6 Mon Sep 17 00:00:00 2001 From: Diego Freitas Date: Mon, 8 Jun 2026 10:42:52 -0300 Subject: [PATCH] ajustes can ethernet para mks --- .../AgroBase/Services/CanServiceEthernet.cs | 53 ++++++++++++++++--- 1 file changed, 47 insertions(+), 6 deletions(-) diff --git a/AgroBase/AgroBase/Services/CanServiceEthernet.cs b/AgroBase/AgroBase/Services/CanServiceEthernet.cs index 0d8e404ed..362b4e3ec 100644 --- a/AgroBase/AgroBase/Services/CanServiceEthernet.cs +++ b/AgroBase/AgroBase/Services/CanServiceEthernet.cs @@ -53,6 +53,9 @@ namespace AgroBase.Services private readonly ConcurrentDictionary _roteadoresRegistrados = new ConcurrentDictionary(); private readonly List MensagensPendentes = new List(); + private readonly ConcurrentDictionary _cooldownPorId = new ConcurrentDictionary(); + 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,