C # и RS485 / USB получают посторонние символы - PullRequest
0 голосов
/ 14 октября 2011

В моем проекте с шестью лазерными счетчиками частиц при отправке команд всегда возвращаются посторонние символы. И иногда полученная строка в форме эта неполная. Ниже приведен фрагмент кода: Кто знает, как это исправить?

/// <summary>
/// Class to keep track of string and color for lines in output window.
/// </summary>
private class Line
{
    public string Str;
    public Color ForeColor;
    public Line(string str, Color color)
    {
        Str = str;
        ForeColor = color;
    }
}

ArrayList lines = new ArrayList();
    Font origFont;
    Font monoFont;

public Form1()
    {
        InitializeComponent();
        outputList_Initialize();
    Settings.Read();
        TopMost = Settings.Option.StayOnTop;

    CommPort com = CommPort.Instance;
        com.StatusChanged += OnStatusChanged;
        com.DataReceived += OnDataReceived;
        com.Open();
}

 #region Event handling - data received and status changed

    /// <summary>
    /// Prepare a string for output by converting non-printable characters.
    /// </summary>
    /// <param name="StringIn">input string to prepare.</param>
    /// <returns>output string.</returns>
    private String PrepareData(String StringIn)
    {
        // The names of the first 32 characters
        string[] charNames = {
            // "NUL", "SOH", "STX", "ETX", "EOT",
            //"ENQ", "ACK", "BEL", "BS", "TAB", "LF", "VT", "FF", "CR", "SO", "SI",
            //"DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB", "CAN", "EM", "SUB",
            //"ESC", "FS", "GS", "RS", "US", "Space"
                             };

        string StringOut = "";

        foreach (char c in StringIn)
        {
            if (Settings.Option.HexOutput)
            {
                StringOut = StringOut + String.Format("{0:X2} ", (int)c);
            }
            else if (c < 32 && c != 9)
            {
                StringOut = StringOut + "";// +"<"+charNames[c]+">";

                //Uglier "Termite" style
                //StringOut = StringOut + String.Format("[{0:X2}]", (int)c);
            }
            else
            {
                StringOut = StringOut + c;
            }
        }
        return StringOut;
    }

    /// <summary>
    /// Partial line for AddData().
    /// </summary>
    private Line partialLine = null;

    /// <summary>
    /// Add data to the output.
    /// </summary>
    /// <param name="StringIn"></param>
    /// <returns></returns>
    private Line AddData(String StringIn)
    {
        String StringOut = PrepareData(StringIn);

        // if we have a partial line, add to it.
        if (partialLine != null)
        {
            // tack it on
            partialLine.Str = partialLine.Str + StringOut;
            outputList_Update(partialLine);
            return partialLine;
        }

        return outputList_Add(StringOut, receivedColor);
    }

    // delegate used for Invoke
    internal delegate void StringDelegate(string data);

    /// <summary>
    /// Handle data received event from serial port.
    /// </summary>
    /// <param name="data">incoming data</param>
    public void OnDataReceived(string dataIn)
    {
        //Handle multi-threading
        if (InvokeRequired)
        {
            Invoke(new StringDelegate(OnDataReceived), new object[] { dataIn });
            return;
        }

        // pause scrolling to speed up output of multiple lines
        bool saveScrolling = scrolling;
        scrolling = false;

        // if we detect a line terminator, add line to output
        int index;
        while (dataIn.Length > 0 &&
            ((index = dataIn.IndexOf("\r")) != -1 ||
            (index = dataIn.IndexOf("\n")) != -1))
        {
            String StringIn = dataIn.Substring(0, index);
            dataIn = dataIn.Remove(0, index + 1);

            logFile_writeLine(AddData(StringIn).Str);
            logFile_writeLine1(AddData(StringIn).Str);
            partialLine = null; // terminate partial line
        }

        // if we have data remaining, add a partial line
        if (dataIn.Length > 0)
        {
            partialLine = AddData(dataIn);
        }

        // restore scrolling
        scrolling = saveScrolling;
        outputList_Scroll();
        listBox1_Scroll();
    }

    /// <summary>
    /// Update the connection status
    /// </summary>
    public void OnStatusChanged(string status)
    {
        //Handle multi-threading
        if (InvokeRequired)
        {
            Invoke(new StringDelegate(OnStatusChanged), new object[] { status });
            return;
        }
        textBox1.Text = status;
    }

    #endregion

1 Ответ

1 голос
/ 14 октября 2011

Может ли это быть битовая (или байтовая) начинка?

...