Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using SerialComm;
- using System.Security.Cryptography;
- using COM;
- namespace COM_Vasya {
- public partial class Form1 : Form {
- public Form1() {
- InitializeComponent();
- }
- IntPtr HandleOut = IntPtr.Zero;
- IntPtr HandleIn = IntPtr.Zero;
- int count;
- List<byte> block = new List<byte>();
- Stack<TResult> st = new Stack<TResult>();
- public void Log(string s) {
- edtLog.Lines = edtLog.Lines.Concat(new string[] {s}).ToArray();
- edtLog.SelectionStart = edtLog.Text.Length;
- edtLog.ScrollToCaret();
- }
- unsafe private void ReadBlock() {
- List<byte> blockRead = new List<byte>();
- byte[] buffer = new byte[count + 16];
- while ((int)button1.Tag == 1) {
- System.Threading.NativeOverlapped ol = new System.Threading.NativeOverlapped();
- fixed(byte* pb = buffer) {
- int n = 0;
- if (!NativeMethods.ReadFile(HandleIn, pb, buffer.Length, &n, ref ol))
- Log("Ошибка чтения из порта ");
- else {
- if(n == 0) {
- } else if(n == buffer.Length) {
- blockRead = blockRead.Concat(buffer).ToList();
- TResult r = st.Pop();
- r.Stop();
- Log(r.Time);
- edtRead.Text = blockRead.Take(count).Select(p => p.ToString("X2") + " ").Aggregate((x, y) => x + y);
- if(verifyMd5Hash(blockRead.Take(count).ToArray(), blockRead.Skip(count).ToArray()))
- Log("Ошибок нет");
- else
- Log("Ошибки в пачке");
- blockRead.Clear();
- buffer = new byte[count + 16];
- } else {
- blockRead = blockRead.Concat(buffer.Take(n)).ToList();
- buffer = new byte[buffer.Length - n];
- }
- }
- }
- Application.DoEvents();
- }
- }
- unsafe private void ReadByte() {
- List<byte> blockRead = new List<byte>();
- List<byte> HashRead = new List<byte>();
- while((int)button1.Tag == 1) {
- System.Threading.NativeOverlapped ol = new System.Threading.NativeOverlapped();
- byte buffer;
- int n = 0;
- if(!NativeMethods.ReadFile(HandleIn, &buffer, 1, &n, ref ol))
- Log("Ошибка чтения из порта ");
- else {
- if(n == 1) {
- if(blockRead.Count < count) {
- TResult r = st.Pop();
- r.Stop();
- Log(r.Time);
- blockRead.Add(buffer);
- edtRead.Text += buffer.ToString("X2") + " ";
- edtRead.SelectionStart = edtRead.Text.Length;
- edtRead.ScrollToCaret();
- } else if(HashRead.Count < 16) {
- HashRead.Add(buffer);
- if(HashRead.Count == 16) {
- TResult r = st.Pop();
- r.Stop();
- Log(r.Time);
- if(verifyMd5Hash(blockRead.ToArray(), HashRead.ToArray()))
- Log("Ошибок нет");
- else
- Log("Ошибки в пачке");
- blockRead.Clear();
- HashRead.Clear();
- }
- }
- }
- }
- Application.DoEvents();
- }
- }
- private void Form1_Load(object sender, EventArgs e) {
- cmbSpeed.Items.AddRange(new object[] { 1200, 2400, 4800, 9600, 14400, 19200 });
- cmbIn.Items.AddRange(NativeMethods.GetPort().Select(p => (object)p).ToArray());
- cmbOut.Items.AddRange(NativeMethods.GetPort().Select(p => (object)p).ToArray());
- count = Convert.ToInt16(nudBlock.Value);
- }
- unsafe private void button1_Click(object sender, EventArgs e) {
- if (Convert.ToInt16(button1.Tag) == 0) {
- try {
- HandleOut = CreatWritePort(cmbOut.Text.ToString(), Convert.ToInt16(cmbSpeed.Text));
- HandleIn = CreateReadPort(cmbIn.Text.ToString(), Convert.ToInt16(cmbSpeed.Text));
- if ((HandleOut == IntPtr.Zero) || (HandleIn == IntPtr.Zero)) {
- NativeMethods.CloseHandle(HandleOut);
- NativeMethods.CloseHandle(HandleIn);
- return;
- }
- } catch {
- Log("Ошибка");
- return;
- }
- timer1.Start();
- button1.Tag = 1;
- button1.Text = "Стоп";
- List<byte> blockRead = new List<byte>();
- List<byte> HashRead = new List<byte>();
- if (chbSendBlock.Checked)
- ReadBlock();
- else
- ReadByte();
- } else {
- timer1.Stop();
- button1.Tag = 0;
- button1.Text = "Старт";
- try {
- NativeMethods.CloseHandle(HandleOut);
- NativeMethods.CloseHandle(HandleIn);
- } catch {
- }
- }
- }
- unsafe private IntPtr CreateReadPort(string port, int speed) {
- IntPtr result = NativeMethods.CreateFile(
- @"\\.\" + port,
- unchecked((Int32)NativeMethods.GENERIC_READ),
- 0,
- (IntPtr)0,
- NativeMethods.OPEN_EXISTING,
- 0,
- (IntPtr)0
- );
- if (result == IntPtr.Zero) {
- Log("Error: " + port + " не может быть открыт для чтения");
- return result ;
- }
- DCB lpDCB = new DCB();
- if (!NativeMethods.GetCommState(result, ref lpDCB))
- {
- Log( "Error:" + port + " Ошибка чтения структуры DCB " );
- NativeMethods.CloseHandle(result);
- return IntPtr.Zero;
- };
- NativeMethods.DCBSet(ref lpDCB, speed);
- if (!NativeMethods.SetCommState(result, ref lpDCB))
- {
- Log( "Error:" + port + " ошибка записи структуры DCB ");
- NativeMethods.CloseHandle(result);
- return IntPtr.Zero;
- }
- COMMTIMEOUTS CommTimeOuts = new COMMTIMEOUTS();
- NativeMethods.SetTimeOut(ref CommTimeOuts);
- if (!NativeMethods.SetCommTimeouts(result, ref CommTimeOuts)) {
- Log("Error:" + port + " ошибка записи структуры COMMTIMEOUTS ");
- NativeMethods.CloseHandle(result);
- return IntPtr.Zero;
- }
- Log( port + " открыт для чтения ");
- return result;
- }
- unsafe private IntPtr CreatWritePort(string port, int speed) {
- IntPtr result = NativeMethods.CreateFile(
- @"\\.\" + port,
- unchecked((Int32)NativeMethods.GENERIC_WRITE),
- 0,
- (IntPtr)0,
- NativeMethods.OPEN_EXISTING,
- 0,
- (IntPtr)0
- );
- if (result == IntPtr.Zero) {
- Log("Error: " + port + " не может быть открыт для записи" );
- return result;
- }
- DCB lpDCB = new DCB();
- if (!NativeMethods.GetCommState(result, ref lpDCB)) {
- Log("Error:" + port + " ошибка чтения структуры DCB " );
- NativeMethods.CloseHandle(result);
- return IntPtr.Zero;
- };
- NativeMethods.DCBSet(ref lpDCB, speed);
- if (!NativeMethods.SetCommState(result, ref lpDCB)) {
- Log( "Error:" + port + " ошибка записи структуры DCB ");
- NativeMethods.CloseHandle(result);
- return IntPtr.Zero;
- }
- COMMTIMEOUTS CommTimeOuts = new COMMTIMEOUTS();
- NativeMethods.SetTimeOut(ref CommTimeOuts);
- if (!NativeMethods.SetCommTimeouts(result, ref CommTimeOuts)) {
- Log("Error:" + port + " ошибка записи структуры COMMTIMEOUTS ");
- NativeMethods.CloseHandle(result);
- return IntPtr.Zero;
- }
- Log(port + " открыт для записи " );
- return result;
- }
- private void timer1_Tick(object sender, EventArgs e) {
- if(block.Count == 0)
- edtNewByte.Text = "";
- Random r = new Random();
- byte b = (byte)r.Next(0, 256);
- edtNewByte.Text += b.ToString("X2") + " ";
- block.Add(b);
- if (chbSendBlock.Checked) {
- if (block.Count == count) {
- edtSendByte.Text = "";
- Send(block.Concat(getMd5Hash(block.ToArray())).ToArray(), chbError.Checked);
- block.Clear();
- }
- } else {
- Send(b, chbError.Checked);
- if (block.Count == count) {
- Send(getMd5Hash(block.ToArray()), chbError.Checked);
- block.Clear();
- }
- }
- }
- unsafe private void Send(byte b, bool error) {
- if(block.Count == 1) {
- edtSendByte.Text = "";
- }
- if (error) {
- if ((new Random()).Next(0,7) > 4)
- b = (byte)(new Random()).Next(0, 256);
- }
- int n = 0;
- edtSendByte.Text += b.ToString("X2")+" " ;
- edtSendByte.SelectionStart = edtSendByte.Text.Length;
- edtSendByte.ScrollToCaret();
- st.Push(new TResult());
- do {
- System.Threading.NativeOverlapped ol = new System.Threading.NativeOverlapped();
- if (!NativeMethods.WriteFile(HandleOut, &b, 1, &n, ref ol)) {
- Log("Пачка не отправлена");
- return;
- }
- } while (n < 1);
- }
- unsafe public void Send(byte[] buffer, bool error) {
- if (error)
- {
- for (int i = 0; i < buffer.Length; i++)
- {
- if ((new Random()).Next(0, 7) > 4)
- buffer[i] = (byte)(new Random()).Next(0, 256);
- }
- }
- Int32 n = 0;
- edtSendByte.Text += buffer.Select(p => p.ToString("X2")+ " ").Aggregate((x, y) => x + y) ;
- edtSendByte.SelectionStart = edtSendByte.Text.Length;
- edtSendByte.ScrollToCaret();
- st.Push(new TResult());
- fixed (byte* p = buffer) {
- Send:
- System.Threading.NativeOverlapped ol = new System.Threading.NativeOverlapped();
- if (!NativeMethods.WriteFile(HandleOut, p, buffer.Length, &n, ref ol)) {
- Log("Пачка не отправлена");
- return;
- } else {
- if (n < buffer.Length) {
- buffer = buffer.Skip((int)n).ToArray();
- goto Send;
- }
- }
- }
- }
- static byte[] getMd5Hash(byte[] input) {
- MD5 obj = MD5.Create();
- byte[] data = obj.ComputeHash(input);
- obj.Dispose();
- return data;
- }
- static bool verifyMd5Hash(byte[] input, byte[] hash){
- byte[] hashOfInput = getMd5Hash(input);
- if(hashOfInput.Length == hash.Length) {
- for(int i = 0; i < hashOfInput.Length; i++) {
- if (hashOfInput[i] != hash[i])
- return false;
- }
- return true;
- }
- return false;
- }
- private void nudTick_ValueChanged(object sender, EventArgs e) {
- timer1.Interval = Convert.ToInt16(nudTick.Value);
- }
- private void nudBlock_ValueChanged(object sender, EventArgs e) {
- count = Convert.ToInt16(nudBlock.Value);
- }
- private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
- timer1.Stop();
- button1.Tag = 0;
- }
- }
- }
- public static void DCBSet(ref DCB lpDCB, Int32 speed) {
- lpDCB.BaudRate = speed;
- lpDCB.StopBits = 0;
- lpDCB.ByteSize = 8;
- lpDCB.Parity = 0;
- lpDCB.OutX = false;
- lpDCB.InX = false;
- lpDCB.XonChar = 0x11;
- lpDCB.XoffChar = 0x13;
- lpDCB.XoffLim = 100;
- lpDCB.XonLim = 100;
- }
- public static void SetTimeOut(ref COMMTIMEOUTS cto) {
- cto.ReadIntervalTimeout = MAXDWORD;
- cto.ReadTotalTimeoutMultiplier = 0;
- cto.ReadTotalTimeoutConstant = 0;
- cto.WriteTotalTimeoutMultiplier = 0;
- cto.WriteTotalTimeoutConstant = 1000;
- }
Add Comment
Please, Sign In to add comment