1114 lines
43 KiB
C#
1114 lines
43 KiB
C#
using AgroBase.Models;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using static AgroBase.Models.Enums;
|
|
|
|
namespace AgroBase.Services
|
|
{
|
|
public class OIDService
|
|
{
|
|
public static List<ModbusParametrosModel> Parametros = new List<ModbusParametrosModel>()
|
|
{
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "CodErro",
|
|
Descricao = "Verifica o codigo de erro. Envio (01 04 13 88 00 01 B5 64) retorno (01 04 02 00 00 B9 30)",
|
|
Escala = 1,
|
|
LeituraLoop = true,
|
|
LeituraGeral = true,
|
|
N_Registros = 0x0001,
|
|
Registro = 0x1388,
|
|
LeituraEntrada = true
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "VelocidadeAngular",
|
|
Descricao = "Verifica a velocidade angular do motor em erpm (rpm = erpm / numero de polos). Envio (01 04 13 89 00 02 A4 A5) retorno (01 04 04 00 00 05 41 38 E4) 1345 erpm",
|
|
Escala = 1,
|
|
LeituraLoop = true,
|
|
LeituraGeral = true,
|
|
N_Registros = 0x0002,
|
|
Registro = 0x1389,
|
|
LeituraEntrada = true
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "CicloTrabalho",
|
|
Descricao = "Verifica o ciclo de trabalho, variando de -1000 ~ 1000, onde 1000 equivale a 100% de potencia. Envio (01 04 13 8B 00 01 45 64) retorno (01 04 02 00 64 B8 BD) 100, equivalente a 10%",
|
|
Escala = 10,
|
|
LeituraLoop = true,
|
|
LeituraGeral = true,
|
|
N_Registros = 0x0002,
|
|
Registro = 0x138B,
|
|
LeituraEntrada = true
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "Potencia",
|
|
Descricao = "Verifica a potencia do motor (w). Envio (01 04 13 8C 00 01 F4 A5) retorno (01 04 02 00 00 B9 30) 0w",
|
|
Escala = 1,
|
|
LeituraLoop = true,
|
|
LeituraGeral = true,
|
|
N_Registros = 0x0002,
|
|
Registro = 0x138C,
|
|
LeituraEntrada = true
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "Tensao",
|
|
Descricao = "Verifica a tensao de alimentacao (v). Envio (01 04 13 8D 00 01 A5 65) retorno (01 04 02 00 30 B9 24) 48v",
|
|
Escala = 1,
|
|
LeituraLoop = true,
|
|
LeituraGeral = true,
|
|
N_Registros = 0x0002,
|
|
Registro = 0x138D,
|
|
LeituraEntrada = true
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "CorrenteMotor",
|
|
Descricao = "Verifica a corrente do motor (10 ma). Corrente positiva para Frente, corrente negativa para Tras. Envio (01 04 13 8E 00 01 55 65) retorno (01 04 02 01 A7 F9 1A) 423, ou seja, 4,23A",
|
|
Escala = 100,
|
|
LeituraLoop = true,
|
|
LeituraGeral = true,
|
|
N_Registros = 0x0002,
|
|
Registro = 0x138E,
|
|
LeituraEntrada = true
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "CorrenteBarramento",
|
|
Descricao = "Verifica a corrente do barramento (10 ma). Envio (01 04 13 8F 00 01 04 A5) retorno (01 04 02 00 00 B9 30) 0A",
|
|
Escala = 100,
|
|
LeituraLoop = true,
|
|
LeituraGeral = true,
|
|
N_Registros = 0x0002,
|
|
Registro = 0x138F,
|
|
LeituraEntrada = true
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "Temperatura",
|
|
Descricao = "Verifica a temperatura. Envio (01 04 13 90 00 01 35 63) retorno (01 04 02 00 1B F9 3B) 27 graus",
|
|
Escala = 1,
|
|
LeituraLoop = true,
|
|
LeituraGeral = true,
|
|
N_Registros = 0x0002,
|
|
Registro = 0x1390,
|
|
LeituraEntrada = true
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "Angulo",
|
|
Descricao = "Verifica o angulo (0,01 graus). Envio (01 04 13 91 00 01 64 A3) retorno (01 04 02 00 5A 39 0B) 90, ou seja, 0,9 graus",
|
|
Escala = 100,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0002,
|
|
Registro = 0x1391,
|
|
LeituraEntrada = true
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "Localizacao",
|
|
Descricao = "Verifica a localizacao. Envio (01 04 13 92 00 02 D4 A2) retorno (01 04 04 00 00 70 DA 5F DF) 28890, ou seja, 288,9 graus",
|
|
Escala = 100,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0002,
|
|
Registro = 0x1392,
|
|
LeituraEntrada = true
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "RetornaZeroStatus",
|
|
Descricao = "Realiza leitura do status de retorno a zero. Envio (01 04 13 94 00 01 74 A2) retorno (01 04 02 01 00 B8 A0)",
|
|
Escala = 1,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0001,
|
|
Registro = 0x1394,
|
|
LeituraEntrada = true
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "EntradaZ",
|
|
Descricao = "Leitura da entrada Z. Envio (01 04 13 95 00 01 25 62) retorno (01 04 02 00 00 b9 30) 0, nao encontrado",
|
|
Escala = 1,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0001,
|
|
Registro = 0x1395,
|
|
LeituraEntrada = true
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "ErroHistorico1",
|
|
Descricao = "Verifica o historico de erro 1. Envio (01 04 13 96 00 01 d5 62) retorno (01 04 02 00 00 b9 30) 0, sem erro",
|
|
Escala = 1,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0001,
|
|
Registro = 0x1396,
|
|
LeituraEntrada = true
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "ErroHistorico2",
|
|
Descricao = "Verifica o historico de erro 2",
|
|
Escala = 1,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0001,
|
|
Registro = 0x1397,
|
|
LeituraEntrada = true
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "ErroHistorico3",
|
|
Descricao = "Verifica o historico de erro 3",
|
|
Escala = 1,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0001,
|
|
Registro = 0x1398,
|
|
LeituraEntrada = true
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "ErroHistorico4",
|
|
Descricao = "Verifica o historico de erro 4",
|
|
Escala = 1,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0001,
|
|
Registro = 0x1399,
|
|
LeituraEntrada = true
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "ErroHistorico5",
|
|
Descricao = "Verifica o historico de erro 5",
|
|
Escala = 1,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0001,
|
|
Registro = 0x139A,
|
|
LeituraEntrada = true
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "IO",
|
|
Descricao = "Verifica as entradas IO. Envio (01 04 13 9b 00 01 44 a1) retorno (01 04 02 00 0A 39 37) 0x000A binario e 0b00001010, que esta IN2 e IN4 sao niveis eficazes, IN1 e IN3 sem sinal valido",
|
|
Escala = 1,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0001,
|
|
Registro = 0x139B,
|
|
LeituraEntrada = true
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "E/S",
|
|
Descricao = "Verifica o status da IO de saida. Envio (01 04 13 9c 00 01 f5 60) retorno (01 04 02 00 01 78 F0) saida out1 valida",
|
|
Escala = 1,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0001,
|
|
Registro = 0x139C,
|
|
LeituraEntrada = true
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "Heartbeat",
|
|
Descricao = "Envia o ping de conexao para o driver. Precisa ser enviado a cada metade do TempoVida. Envio (01 06 17 70 00 01 4C 65)",
|
|
Escala = 1,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0001,
|
|
Registro = 0x1770
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "ModoControle",
|
|
Descricao = "Verifica/Define o modo de controle do driver. Envio (01 06 17 71 00 00 DC 65) set controle padrao",
|
|
Escala = 1,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0001,
|
|
Registro = 0x1771
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "ControleCorrente",
|
|
Descricao = "Verifica/Define a corrente de controle em escala de 10 ma. Envio (01 06 17 72 00 64 2D 8E) 100 = 1A",
|
|
Escala = 100,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0001,
|
|
Registro = 0x1772
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "ControleVelocidade",
|
|
Descricao = "Verifica/Define a velocidade de controle em escala de erpm (erpm = rpm * numero de polos). Envio (01 10 17 73 00 02 04 00 00 0F A0 5A E6) 4000rpm",
|
|
Escala = VariaveisEquipamento.NumeroPolosMotor,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0002,
|
|
Registro = 0x1773,
|
|
EscritaMultipla = true,
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "ControleCicloTrabalho",
|
|
Descricao = "Verifica/Define o ciclo de trabalho em escala de -1000 ~ 1000, indicando potencia maxima para traz e para frente. Envio (01 06 17 75 00 64 9C 4F) 100 = 10%",
|
|
Escala = 10,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0001,
|
|
Registro = 0x1775
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "ControlePosicaoAbosuluta",
|
|
Descricao = "Verifica/Define a posicao absoluta de controle em escala de 0,01 graus. Envio (01 10 17 76 00 02 04 00 00 8C A0 FB E9) 36000 = 360 graus",
|
|
Escala = 100,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0002,
|
|
Registro = 0x1776,
|
|
EscritaMultipla = true
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "ControlePosicaoRelativa1",
|
|
Descricao = "Verifica/Define a posicao relativa de controle ao valor alvo anterior em escala de 0,01 graus. Envio (01 10 17 78 00 02 04 00 00 8C A0 7A 65) 36000 = 360 graus",
|
|
Escala = 100,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0002,
|
|
Registro = 0x1778,
|
|
EscritaMultipla = true
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "ControlePosicaoRelativa2",
|
|
Descricao = "Verifica/Define a posicao relativa de controle ao valor alvo atual em escala de 0,01 graus. Envio (01 10 17 7A 00 02 04 00 00 8C A0 FB BC) 36000 = 360 graus",
|
|
Escala = 100,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0002,
|
|
Registro = 0x177A,
|
|
EscritaMultipla = true
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "ControleLocalizacaoAtual",
|
|
Descricao = "Verifica/Define a localizacao atual em 0,01 graus. Envio (01 10 17 7C 00 02 04 00 00 00 00 1F 2E) define posicao atual como 0",
|
|
Escala = 100,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0002,
|
|
Registro = 0x177C,
|
|
EscritaMultipla = true
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "ControleCorrenteFreio",
|
|
Descricao = "Verifica/Define a corrente de freio em escala de 10 ma. Envio (01 06 17 7E 00 64 ED 8D) 100 = 1A",
|
|
Escala = 100,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0001,
|
|
Registro = 0x177E
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "ControleCorrenteFreioMao",
|
|
Descricao = "Verifica/Define a corrente de freio de mao em escala de 10 ma. O sistema forca um angulo especifico para o motor, mantendo-o travado, usar apenas com o motor parado. Envio (01 06 17 7F 00 64 AC 4D) 100 = 1A",
|
|
Escala = 100,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0001,
|
|
Registro = 0x177F
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "RampaSubidaVelocidade",
|
|
Descricao = "Verifica/Define o tempo de rampa em modo velocidade. Envio (01 10 17 80 00 02 04 00 00 07 D0 13 93) aceleracao = 2000 erpm/s2",
|
|
Escala = VariaveisEquipamento.NumeroPolosMotor,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0002,
|
|
Registro = 0x1780,
|
|
EscritaMultipla = true
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "ControleVelocidadeMaxima",
|
|
Descricao = "Verifica/Define a velocidade maxima. Envio (01 10 17 82 00 02 04 00 00 13 88 9C B0) velocidade maxima definida para 5000 rpm",
|
|
Escala = VariaveisEquipamento.NumeroPolosMotor,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0002,
|
|
Registro = 0x1782,
|
|
EscritaMultipla = true
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "ControleAceleracaoMaxima",
|
|
Descricao = "Verifica/Define a aceleracao maxima. Envio (01 10 17 84 00 02 04 00 00 13 88 1C 9A) aceleracao definida para 5000 rpm/s2",
|
|
Escala = VariaveisEquipamento.NumeroPolosMotor,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0002,
|
|
Registro = 0x1784,
|
|
EscritaMultipla = true
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "ControleDesaceleracaoMaxima",
|
|
Descricao = "Verifica/Define a desaceleracao maxima. Envio (01 10 17 86 00 02 04 00 00 13 88 9D 43) desaceleracao definida para 5000 rpm/s2",
|
|
Escala = VariaveisEquipamento.NumeroPolosMotor,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0002,
|
|
Registro = 0x1786,
|
|
EscritaMultipla = true
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "ControlePerfilAtual",
|
|
Descricao = "Verifica/Define o perfil atual, variando de 0 a 3. Envio (01 06 17 88 00 01 CD 94) definido perfil 2",
|
|
Escala = 1,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0001,
|
|
Registro = 0x1788
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "RampaDescidaVelocidade",
|
|
Descricao = "Verifica/Define a desaceleracao para modo velocidade. Envio (01 10 17 89 00 02 04 00 00 03 20 D1 7D) desaceleracao definida para 800 rpm/s2",
|
|
Escala = VariaveisEquipamento.NumeroPolosMotor,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0002,
|
|
Registro = 0x1789,
|
|
EscritaMultipla = true
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "ControleRetornarZero",
|
|
Descricao = "Define modo de retorno a zero. Envio (01 06 17 8B 00 01 3D 94) definido modo 01",
|
|
Escala = 1,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0001,
|
|
Registro = 0x178B
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "CorrenteTorqueMaximo",
|
|
Descricao = "Verifica/Define a corrente maxima para gerenciar o torque atual em escala de 10 ma. Envio (01 06 17 8C 00 64 4C 7E) 100 = 1A",
|
|
Escala = 100,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0001,
|
|
Registro = 0x178C
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "ControleCorrenteAceleracao",
|
|
Descricao = "Verifica/Define a corrente de rampa de subida em ma/S. Escala em %, ou seja, valor definido / corrente maxima, entao se corrente maxima = 1000 (1A), 10% seria 100. Envio (01 06 17 8D 00 64 1D SER) 100 = 10%",
|
|
Escala = 10,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0001,
|
|
Registro = 0x178D
|
|
},
|
|
new ModbusParametrosModel()
|
|
{
|
|
Chave = "ControleModoRampa",
|
|
Descricao = "Verifica/Define o modo de rampa atual. Envio (01 06 17 8E 00 64 ED BE) 100 = 10%",
|
|
Escala = 10,
|
|
LeituraLoop = false,
|
|
LeituraGeral = false,
|
|
N_Registros = 0x0001,
|
|
Registro = 0x178E
|
|
},
|
|
|
|
};
|
|
|
|
public Dictionary<int, string> CodigosErro = new Dictionary<int, string>()
|
|
{
|
|
{ 0, "Sem erro" },
|
|
{ 1, "Sobretensão" },
|
|
{ 2, "Subtensão" },
|
|
{ 3, "Corrente máxima excedida" },
|
|
{ 4, "Temperatura máxima no MOS excedida" },
|
|
{ 5, "Subtensão no MCU" },
|
|
{ 6, "Watchdog acionado" },
|
|
{ 7, "Erro de driver de interface SPI" },
|
|
{ 8, "FLASH danificado" },
|
|
{ 9, "O deslocamento do sensor de corrente da fase U é muito grande" },
|
|
{ 10, "O deslocamento do sensor de corrente da fase V é muito grande" },
|
|
{ 11, "O deslocamento do sensor de corrente da fase W é muito grande" },
|
|
{ 12, "Desiquilíbrio de corrente trifásico" },
|
|
{ 13, "A configuração do motor em FLASH está danificada" },
|
|
{ 14, "A configuração da aplicação em FLASH está danificada" },
|
|
{ 15, "Erro de pulsação CANOPEN" },
|
|
{ 16, "Parado" },
|
|
{ 17, "Parar" },
|
|
{ 18, "Fora da tolerância" },
|
|
{ 19, "Codificador não encontra sinal Z" },
|
|
};
|
|
|
|
|
|
public static EthernetService _ethernetService;
|
|
private static int ComandosNaoRespondidos = 0;
|
|
private static int ComandosNaoRespondidosMax = 24;
|
|
public static bool Iniciado
|
|
{
|
|
get
|
|
{
|
|
return _ethernetService != null && _ethernetService.IsConnected && SerialService.DispositivosMapeados.Any(x => x.Dispositivo == T_Code.Mov) && DadosLeitura.Any(x => x.Iniciado);
|
|
}
|
|
}
|
|
public static int TaxaAmostragem { get; set; } = 1000;
|
|
|
|
public static List<OIDModel> DadosLeitura = new List<OIDModel>();
|
|
|
|
|
|
private static List<OIDComandoModel> FilaComandos = new List<OIDComandoModel>();
|
|
|
|
private static readonly object FilaLock = new object();
|
|
|
|
private static AsyncTaskTimerModel tmrLoopComandos;
|
|
private static AsyncTaskTimerModel tmrHeartbeat;
|
|
|
|
private static bool EnvioLiberado { get; set; } = true;
|
|
|
|
public static void IniciarRotinas()
|
|
{
|
|
PararRotinas();
|
|
|
|
tmrLoopComandos = new AsyncTaskTimerModel("tmrLoopComandos", tmrLoopComandos_Tick, 100);
|
|
tmrLoopComandos.Start();
|
|
|
|
tmrHeartbeat = new AsyncTaskTimerModel("tmrHeartbeat", tmrHeartbeat_Tick, 1000);
|
|
tmrHeartbeat.Start();
|
|
}
|
|
|
|
public static void PararRotinas()
|
|
{
|
|
tmrLoopComandos?.Dispose();
|
|
tmrHeartbeat?.Dispose();
|
|
}
|
|
|
|
|
|
// Inicializa o serviço Ethernet com IP e porta específicos
|
|
public static async Task<bool> InicializarEthernetService()
|
|
{
|
|
string ipAddress = Variaveis.OperacaoEmAndamento.DispMvd.Dados.IP_Mov;
|
|
int port = VariaveisPortas.Ethernet_TCP;
|
|
|
|
_ethernetService?.Disconnect();
|
|
|
|
await Task.Delay(1000);
|
|
|
|
_ethernetService = new EthernetService(ipAddress, port);
|
|
return await _ethernetService.ConnectAsync();
|
|
}
|
|
|
|
public static async Task<bool> VerificaPortaOID()
|
|
{
|
|
EnvioLiberado = false;
|
|
|
|
bool connect = await InicializarEthernetService();
|
|
if (!connect)
|
|
{
|
|
Console.WriteLine("Falha ao inicializar o serviço Ethernet.");
|
|
_ethernetService = null;
|
|
EnvioLiberado = true;
|
|
return false;
|
|
}
|
|
|
|
if (_ethernetService._isReconnecting)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
if (!Iniciado && !await _ethernetService.CheckConnectionAsync())
|
|
{
|
|
Console.WriteLine("Falha ao conectar ao dispositivo via Ethernet.");
|
|
EnvioLiberado = true;
|
|
return false;
|
|
}
|
|
|
|
var Parametro = Parametros.First(x => x.Chave == "CodErro");
|
|
|
|
List<string> Mod_IDs = new List<string>();
|
|
|
|
foreach (var Modulo in Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.Where(x => !x.MovMotor.Inicializado))
|
|
{
|
|
byte Addr = 0;
|
|
try
|
|
{
|
|
Addr = Modulo.MovMotor.EnderecoByte;
|
|
}
|
|
catch
|
|
{
|
|
RegisrarErrosComunicacao(Addr, $"Erro ao definir endereço");
|
|
}
|
|
|
|
if (DadosLeitura.Any(x => x.Endereco == Addr && x.Iniciado))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
var comando = ModbusService.ComandoGetParametro(Addr, Parametro);
|
|
|
|
bool envioBemSucedido = await EnviarComando(_ethernetService, comando);
|
|
if (!envioBemSucedido)
|
|
{
|
|
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.Oid, comando, resposta);
|
|
|
|
OIDComandoModel Comando = new OIDComandoModel()
|
|
{
|
|
Endereco = Addr,
|
|
Parametro = Parametro,
|
|
Get = true,
|
|
AguardaResposta = true
|
|
};
|
|
|
|
DecifrarResposta(resposta, Comando);
|
|
|
|
if (DadosLeitura.Any(x => x.Endereco == Addr && x.Iniciado))
|
|
{
|
|
Mod_IDs.Add(Modulo.Modulo_ID);
|
|
}
|
|
}
|
|
|
|
if (Mod_IDs.Any())
|
|
{
|
|
DefinirDispositivo(Mod_IDs);
|
|
}
|
|
|
|
EnvioLiberado = true;
|
|
return Iniciado;
|
|
}
|
|
|
|
public static async Task<bool> VerificaPortaOID2()
|
|
{
|
|
EnvioLiberado = false;
|
|
|
|
bool connect = await InicializarEthernetService();
|
|
if (!connect)
|
|
{
|
|
Console.WriteLine("Falha ao inicializar o serviço Ethernet.");
|
|
_ethernetService = null;
|
|
EnvioLiberado = true;
|
|
return false;
|
|
}
|
|
|
|
if (_ethernetService._isReconnecting)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
if (!Iniciado && !await _ethernetService.CheckConnectionAsync())
|
|
{
|
|
Console.WriteLine("Falha ao conectar ao dispositivo via Ethernet.");
|
|
EnvioLiberado = true;
|
|
return false;
|
|
}
|
|
|
|
var Parametro = Parametros.First(x => x.Chave == "CodErro");
|
|
|
|
List<string> Mod_IDs = new List<string>();
|
|
|
|
byte Addr = 0x01;
|
|
|
|
var comando = ModbusService.ComandoGetParametro(Addr, Parametro);
|
|
|
|
bool envioBemSucedido = await EnviarComando(_ethernetService, comando);
|
|
if (!envioBemSucedido)
|
|
{
|
|
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.Oid, comando, resposta);
|
|
|
|
OIDComandoModel Comando = new OIDComandoModel()
|
|
{
|
|
Endereco = Addr,
|
|
Parametro = Parametro,
|
|
Get = true,
|
|
AguardaResposta = true
|
|
};
|
|
|
|
DecifrarResposta(resposta, Comando);
|
|
|
|
DefinirDispositivo(new List<string>() { "ET" });
|
|
|
|
EnvioLiberado = true;
|
|
return Iniciado;
|
|
}
|
|
|
|
public static async Task<bool> EnviarComando(EthernetService ethernetService, byte[] comando)
|
|
{
|
|
try
|
|
{
|
|
bool sucesso = await ethernetService.SendDataAsync(comando);
|
|
RegisrarComandosComunicacao(comando[0], $"TX: {sucesso} - {BitConverter.ToString(comando).Replace("-", " ")}");
|
|
return sucesso;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"Erro ao enviar comando: {ex.Message}");
|
|
return false;
|
|
}
|
|
}
|
|
|
|
public static async Task EnviarComandoControle(OIDComandoModel Comando)
|
|
{
|
|
try
|
|
{
|
|
byte[] comando = Comando.Get
|
|
? ModbusService.ComandoGetParametro(Comando.Endereco, Comando.Parametro)
|
|
: ModbusService.ComandoSetParametro(Comando.Endereco, Comando.Parametro, Comando.Valor);
|
|
|
|
Comando.Comando = comando;
|
|
|
|
if (comando != null && comando.Length > 0)
|
|
{
|
|
// Envia o comando via Ethernet
|
|
Comando.ErroEnvio = !await EnviarComando(_ethernetService, comando);
|
|
Comando.Enviado = true;
|
|
|
|
// Recebe a resposta via Ethernet, independentemente de precisar processá-la ou não
|
|
byte[] resposta = await _ethernetService.ReceiveDataAsync(Comando.TamanhoEsperado, Comando.TimeoutResposta); // Timeout ajustável, aqui 1 segundo
|
|
Comando.Resposta = resposta;
|
|
|
|
//SerialService.MostrarComandoResposta(T_Code.Oid, comando, resposta);
|
|
|
|
// Processa a resposta, pois é esperada
|
|
bool Respondido = DecifrarResposta(resposta, Comando);
|
|
Comando.Respondido = Respondido;
|
|
if (!Respondido)
|
|
{
|
|
RegisrarErrosComunicacao(Comando.Endereco, $"Timeout ou erro ao receber resposta. GET={Comando.Get}, Parametro={Comando.Parametro.Chave}, Valor={Comando.Valor}");
|
|
//Comando.Momento = DateTime.Now.AddMilliseconds(500); // Retenta após um pequeno intervalo
|
|
|
|
if (!Comando.Get)
|
|
{
|
|
ComandosNaoRespondidos++;
|
|
if (ComandosNaoRespondidos > ComandosNaoRespondidosMax)
|
|
{
|
|
ComandosNaoRespondidos = 0;
|
|
await InicializarEthernetService();
|
|
}
|
|
}
|
|
}
|
|
|
|
//await Task.Delay(100);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
// Log de erro
|
|
RegisrarErrosComunicacao(Comando.Endereco, $"Erro ao enviar comando: {ex.Message}");
|
|
Comando.Enviado = false;
|
|
Comando.Momento = DateTime.Now.AddMilliseconds(500);
|
|
}
|
|
}
|
|
|
|
private static void DefinirDispositivo(List<string> Mod_IDs)
|
|
{
|
|
if (!SerialService.DispositivosMapeados.Any(x => x.Dispositivo == T_Code.Mov))
|
|
{
|
|
IniciarRotinas();
|
|
}
|
|
|
|
foreach (var Mod_ID in Mod_IDs)
|
|
{
|
|
var Modulo = Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.FirstOrDefault(x => x.Modulo_ID == Mod_ID);
|
|
byte Addr = Modulo.MovMotor.EnderecoByte;
|
|
|
|
if (DadosLeitura.Any(x => x.Endereco == Addr && !x.Configurado))
|
|
{
|
|
ConfigurarDriver(Addr);
|
|
}
|
|
|
|
if (!SerialService.DispositivosMapeados.Any(x => x.Dispositivo == T_Code.Mov && x.Mod_ID == Mod_ID))
|
|
{
|
|
var leitura = DadosLeitura.FirstOrDefault(x => x.Endereco == Addr);
|
|
SerialService.DispositivosMapeados.Add(new DispositivoDetalhesModel()
|
|
{
|
|
Endereco = _ethernetService != null ? _ethernetService._ipAddress : "N/A",
|
|
Dispositivo = T_Code.Mov,
|
|
Erro = leitura.CodigoAlarme > 0,
|
|
Versao = "1.0",
|
|
Mod_ID = Mod_ID,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
private static void ConfigurarDriver(byte Addr)
|
|
{
|
|
var Modulo = Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.FirstOrDefault(x => x.MovMotor.EnderecoByte == Addr);
|
|
AdicionarComandoNaFila(new OIDComandoModel()
|
|
{
|
|
Endereco = Addr,
|
|
AguardaResposta = false,
|
|
TimeoutResposta = 50,
|
|
Get = false,
|
|
Parametro = Parametros.First(x => x.Chave == "ModoControle"),
|
|
Valor = (int)OIDModoControle.Freio
|
|
});
|
|
AdicionarComandoNaFila(new OIDComandoModel()
|
|
{
|
|
Endereco = Addr,
|
|
AguardaResposta = false,
|
|
TimeoutResposta = 50,
|
|
Get = false,
|
|
Parametro = Parametros.First(x => x.Chave == "ControleCorrenteFreio"),
|
|
Valor = 3
|
|
});
|
|
AdicionarComandoNaFila(new OIDComandoModel()
|
|
{
|
|
Endereco = Addr,
|
|
AguardaResposta = false,
|
|
TimeoutResposta = 50,
|
|
Get = false,
|
|
Parametro = Parametros.First(x => x.Chave == "ModoControle"),
|
|
Valor = (int)OIDModoControle.Velocidade
|
|
});
|
|
AdicionarComandoNaFila(new OIDComandoModel()
|
|
{
|
|
Endereco = Addr,
|
|
AguardaResposta = false,
|
|
TimeoutResposta = 50,
|
|
Get = false,
|
|
Parametro = Parametros.First(x => x.Chave == "ControleVelocidade"),
|
|
Valor = 0
|
|
});
|
|
AdicionarComandoNaFila(new OIDComandoModel()
|
|
{
|
|
Endereco = Addr,
|
|
AguardaResposta = false,
|
|
TimeoutResposta = 50,
|
|
Get = false,
|
|
Parametro = Parametros.First(x => x.Chave == "CorrenteTorqueMaximo"),
|
|
Valor = 20
|
|
});
|
|
AdicionarComandoNaFila(new OIDComandoModel()
|
|
{
|
|
Endereco = Addr,
|
|
AguardaResposta = false,
|
|
TimeoutResposta = 50,
|
|
Get = false,
|
|
Parametro = Parametros.First(x => x.Chave == "RampaSubidaVelocidade"),
|
|
Valor = Modulo.MovMotor.Rampa
|
|
});
|
|
AdicionarComandoNaFila(new OIDComandoModel()
|
|
{
|
|
Endereco = Addr,
|
|
AguardaResposta = false,
|
|
TimeoutResposta = 50,
|
|
Get = false,
|
|
Parametro = Parametros.First(x => x.Chave == "RampaDescidaVelocidade"),
|
|
Valor = Modulo.MovMotor.Rampa
|
|
});
|
|
DadosLeitura.Where(x => x.Endereco == Addr).First().Configurado = true;
|
|
}
|
|
|
|
|
|
public static bool DecifrarResposta(byte[] resposta, OIDComandoModel Comando)
|
|
{
|
|
byte Addr = Comando.Endereco;
|
|
try
|
|
{
|
|
ModbusParametrosModel Parametro = Comando.Parametro;
|
|
|
|
RegisrarComandosComunicacao(Addr, $"RX: - {BitConverter.ToString(resposta ?? new byte[] { }).Replace("-", " ")}");
|
|
|
|
var Leitura = DadosLeitura.FirstOrDefault(x => x.Endereco == Addr);
|
|
if (Leitura == null)
|
|
{
|
|
Leitura = new OIDModel()
|
|
{
|
|
Endereco = Addr,
|
|
UltimoComandoRecebido = DateTime.MinValue,
|
|
parametros = new List<OIDParametrosRequisitar>()
|
|
{
|
|
new OIDParametrosRequisitar()
|
|
{
|
|
Registro = Parametro.Registro,
|
|
Escala = Parametro.Escala,
|
|
Valor = null
|
|
}
|
|
}
|
|
};
|
|
DadosLeitura.Add(Leitura);
|
|
}
|
|
|
|
OIDParametrosRequisitar _parametro = Leitura.parametros.FirstOrDefault(x => x.Registro == Parametro.Registro);
|
|
if (_parametro == null)
|
|
{
|
|
_parametro = new OIDParametrosRequisitar()
|
|
{
|
|
Registro = Parametro.Registro,
|
|
Escala = Parametro.Escala,
|
|
Valor = null
|
|
};
|
|
Leitura.parametros.Add(_parametro);
|
|
}
|
|
|
|
if (!Comando.AguardaResposta)
|
|
{
|
|
if (!Comando.Get)
|
|
{
|
|
byte[] val = BitConverter.GetBytes((ushort)Comando.Valor).Reverse().ToArray();
|
|
|
|
Parametro.Valor = val;
|
|
_parametro.Valor = val;
|
|
//Leitura.UltimoComandoRecebido = DateTime.Now;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
if (resposta == null || resposta.Length == 0)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
if (resposta.Length > 3)
|
|
{
|
|
// GET
|
|
if (resposta[1] == 0x03 || resposta[1] == 0x04)
|
|
{
|
|
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;
|
|
}
|
|
// SET
|
|
else if (resposta[1] == 0x06)
|
|
{
|
|
byte[] val = resposta.Skip(4).Take(2).ToArray();
|
|
|
|
Parametro.Valor = val;
|
|
_parametro.Valor = val;
|
|
Leitura.UltimoComandoRecebido = DateTime.Now;
|
|
return true;
|
|
}
|
|
// SET MÚLTIPLO
|
|
else if (resposta[1] == 0x10)
|
|
{
|
|
byte[] val = resposta.Skip(2).Take(4).ToArray();
|
|
|
|
Parametro.Valor = val;
|
|
_parametro.Valor = val;
|
|
Leitura.UltimoComandoRecebido = DateTime.Now;
|
|
return true;
|
|
}
|
|
}
|
|
RegisrarErrosComunicacao(Addr, $"Resposta inválida. {BitConverter.ToString(resposta)}");
|
|
return false;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
RegisrarErrosComunicacao(Addr, $"Erro ao decifrar resposta. {BitConverter.ToString(resposta)}");
|
|
return false;
|
|
}
|
|
}
|
|
|
|
public static void RegisrarErrosComunicacao(byte addr, string mensagem)
|
|
{
|
|
try
|
|
{
|
|
var Caminho = Variaveis.CaminhoLogsDispositivos;
|
|
if (!Directory.Exists(Caminho))
|
|
{
|
|
Directory.CreateDirectory(Caminho);
|
|
}
|
|
|
|
var Arquivo = T_Code.Oid.ToString() + "_err.txt";
|
|
Caminho += "/" + Arquivo;
|
|
|
|
mensagem = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss:fff") + " - Endereço " + addr + " (" + _ethernetService._ipAddress + "): " + mensagem + Environment.NewLine;
|
|
|
|
if (!File.Exists(Caminho))
|
|
{
|
|
File.WriteAllText(Caminho, mensagem);
|
|
}
|
|
else
|
|
{
|
|
File.AppendAllText(Caminho, mensagem);
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
Console.WriteLine("Erro ao salvar log de erro OID");
|
|
}
|
|
}
|
|
|
|
public static void RegisrarComandosComunicacao(byte addr, string mensagem)
|
|
{
|
|
try
|
|
{
|
|
var Caminho = Variaveis.CaminhoLogsDispositivos;
|
|
if (!Directory.Exists(Caminho))
|
|
{
|
|
Directory.CreateDirectory(Caminho);
|
|
}
|
|
|
|
var Arquivo = T_Code.Oid.ToString() + "_log.txt";
|
|
Caminho += "/" + Arquivo;
|
|
|
|
mensagem = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss:fff") + " - Endereço " + addr + " (" + _ethernetService._ipAddress + "): " + mensagem + Environment.NewLine;
|
|
|
|
if (!File.Exists(Caminho))
|
|
{
|
|
File.WriteAllText(Caminho, mensagem);
|
|
}
|
|
else
|
|
{
|
|
File.AppendAllText(Caminho, mensagem);
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
Console.WriteLine("Erro ao salvar log de comunicacao OID");
|
|
}
|
|
}
|
|
|
|
private static async Task tmrLoopComandos_Tick()
|
|
{
|
|
if (!EnvioLiberado)
|
|
{
|
|
return;
|
|
}
|
|
|
|
EnvioLiberado = false;
|
|
|
|
// Verifica se a conexão foi perdida e tenta reconectar
|
|
if (_ethernetService != null && !_ethernetService.IsConnected)
|
|
{
|
|
if (!await _ethernetService.ReconnectAsync())
|
|
{
|
|
EnvioLiberado = true;
|
|
return;
|
|
}
|
|
}
|
|
|
|
try
|
|
{
|
|
await ProcessarFilaPrioridade();
|
|
|
|
List<OIDComandoModel> comandosParaEnviar;
|
|
|
|
lock (FilaLock)
|
|
{
|
|
comandosParaEnviar = FilaComandos.Where(x => !x.Enviado && x.Get).OrderBy(x => x.Momento).ToList();
|
|
}
|
|
|
|
foreach (var Comando in comandosParaEnviar)
|
|
{
|
|
await EnviarComandoControle(Comando);
|
|
await ProcessarFilaPrioridade();
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
RegisrarErrosComunicacao(0, $"Erro ao processar fila de comandos. Erro={ex.Message}");
|
|
}
|
|
finally
|
|
{
|
|
EnvioLiberado = true;
|
|
}
|
|
}
|
|
|
|
public static void AdicionarComandoNaFila(OIDComandoModel Comando)
|
|
{
|
|
lock (FilaLock)
|
|
{
|
|
if (!FilaComandos.Any(x => x.Endereco == Comando.Endereco && x.Parametro.Registro == Comando.Parametro.Registro && x.Get == Comando.Get && !x.Enviado))
|
|
{
|
|
FilaComandos.Add(Comando);
|
|
}
|
|
}
|
|
}
|
|
|
|
private static async Task ProcessarFilaPrioridade()
|
|
{
|
|
var FilaPrioridade = new List<OIDComandoModel>();
|
|
lock (FilaLock)
|
|
{
|
|
FilaPrioridade = FilaComandos.Where(x => !x.Enviado && !x.Get).OrderBy(x => x.Momento).ToList();
|
|
}
|
|
|
|
while (FilaPrioridade.Count > 0)
|
|
{
|
|
foreach (var Comando in FilaPrioridade)
|
|
{
|
|
await EnviarComandoControle(Comando);
|
|
}
|
|
|
|
lock (FilaLock)
|
|
{
|
|
FilaPrioridade = FilaComandos.Where(x => !x.Enviado && !x.Get).OrderBy(x => x.Momento).ToList();
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
private static async Task tmrHeartbeat_Tick()
|
|
{
|
|
foreach (var Mod in Variaveis.OperacaoEmAndamento.DispMvd?.Dados?.Modulos)
|
|
{
|
|
if (Mod.MovMotor.Inicializado)
|
|
{
|
|
var Parametro = Parametros.First(x => x.Chave == "Heartbeat");
|
|
int valor = DadosLeitura.FirstOrDefault(x => x.Endereco == Mod.MovMotor.EnderecoByte && x.parametros.Any(y => y.Registro == Parametro.Registro))?.Heartbeat ?? 0;
|
|
int novoValor = valor == 0 ? 1 : 0;
|
|
|
|
AdicionarComandoNaFila(new OIDComandoModel()
|
|
{
|
|
Endereco = Mod.MovMotor.EnderecoByte,
|
|
AguardaResposta = false,
|
|
TimeoutResposta = 10,
|
|
Get = false,
|
|
Parametro = Parametro,
|
|
Valor = novoValor
|
|
});
|
|
|
|
//Console.WriteLine("MOD_ID: " + Mod.MovMotor.Endereco + " - Heartbeat: " + valor);
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|
|
}
|