Skip to content

Commit 708cfe7

Browse files
committed
Refactoring, event handling
- General code cleanup throughout files - Refactored Disconnect subroutine in the Socket class; there is no more "silent" operation, and the SocketDisconnected event is always raised regardless of result. We will also avoid trying to log out when not already logged in. - Added a ToString function to UPS_Device to give the UPSName property. I'm realizing that depending on a valid instance of Nut_Config for any of the properties to successfully return is fairly problematic, so this may necessitate the need to migrate to Nut.Net. - Made the Disconnect subroutine in UPS_Device the final stop for handling exceptions generated during the procedure. Any communication is raised as events back to a listening client. - Removed unused Watchdog subroutine
1 parent 380ffdf commit 708cfe7

File tree

3 files changed

+53
-90
lines changed

3 files changed

+53
-90
lines changed

Diff for: WinNUT_V2/WinNUT-Client/WinNUT.vb

+10-11
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,7 @@ Public Class WinNUT
297297
Arr_Reg_Key.Item("AutoReconnect"))
298298

299299
UPS_Device = New UPS_Device(Nut_Config, LogFile, Arr_Reg_Key.Item("Delay"))
300+
AddHandler UPS_Device.EncounteredNUTException, AddressOf HandleNUTException
300301
UPS_Device.Connect_UPS(retryOnConnFailure)
301302
End Sub
302303

@@ -331,15 +332,16 @@ Public Class WinNUT
331332
End Sub
332333

333334
''' <summary>
334-
''' Prepare application for and handle disconnecting from the UPS.
335+
''' Prepare application for and initiate disconnecting from the UPS.
335336
''' </summary>
336-
Private Sub UPSDisconnect() ' Handles UPS_Device.Disconnected
337-
' LogFile.LogTracing("Running Client disconnect subroutine.", LogLvl.LOG_DEBUG, Me)
337+
Private Sub UPSDisconnect()
338+
LogFile.LogTracing("Running Client disconnect subroutine.", LogLvl.LOG_DEBUG, Me)
338339

339340
If UPS_Device IsNot Nothing Then
340341
UPS_Device.Disconnect(True)
342+
RemoveHandler UPS_Device.EncounteredNUTException, AddressOf HandleNUTException
341343
Else
342-
LogFile.LogTracing("Attempted to disconnect when UPS_Device is Nothing.", LogLvl.LOG_DEBUG, Me)
344+
LogFile.LogTracing("Attempted to disconnect when UPS_Device is Nothing.", LogLvl.LOG_ERROR, Me)
343345
End If
344346
End Sub
345347

@@ -415,18 +417,14 @@ Public Class WinNUT
415417
NotifyIcon.Visible = True
416418
e.Cancel = True
417419
Else
418-
' TODO: Common shutdown subroutine? --v
419420
LogFile.LogTracing("Init Disconnecting Before Close WinNut", LogLvl.LOG_DEBUG, Me)
420-
RemoveHandler Microsoft.Win32.SystemEvents.PowerModeChanged, AddressOf SystemEvents_PowerModeChanged
421421
UPSDisconnect()
422-
LogFile.LogTracing("WinNut Is now Closed", LogLvl.LOG_DEBUG, Me)
423-
End
424422
End If
425423
End Sub
426424

427425
Private Sub Menu_Quit_Click_1(sender As Object, e As EventArgs) Handles Menu_Quit.Click
428426
LogFile.LogTracing("Close WinNut From Menu Quit", LogLvl.LOG_DEBUG, Me)
429-
End
427+
Application.Exit()
430428
End Sub
431429

432430
Private Sub Menu_Settings_Click(sender As Object, e As EventArgs) Handles Menu_Settings.Click
@@ -439,7 +437,7 @@ Public Class WinNUT
439437

440438
Private Sub Menu_Sys_Exit_Click(sender As Object, e As EventArgs) Handles Menu_Sys_Exit.Click
441439
LogFile.LogTracing("Close WinNut From Systray", LogLvl.LOG_DEBUG, Me)
442-
End
440+
Application.Exit()
443441
End Sub
444442

445443
Private Sub Menu_Sys_Settings_Click(sender As Object, e As EventArgs) Handles Menu_Sys_Settings.Click
@@ -572,11 +570,12 @@ Public Class WinNUT
572570
LogFile.LogTracing("Battery Status => " & Status, LogLvl.LOG_DEBUG, Me)
573571
End Sub
574572

575-
Sub HandleNUTException(ex As NutException, sender As Object) Handles UPS_Device.EncounteredNUTException
573+
Private Sub HandleNUTException(sender As UPS_Device, ex As NutException)
576574
If ex.LastTransaction.ResponseType = NUTResponse.UNKNOWNUPS Then
577575
Event_Unknown_UPS()
578576
End If
579577

578+
LogFile.LogTracing("NUT protocol error encoutnered:" + vbNewLine + ex.ToString(), LogLvl.LOG_NOTICE, sender)
580579
End Sub
581580

582581
Public Sub Event_Unknown_UPS() ' Handles UPS_Device.Unknown_UPS

Diff for: WinNUT_V2/WinNUT-Client_Common/Nut_Socket.vb

+11-21
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@
1010

1111

1212
' Class dealing only with the management of the communication socket with the Nut server
13-
Imports System.Net.Sockets
1413
Imports System.IO
14+
Imports System.Net.Sockets
1515

1616
Public Class Nut_Socket
1717

@@ -79,12 +79,6 @@ Public Class Nut_Socket
7979
Public Sub New(Nut_Config As Nut_Parameter, ByRef logger As Logger)
8080
LogFile = logger
8181
NutConfig = Nut_Config
82-
83-
'With Me.WatchDog
84-
' .Interval = 1000
85-
' .Enabled = False
86-
' AddHandler .Tick, AddressOf Event_WatchDog
87-
'End With
8882
End Sub
8983

9084
Public Sub Connect()
@@ -111,7 +105,7 @@ Public Class Nut_Socket
111105

112106
' Something went wrong - cleanup and pass along error.
113107
Catch Excep As Exception
114-
Disconnect(True, True)
108+
Disconnect(True)
115109
Throw ' Pass exception on up to UPS
116110
End Try
117111

@@ -167,19 +161,15 @@ Public Class Nut_Socket
167161
''' <summary>
168162
''' Perform various functions necessary to disconnect the socket from the NUT server.
169163
''' </summary>
170-
''' <param name="Silent">Skip raising the <see cref="SocketDisconnected"/> event if true.</param>
171164
''' <param name="Forceful">Skip sending the LOGOUT command to the NUT server. Unknown effects.</param>
172-
Public Sub Disconnect(Optional silent = False, Optional forceful = False)
173-
' WatchDog.Stop()
174-
175-
If IsConnected AndAlso Not forceful Then
176-
Query_Data("LOGOUT")
177-
End If
178-
179-
Close_Socket()
180-
181-
If Not silent Then
182-
RaiseEvent SocketDisconnected()
165+
Public Sub Disconnect(Optional forceful = False)
166+
If Not forceful AndAlso IsConnected AndAlso IsLoggedIn Then
167+
Try
168+
Query_Data("LOGOUT")
169+
Finally
170+
Close_Socket()
171+
RaiseEvent SocketDisconnected()
172+
End Try
183173
End If
184174
End Sub
185175

@@ -391,7 +381,7 @@ Public Class Nut_Socket
391381
Private Sub Event_WatchDog(sender As Object, e As EventArgs)
392382
Dim Nut_Query = Query_Data("")
393383
If Nut_Query.ResponseType = NUTResponse.NORESPONSE Then
394-
Disconnect(True, True)
384+
Disconnect(True)
395385
RaiseEvent Socket_Broken(New NutException(Nut_Query))
396386
End If
397387
End Sub

Diff for: WinNUT_V2/WinNUT-Client_Common/UPS_Device.vb

+32-58
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,17 @@ Public Class UPS_Device
1515

1616
Public ReadOnly Property Name As String
1717
Get
18-
Return Nut_Config.UPSName
18+
If Nut_Config IsNot Nothing Then
19+
Return Nut_Config.UPSName
20+
Else
21+
Return "null"
22+
End If
1923
End Get
2024
End Property
2125

2226
Public ReadOnly Property IsConnected As Boolean
2327
Get
24-
Return (Nut_Socket.IsConnected) ' And Me.Socket_Status
28+
Return (Nut_Socket.IsConnected)
2529
End Get
2630
End Property
2731

@@ -74,11 +78,18 @@ Public Class UPS_Device
7478
Public Event Lost_Connect()
7579
' Error encountered when trying to connect.
7680
Public Event ConnectionError(sender As UPS_Device, innerException As Exception)
77-
Public Event EncounteredNUTException(ex As NutException, sender As Object)
7881
Public Event New_Retry()
7982
' Public Event Shutdown_Condition()
8083
' Public Event Stop_Shutdown()
8184

85+
''' <summary>
86+
''' Raised when the NUT server returns an error during normal communication and is deemed important for the client
87+
''' application to know.
88+
''' </summary>
89+
''' <param name="sender">The device object that has received the error.</param>
90+
''' <param name="nutEx">An exception detailing the error and cirucmstances surrounding it.</param>
91+
Public Event EncounteredNUTException(sender As UPS_Device, nutEx As NutException)
92+
8293
#End Region
8394

8495
Private Const CosPhi As Double = 0.6
@@ -124,13 +135,7 @@ Public Class UPS_Device
124135
With Reconnect_Nut
125136
.Interval = DEFAULT_RECONNECT_WAIT_MS
126137
.Enabled = False
127-
' AddHandler .Tick, AddressOf Reconnect_Socket
128138
End With
129-
'With WatchDog
130-
' .Interval = 1000
131-
' .Enabled = False
132-
' AddHandler .Tick, AddressOf Event_WatchDog
133-
'End With
134139
End Sub
135140

136141
Public Sub Connect_UPS(Optional retryOnConnFailure = False)
@@ -144,7 +149,7 @@ Public Class UPS_Device
144149
RaiseEvent Connected(Me)
145150
Catch ex As NutException
146151
' This is how we determine if we have a valid UPS name entered, among other errors.
147-
RaiseEvent EncounteredNUTException(ex, Me)
152+
RaiseEvent EncounteredNUTException(Me, ex)
148153

149154
Catch ex As Exception
150155
RaiseEvent ConnectionError(Me, ex)
@@ -156,33 +161,23 @@ Public Class UPS_Device
156161
End Try
157162
End Sub
158163

159-
'Private Sub HandleDisconnectRequest(sender As Object, Optional cancelAutoReconnect As Boolean = True) Handles Me.RequestDisconnect
160-
' If disconnectInProgress Then
161-
' Throw New InvalidOperationException("Disconnection already in progress.")
162-
' End If
163-
164-
' ' WatchDog.Stop()
165-
166-
' If cancelAutoReconnect And Reconnect_Nut.Enabled = True Then
167-
' Debug.WriteLine("Cancelling ")
168-
' End If
169-
'End Sub
170-
171-
Public Sub Disconnect(Optional cancelReconnect As Boolean = True, Optional silent As Boolean = False, Optional forceful As Boolean = False)
164+
Public Sub Disconnect(Optional cancelReconnect As Boolean = True, Optional forceful As Boolean = False)
172165
LogFile.LogTracing("Processing request to disconnect...", LogLvl.LOG_DEBUG, Me)
173-
' WatchDog.Stop()
166+
174167
Update_Data.Stop()
175168
If cancelReconnect And Reconnect_Nut.Enabled Then
176169
LogFile.LogTracing("Stopping Reconnect timer.", LogLvl.LOG_DEBUG, Me)
177170
Reconnect_Nut.Stop()
178171
End If
179172

180173
Retry = 0
181-
Nut_Socket.Disconnect(silent, forceful)
182-
' Confirmation of disconnection will come from raised Disconnected event.
183-
184-
'LogFile.LogTracing("Completed disconnecting UPS, notifying listeners.", LogLvl.LOG_DEBUG, Me)
185-
'RaiseEvent Disconnected()
174+
Try
175+
Nut_Socket.Disconnect(forceful)
176+
Catch nutEx As NutException
177+
RaiseEvent EncounteredNUTException(Me, nutEx)
178+
Finally
179+
RaiseEvent Disconnected()
180+
End Try
186181
End Sub
187182

188183
#Region "Socket Interaction"
@@ -193,29 +188,8 @@ Public Class UPS_Device
193188
RaiseEvent Disconnected()
194189
End Sub
195190

196-
''' <summary>
197-
''' Check underlying connection for an error state by sending an empty query to the server.
198-
''' A watchdog may not actually be necessary under normal circumstances, since queries are regularly being sent to
199-
''' the NUT server and will catch a broken socket that way.
200-
''' </summary>
201-
''' <param name="sender"></param>
202-
''' <param name="e"></param>
203-
Private Sub Event_WatchDog(sender As Object, e As EventArgs)
204-
If IsConnected Then
205-
Dim Nut_Query = Nut_Socket.Query_Data("")
206-
If Nut_Query.ResponseType = NUTResponse.NORESPONSE Then
207-
LogFile.LogTracing("WatchDog Socket report a Broken State", LogLvl.LOG_WARNING, Me)
208-
Nut_Socket.Disconnect(True)
209-
RaiseEvent Lost_Connect()
210-
' Me.Socket_Status = False
211-
End If
212-
End If
213-
End Sub
214-
215191
Private Sub Socket_Broken() Handles Nut_Socket.Socket_Broken
216-
' LogFile.LogTracing("TCP Socket seems Broken", LogLvl.LOG_WARNING, Me)
217192
LogFile.LogTracing("Socket has reported a Broken event.", LogLvl.LOG_WARNING, Me)
218-
' SocketDisconnected()
219193
RaiseEvent Lost_Connect()
220194

221195
If Nut_Config.AutoReconnect Then
@@ -228,7 +202,7 @@ Public Class UPS_Device
228202
Retry += 1
229203
If Retry <= MaxRetry Then
230204
RaiseEvent New_Retry()
231-
LogFile.LogTracing(String.Format("Try Reconnect {0} / {1}", Retry, MaxRetry), LogLvl.LOG_NOTICE, Me, String.Format(WinNUT_Globals.StrLog.Item(AppResxStr.STR_LOG_NEW_RETRY), Retry, MaxRetry))
205+
LogFile.LogTracing(String.Format("Try Reconnect {0} / {1}", Retry, MaxRetry), LogLvl.LOG_NOTICE, Me, String.Format(StrLog.Item(AppResxStr.STR_LOG_NEW_RETRY), Retry, MaxRetry))
232206
Connect_UPS()
233207
If IsConnected Then
234208
LogFile.LogTracing("Nut Host Reconnected", LogLvl.LOG_DEBUG, Me)
@@ -237,9 +211,7 @@ Public Class UPS_Device
237211
RaiseEvent ReConnected(Me)
238212
End If
239213
Else
240-
LogFile.LogTracing("Max Retry reached. Stop Process Autoreconnect and wait for manual Reconnection", LogLvl.LOG_ERROR, Me, WinNUT_Globals.StrLog.Item(AppResxStr.STR_LOG_STOP_RETRY))
241-
'Reconnect_Nut.Stop()
242-
'RaiseEvent Disconnected()
214+
LogFile.LogTracing("Max Retry reached. Stop Process Autoreconnect and wait for manual Reconnection", LogLvl.LOG_ERROR, Me, StrLog.Item(AppResxStr.STR_LOG_STOP_RETRY))
243215
Disconnect(True)
244216
End If
245217
End Sub
@@ -259,7 +231,7 @@ Public Class UPS_Device
259231

260232
' Other constant values for UPS calibration.
261233
freshData.UPS_Value.Batt_Capacity = Double.Parse(GetUPSVar("battery.capacity", 7), ciClone)
262-
Freq_Fallback = Double.Parse(GetUPSVar("output.frequency.nominal", (50 + CInt(WinNUT_Params.Arr_Reg_Key.Item("FrequencySupply")) * 10)), ciClone)
234+
Freq_Fallback = Double.Parse(GetUPSVar("output.frequency.nominal", (50 + CInt(Arr_Reg_Key.Item("FrequencySupply")) * 10)), ciClone)
263235

264236
Return freshData
265237
End Function
@@ -340,10 +312,8 @@ Public Class UPS_Device
340312
Catch Excep As Exception
341313
' Something went wrong while trying to read the data... Consider the socket broken and proceed from here.
342314
LogFile.LogTracing("Something went wrong in Retrieve_UPS_Datas: " & Excep.ToString(), LogLvl.LOG_ERROR, Me)
343-
Disconnect(False, True, True)
315+
Disconnect(False, True)
344316
Socket_Broken()
345-
'Me.Disconnect(True)
346-
'Enter_Reconnect_Process(Excep, "Error When Retrieve_UPS_Data : ")
347317
End Try
348318
End Sub
349319

@@ -435,4 +405,8 @@ Public Class UPS_Device
435405
End Try
436406
Return StringArray(StringArray.Length - 1)
437407
End Function
408+
409+
Public Overrides Function ToString() As String
410+
Return Name
411+
End Function
438412
End Class

0 commit comments

Comments
 (0)