private void portOnReceived(object sender, OnReceivedEventArgs e) { debugBox.Clear(); debugBox.Text += BitStuffing.ConvertBytesToBinaryString(e.Data); byte[] data = ParsePackage(e.Data); byte[] data1; int n; if (data[data.Length - 2] == 0) { data1 = new byte[data.Length - 3]; n = 2; } else { data1 = new byte[data.Length - 2]; n = 1; } for (int i = 1, j = 0; i < data.Length - n; i++, j++) { data1[j] = data[i]; } debugBox.Text += "\r\n"; foreach (byte bt in e.Data) { debugBox.Text += Convert.ToString(bt, 16) + " "; } debugBox.Text += "\r\n"; debugBox.Text += BitStuffing.ConvertBytesToBinaryString(data1); Encoding enc = Encoding.GetEncoding(1251); String buffer = enc.GetString(data1); textBox2.Text += buffer; }
private byte[] ParsePackage(byte[] package) { byte flag = 0; if (package[0] == Convert.ToByte("01111110", 2)) { flag = package[0]; } byte[] undecodeData = new byte[package.Length - 2]; for (int i = 1, j = 0; i < package.Length - 1; i++, j++) { undecodeData[j] = package[i]; } byte[] decodeData = BitStuffing.DecodeData(undecodeData); byte[] flagPart = new byte[] { flag }; List <byte> firstList = new List <byte>(flagPart); List <byte> middleList = new List <byte>(decodeData); List <byte> lastList = new List <byte>(flagPart); firstList.AddRange(middleList); firstList.AddRange(lastList); byte[] data = firstList.ToArray(); return(data); }
private byte[] CreatePackage(string message) { byte flag = Convert.ToByte("01111110", 2); byte[] bytesSent = Encoding.ASCII.GetBytes(message); byte[] dataAfterStuffing = BitStuffing.CodeData(bytesSent); byte[] flagPart = new byte[] { flag }; List <byte> firstList = new List <byte>(flagPart); List <byte> middleList = new List <byte>(dataAfterStuffing); List <byte> lastList = new List <byte>(flagPart); firstList.AddRange(middleList); firstList.AddRange(lastList); byte[] package = firstList.ToArray(); return(package); }
private void SendButton_Click(object sender, EventArgs e) { try { debugBox.Clear(); byte[] data; debugBox.Text += BitStuffing.ConvertBytesToBinaryString(Encoding.ASCII.GetBytes(textBox.Text)); data = CreatePackage(textBox.Text); port.serialPort_SendData(data); debugBox.Text += "\r\n"; foreach (byte bt in data) { debugBox.Text += Convert.ToString(bt, 16) + " "; } debugBox.Text += String.Format("\r\n"); debugBox.Text += BitStuffing.ConvertBytesToBinaryString(data); } catch (System.Exception exception) { MessageBox.Show(exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }