-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSerialPortInfo.cs
More file actions
76 lines (64 loc) · 2.74 KB
/
Copy pathSerialPortInfo.cs
File metadata and controls
76 lines (64 loc) · 2.74 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
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Management;
namespace SerialPlotAndLog
{
public class SerialPortInfo
{
public string PortName { get; set; }
public string Description { get; set; }
public SerialPortInfo(string portName, string description)
{
PortName = portName;
Description = description;
}
public override int GetHashCode()
{
return (PortName ?? "").GetHashCode() ^ (Description ?? "").GetHashCode();
}
public override bool Equals(object obj)
{
var other = obj as SerialPortInfo;
return
other != null &&
other.PortName == PortName &&
other.Description == Description;
}
public static bool operator ==(SerialPortInfo a, SerialPortInfo b)
{
return a is null && b is null || !(a is null) && a.Equals(b);
}
public static bool operator !=(SerialPortInfo a, SerialPortInfo b) => !(a == b);
public override string ToString()
{
var name = !string.IsNullOrEmpty(PortName) ? $"{PortName} " : "";
var description = !string.IsNullOrEmpty(Description) ? $"({Description})" : "";
return $"{name}{description}";
}
public static IEnumerable<SerialPortInfo> GetSerialPorts()
{
var ports = new List<SerialPortInfo>();
// HACK: need to make this a configuration option
//using (var mc = new ManagementClass("Win32_SerialPort"))
//{
// foreach (ManagementObject mo in mc.GetInstances())
// {
// ports.Add(new SerialPortInfo(
// (string)mo.GetPropertyValue("DeviceID"),
// (string)mo.GetPropertyValue("Description")));
// }
//}
// HACK: the above wasn't working on a different machine
foreach (var name in SerialPort.GetPortNames())
if (!ports.Any(p => name.Equals(p.PortName, System.StringComparison.OrdinalIgnoreCase)))
ports.Add(new SerialPortInfo(name, null));
return ports;
// SerialPort.GetPortNames() doesn't update while the application is open if
// a device is unplugged; the same is true of the following registry keys:
// using (var key = Registry.LocalMachine.OpenSubKey(@"HARDWARE\DEVICEMAP\SERIALCOMM"))
// Console.WriteLine("Registry: " + string.Join(", ", key.GetValueNames().Select(name => key.GetValue(name).ToString()).ToArray()));
// WMI doesn't seem to be "sticky" in this way.
}
}
}