Как я могу прочитать положение руки робота? Помогите
Привет Ребята,
I Hope everyone is enjoying their happy Friday. I'm writing code to control a Robot Arm that has two motors on it to move Horizontal and vertical. I found similar code but it's in C# and I'm converting it into Vb.net. I'm able to move the arm backward, forward, up, down and can also home motors. I'm trying to read the position of the both Horizontal and vertical motors in textbox - textPosH & textPosV. It shows moved position in textPosH but then it changes to 8 so let's say if I moved forward 100mm then in text box it will show 100 just for a second then changes back to 8 and that 8 always stays in there while vertical doesn't even show any info. I'm including the both version ( C# and VB.Net) of code below. If anyone can help me to read the actual live position of both Horizontal and vertical motors that would be great. I'm new to programming. That's my first project. For the information C# version of the code works perfectly and shows positions live and correctly. I'm changing that code into vb.net because I'm more familiar with it and later on I want to add some more features to the application. I'm only interested in the position not in the speed, acceleration and origin. Thanks in advance.
Что я уже пробовал:
VB.Net версия кода -
Imports System Imports System.Collections.Generic Imports System.ComponentModel Imports System.Data Imports System.Drawing Imports System.Linq Imports System.Text Imports System.Threading.Tasks Imports System.Windows.Forms Public Class MainMenuForm Inherits Form Const RUN_ACC_H As Integer = 10 Const RUN_ACC_V As Integer = 10 Const RUN_SPEED_H As Integer = 2000 Const RUN_SPEED_V As Integer = 15 Enum MOVE_DIRECTION Stationary StationaryMouseDown MovingBack MovingFwd End Enum Dim _tcpClient As System.Net.Sockets.TcpClient Dim _tcpStream As System.Net.Sockets.NetworkStream Dim _logStream As System.IO.FileStream Dim _readBuffer As Byte() Dim _strBuffer As String Dim _bDisconnecting As Boolean Dim _movingH As MOVE_DIRECTION Dim _movingV As MOVE_DIRECTION Public Sub New() _bDisconnecting = True _readBuffer = New Byte(256) {} _logStream = Nothing _logStream = New System.IO.FileStream("RxLog.log", System.IO.FileMode.Append) _strBuffer = "" _movingH = MOVE_DIRECTION.Stationary _movingV = MOVE_DIRECTION.Stationary _tcpClient = Nothing InitializeComponent() Dim assembly As System.Reflection.Assembly = System.Reflection.Assembly.GetExecutingAssembly() EnableButtons(False) SettingsForm.hScrollSpeedH.LargeChange = RUN_SPEED_H / 20 SettingsForm.hScrollSpeedH.Maximum = RUN_SPEED_H + SettingsForm.hScrollSpeedH.LargeChange - 1 SettingsForm.hScrollSpeedH.Value = RUN_SPEED_H SettingsForm.hScrollSpeedH_Scroll(Nothing, Nothing) SettingsForm.hScrollSpeedV.LargeChange = RUN_SPEED_V / 10 SettingsForm.hScrollSpeedV.Maximum = RUN_SPEED_V + SettingsForm.hScrollSpeedV.LargeChange - 1 SettingsForm.hScrollSpeedV.Value = RUN_SPEED_V SettingsForm.hScrollSpeedV_Scroll(Nothing, Nothing) End Sub Private Sub EnableButtons(ByVal enable As Boolean) BtnHome.Enabled = enable BtnUp.Enabled = enable BtnDown.Enabled = enable BtnForword.Enabled = enable BtnBackword.Enabled = enable BtnStop.Enabled = enable BtnStart.Enabled = enable textPosH.Enabled = enable textPosV.Enabled = enable End Sub Delegate Sub SetTextCallback(ByVal text As String, ByVal Vertical As Boolean) Delegate Sub SetTextOnlyCallback(ByVal text As String) Delegate Sub SetColourCallback(ByVal colour As Color, ByVal Vertical As Boolean) Private Sub SetColourPos(ByVal colour As Color, ByVal Vertical As Boolean) If If(Vertical, textPosV.InvokeRequired, textPosH.InvokeRequired) Then Try Dim d As SetColourCallback = New SetColourCallback(AddressOf SetColourPos) Invoke(d, New Object() {colour, Vertical}) Catch __unusedException1__ As Exception End Try Else If Vertical Then textPosV.BackColor = colour Else textPosH.BackColor = colour End If End If End Sub Private Sub SetTextPos(ByVal text As String, ByVal Vertical As Boolean) If If(Vertical, textPosV.InvokeRequired, textPosH.InvokeRequired) Then Try Dim d As SetTextCallback = New SetTextCallback(AddressOf SetTextPos) Invoke(d, New Object() {text, Vertical}) Catch __unusedException1__ As Exception End Try Else If Vertical Then textPosV.Text = text If Int32.Parse(text) >= Int32.Parse(SettingsForm.textMaxPosV.Text) * 0.98 Then SettingsForm.textMaxPosV.BackColor = Color.Orange Else SettingsForm.textMaxPosV.BackColor = SystemColors.Window End If Else textPosH.Text = text If Int32.Parse(text) >= Int32.Parse(SettingsForm.textMaxPosH.Text) * 0.98 Then SettingsForm.textMaxPosH.BackColor = Color.Orange Else SettingsForm.textMaxPosH.BackColor = SystemColors.Window End If End If End If End Sub Private Function HandleReply(ByVal reply As String) As Boolean Dim Handled As Boolean = False Dim pos As Integer = 0 Dim isV As Boolean = (reply.IndexOf(".2") >= 0) 'Ux.1=8<cr><lf> Movement complete any movement cmd 'Ux.2=8<cr><lf> Movement complete any movement cmd 'Ux.1=0<cr><lf> Motor Status ?99.1 ' 0=Running, 1=overflow, 2=overspeed, 4=overload, 8=In position If ((pos = reply.IndexOf("Ux.") >= 0)) Then Dim posEq As Integer = reply.IndexOf("="c) If (posEq >= 0) Then Dim res As Integer = 1 Int32.TryParse(reply.Substring(posEq + 1), res) Dim setColour As Color = Color.Red If res = 0 Then setColour = Color.Green ElseIf res = 8 Then setColour = SystemColors.Control End If SetColourPos(setColour, (reply(pos + 3) = "2"c)) Handled = True End If End If 'Px.1=245<cr><lf> Current Pos ?96.1 If (pos = reply.IndexOf("Px.") >= 0) Then Dim posEq As Integer = reply.IndexOf("="c) If (posEq >= 0) Then Dim res As Integer = -999 Int32.TryParse(reply.Substring((posEq + 1)), res) Me.SetTextPos(res.ToString(), (reply(pos + 3) = "2"c)) Handled = True End If End If 'Sx.1=0<cr><lf> Current Speed ?97.1 If (pos = reply.IndexOf("Sx.") >= 0) Then Dim posEq As Integer = reply.IndexOf("="c) If (posEq >= 0) Then Dim res As Integer = -999 Int32.TryParse(reply.Substring((posEq + 1)), res) Handled = True End If End If 'Ix.1=0<cr><lf> Current Acc ?98.1 If ((pos = reply.IndexOf("Ix.") >= 0)) Then Dim posEq As Integer = reply.IndexOf("="c) If (posEq >= 0) Then Dim res As Integer = -999 Int32.TryParse(reply.Substring((posEq + 1)), res) Handled = True End If End If 'Origin.1=909<cr><lf> Found and set origin |.1 'Origin.2=41<cr><lf> Found and set origin |.2 If (pos = reply.IndexOf("Origin.") >= 0) Then Dim posEq As Integer = reply.IndexOf("="c) If (posEq >= 0) Then Handled = True End If End If 'Check for echoed commands Select Case (reply.Substring(0, 1)) Case "?", "(", ")", "|", "^", "A", "P", "S" Handled = True End Select Return Handled End Function Private Sub OnDataAvailable(ByVal result As IAsyncResult) If Not _bDisconnecting Then Try Dim nRead As Integer = _tcpStream.EndRead(result) If nRead > 0 Then _strBuffer += Encoding.ASCII.GetString(_readBuffer, 0, nRead) _logStream.Write(_readBuffer, 0, nRead) Dim [end] As Integer = 0 While [end] >= 0 AndAlso Not _bDisconnecting Dim nIgnore As Integer = 0 While nIgnore < _strBuffer.Length AndAlso (_strBuffer(nIgnore) = vbCr OrElse _strBuffer(nIgnore) = vbLf) nIgnore += 1 End While [end] = _strBuffer.IndexOf(vbCrLf, nIgnore) If [end] >= 0 Then Dim sRx As String = _strBuffer.Substring(nIgnore, [end] + 2) If _strBuffer.Length > [end] + 2 Then _strBuffer = _strBuffer.Substring([end] + 2) Else _strBuffer = "" End If If Not HandleReply(sRx) Then AppendLog("Rx: " & sRx) End If End While End If If Not _bDisconnecting Then _tcpStream.BeginRead(_readBuffer, 0, 256, New AsyncCallback(AddressOf OnDataAvailable), Nothing) Catch __unusedException1__ As Exception End Try End If End Sub Private Sub BtnConnect_Click(sender As Object, e As EventArgs) Handles BtnConnect.Click If BtnConnect.Text = "Connect" Then Try _tcpClient = New System.Net.Sockets.TcpClient() _tcpClient.Connect("193.240.200.203", 10001) _tcpStream = _tcpClient.GetStream() _tcpStream.BeginRead(_readBuffer, 0, 256, New AsyncCallback(AddressOf OnDataAvailable), Nothing) BtnConnect.Text = "Disconnect" _bDisconnecting = False EnableButtons(True) SendCmd("S.1=" & SettingsForm.hScrollSpeedH.Value.ToString()) SendCmd("A.1=" & RUN_ACC_H.ToString()) SendCmd("S.2=" & SettingsForm.hScrollSpeedV.Value.ToString()) SendCmd("A.2=" & RUN_ACC_V.ToString()) Catch ex As System.Net.Sockets.SocketException MessageBox.Show(ex.Message, "Socket Exception") End Try Else _bDisconnecting = True timerQuery.Enabled = False _tcpClient.Close() _tcpClient = Nothing BtnConnect.Text = "Connect" EnableButtons(False) End If End Sub Private Sub SendCmd(ByVal cmd As String) cmd += vbCrLf Dim cmdHok As Boolean = (cmd.IndexOf(".1") >= 0) Dim cmdVok As Boolean = (cmd.IndexOf(".2") >= 0) If True Then Select Case cmd(0) Case "|"c Case Else End Select Dim send As Byte() = Encoding.ASCII.GetBytes(cmd) _tcpStream.Write(send, 0, send.Length) System.Threading.Thread.Sleep(10) End If End Sub Private Sub BtnHome_Click(sender As Object, e As EventArgs) Handles BtnHome.Click SendCmd(").1") SendCmd("(.1") SendCmd("|.1") SendCmd(").2") SendCmd("(.2") SendCmd("|.2") End Sub Private Sub BtnForword_Click(sender As Object, e As EventArgs) Handles BtnForword.Click Dim p As Integer = Int32.Parse(textPosH.Text) Dim inc As Integer = Int32.Parse(SettingsForm.textMoveH.Text) Dim target As Integer = p + inc Dim maxVal As Integer = 0 If Int32.TryParse(SettingsForm.textMaxPosH.Text, maxVal) Then If target > maxVal Then target = maxVal SendCmd("P.1=" & target.ToString()) SendCmd("^.1") End If End Sub Private Sub BtnBackword_Click(sender As Object, e As EventArgs) Handles BtnBackword.Click Dim p As Integer = Int32.Parse(textPosH.Text) Dim inc As Integer = Int32.Parse(SettingsForm.textMoveH.Text) Dim target As Integer = p - inc If target < 0 Then target = 0 SendCmd("P.1=" & target.ToString()) SendCmd("^.1") End Sub Private Sub BtnUp_Click(sender As Object, e As EventArgs) Handles BtnUp.Click Dim p As Integer = Int32.Parse(textPosV.Text) Dim inc As Integer = Int32.Parse(SettingsForm.textMoveV.Text) Dim target As Integer = p + inc Dim maxVal As Integer = 0 If Int32.TryParse(SettingsForm.textMaxPosV.Text, maxVal) Then If target > maxVal Then target = maxVal SendCmd("P.2=" & target.ToString()) SendCmd("^.2") End If End Sub Private Sub BtnDown_Click(sender As Object, e As EventArgs) Handles BtnDown.Click Dim p As Integer = Int32.Parse(textPosV.Text) Dim inc As Integer = Int32.Parse(SettingsForm.textMoveV.Text) Dim target As Integer = p - inc If target < 0 Then target = 0 SendCmd("P.2=" & target.ToString()) SendCmd("^.2") End Sub Private Sub MainMenu_FormClosed(ByVal sender As Object, ByVal e As FormClosedEventArgs) _logStream.Close() End Sub Private Sub HineMotorSetup_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) _bDisconnecting = True If BtnConnect.Text = "Disconnect" Then BtnConnect_Click(sender, Nothing) System.Threading.Thread.Sleep(100) End If End Sub Private Sub EXITToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EXITToolStripMenuItem.Click End Sub Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles TimerQuery.Tick SendCmd("?97.1") SendCmd("?96.1") SendCmd("?97.2") SendCmd("?96.2") End Sub Private Sub BtnStop_Click(sender As Object, e As EventArgs) Handles BtnStop.Click SendCmd(").1") SendCmd(").2") End Sub Private Sub BtnStart_Click(sender As Object, e As EventArgs) Handles BtnStart.Click SendCmd("(.1") SendCmd("(.2") End Sub Private Sub ExitToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem1.Click End End Sub Private Sub SettingsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SettingsToolStripMenuItem.Click SettingsForm.Show() End Sub Private Sub AppendLog(p1 As String) Throw New NotImplementedException End Sub End Class
----------------------------------------------------------------------------------
Версия кода на языке C# -
#define HINEMOTORSETUP_LOG_ALL_RX #define HINEMOTORSETUP_DISABLE_CORNERS 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 HineMotorSetup { public partial class HineMotorSetup : Form { const int JOYSTICK_SIZE = 5; const int JOYSTICK_CENTRE = 10; const int RUN_ACC_H = 10; const int RUN_ACC_V = 10; const int JOYSTICK_ACC_H = 1; const int JOYSTICK_ACC_V = 1; const int RUN_SPEED_H = 2000; const int RUN_SPEED_V = 15; enum MOVE_DIRECTION { Stationary, StationaryMouseDown, MovingBack, MovingFwd }; private System.Net.Sockets.TcpClient _tcpClient; private System.Net.Sockets.NetworkStream _tcpStream; private System.IO.FileStream _logStream; private Byte[] _readBuffer; private String _strBuffer; private MOVE_DIRECTION _movingH; private MOVE_DIRECTION _movingV; private bool _bDisconnecting; public HineMotorSetup() { _bDisconnecting = true; _readBuffer = new Byte[256]; _logStream = null; #if (HINEMOTORSETUP_LOG_ALL_RX) _logStream = new System.IO.FileStream("RxLog.log", System.IO.FileMode.Append); #endif _strBuffer = ""; _movingH = MOVE_DIRECTION.Stationary; _movingV = MOVE_DIRECTION.Stationary; _tcpClient = null; InitializeComponent(); System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); Text = "Hine Motor Setup v" + assembly.GetName().Version; EnableButtons(false); hScrollSpeedH.LargeChange = RUN_SPEED_H / 20; hScrollSpeedH.Maximum = RUN_SPEED_H + hScrollSpeedH.LargeChange - 1; hScrollSpeedH.Value = RUN_SPEED_H; hScrollSpeedH_Scroll(null, null); hScrollSpeedV.LargeChange = RUN_SPEED_V / 10; hScrollSpeedV.Maximum = RUN_SPEED_V + hScrollSpeedV.LargeChange - 1; hScrollSpeedV.Value = RUN_SPEED_V; hScrollSpeedV_Scroll(null, null); } public static DialogResult InputBox(string title, string promptText, ref string value) { Form form = new Form(); Label label = new Label(); TextBox textBox = new TextBox(); Button buttonOk = new Button(); Button buttonCancel = new Button(); form.Text = title; label.Text = promptText; textBox.Text = value; buttonOk.Text = "OK"; buttonCancel.Text = "Cancel"; buttonOk.DialogResult = DialogResult.OK; buttonCancel.DialogResult = DialogResult.Cancel; label.SetBounds(9, 20, 372, 13); textBox.SetBounds(12, 36, 372, 20); buttonOk.SetBounds(228, 72, 75, 23); buttonCancel.SetBounds(309, 72, 75, 23); label.AutoSize = true; textBox.Anchor = textBox.Anchor | AnchorStyles.Right; buttonOk.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; form.ClientSize = new Size(396, 107); form.Controls.AddRange(new Control[] { label, textBox, buttonOk, buttonCancel }); form.ClientSize = new Size(Math.Max(300, label.Right + 10), form.ClientSize.Height); form.FormBorderStyle = FormBorderStyle.FixedDialog; form.StartPosition = FormStartPosition.CenterScreen; form.MinimizeBox = false; form.MaximizeBox = false; form.AcceptButton = buttonOk; form.CancelButton = buttonCancel; DialogResult dialogResult = form.ShowDialog(); value = textBox.Text; return dialogResult; } private void EnableButtons(bool enable) { btnHome.Enabled = enable; btnJogDn.Enabled = enable; btnJogUp.Enabled = enable; btnJogExtend.Enabled = enable; btnJogRetract.Enabled = enable; btnSend.Enabled = enable; btnStop.Enabled = enable; btnEnableMotors.Enabled = enable; textPosH.Enabled = enable; textPosV.Enabled = enable; } delegate void SetTextOnlyCallback(string text); delegate void SetTextCallback(string text, bool Vertical); delegate void SetColourCallback(Color colour, bool Vertical); private void AppendLog(string text) { // InvokeRequired required compares the thread ID of the // calling thread to the thread ID of the creating thread. // If these threads are different, it returns true. if (textLog.InvokeRequired) { try { SetTextOnlyCallback d = new SetTextOnlyCallback(AppendLog); Invoke(d, new object[] { text }); } catch (Exception) { } } else { textLog.Text += text; textLog.Select(textLog.Text.Length, 0); textLog.ScrollToCaret(); } } private void SetTextOrig(string text, bool Vertical) { // InvokeRequired required compares the thread ID of the // calling thread to the thread ID of the creating thread. // If these threads are different, it returns true. if (Vertical ? textOrigV.InvokeRequired : textOrigH.InvokeRequired) { try { SetTextCallback d = new SetTextCallback(SetTextOrig); Invoke(d, new object[] { text, Vertical }); } catch (Exception) { } } else { if (Vertical) textOrigV.Text = text; else textOrigH.Text = text; } } private void SetColourPos(Color colour, bool Vertical) { // InvokeRequired required compares the thread ID of the // calling thread to the thread ID of the creating thread. // If these threads are different, it returns true. if (Vertical ? textPosV.InvokeRequired : textPosH.InvokeRequired) { try { SetColourCallback d = new SetColourCallback(SetColourPos); Invoke(d, new object[] { colour, Vertical }); } catch (Exception) { } } else { if (Vertical) textPosV.BackColor = colour; else textPosH.BackColor = colour; } } private void SetTextPos(string text, bool Vertical) { // InvokeRequired required compares the thread ID of the // calling thread to the thread ID of the creating thread. // If these threads are different, it returns true. if (Vertical ? textPosV.InvokeRequired : textPosH.InvokeRequired) { try { SetTextCallback d = new SetTextCallback(SetTextPos); Invoke(d, new object[] { text, Vertical }); } catch (Exception) { } } else { if (Vertical) { textPosV.Text = text; if (Int32.Parse(text) >= Int32.Parse(textMaxPosV.Text) * 0.98) { textMaxPosV.BackColor = Color.Orange; } else { textMaxPosV.BackColor = SystemColors.Window; } } else { textPosH.Text = text; if (Int32.Parse(text) >= Int32.Parse(textMaxPosH.Text)*0.98) { textMaxPosH.BackColor = Color.Orange; } else { textMaxPosH.BackColor = SystemColors.Window; } } } } private void SetTextSpeed(string text, bool Vertical) { // InvokeRequired required compares the thread ID of the // calling thread to the thread ID of the creating thread. // If these threads are different, it returns true. if (Vertical ? textSpeedV.InvokeRequired : textSpeedH.InvokeRequired) { try { SetTextCallback d = new SetTextCallback(SetTextSpeed); Invoke(d, new object[] { text, Vertical }); } catch (Exception) { } } else { if (Vertical) textSpeedV.Text = text; else textSpeedH.Text = text; } } private void SetTextAccel(string text, bool Vertical) { // InvokeRequired required compares the thread ID of the // calling thread to the thread ID of the creating thread. // If these threads are different, it returns true. if (Vertical ? textAccelV.InvokeRequired : textAccelH.InvokeRequired) { try { SetTextCallback d = new SetTextCallback(SetTextAccel); Invoke(d, new object[] { text, Vertical }); } catch (Exception) { } } else { if (Vertical) textAccelV.Text = text; else textAccelH.Text = text; } } private bool HandleReply(String reply) { bool Handled = false; int pos = 0; bool isV = reply.IndexOf(".2") >= 0; //Ux.1=8<cr><lf> Movement complete any movement cmd //Ux.2=8<cr><lf> Movement complete any movement cmd //Ux.1=0<cr><lf> Motor Status ?99.1 // 0=Running, 1=overflow, 2=overspeed, 4=overload, 8=In position if ((pos = reply.IndexOf("Ux.")) >= 0) { int posEq = reply.IndexOf('='); if (posEq >= 0) { int res = 1; Int32.TryParse(reply.Substring(posEq + 1), out res); Color setColour = Color.Red; if (res == 0) setColour = Color.Green; else if (res == 8) { setColour = SystemColors.Control; } SetColourPos(setColour, (reply[pos + 3] == '2')); Handled = true; } } //Px.1=245<cr><lf> Current Pos ?96.1 if ((pos = reply.IndexOf("Px.")) >= 0) { int posEq = reply.IndexOf('='); if (posEq >= 0) { int res = -999; Int32.TryParse(reply.Substring(posEq + 1), out res); SetTextPos(res.ToString(), (reply[pos + 3] == '2')); Handled = true; } } //Sx.1=0<cr><lf> Current Speed ?97.1 if ((pos = reply.IndexOf("Sx.")) >= 0) { int posEq = reply.IndexOf('='); if (posEq >= 0) { int res = -999; Int32.TryParse(reply.Substring(posEq + 1), out res); SetTextSpeed(res.ToString(), (reply[pos + 3] == '2')); Handled = true; } } //Ix.1=0<cr><lf> Current Acc ?98.1 if ((pos = reply.IndexOf("Ix.")) >= 0) { int posEq = reply.IndexOf('='); if (posEq >= 0) { int res = -999; Int32.TryParse(reply.Substring(posEq + 1), out res); SetTextAccel(res.ToString(), (reply[pos + 3] == '2')); Handled = true; } } //Origin.1=909<cr><lf> Found and set origin |.1 //Origin.2=41<cr><lf> Found and set origin |.2 else if ((pos = reply.IndexOf("Origin.")) >= 0) { int posEq = reply.IndexOf('='); if (posEq >= 0) { SetTextOrig(reply.Substring(posEq + 1), (reply[pos + 7] == '2')); Handled = true; } } //Check for echoed commands switch (reply.Substring(0,1)) { case "?": case "(": case ")": case "|": case "^": case "A": case "P": case "S": Handled = true; break; } return Handled; } private void OnDataAvailable(IAsyncResult result) { if (!_bDisconnecting) { try { int nRead = _tcpStream.EndRead(result); if (nRead > 0) { _strBuffer += Encoding.ASCII.GetString(_readBuffer, 0, nRead); #if (HINEMOTORSETUP_LOG_ALL_RX) _logStream.Write(_readBuffer, 0, nRead); #endif int end = 0; while (end >= 0 && !_bDisconnecting) { //Ignore leading /r/n int nIgnore = 0; while (nIgnore < _strBuffer.Length && (_strBuffer[nIgnore] == '\r' || _strBuffer[nIgnore] == '\n')) nIgnore++; end = _strBuffer.IndexOf("\r\n", nIgnore); if (end >= 0) { String sRx = _strBuffer.Substring(nIgnore, end + 2); if (_strBuffer.Length > end + 2) _strBuffer = _strBuffer.Substring(end + 2); else _strBuffer = ""; if (!HandleReply(sRx)) AppendLog("Rx: " + sRx); } } } //Setup the Async Read again for the next data received. if (!_bDisconnecting) _tcpStream.BeginRead(_readBuffer, 0, 256, new AsyncCallback(OnDataAvailable), null); } catch (Exception) { } } } private void btnConnect_Click(object sender, EventArgs e) { if (btnConnect.Text == "Connect") { try { _tcpClient = new System.Net.Sockets.TcpClient(); _tcpClient.Connect("193.240.200.203", 10001); _tcpStream = _tcpClient.GetStream(); _tcpStream.BeginRead(_readBuffer, 0, 256, new AsyncCallback(OnDataAvailable), null); btnConnect.Text = "Disconnect"; EnableButtons(true); timerQuery.Enabled = true; _bDisconnecting = false; //Set Dynamic Command speed and acceleration SendCmd("S.1=" + hScrollSpeedH.Value.ToString()); SendCmd("A.1=" + RUN_ACC_H.ToString()); SendCmd("S.2=" + hScrollSpeedV.Value.ToString()); SendCmd("A.2=" + RUN_ACC_V.ToString()); } catch (System.Net.Sockets.SocketException ex) { MessageBox.Show(ex.Message, "Socket Exception"); } } else { _bDisconnecting = true; timerQuery.Enabled = false; EnableButtons(false); _tcpClient.Close(); _tcpClient = null; btnConnect.Text = "Connect"; } } private void SendCmd(String cmd) { if (!_bDisconnecting) { cmd += "\r\n"; bool cmdHok = (cmd.IndexOf(".1") >= 0); bool cmdVok = (cmd.IndexOf(".2") >= 0); { switch (cmd[0]) { case '|': if (cmdHok) { SetColourPos(Color.Orange, cmdVok); } else if (cmdVok) { SetColourPos(Color.Orange, cmdVok); } break; default: break; } byte[] send = Encoding.ASCII.GetBytes(cmd); _tcpStream.Write(send, 0, send.Length); System.Threading.Thread.Sleep(10); //Seems to stop overlapping replies! } } } private void btnHome_Click(object sender, EventArgs e) { SendCmd(").1"); SendCmd("(.1"); SendCmd("|.1"); SendCmd(").2"); SendCmd("(.2"); SendCmd("|.2"); } private void btnSend_Click(object sender, EventArgs e) { SendCmd(textSend.Text); } private void timerQuery_Tick(object sender, EventArgs e) { SendCmd("?99.1"); //Motor status SendCmd("?98.1"); //Motor acceleration SendCmd("?97.1"); //Motor speed SendCmd("?96.1"); //Motor position SendCmd("?99.2"); SendCmd("?98.2"); SendCmd("?97.2"); SendCmd("?96.2"); } private void btnEnableMotors_Click(object sender, EventArgs e) { SendCmd("(.1"); SendCmd("(.2"); } private void btnStop_Click(object sender, EventArgs e) { SendCmd(").1"); SendCmd(").2"); } private void btnJogExtend_Click(object sender, EventArgs e) { int p = Int32.Parse(textPosH.Text); int inc = Int32.Parse(textJogH.Text); int target = p + inc; int maxVal = 0; if (Int32.TryParse(textMaxPosH.Text, out maxVal)) { if (target > maxVal) target = maxVal; SendCmd("P.1=" + target.ToString()); SendCmd("^.1"); } } private void btnJogRetract_Click(object sender, EventArgs e) { int p = Int32.Parse(textPosH.Text); int inc = Int32.Parse(textJogH.Text); int target = p - inc; if (target < 0) target = 0; SendCmd("P.1=" + target.ToString()); SendCmd("^.1"); } private void btnJogUp_Click(object sender, EventArgs e) { int p = Int32.Parse(textPosV.Text); int inc = Int32.Parse(textJogV.Text); int target = p + inc; int maxVal = 0; if (Int32.TryParse(textMaxPosV.Text, out maxVal)) { if (target > maxVal) target = maxVal; SendCmd("P.2=" + target.ToString()); SendCmd("^.2"); } } private void btnJogDn_Click(object sender, EventArgs e) { int p = Int32.Parse(textPosV.Text); int inc = Int32.Parse(textJogV.Text); int target = p - inc; if (target < 0) target = 0; SendCmd("P.2=" + target.ToString()); SendCmd("^.2"); } private void imgJoystick_Paint(object sender, PaintEventArgs e) { e.Graphics.DrawRectangle(Pens.Red, imgJoystick.Width / 2 - JOYSTICK_CENTRE, imgJoystick.Height / 2 - JOYSTICK_CENTRE, JOYSTICK_CENTRE * 2, JOYSTICK_CENTRE*2); int xpos = imgJoystick.Width / 2 - JOYSTICK_SIZE; if (_movingH == MOVE_DIRECTION.MovingBack) xpos = 0; else if (_movingH == MOVE_DIRECTION.MovingFwd) xpos = imgJoystick.Width - JOYSTICK_SIZE * 2 - 2; int ypos = imgJoystick.Height / 2 - JOYSTICK_SIZE; if (_movingV == MOVE_DIRECTION.MovingBack) ypos = imgJoystick.Height - JOYSTICK_SIZE * 2 - 2; else if (_movingV == MOVE_DIRECTION.MovingFwd) ypos = 0; e.Graphics.FillEllipse(Brushes.Black, xpos, ypos, JOYSTICK_SIZE * 2, JOYSTICK_SIZE * 2); } private void imgJoystick_MouseDown(object sender, MouseEventArgs e) { _movingH = MOVE_DIRECTION.StationaryMouseDown; _movingV = MOVE_DIRECTION.StationaryMouseDown; SendCmd("S.1=" + RUN_SPEED_H.ToString()); SendCmd("S.2=" + RUN_SPEED_V.ToString()); SendCmd("A.1=" + JOYSTICK_ACC_H.ToString()); SendCmd("A.2=" + JOYSTICK_ACC_V.ToString()); imgJoystick_MouseMove(sender, e); } private void imgJoystick_MouseUp(object sender, MouseEventArgs e) { _movingH = MOVE_DIRECTION.Stationary; _movingV = MOVE_DIRECTION.Stationary; SendCmd(").1"); SendCmd("(.1"); SendCmd(").2"); SendCmd("(.2"); SendCmd("S.1=" + hScrollSpeedH.Value.ToString()); SendCmd("S.2=" + hScrollSpeedV.Value.ToString()); SendCmd("A.1=" + RUN_ACC_H.ToString()); SendCmd("A.2=" + RUN_ACC_V.ToString()); imgJoystick.Refresh(); } private void imgJoystick_MouseMove(object sender, MouseEventArgs e) { if (_movingH != MOVE_DIRECTION.Stationary) { MOVE_DIRECTION prevH = _movingH; int mid = imgJoystick.Width / 2; if (e.X < mid - JOYSTICK_CENTRE #if HINEMOTORSETUP_DISABLE_CORNERS && _movingV == MOVE_DIRECTION.StationaryMouseDown #endif ) { _movingH = MOVE_DIRECTION.MovingBack; } else if (e.X > mid + JOYSTICK_CENTRE #if HINEMOTORSETUP_DISABLE_CORNERS && _movingV == MOVE_DIRECTION.StationaryMouseDown #endif ) { _movingH = MOVE_DIRECTION.MovingFwd; } else { _movingH = MOVE_DIRECTION.StationaryMouseDown; } if (prevH != _movingH) { if (_movingH == MOVE_DIRECTION.MovingFwd) { SendCmd("P.1=" + textMaxPosH.Text); SendCmd("^.1"); } else if (_movingH == MOVE_DIRECTION.MovingBack) { SendCmd("P.1=0"); SendCmd("^.1"); } else { SendCmd(").1"); SendCmd("(.1"); } } } if (_movingV != MOVE_DIRECTION.Stationary) { MOVE_DIRECTION prevV = _movingV; int mid = imgJoystick.Height / 2; if (e.Y > mid + JOYSTICK_CENTRE #if HINEMOTORSETUP_DISABLE_CORNERS && _movingH == MOVE_DIRECTION.StationaryMouseDown #endif ) { _movingV = MOVE_DIRECTION.MovingBack; } else if (e.Y < mid - JOYSTICK_CENTRE #if HINEMOTORSETUP_DISABLE_CORNERS && _movingH == MOVE_DIRECTION.StationaryMouseDown #endif ) { _movingV = MOVE_DIRECTION.MovingFwd; } else { _movingV = MOVE_DIRECTION.StationaryMouseDown; } if (prevV != _movingV) { if (_movingV == MOVE_DIRECTION.MovingFwd) { SendCmd("P.2=" + textMaxPosV.Text); SendCmd("^.2"); } else if (_movingV == MOVE_DIRECTION.MovingBack) { SendCmd("P.2=0"); SendCmd("^.2"); } else { SendCmd(").2"); SendCmd("(.2"); } } } imgJoystick.Refresh(); } private void textPosH_Click(object sender, EventArgs e) { String rtn = ""; if (InputBox("Move Horizontal", "Enter target value:", ref rtn) == DialogResult.OK) { int val = 0; int maxVal = 0; if (Int32.TryParse(rtn, out val) && Int32.TryParse(textMaxPosH.Text, out maxVal)) { if (val > maxVal) val = maxVal; SendCmd("P.1=" + val.ToString()); SendCmd("^.1"); } } } private void textPosV_Click(object sender, EventArgs e) { String rtn = ""; if (InputBox("Move Vertical", "Enter target value:", ref rtn) == DialogResult.OK) { int val = 0; int maxVal = 0; if (Int32.TryParse(rtn, out val) && Int32.TryParse(textMaxPosV.Text, out maxVal)) { if (val > maxVal) val = maxVal; SendCmd("P.2=" + val.ToString()); SendCmd("^.2"); } } } private void hScrollSpeedH_Scroll(object sender, ScrollEventArgs e) { labelSetSpeedH.Text = "Set Speed = " + hScrollSpeedH.Value.ToString(); SendCmd("S.1=" + hScrollSpeedH.Value.ToString()); } private void hScrollSpeedV_Scroll(object sender, ScrollEventArgs e) { labelSetSpeedV.Text = "Set Speed = " + hScrollSpeedV.Value.ToString(); SendCmd("S.2=" + hScrollSpeedV.Value.ToString()); } private void HineMotorSetup_Deactivate(object sender, EventArgs e) { imgJoystick_MouseUp(sender, null); } private void HineMotorSetup_FormClosed(object sender, FormClosedEventArgs e) { #if (HINEMOTORSETUP_LOG_ALL_RX) _logStream.Close(); #endif } private void HineMotorSetup_FormClosing(object sender, FormClosingEventArgs e) { _bDisconnecting = true; if (btnConnect.Text == "Disconnect") { btnConnect_Click(sender, null); System.Threading.Thread.Sleep(100); } } private void HineMotorSetup_Load(object sender, EventArgs e) { } private void textOrigH_TextChanged(object sender, EventArgs e) { } private void imgJoystick_Click(object sender, EventArgs e) { } private void textMaxPosH_TextChanged(object sender, EventArgs e) { } } }
Jochen Arndt
Итак, вы ожидаете, что мы прочитаем это большое количество неформатированного кода и найдем части, которые отвечают за чтение и отображение позиций?
Пожалуйста, сократите свой код до этой части и отформатируйте его, используя соответствующую опцию в окне редактора. Тогда вы можете получить ответ здесь. Но имейте также в виду, что у нас не было вашего оборудования или спецификации протокола связи. Мы можем только проверить код, который Вы нам покажете.
Но вы можете сделать гораздо больше, потому что у вас есть оборудование и инструмент для проверки кода во время его выполнения: отладчик.
Установите точку останова в коде, который считывает позиции, а затем выполните код шаг за шагом, наблюдая за связанными переменными.
Member 13936585
Извините за длинный код. Спасибо за ваш совет, и я разрежу его на соответствующие разделы, где мне нужна помощь.