private static void ServerWork() { string strLabInfoServer = ""; DelegateForm1 delegateForm1LabInfoServer = delegate { myForm.labInfoServer.Text = strLabInfoServer; }; TcpListener listener = null; try { strLabInfoServer = "Запуск сервера на " + serverAddress + ":" + serverPort; myForm.Invoke(delegateForm1LabInfoServer); listener = new TcpListener(IPAddress.Parse(serverAddress), serverPort); listener.Start(); strLabInfoServer += "\nСервер запущен."; myForm.Invoke(delegateForm1LabInfoServer); while (myForm.isServerStart) { Thread.Sleep(9); // Пауза, чтобы не грузить поток. if (!listener.Pending()) { continue; } TcpClient client = listener.AcceptTcpClient(); NetworkStream stream = client.GetStream(); string message; if (!ThreadFeelDHT.BDHTTestOk) { message = "Датчик на сервере не обнаружен."; } else { message = "Датчик на сервере обнаружен. T=" + ThreadFeelDHT.T + ", H=" + ThreadFeelDHT.H + ".\n"; int t; int h; if ((!int.TryParse(ThreadFeelDHT.T, out t)) || (!int.TryParse(ThreadFeelDHT.H, out h))) { message += "Ошибка преобразования ThreadFeelDHT.T или ThreadFeelDHT.H из string в int!"; } else { if (t >= myForm.numTCrit.Value) { message += "Критическая температура! "; } if (h >= myForm.numHCrit.Value) { message += "Критическая влажность!"; } } } byte[] data = new byte[256]; // Буфер для отправляемых данных (символ Unicode - 2 байта). data = Encoding.Unicode.GetBytes(message); stream.Write(data, 0, data.Length); //*/ } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { if (listener != null) { listener.Stop(); strLabInfoServer = "Сервер остановлен."; myForm.Invoke(delegateForm1LabInfoServer); } } }
private static void ThreadPortsFeel() { try { long cycleCount = 0; string strFromUART, strOutLabel, strOutTextBox = ""; string[] myPort; DelegateForm1 delegateForm1TextBox = delegate { myForm.textBoxMsgPorts.Text = strOutTextBox; }; // Делегат для отображения инфы о портах. while (true) { myPort = System.IO.Ports.SerialPort.GetPortNames(); // в массив помещаем доступные порты strOutLabel = "Попытка поиска: " + (++cycleCount).ToString() + ". Найдено портов: " + myPort.Count().ToString(); myForm.Invoke(new DelegateForm1(() => myForm.labInfoPorts.Text = strOutLabel)); strOutTextBox = ""; myForm.Invoke(delegateForm1TextBox); if (myPort.Count() == 0) { strOutTextBox = "COM портов не найдено."; myForm.Invoke(delegateForm1TextBox); } try { for (int i = 0; i < myPort.Count(); i++) { myForm.serialPort1.Close(); strOutTextBox += "\r\n" + myPort[i] + " - "; myForm.Invoke(delegateForm1TextBox); try { myForm.serialPort1.PortName = myPort[i]; myForm.serialPort1.Open(); } catch { strOutTextBox += "соединение с портом отсутствует."; myForm.Invoke(delegateForm1TextBox); continue; } Thread.Sleep(3000); if (myForm.serialPort1.BytesToRead == 0) { strOutTextBox += "соединение есть, UART - молчит"; myForm.Invoke(delegateForm1TextBox); continue; } strFromUART = ""; while (myForm.serialPort1.BytesToRead > 0) { strFromUART += (char)myForm.serialPort1.ReadByte(); } if (strFromUART.IndexOf("DHT") >= 0) { strOutTextBox += "Устройство по UART обнаружено."; if (strFromUART.IndexOf("ERROR") >= 0) { strOutTextBox += " Ошибка датчика."; } else { strOutTextBox += " Датчик найден."; bDHTTestOk = true; } myForm.Invoke(delegateForm1TextBox); if (bDHTTestOk) { ThreadUARTFeel(); // Начинаем читать температуру и влажность. } } else { strOutTextBox += "Cоединение есть. Данные по UART не верные."; } myForm.Invoke(delegateForm1TextBox); } } catch { } Thread.Sleep(3000); } } catch { } finally { Finalization(); } }