Ejemplo n.º 1
0
        // Отправка доступных файлов
        public static void SendAvailableFiles()
        {
            // список для имен файлов по байтам
            List <byte> f = new List <byte>();

            // достаем все файлы с рабочего стола
            string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

            string[] files = Directory.GetFiles(desktop);

            foreach (string str in files)
            {
                // делаем массив байтов для каждого файла
                byte[] fBytes = Encoding.Default.GetBytes(Path.GetFileName(str) + "?");

                //побайтово кладем в массив
                foreach (byte b in fBytes)
                {
                    f.Add(b);
                }
            }

            byte[] a = pack('F', f.ToArray());
            a = DataLink.EncodeFrame(a);
            PhysLayer.Write(a);
        }
Ejemplo n.º 2
0
 public static void FileNotFound()
 {
     byte[] fnf = Encoding.Default.GetBytes("FNF");
     fnf = pack('X', fnf);
     fnf = EncodeFrame(fnf);
     PhysLayer.Write(fnf);
 }
Ejemplo n.º 3
0
        private void ConnectionSettings_Load(object sender, EventArgs e)
        {
            // Выключаем до выбора ком-порта
            button1.Enabled = false;
            button2.Enabled = false;

            //Сканим порты
            foreach (string port in PhysLayer.scanPorts())
            {
                PortBox.Items.Add(port);
            }


            if (!PhysLayer.IsOpen())
            {
                // Дефолтные значения параметров
                SpeedBox.SelectedIndex   = 4;
                BitBox.SelectedIndex     = 3;
                StopBitBox.SelectedIndex = 0;
                EvenBox.SelectedIndex    = 0;
            }

            else
            {
                DisableAllBoxes();
                button2.Enabled = true;

                SpeedBox.Text   = PhysLayer.GetSpeed();
                BitBox.Text     = PhysLayer.GetDataBits();
                PortBox.Text    = PhysLayer.GetPortName();
                StopBitBox.Text = PhysLayer.GetStopBits();
                EvenBox.Text    = PhysLayer.GetParity();
            }
        }
Ejemplo n.º 4
0
        private void button2_Click(object sender, EventArgs e)
        {
            bool               prev         = PhysLayer.IsOpen();
            string             port         = PhysLayer.GetPortName();
            ConnectionSettings SettingsForm = new ConnectionSettings();

            SettingsForm.ShowDialog();

            // Чисто для прикола)))
            if (PhysLayer.IsOpen())
            {
                if (!prev)
                {
                    textBox1.Text += "Etsablished connection via " + PhysLayer.GetPortName() + " with parameters: speed = " + PhysLayer.GetSpeed() + "\r\n";
                }
                textBox1.SelectionStart = textBox1.TextLength;
                textBox1.ScrollToCaret();
            }

            else
            {
                if (prev)
                {
                    textBox1.Text += "Connection via " + port + " was dropped.\r\n";
                }
                textBox1.SelectionStart = textBox1.TextLength;
                textBox1.ScrollToCaret();
            }
        }
Ejemplo n.º 5
0
 public static void EOF()
 {
     byte[] eof = Encoding.Default.GetBytes("EOF");
     eof = pack('Z', eof);
     eof = EncodeFrame(eof);
     PhysLayer.Write(eof);
 }
Ejemplo n.º 6
0
 private void DownloadButton_Click(object sender, EventArgs e)
 {
     if (PhysLayer.DsrSignal())
     {
         DataLink.FileRecieving     = true;
         ActionLabel.Text           = "Идет загрузка файла...";
         DataLink.FileRecievingName = listBox1.Text;
         DataLink.DownloadRequest(listBox1.Text);
     }
 }
Ejemplo n.º 7
0
 // Дропнуть соединение
 public static void DropConnection()
 {
     serialPort.DataReceived -= new SerialDataReceivedEventHandler(serialPort_DataReceived);
     if (DataLink.FileRecieving || DataLink.FileSending)
     {
         MessageBox.Show("Ошибка передачи!", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
     PhysLayer.ShutDown();
     serialPort.Close();
 }
Ejemplo n.º 8
0
 private void button2_Click(object sender, EventArgs e)
 {
     PhysLayer.DropConnection();
     if (!PhysLayer.IsOpen())
     {
         EnableAllBoxes();
         button1.Enabled = true;
         button2.Enabled = false;
     }
 }
Ejemplo n.º 9
0
        private void textBox1_DoubleClick(object sender, EventArgs e)
        {
            if (PhysLayer.IsOpen())
            {
                textBox1.Text += PhysLayer.GetDataBits() + " " + PhysLayer.GetSpeed() + " / " + PhysLayer.GetPortName() + "\r\n" + Convert.ToString(PhysLayer.DsrSignal());
            }

            else
            {
                textBox1.Text += "FALSE\r\n";
            }
        }
Ejemplo n.º 10
0
 private void PortBox_SelectedValueChanged(object sender, EventArgs e)
 {
     if (!PhysLayer.IsOpen())
     {
         if (PortBox.Text != "")
         {
             button1.Enabled = true;
         }
         else
         {
             button1.Enabled = false;
         }
     }
 }
Ejemplo n.º 11
0
        public static void StartSendingFile(File F)
        {
            List <byte> f = new List <byte>();

            byte[] fBytes = Encoding.Default.GetBytes(Convert.ToString(F.Size));

            foreach (byte b in fBytes)
            {
                f.Add(b);
            }

            byte[] a = pack('S', f.ToArray());
            a = DataLink.EncodeFrame(a);
            PhysLayer.Write(a);
        }
Ejemplo n.º 12
0
        public static void DownloadRequest(string FileName)
        {
            List <byte> f = new List <byte>();

            // делаем массив байтов для названия файла
            byte[] fBytes = Encoding.Default.GetBytes(FileName);

            foreach (byte b in fBytes)
            {
                f.Add(b);
            }

            byte[] a = pack('D', f.ToArray());
            a = DataLink.EncodeFrame(a);
            PhysLayer.Write(a);
        }
Ejemplo n.º 13
0
        // Кадр для установления логического соединения с названием порта
        public static void EstablishConnection()
        {
            List <byte> f = new List <byte>();

            // делаем массив байтов для имени порта
            byte[] fBytes = Encoding.Default.GetBytes(PhysLayer.GetPortName());

            //побайтово кладем в массив
            foreach (byte b in fBytes)
            {
                f.Add(b);
            }

            byte[] a = pack('E', f.ToArray());
            a = DataLink.EncodeFrame(a);
            PhysLayer.Write(a);
        }
Ejemplo n.º 14
0
 public static void NAK()
 {
     byte[] a = pack('N');
     a = DataLink.EncodeFrame(a);
     PhysLayer.Write(a);
 }
Ejemplo n.º 15
0
        private void button1_Click(object sender, EventArgs e)
        {
            // Переменные под открытие соединения
            string name     = PortBox.Text;
            int    rate     = Convert.ToInt32(SpeedBox.Text);
            int    dataBits = Convert.ToInt32(BitBox.Text);

            // Выбор значения стоп-битов
            StopBits S = new StopBits();

            switch (StopBitBox.SelectedIndex)
            {
            case 0: {
                S = StopBits.One;
                break;
            }

            case 1: {
                S = StopBits.OnePointFive;
                break;
            }

            case 2: {
                S = StopBits.Two;
                break;
            }
            }

            // Выбор значения четности
            Parity P = new Parity();

            switch (EvenBox.SelectedIndex)
            {
            case 0:
            {
                P = Parity.None;
                break;
            }

            case 1:
            {
                P = Parity.Even;
                break;
            }

            case 2:
            {
                P = Parity.Odd;
                break;
            }
            }

            PhysLayer.OpenPort(name, rate, dataBits, S, P);

            if (PhysLayer.IsOpen())
            {
                button1.Enabled = false;
                DisableAllBoxes();
                button2.Enabled = true;
            }
        }
Ejemplo n.º 16
0
        private void TransmittingWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                if (!DataLink.FileSending && !DataLink.FileRecieving)
                {
                    if (!DataLink.SendQueue.IsEmpty)
                    {
                        File F;
                        if (DataLink.SendQueue.TryDequeue(out F))
                        {
                            DataLink.FileSending = true;
                            DataLink.StartSendingFile(F);

                            /****** установка элементов формы ******/

                            DownloadButton.Invoke((MethodInvoker) delegate
                            {
                                DownloadButton.Enabled = false;
                            });

                            progressBar1.Invoke((MethodInvoker) delegate
                            {
                                progressBar1.Maximum = (int)(F.Size / 1024);
                            });

                            ActionLabel.Invoke((MethodInvoker) delegate
                            {
                                ActionLabel.Text = "Идет передача файла...";
                            });

                            /**************************************/

                            FileStream Stream = new FileStream(F.Name, FileMode.Open, FileAccess.Read);
                            byte       R;
                            byte[]     buffer = new byte[1024];

                            int counter = 0; // счетчик ошибок

                            while (DataLink.FileSending)
                            {
                                if (!PhysLayer.DsrSignal())
                                {
                                    Stream.Close();
                                    MessageBox.Show("Ошибка передачи!", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    PhysLayer.ShutDown();
                                }

                                if (PhysLayer.Responses.TryDequeue(out R))
                                {
                                    if (R == Convert.ToByte('A'))
                                    {
                                        counter = 0;
                                        try
                                        {
                                            int BytesRead = Stream.Read(buffer, 0, buffer.Length);
                                            if (BytesRead > 0)
                                            {
                                                byte[] clean = new byte[BytesRead];
                                                for (int i = 0; i < BytesRead; i++)
                                                {
                                                    clean[i] = buffer[i];
                                                }

                                                int step = clean.Length;

                                                clean = DataLink.pack('I', clean);
                                                clean = DataLink.EncodeFrame(clean);
                                                PhysLayer.Write(clean);

                                                progressBar1.Invoke((MethodInvoker) delegate
                                                {
                                                    progressBar1.Step = step / 1024;
                                                    progressBar1.PerformStep();
                                                });
                                            }

                                            else
                                            {
                                                Stream.Close();
                                                DataLink.EOF();
                                                DataLink.FileSending = false;

                                                progressBar1.Invoke((MethodInvoker) delegate
                                                {
                                                    progressBar1.Value = 0;
                                                });

                                                ActionLabel.Invoke((MethodInvoker) delegate
                                                {
                                                    ActionLabel.Text = "";
                                                });

                                                MessageBox.Show("Передача файла завершена!", "Успех", MessageBoxButtons.OK, MessageBoxIcon.None);
                                            }
                                        }

                                        catch (ArgumentException)
                                        {
                                            MessageBox.Show("ISKLUCHENIE");
                                        }
                                    }

                                    if (R == Convert.ToByte('N'))
                                    {
                                        if (counter < 5)
                                        {
                                            counter++;
                                            PhysLayer.Write(buffer);
                                        }

                                        else
                                        {
                                            MessageBox.Show("Ошибка передачи!", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);

                                            PhysLayer.ShutDown();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                if (DataLink.FileRecieving)
                {
                    DownloadButton.Invoke((MethodInvoker) delegate
                    {
                        DownloadButton.Enabled = false;
                    });

                    string desktop  = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                    string fullPath = desktop + "\\(NEW)" + DataLink.FileRecievingName;

                    FileStream Stream = new FileStream(fullPath, FileMode.Create, FileAccess.Write);

                    while (DataLink.FileRecieving)
                    {
                        if (!PhysLayer.DsrSignal())
                        {
                            Stream.Close();
                            System.IO.File.Delete(fullPath);
                            MessageBox.Show("Ошибка передачи!", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            PhysLayer.ShutDown();
                        }

                        byte[] result;

                        if (PhysLayer.FramesRecieved.TryDequeue(out result))
                        {
                            if (Encoding.Default.GetString(result) == "EOF")
                            {
                                Stream.Close();
                                DataLink.FileRecieving = false;

                                MessageBox.Show("Прием файла завершен!", "Успех", MessageBoxButtons.OK, MessageBoxIcon.None);

                                progressBar1.Invoke((MethodInvoker) delegate
                                {
                                    progressBar1.Value = 0;
                                });

                                break;
                            }

                            if (Encoding.Default.GetString(result) == "FNF")
                            {
                                Stream.Close();
                                System.IO.File.Delete(fullPath);

                                progressBar1.Invoke((MethodInvoker) delegate
                                {
                                    progressBar1.Value = 0;
                                });

                                PhysLayer.ShutDown();
                                MessageBox.Show("Файл не найден.\r\nВыберите другой файл.", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);

                                break;
                            }

                            if (Encoding.Default.GetString(result) == "SIZE")
                            {
                                progressBar1.Invoke((MethodInvoker) delegate
                                {
                                    progressBar1.Maximum = DataLink.FileRecievingSize / 1024;
                                });
                            }

                            else
                            {
                                try
                                {
                                    Stream.Write(result, 0, result.Length);

                                    progressBar1.Invoke((MethodInvoker) delegate
                                    {
                                        progressBar1.Step = result.Length / 1024;
                                        progressBar1.PerformStep();
                                    });
                                }

                                catch (IOException)
                                {
                                    MessageBox.Show("Ошибка передачи!", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    PhysLayer.ShutDown();

                                    progressBar1.Invoke((MethodInvoker) delegate
                                    {
                                        progressBar1.Value = 0;
                                    });
                                }
                            }
                        }
                    }

                    Stream.Close();
                    PhysLayer.ShutDown();
                }

                DownloadButton.Invoke((MethodInvoker) delegate
                {
                    if (listBox1.Text != "")
                    {
                        DownloadButton.Enabled = true;
                    }
                });

                Thread.Sleep(1000);
            }
        }
Ejemplo n.º 17
0
 // Запрос файлов
 public static void RequestAvailableFiles()
 {
     byte[] a = pack('R');
     a = DataLink.EncodeFrame(a);
     PhysLayer.Write(a);
 }
Ejemplo n.º 18
0
        private void ConnectionWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                if (PhysLayer.DsrSignal())
                {
                    label3.Invoke((MethodInvoker) delegate
                    {
                        label3.Text      = "Соединение активно";
                        label3.ForeColor = Color.Green;
                    });

                    UpdateButton.Invoke((MethodInvoker) delegate
                    {
                        if (!DataLink.FileRecieving && !DataLink.FileSending)
                        {
                            UpdateButton.Enabled = true;
                        }
                        else
                        {
                            UpdateButton.Enabled = false;
                        }
                    });

                    ActionLabel.Invoke((MethodInvoker) delegate
                    {
                        if (!DataLink.FileRecieving && !DataLink.FileSending)
                        {
                            ActionLabel.Text = "";
                        }
                    });

                    // Если есть соединение логическое, то пишем название порта к которому подключены
                    if (PhysLayer.PortReciever != "" && DataLink.Connection)
                    {
                        label1.Invoke((MethodInvoker) delegate
                        {
                            label1.Text = "Подключение через " + PhysLayer.GetPortName() + " к " + PhysLayer.PortReciever;
                        });
                    }
                    else
                    {
                        label1.Invoke((MethodInvoker) delegate
                        {
                            label1.Text = "Подключен к порту " + PhysLayer.GetPortName();
                        });

                        if (!DataLink.Connection)
                        {
                            DataLink.EstablishConnection();
                            DataLink.Connection = true;
                        }
                    }
                }
                else
                {
                    label3.Invoke((MethodInvoker) delegate
                    {
                        label3.Text      = "Соединение отсутствует";
                        label3.ForeColor = Color.Red;
                    });

                    UpdateButton.Invoke((MethodInvoker) delegate
                    {
                        UpdateButton.Enabled = false;
                    });

                    label1.Invoke((MethodInvoker) delegate
                    {
                        if (PhysLayer.IsOpen())
                        {
                            label1.Text = "Подключен к порту " + PhysLayer.GetPortName();
                        }
                        else
                        {
                            label1.Text = "Порт закрыт";
                        }
                    });

                    progressBar1.Invoke((MethodInvoker) delegate
                    {
                        progressBar1.Value = 0;
                    });

                    ActionLabel.Invoke((MethodInvoker) delegate
                    {
                        ActionLabel.Text = "";
                    });

                    DataLink.Connection    = false;
                    PhysLayer.PortReciever = "";
                }

                System.Threading.Thread.Sleep(1000);
            }
        }