-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
95 lines (80 loc) · 3.08 KB
/
Program.cs
File metadata and controls
95 lines (80 loc) · 3.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
using System;
using System.IO;
using System.IO.Ports;
using Newtonsoft.Json;
class SerialPortLogger
{
private static SerialPort _serialPort;
private static string _logFile = "log.json";
static void Main()
{
Console.WriteLine("=== Настройка COM-порта ===");
string portName = Prompt("Имя порта", "COM9");
int baudRate = int.Parse(Prompt("BaudRate", "9600"));
int dataBits = int.Parse(Prompt("DataBits", "8"));
Parity parity = Enum.TryParse(Prompt("Parity (None, Even, Odd, Mark, Space)", "None"), out Parity p) ? p : Parity.None;
StopBits stopBits = Enum.TryParse(Prompt("StopBits (None, One, Two, OnePointFive)", "One"), out StopBits sb) ? sb : StopBits.One;
bool dtrEnable = Prompt("DTR Enable (true/false)", "false").ToLower() == "true";
bool rtsEnable = Prompt("RTS Enable (true/false)", "false").ToLower() == "true";
try
{
_serialPort = new SerialPort
{
PortName = portName,
BaudRate = baudRate,
DataBits = dataBits,
Parity = parity,
StopBits = stopBits,
DtrEnable = dtrEnable,
RtsEnable = rtsEnable,
NewLine = "\r\n",
ReadTimeout = 1000,
WriteTimeout = 1000
};
_serialPort.DataReceived += SerialDataReceived;
_serialPort.Open();
Console.WriteLine($"[{DateTime.Now}] Мониторинг {portName} начат. Нажмите Enter для остановки.");
Console.ReadLine();
_serialPort.Close();
}
catch (Exception ex)
{
Console.WriteLine($"Ошибка при открытии порта: {ex.Message}");
}
}
private static void SerialDataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
string data = _serialPort.ReadLine().Trim();
var logEntry = new LogEntry
{
Timestamp = DateTime.Now,
Message = data
};
AppendLog(logEntry);
Console.WriteLine($"[{logEntry.Timestamp:yyyy-MM-dd HH:mm:ss}] {logEntry.Message}");
}
catch (TimeoutException) { }
catch (Exception ex)
{
Console.WriteLine($"Ошибка чтения: {ex.Message}");
}
}
private static void AppendLog(LogEntry entry)
{
string jsonLine = JsonConvert.SerializeObject(entry);
File.AppendAllText(_logFile, jsonLine + Environment.NewLine);
}
private static string Prompt(string label, string defaultValue)
{
Console.Write($"{label} [{defaultValue}]: ");
var input = Console.ReadLine();
return string.IsNullOrWhiteSpace(input) ? defaultValue : input;
}
public class LogEntry
{
public DateTime Timestamp { get; set; }
public string Message { get; set; }
}
}