merge referenciamento direcional

This commit is contained in:
Diego Freitas 2024-11-21 13:30:09 -03:00
parent 5a10d30041
commit 0592b49fff
22 changed files with 435 additions and 82 deletions

Binary file not shown.

View File

@ -74,7 +74,7 @@ namespace AgroBase.Forms.Movimentacao
nudRPMMax.Value = (int)Disp.Dados.RPM_Max_MotorBLDC;
nudReducao.Value = (int)Disp.Dados.ReducaoMotorBLDC;
nudDiametroRoda.Value = (int)Disp.Dados.DiametroRoda * 1000;
nudDiametroRoda.Value = (int)(Disp.Dados.DiametroRoda * 1000);
txtIP.Text = Disp.Dados.IP_Bld;
}

View File

@ -293,6 +293,9 @@ namespace AgroBase.Forms.Operacoes
Rectangle rect = new Rectangle(xA - radiusCircle, yA - radiusCircle, 2 * radiusCircle, 2 * radiusCircle);
bool Acionado = false;
Acionado =
(angle == 0 && !(MKS057DService.DadosLeitura.FirstOrDefault(leitura => leitura.Endereco == Convert.ToByte(Modulo.DirMotor.Endereco, 16))?.Entradas?[0] ?? true)) ||
(angle == Math.PI / 2 && !(MKS057DService.DadosLeitura.FirstOrDefault(leitura => leitura.Endereco == Convert.ToByte(Modulo.DirMotor.Endereco, 16))?.Entradas?[1] ?? true));
using (SolidBrush brush = new SolidBrush(Acionado ? Color.Red : Color.DarkRed))
{
g.FillEllipse(brush, rect);

View File

@ -290,6 +290,9 @@ namespace AgroBase.Forms
Rectangle rect = new Rectangle(xA - radiusCircle, yA - radiusCircle, 2 * radiusCircle, 2 * radiusCircle);
bool Acionado = false;
Acionado =
(angle == 0 && !(MKS057DService.DadosLeitura.FirstOrDefault(leitura => leitura.Endereco == Convert.ToByte(Modulo.DirMotor.Endereco, 16))?.Entradas?[0] ?? true)) ||
(angle == Math.PI / 2 && !(MKS057DService.DadosLeitura.FirstOrDefault(leitura => leitura.Endereco == Convert.ToByte(Modulo.DirMotor.Endereco, 16))?.Entradas?[1] ?? true));
using (SolidBrush brush = new SolidBrush(Acionado ? Color.Red : Color.DarkRed))
{
g.FillEllipse(brush, rect);

View File

@ -82,6 +82,7 @@
this.btnCalibrar = new System.Windows.Forms.Button();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.btnGoHome = new System.Windows.Forms.Button();
this.btnGravarRetorno = new System.Windows.Forms.Button();
this.btnIrParaZero = new System.Windows.Forms.Button();
this.btnZero = new System.Windows.Forms.Button();
@ -125,13 +126,24 @@
this.label23 = new System.Windows.Forms.Label();
this.txtDirecao = new System.Windows.Forms.TextBox();
this.label22 = new System.Windows.Forms.Label();
this.btnGoHome = new System.Windows.Forms.Button();
this.chbIN1 = new System.Windows.Forms.CheckBox();
this.chbIN2 = new System.Windows.Forms.CheckBox();
this.btnEntradas = new System.Windows.Forms.Button();
this.groupBox7 = new System.Windows.Forms.GroupBox();
this.txtAnguloSP = new System.Windows.Forms.TextBox();
this.label26 = new System.Windows.Forms.Label();
this.label27 = new System.Windows.Forms.Label();
this.txtAnguloAtual = new System.Windows.Forms.TextBox();
this.label28 = new System.Windows.Forms.Label();
this.txtSensor = new System.Windows.Forms.TextBox();
this.btnIniciarRef = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.groupBox3.SuspendLayout();
this.groupBox4.SuspendLayout();
this.groupBox5.SuspendLayout();
this.groupBox6.SuspendLayout();
this.groupBox7.SuspendLayout();
this.SuspendLayout();
//
// cmbPorta
@ -226,7 +238,7 @@
this.groupBox1.Controls.Add(this.rdbHorarioPosicao);
this.groupBox1.Location = new System.Drawing.Point(259, 150);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(241, 268);
this.groupBox1.Size = new System.Drawing.Size(241, 270);
this.groupBox1.TabIndex = 8;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Controlar posição do motor";
@ -410,7 +422,7 @@
this.groupBox2.Controls.Add(this.btnCalibrar);
this.groupBox2.Location = new System.Drawing.Point(12, 150);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(241, 268);
this.groupBox2.Size = new System.Drawing.Size(241, 270);
this.groupBox2.TabIndex = 9;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Parametros";
@ -692,6 +704,16 @@
this.groupBox4.TabStop = false;
this.groupBox4.Text = "Limite";
//
// btnGoHome
//
this.btnGoHome.Location = new System.Drawing.Point(279, 103);
this.btnGoHome.Name = "btnGoHome";
this.btnGoHome.Size = new System.Drawing.Size(84, 23);
this.btnGoHome.TabIndex = 29;
this.btnGoHome.Text = "Go Home";
this.btnGoHome.UseVisualStyleBackColor = true;
this.btnGoHome.Click += new System.EventHandler(this.btnGoHome_Click);
//
// btnGravarRetorno
//
this.btnGravarRetorno.Location = new System.Drawing.Point(279, 79);
@ -819,6 +841,9 @@
//
// groupBox5
//
this.groupBox5.Controls.Add(this.btnEntradas);
this.groupBox5.Controls.Add(this.chbIN2);
this.groupBox5.Controls.Add(this.chbIN1);
this.groupBox5.Controls.Add(this.btnSobre);
this.groupBox5.Controls.Add(this.btnDesbloquear);
this.groupBox5.Controls.Add(this.btnBloqueado);
@ -840,7 +865,7 @@
this.groupBox5.Controls.Add(this.rdbHex);
this.groupBox5.Location = new System.Drawing.Point(506, 150);
this.groupBox5.Name = "groupBox5";
this.groupBox5.Size = new System.Drawing.Size(334, 268);
this.groupBox5.Size = new System.Drawing.Size(334, 270);
this.groupBox5.TabIndex = 12;
this.groupBox5.TabStop = false;
this.groupBox5.Text = "Leitura Dados";
@ -1105,21 +1130,121 @@
this.label22.TabIndex = 10;
this.label22.Text = "Direção";
//
// btnGoHome
// chbIN1
//
this.btnGoHome.Location = new System.Drawing.Point(279, 103);
this.btnGoHome.Name = "btnGoHome";
this.btnGoHome.Size = new System.Drawing.Size(84, 23);
this.btnGoHome.TabIndex = 29;
this.btnGoHome.Text = "Go Home";
this.btnGoHome.UseVisualStyleBackColor = true;
this.btnGoHome.Click += new System.EventHandler(this.btnGoHome_Click);
this.chbIN1.AutoSize = true;
this.chbIN1.Enabled = false;
this.chbIN1.Location = new System.Drawing.Point(6, 242);
this.chbIN1.Name = "chbIN1";
this.chbIN1.Size = new System.Drawing.Size(43, 17);
this.chbIN1.TabIndex = 20;
this.chbIN1.Text = "IN1";
this.chbIN1.UseVisualStyleBackColor = true;
//
// chbIN2
//
this.chbIN2.AutoSize = true;
this.chbIN2.Enabled = false;
this.chbIN2.Location = new System.Drawing.Point(63, 242);
this.chbIN2.Name = "chbIN2";
this.chbIN2.Size = new System.Drawing.Size(43, 17);
this.chbIN2.TabIndex = 21;
this.chbIN2.Text = "IN2";
this.chbIN2.UseVisualStyleBackColor = true;
//
// btnEntradas
//
this.btnEntradas.Location = new System.Drawing.Point(112, 238);
this.btnEntradas.Name = "btnEntradas";
this.btnEntradas.Size = new System.Drawing.Size(102, 23);
this.btnEntradas.TabIndex = 22;
this.btnEntradas.Text = "Entradas";
this.btnEntradas.UseVisualStyleBackColor = true;
this.btnEntradas.Click += new System.EventHandler(this.btnEntradas_Click);
//
// groupBox7
//
this.groupBox7.Controls.Add(this.btnIniciarRef);
this.groupBox7.Controls.Add(this.label28);
this.groupBox7.Controls.Add(this.txtSensor);
this.groupBox7.Controls.Add(this.label27);
this.groupBox7.Controls.Add(this.txtAnguloAtual);
this.groupBox7.Controls.Add(this.label26);
this.groupBox7.Controls.Add(this.txtAnguloSP);
this.groupBox7.Location = new System.Drawing.Point(846, 12);
this.groupBox7.Name = "groupBox7";
this.groupBox7.Size = new System.Drawing.Size(193, 408);
this.groupBox7.TabIndex = 14;
this.groupBox7.TabStop = false;
this.groupBox7.Text = "Referenciamento";
//
// txtAnguloSP
//
this.txtAnguloSP.Location = new System.Drawing.Point(87, 19);
this.txtAnguloSP.Name = "txtAnguloSP";
this.txtAnguloSP.ReadOnly = true;
this.txtAnguloSP.Size = new System.Drawing.Size(100, 20);
this.txtAnguloSP.TabIndex = 0;
//
// label26
//
this.label26.AutoSize = true;
this.label26.Location = new System.Drawing.Point(6, 22);
this.label26.Name = "label26";
this.label26.Size = new System.Drawing.Size(57, 13);
this.label26.TabIndex = 18;
this.label26.Text = "Angulo SP";
//
// label27
//
this.label27.AutoSize = true;
this.label27.Location = new System.Drawing.Point(6, 48);
this.label27.Name = "label27";
this.label27.Size = new System.Drawing.Size(67, 13);
this.label27.TabIndex = 20;
this.label27.Text = "Angulo Atual";
//
// txtAnguloAtual
//
this.txtAnguloAtual.Location = new System.Drawing.Point(87, 45);
this.txtAnguloAtual.Name = "txtAnguloAtual";
this.txtAnguloAtual.ReadOnly = true;
this.txtAnguloAtual.Size = new System.Drawing.Size(100, 20);
this.txtAnguloAtual.TabIndex = 19;
//
// label28
//
this.label28.AutoSize = true;
this.label28.Location = new System.Drawing.Point(6, 74);
this.label28.Name = "label28";
this.label28.Size = new System.Drawing.Size(40, 13);
this.label28.TabIndex = 22;
this.label28.Text = "Sensor";
//
// txtSensor
//
this.txtSensor.Location = new System.Drawing.Point(87, 71);
this.txtSensor.Name = "txtSensor";
this.txtSensor.ReadOnly = true;
this.txtSensor.Size = new System.Drawing.Size(100, 20);
this.txtSensor.TabIndex = 21;
//
// btnIniciarRef
//
this.btnIniciarRef.Location = new System.Drawing.Point(9, 376);
this.btnIniciarRef.Name = "btnIniciarRef";
this.btnIniciarRef.Size = new System.Drawing.Size(178, 23);
this.btnIniciarRef.TabIndex = 23;
this.btnIniciarRef.Text = "Iniciar Referenciamento";
this.btnIniciarRef.UseVisualStyleBackColor = true;
this.btnIniciarRef.Click += new System.EventHandler(this.btnIniciarRef_Click);
//
// frmMKS
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(855, 432);
this.ClientSize = new System.Drawing.Size(1051, 432);
this.Controls.Add(this.groupBox7);
this.Controls.Add(this.groupBox6);
this.Controls.Add(this.groupBox5);
this.Controls.Add(this.groupBox4);
@ -1141,6 +1266,8 @@
this.groupBox5.PerformLayout();
this.groupBox6.ResumeLayout(false);
this.groupBox6.PerformLayout();
this.groupBox7.ResumeLayout(false);
this.groupBox7.PerformLayout();
this.ResumeLayout(false);
}
@ -1245,5 +1372,16 @@
private System.Windows.Forms.Button btnPararTodos;
private System.Windows.Forms.Button btnIniciarTodos;
private System.Windows.Forms.Button btnGoHome;
private System.Windows.Forms.Button btnEntradas;
private System.Windows.Forms.CheckBox chbIN2;
private System.Windows.Forms.CheckBox chbIN1;
private System.Windows.Forms.GroupBox groupBox7;
private System.Windows.Forms.Label label27;
private System.Windows.Forms.TextBox txtAnguloAtual;
private System.Windows.Forms.Label label26;
private System.Windows.Forms.TextBox txtAnguloSP;
private System.Windows.Forms.Label label28;
private System.Windows.Forms.TextBox txtSensor;
private System.Windows.Forms.Button btnIniciarRef;
}
}

View File

@ -1,16 +1,10 @@
using AgroBase.Services;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static AgroBase.Models.Enums;
namespace AgroBase.Forms
{
@ -187,7 +181,7 @@ namespace AgroBase.Forms
readonly string[] CurrentText_57D = { "100", "1000", "2000", "3000", "4000", "5000", "5200" };
string[] ModosControle = { "CR_OPEN", "CR_CLOSE", "CR_vFOC", "SR_OPEN", "SR_CLOSE", "SR_vFOC" };
string[] VelocidadesPosicao = { "1", "600", "1200", "1800", "2400", "3000" };
string[] VelocidadesPosicao = { "1", "10", "18", "600", "1200", "1800", "2400", "3000" };
string[] ModosControlePosicao = { "Pulses", "RelAxis", "AbsAxis" };
string[] Rampas = { "0", "8", "16", "32", "64", "128", "255" };
string[] LimiteModos = { "Disable", "DirMode", "NearMode" };
@ -565,7 +559,7 @@ namespace AgroBase.Forms
{
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 = serialPort1.BytesToRead; // Número de bytes recebidos
if (serialPort1.BytesToRead > 0)
if (serialPort1.BytesToRead > 0 && serialPort1.BytesToRead <= SerialBuffer_RX.Length)
{
for (int a = 0; a <= Data_Number - 1; a++)
{
@ -1565,6 +1559,14 @@ namespace AgroBase.Forms
_EnderecoControlar = cmbEndereco.Text;
}
private void btnEntradas_Click(object sender, EventArgs e)
{
Button MyButton = (Button)sender;
MyButton.Tag = "46";
DataSended = Convert.ToByte(MyButton.Tag);
SendRelevantData(QueryCommand[DataSended]);
}
private void Text_display()
{
if (txtErroCarregado.InvokeRequired)
@ -1647,6 +1649,7 @@ namespace AgroBase.Forms
str = Convert.ToString(data32, 10);
txtNumeroPulsos.AppendText(str);
txtAnguloAtual.Text = Math.Round(MKS057DService.PulsosParaAngulo(Convert.ToInt32(txtNumeroPulsos.Text)), 2).ToString();
}
else
{
@ -2199,11 +2202,11 @@ namespace AgroBase.Forms
}
break;
/*case 0x34:// 46 Estado do Portão IO
GB5_textBox_IN1.Clear();
GB5_textBox_IN2.Clear();
GB5_textBox_OUT1.Clear();
GB5_textBox_OUT2.Clear();
case 0x34:// 46 Estado do Portão IO
//GB5_textBox_IN1.Clear();
//GB5_textBox_IN2.Clear();
//GB5_textBox_OUT1.Clear();
//GB5_textBox_OUT2.Clear();
byte[] IO = new byte[1];
IO[0] = SerialBuffer_RX[3];
@ -2211,19 +2214,21 @@ namespace AgroBase.Forms
if (HV == HardVersion[3] || HV == HardVersion[4])
{
GB5_textBox_IN1.AppendText(LimitIO.Get(0) ? "H" : "L");
GB5_textBox_IN2.AppendText(LimitIO.Get(1) ? "H" : "L");
GB5_textBox_OUT1.AppendText(LimitIO.Get(2) ? "H" : "L");
GB5_textBox_OUT2.AppendText(LimitIO.Get(3) ? "H" : "L");
chbIN1.Checked = LimitIO.Get(0);
txtSensor.Text = LimitIO.Get(0) ? "HIGH" : "LOW";
chbIN2.Checked = LimitIO.Get(1);
//GB5_textBox_OUT1.AppendText(LimitIO.Get(2) ? "H" : "L");
//GB5_textBox_OUT2.AppendText(LimitIO.Get(3) ? "H" : "L");
}
else if (HV == HardVersion[1] || HV == HardVersion[2])
{
GB5_textBox_IN1.AppendText(LimitIO.Get(0) ? "H" : "L");
GB5_textBox_IN2.AppendText("NC");
GB5_textBox_OUT1.AppendText("NC");
GB5_textBox_OUT2.AppendText("NC");
chbIN1.Checked = LimitIO.Get(0);
txtSensor.Text = LimitIO.Get(0) ? "HIGH" : "LOW";
//GB5_textBox_IN2.AppendText("NC");
//GB5_textBox_OUT1.AppendText("NC");
//GB5_textBox_OUT2.AppendText("NC");
}
break;*/
break;
default:
MessageBox.Show(Text1_window, Text2_window);
@ -2244,6 +2249,11 @@ namespace AgroBase.Forms
Console.WriteLine("{0:X2} rCHK: {1:X2} Length: {2}", SerialBuffer_RX[Data_Number - 1], (byte)rCHK, Data_Number);
}
private async void btnIniciarRef_Click(object sender, EventArgs e)
{
await ReferenciaMotor();
}
private void txDisplay()
{
Console.Write("TX: ");
@ -2254,6 +2264,96 @@ namespace AgroBase.Forms
Console.WriteLine("Length: {0}", Buffer.Length);
}
private async Task ReferenciaMotor()
{
byte Addr = Convert.ToByte(cmbEndereco.Text, 16);
btnEntradas_Click(btnEntradas, new EventArgs());
await Task.Delay(1000);
btnZero_Click(btnZero, new EventArgs());
await Task.Delay(1000);
btnNumeroPulsos_Click(btnNumeroPulsos, new EventArgs());
await Task.Delay(1000);
bool Sucesso = ReferenciaEstaEmZero(Addr);
double Angulo = Convert.ToDouble(txtAnguloAtual.Text);
double _anguloAnterior = Angulo;
int _angulo = 45;
int _offset = 0;
Sentido _sentido = Sentido.Horario;
int tentativas = 0;
const int MaxTentativas = 10;
if (!Sucesso)
{
while (!Sucesso && tentativas < MaxTentativas)
{
cmbVelocidadePosicao.SelectedIndex = 2;
cmbModo.SelectedIndex = 2;
txtValor.Text = _angulo.ToString();
btnIniciarPosicao_Click(btnIniciarPosicao, new EventArgs());
DateTime Inicio = DateTime.Now;
bool passou = false;
while (!Sucesso && !passou && Inicio.AddSeconds(40) > DateTime.Now)
{
Sucesso = ReferenciaEstaEmZero(Addr);
passou = ((Angulo >= (_angulo - 1) && _sentido == Sentido.Horario) || (Angulo <= (_angulo + 1) && _sentido == Sentido.Antihorario));
Console.WriteLine($"Ref {Addr}: Angulo SP = {_angulo}, Angulo Atual = {Angulo}, Sentido SP = {_sentido.ToString()}, Passou = {passou}, Sucesso = {Sucesso}");
if (Sucesso)
{
btnPararPosicao_Click(btnPararPosicao, new EventArgs());
await Task.Delay(500);
btnZero_Click(btnZero, new EventArgs());
await Task.Delay(500);
_angulo = 0;
cmbVelocidadePosicao.SelectedIndex = 1;
txtValor.Text = _angulo.ToString();
//btnIniciarPosicao_Click(btnIniciarPosicao, new EventArgs());
//await Task.Delay(500);
int _anguloRetorno = _sentido == Sentido.Horario ? -8 : 8;
txtValor.Text = _anguloRetorno.ToString();
btnIniciarPosicao_Click(btnIniciarPosicao, new EventArgs());
await Task.Delay(1000);
btnZero_Click(btnZero, new EventArgs());
await Task.Delay(500);
_angulo = 0;
txtValor.Text = _angulo.ToString();
//btnIniciarPosicao_Click(btnIniciarPosicao, new EventArgs());
//await Task.Delay(500);
break;
}
btnEntradas_Click(btnEntradas, new EventArgs());
await Task.Delay(500);
btnNumeroPulsos_Click(btnNumeroPulsos, new EventArgs());
await Task.Delay(500);
Angulo = Convert.ToDouble(txtAnguloAtual.Text);
await Task.Delay(100); // Verificações rápidas.
if (_anguloAnterior == Angulo)
{
btnIniciarPosicao_Click(btnIniciarPosicao, new EventArgs());
}
_anguloAnterior = Angulo;
}
// Alterna sentido ou ajusta o ângulo se falhar.
if (!Sucesso && passou)
{
_sentido = _sentido == Sentido.Horario ? Sentido.Antihorario : Sentido.Horario;
_offset += 25;
_angulo += _offset;
_angulo = _angulo * (_sentido == Sentido.Horario ? 1 : -1);
tentativas++;
txtValor.Text = _angulo.ToString();
txtAnguloSP.Text = txtValor.Text;
}
}
}
if (!Sucesso)
{
btnPararPosicao_Click(btnPararPosicao, new EventArgs());
}
}
private bool ReferenciaEstaEmZero(byte Addr)
{
return chbIN1.Checked;
}

View File

@ -1,9 +1,6 @@
using AgroBase.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static AgroBase.Models.Enums;
namespace AgroBase.Models
@ -16,7 +13,8 @@ namespace AgroBase.Models
get
{
// Houve comandos recebidos do driver dentro dos ultimos 10 segundos
return UltimoComandoRecebido.AddSeconds(10) > DateTime.Now;
int tempo = MKS057DService.UltimoReferenciamento.AddSeconds(10) > DateTime.Now ? 120 : 10;
return UltimoComandoRecebido.AddSeconds(tempo) > DateTime.Now;
}
}
public DateTime UltimoComandoRecebido { get; set; }

View File

@ -32,8 +32,8 @@ namespace AgroBase.Models.Modules
public double ReducaoMotorBLDC { get; set; } = 5;
public double RPM_Max_MotorBLDC { get; set; } = 500;
public string IP_Bld { get; set; } = "192.168.100.110";
public string IP_Mks { get; set; } = "192.168.100.111";
public string IP_Bld { get; set; } = "192.168.105.10";
public string IP_Mks { get; set; } = "192.168.105.11";
public List<ModuloMvdModel> Modulos { get; set; } = new List<ModuloMvdModel>();
@ -1221,65 +1221,157 @@ namespace AgroBase.Models.Modules
{
byte Addr = Convert.ToByte(Endereco, 16);
MKS057DService.AdicionarComandoNaFila(MKS057DService.MontarComandoRequisicaoIO(Addr));
MKS057DService.AdicionarComandoNaFila(MKS057DService.MontarComandoSetZero(Addr));
MKS057DService.AdicionarComandoNaFila(MKS057DService.MontarComandoRequisicaoPulsos(Addr));
MKS057DService.AddrRef = Addr;
MKS057DService.UltimoReferenciamento = DateTime.Now;
await Task.Delay(2000);
await RequisitarDadosReferenciamento(Addr);
await MKS057DService.EnviarComandoControle(MKS057DService.MontarComandoSetZero(Addr));
await Task.Delay(500);
bool Sucesso = ReferenciaEstaEmZero(Addr);
bool Sucesso = false;
bool EstadoInicial = ReferenciaEstaEmZero(Addr);
bool EstadoAnterior = EstadoInicial;
double _anguloAnterior = Angulo;
int _angulo = 45;
int _offset = 0;
Sentido _sentido = Sentido.Horario;
int tentativas = 0;
double _anguloEntrada = 9999;
double _anguloSaida = 9999;
const int MaxTentativas = 10;
DateTime TimeoutGeral = DateTime.Now.AddMinutes(3); // Timeout geral para o processo.
if (!Sucesso)
{
MKS057DService.AdicionarComandoNaFila(MKS057DService.MontarComandoMovimento(Addr, _angulo, 18, Sentido.Horario));
MKS057DService.AddrRef = Addr;
DateTime Inicio = DateTime.Now;
while (!Sucesso && Inicio.AddSeconds(30) > DateTime.Now)
while (!Sucesso && tentativas < MaxTentativas && DateTime.Now < TimeoutGeral)
{
Sucesso = ReferenciaEstaEmZero(Addr);
int VelocidadeGiro = EstadoInicial ? 10 : 18;
if (Sucesso)
await MKS057DService.EnviarComandoControle(MKS057DService.MontarComandoMovimento(Addr, _angulo, VelocidadeGiro, _sentido));
DateTime Inicio = DateTime.Now;
bool inverterGiro = false;
while (!Sucesso && !inverterGiro && Inicio.AddSeconds(40) > DateTime.Now)
{
MKS057DService.AdicionarComandoNaFila(MKS057DService.MontarComandoMovimento(Addr, Angulo, 1, Sentido.Horario));
await RequisitarDadosReferenciamento(Addr);
MKS057DService.AddrRef = 0x00;
bool _ref = ReferenciaEstaEmZero(Addr);
MKS057DService.AdicionarComandoNaFila(MKS057DService.MontarComandoSetZero(Addr));
//Sucesso = (EstadoInicial && !_ref) || (!EstadoInicial && _ref);
await Task.Delay(500);
// Comecou com o sensor ja atuado
if (EstadoInicial)
{
// Quando houver alteracao na leitura do sensor
if (_ref != EstadoAnterior)
{
// Se estava atuado e agora nao esta mais, e ainda nao definiu o angulo de entrada
if (!_ref && _anguloEntrada == 9999)
{
_anguloEntrada = Angulo;
inverterGiro = true;
}
// Se estava atuado e agora nao esta mais, e ja definiu o angulo de entrada, e ainda nao definiu o angulo de saida
else if (!_ref && _anguloEntrada != 9999 && _anguloSaida == 9999)
{
_anguloSaida = Angulo;
}
}
}
// Comecou com o sensor nao atuado
else
{
// Quando houver alteracao na leitura do sensor
if (_ref != EstadoAnterior)
{
// Se nao estava atuado e agora esta, e ainda nao definiu o angulo de entrada
if (_ref && _anguloEntrada == 9999)
{
_anguloEntrada = Angulo;
}
// Se estava atuado e agora nao esta mais, e ja definiu o angulo de entrada, e ainda nao definiu o angulo de saida
else if (!_ref && _anguloEntrada != 9999 && _anguloSaida == 9999)
{
_anguloSaida = Angulo;
}
}
}
MKS057DService.AdicionarComandoNaFila(MKS057DService.MontarComandoMovimento(Addr, 0, 1, Sentido.Parado));
break;
// Realiza a verificacao de necessidade de reverter a rotacao do motor apenas se ainda nao encontrou o angulo de entrada do sensor
if (_anguloEntrada == 9999)
{
inverterGiro = Math.Abs(Angulo - _angulo) <= 1;
}
Sucesso = _anguloEntrada != 9999 && _anguloSaida != 9999;
EstadoAnterior = _ref;
Console.WriteLine($"Ref {Addr}: Angulo SP = {_angulo}, Angulo Atual = {Angulo}, Sentido SP = {_sentido.ToString()}, Passou = {inverterGiro}, Sucesso = {Sucesso}");
if (Sucesso)
{
await MKS057DService.EnviarComandoControle(MKS057DService.MontarComandoParada(Addr));
await Task.Delay(1500);
int _centro = Convert.ToInt32((_anguloEntrada + _anguloSaida) / 2.0);
await MKS057DService.EnviarComandoControle(MKS057DService.MontarComandoMovimento(Addr, _centro, 10, Sentido.Horario));
await Task.Delay(2000);
await MKS057DService.EnviarComandoControle(MKS057DService.MontarComandoSetZero(Addr));
await Task.Delay(1000);
break;
}
await Task.Delay(100); // Verificações rápidas.
if (_anguloAnterior == Angulo)
{
await MKS057DService.EnviarComandoControle(MKS057DService.MontarComandoMovimento(Addr, _angulo, VelocidadeGiro, _sentido));
}
_anguloAnterior = Angulo;
}
if (Angulo >= 45 || Angulo <= -45)
if (!Sucesso && inverterGiro)
{
_angulo = Angulo >= 45 ? -45 : 45;
MKS057DService.AdicionarComandoNaFila(MKS057DService.MontarComandoMovimento(Addr, _angulo, 18, Sentido.Horario));
_sentido = _sentido == Sentido.Horario ? Sentido.Antihorario : Sentido.Horario;
_offset += Math.Min(25, 90 - Math.Abs(_angulo)); // Limita o offset máximo para evitar valores extremos.
_angulo = _angulo * (_sentido == Sentido.Horario ? 1 : -1) + _offset;
tentativas++;
}
await Task.Delay(500);
}
}
if (!Sucesso)
{
MKS057DService.AddrRef = 0x00;
MKS057DService.AdicionarComandoNaFila(MKS057DService.MontarComandoMovimento(Addr, 0, 18, Sentido.Parado));
await MKS057DService.EnviarComandoControle(MKS057DService.MontarComandoParada(Addr));
}
MKS057DService.AddrRef = 0x00;
}
private bool ReferenciaEstaEmZero(byte Addr)
{
var Leitura = MKS057DService.DadosLeitura.FirstOrDefault(x => x.Endereco == Addr);
bool Sucesso = Leitura != null && Leitura.Entradas != null && Leitura.Entradas[0] == true;
return Sucesso;
bool atuado = (Leitura?.Entradas?[0] ?? true) == false;
return atuado;
}
private async Task RequisitarDadosReferenciamento(byte Addr)
{
await MKS057DService.EnviarComandoControle(MKS057DService.MontarComandoRequisicaoPulsos(Addr));
await MKS057DService.EnviarComandoControle(MKS057DService.MontarComandoRequisicaoIO(Addr));
}
}
public class MvdMotorMOVSensorimanetoGrafico

View File

@ -219,6 +219,7 @@ namespace AgroBase.Services
if (!connect)
{
Console.WriteLine("Falha ao inicializar o serviço Ethernet.");
_ethernetService = null;
EnvioLiberado = true;
return false;
}

View File

@ -37,6 +37,8 @@ namespace AgroBase.Services
return AddrRef > 0x00;
}
}
public static DateTime UltimoReferenciamento = DateTime.MinValue;
public static int AnguloOffsetSensor = 8;
public static void IniciarRotinas()
{
@ -71,6 +73,7 @@ namespace AgroBase.Services
if (!connect)
{
Console.WriteLine("Falha ao inicializar o serviço Ethernet.");
_ethernetService = null;
EnvioLiberado = true;
return false;
}
@ -492,6 +495,21 @@ namespace AgroBase.Services
};
}
public static MKS057ComandoModel MontarComandoParada(byte Endereco)
{
return new MKS057ComandoModel()
{
Get = false,
Comando = Convert.ToByte("38"),
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()
@ -530,7 +548,7 @@ namespace AgroBase.Services
}
_Angulo[Addr] = ConverterAnguloParaValor(Comando.Angulo).ToString();
_Velocidade[Addr] = Comando.Velocidade.ToString();
_Velocidade[Addr] = Comando._Sentido == Sentido.Parado ? "0" : Comando.Velocidade.ToString();
_ModoControle = Comando.ModoControle;
_Sentido[Addr] = Comando._Sentido;
}
@ -1505,7 +1523,7 @@ namespace AgroBase.Services
{
PulseText = Convert.ToUInt32(_Angulo[Addr], 10);
Pulse = BitConverter.GetBytes(PulseText);
if (SpeedText2 <= 3000 && SpeedText2 >= 1)
if (SpeedText2 <= 3000 && SpeedText2 >= 0)
{
if (PulseText <= 4294967295 && PulseText >= 1)
{
@ -1565,7 +1583,7 @@ namespace AgroBase.Services
RelAxisText = Convert.ToInt32(_Angulo[Addr], 10);
RelAxis = BitConverter.GetBytes(RelAxisText * 16384 / 360);
}
if (SpeedText2 <= 3000 && SpeedText2 >= 1)
if (SpeedText2 <= 3000 && SpeedText2 >= 0)
{
if (RelAxisText <= 2147483647 && RelAxisText >= -2147483647)
{
@ -1607,7 +1625,7 @@ namespace AgroBase.Services
AbsAxisText = Convert.ToInt32(_Angulo[Addr], 10);
AbsAxis = BitConverter.GetBytes(AbsAxisText * 16384 / 360);
}
if (SpeedText2 <= 3000 && SpeedText2 >= 1)
if (SpeedText2 <= 3000 && SpeedText2 >= 0)
{
if (AbsAxisText <= 2147483647 && AbsAxisText >= -2147483647)
{

View File

@ -1,6 +1,5 @@
using AgroBase.Forms;
using AgroBase.Models;
using OpenCvSharp.Internal.Vectors;
using System;
using System.Collections.Generic;
using System.IO.Ports;
@ -759,11 +758,11 @@ namespace AgroBase.Services
{
bool ethernetEncontrado = false;
/*bool DispBld = await ProcuraDispositivoBLD();
bool DispBld = await ProcuraDispositivoBLD();
if (DispBld)
{
ethernetEncontrado = true;
}*/
}
bool DispMks = await ProcuraDispositivoMKS();
if (DispMks)

View File

@ -26,8 +26,8 @@ namespace AgroBase.Services
Endereco = slaveAddress,
Comando = ComandoAquisicaoDados(),
Verificacao = true,
TamanhoEsperado = 11,
TimeoutResposta = 1000,
TamanhoEsperado = 18,
TimeoutResposta = 2000,
};
ModbusService.AdicionarComandoNaFila(Comando);

View File

@ -14,3 +14,4 @@
11/11/2024 09:33:39:070 - Porta COM68 - 0: Erro ao processar fila de comandos. Erro=The port is closed.
11/11/2024 09:35:21:159 - Porta COM68 - 0: Erro ao processar fila de comandos. Erro=The port is closed.
11/11/2024 13:38:33:524 - Porta COM85 - 0: Erro ao processar fila de comandos. Erro=The port is closed.
21/11/2024 13:26:00:651 - Porta COM90 - 0: Erro ao processar fila de comandos. Erro=The port is closed.

View File

@ -1 +1 @@
{"Modulo_ID":"Atu","RequisitarDados":false,"Conectado":false,"QuantidadeBicos":4,"DensidadeHerbicida":1.05,"AtuacaoNivelAlto":true,"BicosPulverizadores":[{"ID":"B01","Posicao":1,"Atuado":false,"Comandar":true,"Inicializado":false,"Testando":false,"Funcoes":[21],"StatusBico":false,"MediaNivelFluxo":0.0,"Atuacoes":0,"InicioAtuacao":"0001-01-01T00:00:00","TempoAtuado":0.0},{"ID":"B02","Posicao":2,"Atuado":false,"Comandar":true,"Inicializado":false,"Testando":false,"Funcoes":[21],"StatusBico":false,"MediaNivelFluxo":0.0,"Atuacoes":0,"InicioAtuacao":"0001-01-01T00:00:00","TempoAtuado":0.0},{"ID":"B03","Posicao":3,"Atuado":false,"Comandar":true,"Inicializado":false,"Testando":false,"Funcoes":[21],"StatusBico":false,"MediaNivelFluxo":0.0,"Atuacoes":0,"InicioAtuacao":"0001-01-01T00:00:00","TempoAtuado":0.0},{"ID":"B04","Posicao":4,"Atuado":false,"Comandar":true,"Inicializado":false,"Testando":false,"Funcoes":[21],"StatusBico":false,"MediaNivelFluxo":0.0,"Atuacoes":0,"InicioAtuacao":"0001-01-01T00:00:00","TempoAtuado":0.0}],"BombaPressurizadora":{"ID":"BOMBA","BombaAtuada":false,"Ligado":false,"Comandar":true,"Inicializado":false,"Testando":false,"Funcoes":[14,35,36,37,5],"Pressao":0.0,"Potencia":0.0},"Sensores":[{"LogGrafico":[],"ID":"FLXLN","Prioridade":23,"Descricao":"Fluxo na linha principal","Componente":198,"Aferir":true,"DelayAmostragem":300,"Inicializado":false,"Testando":false,"Funcoes":[25],"Parametros":[],"UnidadeMedida":"mL/s","Leituras":[],"ValorMinimo":0.0,"ValorMaximo":0.0,"LimiteMaximo":0.0,"LimiteMinimo":0.0},{"LogGrafico":[],"ID":"MASRS","Prioridade":3,"Descricao":"Massa do reservatório de herbicida","Componente":532,"Aferir":true,"DelayAmostragem":1000,"Inicializado":false,"Testando":false,"Funcoes":[22,23],"Parametros":[],"UnidadeMedida":"Kg","Leituras":[],"ValorMinimo":0.0,"ValorMaximo":0.0,"LimiteMaximo":50.0,"LimiteMinimo":5.0},{"LogGrafico":[],"ID":"PRSLN","Prioridade":3,"Descricao":"Pressão na linha principal","Componente":333,"Aferir":true,"DelayAmostragem":1000,"Inicializado":false,"Testando":false,"Funcoes":[24],"Parametros":[["Vmin","000.00"],["Vmax","004.50"],["Pmax","174.04"]],"UnidadeMedida":"psi","Leituras":[],"ValorMinimo":0.0,"ValorMaximo":0.0,"LimiteMaximo":120.0,"LimiteMinimo":60.0}],"ScriptDeteccaoErvas":"weed_detector-1_0.py","_MassaRef":0.8,"_MassaLeituraRef":40876.37,"_MassaLeituraExtra":1895800.0,"_MassaLeitura":1895800.0,"MassaReservatorio":0.0,"VolumeReservatorio":0.0,"PercentualReservatorio":0.0,"VolumeVazaoAferido":0.0,"_FluxoMlRef":102.0,"_FluxoPulsoRef":80.0,"_LeituraPulsos":0,"_LeituraPeriodo":0,"VazaoFluxoMLpS":0.0,"VolumeVazaoML":0.0,"InicioAtuacao":"0001-01-01T00:00:00","TempoAtuado":0.0,"_PressaoVmin":0.0,"_PressaoVmax":4.5,"_PressaoMax":174.045,"_LeituraPressao":0.0,"PressaoLinha":0.0,"PressaoLinhaCalc":0.0}
{"Modulo_ID":"Atu","RequisitarDados":false,"Conectado":false,"QuantidadeBicos":4,"DensidadeHerbicida":1.05,"AtuacaoNivelAlto":true,"BicosPulverizadores":[{"ID":"B01","Posicao":1,"Atuado":false,"Comandar":true,"Inicializado":false,"Testando":false,"Funcoes":[21],"StatusBico":false,"MediaNivelFluxo":0.0},{"ID":"B02","Posicao":2,"Atuado":false,"Comandar":true,"Inicializado":false,"Testando":false,"Funcoes":[21],"StatusBico":false,"MediaNivelFluxo":0.0},{"ID":"B03","Posicao":3,"Atuado":false,"Comandar":true,"Inicializado":false,"Testando":false,"Funcoes":[21],"StatusBico":false,"MediaNivelFluxo":0.0},{"ID":"B04","Posicao":4,"Atuado":false,"Comandar":true,"Inicializado":false,"Testando":false,"Funcoes":[21],"StatusBico":false,"MediaNivelFluxo":0.0}],"BombaPressurizadora":{"ID":"BOMBA","BombaAtuada":false,"Ligado":false,"Comandar":true,"Inicializado":false,"Testando":false,"Funcoes":[14,35,36,37,5],"Pressao":0.0,"Potencia":0.0},"Sensores":[{"LogGrafico":[],"ID":"FLXLN","Prioridade":23,"Descricao":"Fluxo na linha principal","Componente":198,"Aferir":true,"DelayAmostragem":300,"Inicializado":false,"Testando":false,"Funcoes":[25],"Parametros":[],"UnidadeMedida":"mL/s","Leituras":[],"ValorMinimo":0.0,"ValorMaximo":0.0,"LimiteMaximo":0.0,"LimiteMinimo":0.0},{"LogGrafico":[],"ID":"MASRS","Prioridade":3,"Descricao":"Massa do reservatório de herbicida","Componente":532,"Aferir":true,"DelayAmostragem":1000,"Inicializado":false,"Testando":false,"Funcoes":[22,23],"Parametros":[],"UnidadeMedida":"Kg","Leituras":[],"ValorMinimo":0.0,"ValorMaximo":0.0,"LimiteMaximo":50.0,"LimiteMinimo":5.0},{"LogGrafico":[],"ID":"PRSLN","Prioridade":3,"Descricao":"Pressão na linha principal","Componente":333,"Aferir":true,"DelayAmostragem":1000,"Inicializado":false,"Testando":false,"Funcoes":[24],"Parametros":[["Vmin","000.00"],["Vmax","004.50"],["Pmax","174.04"]],"UnidadeMedida":"psi","Leituras":[],"ValorMinimo":0.0,"ValorMaximo":0.0,"LimiteMaximo":120.0,"LimiteMinimo":60.0}],"ScriptDeteccaoErvas":"weed_detector-1_0.py","_MassaRef":0.8,"_MassaLeituraRef":40876.37,"_MassaLeituraExtra":1895800.0,"_MassaLeitura":1895800.0,"MassaReservatorio":0.0,"VolumeReservatorio":0.0,"PercentualReservatorio":0.0,"VolumeVazaoAferido":0.0,"_FluxoMlRef":102.0,"_FluxoPulsoRef":80.0,"_LeituraPulsos":0,"_LeituraPeriodo":0,"VazaoFluxoMLpS":0.0,"VolumeVazaoML":0.0,"InicioAtuacao":"0001-01-01T00:00:00","FimAtuacao":"0001-01-01T00:00:00","TempoAtuado":0.0,"_PressaoVmin":0.0,"_PressaoVmax":4.5,"_PressaoMax":174.045,"_LeituraPressao":0.0,"PressaoLinha":0.0,"PressaoLinhaCalc":0.0}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long