├── test
├── GodSharp.SerialPort.ConsoleSample
│ ├── app.config
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ ├── Program.cs
│ └── GodSharp.SerialPort.ConsoleSample.csproj
├── GodSharp.SerialPort.Tests
│ ├── packages.config
│ ├── SerialClassTests.cs
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ └── GodSharp.SerialPort.Tests.csproj
└── GodSharp.SerialPort.NetCore.ConsoleSample
│ ├── GodSharp.SerialPort.NetCore.ConsoleSample.csproj
│ └── Program.cs
├── src
└── GodSharp.SerialPort
│ ├── Enums
│ └── SerialPortDataFormat.cs
│ ├── Extensions
│ ├── StringExtension.cs
│ └── ByteExtension.cs
│ ├── Core
│ ├── GodSerialPort.Event.cs
│ ├── GodSerialPort.Static.cs
│ ├── SerialConfigOptions.cs
│ └── GodSerialPort.cs
│ └── GodSharp.SerialPort.csproj
├── LICENSE
├── appveyor.yml
├── README.md
├── GodSharp.SerialPort.sln
└── .gitignore
/test/GodSharp.SerialPort.ConsoleSample/app.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/test/GodSharp.SerialPort.Tests/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/src/GodSharp.SerialPort/Enums/SerialPortDataFormat.cs:
--------------------------------------------------------------------------------
1 | namespace GodSharp.SerialPort.Enums
2 | {
3 | ///
4 | /// serialport data format
5 | ///
6 | public enum SerialPortDataFormat
7 | {
8 | ///
9 | /// Normal string
10 | ///
11 | Char,
12 | ///
13 | /// Hex string
14 | ///
15 | Hex
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/test/GodSharp.SerialPort.NetCore.ConsoleSample/GodSharp.SerialPort.NetCore.ConsoleSample.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp2.0
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/src/GodSharp.SerialPort/Extensions/StringExtension.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | // ReSharper disable SuggestVarOrType_Elsewhere
3 | // ReSharper disable SuggestVarOrType_BuiltInTypes
4 |
5 | namespace GodSharp.SerialPort.Extensions
6 | {
7 | ///
8 | /// String extension methods class.
9 | ///
10 | public partial class Extension
11 | {
12 | ///
13 | /// Hexadecimal string to an byte array.
14 | ///
15 | /// The hex string.
16 | /// An byte array.
17 | public static byte[] HexToByte(this string hex)
18 | {
19 | // remove space
20 | hex = hex.Replace(" ", "");
21 |
22 | byte[] bytes = new byte[hex.Length / 2];
23 | for (int i = 0; i < hex.Length; i += 2)
24 | {
25 | bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
26 | }
27 | return bytes;
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2017 GodSharp
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/src/GodSharp.SerialPort/Extensions/ByteExtension.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | // ReSharper disable SuggestVarOrType_Elsewhere
3 | // ReSharper disable LoopCanBeConvertedToQuery
4 | // ReSharper disable SuggestVarOrType_BuiltInTypes
5 |
6 | namespace GodSharp.SerialPort.Extensions
7 | {
8 | ///
9 | /// Byte extension methods class.
10 | ///
11 | public static partial class Extension
12 | {
13 | ///
14 | /// Bytes to hexadecimal.
15 | ///
16 | /// The byte array.
17 | /// The separator,default is space
18 | /// String of hex.
19 | public static string ToHexString(this byte[] bytes,string separator=" ")
20 | {
21 | if (bytes==null||bytes.Length<1)
22 | {
23 | return null;
24 | }
25 |
26 | List list = new List();
27 | foreach (byte b in bytes)
28 | {
29 | list.Add(b.ToString("X2"));
30 | }
31 |
32 | return string.Join(separator, list.ToArray());
33 | }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/appveyor.yml:
--------------------------------------------------------------------------------
1 | version: 1.2.0.{build}
2 | branches:
3 | only:
4 | - master
5 | - release
6 | - dev
7 | skip_branch_with_pr: true
8 | image: Visual Studio 2017
9 | configuration: Release
10 | platform: Any CPU
11 | clone_folder: c:\projects\godsharp.serialport
12 | install:
13 | - cmd: nuget restore
14 | nuget:
15 | account_feed: true
16 | project_feed: true
17 | build:
18 | project: GodSharp.SerialPort.sln
19 | publish_nuget: false
20 | include_nuget_references: true
21 | verbosity: minimal
22 | test: off
23 | artifacts:
24 | - path: test\GodSharp.SerialPort.ConsoleSample\bin\$(configuration)\
25 | name: GodSharp.SerialPort.ConsoleSample-v$(appveyor_build_version)
26 | - path: 'output\**\*.nupkg'
27 | name: nuget
28 | deploy:
29 | - provider: NuGet
30 | server: https://www.nuget.org/api/v2/package
31 | api_key:
32 | secure: s388/c8yQWnGyZ9v9cUDfBe4ud6MFl/ouUEEBruiN5j5+LjSQ4giGKMKuLuvglS1
33 | artifact: /.*\.nupkg/
34 | on:
35 | branch: /(release)|(dev)/
36 | - provider: NuGet
37 | server: https://www.myget.org/F/godsharp/api/v2/package
38 | api_key:
39 | secure: CKm5m2qGYNYnh5yDUE2zKfN+JKBmO5xmtG80AP0yni9yPBqDOaRQ48Y/4k8KGo2y
40 | artifact: /.*\.nupkg/
41 | on:
42 | branch: /(release)|(dev)/
43 | - provider: GitHub
44 | description: Release.
45 | auth_token:
46 | secure: uCHTzET52dtiexqTKhgQmup+EBGZs1Afw6eBMfvN4PbQ720YaybNd890Y96ISZ0T
47 | artifact: /.*\.(?:nupkg|zip)/
48 | draft: true
49 | force_update: true
50 | on:
51 | branch: /(release)|(dev)/
--------------------------------------------------------------------------------
/test/GodSharp.SerialPort.Tests/SerialClassTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using GodSharp.SerialPort.Extensions;
3 | using Microsoft.VisualStudio.TestTools.UnitTesting;
4 |
5 | namespace GodSharp.Tests
6 | {
7 | [TestClass()]
8 | public class SerialClassTests
9 | {
10 | [TestMethod()]
11 | public void HexToByteTest()
12 | {
13 | byte[] bytes;
14 | bytes = "58 16 37".HexToByte();
15 | foreach (var item in bytes)
16 | {
17 | Console.WriteLine(item);
18 | }
19 | bytes ="581637".HexToByte();
20 | Console.WriteLine("no space");
21 | foreach (var item in bytes)
22 | {
23 | Console.WriteLine(item);
24 | }
25 | }
26 |
27 | [TestMethod()]
28 | public void SerialValueTest()
29 | {
30 | System.IO.Ports.SerialPort port = new System.IO.Ports.SerialPort();
31 | Console.WriteLine("PortName:" + port.PortName);
32 | Console.WriteLine("BaudRate:" + port.BaudRate);
33 | Console.WriteLine("Parity:" + port.Parity);
34 | Console.WriteLine("DataBits:" + port.DataBits);
35 | Console.WriteLine("StopBits:" + port.StopBits);
36 | Console.WriteLine("Handshake:" + port.Handshake);
37 | Console.WriteLine("ReadBufferSize:" + port.ReadBufferSize);
38 | Console.WriteLine("WriteBufferSize:" + port.WriteBufferSize);
39 | }
40 | }
41 | }
--------------------------------------------------------------------------------
/test/GodSharp.SerialPort.Tests/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("GodSharp.SerialPort.Tests")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("GodSharp.SerialPort.Tests")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("de27ffb1-2029-4ff5-892e-6f4274460cf1")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/test/GodSharp.SerialPort.ConsoleSample/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("GodSharp.SerialPort.ConsoleSample")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("GodSharp.SerialPort.ConsoleSample")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("64a904fc-399a-4d07-99f5-1b5ccd9ff17a")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/test/GodSharp.SerialPort.NetCore.ConsoleSample/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using GodSharp.SerialPort;
3 |
4 | namespace GodSharp.NetCore.ConsoleSample
5 | {
6 | class Program
7 | {
8 | static void Main(string[] args)
9 | {
10 | Console.Write("input serialport name:");
11 | string read = Console.ReadLine();
12 |
13 | if (string.IsNullOrWhiteSpace(read))
14 | {
15 | Exit();
16 | }
17 |
18 | GodSerialPort gsp = new GodSerialPort(x => {
19 | x.PortName = read;
20 | });
21 |
22 | gsp.UseDataReceived(true, (sp, bytes) => {
23 | if (bytes != null && bytes.Length > 0)
24 | {
25 | string buffer = string.Join(" ", bytes);
26 | Console.WriteLine("receive data:" + buffer);
27 | }
28 | });
29 |
30 | bool flag = gsp.Open();
31 |
32 | if (!flag)
33 | {
34 | Exit();
35 | }
36 |
37 | Console.WriteLine("serialport opend");
38 |
39 | Console.WriteLine("press any thing as data to send,press key 'q' to quit.");
40 |
41 | string data = null;
42 | while (data == null || data.ToLower() != "q")
43 | {
44 | if (!string.IsNullOrEmpty(data))
45 | {
46 | Console.WriteLine("send data:" + data);
47 | gsp.WriteAsciiString(data);
48 | }
49 | data = Console.ReadLine();
50 | }
51 | }
52 |
53 | static void Exit()
54 | {
55 | Console.WriteLine("press any key to quit.");
56 | Console.ReadKey();
57 | Environment.Exit(0);
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/test/GodSharp.SerialPort.ConsoleSample/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | // ReSharper disable RedundantArgumentDefaultValue
4 | namespace GodSharp.SerialPort.ConsoleSample
5 | {
6 | class Program
7 | {
8 | // ReSharper disable once UnusedParameter.Local
9 | static void Main(string[] args)
10 | {
11 | Console.Write("input serialport name:");
12 | string read = Console.ReadLine();
13 |
14 | if (string.IsNullOrWhiteSpace(read))
15 | {
16 | Exit();
17 | }
18 |
19 | GodSerialPort gsp = new GodSerialPort(x=> {
20 | x.PortName = read;
21 | });
22 |
23 | gsp.UseDataReceived(true,(sp,bytes) => {
24 | if (bytes!=null&&bytes.Length>0)
25 | {
26 | string buffer = string.Join(" ", bytes);
27 | Console.WriteLine("receive data:" + buffer);
28 | }
29 | });
30 |
31 | bool flag = gsp.Open();
32 |
33 | if (!flag)
34 | {
35 | Exit();
36 | }
37 |
38 | Console.WriteLine("serialport opend");
39 |
40 | Console.WriteLine("press any thing as data to send,press key 'q' to quit.");
41 |
42 | string data = null;
43 | while (data == null || data.ToLower()!="q")
44 | {
45 | if (!string.IsNullOrEmpty(data))
46 | {
47 | Console.WriteLine("send data:"+data);
48 | gsp.WriteAsciiString(data);
49 | }
50 | data = Console.ReadLine();
51 | }
52 | }
53 |
54 | static void Exit()
55 | {
56 | Console.WriteLine("press any key to quit.");
57 | Console.ReadKey();
58 | Environment.Exit(0);
59 | }
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/GodSharp.SerialPort/Core/GodSerialPort.Event.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO.Ports;
3 | // ReSharper disable SuggestVarOrType_Elsewhere
4 |
5 | // ReSharper disable once CheckNamespace
6 | namespace GodSharp.SerialPort
7 | {
8 | public partial class GodSerialPort
9 | {
10 | #region DataReceived event
11 | ///
12 | /// Handles the DataReceived event of the SerialPort.
13 | ///
14 | /// The source of the event.
15 | /// The instance containing the event data.
16 | private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
17 | {
18 | try
19 | {
20 | byte[] bytes = TryRead();
21 | OnData?.Invoke(this, bytes);
22 | }
23 | catch (Exception ex)
24 | {
25 | Console.WriteLine(ex.Message);
26 | }
27 | }
28 |
29 | #endregion
30 |
31 | #region ErrorReceived event
32 | ///
33 | /// Handles the ErrorReceived event of the SerialPort.
34 | ///
35 | /// The source of the event.
36 | /// The instance containing the event data.
37 | private void SerialPort_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
38 | {
39 | try
40 | {
41 | onError?.Invoke(this, e.EventType);
42 | }
43 | catch (Exception ex)
44 | {
45 | Console.WriteLine(ex.Message);
46 | }
47 | }
48 |
49 | #endregion
50 |
51 | #region PinChanged event
52 | ///
53 | /// Handles the PinChanged event of the SerialPort.
54 | ///
55 | /// The source of the event.
56 | /// The instance containing the event data.
57 | private void SerialPort_PinChanged(object sender, SerialPinChangedEventArgs e)
58 | {
59 | try
60 | {
61 | onPinChange?.Invoke(this, e.EventType);
62 | }
63 | catch (Exception ex)
64 | {
65 | Console.WriteLine(ex.Message);
66 | }
67 | }
68 |
69 | #endregion
70 | }
71 | }
--------------------------------------------------------------------------------
/test/GodSharp.SerialPort.ConsoleSample/GodSharp.SerialPort.ConsoleSample.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {64A904FC-399A-4D07-99F5-1B5CCD9FF17A}
8 | Exe
9 | GodSharp.SerialPort.ConsoleSample
10 | GodSharp.SerialPort.ConsoleSample
11 | v4.5
12 | 512
13 |
14 |
15 |
16 | AnyCPU
17 | true
18 | full
19 | false
20 | bin\Debug\
21 | DEBUG;TRACE
22 | prompt
23 | 4
24 | false
25 |
26 |
27 | AnyCPU
28 | pdbonly
29 | true
30 | bin\Release\
31 | TRACE
32 | prompt
33 | 4
34 | false
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 | {4006dd01-8b21-4246-a7cf-a15421738486}
46 | GodSharp.SerialPort
47 |
48 |
49 |
50 |
51 |
52 |
53 |
--------------------------------------------------------------------------------
/src/GodSharp.SerialPort/Core/GodSerialPort.Static.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | // ReSharper disable All
4 | namespace GodSharp.SerialPort
5 | {
6 | ///
7 | /// SerialPort util.
8 | ///
9 | public partial class GodSerialPort
10 | {
11 |
12 | ///
13 | /// Get an array of serialport name for current computer.
14 | ///
15 | ///
16 | public static string[] GetPortNames() => System.IO.Ports.SerialPort.GetPortNames();
17 |
18 | ///
19 | /// Gets the baudrate dictionary.
20 | ///
21 | /// The baudrate dictionary.
22 | public static Dictionary BaudRateDictionary { get; }
23 |
24 | ///
25 | /// Gets the parity dictionary.
26 | ///
27 | /// The parity dictionary.
28 | public static Dictionary ParityDictionary { get; }
29 |
30 | ///
31 | /// Gets the stop bit dictionary.
32 | ///
33 | /// The stop bit dictionary.
34 | public static Dictionary StopBitDictionary { get; }
35 |
36 | ///
37 | ///
38 | ///
39 | public static Dictionary HandshakeDictionary { get; }
40 |
41 |
42 | ///
43 | /// Initializes static members of the class.
44 | ///
45 | static GodSerialPort()
46 | {
47 | BaudRateDictionary = new Dictionary
48 | {
49 | {"110", 110},
50 | {"300", 300},
51 | {"600", 600},
52 | {"1200", 1200},
53 | {"2400", 2400},
54 | {"4800", 4800},
55 | {"9600", 9600},
56 | {"14400", 14400},
57 | {"19200", 19200},
58 | {"38400", 38400},
59 | {"56000", 56000},
60 | {"57600", 57600},
61 | {"115200", 115200}
62 | };
63 |
64 | ParityDictionary = new Dictionary
65 | {
66 | {"None", 0},
67 | {"Odd", 1},
68 | {"Even", 2},
69 | {"Mark", 3},
70 | {"Space", 4}
71 | };
72 |
73 | StopBitDictionary = new Dictionary
74 | {
75 | {"None", 0},
76 | {"1", 1},
77 | {"2", 2},
78 | {"1.5", 3}
79 | };
80 |
81 | HandshakeDictionary = new Dictionary
82 | {
83 | {"None", 0},
84 | {"Software", 1},
85 | {"Hardware", 2},
86 | {"Both", 3}
87 | };
88 | }
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/src/GodSharp.SerialPort/GodSharp.SerialPort.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | 1.2.0.6
4 | 1.2.0.6
5 | true
6 | true
7 | en-US
8 | GodSharp.SerialPort
9 | GodSharp.SerialPort
10 | GodSharp,GodSharp.SerialPort,SerialPort
11 | GodSharp
12 | seayxu
13 | An easy-to-use .NET SerialPort Library.
14 | git
15 | https://github.com/godsharp/GodSharp.SerialPort.git
16 | https://github.com/godsharp/GodSharp.SerialPort
17 | Copyright © GodSharp 2017
18 | https://avatars3.githubusercontent.com/u/26563296
19 | https://github.com/godsharp/GodSharp.SerialPort/blob/master/LICENSE
20 | netstandard2.0;net47;net46;net45;net40;net35;
21 | $(LibraryFrameworks)
22 |
23 |
24 |
25 |
26 | NFX;NET35;$(AdditionalConstants)
27 |
28 |
29 | NFX;NET40;$(AdditionalConstants)
30 |
31 |
32 | NFX;NET45;$(AdditionalConstants)
33 |
34 |
35 | NFX;NET46;$(AdditionalConstants)
36 |
37 |
38 | NFX;NET47;$(AdditionalConstants)
39 |
40 |
41 | CFX;NETSTANDARD2_0;$(AdditionalConstants)
42 |
43 |
44 | ..\..\output\
45 | 1.2.0.6
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # GodSharp.SerialPort
2 | An easy-to-use .NET SerialPort class.
3 |
4 | [](https://ci.appveyor.com/project/seayxu/godsharp-serialport/) [](https://www.nuget.org/packages/GodSharp.SerialPort/) [](https://www.myget.org/Package/Details/godsharp?packageType=nuget&packageId=GodSharp.SerialPort)
5 |
6 |
7 | # Requirement
8 | .NET Framework >= 3.5
9 |
10 | # Getting Started
11 |
12 | 1. New instance GodSerialPort.
13 |
14 | ```
15 | GodSerialPort serial = new GodSerialPort("COM1", 9600,0);
16 | ```
17 |
18 | 2. Use `DataReceived` event with received data action: `Action`.
19 |
20 | **Notice**:*This is not need when you read data by read method.*
21 | ```
22 | serial.UseDataReceived(true,(sp,bytes)=>{});
23 | ```
24 |
25 | 3. Open SerialPort object.
26 |
27 | ```
28 | serial.Open();
29 | ```
30 |
31 | 4. Write/Send data.
32 |
33 | ```
34 | byte[] bytes = new byte[]{31,32,33,34};
35 | serial.Write(bytes);
36 | serial.Write(bytes,offset:1,count:2);
37 | serial.WriteHexString("7E 48 53 44");
38 | serial.WriteAsciiString("ascii string");
39 | ```
40 |
41 | 5. Read data.
42 | ```
43 | byte[] bytes = serial.Read();
44 | string stringAsciiOrHex = serial.ReadString();
45 | ```
46 |
47 | # Sample
48 |
49 | ```
50 | class Program
51 | {
52 | static void Main(string[] args)
53 | {
54 | Console.Write("input serialport number(only 0-9):");
55 | string read = Console.ReadLine();
56 | bool flag = uint.TryParse(read, out uint num);
57 | if (!flag)
58 | {
59 | Exit();
60 | }
61 |
62 | GodSerialPort gsp = new GodSerialPort("COM"+num, 9600,0);
63 | gsp.UseDataReceived(true,(sp,bytes) => {
64 | string buffer = string.Join(" ", bytes);
65 | Console.WriteLine("receive data:" + buffer);
66 | });
67 | flag = gsp.Open();
68 |
69 | if (!flag)
70 | {
71 | Exit();
72 | }
73 |
74 | Console.WriteLine("serialport opend");
75 |
76 | Console.WriteLine("press any thing as data to send,press key 'q' to quit.");
77 |
78 | string data = null;
79 | while (data == null || data.ToLower()!="q")
80 | {
81 | if (!string.IsNullOrEmpty(data))
82 | {
83 | Console.WriteLine("send data:"+data);
84 | gsp.WriteAsciiString(data);
85 | }
86 | data = Console.ReadLine();
87 | }
88 | }
89 |
90 | static void Exit()
91 | {
92 | Console.WriteLine("press any key to quit.");
93 | Console.ReadKey();
94 | Environment.Exit(0);
95 | }
96 | }
97 | ```
98 |
99 | # Notes
100 |
101 | ## 1.2.0
102 | - 1.support .NET Core 2.0.
103 |
104 | ## 1.1.2
105 | - 1.Add GodSerialPort to event action as signature param for initial a list.
106 |
107 | ## 1.1.1
108 | - 1.Add constructor and change the constructor signature.
109 | - 2.Add `PortUtil` class.
110 |
111 | ## 1.1.0
112 | - 1.Add UseDataReceived method use to trigger DataReceived event.
113 | - 2.The read metnod can be used to end character.
114 | - 3.Add sleep time when try read data.
115 |
116 | ## 1.0.1
117 | - 1.Fix ctor and comments.
118 |
119 | ## 1.0.0
120 | - 1.The first version release.
--------------------------------------------------------------------------------
/GodSharp.SerialPort.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.26730.15
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{A9C28F7F-0F11-4E92-B31A-BF950A54F863}"
7 | EndProject
8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{0D3F3351-97B4-4A86-B885-991892A0FAD9}"
9 | EndProject
10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GodSharp.SerialPort", "src\GodSharp.SerialPort\GodSharp.SerialPort.csproj", "{4006DD01-8B21-4246-A7CF-A15421738486}"
11 | EndProject
12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GodSharp.SerialPort.ConsoleSample", "test\GodSharp.SerialPort.ConsoleSample\GodSharp.SerialPort.ConsoleSample.csproj", "{64A904FC-399A-4D07-99F5-1B5CCD9FF17A}"
13 | EndProject
14 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GodSharp.SerialPort.Tests", "test\GodSharp.SerialPort.Tests\GodSharp.SerialPort.Tests.csproj", "{DE27FFB1-2029-4FF5-892E-6F4274460CF1}"
15 | EndProject
16 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{29956551-411E-4631-A3E3-397100FCD8B8}"
17 | ProjectSection(SolutionItems) = preProject
18 | .gitignore = .gitignore
19 | appveyor.yml = appveyor.yml
20 | LICENSE = LICENSE
21 | README.md = README.md
22 | EndProjectSection
23 | EndProject
24 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GodSharp.SerialPort.NetCore.ConsoleSample", "test\GodSharp.SerialPort.NetCore.ConsoleSample\GodSharp.SerialPort.NetCore.ConsoleSample.csproj", "{12A88642-232B-4FFF-941B-A2B650B9F3C0}"
25 | EndProject
26 | Global
27 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
28 | Debug|Any CPU = Debug|Any CPU
29 | Release|Any CPU = Release|Any CPU
30 | EndGlobalSection
31 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
32 | {4006DD01-8B21-4246-A7CF-A15421738486}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
33 | {4006DD01-8B21-4246-A7CF-A15421738486}.Debug|Any CPU.Build.0 = Debug|Any CPU
34 | {4006DD01-8B21-4246-A7CF-A15421738486}.Release|Any CPU.ActiveCfg = Release|Any CPU
35 | {4006DD01-8B21-4246-A7CF-A15421738486}.Release|Any CPU.Build.0 = Release|Any CPU
36 | {64A904FC-399A-4D07-99F5-1B5CCD9FF17A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
37 | {64A904FC-399A-4D07-99F5-1B5CCD9FF17A}.Debug|Any CPU.Build.0 = Debug|Any CPU
38 | {64A904FC-399A-4D07-99F5-1B5CCD9FF17A}.Release|Any CPU.ActiveCfg = Release|Any CPU
39 | {64A904FC-399A-4D07-99F5-1B5CCD9FF17A}.Release|Any CPU.Build.0 = Release|Any CPU
40 | {DE27FFB1-2029-4FF5-892E-6F4274460CF1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
41 | {DE27FFB1-2029-4FF5-892E-6F4274460CF1}.Debug|Any CPU.Build.0 = Debug|Any CPU
42 | {DE27FFB1-2029-4FF5-892E-6F4274460CF1}.Release|Any CPU.ActiveCfg = Release|Any CPU
43 | {DE27FFB1-2029-4FF5-892E-6F4274460CF1}.Release|Any CPU.Build.0 = Release|Any CPU
44 | {12A88642-232B-4FFF-941B-A2B650B9F3C0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
45 | {12A88642-232B-4FFF-941B-A2B650B9F3C0}.Debug|Any CPU.Build.0 = Debug|Any CPU
46 | {12A88642-232B-4FFF-941B-A2B650B9F3C0}.Release|Any CPU.ActiveCfg = Release|Any CPU
47 | {12A88642-232B-4FFF-941B-A2B650B9F3C0}.Release|Any CPU.Build.0 = Release|Any CPU
48 | EndGlobalSection
49 | GlobalSection(SolutionProperties) = preSolution
50 | HideSolutionNode = FALSE
51 | EndGlobalSection
52 | GlobalSection(NestedProjects) = preSolution
53 | {4006DD01-8B21-4246-A7CF-A15421738486} = {A9C28F7F-0F11-4E92-B31A-BF950A54F863}
54 | {64A904FC-399A-4D07-99F5-1B5CCD9FF17A} = {0D3F3351-97B4-4A86-B885-991892A0FAD9}
55 | {DE27FFB1-2029-4FF5-892E-6F4274460CF1} = {0D3F3351-97B4-4A86-B885-991892A0FAD9}
56 | {12A88642-232B-4FFF-941B-A2B650B9F3C0} = {0D3F3351-97B4-4A86-B885-991892A0FAD9}
57 | EndGlobalSection
58 | GlobalSection(ExtensibilityGlobals) = postSolution
59 | SolutionGuid = {BB2FB7BA-CC7A-43CD-A7E3-4B8A06B10A56}
60 | EndGlobalSection
61 | EndGlobal
62 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.userosscache
8 | *.sln.docstates
9 |
10 | # User-specific files (MonoDevelop/Xamarin Studio)
11 | *.userprefs
12 |
13 | # Build results
14 | [Dd]ebug/
15 | [Dd]ebugPublic/
16 | [Rr]elease/
17 | [Rr]eleases/
18 | x64/
19 | x86/
20 | bld/
21 | [Bb]in/
22 | [Oo]bj/
23 | [Ll]og/
24 |
25 | # Visual Studio 2015 cache/options directory
26 | .vs/
27 | # Uncomment if you have tasks that create the project's static files in wwwroot
28 | #wwwroot/
29 |
30 | # MSTest test Results
31 | [Tt]est[Rr]esult*/
32 | [Bb]uild[Ll]og.*
33 |
34 | # NUNIT
35 | *.VisualState.xml
36 | TestResult.xml
37 |
38 | # Build Results of an ATL Project
39 | [Dd]ebugPS/
40 | [Rr]eleasePS/
41 | dlldata.c
42 |
43 | # DNX
44 | project.lock.json
45 | artifacts/
46 |
47 | *_i.c
48 | *_p.c
49 | *_i.h
50 | *.ilk
51 | *.meta
52 | *.obj
53 | *.pch
54 | *.pdb
55 | *.pgc
56 | *.pgd
57 | *.rsp
58 | *.sbr
59 | *.tlb
60 | *.tli
61 | *.tlh
62 | *.tmp
63 | *.tmp_proj
64 | *.log
65 | *.vspscc
66 | *.vssscc
67 | .builds
68 | *.pidb
69 | *.svclog
70 | *.scc
71 |
72 | # Chutzpah Test files
73 | _Chutzpah*
74 |
75 | # Visual C++ cache files
76 | ipch/
77 | *.aps
78 | *.ncb
79 | *.opendb
80 | *.opensdf
81 | *.sdf
82 | *.cachefile
83 | *.VC.db
84 | *.VC.VC.opendb
85 |
86 | # Visual Studio profiler
87 | *.psess
88 | *.vsp
89 | *.vspx
90 | *.sap
91 |
92 | # TFS 2012 Local Workspace
93 | $tf/
94 |
95 | # Guidance Automation Toolkit
96 | *.gpState
97 |
98 | # ReSharper is a .NET coding add-in
99 | _ReSharper*/
100 | *.[Rr]e[Ss]harper
101 | *.DotSettings.user
102 |
103 | # JustCode is a .NET coding add-in
104 | .JustCode
105 |
106 | # TeamCity is a build add-in
107 | _TeamCity*
108 |
109 | # DotCover is a Code Coverage Tool
110 | *.dotCover
111 |
112 | # NCrunch
113 | _NCrunch_*
114 | .*crunch*.local.xml
115 | nCrunchTemp_*
116 |
117 | # MightyMoose
118 | *.mm.*
119 | AutoTest.Net/
120 |
121 | # Web workbench (sass)
122 | .sass-cache/
123 |
124 | # Installshield output folder
125 | [Ee]xpress/
126 |
127 | # DocProject is a documentation generator add-in
128 | DocProject/buildhelp/
129 | DocProject/Help/*.HxT
130 | DocProject/Help/*.HxC
131 | DocProject/Help/*.hhc
132 | DocProject/Help/*.hhk
133 | DocProject/Help/*.hhp
134 | DocProject/Help/Html2
135 | DocProject/Help/html
136 |
137 | # Click-Once directory
138 | publish/
139 |
140 | # Publish Web Output
141 | *.[Pp]ublish.xml
142 | *.azurePubxml
143 | # TODO: Comment the next line if you want to checkin your web deploy settings
144 | # but database connection strings (with potential passwords) will be unencrypted
145 | *.pubxml
146 | *.publishproj
147 |
148 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
149 | # checkin your Azure Web App publish settings, but sensitive information contained
150 | # in these scripts will be unencrypted
151 | PublishScripts/
152 |
153 | # NuGet Packages
154 | *.nupkg
155 | # The packages folder can be ignored because of Package Restore
156 | **/packages/*
157 | # except build/, which is used as an MSBuild target.
158 | !**/packages/build/
159 | # Uncomment if necessary however generally it will be regenerated when needed
160 | #!**/packages/repositories.config
161 | # NuGet v3's project.json files produces more ignoreable files
162 | *.nuget.props
163 | *.nuget.targets
164 |
165 | # Microsoft Azure Build Output
166 | csx/
167 | *.build.csdef
168 |
169 | # Microsoft Azure Emulator
170 | ecf/
171 | rcf/
172 |
173 | # Windows Store app package directories and files
174 | AppPackages/
175 | BundleArtifacts/
176 | Package.StoreAssociation.xml
177 | _pkginfo.txt
178 |
179 | # Visual Studio cache files
180 | # files ending in .cache can be ignored
181 | *.[Cc]ache
182 | # but keep track of directories ending in .cache
183 | !*.[Cc]ache/
184 |
185 | # Others
186 | ClientBin/
187 | ~$*
188 | *~
189 | *.dbmdl
190 | *.dbproj.schemaview
191 | *.pfx
192 | *.publishsettings
193 | node_modules/
194 | orleans.codegen.cs
195 |
196 | # Since there are multiple workflows, uncomment next line to ignore bower_components
197 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
198 | #bower_components/
199 |
200 | # RIA/Silverlight projects
201 | Generated_Code/
202 |
203 | # Backup & report files from converting an old project file
204 | # to a newer Visual Studio version. Backup files are not needed,
205 | # because we have git ;-)
206 | _UpgradeReport_Files/
207 | Backup*/
208 | UpgradeLog*.XML
209 | UpgradeLog*.htm
210 |
211 | # SQL Server files
212 | *.mdf
213 | *.ldf
214 |
215 | # Business Intelligence projects
216 | *.rdl.data
217 | *.bim.layout
218 | *.bim_*.settings
219 |
220 | # Microsoft Fakes
221 | FakesAssemblies/
222 |
223 | # GhostDoc plugin setting file
224 | *.GhostDoc.xml
225 |
226 | # Node.js Tools for Visual Studio
227 | .ntvs_analysis.dat
228 |
229 | # Visual Studio 6 build log
230 | *.plg
231 |
232 | # Visual Studio 6 workspace options file
233 | *.opt
234 |
235 | # Visual Studio LightSwitch build output
236 | **/*.HTMLClient/GeneratedArtifacts
237 | **/*.DesktopClient/GeneratedArtifacts
238 | **/*.DesktopClient/ModelManifest.xml
239 | **/*.Server/GeneratedArtifacts
240 | **/*.Server/ModelManifest.xml
241 | _Pvt_Extensions
242 |
243 | # Paket dependency manager
244 | .paket/paket.exe
245 | paket-files/
246 |
247 | # FAKE - F# Make
248 | .fake/
249 |
250 | # JetBrains Rider
251 | .idea/
252 | *.sln.iml
253 |
254 | # ower
255 |
256 | output/
--------------------------------------------------------------------------------
/test/GodSharp.SerialPort.Tests/GodSharp.SerialPort.Tests.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {DE27FFB1-2029-4FF5-892E-6F4274460CF1}
8 | Library
9 | Properties
10 | GodSharp.SerialPort.Tests
11 | GodSharp.SerialPort.Tests
12 | v4.5
13 | 512
14 | {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
15 | 10.0
16 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)
17 | $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages
18 | False
19 | UnitTest
20 |
21 |
22 |
23 |
24 | true
25 | full
26 | false
27 | bin\Debug\
28 | DEBUG;TRACE
29 | prompt
30 | 4
31 |
32 |
33 | pdbonly
34 | true
35 | bin\Release\
36 | TRACE
37 | prompt
38 | 4
39 |
40 |
41 |
42 | ..\..\packages\MSTest.TestFramework.1.1.11\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll
43 |
44 |
45 | ..\..\packages\MSTest.TestFramework.1.1.11\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 | {4006dd01-8b21-4246-a7cf-a15421738486}
67 | GodSharp.SerialPort
68 |
69 |
70 |
71 |
72 |
73 |
74 | False
75 |
76 |
77 | False
78 |
79 |
80 | False
81 |
82 |
83 | False
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 | This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.
93 |
94 |
95 |
96 |
97 |
98 |
105 |
--------------------------------------------------------------------------------
/src/GodSharp.SerialPort/Core/SerialConfigOptions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO.Ports;
3 |
4 | namespace GodSharp.SerialPort
5 | {
6 | ///
7 | /// SerialConfigOptions
8 | ///
9 | public class SerialConfigOptions
10 | {
11 | ///
12 | /// Gets or sets the name of the port.
13 | ///
14 | ///
15 | /// The name of the port.
16 | ///
17 | public string PortName { get; set; }
18 |
19 | ///
20 | /// Gets or sets the baud rate.
21 | ///
22 | ///
23 | /// The baud rate.
24 | ///
25 | public int BaudRate { get; set; } = 9600;
26 |
27 | ///
28 | /// Gets or sets the data bits.
29 | ///
30 | ///
31 | /// The data bits.
32 | ///
33 | public int DataBits { get; set; } = 8;
34 |
35 | ///
36 | /// Gets or sets the stop bits.
37 | ///
38 | ///
39 | /// The stop bits.
40 | ///
41 | public StopBits StopBits { get; set; } = StopBits.One;
42 |
43 | ///
44 | /// Gets or sets the parity bits.
45 | ///
46 | ///
47 | /// The parity bits.
48 | ///
49 | public Parity Parity { get; set; } = Parity.None;
50 |
51 | ///
52 | /// Gets or sets the handshake.
53 | ///
54 | ///
55 | /// The handshake.
56 | ///
57 | public Handshake Handshake { get; set; } = Handshake.None;
58 |
59 | ///
60 | /// Initializes a new instance of the class.
61 | ///
62 | public SerialConfigOptions()
63 | {
64 | }
65 |
66 | ///
67 | /// Initializes a new instance of the class.
68 | ///
69 | /// Name of the port.
70 | /// The baud rate.
71 | /// The data bits.
72 | /// The stop bits.
73 | /// The parity.
74 | /// The handshake.
75 | /// portName
76 | public SerialConfigOptions(string portName, int baudRate = 9600, int dataBits = 8, StopBits stopBits = StopBits.One, Parity parity = Parity.None, Handshake handshake = Handshake.None)
77 | {
78 | PortName = portName ?? throw new ArgumentNullException(nameof(portName));
79 | if (dataBits < 7 || dataBits > 8) throw new ArgumentNullException(nameof(dataBits), "only 7,8");
80 | BaudRate = baudRate;
81 | DataBits = dataBits;
82 | StopBits = stopBits;
83 | Parity = parity;
84 | Handshake = handshake;
85 | }
86 |
87 | ///
88 | /// Initializes a new instance of the class.
89 | ///
90 | /// Name of the port.
91 | /// The baudrate,default is 9600.
92 | /// The databits,default is 8.
93 | /// The int stopbits,default is 1,StopBits.One.
94 | /// StopBits.None:0
95 | /// StopBits.One:1
96 | /// StopBits.Two:2
97 | /// StopBits.OnePointFive:3
98 | ///
99 | /// The int parity,default is 0,Parity.None.
100 | /// Parity.None:0
101 | /// Parity.Odd:1
102 | /// Parity.Even:2
103 | /// Parity.Mark:3
104 | /// Parity.Space:4
105 | ///
106 | /// The int handshake,default is 0,Handshake.None.
107 | /// Handshake.None:0
108 | /// Handshake.XOnXOff:1
109 | /// Handshake.RequestToSend:2
110 | /// Handshake.RequestToSendXOnXOff:3
111 | ///
112 | public SerialConfigOptions(string portName, int baudRate = 9600, int dataBits = 8, int stopBits = 1, int parity = 0, int handshake = 0) : this(portName, baudRate, dataBits, GetStopBits(stopBits), GetParity(parity), GetHandshake(handshake)) { }
113 |
114 | ///
115 | /// Initializes a new instance of the class.
116 | ///
117 | /// Name of the port.
118 | /// The baudrate,default is 9600.
119 | /// The databits,default is 8.
120 | /// The string stopbits,default is one,StopBits.One.
121 | /// StopBits.None:0|n|none
122 | /// StopBits.One:1|o|one
123 | /// StopBits.Two:2|t|two
124 | /// StopBits.OnePointFive:3|1.5|f|of|opf|onepointfive
125 | ///
126 | /// The string parity,default is none,Parity.None.
127 | /// Parity.None:0|n|none
128 | /// Parity.Odd:1|o|odd
129 | /// Parity.Even:2|e|even
130 | /// Parity.Mark:3|m|mark
131 | /// Parity.Space:4|s|space
132 | ///
133 | /// The string handshake,default is none,Handshake.None.
134 | /// Handshake.None:0|n|none
135 | /// Handshake.XOnXOff:1|x|xoxo
136 | /// Handshake.RequestToSend:2|r|rst
137 | /// Handshake.RequestToSendXOnXOff:3|rx|rtsxx
138 | ///
139 | public SerialConfigOptions(string portName, int baudRate = 9600, int dataBits = 8, string stopBits = "one", string parity = "none", string handshake = "none") : this(portName, baudRate, dataBits, GetStopBits(stopBits), GetParity(parity), GetHandshake(handshake)) { }
140 |
141 | #region Gets the parity method
142 | ///
143 | /// Gets the parity by string.
144 | ///
145 | /// The string parity value.
146 | /// Parity.None:0|n|none
147 | /// Parity.Odd:1|o|odd
148 | /// Parity.Even:2|e|even
149 | /// Parity.Mark:3|m|mark
150 | /// Parity.Space:4|s|space
151 | ///
152 | /// The .
153 | public static Parity GetParity(string parityVal)
154 | {
155 | Parity patityBit;
156 | switch (parityVal?.ToLower())
157 | {
158 | case "0":
159 | case "n":
160 | case "none":
161 | patityBit = Parity.None;
162 | break;
163 | case "1":
164 | case "o":
165 | case "odd":
166 | patityBit = Parity.Odd;
167 | break;
168 | case "2":
169 | case "e":
170 | case "even":
171 | patityBit = Parity.Even;
172 | break;
173 | case "3":
174 | case "m":
175 | case "mark":
176 | patityBit = Parity.Mark;
177 | break;
178 | case "4":
179 | case "s":
180 | case "space":
181 | patityBit = Parity.Space;
182 | break;
183 | default:
184 | patityBit = Parity.None;
185 | break;
186 | }
187 | return patityBit;
188 | }
189 |
190 | ///
191 | /// Gets the parity by int.
192 | ///
193 | /// The int parity value.
194 | /// Parity.None:0
195 | /// Parity.Odd:1
196 | /// Parity.Even:2
197 | /// Parity.Mark:3
198 | /// Parity.Space:4
199 | ///
200 | /// The .
201 | public static Parity GetParity(int parityVal) => GetParity(parityVal.ToString());
202 | #endregion
203 |
204 | #region Gets the stopbits method
205 | ///
206 | /// Gets the stopbits by string.
207 | ///
208 | /// The string stop bits.
209 | /// StopBits.None:0|n|none
210 | /// StopBits.One:1|o|one
211 | /// StopBits.Two:2|t|two
212 | /// StopBits.OnePointFive:3|1.5|f|of|opf|onepointfive
213 | ///
214 | /// The .
215 | public static StopBits GetStopBits(string stopBitsVal)
216 | {
217 | StopBits stopBit;
218 | switch (stopBitsVal?.ToLower())
219 | {
220 | case "0":
221 | case "n":
222 | case "none":
223 | stopBit = StopBits.None;
224 | break;
225 | case "1":
226 | case "o":
227 | case "one":
228 | stopBit = StopBits.One;
229 | break;
230 | case "2":
231 | case "t":
232 | case "two":
233 | stopBit = StopBits.Two;
234 | break;
235 | case "3":
236 | case "1.5":
237 | case "f":
238 | case "of":
239 | case "opf":
240 | case "onepointfive":
241 | stopBit = StopBits.OnePointFive;
242 | break;
243 | default:
244 | stopBit = StopBits.One;
245 | break;
246 | }
247 |
248 | return stopBit;
249 | }
250 |
251 | ///
252 | /// Gets the stopbits by int.
253 | ///
254 | /// The int stop bits.
255 | /// StopBits.None:0
256 | /// StopBits.One:1
257 | /// StopBits.Two:2
258 | /// StopBits.OnePointFive:3
259 | ///
260 | /// The .
261 | public static StopBits GetStopBits(int stopBitsVal) => GetStopBits(stopBitsVal.ToString());
262 | #endregion
263 |
264 | #region Gets the handshake by string
265 | ///
266 | /// Gets the handshake by string.
267 | ///
268 | /// The string handshake value.
269 | /// Handshake.None:0|n|none
270 | /// Handshake.XOnXOff:1|x|xoxo
271 | /// Handshake.RequestToSend:2|r|rst
272 | /// Handshake.RequestToSendXOnXOff:3|rx|rtsxx
273 | ///
274 | /// Handshake.
275 | public static Handshake GetHandshake(string shake)
276 | {
277 | Handshake handShake;
278 | switch (shake?.ToLower())
279 | {
280 | case "0":
281 | case "n":
282 | case "none":
283 | handShake = Handshake.None;
284 | break;
285 | case "1":
286 | case "x":
287 | case "xoxo":
288 | case "xonxoff":
289 | case "software":
290 | handShake = Handshake.XOnXOff;
291 | break;
292 | case "2":
293 | case "r":
294 | case "rts":
295 | case "requesttosend":
296 | case "hardware":
297 | handShake = Handshake.RequestToSend;
298 | break;
299 | case "3":
300 | case "rx":
301 | case "rtsxx":
302 | case "requesttosendxonxoff":
303 | case "both":
304 | handShake = Handshake.RequestToSendXOnXOff;
305 | break;
306 | default:
307 | handShake = Handshake.None;
308 | break;
309 | }
310 | return handShake;
311 | }
312 |
313 | ///
314 | /// Gets the handshake by string.
315 | ///
316 | /// The int handshake value.
317 | /// Handshake.None:0
318 | /// Handshake.XOnXOff:1
319 | /// Handshake.RequestToSend:2
320 | /// Handshake.RequestToSendXOnXOff:3
321 | ///
322 | /// Handshake.
323 | public static Handshake GetHandshake(int shake) => GetHandshake(shake.ToString());
324 | #endregion
325 | }
326 | }
327 |
--------------------------------------------------------------------------------
/src/GodSharp.SerialPort/Core/GodSerialPort.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO.Ports;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Threading;
7 | using GodSharp.SerialPort.Enums;
8 | using GodSharp.SerialPort.Extensions;
9 | // ReSharper disable FieldCanBeMadeReadOnly.Local
10 | // ReSharper disable MemberCanBePrivate.Global
11 | // ReSharper disable SuggestVarOrType_BuiltInTypes
12 | // ReSharper disable SuggestVarOrType_Elsewhere
13 | // ReSharper disable InvertIf
14 | // ReSharper disable SwitchStatementMissingSomeCases
15 | // ReSharper disable TooWideLocalVariableScope
16 | // ReSharper disable ArrangeThisQualifier
17 | // ReSharper disable once CheckNamespace
18 | // ReSharper disable SuggestVarOrType_SimpleTypes
19 | namespace GodSharp.SerialPort
20 | {
21 | ///
22 | /// GodSerialPort Util Class.
23 | ///
24 | ///
25 | /// GodSerialPort serial= new GodSerialPort("COM1",9600);
26 | /// serial.UseDataReceived((sp,bytes)=>{});
27 | /// serial.Open();
28 | ///
29 | public partial class GodSerialPort
30 | {
31 | #region Propertys
32 |
33 | private int tryReadNumber;
34 |
35 | private bool initialized = false;
36 |
37 | private bool onDataBind = false;
38 |
39 | ///
40 | /// Gets or sets the name.
41 | ///
42 | ///
43 | /// The name.
44 | ///
45 | public string Name { get; set; }
46 |
47 | public SerialConfigOptions Options { get; private set; }
48 |
49 | ///
50 | /// The method of execution that data has been received through a port represented by the SerialPort object.
51 | ///
52 | public Action OnData { get; set; }
53 |
54 | ///
55 | /// The method of execution that an error has occurred with a port represented by a SerialPort object.
56 | ///
57 | private Action onError;
58 |
59 | ///
60 | /// The method of execution that a non-data signal event has occurred on the port represented by the SerialPort object.
61 | ///
62 | private Action onPinChange;
63 |
64 | ///
65 | /// Gets or sets the data format.
66 | ///
67 | /// The data format.
68 | // ReSharper disable once MemberCanBePrivate.Global
69 | public SerialPortDataFormat DataFormat { get; set; } = SerialPortDataFormat.Hex;
70 |
71 | ///
72 | /// Gets or sets the try count of receive.
73 | ///
74 | /// The try count of receive,default is 3.
75 | public int TryReadNumber
76 | {
77 | get => this.tryReadNumber;
78 | set
79 | {
80 | if (value < 1) throw new ArgumentOutOfRangeException(nameof(TryReadNumber), nameof(TryReadNumber) + " must be equal or greater than 1.");
81 | tryReadNumber = value;
82 | }
83 | }
84 |
85 | ///
86 | /// Gets or sets the try sleep time of receive,unit is ms.
87 | ///
88 | /// The try sleep time of receive,default is 10.
89 | // ReSharper disable once MemberCanBePrivate.Global
90 | public int TryReadSpanTime { get; set; } = 10;
91 |
92 | ///
93 | /// Gets or sets the terminator,hex value.
94 | ///
95 | ///
96 | /// The terminator.
97 | ///
98 | ///
99 | /// Terminator = "0D 0A"
100 | ///
101 | public string Terminator { get; set; } = null;
102 |
103 | ///
104 | /// The serial port
105 | ///
106 | private System.IO.Ports.SerialPort serialPort;
107 |
108 | ///
109 | /// SerialPort object.
110 | ///
111 | public System.IO.Ports.SerialPort SerialPort => serialPort;
112 |
113 | ///
114 | /// Determines whether this instance is open.
115 | ///
116 | /// true if this serialport is open; otherwise, false.
117 | public bool IsOpen => serialPort != null && serialPort.IsOpen;
118 |
119 | ///
120 | /// Gets or sets the name of the port.
121 | ///
122 | /// The name of the port.
123 | public string PortName
124 | {
125 | get => serialPort.PortName;
126 | set => serialPort.PortName = value;
127 | }
128 |
129 | ///
130 | /// Gets or sets the baudrate.
131 | ///
132 | /// The baudrate.
133 | public int BaudRate
134 | {
135 | get => serialPort.BaudRate;
136 | set => serialPort.BaudRate = value;
137 | }
138 |
139 | ///
140 | /// Gets or sets a value indicating whether [break state].
141 | ///
142 | /// true if [break state]; otherwise, false.
143 | public bool BreakState
144 | {
145 | get => serialPort.BreakState;
146 | set => serialPort.BreakState = value;
147 | }
148 | ///
149 | /// Gets or sets the databits.
150 | ///
151 | /// The databits.
152 | public int DataBits
153 | {
154 | get => serialPort.DataBits;
155 | set => serialPort.DataBits = value;
156 | }
157 |
158 | ///
159 | /// Gets or sets the encoding.
160 | ///
161 | /// The encoding.
162 | public Encoding Encoding
163 | {
164 | get => serialPort.Encoding;
165 | set => serialPort.Encoding = value;
166 | }
167 |
168 | ///
169 | /// Gets or sets the handshake.
170 | ///
171 | /// The handshake.
172 | public Handshake Handshake
173 | {
174 | get => serialPort.Handshake;
175 | set => serialPort.Handshake = value;
176 | }
177 |
178 | ///
179 | /// Gets or sets the parity.
180 | ///
181 | /// The parity.
182 | public Parity Parity
183 | {
184 | get => serialPort.Parity;
185 | set => serialPort.Parity = value;
186 | }
187 |
188 | ///
189 | /// Gets or sets the stopbits.
190 | ///
191 | /// The stopbits.
192 | public StopBits StopBits
193 | {
194 | get => serialPort.StopBits;
195 | set => serialPort.StopBits = value;
196 | }
197 |
198 | ///
199 | /// Gets or sets the read timeout.
200 | ///
201 | /// The read timeout.
202 | public int ReadTimeout
203 | {
204 | get => serialPort.ReadTimeout;
205 | set => serialPort.ReadTimeout = value;
206 | }
207 |
208 | ///
209 | /// Gets or sets the write timeout.
210 | ///
211 | /// The write timeout.
212 | public int WriteTimeout
213 | {
214 | get => serialPort.WriteTimeout;
215 | set => serialPort.WriteTimeout = value;
216 | }
217 |
218 | ///
219 | /// Gets or sets a value indicating whether [DTR enable].
220 | ///
221 | /// true if [DTR enable]; otherwise, false.
222 | public bool DtrEnable
223 | {
224 | get => serialPort.DtrEnable;
225 | set => serialPort.DtrEnable = value;
226 | }
227 |
228 | ///
229 | /// Gets or sets a value indicating whether [RTS enable].
230 | ///
231 | /// true if [RTS enable]; otherwise, false.
232 | public bool RtsEnable
233 | {
234 | get => serialPort.RtsEnable;
235 | set => serialPort.RtsEnable = value;
236 | }
237 |
238 | ///
239 | /// Gets a value indicating whether [CTS holding].
240 | ///
241 | /// true if [CTS holding]; otherwise, false.
242 | public bool CtsHolding => serialPort.CtsHolding;
243 |
244 | ///
245 | /// Gets a value indicating whether [DSR holding].
246 | ///
247 | /// true if [DSR holding]; otherwise, false.
248 | public bool DsrHolding => serialPort.DsrHolding;
249 |
250 | ///
251 | /// Gets a value indicating whether [cd holding].
252 | ///
253 | /// true if [cd holding]; otherwise, false.
254 | public bool CdHolding => serialPort.CDHolding;
255 |
256 | ///
257 | /// Gets or sets a value indicating whether [discard null].
258 | ///
259 | /// true if [discard null]; otherwise, false.
260 | public bool DiscardNull
261 | {
262 | get => serialPort.DiscardNull;
263 | set => serialPort.DiscardNull = value;
264 | }
265 |
266 | ///
267 | /// Gets or sets the size of the read buffer.
268 | ///
269 | /// The size of the read buffer.
270 | public int ReadBufferSize
271 | {
272 | get => serialPort.ReadBufferSize;
273 | set => serialPort.ReadBufferSize = value;
274 | }
275 |
276 | ///
277 | /// Gets or sets the parity replace.
278 | ///
279 | /// The parity replace.
280 | public byte ParityReplace
281 | {
282 | get => serialPort.ParityReplace;
283 | set => serialPort.ParityReplace = value;
284 | }
285 |
286 | ///
287 | /// Gets or sets the received bytes threshold.
288 | ///
289 | /// The received bytes threshold.
290 | public int ReceivedBytesThreshold
291 | {
292 | get => serialPort.ReceivedBytesThreshold;
293 | set => serialPort.ReceivedBytesThreshold = value;
294 | }
295 |
296 | ///
297 | /// Gets or sets the size of the write buffer.
298 | ///
299 | /// The size of the write buffer.
300 | public int WriteBufferSize
301 | {
302 | get => serialPort.WriteBufferSize;
303 | set => serialPort.WriteBufferSize = value;
304 | }
305 | #endregion
306 |
307 | #region Constructor
308 |
309 | ///
310 | /// Initializes a new instance of the class.
311 | ///
312 | private GodSerialPort()
313 | {
314 | this.tryReadNumber = 3;
315 | this.serialPort = new System.IO.Ports.SerialPort();
316 |
317 | Options = new SerialConfigOptions()
318 | {
319 | Handshake = serialPort.Handshake,
320 | Parity = serialPort.Parity,
321 | StopBits = serialPort.StopBits
322 | };
323 | }
324 |
325 | ///
326 | /// Initializes a new instance of the class.
327 | ///
328 | /// The name of the port.
329 | /// The baudrate,default is 9600.
330 | /// The string parity,default is none,Parity.None.
331 | /// Parity.None:0|n|none
332 | /// Parity.Odd:1|o|odd
333 | /// Parity.Even:2|e|even
334 | /// Parity.Mark:3|m|mark
335 | /// Parity.Space:4|s|space
336 | ///
337 | /// The databits,default is 8.
338 | /// The string stopbits,default is one,StopBits.One.
339 | /// StopBits.None:0|n|none
340 | /// StopBits.One:1|o|one
341 | /// StopBits.Two:2|t|two
342 | /// StopBits.OnePointFive:3|1.5|f|of|opf
343 | ///
344 | /// The string handshake,default is none,Handshake.None.
345 | /// Handshake.None:0|n|none
346 | /// Handshake.XOnXOff:1|x|xoxo
347 | /// Handshake.RequestToSend:2|r|rst
348 | /// Handshake.RequestToSendXOnXOff:3|rx|rtsxx
349 | ///
350 | public GodSerialPort(string portName, int baudRate = 9600, string parity = "none", int dataBits = 8, string stopBits = null, string handshake = null) : this(new SerialConfigOptions(portName, baudRate, dataBits, stopBits, parity, handshake))
351 | {
352 | }
353 |
354 | ///
355 | /// Initializes a new instance of the class.
356 | ///
357 | /// The name of the port.
358 | /// The baudrate,default is 9600.
359 | /// The int parity,default is 0,Parity.None.
360 | /// Parity.None:0
361 | /// Parity.Odd:1
362 | /// Parity.Even:2
363 | /// Parity.Mark:3
364 | /// Parity.Space:4
365 | ///
366 | /// The databits,default is 8.
367 | /// The int stopbits,default is 1,StopBits.One.
368 | /// StopBits.None:0
369 | /// StopBits.One:1
370 | /// StopBits.Two:2
371 | /// StopBits.OnePointFive:3
372 | ///
373 | /// The int handshake,default is 0,Handshake.None.
374 | /// Handshake.None:0
375 | /// Handshake.XOnXOff:1
376 | /// Handshake.RequestToSend:2
377 | /// Handshake.RequestToSendXOnXOff:3
378 | ///
379 | public GodSerialPort(string portName, int baudRate = 9600, int parity = 0, int dataBits = 8, int stopBits = 1, int handshake = 0) : this(new SerialConfigOptions(portName, baudRate, dataBits, stopBits, parity, handshake))
380 | {
381 | }
382 |
383 | ///
384 | /// Initializes a new instance of the class.
385 | ///
386 | /// The name of the port.
387 | /// The baudrate,default is 9600.
388 | /// The int parity,default is Parity.None.
389 | /// The databits,default is 8.
390 | /// The int stopbits,default is StopBits.One.
391 | /// The int handshake,default is Handshake.None.
392 | public GodSerialPort(string portName, int baudRate = 9600, Parity parity = Parity.None, int dataBits = 8, StopBits stopBits = StopBits.None, Handshake handshake = Handshake.None) : this(new SerialConfigOptions(portName,baudRate,dataBits,stopBits,parity,handshake))
393 | {
394 | }
395 |
396 | ///
397 | /// Initializes a new instance of the class.
398 | ///
399 | /// The options.
400 | public GodSerialPort(SerialConfigOptions options) : this()
401 | {
402 | this.Initialize(options);
403 | }
404 |
405 | ///
406 | /// Initializes a new instance of the class.
407 | ///
408 | /// The action.
409 | public GodSerialPort(Action action) : this()
410 | {
411 | action?.Invoke(Options);
412 | this.Initialize(Options);
413 | }
414 | #endregion
415 |
416 | #region Initializes the SerialPort method
417 | ///
418 | /// Initializes the with the action of data receive.
419 | ///
420 | private void Initialize(SerialConfigOptions options)
421 | {
422 | try
423 | {
424 | if (initialized) throw new InvalidOperationException("Already initialized");
425 |
426 | Options = options ?? throw new ArgumentNullException(nameof(options));
427 |
428 | serialPort.PortName = Options.PortName;
429 | serialPort.BaudRate = Options.BaudRate;
430 | serialPort.DataBits = Options.DataBits;
431 | serialPort.Handshake = Options.Handshake;
432 | serialPort.Parity = Options.Parity;
433 | serialPort.StopBits = Options.StopBits;
434 | serialPort.PinChanged += SerialPort_PinChanged;
435 | serialPort.ErrorReceived += SerialPort_ErrorReceived;
436 |
437 | initialized = true;
438 | }
439 | catch (Exception ex)
440 | {
441 | #if DEBUG
442 | Console.WriteLine("Init SerialPort Exception:" + PortName + "\r\nMessage:" + ex.Message);
443 | #endif
444 | throw new Exception(ex.Message, ex);
445 | }
446 | }
447 |
448 | #endregion
449 |
450 | ///
451 | /// Use DataReceived event with data received action or not.
452 | ///
453 | /// The action which process data.
454 | public void UseDataReceived(bool flag)
455 | {
456 | if (flag && !onDataBind)
457 | {
458 | onDataBind = true;
459 | serialPort.DataReceived += SerialPort_DataReceived;
460 |
461 | return;
462 | }
463 |
464 | if (!flag && onDataBind)
465 | {
466 | onDataBind = false;
467 | serialPort.DataReceived -= SerialPort_DataReceived;
468 | }
469 | }
470 |
471 | ///
472 | /// Use DataReceived event with data received action or not.
473 | ///
474 | ///
475 | ///
476 | public void UseDataReceived(bool flag, Action action = null)
477 | {
478 | UseDataReceived(flag);
479 | OnData = action;
480 | }
481 |
482 | ///
483 | /// Use DataReceived event with data received action.
484 | ///
485 | ///
486 | [Obsolete("This method is obsolete,will be removed next release version.")]
487 | public void UseDataReceived(Action action)=> UseDataReceived(true, action);
488 |
489 | #region Open SerialPort method
490 | ///
491 | /// Opens this instance.
492 | ///
493 | ///
494 | /// Not initialized
495 | public bool Open()
496 | {
497 | if (!initialized) throw new InvalidOperationException("Not initialized");
498 |
499 | bool rst = false;
500 | try
501 | {
502 | if (!serialPort.IsOpen)
503 | {
504 | serialPort.Open();
505 | }
506 | else
507 | {
508 | #if DEBUG
509 | Console.WriteLine("the port is opened!");
510 | #endif
511 | return true;
512 | }
513 | }
514 | #if !DEBUG
515 | catch (Exception)
516 | {
517 | #elif DEBUG
518 | catch (Exception ex)
519 | {
520 | Console.WriteLine("Open SerialPort Exception:" + PortName + "\r\nMessage:" + ex.Message);
521 | #endif
522 | }
523 |
524 | if (serialPort.IsOpen)
525 | {
526 | #if DEBUG
527 | Console.WriteLine("successed to open the port!");
528 | #endif
529 | rst = true;
530 | }
531 | return rst;
532 | }
533 |
534 | #endregion
535 |
536 | #region Set the method when error
537 | ///
538 | /// Set the method when [error].
539 | ///
540 | /// The action.
541 | public void OnError(Action action)
542 | {
543 | this.onError = action;
544 | }
545 | #endregion
546 |
547 | #region Set the method when pin changed
548 | ///
549 | /// Set the method when [pin changed].
550 | ///
551 | /// The action.
552 | public void OnPinChange(Action action)
553 | {
554 | this.onPinChange = action;
555 | }
556 | #endregion
557 |
558 | #region Close SerialPort method
559 | ///
560 | /// Close the .
561 | ///
562 | /// true if closed, false otherwise.
563 | public bool Close()
564 | {
565 | try
566 | {
567 | if (serialPort.IsOpen) serialPort.Close();
568 |
569 | return true;
570 | }
571 | catch (Exception ex)
572 | {
573 | #if DEBUG
574 | Console.WriteLine("Close SerialPort Exception:" + PortName + "\r\nMessage:" + ex.Message + "\r\nStackTrace:" + ex.StackTrace);
575 | #endif
576 | throw new Exception(ex.Message, ex);
577 | }
578 | }
579 |
580 | #endregion
581 |
582 | #region Reads method
583 |
584 | ///
585 | /// Synchronously reads one byte from the SerialPort input buffer.
586 | ///
587 | /// The byte, cast to an Int32, or -1 if the end of the stream has been read.
588 | public int ReadByte() => serialPort.ReadByte();
589 |
590 | ///
591 | /// Synchronously reads one character from the SerialPort input buffer.
592 | ///
593 | /// The character that was read.
594 | public int ReadChar() => serialPort.ReadChar();
595 |
596 | ///
597 | /// Reads up to the NewLine value in the input buffer.
598 | ///
599 | /// The contents of the input buffer up to the first occurrence of a NewLine value.
600 | public string ReadLine() => serialPort.ReadLine();
601 |
602 | ///
603 | /// Reads all immediately available bytes, based on the encoding, in both the stream and the input buffer of the SerialPort object.
604 | ///
605 | /// The contents of the stream and the input buffer of the SerialPort object.
606 | public string ReadExisting() => serialPort.ReadExisting();
607 |
608 | ///
609 | /// Reads a string up to the specified value in the input buffer.
610 | ///
611 | /// A value that indicates where the read operation stops.
612 | /// The contents of the input buffer up to the specified value.
613 | public string ReadTo(string value) => serialPort.ReadTo(value);
614 |
615 | ///
616 | /// Reads data from the input buffer.
617 | ///
618 | /// System.String,hex or ascii format.
619 | public string ReadString()
620 | {
621 | try
622 | {
623 | string str = null;
624 |
625 | byte[] bytes = this.TryRead();
626 |
627 | if (bytes != null && bytes.Length > 0)
628 | {
629 | switch (DataFormat)
630 | {
631 | case SerialPortDataFormat.Char:
632 | str = serialPort.Encoding.GetString(bytes);
633 | break;
634 | case SerialPortDataFormat.Hex:
635 | str = bytes.ToHexString();
636 | break;
637 | }
638 | }
639 |
640 | return str;
641 | }
642 | catch (Exception ex)
643 | {
644 | throw new Exception(ex.Message, ex);
645 | }
646 | }
647 |
648 | ///
649 | /// Reads data from the input buffer.
650 | ///
651 | /// The byte array.
652 | public byte[] Read()
653 | {
654 | try
655 | {
656 | return this.TryRead();
657 | }
658 | catch (Exception ex)
659 | {
660 | throw new Exception(ex.Message, ex);
661 | }
662 | }
663 |
664 | #endregion
665 |
666 | #region //Try Read Data
667 | ///
668 | /// Try Read Data
669 | ///
670 | /// The byte array.
671 | private byte[] TryRead()
672 | {
673 | int tryCount = 0;
674 | int endingLength = 0;
675 | bool found = false;
676 | List list = new List();
677 | byte[] bytes;
678 | byte[] ending = null;
679 | byte[] currentEnding;
680 |
681 | if (Terminator != null)
682 | {
683 | ending = Terminator.HexToByte();
684 | endingLength = ending.Length;
685 | }
686 |
687 | int dataLength;
688 |
689 | while ((serialPort.BytesToRead > 0 || !found) && tryCount < tryReadNumber)
690 | {
691 | dataLength = serialPort.BytesToRead < serialPort.ReadBufferSize
692 | ? serialPort.BytesToRead
693 | : serialPort.ReadBufferSize;
694 | bytes = new byte[dataLength];
695 | serialPort.Read(bytes, 0, bytes.Length);
696 | list.AddRange(bytes);
697 |
698 | if (ending != null && endingLength > 0)
699 | {
700 | currentEnding = new byte[endingLength];
701 |
702 | if (bytes.Length >= endingLength)
703 | {
704 | Buffer.BlockCopy(bytes, bytes.Length - endingLength, currentEnding, 0, endingLength);
705 | }
706 | else if (list.ToArray().Length >= endingLength)
707 | {
708 | byte[] temp = list.ToArray();
709 | Buffer.BlockCopy(temp, temp.Length - endingLength, currentEnding, 0, endingLength);
710 | }
711 | else
712 | {
713 | continue;
714 | }
715 |
716 | found = ending.Length > 0 && currentEnding.SequenceEqual(ending);
717 | }
718 |
719 | if (TryReadSpanTime > 0) Thread.Sleep(TryReadSpanTime);
720 |
721 | tryCount++;
722 | }
723 |
724 | return list.Count > 0 ? list.ToArray() : null;
725 | }
726 | #endregion
727 |
728 | #region Writes method
729 | ///
730 | /// Writes the specified hex string.
731 | ///
732 | /// The hex string with space.example:'30 31 32'.
733 | /// sp.WriteHexString("30 31 32");
734 | /// The byte number to be written.
735 | public int WriteHexString(string str)
736 | {
737 | try
738 | {
739 | byte[] bytes = str.HexToByte();
740 |
741 | return Write(bytes, 0, bytes.Length);
742 | }
743 | catch (Exception ex)
744 | {
745 | throw new Exception(ex.Message, ex);
746 | }
747 | }
748 |
749 | ///
750 | /// Writes the specified ascii string.
751 | ///
752 | /// The ascii string.
753 | /// sp.WriteHexString("123");
754 | /// The byte number to be written.
755 | public int WriteAsciiString(string str)
756 | {
757 | try
758 | {
759 | byte[] bytes = serialPort.Encoding.GetBytes(str);
760 |
761 | return Write(bytes, 0, bytes.Length);
762 | }
763 | catch (Exception ex)
764 | {
765 | throw new Exception(ex.Message, ex);
766 | }
767 | }
768 |
769 | ///
770 | /// Writes the byte array.
771 | ///
772 | /// The byte array.
773 | /// The byte number to be written.
774 | public int Write(byte[] bytes)
775 | {
776 | return Write(bytes, 0, bytes.Length);
777 | }
778 |
779 | ///
780 | /// Writes the byte array with offset.
781 | ///
782 | /// The byte array.
783 | /// The number of offset.
784 | /// The length of write.
785 | /// The byte number to be written.
786 | public int Write(byte[] bytes, int offset, int count)
787 | {
788 | try
789 | {
790 | serialPort.Write(bytes, offset, count);
791 |
792 | return count;
793 | }
794 | catch (Exception ex)
795 | {
796 | throw new Exception(ex.Message, ex);
797 | }
798 | }
799 |
800 | ///
801 | /// Writes the specified string and the NewLine value to the output buffer.
802 | ///
803 | ///
804 | public void WriteLine(string str) => serialPort.WriteLine(str);
805 |
806 | #endregion
807 |
808 | #region SerialPort other method
809 | ///
810 | /// Discards the input buffer.
811 | ///
812 | public void DiscardInBuffer() => serialPort.DiscardInBuffer();
813 |
814 | ///
815 | /// Discards the output buffer.
816 | ///
817 | public void DiscardOutBuffer() => serialPort.DiscardOutBuffer();
818 | #endregion
819 | }
820 | }
--------------------------------------------------------------------------------