Skip to content

Commit

Permalink
使用串口枚举
Browse files Browse the repository at this point in the history
  • Loading branch information
nnhy committed Oct 30, 2023
1 parent 2f23611 commit 52c4b1d
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
2 changes: 1 addition & 1 deletion Samples/Serial2NetClientTest/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ private static void Main(string[] args)
var host = new A2();

// 配置并打开串口COM1
var serial = host.CreateSerial(1, 9600);
var serial = host.CreateSerial(Coms.COM1, 9600);
serial.DataReceived += OnReceiveSerial;
serial.Open();

Expand Down
28 changes: 22 additions & 6 deletions SmartA2/A2.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,22 @@

namespace SmartA2;

/// <summary>串口</summary>
public enum Coms
{
/// <summary>COM1</summary>
COM1,

/// <summary>COM2</summary>
COM2,

/// <summary>COM3</summary>
COM3,

/// <summary>COM4</summary>
COM4,
}

/// <summary>A2硬件工厂</summary>
public class A2
{
Expand Down Expand Up @@ -39,23 +55,23 @@ public class A2
/// <param name="baudrate"></param>
/// <returns></returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public SerialPort CreateSerial(Int32 com, Int32 baudrate = 9600)
public SerialPort CreateSerial(Coms com, Int32 baudrate = 9600)
{
if (com <= 0 || com > 4) throw new ArgumentOutOfRangeException(nameof(com), $"无效串口COM{com},支持COM1/COM2/COM3/COM4");
if (com < 0 || com > Coms.COM4) throw new ArgumentOutOfRangeException(nameof(com), $"无效串口{com},支持COM1/COM2/COM3/COM4");

return new SerialPort(ComNames[com - 1], baudrate);
return new SerialPort(ComNames[(Int32)com], baudrate);
}

/// <summary>创建Modbus</summary>
/// <param name="com"></param>
/// <param name="baudrate"></param>
/// <returns></returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public Modbus CreateModbus(Int32 com, Int32 baudrate = 9600)
public Modbus CreateModbus(Coms com, Int32 baudrate = 9600)
{
if (com <= 0 || com > 4) throw new ArgumentOutOfRangeException(nameof(com), $"无效串口COM{com},支持COM1/COM2/COM3/COM4");
if (com < 0 || com > Coms.COM4) throw new ArgumentOutOfRangeException(nameof(com), $"无效串口{com},支持COM1/COM2/COM3/COM4");

return new ModbusRtu { PortName = ComNames[com - 1], Baudrate = baudrate };
return new ModbusRtu { PortName = ComNames[(Int32)com], Baudrate = baudrate };
}
#endregion

Expand Down

0 comments on commit 52c4b1d

Please sign in to comment.