-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathGet-SerialPort.ps1
232 lines (191 loc) · 6.35 KB
/
Get-SerialPort.ps1
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
New-Module {
<#
.Synopsis
Create a new serial port to read or write to.
.DESCRIPTION
.EXAMPLE
$myport = New-SerialPort
Create a new port with a .net event subscribed to the incoming data
.EXAMPLE
New-SerialPort -outvariable port -Name COM5
Create a new port whislt seing it's configuration.
BaseStream :
BaudRate : 9600
BreakState :
BytesToWrite :
BytesToRead :
CDHolding :
CtsHolding :
DataBits : 8
DiscardNull : False
DsrHolding :
DtrEnable : False
Encoding : System.Text.ASCIIEncoding
Handshake : None
IsOpen : False
NewLine :
Parity : None
ParityReplace : 63
PortName : com5
ReadBufferSize : 4096
ReadTimeout : 1000
ReceivedBytesThreshold : 1
RtsEnable : False
StopBits : One
WriteBufferSize : 2048
WriteTimeout : -1
Site :
Container :
#>
function New-SerialPort {
[CmdletBinding()]
[OutputType([System.IO.Ports.SerialPort])]
Param
(
# Event Identifier
[Parameter()]
[ValidatePattern("[a-zA-Z]\d")]
[String]
$Name = "COM3"
)
$error.Clear()
if (Get-Serialport -Name $Name) {
throw "Name already exists, use Get-SerialPort"
}
$port = InstancePort -Name $Name
if ($port) {
# Print data only when recieved, No polling the port that's crazy talk.
Register-ObjectEvent -InputObject $port -EventName "DataReceived" -SourceIdentifier $Name > $null
}
else {
throw "Port is not defined"
}
$port | Write-Output
}
function Get-SerialPort {
[CmdletBinding()]
[OutputType([System.IO.Ports.SerialPort])]
Param
(
# Name of port to find, default all
[Parameter()]
[string]
$name = '*'
)
$real = [System.IO.Ports.SerialPort]::getportnames() |
ForEach-Object {
new-object -TypeName PSCustomObject -Property @{
"type" = "Physical"
"name" = $psitem.PortName
"port" = $psitem
}
}
# TODO: implement some kind of virtual port
# Wrote all of this without testing if you can open a port that doesn't exist in hardware.
$virtual = Get-EventSubscriber -SourceIdentifier $name -ErrorAction SilentlyContinue |
Select-Object -ExpandProperty SourceObject |
ForEach-Object {
new-object -TypeName PSCustomObject -Property @{
"type" = "Virtual"
"name" = $psitem.PortName
"port" = $psitem
}
}
$real + $virtual | Write-Output
}
function Show-SerialPort {
[CmdletBinding(DefaultParameterSetName = "Name")]
[OutputType([string])]
Param
(
# Serial Port Object
[Parameter(ParameterSetName = "Object",
Mandatory = $true,
Position = 0,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true)]
[System.IO.Ports.SerialPort]
$Port
, # Port Name
[Parameter(ParameterSetName = "Name",
Mandatory = $true,
Position = 0,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true)]
[string]
$Name
)
if ($Name) {
$port = Get-SerialPort -Name $Name |
Where-Object type -eq "Physical" |
Select-Object -ExpandProperty port
}
if (-not $port) {
throw "No physical port found to open."
}
Write-verbose ("Current port open status: " + $port.isOpen)
if ( -not $port.isOpen) { $port.open() }
Write-Verbose "Waiting on data"
while ($true) {
Wait-Event -SourceIdentifier $port.portname -Timeout ($port.ReadTimeout / 1000)
}
# TODO: catch the difference between data or timeout
# Why does this just loop the same event output
Write-Output ($port.ReadExisting())
}
function Remove-SerialPort {
[CmdletBinding()]
[OutputType([PSObject])]
Param
(
# Serial port reference
[Parameter(Position = 0,
Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true)]
[System.IO.Ports.SerialPort[]]
$port
, # Remove all events in log
[switch]
$clean
)
Process {
Write-Verbose "Stop Listening to data"
Write-Verbose "$($port.portname) status: $($port.isOpen)"
$port.Close()
# Free the resources just to be sure it's safely unbound for sucessive runs of the script
$port.Dispose()
# Dispose of the event handler to make sure we're all clean
Unregister-Event $port.portname -ErrorAction SilentlyContinue
switch ($clean) {
$true {
Remove-Event -SourceIdentifier $port.portName -ErrorAction SilentlyContinue
}
Default {}
}
Write-Verbose "Event count: $(get-event | measure | select -expandproperty count)"
}
}
function instancePort() {
[CmdletBinding()]
[OutputType([System.IO.Ports.SerialPort])]
Param
(
# Port Name
[String]
$name = "COM3"
, # Baud Rate
$BaudRate = 9600
, # Parity Bit
$ParityBit = "None"
, # Data Bits
$DataBits = 8
, # Stop Bit
$StopBit = "one"
)
$port = New-Object system.io.ports.serialport $name, $BaudRate, $ParityBit, $DataBits, $StopBit
$port.ReadTimeout = 1000 # milliseconds
Write-Output $port
}
Export-ModuleMember "*-*"
}