Guest User

Untitled

a guest
Apr 26th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 14.55 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9. using SerialComm;
  10. using System.Security.Cryptography;
  11. using COM;
  12.  
  13. namespace COM_Vasya {
  14.     public partial class Form1 : Form {
  15.         public Form1() {
  16.             InitializeComponent();
  17.         }
  18.         IntPtr HandleOut = IntPtr.Zero;
  19.         IntPtr HandleIn = IntPtr.Zero;
  20.         int count;
  21.         List<byte> block = new List<byte>();
  22.         Stack<TResult> st = new Stack<TResult>();
  23.  
  24.         public void Log(string s) {
  25.             edtLog.Lines = edtLog.Lines.Concat(new string[] {s}).ToArray();
  26.             edtLog.SelectionStart = edtLog.Text.Length;
  27.             edtLog.ScrollToCaret();
  28.         }
  29.  
  30.        
  31.         unsafe private void ReadBlock() {
  32.             List<byte> blockRead = new List<byte>();
  33.             byte[] buffer = new byte[count + 16];
  34.             while ((int)button1.Tag == 1)   {
  35.                 System.Threading.NativeOverlapped ol = new System.Threading.NativeOverlapped();
  36.                 fixed(byte* pb = buffer) {
  37.                     int n = 0;
  38.                     if (!NativeMethods.ReadFile(HandleIn, pb, buffer.Length, &n, ref ol))
  39.                         Log("Ошибка чтения из порта ");
  40.                     else  {
  41.                         if(n == 0) {
  42.                         } else if(n == buffer.Length) {
  43.                             blockRead = blockRead.Concat(buffer).ToList();
  44.                             TResult r = st.Pop();
  45.                             r.Stop();
  46.                             Log(r.Time);
  47.                             edtRead.Text = blockRead.Take(count).Select(p => p.ToString("X2") + " ").Aggregate((x, y) => x + y);
  48.                             if(verifyMd5Hash(blockRead.Take(count).ToArray(), blockRead.Skip(count).ToArray()))
  49.                                 Log("Ошибок нет");
  50.                             else
  51.                                 Log("Ошибки в пачке");
  52.                             blockRead.Clear();
  53.                             buffer = new byte[count + 16];
  54.                         } else {
  55.                             blockRead = blockRead.Concat(buffer.Take(n)).ToList();
  56.                             buffer = new byte[buffer.Length - n];
  57.                         }
  58.                     }
  59.                 }
  60.                 Application.DoEvents();
  61.             }
  62.         }
  63.  
  64.  
  65.         unsafe private void ReadByte() {
  66.             List<byte> blockRead = new List<byte>();
  67.             List<byte> HashRead = new List<byte>();
  68.             while((int)button1.Tag == 1) {
  69.                 System.Threading.NativeOverlapped ol = new System.Threading.NativeOverlapped();
  70.                 byte buffer;
  71.                 int n = 0;
  72.                 if(!NativeMethods.ReadFile(HandleIn, &buffer, 1, &n, ref ol))
  73.                     Log("Ошибка чтения из порта ");
  74.                 else {
  75.                     if(n == 1) {
  76.                         if(blockRead.Count < count) {
  77.                             TResult r = st.Pop();
  78.                             r.Stop();
  79.                             Log(r.Time);
  80.                             blockRead.Add(buffer);
  81.                             edtRead.Text += buffer.ToString("X2") + " ";
  82.                             edtRead.SelectionStart = edtRead.Text.Length;
  83.                             edtRead.ScrollToCaret();
  84.                         } else if(HashRead.Count < 16) {
  85.                             HashRead.Add(buffer);
  86.                             if(HashRead.Count == 16) {
  87.                                 TResult r = st.Pop();
  88.                                 r.Stop();
  89.                                 Log(r.Time);
  90.                                 if(verifyMd5Hash(blockRead.ToArray(), HashRead.ToArray()))
  91.                                     Log("Ошибок нет");
  92.                                 else
  93.                                     Log("Ошибки в пачке");
  94.                                 blockRead.Clear();
  95.                                 HashRead.Clear();
  96.                             }
  97.                         }
  98.                     }
  99.                 }
  100.                 Application.DoEvents();
  101.             }
  102.         }
  103.         private void Form1_Load(object sender, EventArgs e) {
  104.             cmbSpeed.Items.AddRange(new object[] { 1200, 2400, 4800, 9600, 14400, 19200 });
  105.             cmbIn.Items.AddRange(NativeMethods.GetPort().Select(p => (object)p).ToArray());
  106.             cmbOut.Items.AddRange(NativeMethods.GetPort().Select(p => (object)p).ToArray());
  107.             count = Convert.ToInt16(nudBlock.Value);
  108.            
  109.         }
  110.  
  111.         unsafe private void button1_Click(object sender, EventArgs e) {
  112.            
  113.             if (Convert.ToInt16(button1.Tag) == 0) {
  114.                
  115.                 try {
  116.                     HandleOut = CreatWritePort(cmbOut.Text.ToString(), Convert.ToInt16(cmbSpeed.Text));
  117.                     HandleIn = CreateReadPort(cmbIn.Text.ToString(), Convert.ToInt16(cmbSpeed.Text));
  118.                     if ((HandleOut == IntPtr.Zero) || (HandleIn == IntPtr.Zero)) {
  119.                         NativeMethods.CloseHandle(HandleOut);
  120.                         NativeMethods.CloseHandle(HandleIn);
  121.                         return;
  122.  
  123.                     }
  124.                 } catch {
  125.                     Log("Ошибка");
  126.                     return;                    
  127.                 }
  128.  
  129.                 timer1.Start();
  130.                 button1.Tag = 1;
  131.                 button1.Text = "Стоп";
  132.                 List<byte> blockRead = new List<byte>();
  133.                 List<byte> HashRead = new List<byte>();
  134.                 if (chbSendBlock.Checked)
  135.                     ReadBlock();
  136.                 else  
  137.                     ReadByte();
  138.             } else {
  139.                 timer1.Stop();
  140.                 button1.Tag = 0;
  141.                 button1.Text = "Старт";
  142.                 try {
  143.                     NativeMethods.CloseHandle(HandleOut);
  144.                     NativeMethods.CloseHandle(HandleIn);
  145.                 } catch {
  146.                 }
  147.             }
  148.         }
  149.  
  150.  
  151.  
  152.        
  153.         unsafe private IntPtr CreateReadPort(string port, int speed) {
  154.            
  155.             IntPtr result = NativeMethods.CreateFile(
  156.                                 @"\\.\" + port,
  157.                                 unchecked((Int32)NativeMethods.GENERIC_READ),
  158.                                 0,
  159.                                 (IntPtr)0,
  160.                                 NativeMethods.OPEN_EXISTING,
  161.                                 0,
  162.                                 (IntPtr)0
  163.                             );
  164.             if (result == IntPtr.Zero) {
  165.                 Log("Error: " + port + " не может быть открыт для чтения");
  166.                 return result ;
  167.             }
  168.             DCB lpDCB = new DCB();
  169.             if (!NativeMethods.GetCommState(result, ref lpDCB))
  170.             {
  171.                 Log( "Error:" + port + " Ошибка чтения структуры DCB " );
  172.                 NativeMethods.CloseHandle(result);
  173.                 return IntPtr.Zero;
  174.             };
  175.             NativeMethods.DCBSet(ref lpDCB, speed);
  176.  
  177.             if (!NativeMethods.SetCommState(result, ref lpDCB))
  178.             {
  179.                 Log( "Error:" + port + " ошибка записи структуры DCB ");
  180.                 NativeMethods.CloseHandle(result);
  181.                 return IntPtr.Zero;
  182.             }
  183.             COMMTIMEOUTS CommTimeOuts = new COMMTIMEOUTS();
  184.             NativeMethods.SetTimeOut(ref CommTimeOuts);
  185.             if (!NativeMethods.SetCommTimeouts(result, ref CommTimeOuts)) {
  186.                 Log("Error:" + port + " ошибка записи структуры COMMTIMEOUTS ");
  187.                 NativeMethods.CloseHandle(result);
  188.                 return IntPtr.Zero;
  189.  
  190.             }
  191.             Log( port + " открыт для чтения ");
  192.      
  193.             return result;
  194.         }
  195.  
  196.  
  197.         unsafe private IntPtr CreatWritePort(string port, int speed) {
  198.  
  199.             IntPtr result = NativeMethods.CreateFile(
  200.                                 @"\\.\" + port,
  201.                                 unchecked((Int32)NativeMethods.GENERIC_WRITE),
  202.                                 0,
  203.                                 (IntPtr)0,
  204.                                 NativeMethods.OPEN_EXISTING,
  205.                                 0,
  206.                                 (IntPtr)0
  207.                             );
  208.             if (result == IntPtr.Zero) {
  209.                 Log("Error: " + port + " не может быть открыт для записи" );
  210.                 return result;
  211.             }
  212.             DCB lpDCB = new DCB();
  213.             if (!NativeMethods.GetCommState(result, ref lpDCB)) {
  214.                 Log("Error:" + port + " ошибка чтения структуры DCB " );
  215.                 NativeMethods.CloseHandle(result);
  216.                 return IntPtr.Zero;
  217.             };
  218.             NativeMethods.DCBSet(ref lpDCB, speed);
  219.  
  220.             if (!NativeMethods.SetCommState(result, ref lpDCB)) {
  221.                 Log( "Error:" + port + " ошибка записи структуры DCB ");
  222.                 NativeMethods.CloseHandle(result);
  223.                 return IntPtr.Zero;
  224.             }
  225.             COMMTIMEOUTS CommTimeOuts = new COMMTIMEOUTS();
  226.             NativeMethods.SetTimeOut(ref CommTimeOuts);
  227.             if (!NativeMethods.SetCommTimeouts(result, ref CommTimeOuts)) {
  228.                 Log("Error:" + port + " ошибка записи структуры COMMTIMEOUTS ");
  229.                 NativeMethods.CloseHandle(result);
  230.                 return IntPtr.Zero;
  231.  
  232.             }
  233.  
  234.             Log(port + " открыт для записи " );
  235.             return result;
  236.         }
  237.  
  238.         private void timer1_Tick(object sender, EventArgs e) {
  239.             if(block.Count == 0)
  240.                 edtNewByte.Text = "";
  241.            
  242.             Random r = new Random();
  243.             byte b = (byte)r.Next(0, 256);
  244.             edtNewByte.Text += b.ToString("X2") + " ";
  245.             block.Add(b);
  246.             if (chbSendBlock.Checked)   {
  247.                 if (block.Count == count)  {
  248.                     edtSendByte.Text = "";
  249.                     Send(block.Concat(getMd5Hash(block.ToArray())).ToArray(), chbError.Checked);
  250.                     block.Clear();
  251.                 }
  252.             } else {
  253.                 Send(b, chbError.Checked);
  254.                 if (block.Count == count) {
  255.                     Send(getMd5Hash(block.ToArray()), chbError.Checked);
  256.                     block.Clear();
  257.                 }
  258.             }
  259.         }
  260.  
  261.        
  262.         unsafe private void Send(byte b, bool error) {
  263.             if(block.Count == 1) {
  264.                 edtSendByte.Text = "";
  265.             }
  266.            
  267.             if (error) {
  268.                 if ((new Random()).Next(0,7) > 4)
  269.                     b = (byte)(new Random()).Next(0, 256);
  270.             }
  271.             int n = 0;
  272.             edtSendByte.Text += b.ToString("X2")+" " ;
  273.             edtSendByte.SelectionStart = edtSendByte.Text.Length;
  274.             edtSendByte.ScrollToCaret();
  275.             st.Push(new TResult());
  276.             do {
  277.                 System.Threading.NativeOverlapped ol = new System.Threading.NativeOverlapped();
  278.                 if (!NativeMethods.WriteFile(HandleOut, &b, 1, &n, ref ol)) {
  279.                     Log("Пачка не отправлена");
  280.                     return;
  281.                 }
  282.             } while (n < 1);
  283.         }
  284.  
  285.         unsafe public void Send(byte[] buffer, bool error) {
  286.             if (error)
  287.             {
  288.                 for (int i = 0; i < buffer.Length; i++)
  289.                 {
  290.                     if ((new Random()).Next(0, 7) > 4)
  291.                         buffer[i] = (byte)(new Random()).Next(0, 256);
  292.                 }
  293.             }
  294.             Int32 n = 0;
  295.             edtSendByte.Text += buffer.Select(p => p.ToString("X2")+ " ").Aggregate((x, y) => x  + y) ;
  296.             edtSendByte.SelectionStart = edtSendByte.Text.Length;
  297.             edtSendByte.ScrollToCaret();
  298.             st.Push(new TResult());
  299.             fixed (byte* p = buffer) {
  300.             Send:
  301.                 System.Threading.NativeOverlapped ol = new System.Threading.NativeOverlapped();
  302.                 if (!NativeMethods.WriteFile(HandleOut, p, buffer.Length, &n, ref ol)) {
  303.                     Log("Пачка не отправлена");
  304.                     return;
  305.                 } else {
  306.                     if (n < buffer.Length) {
  307.                         buffer = buffer.Skip((int)n).ToArray();
  308.                         goto Send;
  309.                     }
  310.                 }
  311.             }
  312.            
  313.         }
  314.  
  315.         static byte[] getMd5Hash(byte[] input) {
  316.             MD5 obj = MD5.Create();
  317.             byte[] data = obj.ComputeHash(input);
  318.             obj.Dispose();
  319.             return data;
  320.         }
  321.  
  322.         static bool verifyMd5Hash(byte[] input, byte[] hash){
  323.             byte[] hashOfInput = getMd5Hash(input);
  324.             if(hashOfInput.Length == hash.Length) {
  325.                 for(int i = 0; i < hashOfInput.Length; i++) {
  326.                     if (hashOfInput[i] != hash[i])
  327.                         return false;
  328.                 }
  329.                 return true;
  330.             }
  331.             return false;
  332.         }
  333.  
  334.        
  335.  
  336.         private void nudTick_ValueChanged(object sender, EventArgs e) {
  337.             timer1.Interval = Convert.ToInt16(nudTick.Value);
  338.            
  339.         }
  340.  
  341.         private void nudBlock_ValueChanged(object sender, EventArgs e) {
  342.             count = Convert.ToInt16(nudBlock.Value);
  343.         }
  344.  
  345.  
  346.         private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
  347.             timer1.Stop();
  348.             button1.Tag = 0;
  349.         }
  350.  
  351.  
  352.  
  353.  
  354.     }
  355. }
  356.  
  357.  
  358.  
  359.  
  360.  
  361.         public static void DCBSet(ref DCB lpDCB, Int32 speed) {
  362.             lpDCB.BaudRate = speed;
  363.             lpDCB.StopBits = 0;
  364.             lpDCB.ByteSize = 8;
  365.             lpDCB.Parity = 0;
  366.             lpDCB.OutX = false;
  367.             lpDCB.InX = false;
  368.             lpDCB.XonChar = 0x11;
  369.             lpDCB.XoffChar = 0x13;
  370.             lpDCB.XoffLim = 100;
  371.             lpDCB.XonLim = 100;
  372.         }
  373.  
  374.         public static void SetTimeOut(ref COMMTIMEOUTS cto) {
  375.  
  376.             cto.ReadIntervalTimeout  = MAXDWORD;
  377.             cto.ReadTotalTimeoutMultiplier = 0;
  378.             cto.ReadTotalTimeoutConstant = 0;
  379.             cto.WriteTotalTimeoutMultiplier = 0;
  380.             cto.WriteTotalTimeoutConstant = 1000;
  381.         }
Add Comment
Please, Sign In to add comment