2353 lines
103 KiB
C#
2353 lines
103 KiB
C#
using AgroBase.Models;
|
|
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.IO.Ports;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using System.Windows.Forms;
|
|
using static AgroBase.Models.Enums;
|
|
|
|
namespace AgroBase.Services
|
|
{
|
|
public class MKS057DService
|
|
{
|
|
public static bool Iniciado
|
|
{
|
|
get
|
|
{
|
|
if (!SerialService.DispositivosMapeados.Any(x => x.Dispositivo == T_Code.Mks) && DadosLeitura.All(x => !x.Iniciado))
|
|
{
|
|
return false;
|
|
}
|
|
lock (_PortaLock)
|
|
{
|
|
if (_PortaMKS != null && !_PortaMKS.IsOpen)
|
|
{
|
|
if (!SerialPort.GetPortNames().Any(x => x == _PortaMKS.PortName))
|
|
{
|
|
_PortaMKS = null;
|
|
foreach (var d in SerialService.DispositivosMapeados.Where(x => x.Dispositivo == T_Code.Mks))
|
|
{
|
|
SerialService.DispositivosMapeados.Remove(d);
|
|
}
|
|
return false;
|
|
}
|
|
try
|
|
{
|
|
_PortaMKS.Open();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
RegisrarErrosComunicacao(0, $"Erro ao abrir porta {_PortaMKS.PortName}. Erro={ex.Message}");
|
|
//_PortaMKS = null;
|
|
AtualizarPortaCOM(new SerialPort() { PortName = _PortaMKS.PortName, BaudRate = _PortaMKS.BaudRate });
|
|
}
|
|
}
|
|
return _PortaMKS != null && _PortaMKS.IsOpen && DadosLeitura.Any(x => x.Iniciado);
|
|
}
|
|
}
|
|
}
|
|
public static int TaxaAmostragem { get; set; } = 1000;
|
|
public static SerialPort _PortaMKS = new SerialPort();
|
|
private static System.Timers.Timer tmrLoopComandos = new System.Timers.Timer() { Interval = 100, Enabled = false };
|
|
private static System.Timers.Timer tmrReceberDados = new System.Timers.Timer() { Interval = TaxaAmostragem, Enabled = false };
|
|
public static readonly object _PortaLock = new object();
|
|
|
|
public static async Task<bool> VerificaPortaMKS(SerialPort porta)
|
|
{
|
|
EnvioLiberado = false;
|
|
|
|
if (!Iniciado)
|
|
{
|
|
porta.Close();
|
|
porta.BaudRate = 38400;
|
|
|
|
AtualizarPortaCOM(porta);
|
|
}
|
|
|
|
List<string> Mod_IDs = new List<string>();
|
|
|
|
foreach (var Modulo in Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.Where(x => !x.DirMotor.MKS_Inicializado))
|
|
{
|
|
byte Addr = Convert.ToByte(Modulo.DirMotor.Endereco, 16);
|
|
|
|
DataSended = Convert.ToByte("43");
|
|
|
|
await SendRelevantData(Addr, QueryCommand[DataSended]);
|
|
|
|
bool respondido = false;
|
|
DateTime inicio = DateTime.Now;
|
|
while (!respondido && inicio.AddMilliseconds(1000) > DateTime.Now)
|
|
{
|
|
await Task.Delay(100);
|
|
respondido = DadosLeitura.Any(x => x.Endereco == Addr && x.Iniciado);
|
|
}
|
|
|
|
if (respondido)
|
|
{
|
|
Mod_IDs.Add(Modulo.Modulo_ID);
|
|
}
|
|
}
|
|
|
|
if (Mod_IDs.Any())
|
|
{
|
|
DefinirDispositivo(Mod_IDs);
|
|
}
|
|
|
|
if (!Iniciado)
|
|
{
|
|
lock (_PortaLock)
|
|
{
|
|
_PortaMKS.Close();
|
|
_PortaMKS = null;
|
|
}
|
|
}
|
|
|
|
EnvioLiberado = true;
|
|
return Iniciado;
|
|
}
|
|
|
|
public static void AtualizarPortaCOM(SerialPort Porta)
|
|
{
|
|
lock (_PortaLock)
|
|
{
|
|
_PortaMKS = new SerialPort();
|
|
_PortaMKS.PortName = Porta.PortName;
|
|
_PortaMKS.BaudRate = Porta.BaudRate;
|
|
|
|
_PortaMKS.DataReceived -= port_DataReceived;
|
|
_PortaMKS.DataReceived += port_DataReceived;
|
|
|
|
_PortaMKS.Open();
|
|
}
|
|
}
|
|
|
|
private static void DefinirDispositivo(List<string> 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.DirMotor.Endereco.Replace("0x", ""), 16);
|
|
|
|
if (!SerialService.DispositivosMapeados.Any(x => x.Dispositivo == T_Code.Mks && x.Mod_ID == Mod_ID))
|
|
{
|
|
var Leitura = DadosLeitura.FirstOrDefault(x => x.Endereco == Addr);
|
|
if (Leitura != null)
|
|
{
|
|
SerialService.DispositivosMapeados.Add(new SerialService.DispositivoDetalhesModel()
|
|
{
|
|
PortaCOM = _PortaMKS.PortName,
|
|
Dispositivo = T_Code.Mks,
|
|
Erro = (Leitura.Mensagem ?? "") != "",
|
|
Versao = (Leitura.FV ?? "").ToString(),
|
|
Mod_ID = Mod_ID,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
public static void IniciarRotinas()
|
|
{
|
|
//Task.Run(() => LoopEnvioComandos()); // Inicia o loop de comandos em segundo plano
|
|
//Task.Run(() => ReceberDados()); // Inicia a recepção de dados em segundo plano
|
|
if (!tmrReceberDados.Enabled)
|
|
{
|
|
tmrReceberDados.Elapsed += TmrReceberDados_Elapsed;
|
|
tmrReceberDados.Start();
|
|
}
|
|
if (!tmrLoopComandos.Enabled)
|
|
{
|
|
tmrLoopComandos.Elapsed += TmrLoopComandos_Elapsed;
|
|
tmrLoopComandos.Start();
|
|
}
|
|
}
|
|
|
|
private static void TmrReceberDados_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
|
|
{
|
|
((System.Timers.Timer)sender).Stop();
|
|
|
|
if (!Iniciado && SerialService.DispositivosMapeados.Any(x => x.Dispositivo == T_Code.Mks))
|
|
{
|
|
foreach (var Leitura in DadosLeitura.Where(x => x.UltimoComandoRecebido.AddSeconds(10) < DateTime.Now))
|
|
{
|
|
AdicionarComandoNaFila(MontarComandoRequisicaoPulsos(Leitura.Endereco));
|
|
}
|
|
|
|
TaxaAmostragem = 3000;
|
|
|
|
ReconectarPortaCOM();
|
|
|
|
((System.Timers.Timer)sender).Start();
|
|
return;
|
|
}
|
|
|
|
TaxaAmostragem = Referenciando ? 200 : 1000;
|
|
|
|
if (Referenciando)
|
|
{
|
|
AdicionarComandoNaFila(MontarComandoRequisicaoPulsos(AddrRef));
|
|
AdicionarComandoNaFila(MontarComandoRequisicaoIO(AddrRef));
|
|
}
|
|
else if (Variaveis.OperacaoEmAndamento.DispMvd != null)
|
|
{
|
|
foreach (var Modulo in Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.Where(x => x.DirMotor.MKS_Inicializado))
|
|
{
|
|
AdicionarComandoNaFila(MontarComandoRequisicaoPulsos(Convert.ToByte(Modulo.DirMotor.Endereco, 16)));
|
|
}
|
|
}
|
|
|
|
((System.Timers.Timer)sender).Start();
|
|
}
|
|
|
|
private static async void TmrLoopComandos_Elapsed(object sender, EventArgs e)
|
|
{
|
|
((System.Timers.Timer)sender).Stop();
|
|
|
|
if (EnvioLiberado)
|
|
{
|
|
await LoopEnvioComandos();
|
|
}
|
|
|
|
((System.Timers.Timer)sender).Start();
|
|
}
|
|
|
|
private static bool EnderecoValido(byte addr)
|
|
{
|
|
return Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.Any(x => Convert.ToByte(x.DirMotor.Endereco.Replace("0x", ""), 16) == addr);
|
|
}
|
|
|
|
public static void AdicionarComandoNaFila(MKS057ComandoModel Comando)
|
|
{
|
|
if (!EnderecoValido(Comando.Endereco))
|
|
{
|
|
return;
|
|
}
|
|
|
|
lock (FilaLock)
|
|
{
|
|
if (!FilaComandos.Any(x => x.Endereco == Comando.Endereco && x.Comando == Comando.Comando && x.Get == Comando.Get && !x.Enviado))
|
|
{
|
|
FilaComandos.Add(Comando);
|
|
}
|
|
}
|
|
}
|
|
|
|
private static async Task LoopEnvioComandos()
|
|
{
|
|
EnvioLiberado = false;
|
|
|
|
try
|
|
{
|
|
await ProcessarFilaPrioridade();
|
|
|
|
List<MKS057ComandoModel> 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;
|
|
}
|
|
}
|
|
|
|
private static async Task ProcessarFilaPrioridade()
|
|
{
|
|
var FilaPrioridade = new List<MKS057ComandoModel>();
|
|
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 void RegisrarErrosComunicacao(byte addr, string mensagem)
|
|
{
|
|
try
|
|
{
|
|
var Caminho = Variaveis.CaminhoLogsDispositivos;
|
|
if (!Directory.Exists(Caminho))
|
|
{
|
|
Directory.CreateDirectory(Caminho);
|
|
}
|
|
|
|
var Arquivo = T_Code.Mks.ToString() + "_err.txt";
|
|
Caminho += "/" + Arquivo;
|
|
|
|
mensagem = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss:fff") + " - Porta " + (_PortaMKS?.PortName ?? "COM") + " - " + addr + ": " + 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 MKS");
|
|
}
|
|
}
|
|
|
|
private static void ReconectarPortaCOM()
|
|
{
|
|
lock (_PortaLock)
|
|
{
|
|
if (_PortaMKS == null)
|
|
{
|
|
return;
|
|
}
|
|
RegisrarErrosComunicacao(0, $"Reiniciando conexão com a porta {_PortaMKS.PortName}...");
|
|
try
|
|
{
|
|
_PortaMKS.Close();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
RegisrarErrosComunicacao(0, $"Erro ao reiniciar conexão. Erro={ex.Message}");
|
|
}
|
|
|
|
if (Iniciado)
|
|
{
|
|
RegisrarErrosComunicacao(0, $"Reconexão com a porta {_PortaMKS.PortName} reestabelecida");
|
|
}
|
|
else
|
|
{
|
|
RegisrarErrosComunicacao(0, $"Erro ao reestabelecer conexão com a porta {_PortaMKS.PortName}");
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
|
|
//static byte Addr;
|
|
static byte DataSended;
|
|
static string word16;
|
|
static int data16;
|
|
static string word32;
|
|
static long data32;
|
|
static string word64;
|
|
static long data64;
|
|
static string Text_BUF;
|
|
|
|
static int tCHK;
|
|
static int rCHK;
|
|
static byte Readata;
|
|
static byte[] Buffer;
|
|
static byte[] SerialBuffer_RX;
|
|
static int Data_Number;
|
|
static string str;
|
|
static byte[] FV1 = new byte[] { 0, 0, 0 };
|
|
static int Temp1 = 0;
|
|
static readonly string[] UartBaud = { "9600", "19200", "25000", "38400", "57600", "115200", "256000" };
|
|
static readonly string[] HardVersion = { "未知电机", "MKS SERVO42D_485", "MKS SERVO42D_CAN", "MKS SERVO57D_485", "MKS SERVO57D_CAN", "MKS SERVO28D_485", "MKS SERVO28D_CAN", "MKS SERVO35D_485", "MKS SERVO35D_CAN" };
|
|
|
|
#region Bytes
|
|
|
|
// Instruções
|
|
static int[] QueryCommand = new int[] {
|
|
0x30, 0x33, 0x39, 0x3A, 0x3B, 0x3E, // (0 Valor do codificador de carry 1 Número de pulsos acumulados de entrada 2 Erro de ângulo de posição 3 Estado de habilitação da placa de acionamento em malha fechada 4 Estado de retorno automático ao zero de um círculo ao ligar 5 Indicador de travamento)
|
|
0xF3, 0xF3, // (6 Habilitar a placa de acionamento 7 Desabilitar a placa de acionamento)
|
|
0xF6, // (8 Modo de controle de velocidade do motor - iniciar)
|
|
0xF6, // (9 Modo de controle de velocidade do motor - parar)
|
|
0xFF, // (10 Iniciar operação automática ao ligar)
|
|
0xFF, // (11 Parar operação automática ao ligar)
|
|
0x84, // (12 Configuração de subdivisão - confirmar)
|
|
0xFD, // (13 Modo de controle de posição do motor - iniciar)
|
|
0x80, // (14 Calibrar o codificador)
|
|
0x81, // (15 Confirmar tipo de motor)
|
|
0x82, // (16 Confirmar modo de operação)
|
|
0x83, // (17 Confirmar valor da corrente (mA))
|
|
0x85, // (18 Confirmar configuração de habilitação)
|
|
0x86, // (19 Confirmar direção do motor)
|
|
0x87, // (20 Confirmar apagamento automático da tela)
|
|
0x88, // (21 Confirmar proteção contra travamento)
|
|
0x89, // (22 Confirmar interpolação de subdivisão)
|
|
0x8A, // (23 Confirmar taxa de transmissão serial)
|
|
0x8B, // (24 Confirmar endereço de comunicação do motor)
|
|
0xA1, // (25 Confirmar posição Kp)
|
|
0xA2, // (26 Confirmar posição Ki)
|
|
0xA3, // (27 Confirmar posição Kd)
|
|
0xA4, // (28 Confirmar aceleração de início)
|
|
0xA5, // (29 Confirmar aceleração de parada)
|
|
0x90, // (30 Ativar modo de retorno ao zero)
|
|
0x90, // (31 Parâmetros de limite)
|
|
0x91, // (32 Retorno ao zero de limite)
|
|
0x92, // (33 Retorno direto ao zero)
|
|
0x93, // (34 Confirmar direção de retorno ao zero)
|
|
0x94, // (35 Retornar ao ponto zero)
|
|
0x3F, // (36 Restaurar configuração de fábrica)
|
|
0x3D, // (37 Ler parâmetros - cancelar estado de travamento)
|
|
0xFD, // (38 Modo de controle de posição do motor - parar)
|
|
0x31, // (39 Ler parâmetros - valor do codificador incremental)
|
|
0x32, // (40 Ler parâmetros - velocidade real do motor)
|
|
0x8C, // (41 Confirmar resposta do escravo)
|
|
0x8D, // (42 Confirmar agrupamento do escravo)
|
|
0x40, // (43 Informações da versão)
|
|
0xF4, // (44 Modo de controle de posição do motor - coordenadas relativas)
|
|
0xF5, // (45 Modo de controle de posição do motor - coordenadas absolutas)
|
|
0x34, // (46 Ler estado da porta IO)
|
|
0x8E, // (47 Confirmar MODBUS)
|
|
0x8F, // (48 Confirmar bloqueio de tecla)
|
|
0x9A // (49 Retorno ao zero de um círculo)
|
|
};
|
|
|
|
|
|
// Bytes comuns
|
|
static byte[] byte_data = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10 };
|
|
|
|
// Bytes de função
|
|
static byte FWD = 0x80;
|
|
static byte RWD = 0x00;
|
|
static byte STOP = 0xF7;
|
|
static byte EN_ON = 0x01;
|
|
static byte EN_OFF = 0x00;
|
|
static byte Save_Speed = 0xC8;
|
|
static byte Clear_Speed = 0xCA;
|
|
|
|
// Dados
|
|
static byte Speed;
|
|
static byte Speed2;
|
|
static ushort Subdivision;
|
|
static byte[] Pulse;
|
|
static byte[] RelAxis;
|
|
static byte[] AbsAxis;
|
|
static byte[] Kp;
|
|
static byte[] Ki;
|
|
static byte[] Kd;
|
|
static byte[] ACC;
|
|
static byte[] MaxT;
|
|
static byte[] Start_ACC = { 0x10 }, Stop_ACC = { 0x10 };
|
|
static byte[] Speed_1, Speed_2;
|
|
static byte[] Current;
|
|
static ushort Max_Current;
|
|
|
|
// Recepção de estado
|
|
static byte EN_STATE_ON = 0x01;
|
|
static byte EN_STATE_OFF = 0x00;
|
|
static byte Stall_YES = 0x01;
|
|
static byte Stall_ON = 0x02;
|
|
|
|
#endregion
|
|
|
|
#region Parametros
|
|
|
|
private static string ModoLeitura = "Decimal";
|
|
|
|
public static ModosOperacao _ModoOperacao { get; set; } = ModosOperacao.SR_vFOC;
|
|
public static string _MStep { get; set; } = "16";
|
|
public static string _CorrenteMaxima { get; set; } = "5200";
|
|
public static Estado _Protecao { get; set; } = Estado.Desligado;
|
|
public static Estado _InterpolacaoSubdivisao { get; set; } = Estado.Desligado;
|
|
public static string _baudSlave { get; set; } = "38400";
|
|
public static string _addressSlave { get; set; } = "0x01";
|
|
public static string _RampaPartida { get; set; } = "16";
|
|
public static string _RampaParada { get; set; } = "16";
|
|
public static Estado _RetornoOrigem { get; set; } = Estado.Ligado;
|
|
public static ModosRetornoOrigem _ModoRetornoOrigem { get; set; } = ModosRetornoOrigem.Desativado;
|
|
public static string _TipoLimiteZero { get; set; } = "Definir";
|
|
|
|
public static Dictionary<byte, string> _Velocidade { get; set; } = new Dictionary<byte, string>();
|
|
public static ModosControle _ModoControle { get; set; } = ModosControle.AnguloAbsoluto;
|
|
public static Dictionary<byte, Sentido> _Sentido { get; set; } = new Dictionary<byte, Sentido>();
|
|
public static Dictionary<byte, string> _Angulo { get; set; } = new Dictionary<byte, string>();
|
|
|
|
#endregion
|
|
|
|
private static List<MKS057ComandoModel> FilaComandos = new List<MKS057ComandoModel>();
|
|
private static readonly object FilaLock = new object();
|
|
private static bool EnvioLiberado { get; set; } = true;
|
|
|
|
public static List<MKS057DModel> DadosLeitura = new List<MKS057DModel>();
|
|
public static bool FilaEmEspera = false;
|
|
public static bool Respondido = false;
|
|
public static byte AddrRef = 0x00;
|
|
public static bool Referenciando
|
|
{
|
|
get
|
|
{
|
|
return AddrRef > 0x00;
|
|
}
|
|
}
|
|
|
|
|
|
|
|
public static MKS057ComandoModel MontarComandoRequisicaoPulsos(byte Endereco)
|
|
{
|
|
return new MKS057ComandoModel()
|
|
{
|
|
Get = true,
|
|
Comando = Convert.ToByte("1"),
|
|
Endereco = Endereco,
|
|
AguardaResposta = true,
|
|
};
|
|
}
|
|
|
|
public static MKS057ComandoModel MontarComandoRequisicaoIO(byte Endereco)
|
|
{
|
|
return new MKS057ComandoModel()
|
|
{
|
|
Get = true,
|
|
Comando = Convert.ToByte("46"),
|
|
Endereco = Endereco,
|
|
AguardaResposta = true,
|
|
};
|
|
}
|
|
|
|
public static MKS057ComandoModel MontarComandoSetZero(byte Endereco)
|
|
{
|
|
return new MKS057ComandoModel()
|
|
{
|
|
Get = false,
|
|
Comando = Convert.ToByte("33"),
|
|
Endereco = Endereco,
|
|
AguardaResposta = true,
|
|
Angulo = 0,
|
|
_Sentido = Sentido.Parado,
|
|
Velocidade = 1,
|
|
ModoControle = ModosControle.AnguloAbsoluto
|
|
};
|
|
}
|
|
|
|
public static MKS057ComandoModel MontarComandoMovimento(byte Endereco, double Angulo_SP, int Velocidade, Sentido Sentido_SP, ModosControle Controle = ModosControle.AnguloAbsoluto)
|
|
{
|
|
return new MKS057ComandoModel()
|
|
{
|
|
Get = false,
|
|
Comando = Convert.ToByte("13"),
|
|
Endereco = Endereco,
|
|
Angulo = Angulo_SP,
|
|
Velocidade = Velocidade,
|
|
_Sentido = Sentido_SP,
|
|
ModoControle = Controle,
|
|
AguardaResposta = false,
|
|
};
|
|
}
|
|
|
|
public static async Task EnviarComandoControle(MKS057ComandoModel Comando)
|
|
{
|
|
byte Addr = Comando.Endereco;
|
|
|
|
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;
|
|
|
|
await SendRelevantData(Addr, QueryCommand[DataSended]);
|
|
|
|
Comando.Enviado = true;
|
|
Respondido = !Comando.AguardaResposta;
|
|
|
|
DateTime Inicio = DateTime.Now;
|
|
while (Comando.AguardaResposta && !Respondido && Inicio.AddMilliseconds(Comando.TimeoutResposta) > DateTime.Now)
|
|
{
|
|
await Task.Delay(100);
|
|
}
|
|
|
|
if (!Respondido)
|
|
{
|
|
RegisrarErrosComunicacao(Addr, $"Timeout ao receber resposta. GET={Comando.Get}, Parametro={Comando.Comando}");
|
|
Comando.Enviado = false;
|
|
Comando.Momento = DateTime.Now.AddMilliseconds(500);
|
|
//ReconectarPortaCOM();
|
|
}
|
|
}
|
|
|
|
public static void AdicionaComandosGoHomeFila(byte Endereco)
|
|
{
|
|
// Configura o GoHome
|
|
AdicionarComandoNaFila(new MKS057ComandoModel()
|
|
{
|
|
Get = false,
|
|
Comando = Convert.ToByte("46"),
|
|
Endereco = Endereco,
|
|
Angulo = 0,
|
|
Velocidade = 1, // 0 ~ 4
|
|
_Sentido = Sentido.Horario,
|
|
ModoControle = ModosControle.AnguloAbsoluto,
|
|
AguardaResposta = false,
|
|
});
|
|
// Inicia o GoHome
|
|
AdicionarComandoNaFila(new MKS057ComandoModel()
|
|
{
|
|
Get = false,
|
|
Comando = Convert.ToByte("32"),
|
|
Endereco = Endereco,
|
|
Angulo = 0,
|
|
Velocidade = 1,
|
|
_Sentido = Sentido.Horario,
|
|
ModoControle = ModosControle.AnguloAbsoluto,
|
|
AguardaResposta = false,
|
|
});
|
|
}
|
|
|
|
|
|
private static void DefinirDadosModulo(MKS057DModel leitura)
|
|
{
|
|
if (Variaveis.OperacaoEmAndamento.DispMvd != null)
|
|
{
|
|
var Modulo = Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.FirstOrDefault(x => Convert.ToByte(x.DirMotor.Endereco, 16) == leitura.Endereco);
|
|
if (Modulo != null)
|
|
{
|
|
Modulo.DirMotor.Angulo = PulsosParaAngulo(leitura.NumeroPulsos);
|
|
Modulo.DirMotor.Sentido = leitura.Direcao;
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
public static int ConverterAnguloParaValor(double _angulo)
|
|
{
|
|
int val = 0;
|
|
|
|
|
|
if (_ModoControle == ModosControle.Pulsos)
|
|
{
|
|
int.TryParse(_MStep, out int mstep);
|
|
double pulsos = mstep * 200;
|
|
double relacao = (pulsos * VariaveisEquipamento.ReducaoDirecional) / 360.0;
|
|
val = Convert.ToInt32(_angulo * relacao);
|
|
}
|
|
else
|
|
{
|
|
val = Convert.ToInt32(_angulo * VariaveisEquipamento.ReducaoDirecional);
|
|
}
|
|
|
|
return val;
|
|
}
|
|
|
|
public static double PulsosParaAngulo(int valor)
|
|
{
|
|
double reducao = VariaveisEquipamento.ReducaoDirecional;
|
|
|
|
int mstep = 16;
|
|
double pulsos = mstep * 200.0;
|
|
double relacao = (pulsos * reducao) / 360.0;
|
|
double angulo = valor / relacao;
|
|
|
|
return angulo;
|
|
}
|
|
|
|
|
|
#region METODOS PRINCIPAIS
|
|
|
|
private static void WriteByteToSerialPort(byte[] data, byte start, byte length)
|
|
{
|
|
byte Addr = data[1];
|
|
|
|
lock (_PortaLock)
|
|
{
|
|
if (_PortaMKS == null)
|
|
{
|
|
RegisrarErrosComunicacao(Addr, "Porta serial não está definida");
|
|
}
|
|
else if (_PortaMKS.IsOpen)
|
|
{
|
|
try
|
|
{
|
|
SerialService.EnviarDadosPortaSerial(_PortaMKS, data, start, length);
|
|
txDisplay();
|
|
}
|
|
catch
|
|
{
|
|
RegisrarErrosComunicacao(Addr, "Erro ao enviar dados para a porta serial");
|
|
}
|
|
}
|
|
else
|
|
{
|
|
RegisrarErrosComunicacao(Addr, "Porta serial não está aberta");
|
|
}
|
|
}
|
|
}
|
|
|
|
private static void port_DataReceived(object sender, SerialDataReceivedEventArgs e) // Evento de recebimento de dados da porta serial
|
|
{
|
|
ProcessarDadosRecebidos();
|
|
}
|
|
|
|
private static void ProcessarDadosRecebidos()
|
|
{
|
|
lock (_PortaLock)
|
|
{
|
|
if (_PortaMKS.IsOpen)
|
|
{
|
|
SerialBuffer_RX = new byte[11] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // SerialBuffer_RX[0] Cabeçalho do quadro [1] Endereço do escravo [2] Número da instrução
|
|
Data_Number = _PortaMKS.BytesToRead; // Número de bytes recebidos
|
|
if (_PortaMKS.BytesToRead > 0 && _PortaMKS.BytesToRead <= SerialBuffer_RX.Length)
|
|
{
|
|
for (int a = 0; a <= Data_Number - 1; a++)
|
|
{
|
|
SerialBuffer_RX[a] = (byte)_PortaMKS.ReadByte(); // Lê um byte do buffer de entrada SerialPort
|
|
}
|
|
Text_display();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private static async Task SendRelevantData(byte Addr, int data) // Verifica o tipo de dados e envia
|
|
{
|
|
ushort SpeedText;
|
|
ushort SpeedText2;
|
|
byte SpeedText3;
|
|
ushort SubdivisionText;
|
|
uint PulseText;
|
|
long RelAxisText;
|
|
long AbsAxisText;
|
|
byte UartAddrText;
|
|
ushort KpText;
|
|
ushort KiText;
|
|
ushort KdText;
|
|
ushort ACCText;
|
|
ushort MaxTText;
|
|
ushort Start_ACCText, Stop_ACCText;
|
|
ushort CurrentText;
|
|
byte HomeTrig = 0x00, HomeDir = 0x00, EndLimit = 0x00;
|
|
byte Mode_0 = 0x00, Set_0 = 0x00, Speed_0 = 0x00, Dir_0 = 0x00;
|
|
|
|
if (Addr <= 0xff && Addr >= 0x00)
|
|
{
|
|
if (DataSended < 6 || DataSended == 37 || DataSended == 39 || DataSended == 40 || DataSended == 43 || DataSended == 46)
|
|
//(0 valor do codificador de posição 1 número acumulado de pulsos de entrada 2 erro de ângulo de posição 3 estado de habilitação da placa de acionamento em malha fechada 4 estado de retorno automático único ao ligar 5 bit de bloqueio 37 estado de desbloqueio 39 valor do codificador de contagem acumulada 40 velocidade atual do motor 43 informação de versão 46 estado do status do porto IO)
|
|
{
|
|
if (DataSended == 46)
|
|
{
|
|
//-------------------Determinação do tipo de motor--------------------
|
|
tCHK = 0xFA + Addr + 0x40;
|
|
Buffer = new byte[] { 0xFA, Addr, 0x40, (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 4);
|
|
await Task.Delay(50);
|
|
//---------------------------------------------------
|
|
}
|
|
tCHK = 0xFA + Addr + data;
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 4);
|
|
}
|
|
|
|
if (DataSended > 5 && DataSended < 8) //(6 habilitar placa de acionamento 7 desabilitar placa de acionamento)
|
|
{
|
|
if (DataSended == 6)
|
|
{
|
|
tCHK = 0xFA + Addr + data + EN_ON;
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, EN_ON, (byte)tCHK };
|
|
//GB4_button_使能驱动板.Enabled = false;
|
|
//GB4_button_关闭驱动板.Enabled = true;
|
|
}
|
|
else
|
|
{
|
|
tCHK = 0xFA + Addr + data + EN_OFF;
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, EN_OFF, (byte)tCHK };
|
|
//GB4_button_关闭驱动板.Enabled = false;
|
|
//GB4_button_使能驱动板.Enabled = true;
|
|
}
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
|
|
/*if (DataSended == 8) //(8 modo de controle de velocidade do motor - iniciar)
|
|
{
|
|
try
|
|
{
|
|
SpeedText = Convert.ToUInt16(GB4_3_comboBox_速度档位.Text, 10);
|
|
Speed_1 = BitConverter.GetBytes(SpeedText);
|
|
if (SpeedText <= 3000 && SpeedText >= 1)
|
|
{
|
|
if (GB4_3_radioButton_反转.Checked)
|
|
{
|
|
//Speed = Convert.ToByte(SpeedText | RWD);
|
|
Speed_1[1] |= RWD;
|
|
//Console.WriteLine(Speed);
|
|
}
|
|
else if (GB4_3_radioButton_正转.Checked)
|
|
{
|
|
//Speed = Convert.ToByte(SpeedText | FWD);
|
|
Speed_1[1] |= FWD;
|
|
//Console.WriteLine(Speed);
|
|
}
|
|
tCHK = 0xFA + Addr + data + Speed_1[1] + Speed_1[0] + Start_ACC[0];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, Speed_1[1], Speed_1[0], Start_ACC[0], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 7);
|
|
}
|
|
else
|
|
MessageBox.Show(Text1_Speedgear, Text1_window);
|
|
}
|
|
catch
|
|
{
|
|
MessageBox.Show(Text1_General, Text2_window);
|
|
}
|
|
}*/
|
|
|
|
if (DataSended == 9) //(9 modo de controle de velocidade do motor - parar)
|
|
{
|
|
tCHK = 0xFA + Addr + data + 0x00 + 0x00 + Stop_ACC[0];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, 0x00, 0x00, Stop_ACC[0], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 7);
|
|
}
|
|
|
|
if (DataSended == 10) //(10 iniciar execução automática ao ligar)
|
|
{
|
|
tCHK = 0xFA + Addr + data + Save_Speed;
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, Save_Speed, (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
Console.WriteLine(value: Save_Speed);
|
|
}
|
|
|
|
if (DataSended == 11) //(11 parar execução automática ao ligar)
|
|
{
|
|
tCHK = 0xFA + Addr + data + Clear_Speed;
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, Clear_Speed, (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
|
|
if (DataSended == 12) //(12 configuração de subdivisão - confirmar)
|
|
{
|
|
try
|
|
{
|
|
SubdivisionText = Convert.ToUInt16(_MStep, 10);
|
|
//Console.WriteLine(SubdivisionText); //saída no console
|
|
if (SubdivisionText < 256 && SubdivisionText >= 1)
|
|
{
|
|
Subdivision = Convert.ToByte(SubdivisionText);
|
|
tCHK = 0xFA + Addr + data + Subdivision;
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, (byte)Subdivision, (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
else if (SubdivisionText == 256)
|
|
{
|
|
tCHK = 0xFA + Addr + data + 0x00;
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, 0x00, (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
else
|
|
MessageBox.Show("O valor de MStep deve estar entre 1 e 256");
|
|
}
|
|
catch
|
|
{
|
|
Console.WriteLine("Erro ao configurar MStep");
|
|
}
|
|
}
|
|
|
|
if (DataSended == 13) //(13 modo de controle de posição do motor - iniciar)
|
|
{
|
|
try
|
|
{
|
|
SpeedText2 = Convert.ToUInt16(_Velocidade[Addr], 10);
|
|
Speed_2 = BitConverter.GetBytes(SpeedText2);
|
|
if (_ModoControle == ModosControle.Pulsos) // Se o controle for através de pulsos
|
|
{
|
|
try
|
|
{
|
|
PulseText = Convert.ToUInt32(_Angulo[Addr], 10);
|
|
Pulse = BitConverter.GetBytes(PulseText);
|
|
if (SpeedText2 <= 3000 && SpeedText2 >= 1)
|
|
{
|
|
if (PulseText <= 4294967295 && PulseText >= 1)
|
|
{
|
|
if (_Sentido[Addr] == Sentido.Antihorario)
|
|
{
|
|
//Speed2 = Convert.ToByte(SpeedText2 | RWD);
|
|
Speed_2[1] |= RWD;
|
|
//Pulse = Convert.ToByte(PulseText);
|
|
}
|
|
else if (_Sentido[Addr] == Sentido.Horario)
|
|
{
|
|
//Speed2 = Convert.ToByte(SpeedText2 | FWD);
|
|
Speed_2[1] |= FWD;
|
|
//Pulse = Convert.ToByte(PulseText);
|
|
}
|
|
else
|
|
{
|
|
MessageBox.Show("Sentido de giro não selecionado");
|
|
}
|
|
tCHK = 0xFA + Addr + data + Speed_2[1] + Speed_2[0] + Start_ACC[0] + Pulse[3] + Pulse[2] + Pulse[1] + Pulse[0];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, Speed_2[1], Speed_2[0], Start_ACC[0], Pulse[3], Pulse[2], Pulse[1], Pulse[0], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 11);
|
|
}
|
|
else
|
|
MessageBox.Show("O número de pulsos deve estar entre 1 e 4294967295");
|
|
}
|
|
else
|
|
MessageBox.Show("A velocidade deve estar entre 1 e 3000");
|
|
}
|
|
catch
|
|
{
|
|
Console.WriteLine("Erro ao definir controle Pulses");
|
|
}
|
|
}
|
|
else if (_ModoControle == ModosControle.AnguloRelativo)
|
|
{
|
|
DataSended = 44;
|
|
data = 0xF4;
|
|
try
|
|
{
|
|
Text_BUF = _Angulo[Addr];
|
|
if (Text_BUF.Length > 1)
|
|
{
|
|
if (Text_BUF[0] == '0' && (Text_BUF[1] == 'x' || Text_BUF[1] == 'X'))
|
|
{
|
|
RelAxisText = Convert.ToInt32(_Angulo[Addr], 16);
|
|
RelAxis = BitConverter.GetBytes(RelAxisText);
|
|
}
|
|
else
|
|
{
|
|
RelAxisText = Convert.ToInt32(_Angulo[Addr], 10);
|
|
RelAxis = BitConverter.GetBytes(RelAxisText * 16384 / 360);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
RelAxisText = Convert.ToInt32(_Angulo[Addr], 10);
|
|
RelAxis = BitConverter.GetBytes(RelAxisText * 16384 / 360);
|
|
}
|
|
if (SpeedText2 <= 3000 && SpeedText2 >= 1)
|
|
{
|
|
if (RelAxisText <= 2147483647 && RelAxisText >= -2147483647)
|
|
{
|
|
tCHK = 0xFA + Addr + data + Speed_2[1] + Speed_2[0] + Start_ACC[0] + RelAxis[3] + RelAxis[2] + RelAxis[1] + RelAxis[0];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, Speed_2[1], Speed_2[0], Start_ACC[0], RelAxis[3], RelAxis[2], RelAxis[1], RelAxis[0], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 11);
|
|
}
|
|
}
|
|
else
|
|
MessageBox.Show("Valor para controle inválido");
|
|
}
|
|
catch
|
|
{
|
|
Console.WriteLine("Erro ao definir controle RelAxis");
|
|
}
|
|
}
|
|
else if (_ModoControle == ModosControle.AnguloAbsoluto)
|
|
{
|
|
DataSended = 45;
|
|
data = 0xF5;
|
|
try
|
|
{
|
|
Text_BUF = _Angulo[Addr];
|
|
if (Text_BUF.Length > 1)
|
|
{
|
|
if (Text_BUF[0] == '0' && (Text_BUF[1] == 'x' || Text_BUF[1] == 'X'))
|
|
{
|
|
AbsAxisText = Convert.ToInt32(_Angulo[Addr], 16);
|
|
AbsAxis = BitConverter.GetBytes(AbsAxisText);
|
|
}
|
|
else
|
|
{
|
|
AbsAxisText = Convert.ToInt32(_Angulo[Addr], 10);
|
|
AbsAxis = BitConverter.GetBytes(AbsAxisText * 16384 / 360);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
AbsAxisText = Convert.ToInt32(_Angulo[Addr], 10);
|
|
AbsAxis = BitConverter.GetBytes(AbsAxisText * 16384 / 360);
|
|
}
|
|
if (SpeedText2 <= 3000 && SpeedText2 >= 1)
|
|
{
|
|
if (AbsAxisText <= 2147483647 && AbsAxisText >= -2147483647)
|
|
{
|
|
tCHK = 0xFA + Addr + data + Speed_2[1] + Speed_2[0] + Start_ACC[0] + AbsAxis[3] + AbsAxis[2] + AbsAxis[1] + AbsAxis[0];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, Speed_2[1], Speed_2[0], Start_ACC[0], AbsAxis[3], AbsAxis[2], AbsAxis[1], AbsAxis[0], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 11);
|
|
}
|
|
}
|
|
else
|
|
MessageBox.Show("Valor para controle inválido");
|
|
}
|
|
catch
|
|
{
|
|
Console.WriteLine("Erro ao definir controle AbsAxis");
|
|
}
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
Console.WriteLine("Erro ao controlar motor de passo");
|
|
}
|
|
}
|
|
|
|
if (DataSended == 14) //(14 calibrar codificador)
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[0];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[0], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
|
|
/*
|
|
if (DataSended == 15) //(15 tipo de motor - confirmar xx)
|
|
{
|
|
Text_BUF = comboBox6.Text;
|
|
if (Text_BUF == Mot_18)
|
|
{
|
|
tCHK = Addr + data + byte_data[1];
|
|
Buffer = new byte[] { Addr, (byte)data, byte_data[1], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 4);
|
|
}
|
|
else if (Text_BUF == Mot_09)
|
|
{
|
|
tCHK = Addr + data + byte_data[0];
|
|
Buffer = new byte[] { Addr, (byte)data, byte_data[0], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 4);
|
|
}
|
|
}
|
|
*/
|
|
|
|
if (DataSended == 16) //(16 modo de operação - confirmar)
|
|
{
|
|
if (_ModoOperacao == ModosOperacao.CR_OPEN)
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[0];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[0], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
|
|
else if (_ModoOperacao == ModosOperacao.CR_CLOSE)
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[1];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[1], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
|
|
else if (_ModoOperacao == ModosOperacao.CR_vFOC)
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[2];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[2], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
|
|
else if (_ModoOperacao == ModosOperacao.SR_OPEN)
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[3];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[3], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
else if (_ModoOperacao == ModosOperacao.SR_CLOSE)
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[4];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[4], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
else if (_ModoOperacao == ModosOperacao.SR_vFOC)
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[5];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[5], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
}
|
|
|
|
if (DataSended == 17) //(17 valor de corrente (mA) - confirmar)
|
|
{
|
|
//-------------------Determinação do tipo de motor--------------------
|
|
tCHK = 0xFA + Addr + 0x40;
|
|
Buffer = new byte[] { 0xFA, Addr, 0x40, (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 4);
|
|
await Task.Delay(50);
|
|
//---------------------------------------------------
|
|
try
|
|
{
|
|
CurrentText = Convert.ToUInt16(_CorrenteMaxima, 10);
|
|
Current = BitConverter.GetBytes(CurrentText);
|
|
if (CurrentText <= Max_Current && CurrentText >= 0)
|
|
{
|
|
tCHK = 0xFA + Addr + data + Current[1] + Current[0];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, Current[1], Current[0], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 6);
|
|
}
|
|
else
|
|
MessageBox.Show("Corrente máxima deve estar entre 0 e " + Max_Current);
|
|
}
|
|
catch
|
|
{
|
|
Console.WriteLine("Erro ao salvar valor da corrente máxima");
|
|
}
|
|
}
|
|
|
|
/*if (DataSended == 18) //(18 configuração de habilitação - confirmar)
|
|
{
|
|
Text_BUF = GB3_comboBox_使能设置.Text;
|
|
if (Text_BUF == EN_H)
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[1];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[1], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
|
|
else if (Text_BUF == EN_L)
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[0];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[0], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
|
|
else if (Text_BUF == EN_Hold)
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[2];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[2], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
}
|
|
|
|
if (DataSended == 19) //(19 direção do motor - confirmar)
|
|
{
|
|
Text_BUF = GB3_comboBox_电机方向.Text;
|
|
if (Text_BUF == Dir_CW)
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[0];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[0], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
|
|
else if (Text_BUF == Dir_CCW)
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[1];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[1], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
}
|
|
|
|
if (DataSended == 20) //(20 desligamento automático da tela - confirmar)
|
|
{
|
|
Text_BUF = GB3_comboBox_自动熄屏.Text;
|
|
if (Text_BUF == Disable)
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[0];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[0], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
|
|
else if (Text_BUF == Enable)
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[1];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[1], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
}*/
|
|
|
|
if (DataSended == 21) //(21 proteção contra travamento - confirmar)
|
|
{
|
|
if (_Protecao == Estado.Desligado)
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[0];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[0], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
else if (_Protecao == Estado.Ligado)
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[1];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[1], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
}
|
|
|
|
if (DataSended == 22) //(22 interpolação de subdivisão - confirmar)
|
|
{
|
|
if (_InterpolacaoSubdivisao == Estado.Desligado)
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[0];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[0], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
else if (_InterpolacaoSubdivisao == Estado.Ligado)
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[1];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[1], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
}
|
|
|
|
if (DataSended == 23) //(23 taxa de baud da porta serial - confirmar)
|
|
{
|
|
Text_BUF = _baudSlave;
|
|
if (Text_BUF == UartBaud[0]) //9600
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[1];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[1], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
else if (Text_BUF == UartBaud[1]) //19200
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[2];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[2], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
else if (Text_BUF == UartBaud[2]) //25000
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[3];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[3], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
else if (Text_BUF == UartBaud[3]) //38400
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[4];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[4], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
else if (Text_BUF == UartBaud[4]) //57600
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[5];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[5], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
else if (Text_BUF == UartBaud[5]) //115200
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[6];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[6], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
else if (Text_BUF == UartBaud[6]) //256000
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[7];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[7], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
}
|
|
|
|
if (DataSended == 24) //(24 endereço de comunicação do motor - confirmar)
|
|
{
|
|
try
|
|
{
|
|
UartAddrText = Convert.ToByte(_addressSlave, 16);
|
|
if (UartAddrText <= 0xff && UartAddrText >= 0x01)
|
|
{
|
|
tCHK = 0xFA + Addr + data + UartAddrText;
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, UartAddrText, (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
else
|
|
MessageBox.Show("Endereço deve estar entre 0x01 e 0xff");
|
|
}
|
|
catch
|
|
{
|
|
Console.WriteLine("Erro ao definir endereço");
|
|
}
|
|
}
|
|
|
|
|
|
/*
|
|
if (DataSended == 25) //(25 Confirmar posição Kp)
|
|
{
|
|
KpText = Convert.ToUInt16(comboBox16.Text, 10);
|
|
Kp = BitConverter.GetBytes(KpText);
|
|
if (KpText < 65535 && KpText >= 0)
|
|
{
|
|
tCHK = Addr + data + Kp[1] + Kp[0];
|
|
Buffer = new byte[] { Addr, (byte)data, Kp[1], Kp[0], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
else
|
|
{
|
|
MessageBox.Show(Text2_Geral, Text2_janela);
|
|
}
|
|
}
|
|
|
|
if (DataSended == 26) //(26 Confirmar posição Ki)
|
|
{
|
|
KiText = Convert.ToUInt16(comboBox17.Text, 10);
|
|
Ki = BitConverter.GetBytes(KiText);
|
|
if (KiText < 65535 && KiText >= 0)
|
|
{
|
|
tCHK = Addr + data + Ki[1] + Ki[0];
|
|
Buffer = new byte[] { Addr, (byte)data, Ki[1], Ki[0], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
else
|
|
{
|
|
MessageBox.Show(Text2_Geral, Text2_janela);
|
|
}
|
|
}
|
|
|
|
if (DataSended == 27) //(27 Confirmar posição Kd)
|
|
{
|
|
KdText = Convert.ToUInt16(comboBox18.Text, 10);
|
|
Kd = BitConverter.GetBytes(KdText);
|
|
if (KdText < 65535 && KdText >= 0)
|
|
{
|
|
tCHK = Addr + data + Kd[1] + Kd[0];
|
|
Buffer = new byte[] { Addr, (byte)data, Kd[1], Kd[0], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
else
|
|
{
|
|
MessageBox.Show(Text2_Geral, Text2_janela);
|
|
}
|
|
}*/
|
|
|
|
if (DataSended == 28) //(28 Confirmar aceleração inicial)
|
|
{
|
|
try
|
|
{
|
|
Start_ACCText = Convert.ToUInt16(_RampaParada, 10);
|
|
if (Start_ACCText <= 255 && Start_ACCText >= 0)
|
|
{
|
|
Start_ACC = BitConverter.GetBytes(Start_ACCText);
|
|
try
|
|
{
|
|
Temp1++;
|
|
}
|
|
catch
|
|
{
|
|
Temp1 = 0;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
MessageBox.Show("O valor da rampa deve estar entre 0 e 255");
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
MessageBox.Show("Erro ao definir rampa de início");
|
|
}
|
|
}
|
|
|
|
if (DataSended == 29) //(29 Confirmar aceleração de parada)
|
|
{
|
|
try
|
|
{
|
|
Stop_ACCText = Convert.ToUInt16(_RampaParada, 10);
|
|
if (Stop_ACCText <= 255 && Stop_ACCText >= 0)
|
|
{
|
|
Stop_ACC = BitConverter.GetBytes(Stop_ACCText);
|
|
try
|
|
{
|
|
Temp1++;
|
|
}
|
|
catch
|
|
{
|
|
Temp1 = 0;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
MessageBox.Show("O valor da rampa deve estar entre 0 e 255");
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
MessageBox.Show("Erro ao definir rampa de parada");
|
|
}
|
|
}
|
|
|
|
/*
|
|
if (DataSended == 30) //(30 Ativar modo de retorno à origem)
|
|
{
|
|
if (radioButton7.Checked)
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[1];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[1], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
else if (radioButton8.Checked)
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[2];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[2], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
else
|
|
{
|
|
MessageBox.Show(Text2_Geral, Text2_janela);
|
|
}
|
|
}
|
|
*/
|
|
|
|
if (DataSended == 31) //(31 Parâmetros de limite)
|
|
{
|
|
//-------------------Verificar tipo de motor--------------------
|
|
tCHK = 0xFA + Addr + 0x40;
|
|
Buffer = new byte[] { 0xFA, Addr, 0x40, (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 4);
|
|
await Task.Delay(50);
|
|
//---------------------------------------------------
|
|
try
|
|
{
|
|
//Nível de gatilho
|
|
Text_BUF = "Baixo";
|
|
if (Text_BUF == "Baixo")
|
|
{
|
|
HomeTrig = 0x00;
|
|
}
|
|
else if (Text_BUF == "Alto")
|
|
{
|
|
HomeTrig = 0x01;
|
|
}
|
|
|
|
//Direção de retorno à origem
|
|
if (_Sentido[Addr] == Sentido.Antihorario)
|
|
{
|
|
HomeDir = 0x00;
|
|
}
|
|
else if (_Sentido[Addr] == Sentido.Horario)
|
|
{
|
|
HomeDir = 0x01;
|
|
}
|
|
|
|
//Habilitar retorno à origem
|
|
if (_RetornoOrigem == Estado.Desligado)
|
|
{
|
|
EndLimit = 0x00;
|
|
}
|
|
else if (_RetornoOrigem == Estado.Ligado)
|
|
{
|
|
EndLimit = 0x01;
|
|
}
|
|
|
|
//Velocidade de retorno à origem
|
|
SpeedText = Convert.ToUInt16(_Velocidade[Addr], 10);
|
|
Speed_1 = BitConverter.GetBytes(SpeedText);
|
|
|
|
if (FV1[2] == 0x03)
|
|
{
|
|
if (SpeedText <= 3000 && SpeedText >= 1)
|
|
{
|
|
tCHK = 0xFA + Addr + data + HomeTrig + HomeDir + Speed_1[1] + Speed_1[0] + EndLimit;
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, HomeTrig, HomeDir, Speed_1[1], Speed_1[0], EndLimit, (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 9);
|
|
}
|
|
else
|
|
MessageBox.Show("Limite de velocidade de retorno deve estar entre 1 e 3000");
|
|
}
|
|
else
|
|
{
|
|
if (SpeedText <= 3000 && SpeedText >= 1)
|
|
{
|
|
tCHK = 0xFA + Addr + data + HomeTrig + HomeDir + Speed_1[1] + Speed_1[0];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, HomeTrig, HomeDir, Speed_1[1], Speed_1[0], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 8);
|
|
}
|
|
else
|
|
MessageBox.Show("Limite de velocidade de retorno deve estar entre 1 e 3000");
|
|
}
|
|
//----
|
|
}
|
|
catch
|
|
{
|
|
MessageBox.Show("Erro ao definir limite");
|
|
}
|
|
}
|
|
|
|
if (DataSended == 32) //(32 Limite de retorno à origem)
|
|
{
|
|
tCHK = 0xFA + Addr + data;
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 4);
|
|
}
|
|
|
|
if (DataSended == 33) //(33 Retorno à origem direto)
|
|
{
|
|
tCHK = 0xFA + Addr + data;
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 4);
|
|
}
|
|
|
|
/*
|
|
if (DataSended == 34) //(34 Confirmar direção de retorno à origem)
|
|
{
|
|
if (radioButton10.Checked)
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[0];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[0], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
else if (radioButton9.Checked)
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[1];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[1], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
else
|
|
{
|
|
MessageBox.Show(Text2_Geral, Text2_janela);
|
|
}
|
|
}
|
|
*/
|
|
|
|
if (DataSended == 35) //(35 Voltar ao ponto zero)
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[0];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[0], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
|
|
if (DataSended == 36) //(36 Restaurar configurações de fábrica)
|
|
{
|
|
tCHK = 0xFA + Addr + data;
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 4);
|
|
}
|
|
|
|
if (DataSended == 38) //(38 Parar modo de controle de posição do motor)
|
|
{
|
|
if (_ModoControle == ModosControle.Pulsos)
|
|
{
|
|
|
|
}
|
|
else if (_ModoControle == ModosControle.AnguloRelativo)
|
|
{
|
|
data = 0xF4;
|
|
}
|
|
else if (_ModoControle == ModosControle.AnguloAbsoluto)
|
|
{
|
|
data = 0xF5;
|
|
}
|
|
tCHK = 0xFA + Addr + data + 0x00 + 0x00 + Stop_ACC[0] + 0x00 + 0x00 + 0x00 + 0x00;
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, 0x00, 0x00, Stop_ACC[0], 0x00, 0x00, 0x00, 0x00, (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 11);
|
|
}
|
|
|
|
/*if (DataSended == 41) //(41 Resposta do escravo)
|
|
{
|
|
Text_BUF = GB3_comboBox_从机应答.Text;
|
|
if (Text_BUF == Desativar)
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[0];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[0], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
|
|
else if (Text_BUF == Ativar)
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[1];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[1], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
}
|
|
|
|
if (DataSended == 42) //(42 Grupo de escravos)
|
|
{
|
|
try
|
|
{
|
|
UartAddrText = Convert.ToByte(GB3_comboBox_从机分组.Text, 16);
|
|
if (UartAddrText <= 0xff && UartAddrText >= 0x01)
|
|
{
|
|
tCHK = 0xFA + Addr + data + UartAddrText;
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, UartAddrText, (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
else
|
|
MessageBox.Show(Text1_UartAddrError, Text1_janela);
|
|
}
|
|
catch
|
|
{
|
|
MessageBox.Show(Text1_Geral, Text2_janela);
|
|
}
|
|
}
|
|
|
|
if (DataSended == 47) //(47 MODBUS)
|
|
{
|
|
Text_BUF = GB3_comboBox_MODBUS.Text;
|
|
if (Text_BUF == Desativar)
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[0];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[0], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
else if (Text_BUF == Ativar)
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[1];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[1], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
}
|
|
|
|
if (DataSended == 48) //(48 Bloqueio de teclas)
|
|
{
|
|
Text_BUF = GB3_comboBox_按键锁定.Text;
|
|
if (Text_BUF == "Desbloquear")
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[0];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[0], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
else if (Text_BUF == "Bloquear")
|
|
{
|
|
tCHK = 0xFA + Addr + data + byte_data[1];
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, byte_data[1], (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 5);
|
|
}
|
|
}*/
|
|
|
|
if (DataSended == 49) //(49 Retorno único)
|
|
{
|
|
try
|
|
{
|
|
//Modo de retorno à origem
|
|
if (_ModoRetornoOrigem == ModosRetornoOrigem.Desativado)
|
|
{
|
|
Mode_0 = 0x00;
|
|
}
|
|
else if (_ModoRetornoOrigem == ModosRetornoOrigem.ModoDirecao)
|
|
{
|
|
Mode_0 = 0x01;
|
|
}
|
|
else if (_ModoRetornoOrigem == ModosRetornoOrigem.ModoAproximacao)
|
|
{
|
|
Mode_0 = 0x02;
|
|
}
|
|
|
|
//Configurar zero
|
|
Text_BUF = _TipoLimiteZero;
|
|
if (Text_BUF == "Limpar")
|
|
{
|
|
Set_0 = 0x00;
|
|
}
|
|
else if (Text_BUF == "Definir")
|
|
{
|
|
Set_0 = 0x01;
|
|
}
|
|
|
|
//Direção de retorno à origem
|
|
if (_Sentido[Addr] == Sentido.Antihorario)
|
|
{
|
|
Dir_0 = 0x00;
|
|
}
|
|
else if (_Sentido[Addr] == Sentido.Horario)
|
|
{
|
|
Dir_0 = 0x01;
|
|
}
|
|
|
|
//Velocidade de retorno à origem
|
|
Speed_0 = Convert.ToByte(_Velocidade[Addr], 10);
|
|
|
|
tCHK = 0xFA + Addr + data + Mode_0 + Set_0 + Speed_0 + Dir_0;
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, Mode_0, Set_0, Speed_0, Dir_0, (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 8);
|
|
//----
|
|
}
|
|
catch
|
|
{
|
|
MessageBox.Show("Erro ao gravar parametros de limite");
|
|
}
|
|
}
|
|
|
|
if (DataSended == 91) //(91 Go Home)
|
|
{
|
|
tCHK = 0xFA + Addr + data;
|
|
Buffer = new byte[] { 0xFA, Addr, (byte)data, (byte)tCHK };
|
|
WriteByteToSerialPort(Buffer, 0, 4);
|
|
}
|
|
|
|
}
|
|
else
|
|
MessageBox.Show("Endereço selecionado é inválido");
|
|
}
|
|
|
|
private static void Text_display()
|
|
{
|
|
rxDisplay(); //计算rCHK
|
|
|
|
byte addr = SerialBuffer_RX[1];
|
|
|
|
if (!EnderecoValido(addr))
|
|
{
|
|
RegisrarErrosComunicacao(addr, "Dados recebidos de um endereço inválido: [" + string.Join(" ", SerialBuffer_RX) + "]");
|
|
return;
|
|
}
|
|
|
|
MKS057DModel leitura = DadosLeitura.FirstOrDefault(x => x.Endereco == addr);
|
|
if (leitura == null)
|
|
{
|
|
leitura = new MKS057DModel()
|
|
{
|
|
Endereco = addr,
|
|
UltimoComandoRecebido = DateTime.MinValue,
|
|
};
|
|
DadosLeitura.Add(leitura);
|
|
}
|
|
|
|
if ((byte)rCHK == SerialBuffer_RX[Data_Number - 1])
|
|
{
|
|
switch (SerialBuffer_RX[2])
|
|
{
|
|
case 0x30: // 0 Encoder de valor em modo posicional FB + 01 + 30 + int32_t valor posicional + uint16_t valor do encoder + CRC
|
|
if (ModoLeitura == "Hex") // Hexadecimal
|
|
{
|
|
leitura.ErroCarregado_Hex = "";
|
|
|
|
leitura.ErroCarregado_Hex += "0x";
|
|
for (int a = 3; a < 9; a++)
|
|
{
|
|
str = Convert.ToString(SerialBuffer_RX[a], 16).ToUpper();
|
|
leitura.ErroCarregado_Hex += str.Length == 1 ? "0" + str : str;
|
|
}
|
|
}
|
|
else if (ModoLeitura == "Decimal") // Decimal
|
|
{
|
|
leitura.ErroCarregado = 0;
|
|
|
|
word32 = "0";
|
|
for (int a = 3; a < 7; a++)
|
|
{
|
|
str = Convert.ToString(SerialBuffer_RX[a], 16).ToUpper();
|
|
word32 += str.Length == 1 ? "0" + str : str;
|
|
}
|
|
data32 = Convert.ToInt32(word32, 16);
|
|
|
|
word16 = "0";
|
|
for (int a = 7; a < 9; a++)
|
|
{
|
|
str = Convert.ToString(SerialBuffer_RX[a], 16).ToUpper();
|
|
word16 += str.Length == 1 ? "0" + str : str;
|
|
}
|
|
data16 = Convert.ToInt16(word16, 16);
|
|
|
|
str = Convert.ToString(data32 * 360 + data16 * 360 / 16384, 10);
|
|
double.TryParse(str, out double val);
|
|
leitura.ErroCarregado = val;
|
|
}
|
|
else
|
|
{
|
|
MessageBox.Show("Erro ao ler dados de erro"); // Erro de dados
|
|
}
|
|
break;
|
|
|
|
case 0x33: // 1 Contagem acumulada de pulsos FB + 01 + 33 + int32_t contagem acumulada de pulsos + CRC
|
|
if (ModoLeitura == "Hex") // Hexadecimal
|
|
{
|
|
leitura.NumeroPulsos_Hex = "";
|
|
|
|
leitura.NumeroPulsos_Hex += "0x";
|
|
for (int a = 3; a < 7; a++)
|
|
{
|
|
str = Convert.ToString(SerialBuffer_RX[a], 16).ToUpper();
|
|
leitura.NumeroPulsos_Hex += str.Length == 1 ? "0" + str : str;
|
|
}
|
|
}
|
|
else if (ModoLeitura == "Decimal") // Decimal
|
|
{
|
|
leitura.NumeroPulsos = 0;
|
|
|
|
word32 = "0";
|
|
for (int a = 3; a < 7; a++)
|
|
{
|
|
str = Convert.ToString(SerialBuffer_RX[a], 16).ToUpper();
|
|
word32 += str.Length == 1 ? "0" + str : str;
|
|
}
|
|
data32 = Convert.ToInt32(word32, 16);
|
|
|
|
str = Convert.ToString(data32, 10);
|
|
int.TryParse(str, out int val);
|
|
leitura.NumeroPulsos = val;
|
|
|
|
DefinirDadosModulo(leitura);
|
|
}
|
|
else
|
|
{
|
|
MessageBox.Show("Erro ao ler dados de pulsos"); // Erro de dados
|
|
}
|
|
break;
|
|
|
|
case 0x39: // 2 Erro de ângulo de posição FB + 01 + 39 + int32_t erro de ângulo de posição + CRC
|
|
if (ModoLeitura == "Hex") // Hexadecimal
|
|
{
|
|
leitura.ErroAngulo_Hex = "";
|
|
leitura.ErroAngulo_Hex += "0x";
|
|
for (int a = 3; a < 7; a++)
|
|
{
|
|
str = Convert.ToString(SerialBuffer_RX[a], 16).ToUpper();
|
|
leitura.ErroAngulo_Hex += str.Length == 1 ? "0" + str : str;
|
|
}
|
|
}
|
|
else if (ModoLeitura == "Decimal") // Decimal
|
|
{
|
|
leitura.ErroAngulo = 0;
|
|
word32 = "0";
|
|
for (int a = 3; a < 7; a++)
|
|
{
|
|
str = Convert.ToString(SerialBuffer_RX[a], 16).ToUpper();
|
|
word32 += str.Length == 1 ? "0" + str : str;
|
|
}
|
|
data32 = Convert.ToInt32(word32, 16);
|
|
|
|
str = Convert.ToString(data32, 10);
|
|
double.TryParse(str, out double val);
|
|
leitura.ErroAngulo = val;
|
|
}
|
|
else
|
|
{
|
|
MessageBox.Show("Erro ao ler dados de erro de angulo"); // Erro de dados
|
|
}
|
|
break;
|
|
|
|
case 0x3A: // 3 Estado de habilitação da placa de acionamento FB + 01 + 3A + uint8_t estado de habilitação do loop fechado da placa de acionamento + CRC
|
|
// Habilitado: 01
|
|
// Desabilitado: 00
|
|
leitura.StatusDriver = SerialBuffer_RX[3] == EN_STATE_ON ? Estado.Ligado : SerialBuffer_RX[3] == EN_STATE_OFF ? Estado.Desligado : Estado.Reset;
|
|
if (leitura.StatusDriver == Estado.Reset)
|
|
{
|
|
MessageBox.Show("Erro ao ler dados de driver habilitado"); // Erro de dados
|
|
}
|
|
break;
|
|
|
|
case 0x3B: // 4 Estado de retorno automático para a posição inicial após ligar FB + 01 + 3B + uint8_t valor de estado de retorno para a posição inicial + CRC
|
|
// Executando retorno para a posição inicial: 00
|
|
// Retorno para a posição inicial concluído: 01
|
|
// Falha ao retornar para a posição inicial: 02
|
|
if (SerialBuffer_RX[3] == 0x00)
|
|
{
|
|
leitura.StatusModoLimiteZero = StatusComando.Retornando; // Texto1 de retorno para zero
|
|
}
|
|
else if (SerialBuffer_RX[3] == 0x01)
|
|
{
|
|
leitura.StatusModoLimiteZero = StatusComando.Sucesso; // Texto2 de retorno para zero
|
|
}
|
|
else if (SerialBuffer_RX[3] == 0x02)
|
|
{
|
|
leitura.StatusModoLimiteZero = StatusComando.Falha; // Texto3 de retorno para zero
|
|
}
|
|
break;
|
|
|
|
case 0x3E: // 5 Sinal de bloqueio do motor FB + 01 + 3E + uint8_t sinal de bloqueio + CRC
|
|
// Bloqueado: 01
|
|
// Não bloqueado: 00
|
|
if (SerialBuffer_RX[3] == 0x01)
|
|
{
|
|
leitura.StatusTravaMotor = Estado.Ligado; // Texto1 de bloqueio
|
|
}
|
|
else if (SerialBuffer_RX[3] == 0x00)
|
|
{
|
|
leitura.StatusTravaMotor = Estado.Desligado; // Texto2 de bloqueio
|
|
}
|
|
else
|
|
{
|
|
leitura.StatusTravaMotor = Estado.Reset;
|
|
}
|
|
break;
|
|
|
|
case 0x3D: // 37 Status de desbloqueio
|
|
// Desbloqueio bem-sucedido: retorna FB 01 3D 01 3A
|
|
// Falha no desbloqueio: retorna FB 01 3D 00 39
|
|
if (SerialBuffer_RX[3] == 0x01)
|
|
{
|
|
leitura.StatusBloqueioMotor = StatusComando.Sucesso; // Texto1 de bloqueio
|
|
}
|
|
else if (SerialBuffer_RX[3] == 0x00)
|
|
{
|
|
leitura.StatusBloqueioMotor = StatusComando.Falha; // Texto2 de bloqueio
|
|
}
|
|
break;
|
|
|
|
case 0xF6: // 8 Início do controle de velocidade & 9 Parada do controle de velocidade
|
|
if (DataSended == 8)
|
|
{
|
|
if (SerialBuffer_RX[3] == 0x01) // Sucesso
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Completo; // Texto1 de movimento
|
|
}
|
|
else if (SerialBuffer_RX[3] == 0x00) // Falha
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Falha; // Texto3 de movimento
|
|
break;
|
|
}
|
|
else
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Erro; // Texto1 de erro de comunicação
|
|
break;
|
|
}
|
|
double.TryParse(_Velocidade[addr], out double vel);
|
|
double.TryParse(Start_ACC[0].ToString(), out double acl);
|
|
leitura.Direcao = _Sentido[addr];
|
|
leitura.Velocidade = vel;
|
|
leitura.Aceleracao = acl;
|
|
|
|
DefinirDadosModulo(leitura);
|
|
}
|
|
else if (DataSended == 9)
|
|
{
|
|
if (SerialBuffer_RX[3] == 0x02) // Concluído
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Sucesso; // Texto2 de parada
|
|
}
|
|
else if (SerialBuffer_RX[3] == 0x01) // Iniciado
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Parando; // Texto4 de parada
|
|
}
|
|
else if (SerialBuffer_RX[3] == 0x00) // Falha
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Falha; // Texto3 de parada
|
|
break;
|
|
}
|
|
else
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Erro; // Texto1 de erro de comunicação
|
|
break;
|
|
}
|
|
double.TryParse(Stop_ACC[0].ToString(), out double acl);
|
|
leitura.Direcao = Sentido.Parado; // Texto3 de direção
|
|
leitura.Velocidade = 0; // Velocidade alvo zero
|
|
leitura.Aceleracao = acl; // Aceleração alvo de parada
|
|
|
|
DefinirDadosModulo(leitura);
|
|
}
|
|
break;
|
|
|
|
case 0xFD: // 13 Início do controle de posição & 38 Parada do controle de posição
|
|
if (DataSended != 38)
|
|
{
|
|
if (SerialBuffer_RX[3] == 0x02) // Concluído
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Sucesso; // Texto2 de movimento
|
|
break;
|
|
}
|
|
else if (SerialBuffer_RX[3] == 0x01) // Iniciado
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Movendo; // Texto4 de movimento
|
|
}
|
|
else if (SerialBuffer_RX[3] == 0x00) // Falha
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Falha; // Texto3 de movimento
|
|
break;
|
|
}
|
|
else
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Erro; // Texto1 de erro de comunicação
|
|
break;
|
|
}
|
|
leitura.Direcao = _Sentido[addr];
|
|
double.TryParse(_Velocidade[addr], out double vel);
|
|
double.TryParse(Start_ACC[0].ToString(), out double acl);
|
|
leitura.Velocidade = vel; // Velocidade alvo
|
|
leitura.Aceleracao = acl; // Aceleração alvo
|
|
|
|
DefinirDadosModulo(leitura);
|
|
}
|
|
else if (DataSended == 38)
|
|
{
|
|
if (SerialBuffer_RX[3] == 0x02) // Concluído
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Sucesso; // Texto2 de parada
|
|
break;
|
|
}
|
|
else if (SerialBuffer_RX[3] == 0x01) // Iniciado
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Parando; // Texto4 de parada
|
|
}
|
|
else if (SerialBuffer_RX[3] == 0x00) // Falha
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Falha; // Texto3 de parada
|
|
break;
|
|
}
|
|
else
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Erro; // Texto1 de erro de comunicação
|
|
break;
|
|
}
|
|
leitura.Direcao = Sentido.Parado; // Texto3 de direção
|
|
leitura.Velocidade = 0; // Velocidade alvo zero
|
|
double.TryParse(Stop_ACC[0].ToString(), out double acl);
|
|
leitura.Aceleracao = acl; // Aceleração alvo de parada
|
|
|
|
DefinirDadosModulo(leitura);
|
|
}
|
|
break;
|
|
|
|
case 0xF4: // 44 Coordenadas Relativas & 38 Controle de Parada de Posição
|
|
if (DataSended != 38)
|
|
{
|
|
if (SerialBuffer_RX[3] == 0x02) // Completo
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Sucesso;
|
|
break;
|
|
}
|
|
else if (SerialBuffer_RX[3] == 0x01) // Iniciar
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Movendo;
|
|
}
|
|
else if (SerialBuffer_RX[3] == 0x00) // Falha
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Falha;
|
|
break;
|
|
}
|
|
else
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Erro;
|
|
break;
|
|
}
|
|
double.TryParse(_Velocidade[addr], out double vel);
|
|
double.TryParse(Start_ACC[0].ToString(), out double acl);
|
|
leitura.Velocidade = vel; // Velocidade alvo
|
|
leitura.Aceleracao = acl; // Aceleração alvo
|
|
}
|
|
else if (DataSended == 38)
|
|
{
|
|
if (SerialBuffer_RX[3] == 0x02) // Completo
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Sucesso;
|
|
break;
|
|
}
|
|
else if (SerialBuffer_RX[3] == 0x01) // Iniciar
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Parando;
|
|
}
|
|
else if (SerialBuffer_RX[3] == 0x00) // Falha
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Falha;
|
|
break;
|
|
}
|
|
else
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Erro;
|
|
break;
|
|
}
|
|
double.TryParse(Start_ACC[0].ToString(), out double acl);
|
|
leitura.Direcao = Sentido.Parado;
|
|
leitura.Velocidade = 0;
|
|
leitura.Aceleracao = acl;
|
|
|
|
DefinirDadosModulo(leitura);
|
|
}
|
|
break;
|
|
|
|
case 0xF5: // 45 Coordenadas Absolutas & 38 Controle de Parada de Posição
|
|
if (DataSended != 38)
|
|
{
|
|
if (SerialBuffer_RX[3] == 0x02) // Completo
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Sucesso;
|
|
break;
|
|
}
|
|
else if (SerialBuffer_RX[3] == 0x01) // Iniciar
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Movendo;
|
|
}
|
|
else if (SerialBuffer_RX[3] == 0x00) // Falha
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Falha;
|
|
break;
|
|
}
|
|
else
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Erro;
|
|
break;
|
|
}
|
|
double.TryParse(_Velocidade[addr], out double vel);
|
|
double.TryParse(Start_ACC[0].ToString(), out double acl);
|
|
leitura.Velocidade = vel; // Velocidade alvo
|
|
leitura.Aceleracao = acl; // Aceleração alvo
|
|
}
|
|
else if (DataSended == 38)
|
|
{
|
|
if (SerialBuffer_RX[3] == 0x02) // Completo
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Sucesso;
|
|
break;
|
|
}
|
|
else if (SerialBuffer_RX[3] == 0x01) // Iniciar
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Parando;
|
|
}
|
|
else if (SerialBuffer_RX[3] == 0x00) // Falha
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Falha;
|
|
break;
|
|
}
|
|
else
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Erro;
|
|
break;
|
|
}
|
|
leitura.Direcao = Sentido.Parado;
|
|
double.TryParse(_Velocidade[addr], out double vel);
|
|
double.TryParse(Start_ACC[0].ToString(), out double acl);
|
|
leitura.Velocidade = vel; // Velocidade alvo
|
|
leitura.Aceleracao = acl; // Aceleração alvo
|
|
|
|
DefinirDadosModulo(leitura);
|
|
}
|
|
break;
|
|
|
|
case 0x31:// 39 Valor do Codificador Incremental FB + 01 + 31 + Valor do Codificador uint48_t + CRC
|
|
if (ModoLeitura == "Hex") // Hexadecimal
|
|
{
|
|
leitura.ErroCarregado_Hex = "";
|
|
|
|
leitura.ErroCarregado_Hex += "0x";
|
|
for (int a = 3; a < 9; a++)
|
|
{
|
|
str = Convert.ToString(SerialBuffer_RX[a], 16).ToUpper();
|
|
leitura.ErroCarregado_Hex += str.Length == 1 ? "0" + str : str;
|
|
}
|
|
}
|
|
else if (ModoLeitura == "Decimal") // Decimal
|
|
{
|
|
leitura.ErroCarregado = 0;
|
|
|
|
word64 = "0";
|
|
for (int a = 3; a < 9; a++)
|
|
{
|
|
if (a == 3 && SerialBuffer_RX[3] >= 0x80)
|
|
{
|
|
str = Convert.ToString(SerialBuffer_RX[a], 16).ToUpper();
|
|
word64 = "FFFF" + str;
|
|
}
|
|
else
|
|
{
|
|
str = Convert.ToString(SerialBuffer_RX[a], 16).ToUpper();
|
|
word64 += str.Length == 1 ? "0" + str : str;
|
|
}
|
|
}
|
|
data64 = Convert.ToInt64(word64, 16);
|
|
|
|
str = Convert.ToString(data64 * 360 / 16384, 10);
|
|
double.TryParse(str, out double val);
|
|
leitura.ErroCarregado = val;
|
|
}
|
|
else
|
|
{
|
|
MessageBox.Show("Erro ao ler dados de erro carregado");
|
|
}
|
|
break;
|
|
|
|
case 0x32:// 40 Velocidade Atual do Motor
|
|
if (ModoLeitura == "Hex") // Hexadecimal
|
|
{
|
|
leitura.RPM_Hex = "";
|
|
leitura.RPM_Hex += "0x";
|
|
for (int a = 3; a < 5; a++)
|
|
{
|
|
str = Convert.ToString(SerialBuffer_RX[a], 16).ToUpper();
|
|
leitura.RPM_Hex += str.Length == 1 ? "0" + str : str;
|
|
}
|
|
}
|
|
else if (ModoLeitura == "Decimal") // Decimal
|
|
{
|
|
leitura.RPM = 0;
|
|
word16 = "0";
|
|
for (int a = 3; a < 5; a++)
|
|
{
|
|
str = Convert.ToString(SerialBuffer_RX[a], 16).ToUpper();
|
|
word16 += str.Length == 1 ? "0" + str : str;
|
|
}
|
|
data16 = Convert.ToInt16(word16, 16);
|
|
str = Convert.ToString(data16, 10);
|
|
double.TryParse(str, out double val);
|
|
leitura.RPM = val;
|
|
}
|
|
else
|
|
{
|
|
MessageBox.Show("Erro ao ler dados de RPM");
|
|
}
|
|
break;
|
|
|
|
case 0x80:// 14 Calibrar Codificador
|
|
if (SerialBuffer_RX[3] == 0x00)
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Calibrando;
|
|
}
|
|
else if (SerialBuffer_RX[3] == 0x01)
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Sucesso;
|
|
}
|
|
else if (SerialBuffer_RX[3] == 0x02)
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Falha;
|
|
}
|
|
break;
|
|
|
|
case 0x3F:// 36 Restaurar Configurações de Fábrica
|
|
case 0x82:// 16 Modo de Trabalho
|
|
case 0x83:// 17 Valor de Corrente
|
|
case 0x84:// 12 Configuração de Subdivisão
|
|
case 0x85:// 18 Configuração de Habilitação
|
|
case 0x86:// 19 Direção do Motor
|
|
case 0x87:// 20 Desligamento Automático da Tela
|
|
case 0x88:// 21 Proteção de Bloqueio
|
|
case 0x89:// 22 Interpolação de Subdivisão
|
|
case 0x8A:// 23 Taxa de Baud da Porta Serial
|
|
case 0x8B:// 24 Endereço de Comunicação do Motor
|
|
case 0x8C:// 41 Resposta do Dispositivo Escravo
|
|
case 0x8D:// 42 Grupo do Dispositivo Escravo
|
|
case 0x90:// 31 Parâmetros de Limite
|
|
case 0xF3:// 6 Habilitar Placa de Acionamento & 7 Desligar Placa de Acionamento
|
|
case 0xFF:// 10 Iniciar Execução Automática na Inicialização & 11 Parar Execução Automática na Inicialização
|
|
case 0x8E:// 47 Confirmação MODBUS
|
|
case 0x8F:// 48 Bloqueio de Teclas - Confirmação
|
|
case 0x9A:// 49 Retorno de uma Volta
|
|
try
|
|
{
|
|
Temp1++;
|
|
if (SerialBuffer_RX[3] == 0x00)
|
|
{
|
|
leitura.Mensagem = "Erro ao configurar: (" + Temp1 + ")";
|
|
}
|
|
else if (SerialBuffer_RX[3] == 0x01)
|
|
{
|
|
leitura.Mensagem = "Sucesso ao configurar: (" + Temp1 + ")";
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
Temp1 = 0;
|
|
}
|
|
break;
|
|
|
|
case 0x91:// 32 Reiniciar Limites
|
|
if (SerialBuffer_RX[3] == 0x00)
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Falha;
|
|
}
|
|
else if (SerialBuffer_RX[3] == 0x01)
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Retornando;
|
|
}
|
|
else if (SerialBuffer_RX[3] == 0x02)
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Sucesso;
|
|
}
|
|
break;
|
|
|
|
case 0x92:// 33 Reinicialização Direta
|
|
if (SerialBuffer_RX[3] == 0x00)
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Falha;
|
|
}
|
|
else if (SerialBuffer_RX[3] == 0x01)
|
|
{
|
|
leitura.StatusMovimentoMotor = StatusComando.Sucesso;
|
|
}
|
|
break;
|
|
|
|
case 0x40:// 43 Informação de Versão
|
|
try
|
|
{
|
|
int idx = SerialBuffer_RX[3] < 9 ? SerialBuffer_RX[3] : 22 - SerialBuffer_RX[3];
|
|
leitura.HV = HardVersion[idx];
|
|
leitura.FV = "V" + SerialBuffer_RX[4] + "." + SerialBuffer_RX[5] + "." + SerialBuffer_RX[6];
|
|
for (int a = 0; a < 3; a++)
|
|
{
|
|
FV1[a] = SerialBuffer_RX[a + 4];
|
|
}
|
|
if (DataSended == 43)
|
|
{
|
|
if (leitura.Iniciado)
|
|
{
|
|
MessageBox.Show("Versão do hardware: " + leitura.HV + "\nVersão da firmware: " + leitura.FV, "Versão");
|
|
}
|
|
DataSended = 0;
|
|
}
|
|
if (SerialBuffer_RX[3] == 1 || SerialBuffer_RX[3] == 2)
|
|
{
|
|
Max_Current = 3000;
|
|
}
|
|
else if (SerialBuffer_RX[3] == 3 || SerialBuffer_RX[3] == 4)
|
|
{
|
|
Max_Current = 5200;
|
|
}
|
|
else
|
|
{
|
|
Max_Current = 3000;
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
Console.WriteLine("Erro ao requisitar versão");
|
|
}
|
|
break;
|
|
|
|
case 0x34:// 46 Estado do Portão IO
|
|
leitura.Entradas = new List<bool>() { false, false };
|
|
leitura.Saidas = new List<bool>() { false, false };
|
|
|
|
byte[] IO = new byte[1];
|
|
IO[0] = SerialBuffer_RX[3];
|
|
BitArray LimitIO = new BitArray(IO);
|
|
|
|
if (leitura.HV == HardVersion[3] || leitura.HV == HardVersion[4])
|
|
{
|
|
leitura.Entradas[0] = LimitIO.Get(0) ? false : true;
|
|
leitura.Entradas[1] = LimitIO.Get(1) ? false : true;
|
|
leitura.Saidas[0] = LimitIO.Get(2) ? false : true;
|
|
leitura.Saidas[1] = LimitIO.Get(3) ? false : true;
|
|
}
|
|
else if (leitura.HV == HardVersion[1] || leitura.HV == HardVersion[2])
|
|
{
|
|
leitura.Entradas[0] = LimitIO.Get(0) ? false : true;
|
|
}
|
|
break;
|
|
|
|
default:
|
|
MessageBox.Show("Erro ao decodificar resposta");
|
|
break;
|
|
}
|
|
|
|
leitura.UltimoComandoRecebido = DateTime.Now;
|
|
}
|
|
|
|
Respondido = true;
|
|
}
|
|
|
|
private static void rxDisplay()
|
|
{
|
|
rCHK = 0x00;
|
|
//Console.Write("RX: ");
|
|
for (int a = 0; a < Data_Number - 1; a++)
|
|
{
|
|
rCHK += SerialBuffer_RX[a];
|
|
//Console.Write("{0:X2} ", SerialBuffer_RX[a]);
|
|
}
|
|
//Console.WriteLine("{0:X2} rCHK: {1:X2} Length: {2}", SerialBuffer_RX[Data_Number > 0 ? Data_Number - 1 : Data_Number], (byte)rCHK, Data_Number);
|
|
}
|
|
|
|
private static void txDisplay()
|
|
{
|
|
return;
|
|
|
|
Console.Write("TX: ");
|
|
for (int a = 0; a < Buffer.Length; a++)
|
|
{
|
|
Console.Write("{0:X2} ", Buffer[a]);
|
|
}
|
|
Console.WriteLine("Length: {0}", Buffer.Length);
|
|
}
|
|
|
|
#endregion
|
|
|
|
|
|
}
|
|
|
|
|
|
} |