using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
using System.IO;
using System.Threading;
public class PortChat
{
/*参数初始化*/
#region
private static byte xor = 0X02; //转义字符
private static string str = "";
private static string strSend = "";
private static string txtReceive = null; //存储接收的一帧字符
static SerialPort Com; //定义串口类
#endregion
private static void Main (string[] args)
{
/* 串口通讯参数配置*/
Com = new SerialPort ();
Com.BaudRate = 9600;
Com.PortName = "COM3";
Com.DataBits = 8;
Com.Open ();
StreamReader sr = new System.IO.StreamReader ("1.txt"); //打开根目录中的1.txt文档
str = "";
str = sr.ReadToEnd ();
str = str.Trim ();
int ilen = str.Length;
int m = 0;
int ibegin = 0;
int f = 0;
strSend = "";
ilen = ilen / 14;
m = ilen % 14;
/* 每帧数据中发送14个字符*/
for ( f = 0; f < ilen; f++ )
{
ibegin = f * 14;
strSend = str.Substring (ibegin, 14);
Send (strSend);
Receive ();
}
}
private static void Send (string strSend)
{
char[] chrData = strSend.ToCharArray ();
Byte[] Data = new Byte[chrData.Length + 8];
Data[0] = 0x7E; //帧首
int c = 2;
byte result = 0X00;
for ( Int32 index = 0; index < chrData.Length; index++ )
{
Data[c] = (Byte) chrData[index];
if ( Data[c] == 0X7E ) //判断字符串中是否有帧首
{
result = (byte) (Data[c] ^ xor);
Data[c] = 0X7D;
c++;
Data[c] = result;
}
else if ( Data[c] == 0X7D ) //判断字符串中是否有转义符
{
result = (byte) (Data[c] ^ xor);
Data[c] = 0X7D;
c++;
Data[c] = result;
}
else if ( Data[c] == 0X7F ) //判断字符串中是否有帧尾
{
result = (byte) (Data[c] ^ xor);
Data[c] = 0X7D;
c++;
Data[c] = result;
}
c++;
}
Data[c++] = 0;
Data[c] = 0X7F; //帧尾存储
Data[1] = (byte) (++c);
Byte[] SendData = new Byte[c];
for ( int k = 0; k < c; k++ )
{
SendData[k] = Data[k];
}
int sum = 0;
for ( int i = 0; i < SendData.Length - 2; i++ )
{
sum += SendData[i];
}
SendData[SendData.Length - 2] = (byte) (sum % 2);
Com.Write (SendData, 0, SendData.Length);
}
/* 数据接收函数定义*/
private static void Receive ()
{
byte[] receivedData = new byte[Com.BytesToRead]; //创建接收字节数组
Com.Read (receivedData, 0, receivedData.Length); //读取数据
Com.DiscardInBuffer ();
txtReceive = Encoding.Default.GetString (receivedData);
Console.WriteLine (txtReceive);
//Console.WriteLine ("OK");
}
}