18
18
import java .io .PrintWriter ;
19
19
import java .net .Socket ;
20
20
import java .net .SocketTimeoutException ;
21
+ import java .util .Optional ;
21
22
22
23
import org .eclipse .jdt .annotation .NonNullByDefault ;
23
- import org .eclipse .jdt .annotation .Nullable ;
24
24
import org .openhab .binding .gce .internal .model .M2MMessageParser ;
25
25
import org .openhab .core .thing .ThingUID ;
26
26
import org .slf4j .Logger ;
35
35
*/
36
36
@ NonNullByDefault
37
37
public class Ipx800DeviceConnector extends Thread {
38
- private final Logger logger = LoggerFactory .getLogger (Ipx800DeviceConnector .class );
39
38
private static final int DEFAULT_SOCKET_TIMEOUT_MS = 5000 ;
40
39
private static final int DEFAULT_RECONNECT_TIMEOUT_MS = 5000 ;
41
40
private static final int MAX_KEEPALIVE_FAILURE = 3 ;
42
41
private static final String ENDL = "\r \n " ;
43
42
43
+ private final Logger logger = LoggerFactory .getLogger (Ipx800DeviceConnector .class );
44
+
44
45
private final String hostname ;
45
46
private final int portNumber ;
46
- private @ Nullable M2MMessageParser parser ;
47
47
48
- private @ NonNullByDefault ({}) Socket client ;
49
- private @ NonNullByDefault ({}) BufferedReader in ;
50
- private @ NonNullByDefault ({}) PrintWriter out ;
48
+ private Optional <M2MMessageParser > messageParser = Optional .empty ();
49
+ private Optional <Socket > socket = Optional .empty ();
50
+ private Optional <BufferedReader > input = Optional .empty ();
51
+ private Optional <PrintWriter > output = Optional .empty ();
51
52
52
53
private int failedKeepalive = 0 ;
53
54
private boolean waitingKeepaliveResponse = false ;
@@ -60,9 +61,11 @@ public Ipx800DeviceConnector(String hostname, int portNumber, ThingUID uid) {
60
61
}
61
62
62
63
public synchronized void send (String message ) {
63
- logger .debug ("Sending '{}' to Ipx800" , message );
64
- out .write (message + ENDL );
65
- out .flush ();
64
+ output .ifPresentOrElse (out -> {
65
+ logger .debug ("Sending '{}' to Ipx800" , message );
66
+ out .write (message + ENDL );
67
+ out .flush ();
68
+ }, () -> logger .warn ("Trying to send '{}' while the output stream is closed." , message ));
66
69
}
67
70
68
71
/**
@@ -72,12 +75,15 @@ public synchronized void send(String message) {
72
75
*/
73
76
private void connect () throws IOException {
74
77
disconnect ();
75
- logger .debug ("Connecting {}:{}..." , hostname , portNumber );
76
- client = new Socket (hostname , portNumber );
77
- client .setSoTimeout (DEFAULT_SOCKET_TIMEOUT_MS );
78
- client .getInputStream ().skip (client .getInputStream ().available ());
79
- in = new BufferedReader (new InputStreamReader (client .getInputStream ()));
80
- out = new PrintWriter (client .getOutputStream (), true );
78
+
79
+ logger .debug ("Connecting to {}:{}..." , hostname , portNumber );
80
+ Socket socket = new Socket (hostname , portNumber );
81
+ socket .setSoTimeout (DEFAULT_SOCKET_TIMEOUT_MS );
82
+ socket .getInputStream ().skip (socket .getInputStream ().available ());
83
+ this .socket = Optional .of (socket );
84
+
85
+ input = Optional .of (new BufferedReader (new InputStreamReader (socket .getInputStream ())));
86
+ output = Optional .of (new PrintWriter (socket .getOutputStream (), true ));
81
87
}
82
88
83
89
/**
@@ -86,24 +92,25 @@ private void connect() throws IOException {
86
92
private void disconnect () {
87
93
logger .debug ("Disconnecting" );
88
94
89
- if (in != null ) {
95
+ input . ifPresent (in -> {
90
96
try {
91
97
in .close ();
92
98
} catch (IOException ignore ) {
93
99
}
94
- this . in = null ;
95
- }
96
- if ( out != null ) {
97
- out . close ( );
98
- this . out = null ;
99
- }
100
- if (client != null ) {
100
+ input = Optional . empty () ;
101
+ });
102
+
103
+ output . ifPresent ( PrintWriter :: close );
104
+ output = Optional . empty () ;
105
+
106
+ socket . ifPresent (client -> {
101
107
try {
102
108
client .close ();
103
109
} catch (IOException ignore ) {
104
110
}
105
- this .client = null ;
106
- }
111
+ socket = Optional .empty ();
112
+ });
113
+
107
114
logger .debug ("Disconnected" );
108
115
}
109
116
@@ -120,7 +127,7 @@ public void dispose() {
120
127
* If we don't receive the update maxKeepAliveFailure time, the connection is closed and reopened
121
128
*/
122
129
private void sendKeepalive () {
123
- if (out != null ) {
130
+ output . ifPresent (out -> {
124
131
if (waitingKeepaliveResponse ) {
125
132
failedKeepalive ++;
126
133
logger .debug ("Sending keepalive, attempt {}" , failedKeepalive );
@@ -131,7 +138,7 @@ private void sendKeepalive() {
131
138
out .println ("GetIn01" );
132
139
out .flush ();
133
140
waitingKeepaliveResponse = true ;
134
- }
141
+ });
135
142
}
136
143
137
144
@ Override
@@ -144,15 +151,15 @@ public void run() {
144
151
if (failedKeepalive > MAX_KEEPALIVE_FAILURE ) {
145
152
throw new IOException ("Max keep alive attempts has been reached" );
146
153
}
147
- try {
148
- String command = in .readLine ();
149
- waitingKeepaliveResponse = false ;
150
- if (parser != null ) {
151
- parser .unsolicitedUpdate (command );
154
+ input .ifPresent (in -> {
155
+ try {
156
+ String command = in .readLine ();
157
+ waitingKeepaliveResponse = false ;
158
+ messageParser .ifPresent (parser -> parser .unsolicitedUpdate (command ));
159
+ } catch (IOException e ) {
160
+ handleException (e );
152
161
}
153
- } catch (SocketTimeoutException e ) {
154
- handleException (e );
155
- }
162
+ });
156
163
}
157
164
disconnect ();
158
165
} catch (IOException e ) {
@@ -171,15 +178,13 @@ private void handleException(Exception e) {
171
178
sendKeepalive ();
172
179
return ;
173
180
} else if (e instanceof IOException ) {
174
- logger .warn ("Communication error : '{}', will retry in {} ms" , e , DEFAULT_RECONNECT_TIMEOUT_MS );
175
- }
176
- if (parser != null ) {
177
- parser .errorOccurred (e );
181
+ logger .warn ("Communication error: '{}'. Will retry in {} ms" , e , DEFAULT_RECONNECT_TIMEOUT_MS );
178
182
}
183
+ messageParser .ifPresent (parser -> parser .errorOccurred (e ));
179
184
}
180
185
}
181
186
182
187
public void setParser (M2MMessageParser parser ) {
183
- this .parser = parser ;
188
+ this .messageParser = Optional . of ( parser ) ;
184
189
}
185
190
}
0 commit comments