implantado driver OID

This commit is contained in:
Diego Freitas 2025-01-10 15:52:38 -03:00
parent c34369a69e
commit 3606999705
63 changed files with 4216 additions and 1262 deletions

Binary file not shown.

View File

@ -289,6 +289,12 @@
<Compile Include="Forms\frmMvdConfig.Designer.cs">
<DependentUpon>frmMvdConfig.cs</DependentUpon>
</Compile>
<Compile Include="Forms\frmOID.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Forms\frmOID.Designer.cs">
<DependentUpon>frmOID.cs</DependentUpon>
</Compile>
<Compile Include="Forms\frmPinout.cs">
<SubType>Form</SubType>
</Compile>
@ -439,6 +445,7 @@
<Compile Include="Models\Modules\PinoutModel.cs" />
<Compile Include="Models\Modules\SensoriamentoModel.cs" />
<Compile Include="Models\MotorComum.cs" />
<Compile Include="Models\OIDModel.cs" />
<Compile Include="Models\Operacoes\OperacaoManualModel.cs" />
<Compile Include="Models\Operacoes\OperacaoMapaGPSModel.cs" />
<Compile Include="Models\Operacoes\OperacaoModel.cs" />
@ -477,6 +484,7 @@
<Compile Include="Services\MKS057DService.cs" />
<Compile Include="Services\ModbusService.cs" />
<Compile Include="Services\MqttService.cs" />
<Compile Include="Services\OIDService.cs" />
<Compile Include="Services\PythonService.cs" />
<Compile Include="Services\PZEMService.cs" />
<Compile Include="Services\SerialService.cs" />
@ -693,6 +701,9 @@
<EmbeddedResource Include="Forms\frmMvdConfig.resx">
<DependentUpon>frmMvdConfig.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Forms\frmOID.resx">
<DependentUpon>frmOID.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Forms\frmPinout.resx">
<DependentUpon>frmPinout.cs</DependentUpon>
</EmbeddedResource>

View File

@ -78,7 +78,7 @@ namespace AgroBase.Forms.Direcional
}
}
txtIP.Text = Disp.Dados.IP_Mks;
txtIP.Text = Disp.Dados.IP_Dir;
}
private void frmDirConfig_FormClosing(object sender, FormClosingEventArgs e)
@ -121,7 +121,7 @@ namespace AgroBase.Forms.Direcional
}
}
Disp.Dados.IP_Mks = txtIP.Text;
Disp.Dados.IP_Dir = txtIP.Text;
Disp.SalvarParametros(Disp.Dados);
}

View File

@ -630,7 +630,7 @@ namespace AgroBase.Forms.IHM
bool Conectado = SerialService.DispositivosMapeados.Any(x => x.Dispositivo == Enums.T_Code.Bld && x.Mod_ID == Modulo.Modulo_ID);
idx = PreencheDadosLinha(grid, Testes, idx, Conectado ? 1 : 0);
bool Inicializado = Modulo.MovMotor.BLD_Inicializado;
bool Inicializado = Modulo.MovMotor.Inicializado;
idx = PreencheDadosLinha(grid, Testes, idx, Inicializado ? 1 : 0);
var SensorTmp = Modulo_Sen.Sensores.FirstOrDefault(x => x.Componente == S_Code.sTMP && x.ID.Contains(Modulo.Modulo_ID));
@ -825,7 +825,7 @@ namespace AgroBase.Forms.IHM
bool Conectado = SerialService.DispositivosMapeados.Any(x => x.Dispositivo == Enums.T_Code.Mks && x.Mod_ID == Modulo.Modulo_ID);
idx = PreencheDadosLinha(grid, Testes, idx, Conectado ? 1 : 0);
bool Inicializado = Modulo.DirMotor.MKS_Inicializado;
bool Inicializado = Modulo.DirMotor.Inicializado;
idx = PreencheDadosLinha(grid, Testes, idx, Inicializado ? 1 : 0);
int.TryParse(Leitura?.Mensagem ?? "", out int CodigoErro);

View File

@ -28,7 +28,7 @@
/// </summary>
private void InitializeComponent()
{
this.lblD_Bld_DF = new System.Windows.Forms.Label();
this.lblD_Mov_DF = new System.Windows.Forms.Label();
this.lblD_Atu = new System.Windows.Forms.Label();
this.lblD_Sen = new System.Windows.Forms.Label();
this.lblD_Gps = new System.Windows.Forms.Label();
@ -36,13 +36,13 @@
this.lblD_Pzm = new System.Windows.Forms.Label();
this.lblD_Lra = new System.Windows.Forms.Label();
this.lblD_Wit = new System.Windows.Forms.Label();
this.lblD_Bld_DT = new System.Windows.Forms.Label();
this.lblD_Mks_DF = new System.Windows.Forms.Label();
this.lblD_Mks_EF = new System.Windows.Forms.Label();
this.lblD_Bld_EF = new System.Windows.Forms.Label();
this.lblD_Mks_DT = new System.Windows.Forms.Label();
this.lblD_Mks_ET = new System.Windows.Forms.Label();
this.lblD_Bld_ET = new System.Windows.Forms.Label();
this.lblD_Mov_DT = new System.Windows.Forms.Label();
this.lblD_Dir_DF = new System.Windows.Forms.Label();
this.lblD_Dir_EF = new System.Windows.Forms.Label();
this.lblD_Mov_EF = new System.Windows.Forms.Label();
this.lblD_Dir_DT = new System.Windows.Forms.Label();
this.lblD_Dir_ET = new System.Windows.Forms.Label();
this.lblD_Mov_ET = new System.Windows.Forms.Label();
this.lblD_Cam_S0 = new System.Windows.Forms.Label();
this.lblD_Cam_S1 = new System.Windows.Forms.Label();
this.lblD_Knt = new System.Windows.Forms.Label();
@ -75,17 +75,17 @@
((System.ComponentModel.ISupportInitialize)(this.picWifi)).BeginInit();
this.SuspendLayout();
//
// lblD_Bld_DF
// lblD_Mov_DF
//
this.lblD_Bld_DF.AutoSize = true;
this.lblD_Bld_DF.BackColor = System.Drawing.Color.Transparent;
this.lblD_Bld_DF.Cursor = System.Windows.Forms.Cursors.Hand;
this.lblD_Bld_DF.Location = new System.Drawing.Point(305, 33);
this.lblD_Bld_DF.Name = "lblD_Bld_DF";
this.lblD_Bld_DF.Size = new System.Drawing.Size(45, 24);
this.lblD_Bld_DF.TabIndex = 2;
this.lblD_Bld_DF.Text = "BLD";
this.lblD_Bld_DF.Click += new System.EventHandler(this.lblModulo_Click);
this.lblD_Mov_DF.AutoSize = true;
this.lblD_Mov_DF.BackColor = System.Drawing.Color.Transparent;
this.lblD_Mov_DF.Cursor = System.Windows.Forms.Cursors.Hand;
this.lblD_Mov_DF.Location = new System.Drawing.Point(305, 33);
this.lblD_Mov_DF.Name = "lblD_Mov_DF";
this.lblD_Mov_DF.Size = new System.Drawing.Size(54, 24);
this.lblD_Mov_DF.TabIndex = 2;
this.lblD_Mov_DF.Text = "MOV";
this.lblD_Mov_DF.Click += new System.EventHandler(this.lblModulo_Click);
//
// lblD_Atu
//
@ -169,89 +169,89 @@
this.lblD_Wit.Text = "WIT";
this.lblD_Wit.Click += new System.EventHandler(this.lblModulo_Click);
//
// lblD_Bld_DT
// lblD_Mov_DT
//
this.lblD_Bld_DT.AutoSize = true;
this.lblD_Bld_DT.BackColor = System.Drawing.Color.Lavender;
this.lblD_Bld_DT.Cursor = System.Windows.Forms.Cursors.Hand;
this.lblD_Bld_DT.Location = new System.Drawing.Point(305, 423);
this.lblD_Bld_DT.Name = "lblD_Bld_DT";
this.lblD_Bld_DT.Size = new System.Drawing.Size(45, 24);
this.lblD_Bld_DT.TabIndex = 18;
this.lblD_Bld_DT.Text = "BLD";
this.lblD_Bld_DT.Click += new System.EventHandler(this.lblModulo_Click);
this.lblD_Mov_DT.AutoSize = true;
this.lblD_Mov_DT.BackColor = System.Drawing.Color.Lavender;
this.lblD_Mov_DT.Cursor = System.Windows.Forms.Cursors.Hand;
this.lblD_Mov_DT.Location = new System.Drawing.Point(305, 423);
this.lblD_Mov_DT.Name = "lblD_Mov_DT";
this.lblD_Mov_DT.Size = new System.Drawing.Size(54, 24);
this.lblD_Mov_DT.TabIndex = 18;
this.lblD_Mov_DT.Text = "MOV";
this.lblD_Mov_DT.Click += new System.EventHandler(this.lblModulo_Click);
//
// lblD_Mks_DF
// lblD_Dir_DF
//
this.lblD_Mks_DF.AutoSize = true;
this.lblD_Mks_DF.BackColor = System.Drawing.Color.Transparent;
this.lblD_Mks_DF.Cursor = System.Windows.Forms.Cursors.Hand;
this.lblD_Mks_DF.Location = new System.Drawing.Point(346, 101);
this.lblD_Mks_DF.Name = "lblD_Mks_DF";
this.lblD_Mks_DF.Size = new System.Drawing.Size(50, 24);
this.lblD_Mks_DF.TabIndex = 19;
this.lblD_Mks_DF.Text = "MKS";
this.lblD_Mks_DF.Click += new System.EventHandler(this.lblModulo_Click);
this.lblD_Dir_DF.AutoSize = true;
this.lblD_Dir_DF.BackColor = System.Drawing.Color.Transparent;
this.lblD_Dir_DF.Cursor = System.Windows.Forms.Cursors.Hand;
this.lblD_Dir_DF.Location = new System.Drawing.Point(346, 101);
this.lblD_Dir_DF.Name = "lblD_Dir_DF";
this.lblD_Dir_DF.Size = new System.Drawing.Size(40, 24);
this.lblD_Dir_DF.TabIndex = 19;
this.lblD_Dir_DF.Text = "DIR";
this.lblD_Dir_DF.Click += new System.EventHandler(this.lblModulo_Click);
//
// lblD_Mks_EF
// lblD_Dir_EF
//
this.lblD_Mks_EF.AutoSize = true;
this.lblD_Mks_EF.BackColor = System.Drawing.Color.Transparent;
this.lblD_Mks_EF.Cursor = System.Windows.Forms.Cursors.Hand;
this.lblD_Mks_EF.Location = new System.Drawing.Point(72, 101);
this.lblD_Mks_EF.Name = "lblD_Mks_EF";
this.lblD_Mks_EF.Size = new System.Drawing.Size(50, 24);
this.lblD_Mks_EF.TabIndex = 21;
this.lblD_Mks_EF.Text = "MKS";
this.lblD_Mks_EF.Click += new System.EventHandler(this.lblModulo_Click);
this.lblD_Dir_EF.AutoSize = true;
this.lblD_Dir_EF.BackColor = System.Drawing.Color.Transparent;
this.lblD_Dir_EF.Cursor = System.Windows.Forms.Cursors.Hand;
this.lblD_Dir_EF.Location = new System.Drawing.Point(72, 101);
this.lblD_Dir_EF.Name = "lblD_Dir_EF";
this.lblD_Dir_EF.Size = new System.Drawing.Size(40, 24);
this.lblD_Dir_EF.TabIndex = 21;
this.lblD_Dir_EF.Text = "DIR";
this.lblD_Dir_EF.Click += new System.EventHandler(this.lblModulo_Click);
//
// lblD_Bld_EF
// lblD_Mov_EF
//
this.lblD_Bld_EF.AutoSize = true;
this.lblD_Bld_EF.BackColor = System.Drawing.Color.Transparent;
this.lblD_Bld_EF.Cursor = System.Windows.Forms.Cursors.Hand;
this.lblD_Bld_EF.Location = new System.Drawing.Point(120, 33);
this.lblD_Bld_EF.Name = "lblD_Bld_EF";
this.lblD_Bld_EF.Size = new System.Drawing.Size(45, 24);
this.lblD_Bld_EF.TabIndex = 20;
this.lblD_Bld_EF.Text = "BLD";
this.lblD_Bld_EF.Click += new System.EventHandler(this.lblModulo_Click);
this.lblD_Mov_EF.AutoSize = true;
this.lblD_Mov_EF.BackColor = System.Drawing.Color.Transparent;
this.lblD_Mov_EF.Cursor = System.Windows.Forms.Cursors.Hand;
this.lblD_Mov_EF.Location = new System.Drawing.Point(120, 33);
this.lblD_Mov_EF.Name = "lblD_Mov_EF";
this.lblD_Mov_EF.Size = new System.Drawing.Size(54, 24);
this.lblD_Mov_EF.TabIndex = 20;
this.lblD_Mov_EF.Text = "MOV";
this.lblD_Mov_EF.Click += new System.EventHandler(this.lblModulo_Click);
//
// lblD_Mks_DT
// lblD_Dir_DT
//
this.lblD_Mks_DT.AutoSize = true;
this.lblD_Mks_DT.BackColor = System.Drawing.Color.Lavender;
this.lblD_Mks_DT.Cursor = System.Windows.Forms.Cursors.Hand;
this.lblD_Mks_DT.Location = new System.Drawing.Point(346, 355);
this.lblD_Mks_DT.Name = "lblD_Mks_DT";
this.lblD_Mks_DT.Size = new System.Drawing.Size(50, 24);
this.lblD_Mks_DT.TabIndex = 22;
this.lblD_Mks_DT.Text = "MKS";
this.lblD_Mks_DT.Click += new System.EventHandler(this.lblModulo_Click);
this.lblD_Dir_DT.AutoSize = true;
this.lblD_Dir_DT.BackColor = System.Drawing.Color.Lavender;
this.lblD_Dir_DT.Cursor = System.Windows.Forms.Cursors.Hand;
this.lblD_Dir_DT.Location = new System.Drawing.Point(346, 355);
this.lblD_Dir_DT.Name = "lblD_Dir_DT";
this.lblD_Dir_DT.Size = new System.Drawing.Size(40, 24);
this.lblD_Dir_DT.TabIndex = 22;
this.lblD_Dir_DT.Text = "DIR";
this.lblD_Dir_DT.Click += new System.EventHandler(this.lblModulo_Click);
//
// lblD_Mks_ET
// lblD_Dir_ET
//
this.lblD_Mks_ET.AutoSize = true;
this.lblD_Mks_ET.BackColor = System.Drawing.Color.Lavender;
this.lblD_Mks_ET.Cursor = System.Windows.Forms.Cursors.Hand;
this.lblD_Mks_ET.Location = new System.Drawing.Point(72, 355);
this.lblD_Mks_ET.Name = "lblD_Mks_ET";
this.lblD_Mks_ET.Size = new System.Drawing.Size(50, 24);
this.lblD_Mks_ET.TabIndex = 24;
this.lblD_Mks_ET.Text = "MKS";
this.lblD_Mks_ET.Click += new System.EventHandler(this.lblModulo_Click);
this.lblD_Dir_ET.AutoSize = true;
this.lblD_Dir_ET.BackColor = System.Drawing.Color.Lavender;
this.lblD_Dir_ET.Cursor = System.Windows.Forms.Cursors.Hand;
this.lblD_Dir_ET.Location = new System.Drawing.Point(72, 355);
this.lblD_Dir_ET.Name = "lblD_Dir_ET";
this.lblD_Dir_ET.Size = new System.Drawing.Size(40, 24);
this.lblD_Dir_ET.TabIndex = 24;
this.lblD_Dir_ET.Text = "DIR";
this.lblD_Dir_ET.Click += new System.EventHandler(this.lblModulo_Click);
//
// lblD_Bld_ET
// lblD_Mov_ET
//
this.lblD_Bld_ET.AutoSize = true;
this.lblD_Bld_ET.BackColor = System.Drawing.Color.Lavender;
this.lblD_Bld_ET.Cursor = System.Windows.Forms.Cursors.Hand;
this.lblD_Bld_ET.Location = new System.Drawing.Point(120, 423);
this.lblD_Bld_ET.Name = "lblD_Bld_ET";
this.lblD_Bld_ET.Size = new System.Drawing.Size(45, 24);
this.lblD_Bld_ET.TabIndex = 23;
this.lblD_Bld_ET.Text = "BLD";
this.lblD_Bld_ET.Click += new System.EventHandler(this.lblModulo_Click);
this.lblD_Mov_ET.AutoSize = true;
this.lblD_Mov_ET.BackColor = System.Drawing.Color.Lavender;
this.lblD_Mov_ET.Cursor = System.Windows.Forms.Cursors.Hand;
this.lblD_Mov_ET.Location = new System.Drawing.Point(120, 423);
this.lblD_Mov_ET.Name = "lblD_Mov_ET";
this.lblD_Mov_ET.Size = new System.Drawing.Size(54, 24);
this.lblD_Mov_ET.TabIndex = 23;
this.lblD_Mov_ET.Text = "MOV";
this.lblD_Mov_ET.Click += new System.EventHandler(this.lblModulo_Click);
//
// lblD_Cam_S0
//
@ -532,13 +532,13 @@
this.Controls.Add(this.lblD_Cam_S1);
this.Controls.Add(this.lblD_Cam_S0);
this.Controls.Add(this.picDesligar);
this.Controls.Add(this.lblD_Mks_ET);
this.Controls.Add(this.lblD_Bld_ET);
this.Controls.Add(this.lblD_Mks_DT);
this.Controls.Add(this.lblD_Mks_EF);
this.Controls.Add(this.lblD_Bld_EF);
this.Controls.Add(this.lblD_Mks_DF);
this.Controls.Add(this.lblD_Bld_DT);
this.Controls.Add(this.lblD_Dir_ET);
this.Controls.Add(this.lblD_Mov_ET);
this.Controls.Add(this.lblD_Dir_DT);
this.Controls.Add(this.lblD_Dir_EF);
this.Controls.Add(this.lblD_Mov_EF);
this.Controls.Add(this.lblD_Dir_DF);
this.Controls.Add(this.lblD_Mov_DT);
this.Controls.Add(this.lblD_Wit);
this.Controls.Add(this.lblD_Lra);
this.Controls.Add(this.lblD_Pzm);
@ -546,7 +546,7 @@
this.Controls.Add(this.lblD_Gps);
this.Controls.Add(this.lblD_Sen);
this.Controls.Add(this.lblD_Atu);
this.Controls.Add(this.lblD_Bld_DF);
this.Controls.Add(this.lblD_Mov_DF);
this.Controls.Add(this.picRobo);
this.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
@ -570,7 +570,7 @@
#endregion
private System.Windows.Forms.PictureBox picRobo;
private System.Windows.Forms.Label lblD_Bld_DF;
private System.Windows.Forms.Label lblD_Mov_DF;
private System.Windows.Forms.Label lblD_Atu;
private System.Windows.Forms.Label lblD_Sen;
private System.Windows.Forms.Label lblD_Gps;
@ -578,13 +578,13 @@
private System.Windows.Forms.Label lblD_Pzm;
private System.Windows.Forms.Label lblD_Lra;
private System.Windows.Forms.Label lblD_Wit;
private System.Windows.Forms.Label lblD_Bld_DT;
private System.Windows.Forms.Label lblD_Mks_DF;
private System.Windows.Forms.Label lblD_Mks_EF;
private System.Windows.Forms.Label lblD_Bld_EF;
private System.Windows.Forms.Label lblD_Mks_DT;
private System.Windows.Forms.Label lblD_Mks_ET;
private System.Windows.Forms.Label lblD_Bld_ET;
private System.Windows.Forms.Label lblD_Mov_DT;
private System.Windows.Forms.Label lblD_Dir_DF;
private System.Windows.Forms.Label lblD_Dir_EF;
private System.Windows.Forms.Label lblD_Mov_EF;
private System.Windows.Forms.Label lblD_Dir_DT;
private System.Windows.Forms.Label lblD_Dir_ET;
private System.Windows.Forms.Label lblD_Mov_ET;
private System.Windows.Forms.PictureBox picDiagnosticos;
private System.Windows.Forms.PictureBox picOperacao;
private System.Windows.Forms.PictureBox picDesligar;

View File

@ -89,7 +89,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);
txtIP.Text = Disp.Dados.IP_Bld;
txtIP.Text = Disp.Dados.IP_Mov;
}
private void frmMovConfig_FormClosing(object sender, FormClosingEventArgs e)
@ -147,7 +147,7 @@ namespace AgroBase.Forms.Movimentacao
Disp.Dados.RPM_Max_MotorBLDC = Convert.ToInt32(nudRPMMax.Value);
Disp.Dados.ReducaoMotorBLDC = Convert.ToInt32(nudReducao.Value);
Disp.Dados.DiametroRoda = Convert.ToDouble(nudDiametroRoda.Value / 1000);
Disp.Dados.IP_Bld = txtIP.Text;
Disp.Dados.IP_Mov = txtIP.Text;
Disp.SalvarParametros(Disp.Dados);
}

View File

@ -156,8 +156,8 @@ namespace AgroBase.Forms.Operacoes
lblTensao.Text = PZEMService.UltimaLeitura.Tensao.ToString("0.00") + " v";
lblCorrente.Text = PZEMService.UltimaLeitura.Corrente.ToString("0.00") + " A";
lblRPM.Text = Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.Average(x => x.MovMotor.RPM_Roda).ToString("0") + " rpm";
lblVelocidade.Text = Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.Average(x => x.MovMotor.VelocidadeInstantanea).ToString("0.00");
lblRPM.Text = Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.Where(x => x.MovMotor.Inicializado).Average(x => x.MovMotor.RPM_Roda).ToString("0") + " rpm";
lblVelocidade.Text = Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.Where(x => x.MovMotor.Inicializado).Average(x => x.MovMotor.VelocidadeInstantanea).ToString("0.00");
var Sonar = Variaveis.OperacaoEmAndamento.Sensoriamento.SonarFrontal_Kinect;
bool sonarAtivado = (Sonar?.Iniciado ?? false) && Variaveis.OperacaoEmAndamento.Controle.SonarAtivado;
@ -207,11 +207,11 @@ namespace AgroBase.Forms.Operacoes
Label lblAngulo = pnl.Controls.OfType<Label>().FirstOrDefault(ctrl => ctrl.Name == "lblDir_" + ID);
lblAngulo.Text = ID + " " + Angulo.ToString("000") + "º";
lblAngulo.ForeColor = Modulo.DirMotor.MKS_Inicializado ? Color.Green : Color.Red;
lblAngulo.ForeColor = Modulo.DirMotor.Inicializado ? Color.Green : Color.Red;
Label lblMov = pnl.Controls.OfType<Label>().FirstOrDefault(ctrl => ctrl.Name == "lblMov_" + ID);
lblMov.Text = $"{ID} {Modulo.MovMotor.Sentido} {Modulo.MovMotor.RPM_Roda} ({Modulo.MovMotor.CodigoAlarme})";
lblMov.ForeColor = Modulo.MovMotor.BLD_Inicializado ? Color.Green : Color.Red;
lblMov.ForeColor = Modulo.MovMotor.Inicializado ? Color.Green : Color.Red;
// Use o objeto Graphics para desenhar a representação do motor
Graphics g = e.Graphics;

View File

@ -53,8 +53,8 @@ namespace AgroBase.Forms.Operacoes
private void AtualizarDispositivos()
{
chbMOVativo.Checked = Variaveis.OperacaoEmAndamento.DispMvd?.Dados?.Modulos?.Any(x => x.MovMotor.BLD_Inicializado) ?? false;
chbDIRativo.Checked = Variaveis.OperacaoEmAndamento.DispMvd?.Dados?.Modulos?.Any(x => x.DirMotor.MKS_Inicializado) ?? false;
chbMOVativo.Checked = Variaveis.OperacaoEmAndamento.DispMvd?.Dados?.Modulos?.Any(x => x.MovMotor.Inicializado) ?? false;
chbDIRativo.Checked = Variaveis.OperacaoEmAndamento.DispMvd?.Dados?.Modulos?.Any(x => x.DirMotor.Inicializado) ?? false;
chbATUativo.Checked = Variaveis.OperacaoEmAndamento.DispAtu?.Dados.Conectado ?? false;
chbGPSativo.Checked = GPSService.PortaGPS?.IsOpen ?? false;
Variaveis.OperacaoEmAndamento.chartGraficos = chartGraficos;

File diff suppressed because it is too large Load Diff

View File

@ -54,7 +54,7 @@ namespace AgroBase.Forms.Operacoes
GraficoInterativoModel graficoMovGeral;
GraficoInterativoModel graficoMovTemperatura;
GraficoInterativoModel graficoMovTensao;
GraficoInterativoModel graficoMovAlimentacao;
GraficoInterativoModel graficoMovVelocidade;
GraficoInterativoModel graficoAtu;
GraficoInterativoModel graficoSen;
@ -293,32 +293,107 @@ namespace AgroBase.Forms.Operacoes
},
});
graficoMovTensao = new GraficoInterativoModel(chartMovTensao, Momentos, new List<GraficoInterativoSerieModel>()
graficoMovAlimentacao = new GraficoInterativoModel(chartMovTensao, Momentos, new List<GraficoInterativoSerieModel>()
{
new GraficoInterativoSerieModel()
{
Titulo = "EF",
Titulo = "V EF",
Valores = LogsMovimentacao.Where(x => x.Modulo_ID == "EF").Select(x => x.Tensao).ToList(),
Visivel = true
},
new GraficoInterativoSerieModel()
{
Titulo = "ET",
Titulo = "V ET",
Valores = LogsMovimentacao.Where(x => x.Modulo_ID == "ET").Select(x => x.Tensao).ToList(),
Visivel = true
},
new GraficoInterativoSerieModel()
{
Titulo = "DT",
Titulo = "V DT",
Valores = LogsMovimentacao.Where(x => x.Modulo_ID == "DT").Select(x => x.Tensao).ToList(),
Visivel = true
},
new GraficoInterativoSerieModel()
{
Titulo = "DF",
Titulo = "V DF",
Valores = LogsMovimentacao.Where(x => x.Modulo_ID == "DF").Select(x => x.Tensao).ToList(),
Visivel = true
},
new GraficoInterativoSerieModel()
{
Titulo = "A EF",
Valores = LogsMovimentacao.Where(x => x.Modulo_ID == "EF").Select(x => x.Corrente_Motor).ToList(),
Visivel = true
},
new GraficoInterativoSerieModel()
{
Titulo = "A ET",
Valores = LogsMovimentacao.Where(x => x.Modulo_ID == "ET").Select(x => x.Corrente_Motor).ToList(),
Visivel = true
},
new GraficoInterativoSerieModel()
{
Titulo = "A DT",
Valores = LogsMovimentacao.Where(x => x.Modulo_ID == "DT").Select(x => x.Corrente_Motor).ToList(),
Visivel = true
},
new GraficoInterativoSerieModel()
{
Titulo = "A DF",
Valores = LogsMovimentacao.Where(x => x.Modulo_ID == "DF").Select(x => x.Corrente_Motor).ToList(),
Visivel = true
},
new GraficoInterativoSerieModel()
{
Titulo = "W EF",
Valores = LogsMovimentacao.Where(x => x.Modulo_ID == "EF").Select(x => x.Potencia).ToList(),
Visivel = true
},
new GraficoInterativoSerieModel()
{
Titulo = "W ET",
Valores = LogsMovimentacao.Where(x => x.Modulo_ID == "ET").Select(x => x.Potencia).ToList(),
Visivel = true
},
new GraficoInterativoSerieModel()
{
Titulo = "W DT",
Valores = LogsMovimentacao.Where(x => x.Modulo_ID == "DT").Select(x => x.Potencia).ToList(),
Visivel = true
},
new GraficoInterativoSerieModel()
{
Titulo = "W DF",
Valores = LogsMovimentacao.Where(x => x.Modulo_ID == "DF").Select(x => x.Potencia).ToList(),
Visivel = true
},
new GraficoInterativoSerieModel()
{
Titulo = "% EF",
Valores = LogsMovimentacao.Where(x => x.Modulo_ID == "EF").Select(x => x.CicloTrabalho).ToList(),
Visivel = true
},
new GraficoInterativoSerieModel()
{
Titulo = "% ET",
Valores = LogsMovimentacao.Where(x => x.Modulo_ID == "ET").Select(x => x.CicloTrabalho).ToList(),
Visivel = true
},
new GraficoInterativoSerieModel()
{
Titulo = "% DT",
Valores = LogsMovimentacao.Where(x => x.Modulo_ID == "DT").Select(x => x.CicloTrabalho).ToList(),
Visivel = true
},
new GraficoInterativoSerieModel()
{
Titulo = "% DF",
Valores = LogsMovimentacao.Where(x => x.Modulo_ID == "DF").Select(x => x.CicloTrabalho).ToList(),
Visivel = true
},
});
graficoMovVelocidade = new GraficoInterativoModel(chartMovVelocidade, Momentos, new List<GraficoInterativoSerieModel>()
@ -573,6 +648,7 @@ namespace AgroBase.Forms.Operacoes
private void InicializarCombosBusca()
{
CarregarInformacoesBusca(gpbMOV_Alimentacao_Filtro, graficoMovAlimentacao.Series.Select(x => x.Titulo).ToArray());
CarregarInformacoesBusca(gpbMOV_Geral_Filtro, graficoMovGeral.Series.Select(x => x.Titulo).ToArray());
CarregarInformacoesBusca(gpbSEN_Filtro, graficoSen.Series.Select(x => x.Titulo).ToArray());
CarregarInformacoesBusca(gpbCpu_Filtro, graficoCpu.Series.Select(x => x.Titulo).ToArray());
@ -592,7 +668,7 @@ namespace AgroBase.Forms.Operacoes
Button btnBuscar = gpb.Controls.OfType<Button>().FirstOrDefault(x => x.Name.Contains("Buscar"));
btnBuscar.Click += btnBuscarMomento_Click;
Button btnAnterior = gpb.Controls.OfType<Button>().FirstOrDefault(x => x.Name.Contains("Anterior"));
btnAnterior.Click += btnAnteriorFiltro_Click; ;
btnAnterior.Click += btnAnteriorFiltro_Click;
Button btnProximo = gpb.Controls.OfType<Button>().FirstOrDefault(x => x.Name.Contains("Proximo"));
btnProximo.Click += btnProximoFiltro_Click; ;
}
@ -655,6 +731,10 @@ namespace AgroBase.Forms.Operacoes
{
grafico = graficoSen;
}
else if (gpb.Name.Contains("MOV_Alimentacao"))
{
grafico = graficoMovAlimentacao;
}
else if (gpb.Name.Contains("MOV_Geral"))
{
grafico = graficoMovGeral;
@ -817,8 +897,11 @@ namespace AgroBase.Forms.Operacoes
txtDistanciaPercorrida.Text = distanciaPercorrida.ToString("0.00") + " m / " + distanciaOperacao.ToString("0.00") + " m";
int idxRua = Log.DistanciaPercorrida.Count() - 1;
double distanciaRua = LogsOperacao.GroupBy(x => x.DistanciaPercorrida.Count()).FirstOrDefault(x => x.Key == idxRua + 1).LastOrDefault().DistanciaPercorrida[idxRua];
double distanciaPercorridaRua = Log.DistanciaPercorrida[idxRua];
var v = LogsOperacao.GroupBy(x => x.DistanciaPercorrida.Count());
int d = Math.Max(0, idxRua);
var f = v.FirstOrDefault(x => x.Key == idxRua + 1).LastOrDefault().DistanciaPercorrida;
double distanciaRua = f.Any() ? f[d] : 0;
double distanciaPercorridaRua = Log.DistanciaPercorrida.Any() ? Log.DistanciaPercorrida[idxRua] : 0;
double percentualRua = distanciaRua > 0 ? (distanciaPercorridaRua / distanciaRua) * 100.0 : 0.0;
lblPercentualRua.Text = $"Rua {percentualRua.ToString("0.00")}%";
FuncoesGlobais.PreencheValorProgressBar(pgbPercentualRua, percentualRua);
@ -966,7 +1049,7 @@ namespace AgroBase.Forms.Operacoes
graficoMovGeral.AtualizarDados(idxMomentoAtual);
graficoMovTemperatura.AtualizarDados(idxMomentoAtual);
graficoMovTensao.AtualizarDados(idxMomentoAtual);
graficoMovAlimentacao.AtualizarDados(idxMomentoAtual);
graficoMovVelocidade.AtualizarDados(idxMomentoAtual);
AtulizarDadosMotorMovimentacao("DF");
@ -1011,17 +1094,22 @@ namespace AgroBase.Forms.Operacoes
txtMOV_Temperatura_Mediana.Text = FuncoesMatematicas.CalcularMediana(LogsMovimentacao.Where(x => x.Momento <= MomentoAtual).Select(x => x.Temperatura).ToList()).ToString("0.00");
txtMOV_Temperatura_Moda.Text = FuncoesMatematicas.CalcularModa(LogsMovimentacao.Where(x => x.Momento <= MomentoAtual).Select(x => x.Temperatura).ToList()).ToString("0.00");
GroupBox gpbTns = FuncoesGlobais.FindControlRecursive<GroupBox>(tabMovTensao, "gpbMOV_Tensao_" + ID);
TextBox txtTnsAtual = FuncoesGlobais.FindControlRecursive<TextBox>(gpbTns, "txtMOV_TensaoAt_" + ID);
txtTnsAtual.Text = Log.Tensao.ToString();
TextBox txtTnsMinima = FuncoesGlobais.FindControlRecursive<TextBox>(gpbTns, "txtMOV_TensaoMn_" + ID);
txtTnsMinima.Text = LogsMovimentacao.Where(x => x.Momento <= MomentoAtual && x.Modulo_ID == ID).Min(x => x.Tensao).ToString("0.00");
TextBox txtTnsMaxima = FuncoesGlobais.FindControlRecursive<TextBox>(gpbTns, "txtMOV_TensaoMx_" + ID);
txtTnsMaxima.Text = LogsMovimentacao.Where(x => x.Momento <= MomentoAtual && x.Modulo_ID == ID).Max(x => x.Tensao).ToString("0.00");
if (cmbMOV_AlImentacao_Componente.SelectedIndex > -1)
{
var Valores = graficoMovAlimentacao.Series.FirstOrDefault(x => x.Titulo == (cmbMOV_AlImentacao_Componente.Text.Split(' ')[0] + " " + ID)).Valores.Take(idxMomentoAtual + 1).ToList();
txtMOV_Tensao_Media.Text = LogsMovimentacao.Where(x => x.Momento <= MomentoAtual).Average(x => x.Tensao).ToString("0.00");
txtMOV_Tensao_Mediana.Text = FuncoesMatematicas.CalcularMediana(LogsMovimentacao.Where(x => x.Momento <= MomentoAtual).Select(x => x.Tensao).ToList()).ToString("0.00");
txtMOV_Tensao_Moda.Text = FuncoesMatematicas.CalcularModa(LogsMovimentacao.Where(x => x.Momento <= MomentoAtual).Select(x => x.Tensao).ToList()).ToString("0.00");
GroupBox gpbTns = FuncoesGlobais.FindControlRecursive<GroupBox>(tabMovAlimentacao, "gpbMOV_Alimentacao_" + ID);
TextBox txtTnsAtual = FuncoesGlobais.FindControlRecursive<TextBox>(gpbTns, "txtMOV_AlimentacaoAt_" + ID);
txtTnsAtual.Text = Valores[idxMomentoAtual].ToString("0.00");
TextBox txtTnsMinima = FuncoesGlobais.FindControlRecursive<TextBox>(gpbTns, "txtMOV_AlimentacaoMn_" + ID);
txtTnsMinima.Text = Valores.Min().ToString("0.00");
TextBox txtTnsMaxima = FuncoesGlobais.FindControlRecursive<TextBox>(gpbTns, "txtMOV_AlimentacaoMx_" + ID);
txtTnsMaxima.Text = Valores.Max().ToString("0.00");
}
txtMOV_Alimentacao_Media.Text = LogsMovimentacao.Where(x => x.Momento <= MomentoAtual).Average(x => x.Tensao).ToString("0.00");
txtMOV_Alimentacao_Mediana.Text = FuncoesMatematicas.CalcularMediana(LogsMovimentacao.Where(x => x.Momento <= MomentoAtual).Select(x => x.Tensao).ToList()).ToString("0.00");
txtMOV_Alimentacao_Moda.Text = FuncoesMatematicas.CalcularModa(LogsMovimentacao.Where(x => x.Momento <= MomentoAtual).Select(x => x.Tensao).ToList()).ToString("0.00");
}
private void AtualizarInformacoesAtuador()

View File

@ -106,7 +106,7 @@ namespace AgroBase.Forms
foreach (var Modulo in DispMvd.Dados.Modulos)
{
Label lblTitulo = pnlFundo.Controls.OfType<Label>().FirstOrDefault(ctrl => ctrl.Name == "lblM_" + Modulo.Modulo_ID);
lblTitulo.ForeColor = Modulo.MovMotor.Comandar ? Modulo.MovMotor.BLD_Inicializado ? Color.Green : Color.Red : Color.Black;
lblTitulo.ForeColor = Modulo.MovMotor.Comandar ? Modulo.MovMotor.Inicializado ? Color.Green : Color.Red : Color.Black;
lblTitulo.Text = lblTitulo.Text.Split(' ')[0] + " (" + Modulo.Modulo_ID + ") - Alm: " + Modulo.MovMotor.CodigoAlarme;
Label lblM_RPMSP = pnlFundo.Controls.OfType<Label>().FirstOrDefault(ctrl => ctrl.Name == "lbl" + Modulo.Modulo_ID + "M_RPMSP");
lblM_RPMSP.Text = "RPM SP: " + Modulo.MovMotor.RPM_SP_Leitura.ToString("0.00");
@ -122,7 +122,7 @@ namespace AgroBase.Forms
lblM_Temperatura.Text = "Temperatura: " + Modulo.MovMotor.Temperatura.ToString("0.00") + "ºC";
lblM_Temperatura.ForeColor = Modulo.MovMotor.CodigoAlarme > 0 ? Color.Red : Color.Black;
Label lblM_Corrente = pnlFundo.Controls.OfType<Label>().FirstOrDefault(ctrl => ctrl.Name == "lbl" + Modulo.Modulo_ID + "M_Corrente");
lblM_Corrente.Text = "Corrente: " + Modulo.MovMotor.Corrente_Max.ToString("0.00") + "A";
lblM_Corrente.Text = "Corrente: " + Modulo.MovMotor.Corrente_Motor.ToString("0.00") + "A";
Label lblM_Tensao = pnlFundo.Controls.OfType<Label>().FirstOrDefault(ctrl => ctrl.Name == "lbl" + Modulo.Modulo_ID + "M_Tensao");
lblM_Tensao.Text = "Tensão: " + Modulo.MovMotor.Tensao.ToString("0.00") + "V";
@ -145,13 +145,6 @@ namespace AgroBase.Forms
chart.Series.Clear();
List<string> Momentos = Logs.Select(x => x.Momento.ToString("mm:ss:fff")).ToList();
var serieTensao = new Series("Tensão: " + (Log != null ? Log.Tensao : 0));
serieTensao.Points.DataBindXY(Momentos, Logs.Select(x => x.Tensao).ToList());
serieTensao.ChartType = SeriesChartType.Line;
chart.Series.Add(serieTensao);
Minimo = Logs.Any() && Logs.Min(x => x.Tensao) < Minimo ? Logs.Min(x => x.Tensao) : Minimo;
Maximo = Logs.Any() && Logs.Max(x => x.Tensao) > Maximo ? Logs.Max(x => x.Tensao) : Maximo;
var serieRPMsp = new Series("RPM SP: " + (Log != null ? Log.RPM_SP : 0));
serieRPMsp.Points.DataBindXY(Momentos, Logs.Select(x => x.RPM_SP).ToList());
serieRPMsp.ChartType = SeriesChartType.Line;
@ -166,13 +159,6 @@ namespace AgroBase.Forms
Minimo = Logs.Any() && Logs.Min(x => x.RPM_Roda) < Minimo ? Logs.Min(x => x.RPM_Roda) : Minimo;
Maximo = Logs.Any() && Logs.Max(x => x.RPM_Roda) > Maximo ? Logs.Max(x => x.RPM_Roda) : Maximo;
var serieRPMMotor = new Series("RPM Motor: " + (Log != null ? Log.RPM_Motor : 0));
serieRPMMotor.Points.DataBindXY(Momentos, Logs.Select(x => x.RPM_Motor).ToList());
serieRPMMotor.ChartType = SeriesChartType.Spline;
chart.Series.Add(serieRPMMotor);
Minimo = Logs.Any() && Logs.Min(x => x.RPM_Motor) < Minimo ? Logs.Min(x => x.RPM_Motor) : Minimo;
Maximo = Logs.Any() && Logs.Max(x => x.RPM_Motor) > Maximo ? Logs.Max(x => x.RPM_Motor) : Maximo;
var serieTemperatura = new Series("Motor ºC: " + (Log != null ? Log.Temperatura : 0));
serieTemperatura.Points.DataBindXY(Momentos, Logs.Select(x => x.Temperatura).ToList());
serieTemperatura.ChartType = SeriesChartType.Line;
@ -187,6 +173,34 @@ namespace AgroBase.Forms
Minimo = Logs.Any() && Logs.Min(x => x.TemperaturaDriver) < Minimo ? Logs.Min(x => x.TemperaturaDriver) : Minimo;
Maximo = Logs.Any() && Logs.Max(x => x.TemperaturaDriver) > Maximo ? Logs.Max(x => x.TemperaturaDriver) : Maximo;
var serieTensao = new Series("Tensão: " + (Log != null ? Log.Tensao : 0));
serieTensao.Points.DataBindXY(Momentos, Logs.Select(x => x.Tensao).ToList());
serieTensao.ChartType = SeriesChartType.Line;
chart.Series.Add(serieTensao);
Minimo = Logs.Any() && Logs.Min(x => x.Tensao) < Minimo ? Logs.Min(x => x.Tensao) : Minimo;
Maximo = Logs.Any() && Logs.Max(x => x.Tensao) > Maximo ? Logs.Max(x => x.Tensao) : Maximo;
var serieCorrente = new Series("Corrente: " + (Log != null ? Log.Corrente : 0));
serieCorrente.Points.DataBindXY(Momentos, Logs.Select(x => x.Corrente).ToList());
serieCorrente.ChartType = SeriesChartType.Line;
chart.Series.Add(serieCorrente);
Minimo = Logs.Any() && Logs.Min(x => x.Corrente) < Minimo ? Logs.Min(x => x.Corrente) : Minimo;
Maximo = Logs.Any() && Logs.Max(x => x.Corrente) > Maximo ? Logs.Max(x => x.Corrente) : Maximo;
var seriePotencia = new Series("Potencia: " + (Log != null ? Log.Potencia : 0));
seriePotencia.Points.DataBindXY(Momentos, Logs.Select(x => x.Potencia).ToList());
seriePotencia.ChartType = SeriesChartType.Line;
chart.Series.Add(seriePotencia);
Minimo = Logs.Any() && Logs.Min(x => x.Potencia) < Minimo ? Logs.Min(x => x.Potencia) : Minimo;
Maximo = Logs.Any() && Logs.Max(x => x.Potencia) > Maximo ? Logs.Max(x => x.Potencia) : Maximo;
var serieCicloTrabalho = new Series("Ciclo Trabalho %: " + (Log != null ? Log.CicloTrabalho : 0));
serieCicloTrabalho.Points.DataBindXY(Momentos, Logs.Select(x => x.CicloTrabalho).ToList());
serieCicloTrabalho.ChartType = SeriesChartType.Line;
chart.Series.Add(serieCicloTrabalho);
Minimo = Logs.Any() && Logs.Min(x => x.CicloTrabalho) < Minimo ? Logs.Min(x => x.CicloTrabalho) : Minimo;
Maximo = Logs.Any() && Logs.Max(x => x.CicloTrabalho) > Maximo ? Logs.Max(x => x.CicloTrabalho) : Maximo;
foreach (var legend in chart.Legends)
{
legend.Docking = Docking.Bottom;

483
AgroBase/AgroBase/Forms/frmOID.Designer.cs generated Normal file
View File

@ -0,0 +1,483 @@
namespace AgroBase.Forms
{
partial class frmOID
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.btnERPM = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.nudEndereco = new System.Windows.Forms.NumericUpDown();
this.label1 = new System.Windows.Forms.Label();
this.txtERPM = new System.Windows.Forms.TextBox();
this.txtCorrente = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.txtTensao = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.txtPotencia = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.txtCicloTrabalho = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.txtTemperatura = new System.Windows.Forms.TextBox();
this.label6 = new System.Windows.Forms.Label();
this.button3 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.button5 = new System.Windows.Forms.Button();
this.button6 = new System.Windows.Forms.Button();
this.button7 = new System.Windows.Forms.Button();
this.label7 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.txtCodErro = new System.Windows.Forms.TextBox();
this.label8 = new System.Windows.Forms.Label();
this.checkBox1 = new System.Windows.Forms.CheckBox();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.txtConsole = new System.Windows.Forms.RichTextBox();
this.button8 = new System.Windows.Forms.Button();
this.button9 = new System.Windows.Forms.Button();
this.button10 = new System.Windows.Forms.Button();
this.nudVelocidade = new System.Windows.Forms.NumericUpDown();
this.button11 = new System.Windows.Forms.Button();
this.cmbModo = new System.Windows.Forms.ComboBox();
this.chbLeitura = new System.Windows.Forms.CheckBox();
this.timer2 = new System.Windows.Forms.Timer(this.components);
this.chbControle = new System.Windows.Forms.CheckBox();
((System.ComponentModel.ISupportInitialize)(this.nudEndereco)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.nudVelocidade)).BeginInit();
this.SuspendLayout();
//
// btnERPM
//
this.btnERPM.Location = new System.Drawing.Point(215, 130);
this.btnERPM.Name = "btnERPM";
this.btnERPM.Size = new System.Drawing.Size(75, 20);
this.btnERPM.TabIndex = 0;
this.btnERPM.Text = "Ler";
this.btnERPM.UseVisualStyleBackColor = true;
this.btnERPM.Click += new System.EventHandler(this.btnERPM_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(439, 259);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 1;
this.button2.Text = "Ler tudo";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// nudEndereco
//
this.nudEndereco.Location = new System.Drawing.Point(18, 31);
this.nudEndereco.Name = "nudEndereco";
this.nudEndereco.Size = new System.Drawing.Size(50, 20);
this.nudEndereco.TabIndex = 2;
this.nudEndereco.Value = new decimal(new int[] {
1,
0,
0,
0});
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(15, 133);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(38, 13);
this.label1.TabIndex = 3;
this.label1.Text = "ERPM";
//
// txtERPM
//
this.txtERPM.Location = new System.Drawing.Point(109, 130);
this.txtERPM.Name = "txtERPM";
this.txtERPM.Size = new System.Drawing.Size(100, 20);
this.txtERPM.TabIndex = 4;
//
// txtCorrente
//
this.txtCorrente.Location = new System.Drawing.Point(109, 156);
this.txtCorrente.Name = "txtCorrente";
this.txtCorrente.Size = new System.Drawing.Size(100, 20);
this.txtCorrente.TabIndex = 6;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(15, 159);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(47, 13);
this.label2.TabIndex = 5;
this.label2.Text = "Corrente";
//
// txtTensao
//
this.txtTensao.Location = new System.Drawing.Point(109, 182);
this.txtTensao.Name = "txtTensao";
this.txtTensao.Size = new System.Drawing.Size(100, 20);
this.txtTensao.TabIndex = 8;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(15, 185);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(43, 13);
this.label3.TabIndex = 7;
this.label3.Text = "Tensao";
//
// txtPotencia
//
this.txtPotencia.Location = new System.Drawing.Point(109, 208);
this.txtPotencia.Name = "txtPotencia";
this.txtPotencia.Size = new System.Drawing.Size(100, 20);
this.txtPotencia.TabIndex = 10;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(15, 211);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(49, 13);
this.label4.TabIndex = 9;
this.label4.Text = "Potencia";
//
// txtCicloTrabalho
//
this.txtCicloTrabalho.Location = new System.Drawing.Point(109, 234);
this.txtCicloTrabalho.Name = "txtCicloTrabalho";
this.txtCicloTrabalho.Size = new System.Drawing.Size(100, 20);
this.txtCicloTrabalho.TabIndex = 12;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(15, 237);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(86, 13);
this.label5.TabIndex = 11;
this.label5.Text = "Ciclo Trabalho %";
//
// txtTemperatura
//
this.txtTemperatura.Location = new System.Drawing.Point(109, 260);
this.txtTemperatura.Name = "txtTemperatura";
this.txtTemperatura.Size = new System.Drawing.Size(100, 20);
this.txtTemperatura.TabIndex = 14;
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(15, 263);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(67, 13);
this.label6.TabIndex = 13;
this.label6.Text = "Temperatura";
//
// button3
//
this.button3.Location = new System.Drawing.Point(215, 155);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(75, 20);
this.button3.TabIndex = 15;
this.button3.Text = "Ler";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// button4
//
this.button4.Location = new System.Drawing.Point(215, 182);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(75, 20);
this.button4.TabIndex = 16;
this.button4.Text = "Ler";
this.button4.UseVisualStyleBackColor = true;
this.button4.Click += new System.EventHandler(this.button4_Click);
//
// button5
//
this.button5.Location = new System.Drawing.Point(215, 208);
this.button5.Name = "button5";
this.button5.Size = new System.Drawing.Size(75, 20);
this.button5.TabIndex = 17;
this.button5.Text = "Ler";
this.button5.UseVisualStyleBackColor = true;
this.button5.Click += new System.EventHandler(this.button5_Click);
//
// button6
//
this.button6.Location = new System.Drawing.Point(215, 234);
this.button6.Name = "button6";
this.button6.Size = new System.Drawing.Size(75, 20);
this.button6.TabIndex = 18;
this.button6.Text = "Ler";
this.button6.UseVisualStyleBackColor = true;
this.button6.Click += new System.EventHandler(this.button6_Click);
//
// button7
//
this.button7.Location = new System.Drawing.Point(215, 260);
this.button7.Name = "button7";
this.button7.Size = new System.Drawing.Size(75, 20);
this.button7.TabIndex = 19;
this.button7.Text = "Ler";
this.button7.UseVisualStyleBackColor = true;
this.button7.Click += new System.EventHandler(this.button7_Click);
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(15, 15);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(53, 13);
this.label7.TabIndex = 20;
this.label7.Text = "Endereco";
//
// button1
//
this.button1.Location = new System.Drawing.Point(215, 104);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 20);
this.button1.TabIndex = 23;
this.button1.Text = "Ler";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// txtCodErro
//
this.txtCodErro.Location = new System.Drawing.Point(109, 104);
this.txtCodErro.Name = "txtCodErro";
this.txtCodErro.Size = new System.Drawing.Size(100, 20);
this.txtCodErro.TabIndex = 22;
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(15, 107);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(48, 13);
this.label8.TabIndex = 21;
this.label8.Text = "Cod Erro";
//
// checkBox1
//
this.checkBox1.AutoSize = true;
this.checkBox1.Location = new System.Drawing.Point(441, 15);
this.checkBox1.Name = "checkBox1";
this.checkBox1.Size = new System.Drawing.Size(73, 17);
this.checkBox1.TabIndex = 24;
this.checkBox1.Text = "Heartbeat";
this.checkBox1.UseVisualStyleBackColor = true;
this.checkBox1.CheckedChanged += new System.EventHandler(this.checkBox1_CheckedChanged);
//
// timer1
//
this.timer1.Interval = 300;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// txtConsole
//
this.txtConsole.Location = new System.Drawing.Point(12, 288);
this.txtConsole.Name = "txtConsole";
this.txtConsole.Size = new System.Drawing.Size(502, 150);
this.txtConsole.TabIndex = 25;
this.txtConsole.Text = "";
//
// button8
//
this.button8.Location = new System.Drawing.Point(439, 143);
this.button8.Name = "button8";
this.button8.Size = new System.Drawing.Size(75, 23);
this.button8.TabIndex = 26;
this.button8.Text = "Para Frente";
this.button8.UseVisualStyleBackColor = true;
this.button8.Click += new System.EventHandler(this.button8_Click);
//
// button9
//
this.button9.Location = new System.Drawing.Point(439, 172);
this.button9.Name = "button9";
this.button9.Size = new System.Drawing.Size(75, 23);
this.button9.TabIndex = 27;
this.button9.Text = "Para Tras";
this.button9.UseVisualStyleBackColor = true;
this.button9.Click += new System.EventHandler(this.button9_Click);
//
// button10
//
this.button10.Location = new System.Drawing.Point(439, 201);
this.button10.Name = "button10";
this.button10.Size = new System.Drawing.Size(75, 23);
this.button10.TabIndex = 28;
this.button10.Text = "Parar";
this.button10.UseVisualStyleBackColor = true;
this.button10.Click += new System.EventHandler(this.button10_Click);
//
// nudVelocidade
//
this.nudVelocidade.Location = new System.Drawing.Point(439, 117);
this.nudVelocidade.Maximum = new decimal(new int[] {
9999,
0,
0,
0});
this.nudVelocidade.Name = "nudVelocidade";
this.nudVelocidade.Size = new System.Drawing.Size(75, 20);
this.nudVelocidade.TabIndex = 29;
//
// button11
//
this.button11.Location = new System.Drawing.Point(439, 230);
this.button11.Name = "button11";
this.button11.Size = new System.Drawing.Size(75, 23);
this.button11.TabIndex = 30;
this.button11.Text = "Freio";
this.button11.UseVisualStyleBackColor = true;
this.button11.Click += new System.EventHandler(this.button11_Click);
//
// cmbModo
//
this.cmbModo.FormattingEnabled = true;
this.cmbModo.Location = new System.Drawing.Point(439, 90);
this.cmbModo.Name = "cmbModo";
this.cmbModo.Size = new System.Drawing.Size(75, 21);
this.cmbModo.TabIndex = 31;
this.cmbModo.SelectedIndexChanged += new System.EventHandler(this.cmbModo_SelectedIndexChanged);
//
// chbLeitura
//
this.chbLeitura.AutoSize = true;
this.chbLeitura.Location = new System.Drawing.Point(18, 81);
this.chbLeitura.Name = "chbLeitura";
this.chbLeitura.Size = new System.Drawing.Size(137, 17);
this.chbLeitura.TabIndex = 32;
this.chbLeitura.Text = "Atualizacao Automatica";
this.chbLeitura.UseVisualStyleBackColor = true;
this.chbLeitura.CheckedChanged += new System.EventHandler(this.checkBox2_CheckedChanged);
//
// timer2
//
this.timer2.Tick += new System.EventHandler(this.timer2_Tick);
//
// chbControle
//
this.chbControle.AutoSize = true;
this.chbControle.Location = new System.Drawing.Point(215, 15);
this.chbControle.Name = "chbControle";
this.chbControle.Size = new System.Drawing.Size(105, 17);
this.chbControle.TabIndex = 33;
this.chbControle.Text = "Controle Sistema";
this.chbControle.UseVisualStyleBackColor = true;
//
// frmOID
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(524, 450);
this.Controls.Add(this.chbControle);
this.Controls.Add(this.chbLeitura);
this.Controls.Add(this.cmbModo);
this.Controls.Add(this.button11);
this.Controls.Add(this.nudVelocidade);
this.Controls.Add(this.button10);
this.Controls.Add(this.button9);
this.Controls.Add(this.button8);
this.Controls.Add(this.txtConsole);
this.Controls.Add(this.checkBox1);
this.Controls.Add(this.button1);
this.Controls.Add(this.txtCodErro);
this.Controls.Add(this.label8);
this.Controls.Add(this.label7);
this.Controls.Add(this.button7);
this.Controls.Add(this.button6);
this.Controls.Add(this.button5);
this.Controls.Add(this.button4);
this.Controls.Add(this.button3);
this.Controls.Add(this.txtTemperatura);
this.Controls.Add(this.label6);
this.Controls.Add(this.txtCicloTrabalho);
this.Controls.Add(this.label5);
this.Controls.Add(this.txtPotencia);
this.Controls.Add(this.label4);
this.Controls.Add(this.txtTensao);
this.Controls.Add(this.label3);
this.Controls.Add(this.txtCorrente);
this.Controls.Add(this.label2);
this.Controls.Add(this.txtERPM);
this.Controls.Add(this.label1);
this.Controls.Add(this.nudEndereco);
this.Controls.Add(this.button2);
this.Controls.Add(this.btnERPM);
this.Name = "frmOID";
this.Text = "frmOID";
this.Load += new System.EventHandler(this.frmOID_Load);
((System.ComponentModel.ISupportInitialize)(this.nudEndereco)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.nudVelocidade)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnERPM;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.NumericUpDown nudEndereco;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox txtERPM;
private System.Windows.Forms.TextBox txtCorrente;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox txtTensao;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox txtPotencia;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox txtCicloTrabalho;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.TextBox txtTemperatura;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Button button4;
private System.Windows.Forms.Button button5;
private System.Windows.Forms.Button button6;
private System.Windows.Forms.Button button7;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox txtCodErro;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.CheckBox checkBox1;
private System.Windows.Forms.Timer timer1;
private System.Windows.Forms.RichTextBox txtConsole;
private System.Windows.Forms.Button button8;
private System.Windows.Forms.Button button9;
private System.Windows.Forms.Button button10;
private System.Windows.Forms.NumericUpDown nudVelocidade;
private System.Windows.Forms.Button button11;
private System.Windows.Forms.ComboBox cmbModo;
private System.Windows.Forms.CheckBox chbLeitura;
private System.Windows.Forms.Timer timer2;
private System.Windows.Forms.CheckBox chbControle;
}
}

View File

@ -0,0 +1,213 @@
using AgroBase.Models;
using AgroBase.Services;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AgroBase.Forms
{
public partial class frmOID : Form
{
byte Addr = 0x01;
OIDModoControle ModoControle = OIDModoControle.Velocidade;
public frmOID()
{
InitializeComponent();
}
private void frmOID_Load(object sender, EventArgs e)
{
nudEndereco.Value = Convert.ToInt32(Addr);
cmbModo.Items.Clear();
cmbModo.Items.AddRange(new string[] { "ControleCorrente", "ControleVelocidade", "ControleCicloTrabalho" });
cmbModo.SelectedIndex = (int)ModoControle;
}
private async Task EnviarComando(bool get, int tamanho, string parametro, bool aguarda = true, float? val = null)
{
Addr = Convert.ToByte(nudEndereco.Value);
var Comando = new Models.OIDComandoModel()
{
Endereco = Addr,
AguardaResposta = aguarda,
TamanhoEsperado = tamanho,
Get = get,
Parametro = OIDService.Parametros.First(x => x.Chave == parametro),
};
if (val != null)
{
Comando.Valor = (float)val;
}
await OIDService.EnviarComandoControle(Comando);
txtConsole.Text += SerialService.MostrarComandoResposta(Enums.T_Code.Oid, Comando.Comando, Comando.Resposta) + Environment.NewLine;
}
private async void btnERPM_Click(object sender, EventArgs e)
{
await EnviarComando(true, 9, "VelocidadeAngular");
txtERPM.Text = (OIDService.DadosLeitura.FirstOrDefault(x => x.Endereco == Addr)?.ERPM ?? 0).ToString();
}
private async void button3_Click(object sender, EventArgs e)
{
await EnviarComando(true, 9, "CorrenteMotor");
txtCorrente.Text = (OIDService.DadosLeitura.FirstOrDefault(x => x.Endereco == Addr)?.CorrenteMotor ?? 0).ToString();
}
private async void button4_Click(object sender, EventArgs e)
{
await EnviarComando(true, 9, "Tensao");
txtTensao.Text = (OIDService.DadosLeitura.FirstOrDefault(x => x.Endereco == Addr)?.Tensao ?? 0).ToString();
}
private async void button5_Click(object sender, EventArgs e)
{
await EnviarComando(true, 9, "Potencia");
txtPotencia.Text = (OIDService.DadosLeitura.FirstOrDefault(x => x.Endereco == Addr)?.Potencia ?? 0).ToString();
}
private async void button6_Click(object sender, EventArgs e)
{
await EnviarComando(true, 9, "CicloTrabalho");
txtCicloTrabalho.Text = (OIDService.DadosLeitura.FirstOrDefault(x => x.Endereco == Addr)?.CicloTrabalho ?? 0).ToString();
}
private async void button7_Click(object sender, EventArgs e)
{
await EnviarComando(true, 7, "Temperatura");
txtTemperatura.Text = (OIDService.DadosLeitura.FirstOrDefault(x => x.Endereco == Addr)?.Temperatura ?? 0).ToString();
}
private async void button1_Click(object sender, EventArgs e)
{
await EnviarComando(true, 7, "CodErro");
txtCodErro.Text = (OIDService.DadosLeitura.FirstOrDefault(x => x.Endereco == Addr)?.CodigoAlarme ?? 0).ToString();
}
private async void button2_Click(object sender, EventArgs e)
{
btnERPM_Click(sender, e);
await Task.Delay(300);
button3_Click(sender, e);
await Task.Delay(300);
button4_Click(sender, e);
await Task.Delay(300);
button5_Click(sender, e);
await Task.Delay(300);
button6_Click(sender, e);
await Task.Delay(300);
button7_Click(sender, e);
await Task.Delay(300);
button1_Click(sender, e);
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
timer1.Enabled = checkBox1.Checked;
}
private async void timer1_Tick(object sender, EventArgs e)
{
var p = OIDService.Parametros.First(x => x.Chave == "Heartbeat");
int v = OIDService.DadosLeitura.FirstOrDefault(x => x.Endereco == Addr)?.Heartbeat ?? 0;
int nV = v == 0 ? 1 : 0;
await EnviarComando(false, 7, "Heartbeat", false, nV);
}
private async void button8_Click(object sender, EventArgs e)
{
float vel = (float)nudVelocidade.Value;
if (chbControle.Checked)
{
//var Mod = Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.FirstOrDefault(x => x.MovMotor.EnderecoByte == Addr);
//Mod.MovMotor.EnviarComandoControle(Enums.Direcao.Frente);
GeneralJoystick.EnviaComandoMotor(Keys.Up, Enums.T_Code.Mov);
}
else
{
await EnviarComando(false, 8, cmbModo.Text, false, vel);
}
}
private async void button9_Click(object sender, EventArgs e)
{
float vel = (float)nudVelocidade.Value * -1;
if (chbControle.Checked)
{
//var Mod = Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.FirstOrDefault(x => x.MovMotor.EnderecoByte == Addr);
//Mod.MovMotor.EnviarComandoControle(Enums.Direcao.Tras);
GeneralJoystick.EnviaComandoMotor(Keys.Down, Enums.T_Code.Mov);
}
else
{
await EnviarComando(false, 8, cmbModo.Text, false, vel);
}
}
private async void button10_Click(object sender, EventArgs e)
{
if (chbControle.Checked)
{
//var Mod = Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.FirstOrDefault(x => x.MovMotor.EnderecoByte == Addr);
//Mod.MovMotor.EnviarComandoControle(Enums.Direcao.Parado);
GeneralJoystick.EnviaComandoMotor(Keys.Escape, Enums.T_Code.Mov);
}
else
{
await EnviarComando(false, 8, cmbModo.Text, false, 0);
}
}
private async void button11_Click(object sender, EventArgs e)
{
if (chbControle.Checked)
{
//var Mod = Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.FirstOrDefault(x => x.MovMotor.EnderecoByte == Addr);
//Mod.MovMotor.EnviarComandoControle(Enums.Direcao.EmFreio);
GeneralJoystick.EnviaComandoMotor(Keys.Space, Enums.T_Code.Mov);
}
else
{
if (ModoControle != OIDModoControle.Freio)
{
await EnviarComando(false, 8, "ModoControle", false, (int)OIDModoControle.Freio);
ModoControle = OIDModoControle.Freio;
}
}
}
private async void cmbModo_SelectedIndexChanged(object sender, EventArgs e)
{
ModoControle = (OIDModoControle)cmbModo.SelectedIndex;
await EnviarComando(false, 8, "ModoControle", false, (int)ModoControle);
}
private void timer2_Tick(object sender, EventArgs e)
{
txtERPM.Text = (OIDService.DadosLeitura.FirstOrDefault(x => x.Endereco == Addr)?.ERPM ?? 0).ToString();
txtCorrente.Text = (OIDService.DadosLeitura.FirstOrDefault(x => x.Endereco == Addr)?.CorrenteMotor ?? 0).ToString();
txtTensao.Text = (OIDService.DadosLeitura.FirstOrDefault(x => x.Endereco == Addr)?.Tensao ?? 0).ToString();
txtPotencia.Text = (OIDService.DadosLeitura.FirstOrDefault(x => x.Endereco == Addr)?.Potencia ?? 0).ToString();
txtCicloTrabalho.Text = (OIDService.DadosLeitura.FirstOrDefault(x => x.Endereco == Addr)?.CicloTrabalho ?? 0).ToString();
txtTemperatura.Text = (OIDService.DadosLeitura.FirstOrDefault(x => x.Endereco == Addr)?.Temperatura ?? 0).ToString();
txtCodErro.Text = (OIDService.DadosLeitura.FirstOrDefault(x => x.Endereco == Addr)?.CodigoAlarme ?? 0).ToString();
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
timer2.Enabled = chbLeitura.Checked;
}
}
}

View File

@ -0,0 +1,126 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="timer1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="timer2.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>105, 17</value>
</metadata>
</root>

View File

@ -34,6 +34,8 @@ namespace AgroBase
this.lblStripErro = new System.Windows.Forms.ToolStripStatusLabel();
this.lblStatusConexao = new System.Windows.Forms.ToolStripStatusLabel();
this.pnlLateral = new System.Windows.Forms.Panel();
this.lblCodErro = new System.Windows.Forms.Label();
this.txtCodErro = new System.Windows.Forms.TextBox();
this.chbConexaoautomatica = new System.Windows.Forms.CheckBox();
this.gpbDispositivos = new System.Windows.Forms.GroupBox();
this.lstDisponiveis = new System.Windows.Forms.ListView();
@ -76,6 +78,7 @@ namespace AgroBase
this.gpbControleDirecional = new System.Windows.Forms.GroupBox();
this.gpbAtalhos = new System.Windows.Forms.GroupBox();
this.pnlAtalhos = new System.Windows.Forms.Panel();
this.btnOID = new System.Windows.Forms.Button();
this.btnEthernet = new System.Windows.Forms.Button();
this.btnMKS = new System.Windows.Forms.Button();
this.btnBLD300R = new System.Windows.Forms.Button();
@ -100,8 +103,6 @@ namespace AgroBase
this.btnForcarAtualizacao = new System.Windows.Forms.Button();
this.clbRotinas = new System.Windows.Forms.CheckedListBox();
this.btnAtualizarRotinas = new System.Windows.Forms.Button();
this.txtCodErro = new System.Windows.Forms.TextBox();
this.lblCodErro = new System.Windows.Forms.Label();
this.gpbAcoes.SuspendLayout();
this.erroStrip.SuspendLayout();
this.pnlLateral.SuspendLayout();
@ -178,6 +179,24 @@ namespace AgroBase
this.pnlLateral.Size = new System.Drawing.Size(615, 617);
this.pnlLateral.TabIndex = 0;
//
// lblCodErro
//
this.lblCodErro.AutoSize = true;
this.lblCodErro.Location = new System.Drawing.Point(376, 32);
this.lblCodErro.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblCodErro.Name = "lblCodErro";
this.lblCodErro.Size = new System.Drawing.Size(77, 13);
this.lblCodErro.TabIndex = 23;
this.lblCodErro.Text = "Código de Erro";
//
// txtCodErro
//
this.txtCodErro.Location = new System.Drawing.Point(379, 48);
this.txtCodErro.Name = "txtCodErro";
this.txtCodErro.Size = new System.Drawing.Size(210, 20);
this.txtCodErro.TabIndex = 22;
this.txtCodErro.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtCodErro_KeyDown);
//
// chbConexaoautomatica
//
this.chbConexaoautomatica.AutoSize = true;
@ -625,6 +644,7 @@ namespace AgroBase
// pnlAtalhos
//
this.pnlAtalhos.AutoScroll = true;
this.pnlAtalhos.Controls.Add(this.btnOID);
this.pnlAtalhos.Controls.Add(this.btnEthernet);
this.pnlAtalhos.Controls.Add(this.btnMKS);
this.pnlAtalhos.Controls.Add(this.btnBLD300R);
@ -648,6 +668,17 @@ namespace AgroBase
this.pnlAtalhos.Size = new System.Drawing.Size(112, 286);
this.pnlAtalhos.TabIndex = 0;
//
// btnOID
//
this.btnOID.Location = new System.Drawing.Point(5, 415);
this.btnOID.Margin = new System.Windows.Forms.Padding(2);
this.btnOID.Name = "btnOID";
this.btnOID.Size = new System.Drawing.Size(84, 20);
this.btnOID.TabIndex = 31;
this.btnOID.Text = "OIDelec";
this.btnOID.UseVisualStyleBackColor = true;
this.btnOID.Click += new System.EventHandler(this.btnOID_Click);
//
// btnEthernet
//
this.btnEthernet.Location = new System.Drawing.Point(5, 391);
@ -916,24 +947,6 @@ namespace AgroBase
this.btnAtualizarRotinas.UseVisualStyleBackColor = true;
this.btnAtualizarRotinas.Click += new System.EventHandler(this.btnAtualizarRotinas_Click);
//
// txtCodErro
//
this.txtCodErro.Location = new System.Drawing.Point(379, 48);
this.txtCodErro.Name = "txtCodErro";
this.txtCodErro.Size = new System.Drawing.Size(210, 20);
this.txtCodErro.TabIndex = 22;
this.txtCodErro.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtCodErro_KeyDown);
//
// lblCodErro
//
this.lblCodErro.AutoSize = true;
this.lblCodErro.Location = new System.Drawing.Point(376, 32);
this.lblCodErro.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblCodErro.Name = "lblCodErro";
this.lblCodErro.Size = new System.Drawing.Size(77, 13);
this.lblCodErro.TabIndex = 23;
this.lblCodErro.Text = "Código de Erro";
//
// frmPrincipal
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
@ -1061,6 +1074,7 @@ namespace AgroBase
public System.Windows.Forms.ToolStripStatusLabel lblStripWifi;
private System.Windows.Forms.Label lblCodErro;
private System.Windows.Forms.TextBox txtCodErro;
private System.Windows.Forms.Button btnOID;
}
}

View File

@ -470,17 +470,10 @@ namespace AgroBase
}
private void btnBLD300R_Click(object sender, EventArgs e)
{
if (BLD300RService.Iniciado)
{
frmBLD frm = new frmBLD();
frm.Show();
}
else
{
MessageBox.Show("Driver BLD-300R não está conectado!");
}
}
private void btnMKS_Click(object sender, EventArgs e)
{
@ -494,7 +487,11 @@ namespace AgroBase
frm.Show();
}
private void btnOID_Click(object sender, EventArgs e)
{
frmOID frm = new frmOID();
frm.Show();
}

View File

@ -120,6 +120,9 @@
<metadata name="erroStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>11, 10</value>
</metadata>
<metadata name="erroStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>11, 10</value>
</metadata>
<metadata name="generalStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>133, 16</value>
</metadata>

View File

@ -67,15 +67,15 @@ namespace AgroBase.Models
{
DispositivoConectado = KinectService.Iniciado;
}
else if (Dispositivo == T_Code.Bld)
else if (Dispositivo == T_Code.Mov)
{
var Modulo = Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.FirstOrDefault(x => x.Modulo_ID == Mod_ID);
DispositivoConectado = Modulo?.MovMotor?.BLD_Inicializado ?? false;
DispositivoConectado = Modulo?.MovMotor?.Inicializado ?? false;
}
else if (Dispositivo == T_Code.Mks)
else if (Dispositivo == T_Code.Dir)
{
var Modulo = Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.FirstOrDefault(x => x.Modulo_ID == Mod_ID);
DispositivoConectado = Modulo?.DirMotor?.MKS_Inicializado ?? false;
DispositivoConectado = Modulo?.DirMotor?.Inicializado ?? false;
}
else
{

View File

@ -65,6 +65,7 @@ namespace AgroBase.Models
Knt = 113,
A05 = 114,
Mod = 115,
Oid = 116,
}
public enum F_Code

View File

@ -13,12 +13,14 @@ namespace AgroBase.Models
public DateTime UltimaRequisicao { get; set; } = DateTime.MaxValue;
public string Descricao { get; set; }
public string Chave { get; set; }
public byte Registro { get; set; }
public byte N_Registros { get; set; }
public ushort Registro { get; set; } // Alterado para ushort (correto para Modbus)
public ushort N_Registros { get; set; } // Alterado para ushort
public bool LeituraLoop { get; set; }
public bool LeituraGeral { get; set; }
public double Escala { get; set; }
public byte[] Valor { get; set; }
public bool LeituraEntrada { get; set; }
public bool EscritaMultipla { get; set; }
}
public class ModbusComandoModel

View File

@ -31,26 +31,26 @@ namespace AgroBase.Models.Modules
public double ReducaoMotorBLDC { get; set; } = 5;
public double RPM_Max_MotorBLDC { get; set; } = 500;
public string IP_Bld { get; set; } = Variaveis.FaixaIPethernet + ".10";
public string IP_Mks { get; set; } = Variaveis.FaixaIPethernet + ".11";
public string IP_Mov { get; set; } = Variaveis.FaixaIPethernet + ".10";
public string IP_Dir { get; set; } = Variaveis.FaixaIPethernet + ".11";
public static int LogsManter { get; set; } = 60;
public AsyncTaskTimerModel tmrRegistrador;
public AsyncTaskTimerModel tmrRegistradorBLD;
public AsyncTaskTimerModel tmrRegistradorMKS;
public AsyncTaskTimerModel tmrRegistradorMOV;
public AsyncTaskTimerModel tmrRegistradorDIR;
public List<ModuloMvdModel> Modulos { get; set; } = new List<ModuloMvdModel>();
public static Direcao UltimaDirecao { get; set; } = Direcao.Parado;
public (bool, List<string>) StatusModulosBLD(Direcao Lado)
public (bool, List<string>) StatusModulosMOV(Direcao Lado)
{
string Prefixo = Lado == Direcao.Esquerda ? "E" : Lado == Direcao.Direita ? "D" : "";
var Mods = Modulos.Where(Mod => Mod.Modulo_ID.Contains(Prefixo) && Mod.MovMotor.Comandar).ToList();
var ModsComFalha = Mods
.Where(Mod =>
!Mod.MovMotor.BLD_Inicializado ||
!Mod.MovMotor.Inicializado ||
Mod.MovMotor.CodigoAlarme != 0 ||
Mod.MovMotor.AlarmeSensores
)
@ -62,12 +62,12 @@ namespace AgroBase.Models.Modules
return (_operante, ModsInoperantes);
}
public (bool, List<string>) StatusModulosMKS(TipoMovimentoDirecional TipoMovimento)
public (bool, List<string>) StatusModulosDIR(TipoMovimentoDirecional TipoMovimento)
{
var Mods = Modulos.Where(Mod => Mod.DirMotor.Comandar).ToList();
var ModsComFalha = Mods
.Where(Mod =>
!Mod.DirMotor.MKS_Inicializado && (
!Mod.DirMotor.Inicializado && (
Mod.DirMotor.ConfigSentidos[TipoMovimento].Esquerda != Sentido.Parado &&
Mod.DirMotor.ConfigSentidos[TipoMovimento].Direita != Sentido.Parado
)
@ -140,7 +140,6 @@ namespace AgroBase.Models.Modules
x.MovMotor.Temperatura = 0;
x.MovMotor.RPM_SP = 0;
x.MovMotor.RPM_SP_Controle = 0;
x.MovMotor.Corrente = 0;
x.DirMotor.Angulo_SP = 0;
x.DirMotor.Sentido_SP = Sentido.Parado;
@ -172,12 +171,14 @@ namespace AgroBase.Models.Modules
RPM_SP = Modulo.MovMotor.RPM_SP_Leitura,
RPM_Motor = Modulo.MovMotor.RPM_Motor,
RPM_Roda = Modulo.MovMotor.RPM_Roda,
Corrente = Modulo.MovMotor.Corrente,
Corrente = Modulo.MovMotor.Corrente_Motor,
Sentido = Modulo.MovMotor.Sentido,
Temperatura = Modulo.MovMotor.Temperatura,
TemperaturaDriver = Modulo.MovMotor.TemperaturaDriver,
Tensao = Modulo.MovMotor.Tensao,
Velocidade = Modulo.MovMotor.VelocidadeInstantanea
Velocidade = Modulo.MovMotor.VelocidadeInstantanea,
Potencia = Modulo.MovMotor.Potencia,
CicloTrabalho = Modulo.MovMotor.CicloTrabalho
});
if (Modulo.MovMotor.LogGrafico.Count > 60)
@ -212,7 +213,7 @@ namespace AgroBase.Models.Modules
public string GetIP()
{
return IP_Bld;
return IP_Mov;
}
public void IniciarRegistrador()
@ -226,19 +227,19 @@ namespace AgroBase.Models.Modules
tmrRegistrador = new AsyncTaskTimerModel("tmrRegistrador_" + T_Code.Mvd.ToString(), tmrRegistrador_Tick, _TaxaAmostragem);
tmrRegistrador.Start();
tmrRegistradorBLD = new AsyncTaskTimerModel("tmrRegistrador_" + T_Code.Bld.ToString(), tmrRegistradorBLD_Tick, BLD300RService.TaxaAmostragem);
tmrRegistradorBLD.Start();
tmrRegistradorMOV = new AsyncTaskTimerModel("tmrRegistrador_" + T_Code.Mov.ToString(), tmrRegistradorMOV_Tick, OIDService.TaxaAmostragem);
tmrRegistradorMOV.Start();
tmrRegistradorMKS = new AsyncTaskTimerModel("tmrRegistrador_" + T_Code.Mks.ToString(), tmrRegistradorMKS_Tick, MKS057DService.TaxaAmostragem);
tmrRegistradorMKS.Start();
tmrRegistradorDIR = new AsyncTaskTimerModel("tmrRegistrador_" + T_Code.Dir.ToString(), tmrRegistradorDIR_Tick, MKS057DService.TaxaAmostragem);
tmrRegistradorDIR.Start();
}
}
public void PararRegistrador()
{
tmrRegistrador?.Dispose();
tmrRegistradorBLD?.Dispose();
tmrRegistradorMKS?.Dispose();
tmrRegistradorMOV?.Dispose();
tmrRegistradorDIR?.Dispose();
}
public async Task tmrRegistrador_Tick()
@ -258,42 +259,42 @@ namespace AgroBase.Models.Modules
}
}
private async Task tmrRegistradorBLD_Tick()
private async Task tmrRegistradorMOV_Tick()
{
if (!BLD300RService.Iniciado && SerialService.DispositivosMapeados.Any(x => x.Dispositivo == T_Code.Bld))
if (!OIDService.Iniciado && SerialService.DispositivosMapeados.Any(x => x.Dispositivo == T_Code.Mov))
{
await BLD300RService.InicializarEthernetService();
await OIDService.InicializarEthernetService();
foreach (var Leitura in BLD300RService.DadosLeitura.Where(x => x.UltimoComandoRecebido.AddSeconds(10) < DateTime.Now))
foreach (var Leitura in OIDService.DadosLeitura.Where(x => x.UltimoComandoRecebido.AddSeconds(10) < DateTime.Now))
{
BLD300RService.AdicionarComandoNaFila(new BLD300RService.BLDComandoModel()
OIDService.AdicionarComandoNaFila(new OIDComandoModel()
{
Endereco = Leitura.Endereco,
Parametro = BLD300RService.Parametros.First(x => x.Chave == "Versao"),
Parametro = OIDService.Parametros.First(x => x.Chave == "CodErro"),
Get = true,
AguardaResposta = true
});
}
tmrRegistradorBLD.SetInterval(3000);
tmrRegistradorMOV.SetInterval(3000);
return;
}
var Controle = Variaveis.OperacaoEmAndamento.Controle.TiposControle.FirstOrDefault(x => x.Tipo == T_Code.Mov);
foreach (var Modulo in Modulos.Where(x => x.MovMotor.BLD_Inicializado).OrderBy(x => x.MovMotor.EnderecoByte))
foreach (var Modulo in Modulos.Where(x => x.MovMotor.Inicializado).OrderBy(x => x.MovMotor.EnderecoByte))
{
foreach (var Parametro in BLD300RService.Parametros.Where(x => x.LeituraLoop))
foreach (var Parametro in OIDService.Parametros.Where(x => x.LeituraLoop))
{
var Comando = new BLD300RService.BLDComandoModel()
var Comando = new OIDComandoModel()
{
Endereco = Modulo.MovMotor.EnderecoByte,
AguardaResposta = true,
Parametro = Parametro,
Get = true,
TimeoutResposta = 500
TimeoutResposta = 200
};
BLD300RService.AdicionarComandoNaFila(Comando);
OIDService.AdicionarComandoNaFila(Comando);
}
Modulo.MovMotor.EnviarComandoControle(Controle.UltimaDirecao);
@ -303,10 +304,10 @@ namespace AgroBase.Models.Modules
Variaveis.OperacaoEmAndamento.DispMvd.Dados.RegistrarLogMov(Modulo);
}
tmrRegistradorBLD.SetInterval(BLD300RService.TaxaAmostragem);
tmrRegistradorMOV.SetInterval(OIDService.TaxaAmostragem);
}
private async Task tmrRegistradorMKS_Tick()
private async Task tmrRegistradorDIR_Tick()
{
if (!MKS057DService.Iniciado && SerialService.DispositivosMapeados.Any(x => x.Dispositivo == T_Code.Mks))
{
@ -317,12 +318,12 @@ namespace AgroBase.Models.Modules
MKS057DService.AdicionarComandoNaFila(MKS057DService.MontarComandoRequisicaoPulsos(Leitura.Endereco));
}
tmrRegistradorMKS.SetInterval(3000);
tmrRegistradorDIR.SetInterval(3000);
return;
}
var Controle = Variaveis.OperacaoEmAndamento.Controle.TiposControle.FirstOrDefault(x => x.Tipo == T_Code.Dir);
foreach (var Modulo in Modulos.Where(x => x.DirMotor.MKS_Inicializado))
foreach (var Modulo in Modulos.Where(x => x.DirMotor.Inicializado))
{
byte modAddr = Modulo.DirMotor.EnderecoByte;
if (!MKS057DService.Referenciando || (MKS057DService.Referenciando && MKS057DService.AddrRef == modAddr))
@ -343,7 +344,7 @@ namespace AgroBase.Models.Modules
}
MKS057DService.TaxaAmostragem = MKS057DService.Referenciando ? 200 : 1000;
tmrRegistradorMKS.SetInterval(MKS057DService.TaxaAmostragem);
tmrRegistradorDIR.SetInterval(MKS057DService.TaxaAmostragem);
}
@ -365,7 +366,7 @@ namespace AgroBase.Models.Modules
case TipoMovimentoDirecional.RotacionarNoEixo:
case TipoMovimentoDirecional.MovimentoLateral:
foreach (var Modulo in Modulos.Where(x => x.DirMotor.MKS_Inicializado && !x.DirMotor.PosicaoTipoMovimentoConcluido(DirecaoAtual)))
foreach (var Modulo in Modulos.Where(x => x.DirMotor.Inicializado && !x.DirMotor.PosicaoTipoMovimentoConcluido(DirecaoAtual)))
{
Modulo.DirMotor.EnviarComandoControle(DirecaoAtual);
}
@ -403,7 +404,7 @@ namespace AgroBase.Models.Modules
TipoMovimentoDirecional tipoControle = Variaveis.OperacaoEmAndamento.Controle.TipoMovimento;
Variaveis.OperacaoEmAndamento.Controle.TipoMovimento = TipoMovimentoDirecional.Diagnostico;
foreach (var Modulo in Modulos.Where(x => x.DirMotor.Comandar && x.DirMotor.MKS_Inicializado && !x.DirMotor.IN1_Atuado))
foreach (var Modulo in Modulos.Where(x => x.DirMotor.Comandar && x.DirMotor.Inicializado && !x.DirMotor.IN1_Atuado))
{
await Modulo.DirMotor.ReferenciaMotor();
}
@ -425,7 +426,7 @@ namespace AgroBase.Models.Modules
{
get
{
return MovMotor.BLD_Inicializado || DirMotor.MKS_Inicializado;
return MovMotor.Inicializado || DirMotor.Inicializado;
}
}
@ -531,8 +532,6 @@ namespace AgroBase.Models.Modules
var sensorCor = Variaveis.OperacaoEmAndamento.DispSen.Dados.DadosLeitura.SensoresCorrente.FirstOrDefault(x => x.ID.Contains(Modulo_ID));
if (sensorCor != null)
{
MovMotor.Corrente = (double)sensorCor.Current;
AlarmeModel _Alarme = new AlarmeModel()
{
Tipo = S_Code.sCOR,
@ -560,7 +559,7 @@ namespace AgroBase.Models.Modules
bool AlarmeAnterior = (Alm.Maximo && Alm.ParaMaximo) || (Alm.Minimo && Alm.ParaMinimo);
bool AlarmeAtual = (_Alarme.Maximo && _Alarme.ParaMaximo) || (_Alarme.Minimo && _Alarme.ParaMinimo);
if (MovMotor.BLD_Inicializado && (!AlarmeAnterior || Adicionado) && AlarmeAtual) // Motor iniciado, Não estava em alarme anteriormente ou foi adicionado agora, alarme atual
if (MovMotor.Inicializado && (!AlarmeAnterior || Adicionado) && AlarmeAtual) // Motor iniciado, Não estava em alarme anteriormente ou foi adicionado agora, alarme atual
{
MovMotor.EnviarComandoControle(Direcao.Parado);
}
@ -591,7 +590,7 @@ namespace AgroBase.Models.Modules
{
get
{
return Leitura?.Ativado ?? false;
return Leitura?.CorrenteMotor != 0;
}
}
public bool ComandoLigado { get; set; } = false;
@ -630,7 +629,8 @@ namespace AgroBase.Models.Modules
{
get
{
return (Leitura?.RPM ?? 0) * OffsetLeitura;
//return (Leitura?.RPM ?? 0) * OffsetLeitura;
return RPM_Motor / VariaveisEquipamento.RelacaoRPM;
}
}
public Sentido Sentido
@ -655,47 +655,69 @@ namespace AgroBase.Models.Modules
return Math.Round(Leitura?.Tensao ?? 0, 2);
}
}
public double Corrente_Max
public double Corrente_Barramento
{
get
{
return Math.Round(Leitura?.CorrenteMax ?? 0, 2);
return Math.Round(Leitura?.CorrenteBarramento ?? 0, 2);
}
}
public double Corrente_Motor
{
get
{
return Math.Round(Leitura?.CorrenteMotor ?? 0, 2);
}
}
public double Potencia
{
get
{
return Math.Round(Leitura?.Potencia ?? 0, 2);
}
}
public double CicloTrabalho
{
get
{
return Math.Round(Leitura?.CicloTrabalho ?? 0, 2);
}
}
public double Corrente { get; set; } = 0;
public double RPM_Motor
{
get
{
//return Convert.ToInt32(RPM_Motor / VariaveisEquipamento.RelacaoRPM);
return RPM_Roda * VariaveisEquipamento.RelacaoRPM;
//return RPM_Roda * VariaveisEquipamento.RelacaoRPM;
//return RPM_Roda * 0.74;
return (Leitura?.RPM ?? 0);
}
}
public double VelocidadeInstantanea
{
get
{
return FuncoesMatematicas.CalculaVelocidadeRPM(RPM_Motor);
return FuncoesMatematicas.CalculaVelocidadeRPM(RPM_Roda);
}
}
public bool Comandar { get; set; } = false;
public bool AlarmeSensores { get; set; } = false;
public bool BLD_Inicializado
public bool Inicializado
{
get
{
return Leitura?.Iniciado ?? false;
}
}
private BLD300RModel _leitura = null;
public BLD300RModel Leitura
private OIDModel _leitura = null;
public OIDModel Leitura
{
get
{
_leitura = BLD300RService.DadosLeitura?.FirstOrDefault(x => x.Endereco == EnderecoByte);
_leitura = OIDService.DadosLeitura?.FirstOrDefault(x => x.Endereco == EnderecoByte);
return _leitura;
}
set
@ -841,7 +863,7 @@ namespace AgroBase.Models.Modules
bool Freado = DirecaoAtual == Direcao.EmFreio;
(bool AtuarServo, int AnguloFreio) = ConfigFreio.AtualizarDadosFreio(Freado, 0, -1, 5);
if ((Comandar && BLD_Inicializado) || simulando)
if ((Comandar && Inicializado) || simulando)
{
if (AlarmeSensores || AlarmeMotor)
{
@ -851,14 +873,14 @@ namespace AgroBase.Models.Modules
if (AlarmeMotor)
{
BLD300RService.RegisrarErrosComunicacao(EnderecoByte, $"Módulo com código de alarme {CodigoAlarme}, reiniciando o módulo...");
BLD300RService.AdicionarComandoNaFila(new BLD300RService.BLDComandoModel()
OIDService.RegisrarErrosComunicacao(EnderecoByte, $"Módulo com código de alarme {CodigoAlarme}, reiniciando o módulo...");
OIDService.AdicionarComandoNaFila(new OIDComandoModel()
{
Endereco = EnderecoByte,
AguardaResposta = true,
TimeoutResposta = 500,
Get = false,
Parametro = BLD300RService.Parametros.First(x => x.Chave == "AlarmeCode"),
Parametro = OIDService.Parametros.First(x => x.Chave == "CodErro"),
Valor = 0
});
}
@ -898,52 +920,48 @@ namespace AgroBase.Models.Modules
byte Addr = EnderecoByte;
DateTime Agora = DateTime.Now;
if (Sentido_SP != Sentido.Parado && (Leitura == null || Leitura.Direcao != Sentido_SP))
bool SentidoAlterado = Sentido_SP != Sentido.Parado && (Leitura == null || Leitura.Direcao != Sentido_SP);
bool RPMAlterado = ComandoLigado && (Leitura == null || Leitura.ControleVelocidade != RPM_SP_Controle);
bool LigadoAlterado = Leitura == null || ComandoLigado != LeituraLigado;
bool FreioAlterado = Leitura == null || Leitura.Freado != Freado;
bool EnviaComando = SentidoAlterado || RPMAlterado || LigadoAlterado;
OIDModoControle modoControle =
Freado ? OIDModoControle.Freio :
ComandoLigado ? OIDModoControle.Velocidade :
OIDModoControle.Corrente;
if (Leitura.ModoControle != modoControle)
{
BLD300RService.AdicionarComandoNaFila(new BLD300RService.BLDComandoModel()
OIDService.AdicionarComandoNaFila(new OIDComandoModel()
{
Endereco = Addr,
Parametro = BLD300RService.Parametros.First(x => x.Chave == "Direction"),
Valor = Sentido_SP == Sentido.Horario ? 1 : 0,
Parametro = OIDService.Parametros.First(x => x.Chave == "ModoControle"),
Valor = (int)modoControle,
Get = false,
AguardaResposta = true,
TimeoutResposta = 500,
AguardaResposta = false,
TimeoutResposta = 50,
});
}
if (ComandoLigado && (Leitura == null || Leitura.RPM_SP != RPM_SP_Controle))
if (EnviaComando && !Freado)
{
BLD300RService.AdicionarComandoNaFila(new BLD300RService.BLDComandoModel()
int mx =
Sentido_SP == Sentido.Horario ? 1 :
Sentido_SP == Sentido.Antihorario ? -1 :
0;
float velocidade = RPM_SP * mx;
string regisro = modoControle == OIDModoControle.Velocidade ? "ControleVelocidade" : "ControleCorrente";
OIDService.AdicionarComandoNaFila(new OIDComandoModel()
{
Endereco = Addr,
Parametro = BLD300RService.Parametros.First(x => x.Chave == "RPM_SP"),
Valor = RPM_SP,
Parametro = OIDService.Parametros.First(x => x.Chave == regisro),
Valor = velocidade,
Get = false,
AguardaResposta = true,
TimeoutResposta = 500,
});
}
if (Leitura == null || Leitura.Freado != Freado)
{
BLD300RService.AdicionarComandoNaFila(new BLD300RService.BLDComandoModel()
{
Endereco = Addr,
Parametro = BLD300RService.Parametros.First(x => x.Chave == "Breaked"),
Valor = Freado ? 1 : 0,
Get = false,
AguardaResposta = true,
TimeoutResposta = 500,
});
}
if (Leitura == null || ComandoLigado != LeituraLigado)
{
BLD300RService.AdicionarComandoNaFila(new BLD300RService.BLDComandoModel()
{
Endereco = Addr,
Parametro = BLD300RService.Parametros.First(x => x.Chave == "Enabled"),
Valor = ComandoLigado ? 1 : 0,
Get = false,
AguardaResposta = true,
TimeoutResposta = 500,
AguardaResposta = false,
TimeoutResposta = 50,
});
}
}
@ -1027,7 +1045,7 @@ namespace AgroBase.Models.Modules
public bool Comandar { get; set; } = false;
public bool MKS_Inicializado
public bool Inicializado
{
get
{
@ -1197,7 +1215,7 @@ namespace AgroBase.Models.Modules
{
var simulando = Variaveis.OperacaoEmAndamento.Simulando;
if ((MKS_Inicializado && (Comandar || !AtingiuAnguloSP)) || simulando)
if ((Inicializado && (Comandar || !AtingiuAnguloSP)) || simulando)
{
int AnguloTipoMovimento = VariaveisEquipamento.AnguloMovimento[Variaveis.OperacaoEmAndamento.Controle.TipoMovimento];
@ -1465,6 +1483,8 @@ namespace AgroBase.Models.Modules
public double Velocidade { get; set; }
public double Tensao { get; set; }
public double Corrente { get; set; }
public double Potencia { get; set; }
public double CicloTrabalho { get; set; }
}
public class MvdServoFreioModel

View File

@ -0,0 +1,293 @@
using AgroBase.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using static AgroBase.Models.Enums;
namespace AgroBase.Models
{
public class OIDModel
{
public byte Endereco { get; set; }
public bool Iniciado
{
get
{
// Houve comandos recebidos do driver dentro dos ultimos 10 segundos
bool iniciado = UltimoComandoRecebido.AddSeconds(10) > DateTime.Now;
if (!iniciado && Configurado)
{
Configurado = false;
}
return iniciado;
}
}
public bool Configurado { get; set; }
public DateTime UltimoComandoRecebido { get; set; }
public OIDModoControle ModoControle
{
get
{
return (OIDModoControle)ConvertByteArrayToInt(GetParametroValue(OIDService.Parametros.First(x => x.Chave == "ModoControle").Registro));
}
}
public int ControleCorrente
{
get
{
return ConvertByteArrayToInt(GetParametroValue(OIDService.Parametros.First(x => x.Chave == "ControleCorrente").Registro));
}
}
public int ControleVelocidade
{
get
{
return ConvertByteArrayToInt(GetParametroValue(OIDService.Parametros.First(x => x.Chave == "ControleVelocidade").Registro));
}
}
public int ControleCicloTrabalho
{
get
{
return ConvertByteArrayToInt(GetParametroValue(OIDService.Parametros.First(x => x.Chave == "ControleCicloTrabalho").Registro));
}
}
public int ControleCorrenteFreio
{
get
{
return ConvertByteArrayToInt(GetParametroValue(OIDService.Parametros.First(x => x.Chave == "ControleCorrenteFreio").Registro));
}
}
public int RampaSubidaVelocidade
{
get
{
return ConvertByteArrayToInt(GetParametroValue(OIDService.Parametros.First(x => x.Chave == "RampaSubidaVelocidade").Registro));
}
}
public int RampaDescidaVelocidade
{
get
{
return ConvertByteArrayToInt(GetParametroValue(OIDService.Parametros.First(x => x.Chave == "RampaDescidaVelocidade").Registro));
}
}
public int CodigoAlarme
{
get
{
return ConvertByteArrayToInt(GetParametroValue(OIDService.Parametros.First(x => x.Chave == "CodErro").Registro));
}
}
public int Heartbeat
{
get
{
return ConvertByteArrayToInt(GetParametroValue(OIDService.Parametros.First(x => x.Chave == "Heartbeat").Registro));
}
}
public double Torque_Max
{
get
{
return ConvertByteArrayToFloat(GetParametroValue(OIDService.Parametros.First(x => x.Chave == "CorrenteTorqueMaximo").Registro));
}
}
public int ERPM
{
get
{
return ConvertByteArrayToInt(GetParametroValue(OIDService.Parametros.First(x => x.Chave == "VelocidadeAngular").Registro));
}
}
public double CorrenteMotor
{
get
{
var P_A = parametros.FirstOrDefault(x => x.Registro == OIDService.Parametros.First(y => y.Chave == "CorrenteMotor").Registro);
if (P_A == null)
{
return -1;
}
double corrente = ConvertByteArrayToFloat(P_A.Valor) / P_A.Escala;
return Math.Abs(corrente);
}
}
public double CorrenteBarramento
{
get
{
var P_A = parametros.FirstOrDefault(x => x.Registro == OIDService.Parametros.First(y => y.Chave == "CorrenteBarramento").Registro);
if (P_A == null)
{
return -1;
}
double corrente = ConvertByteArrayToFloat(P_A.Valor) / P_A.Escala;
return Math.Abs(corrente);
}
}
public Sentido Direcao
{
get
{
return
ERPM > 0 ? Sentido.Horario :
ERPM < 0 ? Sentido.Antihorario :
Sentido.Parado;
}
}
public double RPM
{
get
{
var P_V = parametros.FirstOrDefault(x => x.Registro == OIDService.Parametros.First(y => y.Chave == "VelocidadeAngular").Registro);
if (P_V == null)
{
return 0;
}
double rpm = Math.Abs((double)ERPM / (double)VariaveisEquipamento.NumeroPolosMotor);
return rpm;
}
}
public double Tensao
{
get
{
var P_V = parametros.FirstOrDefault(x => x.Registro == OIDService.Parametros.First(y => y.Chave == "Tensao").Registro);
if (P_V == null)
{
return -1;
}
double tensao = ConvertByteArrayToFloat(P_V.Valor) / P_V.Escala;
return tensao;
}
}
public double Temperatura
{
get
{
var P_T = parametros.FirstOrDefault(x => x.Registro == OIDService.Parametros.First(y => y.Chave == "Temperatura").Registro);
if (P_T == null)
{
return -1;
}
double temperatura = ConvertByteArrayToFloat(P_T.Valor) / P_T.Escala;
return temperatura;
}
}
public double Potencia
{
get
{
var P_W = parametros.FirstOrDefault(x => x.Registro == OIDService.Parametros.First(y => y.Chave == "Potencia").Registro);
if (P_W == null)
{
return -1;
}
double potencia = ConvertByteArrayToFloat(P_W.Valor) / P_W.Escala;
return Math.Abs(potencia);
}
}
public double CicloTrabalho
{
get
{
var P_C = parametros.FirstOrDefault(x => x.Registro == OIDService.Parametros.First(y => y.Chave == "CicloTrabalho").Registro);
if (P_C == null)
{
return -1;
}
double cicloTrabalho = ConvertByteArrayToFloat(P_C.Valor) / P_C.Escala;
return Math.Abs(cicloTrabalho);
}
}
public bool Freado
{
get
{
return ModoControle == OIDModoControle.Freio || ModoControle == OIDModoControle.FreioDeMao;
}
}
public List<OIDParametrosRequisitar> parametros { get; set; }
int ConvertByteArrayToInt(byte[] bytes)
{
if (bytes == null) return 0;
if (bytes.Length == 2)
{
return BitConverter.ToInt16(bytes.Reverse().ToArray(), 0);
}
else if (bytes.Length == 4)
{
return BitConverter.ToInt32(bytes.Reverse().ToArray(), 0);
}
return 0;
}
private static float ConvertByteArrayToFloat(byte[] bytes)
{
if (bytes == null || bytes.Length != 4) return 0;
// Separar os dois registradores (parte inteira e decimal)
short parteInteira = BitConverter.ToInt16(bytes.Take(2).Reverse().ToArray(), 0);
short parteDecimal = BitConverter.ToInt16(bytes.Skip(2).Reverse().ToArray(), 0);
// Construir o valor real com precisão de 4 casas decimais (igual ao Python)
float valor = parteInteira + (parteDecimal / 10000.0f);
return valor;
}
byte[] GetParametroValue(ushort registro)
{
var p = parametros.FirstOrDefault(x => x.Registro == registro);
return p != null ? p.Valor : null;
}
}
public class OIDParametrosRequisitar
{
public ushort Registro { get; set; }
public byte[] Valor { get; set; }
public double Escala { get; set; }
}
public class OIDComandoModel
{
public DateTime Momento { get; set; } = DateTime.Now;
public bool Enviado { get; set; } = false;
public bool ErroEnvio { get; set; } = false;
public bool Respondido { get; set; } = false;
public byte Endereco { get; set; }
public byte[] Comando { get; set; }
public byte[] Resposta { get; set; }
public ModbusParametrosModel Parametro { get; set; }
public float Valor { get; set; }
public bool Get { get; set; }
public bool AguardaResposta { get; set; } = false;
public int TimeoutResposta { get; set; } = 1000;
public int TamanhoEsperado { get; set; } = 8;
}
public enum OIDModoControle
{
Corrente = 0,
Velocidade = 1,
CicloTrabalho = 2,
PosicaoAbsoluta = 3,
PosicaoRelativa = 4,
PosicaoCorrente = 5,
Freio = 6,
FreioDeMao = 7,
RetornoZero = 8,
RetornoZeroParada = 9,
Rampa = 10
}
}

View File

@ -184,10 +184,10 @@ namespace AgroBase.Models
bool _dispositivosConectados = true;
// Verificação dos motores BLDC
if (Variaveis.OperacaoEmAndamento.ModulosMandatorios.Any(x => x.Dispositivo == T_Code.Bld && x.Conectado))
if (Variaveis.OperacaoEmAndamento.ModulosMandatorios.Any(x => x.Dispositivo == T_Code.Mov && x.Conectado))
{
(bool _EsqOperante, List<string> _EsqModsInoperantes) = Variaveis.OperacaoEmAndamento.DispMvd.Dados.StatusModulosBLD(Direcao.Esquerda);
(bool _DirOperante, List<string> _DirModsInoperantes) = Variaveis.OperacaoEmAndamento.DispMvd.Dados.StatusModulosBLD(Direcao.Direita);
(bool _EsqOperante, List<string> _EsqModsInoperantes) = Variaveis.OperacaoEmAndamento.DispMvd.Dados.StatusModulosMOV(Direcao.Esquerda);
(bool _DirOperante, List<string> _DirModsInoperantes) = Variaveis.OperacaoEmAndamento.DispMvd.Dados.StatusModulosMOV(Direcao.Direita);
// Se qualquer lado estiver completamente inoperante, o robô não pode operar corretamente
if (!_EsqOperante || !_DirOperante)
@ -197,9 +197,9 @@ namespace AgroBase.Models
}
// Verificação dos motores MKS
if (Variaveis.OperacaoEmAndamento.ModulosMandatorios.Any(x => x.Dispositivo == T_Code.Mks && x.Conectado))
if (Variaveis.OperacaoEmAndamento.ModulosMandatorios.Any(x => x.Dispositivo == T_Code.Dir && x.Conectado))
{
(bool _MksOperante, List<string> _MksModsInoperantes) = Variaveis.OperacaoEmAndamento.DispMvd.Dados.StatusModulosMKS(Variaveis.OperacaoEmAndamento.Controle.TipoMovimento);
(bool _MksOperante, List<string> _MksModsInoperantes) = Variaveis.OperacaoEmAndamento.DispMvd.Dados.StatusModulosDIR(Variaveis.OperacaoEmAndamento.Controle.TipoMovimento);
if (!_MksOperante)
{
@ -601,12 +601,12 @@ namespace AgroBase.Models
{
new OperacaoModulosMandatoriosModel()
{
Dispositivo = T_Code.Bld,
Dispositivo = T_Code.Mov,
Mandatorio = false
},
new OperacaoModulosMandatoriosModel()
{
Dispositivo = T_Code.Mks,
Dispositivo = T_Code.Dir,
Mandatorio = false
},
new OperacaoModulosMandatoriosModel()
@ -680,12 +680,12 @@ namespace AgroBase.Models
{
new OperacaoModulosMandatoriosModel()
{
Dispositivo = T_Code.Bld,
Dispositivo = T_Code.Mov,
Mandatorio = true,
},
new OperacaoModulosMandatoriosModel()
{
Dispositivo = T_Code.Mks,
Dispositivo = T_Code.Dir,
Mandatorio = true,
},
new OperacaoModulosMandatoriosModel()
@ -935,7 +935,7 @@ namespace AgroBase.Models
if (DispMvd != null)
{
// Referenciar motores de passo
if (DispMvd.Dados.Modulos.Any(x => x.DirMotor.MKS_Inicializado))
if (DispMvd.Dados.Modulos.Any(x => x.DirMotor.Inicializado))
{
GeneralJoystick.EnviaComandoMotor(Keys.R);
}
@ -1647,7 +1647,7 @@ namespace AgroBase.Models
// Primeiro, coletar todos os logs alinhados por índice em uma lista de tuplas (index, moduloLog)
var Logs = Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos
.Where(x => x.MovMotor.BLD_Inicializado)
.Where(x => x.MovMotor.Inicializado)
.SelectMany(m => m.MovMotor.LogGrafico.Select((log, index) => new { Index = index, Log = log }))
.GroupBy(x => x.Index) // Agrupa por índice
.OrderBy(g => g.Key) // Ordena pelos índices (opcional, mas ajuda na leitura)
@ -2010,9 +2010,9 @@ namespace AgroBase.Models
CompletionPortThreads = Variaveis.OperacaoEmAndamento.Sensoriamento.CompletionPortThreads,
MaxCompletionPortThreads = Variaveis.OperacaoEmAndamento.Sensoriamento.MaxCompletionPortThreads,
OperacaoLiberada = Variaveis.OperacaoEmAndamento.OperacaoLiberada,
Dir_Status = Variaveis.OperacaoEmAndamento.DispMvd.Dados.StatusModulosMKS(Variaveis.OperacaoEmAndamento.Controle.TipoMovimento),
MovEsq_Status = Variaveis.OperacaoEmAndamento.DispMvd.Dados.StatusModulosBLD(Direcao.Esquerda),
MovDir_Status = Variaveis.OperacaoEmAndamento.DispMvd.Dados.StatusModulosBLD(Direcao.Direita),
Dir_Status = Variaveis.OperacaoEmAndamento.DispMvd.Dados.StatusModulosDIR(Variaveis.OperacaoEmAndamento.Controle.TipoMovimento),
MovEsq_Status = Variaveis.OperacaoEmAndamento.DispMvd.Dados.StatusModulosMOV(Direcao.Esquerda),
MovDir_Status = Variaveis.OperacaoEmAndamento.DispMvd.Dados.StatusModulosMOV(Direcao.Direita),
PercentualErvasTerreno = Variaveis.OperacaoEmAndamento.Sensoriamento.PercentualErvasTerreno,
SonarFrontal_old = null,
Controle = Variaveis.OperacaoEmAndamento.Controle,
@ -2043,11 +2043,11 @@ namespace AgroBase.Models
{
Momento = Agora,
Modulo_ID = Modulo.Modulo_ID,
Inicializado = Modulo.MovMotor.BLD_Inicializado,
Inicializado = Modulo.MovMotor.Inicializado,
RPM_SP = Modulo.MovMotor.RPM_SP,
RPM_Motor = Modulo.MovMotor.RPM_Motor,
RPM_Roda = Modulo.MovMotor.RPM_Roda,
Corrente = Modulo.MovMotor.Corrente,
Corrente_Motor = Modulo.MovMotor.Corrente_Motor,
Temperatura = Modulo.MovMotor.Temperatura,
TemperaturaDriver = Modulo.MovMotor.TemperaturaDriver,
Tensao = Modulo.MovMotor.Tensao,
@ -2058,6 +2058,9 @@ namespace AgroBase.Models
EmFreio = Modulo.MovMotor.ConfigFreio.Leitura,
Ativado = Modulo.MovMotor.LeituraLigado,
UltimoComandoRespondido = Modulo.MovMotor.Leitura?.UltimoComandoRecebido ?? DateTime.MinValue,
Corrente_Barramento = Modulo.MovMotor.Corrente_Barramento,
Potencia = Modulo.MovMotor.Potencia,
CicloTrabalho = Modulo.MovMotor.CicloTrabalho
};
SalvarLog(T_Code.Mov.ToString(), logMov, false);
@ -2065,7 +2068,7 @@ namespace AgroBase.Models
{
Momento = Agora,
Modulo_ID = Modulo.Modulo_ID,
Inicializado = Modulo.DirMotor.MKS_Inicializado,
Inicializado = Modulo.DirMotor.Inicializado,
Angulo = Modulo.DirMotor.Angulo,
Angulo_SP = Modulo.DirMotor.Angulo_SP,
Controlar = Modulo.DirMotor.Comandar,
@ -2459,9 +2462,9 @@ namespace AgroBase.Models
(bool _atuOperante, List<string> atuModsFalha) = _dispATU == null ? (false, new List<string>()) : _dispATU.Dados.StatusModulosATU();
(bool _senOperante, List<string> senModsFalha) = _dispSEN == null ? (false, new List<string>()) : _dispSEN.Dados.StatusModulosSEN();
(bool _dirOperante, List<string> dirModsFalha) = _dispMVD == null ? (false, new List<string>()) : _dispMVD.Dados.StatusModulosMKS(Variaveis.OperacaoEmAndamento.Controle.TipoMovimento);
(bool _movEsqOperante, List<string> movEsqModsFalha) = _dispMVD == null ? (false, new List<string>()) : _dispMVD.Dados.StatusModulosBLD(Direcao.Esquerda);
(bool _movDirOperante, List<string> movDirModsFalha) = _dispMVD == null ? (false, new List<string>()) : _dispMVD.Dados.StatusModulosBLD(Direcao.Direita);
(bool _dirOperante, List<string> dirModsFalha) = _dispMVD == null ? (false, new List<string>()) : _dispMVD.Dados.StatusModulosDIR(Variaveis.OperacaoEmAndamento.Controle.TipoMovimento);
(bool _movEsqOperante, List<string> movEsqModsFalha) = _dispMVD == null ? (false, new List<string>()) : _dispMVD.Dados.StatusModulosMOV(Direcao.Esquerda);
(bool _movDirOperante, List<string> movDirModsFalha) = _dispMVD == null ? (false, new List<string>()) : _dispMVD.Dados.StatusModulosMOV(Direcao.Direita);
bool _nivelBateriaEstavel =
!_modsMandatorios.Any(x => x.Dispositivo == T_Code.Pzm) ||
@ -3249,8 +3252,11 @@ namespace AgroBase.Models
public Sentido Sentido { get; set; }
public double Temperatura { get; set; }
public double TemperaturaDriver { get; set; }
public double Corrente { get; set; }
public double Corrente_Motor { get; set; }
public double Corrente_Barramento { get; set; }
public double Tensao { get; set; }
public double Potencia { get; set; }
public double CicloTrabalho { get; set; }
public int CodAlarme { get; set; }
public bool EmFreio { get; set; }
public bool Ativado { get; set; }

View File

@ -120,6 +120,17 @@ namespace AgroBase.Models
return diametro;
}
}
public static int NumeroPolosMotor
{
get
{
double NPolos =
Variaveis.OperacaoEmAndamento.DispMvd != null ?
Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.Average(x => x.MovMotor.NumeroPolos) :
10;
return (int)NPolos;
}
}
public static int TempoEntrePingsConexao { get; set; } = 10000;
public static Dictionary<AcaoFreio, int> AnguloFreio { get; } = new Dictionary<AcaoFreio, int>()
{

View File

@ -205,7 +205,7 @@ namespace AgroBase.Services
// Inicializa o serviço Ethernet com IP e porta específicos
public static async Task<bool> InicializarEthernetService()
{
string ipAddress = Variaveis.OperacaoEmAndamento.DispMvd.Dados.IP_Bld;
string ipAddress = Variaveis.OperacaoEmAndamento.DispMvd.Dados.IP_Mov;
int port = VariaveisPortas.Ethernet_TCP;
_ethernetService?.Disconnect();
@ -245,7 +245,7 @@ namespace AgroBase.Services
List<string> Mod_IDs = new List<string>();
foreach (var Modulo in Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.Where(x => !x.MovMotor.BLD_Inicializado))
foreach (var Modulo in Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.Where(x => !x.MovMotor.Inicializado))
{
byte Addr = 0;
try
@ -481,7 +481,7 @@ namespace AgroBase.Services
{
new BLDParametrosRequisitar()
{
Registro = Parametro.Registro,
Registro = (byte)Parametro.Registro,
Escala = Parametro.Escala,
Valor = null
}
@ -495,7 +495,7 @@ namespace AgroBase.Services
{
_parametro = new BLDParametrosRequisitar()
{
Registro = Parametro.Registro,
Registro = (byte)Parametro.Registro,
Escala = Parametro.Escala,
Valor = null
};

View File

@ -137,7 +137,7 @@ public class EthernetService
}
// Método para receber dados do dispositivo via Ethernet
public async Task<byte[]> ReceiveDataAsync(int expectedLength, int timeoutMilliseconds = 1000)
public async Task<byte[]> ReceiveDataAsync(int expectedLength, int timeoutMilliseconds = 200)
{
var buffer = new byte[expectedLength];
try
@ -156,12 +156,14 @@ public class EthernetService
{
// Se o timeout for atingido, retorna nulo ou exibe uma mensagem
Console.WriteLine("Timeout ao receber dados via Ethernet.");
await ReconnectAsync();
return null;
}
}
catch (Exception ex)
{
Console.WriteLine($"Erro ao receber dados: {ex.Message}");
await ReconnectAsync();
return null;
}
finally
@ -266,13 +268,20 @@ public class EthernetService
}
public async Task FlushBufferAsync()
public async Task FlushBufferAsync(bool forcar = false)
{
try
{
var tempBuffer = new byte[1024]; // Buffer temporário para leitura
if (forcar)
{
await _networkStream?.ReadAsync(tempBuffer, 0, tempBuffer.Length);
}
else
{
if (_networkStream?.DataAvailable ?? false) // Verifica se há dados pendentes no buffer
{
var tempBuffer = new byte[1024]; // Buffer temporário para leitura
while (_networkStream?.DataAvailable ?? false)
{
await _networkStream?.ReadAsync(tempBuffer, 0, tempBuffer.Length);
@ -280,6 +289,7 @@ public class EthernetService
//Console.WriteLine("Buffer limpo.");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Erro ao limpar buffer: {ex.Message}");

View File

@ -777,9 +777,9 @@ namespace AgroBase.Services
double velocidadeMin = FuncoesMatematicas.CalculaVelocidadeRPM(Variaveis.OperacaoEmAndamento.Controle.RPM_Min);
double TemperaturaCampo = WT901CService.Iniciado ? WT901CService.DadosLeitura.Temperatura : 0;
(bool dirOperante, List<string> dirModsFalha) = Variaveis.OperacaoEmAndamento.DispMvd.Dados.StatusModulosMKS(Variaveis.OperacaoEmAndamento.Controle.TipoMovimento);
(bool movEsqOperante, List<string> movEsqModsFalha) = Variaveis.OperacaoEmAndamento.DispMvd.Dados.StatusModulosBLD(Direcao.Esquerda);
(bool movDirOperante, List<string> movDirModsFalha) = Variaveis.OperacaoEmAndamento.DispMvd.Dados.StatusModulosBLD(Direcao.Direita);
(bool dirOperante, List<string> dirModsFalha) = Variaveis.OperacaoEmAndamento.DispMvd.Dados.StatusModulosDIR(Variaveis.OperacaoEmAndamento.Controle.TipoMovimento);
(bool movEsqOperante, List<string> movEsqModsFalha) = Variaveis.OperacaoEmAndamento.DispMvd.Dados.StatusModulosMOV(Direcao.Esquerda);
(bool movDirOperante, List<string> movDirModsFalha) = Variaveis.OperacaoEmAndamento.DispMvd.Dados.StatusModulosMOV(Direcao.Direita);
LoRaProtocoloTransmissaoModel dados = new LoRaProtocoloTransmissaoModel()
{

View File

@ -17,7 +17,7 @@ namespace AgroBase.Services
{
get
{
return _ethernetService != null && _ethernetService.IsConnected && SerialService.DispositivosMapeados.Any(x => x.Dispositivo == T_Code.Mks) && DadosLeitura.Any(x => x.Iniciado);
return _ethernetService != null && _ethernetService.IsConnected && SerialService.DispositivosMapeados.Any(x => x.Dispositivo == T_Code.Dir) && DadosLeitura.Any(x => x.Iniciado);
}
}
public static int TaxaAmostragem { get; set; } = 1000;
@ -54,7 +54,7 @@ namespace AgroBase.Services
// Inicializa o serviço Ethernet com IP e porta específicos
public static async Task<bool> InicializarEthernetService()
{
string ipAddress = Variaveis.OperacaoEmAndamento.DispMvd.Dados.IP_Mks;
string ipAddress = Variaveis.OperacaoEmAndamento.DispMvd.Dados.IP_Dir;
int port = VariaveisPortas.Ethernet_TCP;
_ethernetService?.Disconnect();
@ -93,7 +93,7 @@ namespace AgroBase.Services
List<string> Mod_IDs = new List<string>();
// Verifica e inicializa cada módulo conectado
foreach (var Modulo in Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.Where(x => !x.DirMotor.MKS_Inicializado))
foreach (var Modulo in Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.Where(x => !x.DirMotor.Inicializado))
{
byte Addr = Modulo.DirMotor.EnderecoByte;
DataSended = Convert.ToByte("43");
@ -191,7 +191,7 @@ namespace AgroBase.Services
private static void DefinirDispositivo(List<string> Mod_IDs)
{
if (!SerialService.DispositivosMapeados.Any(x => x.Dispositivo == T_Code.Mks))
if (!SerialService.DispositivosMapeados.Any(x => x.Dispositivo == T_Code.Dir))
{
IniciarRotinas();
}
@ -201,7 +201,7 @@ namespace AgroBase.Services
var Modulo = Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.FirstOrDefault(x => x.Modulo_ID == Mod_ID);
byte Addr = Modulo.DirMotor.EnderecoByte;
if (!SerialService.DispositivosMapeados.Any(x => x.Dispositivo == T_Code.Mks && x.Mod_ID == Mod_ID))
if (!SerialService.DispositivosMapeados.Any(x => x.Dispositivo == T_Code.Dir && x.Mod_ID == Mod_ID))
{
var Leitura = DadosLeitura.FirstOrDefault(x => x.Endereco == Addr);
if (Leitura != null)
@ -209,7 +209,7 @@ namespace AgroBase.Services
SerialService.DispositivosMapeados.Add(new DispositivoDetalhesModel()
{
Endereco = _ethernetService != null ? _ethernetService._ipAddress : "N/A",
Dispositivo = T_Code.Mks,
Dispositivo = T_Code.Dir,
Erro = (Leitura.Mensagem ?? "") != "",
Versao = (Leitura.FV ?? "").ToString(),
Mod_ID = Mod_ID,

View File

@ -353,21 +353,44 @@ namespace AgroBase.Services
public static byte[] ComandoSetParametro(byte slaveAddress, ModbusParametrosModel Parametro, float valor)
{
if (Parametro == null)
throw new ArgumentNullException(nameof(Parametro));
Parametro.UltimaRequisicao = DateTime.Now;
// Convertendo o valor para o formato correto (LSB = 0.01)
int valorInt = (int)(valor * Parametro.Escala); // Convertendo para inteiro conforme a resolução
byte functionCode = 0x06;
// Converte o valor conforme a escala e limita para 32 bits SIGNED (dois registradores Modbus)
int valorInt = (int)(valor * Parametro.Escala);
if (valorInt > int.MaxValue || valorInt < int.MinValue)
throw new ArgumentOutOfRangeException(nameof(valor), "O valor excede o limite do registrador Modbus (-2^31 a 2^31-1).");
// Escolhe a função correta
byte functionCode = Parametro.EscritaMultipla ? (byte)0x10 : (byte)0x06;
ushort registerAddress = Parametro.Registro;
// Construindo o comando
List<byte> command = new List<byte>();
command.Add(slaveAddress);
command.Add(functionCode);
command.AddRange(BitConverter.GetBytes(registerAddress).Reverse()); // Little endian
command.AddRange(BitConverter.GetBytes((ushort)valorInt).Reverse()); // Little endian
command.AddRange(BitConverter.GetBytes(registerAddress).Reverse()); // Big-endian
byte[] crc = Crc16(command.ToArray()); // Supondo que você tenha a implementação do CRC16
if (functionCode == 0x10)
{
// Escrita múltipla → Devemos escrever DOIS registradores (4 bytes)
ushort quantidade = 2; // Sempre 2 registradores para um int32 (4 bytes)
command.AddRange(BitConverter.GetBytes(quantidade).Reverse()); // Número de registradores
command.Add((byte)(quantidade * 2)); // Quantidade de bytes (4)
// Converter valor inteiro (32 bits) em dois registradores (16 bits cada) em big-endian
byte[] valorBytes = BitConverter.GetBytes(valorInt).Reverse().ToArray();
command.AddRange(valorBytes);
}
else
{
// Escrita única (0x06) - Apenas 1 registrador (16 bits)
command.AddRange(BitConverter.GetBytes((short)valorInt).Reverse());
}
// Calcula CRC e adiciona ao final
byte[] crc = Crc16(command.ToArray());
command.AddRange(crc);
return command.ToArray();
@ -375,25 +398,30 @@ namespace AgroBase.Services
public static byte[] ComandoGetParametro(byte slaveAddress, ModbusParametrosModel Parametro)
{
if (Parametro == null)
throw new ArgumentNullException(nameof(Parametro));
Parametro.UltimaRequisicao = DateTime.Now;
byte functionCode = 0x03;
// Escolhe a função correta (0x04 para leitura de entrada, 0x03 para registradores normais)
byte functionCode = Parametro.LeituraEntrada ? (byte)0x04 : (byte)0x03;
ushort registerAddress = Parametro.Registro;
ushort numberOfRegisters = Parametro.N_Registros; // Lendo apenas um registro
ushort numberOfRegisters = Parametro.N_Registros;
// Construindo o comando
List<byte> command = new List<byte>();
command.Add(slaveAddress);
command.Add(functionCode);
command.AddRange(BitConverter.GetBytes(registerAddress).Reverse()); // Big endian
command.AddRange(BitConverter.GetBytes(numberOfRegisters).Reverse()); // Big endian
command.AddRange(BitConverter.GetBytes(registerAddress).Reverse()); // Big-endian
command.AddRange(BitConverter.GetBytes(numberOfRegisters).Reverse());
byte[] crc = Crc16(command.ToArray()); // Supondo que você tenha a implementação do CRC16
// Calcula CRC e adiciona ao final
byte[] crc = Crc16(command.ToArray());
command.AddRange(crc);
return command.ToArray();
}
public static bool FindModbus(byte[] sendByte, byte[] returnByte, out byte[] modbus)
{

File diff suppressed because it is too large Load Diff

View File

@ -28,7 +28,7 @@ namespace AgroBase.Services
public static List<T_Code> DispositivosConexaoInicial = new List<T_Code>() { T_Code.Mvd, T_Code.Atu, T_Code.Sen };
public static List<T_Code> DispositivosProprios = new List<T_Code>() { T_Code.Atu, T_Code.Sen };
public static List<T_Code> DispositivosModbus = new List<T_Code>() { T_Code.Pzm, T_Code.Wit, T_Code.A05 };
public static List<T_Code> DispositivosMultiplos = new List<T_Code>() { T_Code.Bld, T_Code.Mks, T_Code.Mvd };
public static List<T_Code> DispositivosMultiplos = new List<T_Code>() { T_Code.Bld, T_Code.Mks, T_Code.Mvd, T_Code.Oid, T_Code.Mov, T_Code.Dir };
public static List<DispositivoDetalhesModel> DispositivosMapeados = new List<DispositivoDetalhesModel>();
private static Dictionary<string, int> TentativasPortas = new Dictionary<string, int>();
@ -670,8 +670,14 @@ namespace AgroBase.Services
}
}
bool DispBld = await ProcuraDispositivoBLD();
/*bool DispBld = await ProcuraDispositivoBLD();
if (DispBld)
{
ethernetEncontrado = true;
}*/
bool DispOid = await ProcuraDispositivoOID();
if (DispOid)
{
ethernetEncontrado = true;
}
@ -776,6 +782,22 @@ namespace AgroBase.Services
return BLD300RService.Iniciado;
}
private static async Task<bool> ProcuraDispositivoOID()
{
if (!OIDService.Iniciado || OIDService.DadosLeitura.Any(x => !x.Iniciado))
{
AtualizarConsole("Procurando dispositivos OID");
bool Encontrado = await OIDService.VerificaPortaOID();
if (Encontrado)
{
AtualizarConsole("Dispositivo OID encontrado");
return Encontrado;
}
}
return OIDService.Iniciado;
}
private static async Task<bool> ProcuraDispositivoMKS()
{
if (!MKS057DService.Referenciando && (!MKS057DService.Iniciado || MKS057DService.DadosLeitura.Any(x => !x.Iniciado)))
@ -894,13 +916,16 @@ namespace AgroBase.Services
}
}
public static void MostrarComandoResposta(T_Code tipo, byte[] comando, byte[] resposta)
public static string MostrarComandoResposta(T_Code tipo, byte[] comando, byte[] resposta)
{
bool showCommands = true;
string msg = tipo.ToString() + " - TX: " + string.Join(" ", comando.Select(x => x.ToString("x"))) + ", RX: " + string.Join(" ", (resposta != null ? resposta : new byte[] { }).Select(x => x.ToString("x")));
if (showCommands)
{
Console.WriteLine(tipo.ToString() + " - TX: " + string.Join(" ", comando.Select(x => x.ToString("x"))) + ", RX: " + string.Join(" ", (resposta != null ? resposta : new byte[] { }).Select(x => x.ToString("x"))));
Console.WriteLine(msg);
}
return msg;
}

View File

@ -288,3 +288,4 @@
20/12/2024 16:48:14:661 - Porta COM107 - 0: Erro ao processar fila de comandos. Erro=The I/O operation has been aborted because of either a thread exit or an application request.
09/01/2025 16:45:45:498 - Porta COM112 - 0: Erro ao processar fila de comandos. Erro=The port is closed.

Binary file not shown.

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"Id":"1","Name":"Projeto","Length":23.747936168010394,"Dist1":0.0,"Dist2":0.0},"geometry":{"id":"0","type":"LineString","coordinates":[[-47.372156833333335,-22.178973166666665],[-47.372197666666665,-22.178952],[-47.372259333333332,-22.178925833333334],[-47.372304666666665,-22.178904666666668],[-47.372361833333336,-22.178876166666665]]}},{"type":"Feature","properties":{"Id":"2","Name":"Projeto","Length":23.891304512285874,"Dist1":0.0,"Dist2":0.0},"geometry":{"id":"1","type":"LineString","coordinates":[[-47.3723795,-22.178883333333335],[-47.372341166666665,-22.178902666666666],[-47.372294666666669,-22.178925666666668],[-47.372234666666664,-22.1789555],[-47.372178166666664,-22.178984833333335]]}},{"type":"Feature","properties":{"Id":"3","Name":"Projeto","Length":23.838775018394195,"Dist1":0.0,"Dist2":0.0},"geometry":{"id":"2","type":"LineString","coordinates":[[-47.3721695,-22.179005],[-47.3722225,-22.178979166666668],[-47.3722845,-22.178951166666668],[-47.3723305,-22.178931166666668],[-47.372374666666666,-22.178911]]}},{"type":"Feature","properties":{"Id":"4","Name":"Projeto","Length":23.760554463105805,"Dist1":0.0,"Dist2":0.0},"geometry":{"id":"3","type":"LineString","coordinates":[[-47.372394833333331,-22.178915166666666],[-47.372350666666669,-22.178935166666665],[-47.372289166666668,-22.178960833333335],[-47.372228666666665,-22.178988833333332],[-47.372188,-22.179009166666667]]}},{"type":"Feature","properties":{"Id":"5","Name":"Projeto","Length":23.888166936433826,"Dist1":0.0,"Dist2":0.0},"geometry":{"id":"4","type":"LineString","coordinates":[[-47.37217866666667,-22.179029],[-47.372224833333334,-22.179004],[-47.372283,-22.178976166666665],[-47.372326833333332,-22.178956333333332],[-47.37238383333333,-22.1789295]]}}]}
{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"Id":"1","Name":"10_01_2025_08_59_29","Length":0.0,"Dist1":0.0,"Dist2":0.0},"geometry":{"id":null,"type":"LineString","coordinates":[[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0]]}}]}

View File

@ -25,7 +25,7 @@
<meta name="viewport" content="width=device-width,
initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<style>
#map_b1e967db0930cba1bcb6ebd6e1b8e6bd {
#map_392c7a8144b81ff24ee73793d6868543 {
position: relative;
width: 100.0%;
height: 100.0%;
@ -39,14 +39,14 @@
<body>
<div class="folium-map" id="map_b1e967db0930cba1bcb6ebd6e1b8e6bd" ></div>
<div class="folium-map" id="map_392c7a8144b81ff24ee73793d6868543" ></div>
</body>
<script>
var map_b1e967db0930cba1bcb6ebd6e1b8e6bd = L.map(
"map_b1e967db0930cba1bcb6ebd6e1b8e6bd",
var map_392c7a8144b81ff24ee73793d6868543 = L.map(
"map_392c7a8144b81ff24ee73793d6868543",
{
center: [0.0, 0.0],
crs: L.CRS.EPSG3857,
@ -59,6 +59,15 @@
var tile_layer_b7dd6033a6ac952784752ad1d60e70fc = L.tileLayer(
"https://tile.openstreetmap.org/{z}/{x}/{y}.png",
{"attribution": "\u0026copy; \u003ca href=\"https://www.openstreetmap.org/copyright\"\u003eOpenStreetMap\u003c/a\u003e contributors", "detectRetina": false, "maxNativeZoom": 19, "maxZoom": 19, "minZoom": 0, "noWrap": false, "opacity": 1, "subdomains": "abc", "tms": false}
);
tile_layer_b7dd6033a6ac952784752ad1d60e70fc.addTo(map_392c7a8144b81ff24ee73793d6868543);
</script>
<script>
@ -78,7 +87,7 @@
}
trajeto_json_add({"features": []});
trajeto_json.addTo(map_b1e967db0930cba1bcb6ebd6e1b8e6bd);
trajeto_json.addTo(map_392c7a8144b81ff24ee73793d6868543);
function adicionarGeometria(novaGeometria) {
trajeto_json.addData(novaGeometria);
@ -136,7 +145,7 @@
var marcadorDinamico = L.marker([0, 0], {
icon: customIcon
}).addTo(map_b1e967db0930cba1bcb6ebd6e1b8e6bd);
}).addTo(map_392c7a8144b81ff24ee73793d6868543);
// Conectar ao broker MQTT
const client = mqtt.connect('ws://localhost:9001'); // Use wss para conexão segura
@ -174,7 +183,7 @@
marcadorDinamico.setRotationAngle(angulo);
adicionarCoordenada("Tj", [novaLongitude, novaLatitude]);
map_b1e967db0930cba1bcb6ebd6e1b8e6bd.setView(novaPosicao, map_b1e967db0930cba1bcb6ebd6e1b8e6bd.getZoom());
map_392c7a8144b81ff24ee73793d6868543.setView(novaPosicao, map_392c7a8144b81ff24ee73793d6868543.getZoom());
});
function calcularOrientacao(P1latitude, P1longitude, P2latitude, P2longitude) {

View File

@ -25,7 +25,7 @@
<meta name="viewport" content="width=device-width,
initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<style>
#map_d5e32ca089db3877639e615b5d23cc53 {
#map_4620e6c91fa369c768e87742adfd5664 {
position: relative;
width: 100.0%;
height: 100.0%;
@ -39,16 +39,16 @@
<body>
<div class="folium-map" id="map_d5e32ca089db3877639e615b5d23cc53" ></div>
<div class="folium-map" id="map_4620e6c91fa369c768e87742adfd5664" ></div>
</body>
<script>
var map_d5e32ca089db3877639e615b5d23cc53 = L.map(
"map_d5e32ca089db3877639e615b5d23cc53",
var map_4620e6c91fa369c768e87742adfd5664 = L.map(
"map_4620e6c91fa369c768e87742adfd5664",
{
center: [-22.178952583333334, -47.37227583333333],
center: [0.0, 0.0],
crs: L.CRS.EPSG3857,
zoom: 12,
zoomControl: true,
@ -60,6 +60,15 @@
var tile_layer_1f0ea7cc2ab2e8549b198a6a1459bee6 = L.tileLayer(
"https://tile.openstreetmap.org/{z}/{x}/{y}.png",
{"attribution": "\u0026copy; \u003ca href=\"https://www.openstreetmap.org/copyright\"\u003eOpenStreetMap\u003c/a\u003e contributors", "detectRetina": false, "maxNativeZoom": 19, "maxZoom": 19, "minZoom": 0, "noWrap": false, "opacity": 1, "subdomains": "abc", "tms": false}
);
tile_layer_1f0ea7cc2ab2e8549b198a6a1459bee6.addTo(map_4620e6c91fa369c768e87742adfd5664);
var trajetosSelecionados = {};
@ -73,7 +82,7 @@
}*/
});
}
function geo_json_30d80d1ae2d5026de470c2f3babec69d_onEachFeature(feature, layer) {
function geo_json_bbd3fdea3ebda05226bb6843840037bb_onEachFeature(feature, layer) {
layer.on({
click: function(e) {
@ -109,20 +118,20 @@
}*/
});
};
var geo_json_30d80d1ae2d5026de470c2f3babec69d = L.geoJson(null, {
onEachFeature: geo_json_30d80d1ae2d5026de470c2f3babec69d_onEachFeature,
var geo_json_bbd3fdea3ebda05226bb6843840037bb = L.geoJson(null, {
onEachFeature: geo_json_bbd3fdea3ebda05226bb6843840037bb_onEachFeature,
});
function geo_json_30d80d1ae2d5026de470c2f3babec69d_add (data) {
geo_json_30d80d1ae2d5026de470c2f3babec69d
function geo_json_bbd3fdea3ebda05226bb6843840037bb_add (data) {
geo_json_bbd3fdea3ebda05226bb6843840037bb
.addData(data);
}
geo_json_30d80d1ae2d5026de470c2f3babec69d_add({"features": [{"geometry": {"coordinates": [[-47.372156833333335, -22.178973166666665], [-47.372197666666665, -22.178952], [-47.37225933333333, -22.178925833333334], [-47.372304666666665, -22.178904666666668], [-47.372361833333336, -22.178876166666665]], "id": "0", "type": "LineString"}, "id": 0, "properties": {"Dist1": 0.0, "Dist2": 0.0, "Id": "1", "Length": 23.747936168010394, "Name": "Projeto"}, "type": "Feature"}, {"geometry": {"coordinates": [[-47.3723795, -22.178883333333335], [-47.372341166666665, -22.178902666666666], [-47.37229466666667, -22.178925666666668], [-47.372234666666664, -22.1789555], [-47.372178166666664, -22.178984833333335]], "id": "1", "type": "LineString"}, "id": 1, "properties": {"Dist1": 0.0, "Dist2": 0.0, "Id": "2", "Length": 23.891304512285874, "Name": "Projeto"}, "type": "Feature"}, {"geometry": {"coordinates": [[-47.3721695, -22.179005], [-47.3722225, -22.178979166666668], [-47.3722845, -22.178951166666668], [-47.3723305, -22.17893116666667], [-47.372374666666666, -22.178911]], "id": "2", "type": "LineString"}, "id": 2, "properties": {"Dist1": 0.0, "Dist2": 0.0, "Id": "3", "Length": 23.838775018394195, "Name": "Projeto"}, "type": "Feature"}, {"geometry": {"coordinates": [[-47.37239483333333, -22.178915166666666], [-47.37235066666667, -22.178935166666665], [-47.37228916666667, -22.178960833333335], [-47.372228666666665, -22.17898883333333], [-47.372188, -22.179009166666667]], "id": "3", "type": "LineString"}, "id": 3, "properties": {"Dist1": 0.0, "Dist2": 0.0, "Id": "4", "Length": 23.760554463105805, "Name": "Projeto"}, "type": "Feature"}, {"geometry": {"coordinates": [[-47.37217866666667, -22.179029], [-47.372224833333334, -22.179004], [-47.372283, -22.178976166666665], [-47.37232683333333, -22.178956333333332], [-47.37238383333333, -22.1789295]], "id": "4", "type": "LineString"}, "id": 4, "properties": {"Dist1": 0.0, "Dist2": 0.0, "Id": "5", "Length": 23.888166936433826, "Name": "Projeto"}, "type": "Feature"}], "type": "FeatureCollection"});
geo_json_bbd3fdea3ebda05226bb6843840037bb_add({"features": [{"geometry": {"coordinates": [[0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0]], "id": null, "type": "LineString"}, "id": 0, "properties": {"Dist1": 0.0, "Dist2": 0.0, "Id": "1", "Length": 0.0, "Name": "10_01_2025_08_59_29"}, "type": "Feature"}], "type": "FeatureCollection"});
geo_json_30d80d1ae2d5026de470c2f3babec69d.addTo(map_d5e32ca089db3877639e615b5d23cc53);
geo_json_bbd3fdea3ebda05226bb6843840037bb.addTo(map_4620e6c91fa369c768e87742adfd5664);
</script>
@ -143,7 +152,7 @@
}
trajeto_json_add({"features": []});
trajeto_json.addTo(map_d5e32ca089db3877639e615b5d23cc53);
trajeto_json.addTo(map_4620e6c91fa369c768e87742adfd5664);
function adicionarGeometria(novaGeometria) {
trajeto_json.addData(novaGeometria);
@ -201,7 +210,7 @@
}
trajeto_dinamico_json_add({"features": []});
trajeto_dinamico_json.addTo(map_d5e32ca089db3877639e615b5d23cc53);
trajeto_dinamico_json.addTo(map_4620e6c91fa369c768e87742adfd5664);
function adicionarGeometriaDinamica(novaGeometria) {
trajeto_dinamico_json.addData(novaGeometria);
@ -254,9 +263,9 @@
var marcadorEquipamento = L.marker([0, 0], {
icon: customIcon
}).addTo(map_d5e32ca089db3877639e615b5d23cc53);
}).addTo(map_4620e6c91fa369c768e87742adfd5664);
var marcadorBase = L.marker([0, 0], {}).addTo(map_d5e32ca089db3877639e615b5d23cc53);
var marcadorBase = L.marker([0, 0], {}).addTo(map_4620e6c91fa369c768e87742adfd5664);
var icon = L.AwesomeMarkers.icon(
{"extraClasses": "fa-rotate-0", "icon": "info-sign", "iconColor": "white", "markerColor": "red", "prefix": "glyphicon"}
);
@ -338,7 +347,7 @@
}
if (foco) {
map_d5e32ca089db3877639e615b5d23cc53.setView(novaPosicao, map_d5e32ca089db3877639e615b5d23cc53.getZoom());
map_4620e6c91fa369c768e87742adfd5664.setView(novaPosicao, map_4620e6c91fa369c768e87742adfd5664.getZoom());
}
}
@ -355,7 +364,7 @@
function atualizarSelecaoRuas(selecionadas) {
selecionadas = JSON.parse(selecionadas);
RuasSelecionadas = Array.isArray(selecionadas) ? [...selecionadas] : [];
geo_json_30d80d1ae2d5026de470c2f3babec69d.eachLayer(function (layer) {
geo_json_bbd3fdea3ebda05226bb6843840037bb.eachLayer(function (layer) {
if (RuasSelecionadas.includes(parseInt(layer.feature.id))) {
layer.setStyle({ color: 'blue' });
} else {

View File

@ -1 +1 @@
67868050e67547dc83356f09c576b86f9f0a70485da0997bf220ca7410042de4
fd9a57f6605b31f54ec98f9b5a8c43b9b81a30d278234dcc8ced505b3977ec6e

View File

@ -481,3 +481,4 @@ C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\OpenHardwareMonitorLib.dl
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\obj\Debug\AgroBase.Forms.frmA05Config.resources
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\obj\Debug\AgroBase.Forms.frmEthernet.resources
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\obj\Debug\AgroBase.csproj.CopyComplete
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\obj\Debug\AgroBase.Forms.frmOID.resources

View File

@ -37,11 +37,11 @@
this.rtbLRA = new System.Windows.Forms.RichTextBox();
this.chbLra = new System.Windows.Forms.CheckBox();
this.rtbATU = new System.Windows.Forms.RichTextBox();
this.chbBld = new System.Windows.Forms.CheckBox();
this.chbMov = new System.Windows.Forms.CheckBox();
this.chbAtu = new System.Windows.Forms.CheckBox();
this.rtbMVD = new System.Windows.Forms.RichTextBox();
this.rtbGPS = new System.Windows.Forms.RichTextBox();
this.chbMks = new System.Windows.Forms.CheckBox();
this.chbDir = new System.Windows.Forms.CheckBox();
this.chbGps = new System.Windows.Forms.CheckBox();
this.rtbMKS = new System.Windows.Forms.RichTextBox();
this.rtbWIT = new System.Windows.Forms.RichTextBox();
@ -142,11 +142,11 @@
this.pnlModulos.Controls.Add(this.rtbLRA);
this.pnlModulos.Controls.Add(this.chbLra);
this.pnlModulos.Controls.Add(this.rtbATU);
this.pnlModulos.Controls.Add(this.chbBld);
this.pnlModulos.Controls.Add(this.chbMov);
this.pnlModulos.Controls.Add(this.chbAtu);
this.pnlModulos.Controls.Add(this.rtbMVD);
this.pnlModulos.Controls.Add(this.rtbGPS);
this.pnlModulos.Controls.Add(this.chbMks);
this.pnlModulos.Controls.Add(this.chbDir);
this.pnlModulos.Controls.Add(this.chbGps);
this.pnlModulos.Controls.Add(this.rtbMKS);
this.pnlModulos.Controls.Add(this.rtbWIT);
@ -241,16 +241,16 @@
this.rtbATU.TabIndex = 12;
this.rtbATU.Text = "Responsável pelo controle do pulverizador";
//
// chbBld
// chbMov
//
this.chbBld.AutoSize = true;
this.chbBld.Location = new System.Drawing.Point(3, 4);
this.chbBld.Name = "chbBld";
this.chbBld.Size = new System.Drawing.Size(47, 17);
this.chbBld.TabIndex = 1;
this.chbBld.Text = "BLD";
this.chbBld.UseVisualStyleBackColor = true;
this.chbBld.CheckedChanged += new System.EventHandler(this.chbModulo_CheckedChanged);
this.chbMov.AutoSize = true;
this.chbMov.Location = new System.Drawing.Point(3, 4);
this.chbMov.Name = "chbMov";
this.chbMov.Size = new System.Drawing.Size(50, 17);
this.chbMov.TabIndex = 1;
this.chbMov.Text = "MOV";
this.chbMov.UseVisualStyleBackColor = true;
this.chbMov.CheckedChanged += new System.EventHandler(this.chbModulo_CheckedChanged);
//
// chbAtu
//
@ -285,16 +285,16 @@
this.rtbGPS.TabIndex = 10;
this.rtbGPS.Text = "Responsável pelo monitoramento da posição geográfica do equipamento";
//
// chbMks
// chbDir
//
this.chbMks.AutoSize = true;
this.chbMks.Location = new System.Drawing.Point(3, 68);
this.chbMks.Name = "chbMks";
this.chbMks.Size = new System.Drawing.Size(49, 17);
this.chbMks.TabIndex = 3;
this.chbMks.Text = "MKS";
this.chbMks.UseVisualStyleBackColor = true;
this.chbMks.CheckedChanged += new System.EventHandler(this.chbModulo_CheckedChanged);
this.chbDir.AutoSize = true;
this.chbDir.Location = new System.Drawing.Point(3, 68);
this.chbDir.Name = "chbDir";
this.chbDir.Size = new System.Drawing.Size(45, 17);
this.chbDir.TabIndex = 3;
this.chbDir.Text = "DIR";
this.chbDir.UseVisualStyleBackColor = true;
this.chbDir.CheckedChanged += new System.EventHandler(this.chbModulo_CheckedChanged);
//
// chbGps
//
@ -977,13 +977,13 @@
#endregion
private System.Windows.Forms.GroupBox gpbModulos;
private System.Windows.Forms.CheckBox chbBld;
private System.Windows.Forms.CheckBox chbMov;
private System.Windows.Forms.RichTextBox rtbPZM;
private System.Windows.Forms.CheckBox chbPzm;
private System.Windows.Forms.RichTextBox rtbSEN;
private System.Windows.Forms.CheckBox chbSen;
private System.Windows.Forms.RichTextBox rtbMKS;
private System.Windows.Forms.CheckBox chbMks;
private System.Windows.Forms.CheckBox chbDir;
private System.Windows.Forms.RichTextBox rtbMVD;
private System.Windows.Forms.RichTextBox rtbGPS;
private System.Windows.Forms.CheckBox chbGps;

View File

@ -207,4 +207,4 @@ C:\ZendionInc\agrobot_base\AgroBase\AgroMonitor\bin\Debug\x86\msvcp140_codecvt_i
C:\ZendionInc\agrobot_base\AgroBase\AgroMonitor\bin\Debug\x86\opencv_videoio_ffmpeg440.dll
C:\ZendionInc\agrobot_base\AgroBase\AgroMonitor\bin\Debug\x86\vcruntime140.dll
C:\ZendionInc\agrobot_base\AgroBase\AgroMonitor\bin\Debug\OpenHardwareMonitorLib.dll
C:\ZendionINC\agrobot_base\AgroBase\AgroMonitor\obj\Debug\AgroMoni.D419EBC3.Up2Date
C:\ZendionInc\agrobot_base\AgroBase\AgroMonitor\obj\Debug\AgroMonitor.csproj.CopyComplete

303
Python/oidlec/controle.py Normal file
View File

@ -0,0 +1,303 @@
import serial
import struct
import threading
import time
# Configuração da porta serial
SERIAL_PORT = "COM114" # Substitua pela sua porta correta
BAUD_RATE = 115200
DEVICE_ID = 1 # Endereço do dispositivo Modbus
Heartbeat = False
ModoControle = 0
N_Polos = 15
# Mapeamento de registradores
REG_HEARTBEAT = 0x1770
REG_MODOCONTROLE = 0x1771
REG_TORQUEMAX = 0x178C
REGISTERS = {
"velocidade": 0x1389, # Velocidade em ERPM 9
"corrente": 0x138E, # Corrente em escala de 0.01 A 7
"tensao": 0x138D, # Tensão em V (corrigido) 7
"potencia": 0x138C, # Potência em W (corrigido) 7
"codigo_erro": 0x1388, # Código de erro do motor 7
"ciclo_trabalho": 0x138B, # Ciclo de trabalho (% em escala de 0.1) 7
"temperatura": 0x1390 # Temperatura em °C 7
}
# Função para calcular CRC16 Modbus
def calculate_crc(data):
crc = 0xFFFF
for pos in data:
crc ^= pos
for _ in range(8):
if crc & 0x0001:
crc >>= 1
crc ^= 0xA001
else:
crc >>= 1
return crc.to_bytes(2, byteorder='little')
def build_command(slave_address, function_code, register, value=None, num_regs=1):
"""
Constrói um comando Modbus RTU válido, suportando:
- 0x03 (Leitura de Holding Registers)
- 0x04 (Leitura de Input Registers)
- 0x06 (Escrita em um único registrador)
- 0x10 (Escrita em múltiplos registradores)
"""
frame = struct.pack(">BBH", slave_address, function_code, register)
if function_code in (0x03, 0x04): # Leitura de registradores
frame += struct.pack(">H", num_regs) # Número de registradores a ler
elif function_code == 0x06: # Escrita em único registrador
frame += struct.pack(">h", value) # Suporta valores negativos
elif function_code == 0x10: # Escrita em múltiplos registradores
if isinstance(value, int) and num_regs == 2:
# Conversão de um inteiro para dois registradores (32 bits)
value_high = (value >> 16) & 0xFFFF # Parte alta
value_low = value & 0xFFFF # Parte baixa
frame += struct.pack(">H", num_regs) # Número de registradores
frame += struct.pack("B", num_regs * 2) # Número de bytes de dados
frame += struct.pack(">H", value_high) # Registrador alto
frame += struct.pack(">H", value_low) # Registrador baixo
elif isinstance(value, list) and len(value) == num_regs:
frame += struct.pack(">H", num_regs) # Número de registradores
frame += struct.pack("B", num_regs * 2) # Número de bytes de dados
for v in value:
frame += struct.pack(">H", v) # Adiciona cada valor
else:
raise ValueError("Para função 0x10, 'value' deve ser um inteiro (32 bits) ou uma lista com valores correspondentes a 'num_regs'.")
# Adiciona CRC e retorna comando
frame += calculate_crc(frame)
return frame
def send_command(ser, command):
"""
Envia um comando Modbus RTU e aguarda a resposta correta dinamicamente.
"""
ser.write(command)
time.sleep(0.05) # Pequeno delay inicial
# Lendo os primeiros 3 bytes (ID, Função, Nº de bytes de resposta)
response = ser.read(3)
if len(response) < 3:
print(f"Erro: Resposta Modbus incompleta (Recebido: {response.hex()})")
return None
# Extraindo código de função recebido
function_code = response[1]
if function_code in (0x03, 0x04):
# Se for leitura (0x03 ou 0x04), usar o byte 3 para determinar o número de bytes de dados
num_bytes = response[2]
total_bytes = 3 + num_bytes + 2 # 3 iniciais + dados + 2 CRC
else:
# Se for outro comando (ex: 0x06, 0x10), assume resposta fixa de 8 bytes
total_bytes = 8
# Ler o restante dos bytes esperados
remaining_data = ser.read(total_bytes - 3)
response += remaining_data
# Se a resposta não tiver o tamanho esperado, exibir erro
if len(response) != total_bytes:
print(f"Erro: Resposta Modbus incompleta ({len(response)} de {total_bytes} bytes recebidos).")
print(f"Resposta parcial: {response.hex()}")
return None
# Retornar resposta completa
return response
# Função para controle de velocidade
def definir_velocidade(ser, valor):
"""
Define a velocidade do motor:
- Positivo: sentido horário.
- Negativo: sentido anti-horário.
- Zero: desliga o motor.
"""
global ModoControle
funcao = 0x06
velocidade = 0
registro = 0x1772
n_reg = 1
if ModoControle == 0: # 100 = 1A
registro = 0x1772
velocidade = valor * 100
if ModoControle == 1: # RPM = ERPM / N_POLOS
registro = 0x1773
velocidade = valor * N_Polos
funcao = 0x10
n_reg = 2
if ModoControle == 2: # 100 = 10%
registro = 0x1775
velocidade = valor * 10
if ModoControle == 6: # 100 = 1A
registro = 0x177E
velocidade = valor * 100
command = build_command(DEVICE_ID, funcao, registro, value=int(velocidade), num_regs=n_reg)
response = send_command(ser, command)
print(f"Velocidade definida para {velocidade}. Comando: {command.hex()} - Resposta: {response.hex()}")
# Função para thread do heartbeat
def heartbeat_thread(ser):
global Heartbeat
global heartbeat_ativo
while heartbeat_ativo:
try:
idxHeartbeat = 1 if Heartbeat else 0
command = build_command(DEVICE_ID, 0x06, REG_HEARTBEAT, value=idxHeartbeat)
send_command(ser, command)
time.sleep(0.2) # Envia heartbeat a cada 200ms
Heartbeat = not Heartbeat
except Exception as e:
print(f"Erro no heartbeat: {e}")
break
# Função para ler parâmetros e corrigir valores
def ler_parametros(ser):
print("\n📊 **Parâmetros do Motor**")
for nome, reg in REGISTERS.items():
try:
# Criando comando de leitura Modbus (2 registradores = 4 bytes)
command = build_command(DEVICE_ID, 0x04, reg, None, 2)
response = send_command(ser, command)
if len(response) >= 7: # Garantir que há pelo menos 7 bytes na resposta (ID + Função + Byte Count + Dados + CRC)
num_bytes = response[2] # Número de bytes de dados na resposta
num_regs = num_bytes // 2 # Cada registrador Modbus tem 2 bytes
valor = 0.0
if num_regs == 1:
valor = struct.unpack(">H", response[3:5])[0] # 16 bits (unsigned)
elif num_regs == 2:
# Separar os dois registradores
parte_inteira = struct.unpack(">H", response[3:5])[0] # Primeiros 2 bytes
parte_decimal = struct.unpack(">H", response[5:7])[0] # Últimos 2 bytes
# Construir valor real
valor = float(parte_inteira) + (float(parte_decimal) / 10000) # Decimal com precisão de 4 casas
mensagem = f" - {command.hex()} -> {response.hex()}"
# Conversões conforme a escala de cada registro
if nome == "velocidade":
if num_regs == 2:
parte_inteira = struct.unpack(">h", response[3:5])[0] # 16 bits signed
parte_decimal = struct.unpack(">H", response[5:7])[0] # 16 bits unsigned
valor = float(parte_inteira) + (float(parte_decimal))
rpm = int(valor) // N_Polos # Ajustando para polos do motor
print(f"{nome.capitalize()}: {valor:.4f} ERPM ({rpm} RPM)")
elif nome == "corrente":
print(f"{nome.capitalize()}: {valor * 0.01:.4f} A")
elif nome == "tensao":
print(f"{nome.capitalize()}: {valor:.4f} V")
elif nome == "potencia":
print(f"{nome.capitalize()}: {valor:.4f} W")
elif nome == "ciclo_trabalho":
print(f"{nome.capitalize()}: {valor * 0.1:.4f}%")
elif nome == "temperatura":
print(f"{nome.capitalize()}: {valor:.4f} °C")
else:
print(f"{nome.capitalize()}: {valor:.4f}")
else:
print(f"{nome.capitalize()}: Erro na leitura!")
#print(f"{mensagem}")
except Exception as e:
print(f"{nome.capitalize()}: Erro ({e})")
def definir_modo_controle(ser, modo):
"""
Define o modo de controle do motor (valor entre 0 e 10).
"""
global ModoControle
try:
if 0 <= modo <= 10:
command = build_command(DEVICE_ID, 0x06, REG_MODOCONTROLE, value=modo)
response = send_command(ser, command)
print(f"Modo de controle definido para {modo}. Resposta: {response.hex()}")
ModoControle = modo
else:
print("Modo inválido! Digite um número entre 0 e 10.")
except ValueError:
print("Entrada inválida! Digite um número entre 0 e 10.")
def definir_torque_maximo(ser, corrente):
valor = corrente * 100
command = build_command(DEVICE_ID, 0x06, REG_TORQUEMAX, value=valor)
response = send_command(ser, command)
print(f"Torque maximo definido para {corrente}A")
print(f"Comando: {command.hex()} - Resposta: {response.hex()}")
def menu():
global ModoControle
with serial.Serial(SERIAL_PORT, BAUD_RATE, timeout=1) as ser:
# Inicia a thread do heartbeat
threading.Thread(target=heartbeat_thread, args=(ser,), daemon=True).start()
while True:
print("\nMenu de Controle do Motor:")
print("1 - Definir Modo de Controle")
print("2 - Definir Velocidade (RPM)")
print("3 - Acionar Freio")
print("4 - Ler Parâmetros do Motor")
if (ModoControle == 1):
print("5 - Definir torque maximo")
print("0 - Sair")
opcao = input("Escolha uma opção: ")
if opcao == "1":
modo = int(input("\nDigite o modo de controle (0-10): "))
definir_modo_controle(ser, modo)
elif opcao == "2":
descricao = ""
if ModoControle == 0: # 100 = 1A
descricao = "corrente (A)"
if ModoControle == 1: # RPM
descricao = "RPM"
if ModoControle == 2: # 100 = 10%
descricao = "porcentagem"
velocidade = int(input(f"Digite a Velocidade em {descricao} (positivo/negativo ou 0 para desligar): "))
definir_velocidade(ser, velocidade)
if opcao == "3":
definir_velocidade(ser, 0)
modo_anterior = ModoControle
definir_modo_controle(ser, 6)
definir_velocidade(ser, 1)
time.sleep(1.0)
definir_modo_controle(ser, modo_anterior)
elif opcao == "4":
ler_parametros(ser)
if opcao == "5":
corrente = int(input("\nDigite a corrente de torque maximo em A: "))
definir_torque_maximo(ser, corrente)
elif opcao == "0":
print("Encerrando...")
break
else:
print("Opção inválida! Tente novamente.")
# Executar o menu interativo
if __name__ == "__main__":
heartbeat_ativo = True # Inicializa a flag do heartbeat
menu()

52
Python/oidlec/test.py Normal file
View File

@ -0,0 +1,52 @@
import serial
import struct
import time
def calcula_crc(data):
"""Calcula o CRC16-Modbus"""
crc = 0xFFFF
for byte in data:
crc ^= byte
for _ in range(8):
if crc & 0x0001:
crc = (crc >> 1) ^ 0xA001
else:
crc >>= 1
return struct.pack('<H', crc)
def enviar_comando(ser, endereco, funcao, endereco_reg, quantidade):
"""Envia um comando Modbus RTU e lê a resposta"""
comando = struct.pack('>BBHH', endereco, funcao, endereco_reg, quantidade)
comando += calcula_crc(comando)
ser.write(comando)
time.sleep(0.1) # Aguarda resposta
resposta = ser.read(7 + 2 * quantidade) # Espera pelo menos 7 bytes + dados
return resposta
# Configurar porta serial
porta_serial = "COM112" # Substitua pelo nome correto da porta (ex: COM3 no Windows ou /dev/ttyUSB0 no Linux)
baudrate = 115200
ser = serial.Serial(porta_serial, baudrate=baudrate, bytesize=8, parity='N', stopbits=1, timeout=1)
# Endereço do driver (geralmente 1)
endereco_dispositivo = 1
# Código de função Modbus RTU (0x03 = Ler registradores)
codigo_funcao = 0x03
# Registrador de velocidade do motor (exemplo: 0x0001)
endereco_registrador = 0x0001
# Quantidade de registradores a ler (exemplo: 2)
quantidade_registros = 2
# Enviar comando e exibir resposta
resposta = enviar_comando(ser, endereco_dispositivo, codigo_funcao, endereco_registrador, quantidade_registros)
if resposta:
print("Resposta Hex:", resposta.hex())
else:
print("Nenhuma resposta recebida.")
ser.close()