Skip to content

Commit 031bee4

Browse files
committed
Login, socket improvements
Nut_Socket.vb - Removed Socket object and any relating code since TcpClient is already providing the functionality. - Remove Disconnected event since this will be provided through exceptions or intentional commands. - Fixed use of LOGIN protocol command - Simplify Disconnect method UPS_Device.vb - Created dedicated Login method that interfaces with the socket layer. WinNUT.vb - Calls Login method only when a username is provided. Fixes forced/unintended logins.
1 parent ef93c30 commit 031bee4

File tree

3 files changed

+78
-93
lines changed

3 files changed

+78
-93
lines changed

WinNUT_V2/WinNUT-Client/WinNUT.vb

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -383,6 +383,10 @@ Public Class WinNUT
383383
UPS_Device = New UPS_Device(Nut_Config, LogFile, My.Settings.NUT_PollIntervalMsec, My.Settings.CAL_FreqInNom)
384384
AddHandler UPS_Device.EncounteredNUTException, AddressOf HandleNUTException
385385
UPS_Device.Connect_UPS(retryOnConnFailure)
386+
387+
If Not String.IsNullOrEmpty(Nut_Config.Login) Then
388+
UPS_Device.Login()
389+
End If
386390
End Sub
387391

388392
''' <summary>
@@ -409,8 +413,8 @@ Public Class WinNUT
409413
End Sub
410414

411415
Private Sub ConnectionError(sender As UPS_Device, ex As Exception) Handles UPS_Device.ConnectionError
412-
LogFile.LogTracing(String.Format("Something went wrong connecting to UPS {0}. IsConnected: {1}, IsAuthenticated: {2}",
413-
sender.Name, sender.IsConnected, sender.IsAuthenticated), LogLvl.LOG_ERROR, Me,
416+
LogFile.LogTracing(String.Format("Something went wrong connecting to UPS {0}. IsConnected: {1}, IsLoggedIn: {2}",
417+
sender.Name, sender.IsConnected, sender.IsLoggedIn), LogLvl.LOG_ERROR, Me,
414418
String.Format(StrLog.Item(AppResxStr.STR_LOG_CON_FAILED), sender.Nut_Config.Host, sender.Nut_Config.Port,
415419
ex.Message))
416420
End Sub

WinNUT_V2/WinNUT-Client_Common/Nut_Socket.vb

Lines changed: 49 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -11,18 +11,15 @@
1111

1212
' Class dealing only with the management of the communication socket with the Nut server
1313
Imports System.IO
14+
Imports System.Net
1415
Imports System.Net.Sockets
1516

1617
Public Class Nut_Socket
1718

1819
#Region "Properties"
1920
Public ReadOnly Property ConnectionStatus As Boolean
2021
Get
21-
If NutSocket IsNot Nothing Then
22-
Return NutSocket.Connected
23-
Else
24-
Return False
25-
End If
22+
Return client.Connected
2623
End Get
2724
End Property
2825

@@ -58,8 +55,7 @@ Public Class Nut_Socket
5855
Private NutConfig As Nut_Parameter
5956

6057
'Socket Variables
61-
Private NutSocket As Socket
62-
Private NutTCP As TcpClient
58+
Private client As New TcpClient
6359
Private NutStream As NetworkStream
6460
Private ReaderStream As StreamReader
6561
Private WriterStream As StreamWriter
@@ -71,11 +67,6 @@ Public Class Nut_Socket
7167

7268
Public Event Socket_Broken(ex As NutException)
7369

74-
''' <summary>
75-
''' Socket was disconnected as a part of normal operations.
76-
''' </summary>
77-
Public Event SocketDisconnected()
78-
7970
Public Sub New(Nut_Config As Nut_Parameter, ByRef logger As Logger)
8071
LogFile = logger
8172
NutConfig = Nut_Config
@@ -93,67 +84,53 @@ Public Class Nut_Socket
9384
End If
9485

9586
Try
96-
' NutSocket = New Socket(AddressFamily.InterNetwork, ProtocolType.IP)
97-
NutSocket = New Socket(SocketType.Stream, ProtocolType.IP)
9887
LogFile.LogTracing(String.Format("Attempting TCP socket connection to {0}:{1}...", Host, Port), LogLvl.LOG_NOTICE, Me)
99-
NutSocket.Connect(Host, Port)
100-
NutTCP = New TcpClient(Host, Port)
101-
NutStream = NutTCP.GetStream
88+
89+
client.Connect(Host, Port)
90+
NutStream = client.GetStream()
10291
ReaderStream = New StreamReader(NutStream)
10392
WriterStream = New StreamWriter(NutStream)
104-
LogFile.LogTracing(String.Format("Connection established and streams ready for {0}:{1}", Host, Port), LogLvl.LOG_NOTICE, Me)
10593

106-
' Something went wrong - cleanup and pass along error.
94+
LogFile.LogTracing("Connection established and streams ready.", LogLvl.LOG_NOTICE, Me)
95+
10796
Catch Excep As Exception
10897
Disconnect(True)
10998
Throw ' Pass exception on up to UPS
11099
End Try
111100

112-
If ConnectionStatus Then
113-
Try
114-
AuthLogin(Login, Password)
115-
Catch ex As NutException
116-
' TODO: Make friendly message string for user.
117-
LogFile.LogTracing("Error while attempting to log in: " & ex.Message, LogLvl.LOG_ERROR, Me)
118-
End Try
101+
Dim Nut_Query = Query_Data("VER")
119102

120-
Dim Nut_Query = Query_Data("VER")
121-
122-
If Nut_Query.ResponseType = NUTResponse.OK Then
123-
Nut_Ver = (Nut_Query.RawResponse.Split(" "c))(4)
124-
End If
125-
Nut_Query = Query_Data("NETVER")
126-
127-
If Nut_Query.ResponseType = NUTResponse.OK Then
128-
Net_Ver = Nut_Query.RawResponse
129-
End If
103+
If Nut_Query.ResponseType = NUTResponse.OK Then
104+
Nut_Ver = (Nut_Query.RawResponse.Split(" "c))(4)
105+
End If
106+
Nut_Query = Query_Data("NETVER")
130107

131-
LogFile.LogTracing(String.Format("NUT server reports VER: {0} NETVER: {1}", Nut_Ver, Net_Ver), LogLvl.LOG_NOTICE, Me)
108+
If Nut_Query.ResponseType = NUTResponse.OK Then
109+
Net_Ver = Nut_Query.RawResponse
132110
End If
111+
112+
LogFile.LogTracing(String.Format("NUT server reports VER: {0} NETVER: {1}", Nut_Ver, Net_Ver), LogLvl.LOG_NOTICE, Me)
133113
End Sub
134114

135-
''' <summary>
136-
''' Register with the UPSd server as being dependant on it for power.
137-
''' </summary>
138-
''' <param name="Login"></param>
139-
''' <param name="Password"></param>
140-
''' <exception cref="NutException">A protocol error was encountered while trying to authenticate.</exception>
141-
Private Sub AuthLogin(Login As String, Password As String)
115+
Public Sub Login()
142116
If _isLoggedIn Then
143117
Throw New InvalidOperationException("Attempted to login when already logged in.")
144118
End If
145119

146-
LogFile.LogTracing("Attempting authentication...", LogLvl.LOG_NOTICE, Me)
120+
LogFile.LogTracing(String.Format("Logging in to UPS [{0}] as user [{1}] ({2})...",
121+
NutConfig.UPSName, NutConfig.Login,
122+
If(String.IsNullOrEmpty(NutConfig.Password),
123+
"NO Password", "Password provided")), LogLvl.LOG_NOTICE, Me)
147124

148-
If Not String.IsNullOrEmpty(Login) Then
149-
Query_Data("USERNAME " & Login)
125+
If Not String.IsNullOrEmpty(NutConfig.Login) Then
126+
Query_Data("USERNAME " & NutConfig.Login)
150127

151-
If Not String.IsNullOrEmpty(Password) Then
152-
Query_Data("PASSWORD " & Password)
128+
If Not String.IsNullOrEmpty(NutConfig.Password) Then
129+
Query_Data("PASSWORD " & NutConfig.Password)
153130
End If
154131
End If
155132

156-
Query_Data("LOGIN")
133+
Query_Data("LOGIN " & NutConfig.UPSName)
157134
_isLoggedIn = True
158135
LogFile.LogTracing("Authenticated successfully.", LogLvl.LOG_NOTICE, Me)
159136
End Sub
@@ -163,12 +140,29 @@ Public Class Nut_Socket
163140
''' </summary>
164141
''' <param name="forceful">Skip sending the LOGOUT command to the NUT server. Unknown effects.</param>
165142
Public Sub Disconnect(Optional forceful = False)
166-
If Not forceful AndAlso IsConnected AndAlso IsLoggedIn Then
167-
Query_Data("LOGOUT")
168-
End If
143+
If IsConnected Then
144+
If IsLoggedIn AndAlso Not forceful Then
145+
Query_Data("LOGOUT")
146+
End If
169147

170-
Close_Socket()
171-
RaiseEvent SocketDisconnected()
148+
If WriterStream IsNot Nothing Then
149+
WriterStream.Close()
150+
End If
151+
152+
If ReaderStream IsNot Nothing Then
153+
ReaderStream.Close()
154+
End If
155+
156+
If NutStream IsNot Nothing Then
157+
NutStream.Close()
158+
End If
159+
160+
If client IsNot Nothing Then
161+
client.Close()
162+
End If
163+
Else
164+
Throw New InvalidOperationException("NUT Socket is already disconnected.")
165+
End If
172166
End Sub
173167

174168
''' <summary>
@@ -383,31 +377,4 @@ Public Class Nut_Socket
383377
RaiseEvent Socket_Broken(New NutException(Nut_Query))
384378
End If
385379
End Sub
386-
387-
Private Sub Close_Socket()
388-
Try
389-
If WriterStream IsNot Nothing Then
390-
WriterStream.Close()
391-
End If
392-
393-
If ReaderStream IsNot Nothing Then
394-
ReaderStream.Close()
395-
End If
396-
397-
If NutStream IsNot Nothing Then
398-
NutStream.Close()
399-
End If
400-
401-
If NutTCP IsNot Nothing Then
402-
NutTCP.Close()
403-
End If
404-
405-
If NutSocket IsNot Nothing Then
406-
NutSocket.Close()
407-
End If
408-
Catch Excep As Exception
409-
LogFile.LogTracing("Error encountered while shutting down socket: " & vbNewLine & Excep.ToString(),
410-
LogLvl.LOG_ERROR, Me)
411-
End Try
412-
End Sub
413380
End Class

WinNUT_V2/WinNUT-Client_Common/UPS_Device.vb

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,7 @@ Public Class UPS_Device
3737
Return (Nut_Socket.IsConnected)
3838
End Get
3939
End Property
40-
41-
Public ReadOnly Property IsAuthenticated As Boolean
40+
Public ReadOnly Property IsLoggedIn As Boolean
4241
Get
4342
Return Nut_Socket.IsLoggedIn
4443
End Get
@@ -154,6 +153,7 @@ Public Class UPS_Device
154153
UPS_Datas = GetUPSProductInfo()
155154
Update_Data.Start()
156155
RaiseEvent Connected(Me)
156+
157157
Catch ex As NutException
158158
' This is how we determine if we have a valid UPS name entered, among other errors.
159159
RaiseEvent EncounteredNUTException(Me, ex)
@@ -168,6 +168,21 @@ Public Class UPS_Device
168168
End Try
169169
End Sub
170170

171+
Public Sub Login()
172+
If Not IsConnected OrElse IsLoggedIn Then
173+
Throw New InvalidOperationException("UPS is in an invalid state to login.")
174+
End If
175+
176+
If Not String.IsNullOrEmpty(Nut_Config.Login) Then
177+
Try
178+
Nut_Socket.Login()
179+
Catch ex As NutException
180+
LogFile.LogTracing("Error while attempting to log in.", LogLvl.LOG_ERROR, Me)
181+
RaiseEvent EncounteredNUTException(Me, ex)
182+
End Try
183+
End If
184+
End Sub
185+
171186
Public Sub Disconnect(Optional cancelReconnect As Boolean = True, Optional forceful As Boolean = False)
172187
LogFile.LogTracing("Processing request to disconnect...", LogLvl.LOG_DEBUG, Me)
173188

@@ -179,7 +194,7 @@ Public Class UPS_Device
179194

180195
Retry = 0
181196
Try
182-
Nut_Socket.Disconnect(forceful)
197+
183198
Catch nutEx As NutException
184199
RaiseEvent EncounteredNUTException(Me, nutEx)
185200
Finally
@@ -189,12 +204,6 @@ Public Class UPS_Device
189204

190205
#Region "Socket Interaction"
191206

192-
Private Sub SocketDisconnected() Handles Nut_Socket.SocketDisconnected
193-
LogFile.LogTracing("NutSocket raised Disconnected event.", LogLvl.LOG_DEBUG, Me)
194-
195-
RaiseEvent Disconnected()
196-
End Sub
197-
198207
Private Sub Socket_Broken() Handles Nut_Socket.Socket_Broken
199208
LogFile.LogTracing("Socket has reported a Broken event.", LogLvl.LOG_WARNING, Me)
200209
RaiseEvent Lost_Connect()
@@ -215,6 +224,11 @@ Public Class UPS_Device
215224
LogFile.LogTracing("Nut Host Reconnected", LogLvl.LOG_DEBUG, Me)
216225
Reconnect_Nut.Stop()
217226
Retry = 0
227+
228+
If Not String.IsNullOrEmpty(Nut_Config.Login) Then
229+
Login()
230+
End If
231+
218232
RaiseEvent ReConnected(Me)
219233
End If
220234
Else

0 commit comments

Comments
 (0)