adicionado ethernet service e suas funcionalidades

This commit is contained in:
Diego Freitas 2024-11-12 16:43:38 -03:00
parent 1af09acc9e
commit 0f4506bfc2
32 changed files with 2310 additions and 1571 deletions

Binary file not shown.

View File

@ -247,6 +247,12 @@
<Compile Include="Forms\frmBLD.Designer.cs">
<DependentUpon>frmBLD.cs</DependentUpon>
</Compile>
<Compile Include="Forms\frmEthernet.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Forms\frmEthernet.Designer.cs">
<DependentUpon>frmEthernet.cs</DependentUpon>
</Compile>
<Compile Include="Forms\frmGPS.cs">
<SubType>Form</SubType>
</Compile>
@ -460,6 +466,7 @@
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Services\DispositivosServiceFactory.cs" />
<Compile Include="Services\EthernetService.cs" />
<Compile Include="Services\FilaService.cs" />
<Compile Include="Services\GPSService.cs" />
<Compile Include="Services\IDispositivosService.cs" />
@ -663,6 +670,9 @@
<EmbeddedResource Include="Forms\frmBLD.resx">
<DependentUpon>frmBLD.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Forms\frmEthernet.resx">
<DependentUpon>frmEthernet.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Forms\frmGPS.resx">
<DependentUpon>frmGPS.cs</DependentUpon>
</EmbeddedResource>

View File

@ -30,6 +30,8 @@ namespace AgroBase.Forms.Direcional
private void InitializeComponent()
{
this.gpbSentido = new System.Windows.Forms.GroupBox();
this.cmbTipoMovimento = new System.Windows.Forms.ComboBox();
this.lblTipoMovimento = new System.Windows.Forms.Label();
this.btnSalvarSentido = new System.Windows.Forms.Button();
this.gpbDF = new System.Windows.Forms.GroupBox();
this.label2 = new System.Windows.Forms.Label();
@ -67,8 +69,8 @@ namespace AgroBase.Forms.Direcional
this.cmbETEsquerda = new System.Windows.Forms.ComboBox();
this.lblETEsquerda = new System.Windows.Forms.Label();
this.lblETDireita = new System.Windows.Forms.Label();
this.cmbTipoMovimento = new System.Windows.Forms.ComboBox();
this.lblTipoMovimento = new System.Windows.Forms.Label();
this.lblIP = new System.Windows.Forms.Label();
this.txtIP = new System.Windows.Forms.TextBox();
this.gpbSentido.SuspendLayout();
this.gpbDF.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.nudDFOffset)).BeginInit();
@ -82,6 +84,8 @@ namespace AgroBase.Forms.Direcional
//
// gpbSentido
//
this.gpbSentido.Controls.Add(this.lblIP);
this.gpbSentido.Controls.Add(this.txtIP);
this.gpbSentido.Controls.Add(this.cmbTipoMovimento);
this.gpbSentido.Controls.Add(this.lblTipoMovimento);
this.gpbSentido.Controls.Add(this.btnSalvarSentido);
@ -98,6 +102,25 @@ namespace AgroBase.Forms.Direcional
this.gpbSentido.TabStop = false;
this.gpbSentido.Text = "Sentido de giro";
//
// cmbTipoMovimento
//
this.cmbTipoMovimento.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbTipoMovimento.FormattingEnabled = true;
this.cmbTipoMovimento.Location = new System.Drawing.Point(195, 18);
this.cmbTipoMovimento.Name = "cmbTipoMovimento";
this.cmbTipoMovimento.Size = new System.Drawing.Size(168, 21);
this.cmbTipoMovimento.TabIndex = 13;
this.cmbTipoMovimento.SelectedIndexChanged += new System.EventHandler(this.cmbTipoMovimento_SelectedIndexChanged);
//
// lblTipoMovimento
//
this.lblTipoMovimento.AutoSize = true;
this.lblTipoMovimento.Location = new System.Drawing.Point(15, 21);
this.lblTipoMovimento.Name = "lblTipoMovimento";
this.lblTipoMovimento.Size = new System.Drawing.Size(98, 13);
this.lblTipoMovimento.TabIndex = 12;
this.lblTipoMovimento.Text = "Tipo de Movimento";
//
// btnSalvarSentido
//
this.btnSalvarSentido.Location = new System.Drawing.Point(276, 339);
@ -529,24 +552,24 @@ namespace AgroBase.Forms.Direcional
this.lblETDireita.TabIndex = 2;
this.lblETDireita.Text = "Direita";
//
// cmbTipoMovimento
// lblIP
//
this.cmbTipoMovimento.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbTipoMovimento.FormattingEnabled = true;
this.cmbTipoMovimento.Location = new System.Drawing.Point(195, 18);
this.cmbTipoMovimento.Name = "cmbTipoMovimento";
this.cmbTipoMovimento.Size = new System.Drawing.Size(168, 21);
this.cmbTipoMovimento.TabIndex = 13;
this.cmbTipoMovimento.SelectedIndexChanged += new System.EventHandler(this.cmbTipoMovimento_SelectedIndexChanged);
this.lblIP.AutoSize = true;
this.lblIP.Location = new System.Drawing.Point(10, 326);
this.lblIP.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblIP.Name = "lblIP";
this.lblIP.Size = new System.Drawing.Size(17, 13);
this.lblIP.TabIndex = 143;
this.lblIP.Text = "IP";
//
// lblTipoMovimento
// txtIP
//
this.lblTipoMovimento.AutoSize = true;
this.lblTipoMovimento.Location = new System.Drawing.Point(15, 21);
this.lblTipoMovimento.Name = "lblTipoMovimento";
this.lblTipoMovimento.Size = new System.Drawing.Size(98, 13);
this.lblTipoMovimento.TabIndex = 12;
this.lblTipoMovimento.Text = "Tipo de Movimento";
this.txtIP.Location = new System.Drawing.Point(13, 343);
this.txtIP.Margin = new System.Windows.Forms.Padding(2);
this.txtIP.Name = "txtIP";
this.txtIP.Size = new System.Drawing.Size(85, 20);
this.txtIP.TabIndex = 142;
this.txtIP.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// frmDirConfig
//
@ -620,5 +643,7 @@ namespace AgroBase.Forms.Direcional
private System.Windows.Forms.TextBox txtETEndereco;
private System.Windows.Forms.ComboBox cmbTipoMovimento;
private System.Windows.Forms.Label lblTipoMovimento;
private System.Windows.Forms.Label lblIP;
private System.Windows.Forms.TextBox txtIP;
}
}

View File

@ -77,6 +77,8 @@ namespace AgroBase.Forms.Direcional
nudOffset.Value = Convert.ToInt32(Modulo.DirMotor.Angulo_Offset);
}
}
txtIP.Text = Disp.Dados.IP_Mks;
}
private void frmDirConfig_FormClosing(object sender, FormClosingEventArgs e)
@ -119,6 +121,8 @@ namespace AgroBase.Forms.Direcional
}
}
Disp.Dados.IP_Mks = txtIP.Text;
Disp.SalvarParametros(Disp.Dados);
}

View File

@ -74,6 +74,8 @@ namespace AgroBase.Forms.Movimentacao
this.nudNumPolos = new System.Windows.Forms.NumericUpDown();
this.lblRampa = new System.Windows.Forms.Label();
this.nudRampa = new System.Windows.Forms.NumericUpDown();
this.txtIP = new System.Windows.Forms.TextBox();
this.lblIP = new System.Windows.Forms.Label();
this.gpbSentido.SuspendLayout();
this.gpbDF.SuspendLayout();
this.gpbEF.SuspendLayout();
@ -421,6 +423,8 @@ namespace AgroBase.Forms.Movimentacao
//
// groupBox1
//
this.groupBox1.Controls.Add(this.lblIP);
this.groupBox1.Controls.Add(this.txtIP);
this.groupBox1.Controls.Add(this.txtOffsetLeitura);
this.groupBox1.Controls.Add(this.lblOffsetLeitura);
this.groupBox1.Controls.Add(this.lblReducao);
@ -614,6 +618,25 @@ namespace AgroBase.Forms.Movimentacao
this.nudRampa.TabIndex = 31;
this.nudRampa.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// txtIP
//
this.txtIP.Location = new System.Drawing.Point(283, 37);
this.txtIP.Margin = new System.Windows.Forms.Padding(2);
this.txtIP.Name = "txtIP";
this.txtIP.Size = new System.Drawing.Size(85, 20);
this.txtIP.TabIndex = 12;
this.txtIP.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// lblIP
//
this.lblIP.AutoSize = true;
this.lblIP.Location = new System.Drawing.Point(280, 20);
this.lblIP.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblIP.Name = "lblIP";
this.lblIP.Size = new System.Drawing.Size(17, 13);
this.lblIP.TabIndex = 141;
this.lblIP.Text = "IP";
//
// frmMovConfig
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
@ -696,5 +719,7 @@ namespace AgroBase.Forms.Movimentacao
private System.Windows.Forms.Label lblTipoMovimento;
private System.Windows.Forms.TextBox txtOffsetLeitura;
private System.Windows.Forms.Label lblOffsetLeitura;
private System.Windows.Forms.Label lblIP;
private System.Windows.Forms.TextBox txtIP;
}
}

View File

@ -19,8 +19,6 @@ namespace AgroBase.Forms.Movimentacao
private void frmMovConfig_Load(object sender, EventArgs e)
{
nudDiametroRoda.Value = Convert.ToInt32(VariaveisEquipamento.DiametroRoda * 1000.0);
if (Disp == null)
{
return;
@ -67,14 +65,17 @@ namespace AgroBase.Forms.Movimentacao
nudNumPolos.Value = Modulo.MovMotor.NumeroPolos;
nudRampa.Value = Modulo.MovMotor.Rampa;
nudRPMMax.Value = Modulo.MovMotor.RPM_Max;
nudReducao.Value = Modulo.MovMotor.Reducao;
txtOffsetLeitura.Text = Modulo.MovMotor.OffsetLeitura.ToString();
TextBox txtEndereco = FuncoesGlobais.FindControlRecursive<TextBox>(gpbSentido, "txt" + Modulo.Modulo_ID + "Endereco");
txtEndereco.Text = Modulo.MovMotor.Endereco;
}
}
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;
}
private void frmMovConfig_FormClosing(object sender, FormClosingEventArgs e)
@ -111,16 +112,18 @@ namespace AgroBase.Forms.Movimentacao
Modulo.MovMotor.NumeroPolos = Convert.ToInt32(nudNumPolos.Value);
Modulo.MovMotor.Rampa = Convert.ToInt32(nudRampa.Value);
Modulo.MovMotor.RPM_Max = Convert.ToInt32(nudRPMMax.Value);
Modulo.MovMotor.Reducao = Convert.ToInt32(nudReducao.Value);
Modulo.MovMotor.OffsetLeitura = Convert.ToDouble(txtOffsetLeitura.Text);
Modulo.MovMotor.DiametroRoda = Convert.ToDouble(nudDiametroRoda.Value / 1000);
TextBox txtEndereco = FuncoesGlobais.FindControlRecursive<TextBox>(gpbSentido, "txt" + Modulo.Modulo_ID + "Endereco");
Modulo.MovMotor.Endereco = txtEndereco.Text;
}
}
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.SalvarParametros(Disp.Dados);
}

View File

@ -28,7 +28,7 @@ namespace AgroBase.Forms
btnAtualizar_Click(sender, e);
//LoopAtualizacao().ConfigureAwait(false);
this.Text += " - " + BLD300RService._PortaBLD.PortName;
this.Text += " - "; // + BLD300RService._PortaBLD.PortName;
}
private async Task LoopAtualizacao()

View File

@ -0,0 +1,172 @@
namespace AgroBase.Forms
{
partial class frmEthernet
{
/// <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.lblGateway = new System.Windows.Forms.Label();
this.lblIpAtual = new System.Windows.Forms.Label();
this.txtGateway = new System.Windows.Forms.TextBox();
this.txtIpAtual = new System.Windows.Forms.TextBox();
this.btnDefinirIp = new System.Windows.Forms.Button();
this.chbIpFixo = new System.Windows.Forms.CheckBox();
this.cmbInterface = new System.Windows.Forms.ComboBox();
this.lblInterface = new System.Windows.Forms.Label();
this.txtSubmask = new System.Windows.Forms.TextBox();
this.lblSubmask = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// lblGateway
//
this.lblGateway.AutoSize = true;
this.lblGateway.Location = new System.Drawing.Point(12, 49);
this.lblGateway.Name = "lblGateway";
this.lblGateway.Size = new System.Drawing.Size(49, 13);
this.lblGateway.TabIndex = 0;
this.lblGateway.Text = "Gateway";
//
// lblIpAtual
//
this.lblIpAtual.AutoSize = true;
this.lblIpAtual.Location = new System.Drawing.Point(12, 127);
this.lblIpAtual.Name = "lblIpAtual";
this.lblIpAtual.Size = new System.Drawing.Size(44, 13);
this.lblIpAtual.TabIndex = 1;
this.lblIpAtual.Text = "IP Atual";
//
// txtGateway
//
this.txtGateway.Enabled = false;
this.txtGateway.Location = new System.Drawing.Point(15, 65);
this.txtGateway.Name = "txtGateway";
this.txtGateway.Size = new System.Drawing.Size(141, 20);
this.txtGateway.TabIndex = 2;
this.txtGateway.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// txtIpAtual
//
this.txtIpAtual.Enabled = false;
this.txtIpAtual.Location = new System.Drawing.Point(15, 143);
this.txtIpAtual.Name = "txtIpAtual";
this.txtIpAtual.Size = new System.Drawing.Size(141, 20);
this.txtIpAtual.TabIndex = 4;
this.txtIpAtual.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// btnDefinirIp
//
this.btnDefinirIp.Location = new System.Drawing.Point(15, 197);
this.btnDefinirIp.Name = "btnDefinirIp";
this.btnDefinirIp.Size = new System.Drawing.Size(141, 23);
this.btnDefinirIp.TabIndex = 6;
this.btnDefinirIp.Text = "Definir IP";
this.btnDefinirIp.UseVisualStyleBackColor = true;
this.btnDefinirIp.Click += new System.EventHandler(this.btnDefinirIp_Click);
//
// chbIpFixo
//
this.chbIpFixo.AutoSize = true;
this.chbIpFixo.Location = new System.Drawing.Point(15, 170);
this.chbIpFixo.Name = "chbIpFixo";
this.chbIpFixo.Size = new System.Drawing.Size(58, 17);
this.chbIpFixo.TabIndex = 5;
this.chbIpFixo.Text = "IP Fixo";
this.chbIpFixo.UseVisualStyleBackColor = true;
this.chbIpFixo.CheckedChanged += new System.EventHandler(this.chbIpFixo_CheckedChanged);
//
// cmbInterface
//
this.cmbInterface.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbInterface.FormattingEnabled = true;
this.cmbInterface.Location = new System.Drawing.Point(15, 25);
this.cmbInterface.Name = "cmbInterface";
this.cmbInterface.Size = new System.Drawing.Size(141, 21);
this.cmbInterface.TabIndex = 1;
//
// lblInterface
//
this.lblInterface.AutoSize = true;
this.lblInterface.Location = new System.Drawing.Point(12, 9);
this.lblInterface.Name = "lblInterface";
this.lblInterface.Size = new System.Drawing.Size(49, 13);
this.lblInterface.TabIndex = 7;
this.lblInterface.Text = "Interface";
//
// txtSubmask
//
this.txtSubmask.Enabled = false;
this.txtSubmask.Location = new System.Drawing.Point(15, 104);
this.txtSubmask.Name = "txtSubmask";
this.txtSubmask.Size = new System.Drawing.Size(141, 20);
this.txtSubmask.TabIndex = 3;
this.txtSubmask.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// lblSubmask
//
this.lblSubmask.AutoSize = true;
this.lblSubmask.Location = new System.Drawing.Point(12, 88);
this.lblSubmask.Name = "lblSubmask";
this.lblSubmask.Size = new System.Drawing.Size(70, 13);
this.lblSubmask.TabIndex = 8;
this.lblSubmask.Text = "Subnet Mask";
//
// frmEthernet
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(267, 232);
this.Controls.Add(this.txtSubmask);
this.Controls.Add(this.lblSubmask);
this.Controls.Add(this.lblInterface);
this.Controls.Add(this.cmbInterface);
this.Controls.Add(this.chbIpFixo);
this.Controls.Add(this.btnDefinirIp);
this.Controls.Add(this.txtIpAtual);
this.Controls.Add(this.txtGateway);
this.Controls.Add(this.lblIpAtual);
this.Controls.Add(this.lblGateway);
this.Name = "frmEthernet";
this.Text = "Configurações de Rede";
this.Load += new System.EventHandler(this.frmEthernet_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label lblGateway;
private System.Windows.Forms.Label lblIpAtual;
private System.Windows.Forms.TextBox txtGateway;
private System.Windows.Forms.TextBox txtIpAtual;
private System.Windows.Forms.Button btnDefinirIp;
private System.Windows.Forms.CheckBox chbIpFixo;
private System.Windows.Forms.ComboBox cmbInterface;
private System.Windows.Forms.Label lblInterface;
private System.Windows.Forms.TextBox txtSubmask;
private System.Windows.Forms.Label lblSubmask;
}
}

View File

@ -0,0 +1,59 @@
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 frmEthernet : Form
{
public frmEthernet()
{
InitializeComponent();
}
private void frmEthernet_Load(object sender, EventArgs e)
{
var interfaces = EthernetService.ObterNomesInterfaces();
cmbInterface.Items.AddRange(interfaces.ToArray());
if (interfaces.Any(x => x.Contains("Ativa")))
cmbInterface.SelectedIndex = interfaces.IndexOf(interfaces.First(x => x.Contains("Ativa")));
txtGateway.Text = EthernetService.ObterIpGateway();
txtIpAtual.Text = EthernetService.ObterIpAtual();
txtSubmask.Text = EthernetService.ObterSubnetMaskAtual();
chbIpFixo.Checked = EthernetService.ObterTipoConfiguracaoIP().Contains("Fixo");
}
private void btnDefinirIp_Click(object sender, EventArgs e)
{
string ipNovo = txtIpAtual.Text;
string gateway = txtGateway.Text;
string subnetMask = txtSubmask.Text;
// Aqui substituímos "Ethernet" pelo nome correto da interface que o PC está usando
if (chbIpFixo.Checked)
{
EthernetService.DefinirIpFixo(cmbInterface.Text, ipNovo, subnetMask, gateway);
}
else
{
EthernetService.DefinirIpDinamico(cmbInterface.Text);
}
MessageBox.Show("Configuração de IP atualizada.");
}
private void chbIpFixo_CheckedChanged(object sender, EventArgs e)
{
txtGateway.Enabled = chbIpFixo.Checked;
txtIpAtual.Enabled = chbIpFixo.Checked;
txtSubmask.Enabled = chbIpFixo.Checked;
}
}
}

View File

@ -0,0 +1,120 @@
<?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>
</root>

View File

@ -96,6 +96,7 @@ namespace AgroBase
this.lblProgressoAtualizacao = new System.Windows.Forms.Label();
this.pgbAtualizacaoArquivos = new System.Windows.Forms.ProgressBar();
this.btnForcarAtualizacao = new System.Windows.Forms.Button();
this.btnEthernet = new System.Windows.Forms.Button();
this.gpbAcoes.SuspendLayout();
this.erroStrip.SuspendLayout();
this.pnlLateral.SuspendLayout();
@ -610,6 +611,7 @@ namespace AgroBase
// pnlAtalhos
//
this.pnlAtalhos.AutoScroll = true;
this.pnlAtalhos.Controls.Add(this.btnEthernet);
this.pnlAtalhos.Controls.Add(this.btnMKS);
this.pnlAtalhos.Controls.Add(this.btnBLD300R);
this.pnlAtalhos.Controls.Add(this.btnWT901C);
@ -865,6 +867,17 @@ namespace AgroBase
this.btnForcarAtualizacao.UseVisualStyleBackColor = true;
this.btnForcarAtualizacao.Click += new System.EventHandler(this.btnForcarAtualizacao_Click);
//
// btnEthernet
//
this.btnEthernet.Location = new System.Drawing.Point(5, 391);
this.btnEthernet.Margin = new System.Windows.Forms.Padding(2);
this.btnEthernet.Name = "btnEthernet";
this.btnEthernet.Size = new System.Drawing.Size(84, 20);
this.btnEthernet.TabIndex = 30;
this.btnEthernet.Text = "Ethernet";
this.btnEthernet.UseVisualStyleBackColor = true;
this.btnEthernet.Click += new System.EventHandler(this.btnEthernet_Click);
//
// frmPrincipal
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
@ -984,6 +997,7 @@ namespace AgroBase
public System.Windows.Forms.Label lblProgressoAtualizacao;
private System.Windows.Forms.ProgressBar pgbAtualizacaoArquivos;
private System.Windows.Forms.Button btnForcarAtualizacao;
private System.Windows.Forms.Button btnEthernet;
}
}

View File

@ -454,10 +454,17 @@ namespace AgroBase
frm.Show();
}
private void btnEthernet_Click(object sender, EventArgs e)
{
frmEthernet frm = new frmEthernet();
frm.Show();
}
#endregion
}
}

View File

@ -10,7 +10,6 @@ namespace AgroBase.Models.Modules
{
public class MovimentacaoUnificadaModel : DispositivoBaseModel
{
private bool _conectado = false;
public bool Conectado
{
get
@ -19,19 +18,28 @@ namespace AgroBase.Models.Modules
}
set
{
_conectado = value;
}
}
public static int _TaxaAmostragem { get; set; } = 1000;
public List<ModuloMvdModel> Modulos { get; set; } = new List<ModuloMvdModel>();
public static Direcao UltimaDirecao { get; set; } = Direcao.Parado;
public double DistanciaPercorridaOperacao { get; set; } = 0;
public int TempoEmAtividade { get; set; } = 0;
public double DistanciaPercorridaTotal { get; set; } = 0;
public double DistanciaPercorridaParcial { get; set; } = 0;
public double DiametroRoda { get; set; } = 0.3556;
public double ReducaoMotorBLDC { get; set; } = 5;
public double RPM_Max_MotorBLDC { get; set; } = 500;
public string IP_Bld { get; set; } = "192.168.100.110";
public string IP_Mks { get; set; } = "192.168.100.111";
public List<ModuloMvdModel> Modulos { get; set; } = new List<ModuloMvdModel>();
public static Direcao UltimaDirecao { get; set; } = Direcao.Parado;
public (bool, List<string>) StatusModulosBLD(Direcao Lado)
{
string Prefixo = Lado == Direcao.Esquerda ? "E" : Lado == Direcao.Direita ? "D" : "";
@ -659,15 +667,12 @@ namespace AgroBase.Models.Modules
{
get
{
return RPM_SP / Reducao;
return RPM_SP / Convert.ToInt32(Variaveis.OperacaoEmAndamento.DispMvd.Dados.ReducaoMotorBLDC);
}
}
public Sentido Sentido_SP { get; set; } = Sentido.Parado;
public int NumeroPolos { get; set; } = 10;
public int Rampa { get; set; } = 0;
public int RPM_Max { get; set; } = 500;
public int Reducao { get; set; } = 5;
public double DiametroRoda { get; set; } = 0.3556;
public double OffsetLeitura { get; set; } = 1.0;
@ -825,7 +830,7 @@ namespace AgroBase.Models.Modules
Endereco + SerialService.SplitParams +
NumeroPolos + SerialService.SplitParams +
Rampa + SerialService.SplitParams +
RPM_Max + SerialService.SplitParams +
Variaveis.OperacaoEmAndamento.DispMvd.Dados.RPM_Max_MotorBLDC + SerialService.SplitParams +
PinoutModel.PinoProtocolo(_pinout, Funcoes);
return Protocolo;

View File

@ -60,6 +60,7 @@ namespace AgroBase.Models
{
public static int CameraSolo { get; } = 6522;
public static int CameraCaminho { get; } = 6544;
public static int Ethernet { get; } = 502;
}
public static class VariaveisEquipamento
@ -83,7 +84,7 @@ namespace AgroBase.Models
{
double RpmMax =
Variaveis.OperacaoEmAndamento.DispMvd != null ?
Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.Average(x => x.MovMotor.RPM_Max) / RelacaoRPM :
Variaveis.OperacaoEmAndamento.DispMvd.Dados.RPM_Max_MotorBLDC / RelacaoRPM :
100;
return (int)RpmMax;
}
@ -94,7 +95,7 @@ namespace AgroBase.Models
{
double RelacaoRPM =
Variaveis.OperacaoEmAndamento.DispMvd != null ?
Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.Average(x => x.MovMotor.Reducao) :
Variaveis.OperacaoEmAndamento.DispMvd.Dados.ReducaoMotorBLDC :
1;
return RelacaoRPM;
}
@ -105,7 +106,7 @@ namespace AgroBase.Models
{
double diametro =
Variaveis.OperacaoEmAndamento.DispMvd != null ?
Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.Average(x => x.MovMotor.DiametroRoda) :
Variaveis.OperacaoEmAndamento.DispMvd.Dados.DiametroRoda :
0.3556;
return diametro;
}

View File

@ -1,7 +1,6 @@
using AgroBase.Models;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Threading.Tasks;
using static AgroBase.Models.Enums;
@ -11,41 +10,15 @@ namespace AgroBase.Services
{
public class BLD300RService
{
private static EthernetService _ethernetService;
public static bool Iniciado
{
get
{
if (!SerialService.DispositivosMapeados.Any(x => x.Dispositivo == T_Code.Bld) && DadosLeitura.All(x => !x.Iniciado))
{
return false;
}
if (_PortaBLD != null && !_PortaBLD.IsOpen)
{
if (!SerialPort.GetPortNames().Any(x => x == _PortaBLD.PortName))
{
_PortaBLD = null;
foreach (var d in SerialService.DispositivosMapeados.Where(x => x.Dispositivo == T_Code.Bld))
{
SerialService.DispositivosMapeados.Remove(d);
}
return false;
}
try
{
_PortaBLD.Open();
}
catch (Exception ex)
{
RegisrarErrosComunicacao(0, $"Erro ao abrir porta {_PortaBLD.PortName}. Erro={ex.Message}");
//_PortaBLD = null;
AtualizarPortaCOM(new SerialPort() { PortName = _PortaBLD.PortName, BaudRate = _PortaBLD.BaudRate });
}
}
return _PortaBLD != null && _PortaBLD.IsOpen && DadosLeitura.Any(x => x.Iniciado);
return _ethernetService != null && _ethernetService.IsConnected && SerialService.DispositivosMapeados.Any(x => x.Dispositivo == T_Code.Bld) && DadosLeitura.Any(x => x.Iniciado);
}
}
public static int TaxaAmostragem { get; set; } = 1000;
public static SerialPort _PortaBLD = new SerialPort();
public static List<BLD300RModel> DadosLeitura = new List<BLD300RModel>();
@ -213,19 +186,56 @@ namespace AgroBase.Services
private static System.Timers.Timer tmrReceberDados = new System.Timers.Timer() { Interval = TaxaAmostragem, Enabled = false };
private static bool EnvioLiberado { get; set; } = true;
public static void IniciarRotinas()
{
//Task.Run(() => LoopEnvioComandos()); // Inicia o loop de comandos em segundo plano
//Task.Run(() => ReceberDados()); // Inicia a recepção de dados em segundo plano
if (!tmrReceberDados.Enabled)
{
tmrReceberDados.Elapsed += TmrReceberDados_Elapsed; ;
tmrReceberDados.Start();
}
if (!tmrLoopComandos.Enabled)
{
tmrLoopComandos.Elapsed += TmrLoopComandos_Elapsed;
tmrLoopComandos.Start();
}
}
public static async Task<bool> VerificaPortaBLD(SerialPort porta)
// Inicializa o serviço Ethernet com IP e porta específicos
public static async Task<bool> InicializarEthernetService(string ipAddress, int port)
{
_ethernetService = new EthernetService(ipAddress, port);
return await _ethernetService.ConnectAsync();
}
public static async Task<bool> VerificaPortaBLD()
{
EnvioLiberado = false;
if (!Iniciado)
if (_ethernetService == null)
{
porta.Close();
porta.BaudRate = 9600;
AtualizarPortaCOM(porta);
bool connect = await InicializarEthernetService(Variaveis.OperacaoEmAndamento.DispMvd.Dados.IP_Bld, VariaveisPortas.Ethernet);
if (!connect)
{
Console.WriteLine("Falha ao inicializar o serviço Ethernet.");
EnvioLiberado = true;
return false;
}
}
if (_ethernetService._isReconnecting)
{
return false;
}
if (!Iniciado && !await _ethernetService.CheckConnectionAsync())
{
Console.WriteLine("Falha ao conectar ao dispositivo via Ethernet.");
EnvioLiberado = true;
return false;
}
var Parametro = Parametros.First(x => x.Chave == "Versao");
List<string> Mod_IDs = new List<string>();
@ -249,11 +259,13 @@ namespace AgroBase.Services
var comando = ModbusService.ComandoGetParametro(Addr, Parametro);
if (!EnviarComando(_PortaBLD, comando))
if (!await EnviarComando(_ethernetService, comando))
{
break;
}
var resposta = await SerialService.LerDadosDaPortaSerialAsync(_PortaBLD, 7, 1000);
// Recebe a resposta via Ethernet
var resposta = await _ethernetService.ReceiveDataAsync(7);
DecifrarResposta(resposta, Parametro, Addr);
if (DadosLeitura.Any(x => x.Endereco == Addr && x.Iniciado))
@ -267,44 +279,64 @@ namespace AgroBase.Services
DefinirDispositivo(Mod_IDs);
}
if (!Iniciado)
{
_PortaBLD.Close();
_PortaBLD = null;
}
EnvioLiberado = true;
return Iniciado;
}
public static void AtualizarPortaCOM(SerialPort Porta)
private static async Task<bool> EnviarComando(EthernetService ethernetService, byte[] comando)
{
_PortaBLD = new SerialPort();
_PortaBLD.PortName = Porta.PortName;
_PortaBLD.BaudRate = Porta.BaudRate;
_PortaBLD.Open();
}
private static void ReconectarPortaCOM()
{
RegisrarErrosComunicacao(0, $"Reiniciando conexão com a porta {_PortaBLD.PortName}...");
try
{
_PortaBLD.Close();
return await ethernetService.SendDataAsync(comando);
}
catch (Exception ex)
catch (Exception ex)
{
RegisrarErrosComunicacao(0, $"Erro ao reiniciar conexão. Erro={ex.Message}");
Console.WriteLine($"Erro ao enviar comando: {ex.Message}");
return false;
}
}
if (Iniciado)
public static async Task EnviarComandoControle(BLDComandoModel Comando)
{
try
{
RegisrarErrosComunicacao(0, $"Reconexão com a porta {_PortaBLD.PortName} reestabelecida");
byte[] comando = Comando.Get
? ModbusService.ComandoGetParametro(Comando.Endereco, Comando.Parametro)
: ModbusService.ComandoSetParametro(Comando.Endereco, Comando.Parametro, Comando.Valor);
if (comando != null && comando.Length > 0)
{
// Envia o comando via Ethernet
Comando.ErroEnvio = !await EnviarComando(_ethernetService, comando);
Comando.Enviado = true;
// Recebe a resposta via Ethernet, independentemente de precisar processá-la ou não
byte[] resposta = await _ethernetService.ReceiveDataAsync(7, 1000); // Timeout ajustável, aqui 1 segundo
if (Comando.AguardaResposta)
{
// Processa a resposta, pois é esperada
bool Respondido = DecifrarResposta(resposta, Comando.Parametro, Comando.Endereco);
if (!Respondido)
{
RegisrarErrosComunicacao(Comando.Endereco, $"Timeout ou erro ao receber resposta. GET={Comando.Get}, Parametro={Comando.Parametro.Chave}, Valor={Comando.Valor}");
Comando.Enviado = false;
Comando.Momento = DateTime.Now.AddMilliseconds(500); // Retenta após um pequeno intervalo
}
}
else
{
// Descarte da resposta, pois não era esperada
Console.WriteLine($"Resposta descartada para comando que não aguardava resposta.");
}
}
}
else
catch (Exception ex)
{
RegisrarErrosComunicacao(0, $"Erro ao reestabelecer conexão com a porta {_PortaBLD.PortName}");
// Log de erro
RegisrarErrosComunicacao(Comando.Endereco, $"Erro ao enviar comando: {ex.Message}");
Comando.Enviado = false;
Comando.Momento = DateTime.Now.AddMilliseconds(500);
}
}
@ -327,7 +359,7 @@ namespace AgroBase.Services
var leitura = DadosLeitura.FirstOrDefault(x => x.Endereco == Addr);
SerialService.DispositivosMapeados.Add(new SerialService.DispositivoDetalhesModel()
{
PortaCOM = _PortaBLD.PortName,
PortaCOM = _ethernetService != null ? _ethernetService._ipAddress : "N/A",
Dispositivo = T_Code.Bld,
Erro = leitura.CodigoAlarme > 0,
Versao = leitura.Versao.ToString(),
@ -338,22 +370,94 @@ namespace AgroBase.Services
}
}
public static void IniciarRotinas()
private static bool DecifrarResposta(byte[] resposta, ModbusParametrosModel Parametro, byte Addr)
{
//Task.Run(() => LoopEnvioComandos()); // Inicia o loop de comandos em segundo plano
//Task.Run(() => ReceberDados()); // Inicia a recepção de dados em segundo plano
if (!tmrReceberDados.Enabled)
try
{
tmrReceberDados.Elapsed += TmrReceberDados_Elapsed; ;
tmrReceberDados.Start();
if (resposta == null || resposta.Length == 0)
{
return false;
}
var Leitura = DadosLeitura.FirstOrDefault(x => x.Endereco == Addr);
if (Leitura == null)
{
Leitura = new BLD300RModel()
{
Endereco = Addr,
UltimoComandoRecebido = DateTime.MinValue,
parametros = new List<BLDParametrosRequisitar>()
{
new BLDParametrosRequisitar()
{
Registro = Parametro.Registro,
Escala = Parametro.Escala,
Valor = null
}
}
};
DadosLeitura.Add(Leitura);
}
if (resposta.Length > 3)
{
if (Parametros.Any(x => 0x03 == resposta[1]))
{
int num_registros = resposta[2];
byte[] bytes_resposta = resposta.Skip(3).Take(num_registros).ToArray();
Parametro.Valor = bytes_resposta;
Leitura.UltimoComandoRecebido = DateTime.Now;
return true;
}
else if (Parametros.Any(x => 0x06 == resposta[1]))
{
Parametro.Valor = resposta.Skip(4).Take(2).ToArray();
Leitura.UltimoComandoRecebido = DateTime.Now;
return true;
}
}
RegisrarErrosComunicacao(Addr, $"Resposta inválida. {BitConverter.ToString(resposta)}");
return false;
}
if (!tmrLoopComandos.Enabled)
catch (Exception ex)
{
tmrLoopComandos.Elapsed += TmrLoopComandos_Elapsed;
tmrLoopComandos.Start();
RegisrarErrosComunicacao(Addr, $"Erro ao decifrar resposta. {BitConverter.ToString(resposta)}");
return false;
}
}
private static void RegisrarErrosComunicacao(byte addr, string mensagem)
{
try
{
var Caminho = Variaveis.CaminhoLogsDispositivos;
if (!Directory.Exists(Caminho))
{
Directory.CreateDirectory(Caminho);
}
var Arquivo = T_Code.Bld.ToString() + "_err.txt";
Caminho += "/" + Arquivo;
mensagem = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss:fff") + " - Endereço " + addr + " (" + _ethernetService._ipAddress + "): " + mensagem + Environment.NewLine;
if (!File.Exists(Caminho))
{
File.WriteAllText(Caminho, mensagem);
}
else
{
File.AppendAllText(Caminho, mensagem);
}
}
catch
{
Console.WriteLine("Erro ao salvar log de erro BLD");
}
}
private static async void TmrLoopComandos_Elapsed(object sender, EventArgs e)
{
((System.Timers.Timer)sender).Stop();
@ -366,32 +470,6 @@ namespace AgroBase.Services
((System.Timers.Timer)sender).Start();
}
private static bool EnviarComando(SerialPort _Porta, byte[] Comando)
{
lock (FilaLock)
{
try
{
if (_Porta != null)
{
if (!_Porta.IsOpen)
{
_Porta.Open();
}
if (_Porta.IsOpen)
{
return SerialService.EnviarDadosPortaSerial(_Porta, Comando, 0, Comando.Length);
}
}
}
catch (Exception ex)
{
throw ex;
}
return false;
}
}
private static void TmrReceberDados_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
((System.Timers.Timer)sender).Stop();
@ -411,8 +489,6 @@ namespace AgroBase.Services
TaxaAmostragem = 3000;
ReconectarPortaCOM();
((System.Timers.Timer)sender).Start();
return;
}
@ -470,83 +546,6 @@ namespace AgroBase.Services
((System.Timers.Timer)sender).Start();
}
private static bool DecifrarResposta(byte[] resposta, ModbusParametrosModel Parametro, byte Addr)
{
try
{
var Leitura = DadosLeitura.FirstOrDefault(x => x.Endereco == Addr);
if (Leitura == null)
{
Leitura = new BLD300RModel()
{
Endereco = Addr,
UltimoComandoRecebido = DateTime.MinValue,
parametros = new List<BLDParametrosRequisitar>()
{
new BLDParametrosRequisitar()
{
Registro = Parametro.Registro,
Escala = Parametro.Escala,
Valor = null
}
}
};
DadosLeitura.Add(Leitura);
}
var ParametroLeitura = Leitura.parametros.FirstOrDefault(x => x.Registro == Parametro.Registro);
if (ParametroLeitura == null)
{
ParametroLeitura = new BLDParametrosRequisitar()
{
Registro = Parametro.Registro,
Escala = Parametro.Escala,
Valor = null
};
Leitura.parametros.Add(ParametroLeitura);
}
if (resposta.Length > 3)
{
if (Parametros.Any(x => 0x03 == resposta[1]))
{
int num_registros = resposta[2];
byte[] bytes_resposta = resposta.Skip(3).Take(num_registros).ToArray(); // Ajustando para pegar 2 bytes por registro
Parametro.Valor = bytes_resposta;
Parametro.UltimaRequisicao = DateTime.MaxValue;
ParametroLeitura.Valor = Parametro.Valor;
Leitura.UltimoComandoRecebido = DateTime.Now;
return true;
}
else if (Parametros.Any(x => 0x06 == resposta[1]))
{
Parametro.Valor = resposta.Skip(4).Take(2).ToArray();
ParametroLeitura.Valor = Parametro.Valor;
Leitura.UltimoComandoRecebido = DateTime.Now;
return true;
}
else
{
RegisrarErrosComunicacao(Addr, $"Resposta inválida ou código de função incorreto. {BitConverter.ToString(resposta)}");
}
return false;
}
RegisrarErrosComunicacao(Addr, $"Resposta inválida. {BitConverter.ToString(resposta)}");
return false;
}
catch (Exception ex)
{
RegisrarErrosComunicacao(Addr, $"Erro ao decifrar resposta. {BitConverter.ToString(resposta)}");
return false;
}
}
private static void ConfigurarDriver(byte Addr)
{
@ -585,7 +584,7 @@ namespace AgroBase.Services
TimeoutResposta = 200,
Get = false,
Parametro = Parametros.First(x => x.Chave == "RPM_Max"),
Valor = Modulo.MovMotor.RPM_Max
Valor = (int)Variaveis.OperacaoEmAndamento.DispMvd.Dados.RPM_Max_MotorBLDC
});
AdicionarComandoNaFila(new BLDComandoModel()
{
@ -608,51 +607,6 @@ namespace AgroBase.Services
DadosLeitura.Where(x => x.Endereco == Addr).First().Configurado = true;
}
public static async Task EnviarComandoControle(BLDComandoModel Comando)
{
try
{
byte[] comando = null;
if (Comando.Get)
{
comando = ModbusService.ComandoGetParametro(Comando.Endereco, Comando.Parametro);
}
else
{
comando = ModbusService.ComandoSetParametro(Comando.Endereco, Comando.Parametro, Comando.Valor);
}
if (comando != null && comando.Length > 0)
{
//Console.WriteLine("Enviando comando para o endereço: " + Comando.Endereco);
Comando.ErroEnvio = !EnviarComando(_PortaBLD, comando);
Comando.Enviado = true;
if (Comando.AguardaResposta && !Comando.ErroEnvio)
{
byte[] resposta = await SerialService.LerDadosDaPortaSerialAsync(_PortaBLD, 7, Comando.TimeoutResposta);
bool Respondido = DecifrarResposta(resposta, Comando.Parametro, Comando.Endereco);
if (!Respondido)
{
RegisrarErrosComunicacao(Comando.Endereco, $"Timeout ao receber resposta. GET={Comando.Get}, Parametro={Comando.Parametro.Chave}, Valor={Comando.Valor}");
Comando.Enviado = false;
Comando.Momento = DateTime.Now.AddMilliseconds(500);
//ReconectarPortaCOM();
}
}
}
}
catch (IOException ex)
{
RegisrarErrosComunicacao(Comando.Endereco, $"Erro ao enviar comando. GET={Comando.Get}, Parametro={Comando.Parametro.Chave}, Valor={Comando.Valor}, Erro={ex.Message}");
Comando.Enviado = false;
Comando.Momento = DateTime.Now.AddMilliseconds(500);
ReconectarPortaCOM();
}
}
public static void AdicionarComandoNaFila(BLDComandoModel Comando)
{
lock (FilaLock)
@ -668,6 +622,16 @@ namespace AgroBase.Services
{
EnvioLiberado = false;
// Verifica se a conexão foi perdida e tenta reconectar
if (_ethernetService != null && !_ethernetService.IsConnected)
{
if (!await _ethernetService.ReconnectAsync())
{
EnvioLiberado = true;
return;
}
}
try
{
await ProcessarFilaPrioridade();
@ -717,41 +681,6 @@ namespace AgroBase.Services
}
}
private static void RegisrarErrosComunicacao(byte addr, string mensagem)
{
if (_PortaBLD == null)
{
return;
}
try
{
var Caminho = Variaveis.CaminhoLogsDispositivos;
if (!Directory.Exists(Caminho))
{
Directory.CreateDirectory(Caminho);
}
var Arquivo = T_Code.Bld.ToString() + "_err.txt";
Caminho += "/" + Arquivo;
mensagem = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss:fff") + " - Porta " + _PortaBLD.PortName + " - " + addr + ": " + mensagem + Environment.NewLine;
if (!File.Exists(Caminho))
{
File.WriteAllText(Caminho, mensagem);
}
else
{
File.AppendAllText(Caminho, mensagem);
}
}
catch
{
Console.WriteLine("Erro ao salvar log de erro BLD");
}
}
public class BLDParametrosRequisitar
{
public byte Registro { get; set; }

View File

@ -0,0 +1,369 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
public class EthernetService
{
public readonly string _ipAddress;
private readonly int _port;
private TcpClient _client;
private NetworkStream _networkStream;
public bool IsConnected
{
get
{
try
{
// Verifica se o cliente foi inicializado e está conectado
return _client != null && _client.Client != null && _client.Client.Connected;
}
catch
{
return false;
}
}
}
public EthernetService(string ipAddress, int port)
{
_ipAddress = ipAddress;
_port = port;
}
// Método para estabelecer conexão TCP com o conversor Ethernet-RS485
public async Task<bool> ConnectAsync(int timeoutMilliseconds = 1000)
{
try
{
_client = new TcpClient();
using (var cts = new CancellationTokenSource(timeoutMilliseconds))
{
var connectTaskCompletionSource = new TaskCompletionSource<bool>();
var connectTask = _client.ConnectAsync(_ipAddress, _port).ContinueWith(t =>
{
if (t.IsCompleted)
{
connectTaskCompletionSource.TrySetResult(true);
}
else if (t.IsFaulted)
{
connectTaskCompletionSource.TrySetException(t.Exception?.InnerException ?? t.Exception);
}
else
{
connectTaskCompletionSource.TrySetResult(false);
}
}, TaskScheduler.Default);
var completedTask = await Task.WhenAny(connectTaskCompletionSource.Task, Task.Delay(timeoutMilliseconds, cts.Token));
if (completedTask == connectTaskCompletionSource.Task && await connectTaskCompletionSource.Task)
{
if (_client.Connected)
{
_networkStream = _client.GetStream();
return true;
}
}
// Timeout foi atingido; limpa a conexão
Console.WriteLine("Conexão cancelada devido ao timeout.");
_client.Dispose();
return false;
}
}
catch (OperationCanceledException)
{
Console.WriteLine("Conexão cancelada pela operação.");
return false;
}
catch (Exception ex)
{
Console.WriteLine($"Erro ao conectar: {ex.Message}");
_client?.Close();
return false;
}
}
// Método para desconectar e liberar recursos
public void Disconnect()
{
try
{
_networkStream?.Close();
_client?.Close();
_networkStream = null;
_client = null;
}
catch (Exception ex)
{
Console.WriteLine($"Erro ao desconectar: {ex.Message}");
}
}
// Método para enviar dados ao dispositivo via Ethernet
public async Task<bool> SendDataAsync(byte[] data)
{
if (IsConnected && _networkStream.CanWrite)
{
try
{
await _networkStream.WriteAsync(data, 0, data.Length);
await _networkStream.FlushAsync();
return true;
}
catch (Exception ex)
{
Console.WriteLine($"Erro ao enviar dados: {ex.Message}");
}
}
else
{
Console.WriteLine("Não conectado ao dispositivo.");
}
return false;
}
// Método para receber dados do dispositivo via Ethernet
public async Task<byte[]> ReceiveDataAsync(int expectedLength, int timeoutMilliseconds = 1000)
{
var buffer = new byte[expectedLength];
try
{
var readTask = _networkStream.ReadAsync(buffer, 0, expectedLength); // Tarefa de leitura sem o token
// Cria uma tarefa de delay que representa o timeout
if (await Task.WhenAny(readTask, Task.Delay(timeoutMilliseconds)) == readTask)
{
// Se readTask completa antes do timeout
var bytesRead = await readTask;
Array.Resize(ref buffer, bytesRead); // Ajusta o tamanho do buffer para os bytes lidos
return buffer;
}
else
{
// Se o timeout for atingido, retorna nulo ou exibe uma mensagem
Console.WriteLine("Timeout ao receber dados via Ethernet.");
return null;
}
}
catch (Exception ex)
{
Console.WriteLine($"Erro ao receber dados: {ex.Message}");
return null;
}
}
// Método para verificar a conexão (pode ser usado para um "heartbeat")
public async Task<bool> CheckConnectionAsync()
{
if (!IsConnected)
{
Console.WriteLine("Conexão perdida. Tentando reconectar...");
return await ConnectAsync();
}
return true;
}
public bool _isReconnecting = false;
private int _reconnectAttempts = 0;
private const int MaxReconnectAttempts = 5;
private const int ReconnectInterval = 2000; // Intervalo de 2000 ms = 2 segundos
// Método para gerenciar a reconexão
public async Task<bool> ReconnectAsync()
{
if (_isReconnecting) return false; // Evita tentativas duplicadas
_isReconnecting = true;
try
{
while (_reconnectAttempts < MaxReconnectAttempts && !IsConnected)
{
Console.WriteLine($"Tentando reconectar ao IP {_ipAddress}... Tentativa {_reconnectAttempts + 1}");
bool connected = await ConnectAsync(5000);
if (connected)
{
Console.WriteLine("Reconexão bem-sucedida.");
_reconnectAttempts = 0;
return true;
}
else
{
_reconnectAttempts++;
await Task.Delay(ReconnectInterval);
}
}
if (!IsConnected)
{
Console.WriteLine("Número máximo de tentativas de reconexão atingido.");
await Task.Delay(5000);
_reconnectAttempts = 0;
}
return IsConnected;
}
finally
{
_isReconnecting = false; // Libera para novas tentativas futuras
}
}
public static List<string> ObterNomesInterfaces()
{
var listaInterfaces = new List<string>();
var interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (var nic in interfaces)
{
string status = nic.OperationalStatus == OperationalStatus.Up ? "Ativa" : "Inativa";
listaInterfaces.Add($"{nic.Name} ({status})");
}
return listaInterfaces;
}
// Obtém o IP do gateway padrão (roteador) da rede ativa
public static string ObterIpGateway()
{
foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces())
{
if (networkInterface.OperationalStatus == OperationalStatus.Up)
{
foreach (GatewayIPAddressInformation gateway in networkInterface.GetIPProperties().GatewayAddresses)
{
if (gateway.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
return gateway.Address.ToString();
}
}
}
}
return null;
}
// Obtém o IP atual do PC na rede ativa
public static string ObterIpAtual()
{
foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces())
{
if (networkInterface.OperationalStatus == OperationalStatus.Up)
{
foreach (UnicastIPAddressInformation ip in networkInterface.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
return ip.Address.ToString();
}
}
}
}
return null;
}
public static string ObterSubnetMaskAtual()
{
foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces())
{
if (networkInterface.OperationalStatus == OperationalStatus.Up)
{
foreach (UnicastIPAddressInformation ip in networkInterface.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
return ip.IPv4Mask.ToString(); // Retorna a máscara de sub-rede como string
}
}
}
}
return null; // Retorna null se não encontrar uma máscara de sub-rede
}
public static string ObterTipoConfiguracaoIP()
{
foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces())
{
if (networkInterface.OperationalStatus == OperationalStatus.Up)
{
var ipProperties = networkInterface.GetIPProperties();
if (ipProperties.GatewayAddresses.Count > 0) // Confirma que há um gateway configurado
{
// Verifica se o DHCP está habilitado para IPv4
if (ipProperties.GetIPv4Properties().IsDhcpEnabled)
{
return "Dinâmico (DHCP)";
}
else
{
return "IP Fixo (Estático)";
}
}
}
}
return "Nenhuma interface de rede ativa encontrada";
}
public static void DefinirIpDinamico(string interfaceName)
{
// Define o IP para DHCP
string comandoIp = $"interface ip set address \"{interfaceName}\" dhcp";
// Define o DNS para DHCP
string comandoDns = $"interface ip set dns \"{interfaceName}\" dhcp";
ExecutarComandoNetsh(comandoIp);
ExecutarComandoNetsh(comandoDns);
}
public static void DefinirIpFixo(string nomeInterface, string ipAddress, string subnetMask, string gateway)
{
try
{
// Define o IP fixo na interface de rede
string comandoIp = $"interface ip set address name=\"{nomeInterface}\" static {ipAddress} {subnetMask} {gateway}";
ExecutarComandoNetsh(comandoIp);
// Configura o DNS para automático (caso desejado)
string comandoDns = $"interface ip set dns name=\"{nomeInterface}\" source=static addr=8.8.8.8 register=primary";
ExecutarComandoNetsh(comandoDns);
MessageBox.Show("IP fixo definido com sucesso!", "Configuração de IP", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show($"Erro ao definir IP fixo: {ex.Message}", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private static string ExecutarComandoNetsh(string comando)
{
Process process = new Process();
process.StartInfo.FileName = "netsh";
process.StartInfo.Arguments = comando;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.Start();
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
return output;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -380,6 +380,11 @@ namespace AgroBase.Services
return;
}
if (Variaveis.OperacaoEmAndamento.DispMvd != null)
{
await ProcurarDispositivosEthernet();
}
var DispositivosRemovidos = dispositivosMapeados.Where(x => x.PortaCOM != "USB" && !Portas.Contains(x.PortaCOM)).ToList();
foreach (var Dispositivo in DispositivosRemovidos)
{
@ -398,20 +403,6 @@ namespace AgroBase.Services
{
await ProcuraDispositivoModbus(ModbusService._PortaModbus, false);
}
lock (MKS057DService._PortaLock)
{
if (DispositivosMapeados.Any(x => x.Dispositivo == T_Code.Mks) && MKS057DService._PortaMKS != null &&!PortasNaoMapeadas.Contains(MKS057DService._PortaMKS.PortName))
{
//await ProcuraDispositivoMKS(MKS057DService._PortaMKS);
Task.Run(async () => {
await ProcuraDispositivoMKS(MKS057DService._PortaMKS);
});
}
}
if (DispositivosMapeados.Any(x => x.Dispositivo == T_Code.Bld) && !PortasNaoMapeadas.Contains(BLD300RService._PortaBLD.PortName))
{
await ProcuraDispositivoBLD(BLD300RService._PortaBLD);
}
}
catch (Exception ex)
{
@ -558,18 +549,6 @@ namespace AgroBase.Services
return true;
}
bool DispBld = await ProcuraDispositivoBLD(porta);
if (DispBld)
{
return true;
}
bool DispMks = await ProcuraDispositivoMKS(porta);
if (DispMks)
{
return true;
}
bool DispLoRa = await ProcuraDispositivoLoRa(porta);
if (DispLoRa)
{
@ -712,51 +691,6 @@ namespace AgroBase.Services
return ModbusService.Iniciado;
}
private static async Task<bool> ProcuraDispositivoBLD(SerialPort porta)
{
if (BLD300RService.Iniciado && porta.PortName != BLD300RService._PortaBLD.PortName)
{
return false;
}
if (!BLD300RService.Iniciado || BLD300RService.DadosLeitura.Any(x => !x.Iniciado))
{
AtualizarConsole("Procurando dispositivos BLD");
bool Encontrado = await BLD300RService.VerificaPortaBLD(porta);
if (Encontrado)
{
AtualizarConsole("Dispositivo BLD encontrado");
return Encontrado;
}
}
return BLD300RService.Iniciado;
}
private static async Task<bool> ProcuraDispositivoMKS(SerialPort porta)
{
lock (MKS057DService._PortaLock)
{
if (MKS057DService.Iniciado && porta.PortName != MKS057DService._PortaMKS.PortName)
{
return false;
}
}
if (!MKS057DService.Referenciando && (!MKS057DService.Iniciado || Variaveis.OperacaoEmAndamento.DispMvd.Dados.Modulos.Any(x => !x.DirMotor.MKS_Inicializado)))
{
AtualizarConsole("Procurando dispositivos MKS");
bool Encontrado = await MKS057DService.VerificaPortaMKS(porta);
if (Encontrado)
{
AtualizarConsole("Dispositivo MKS encontrado");
return Encontrado;
}
}
return MKS057DService.Iniciado;
}
private static async Task<bool> ProcuraDispositivoLoRa(SerialPort porta)
{
if (LoRaService.Iniciado && porta.PortName != LoRaService._PortaLoRa.PortName)
@ -796,6 +730,63 @@ namespace AgroBase.Services
}
}
private static async Task<bool> ProcurarDispositivosEthernet()
{
if (!Variaveis.IsAgroMonitor)
{
bool ethernetEncontrado = false;
bool DispBld = await ProcuraDispositivoBLD();
if (DispBld)
{
ethernetEncontrado = true;
}
bool DispMks = await ProcuraDispositivoMKS();
if (DispMks)
{
ethernetEncontrado = true;
}
return ethernetEncontrado;
}
return false;
}
private static async Task<bool> ProcuraDispositivoBLD()
{
if (!BLD300RService.Iniciado || BLD300RService.DadosLeitura.Any(x => !x.Iniciado))
{
AtualizarConsole("Procurando dispositivos BLD");
bool Encontrado = await BLD300RService.VerificaPortaBLD();
if (Encontrado)
{
AtualizarConsole("Dispositivo BLD encontrado");
return Encontrado;
}
}
return BLD300RService.Iniciado;
}
private static async Task<bool> ProcuraDispositivoMKS()
{
if (!MKS057DService.Referenciando && (!MKS057DService.Iniciado || MKS057DService.DadosLeitura.Any(x => !x.Iniciado)))
{
AtualizarConsole("Procurando dispositivos MKS");
bool Encontrado = await MKS057DService.VerificaPortaMKS();
if (Encontrado)
{
AtualizarConsole("Dispositivo MKS encontrado");
return Encontrado;
}
}
return MKS057DService.Iniciado;
}
private static bool VerificaRespostaGPS(SerialPort Porta, string Recebido = null)
{
if (string.IsNullOrEmpty(Recebido))

View File

@ -58948,3 +58948,16 @@
11/11/2024 17:20:41:202 - Porta COM21 - 3: Resposta inválida.
11/11/2024 17:20:42:261 - Porta COM21 - 2: Resposta inválida.
11/11/2024 17:20:43:283 - Porta COM21 - 4: Resposta inválida.
12/11/2024 12:53:05:925 - Endereço 1 (192.168.99.105): Resposta inválida. 68-65-79-0D-0A
12/11/2024 12:53:32:988 - Endereço 3 (192.168.99.105): Resposta inválida. 74-65-73-74-65-0D-0A
12/11/2024 12:53:53:776 - Endereço 2 (192.168.99.105): Resposta inválida. 30-31-20-30-35-20-32
12/11/2024 12:53:57:224 - Endereço 4 (192.168.99.105): Resposta inválida. 32-0D-0A
12/11/2024 12:54:48:750 - Endereço 1 (192.168.99.105): Resposta inválida. 6C-0D-0A
12/11/2024 12:54:54:003 - Endereço 3 (192.168.99.105): Resposta inválida. 74-0D-0A
12/11/2024 15:23:52:040 - Endereço 1 (192.168.99.103): Resposta inválida. 31-32-33-0D-0A
12/11/2024 15:23:58:485 - Endereço 3 (192.168.99.103): Resposta inválida. 31-31-0D-0A
12/11/2024 15:26:18:659 - Endereço 1 (192.168.99.103): Resposta inválida. 31-0D-0A
12/11/2024 15:33:41:464 - Endereço 1 (192.168.99.103): Resposta inválida. 31-0D-0A
12/11/2024 15:33:44:482 - Endereço 3 (192.168.99.103): Resposta inválida. 32-0D-0A
12/11/2024 15:33:45:317 - Endereço 2 (192.168.99.103): Resposta inválida. 33-0D-0A
12/11/2024 15:33:46:453 - Endereço 4 (192.168.99.103): Resposta inválida. 34-0D-0A

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
5875a1a9c926bc3d1db863aa7762494af9ca53385f091eb1d7da78431a6d9acf
a7e8182e7c96a094b52f42faa88f285de461d90df42b3912f1224e93f5128942

View File

@ -480,3 +480,4 @@ C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\MathNet.Numerics.dll
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\MathNet.Numerics.xml
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\OpenHardwareMonitorLib.dll
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\obj\Debug\AgroBase.Forms.frmA05Config.resources
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\obj\Debug\AgroBase.Forms.frmEthernet.resources