45
45
import org .slf4j .LoggerFactory ;
46
46
47
47
import java .util .Collections ;
48
- import java .util .HashMap ;
49
48
import java .util .List ;
50
49
import java .util .Map ;
51
50
import java .util .Objects ;
52
51
import java .util .function .Function ;
53
52
import java .util .stream .Collectors ;
54
53
55
54
import static com .hivemq .adapter .sdk .api .state .ProtocolAdapterState .ConnectionStatus .CONNECTED ;
55
+ import static com .hivemq .adapter .sdk .api .state .ProtocolAdapterState .ConnectionStatus .ERROR ;
56
56
57
57
/**
58
58
* Abstract PLC4X implementation. Exposes core abstractions of the underlying framework so instances can be exposes
@@ -135,9 +135,28 @@ public void poll(final @NotNull BatchPollingInput pollingInput, final @NotNull B
135
135
public void start (
136
136
final @ NotNull ProtocolAdapterStartInput input , final @ NotNull ProtocolAdapterStartOutput output ) {
137
137
try {
138
- // we do not subscribe anymore as no current adapter type supports it anyway
139
- initConnection ();
140
- output .startedSuccessfully ();
138
+ if (connection == null ) {
139
+ synchronized (lock ) {
140
+ if (connection == null ) {
141
+ // we do not subscribe anymore as no current adapter type supports it anyway
142
+ if (log .isTraceEnabled ()) {
143
+ log .trace ("Creating new instance of Plc4x connector with {}." , adapterConfig );
144
+ }
145
+ final Plc4xConnection <T > connection = createConnection ();
146
+ if (connection .isConnected ()) {
147
+ protocolAdapterState .setConnectionStatus (CONNECTED );
148
+ output .startedSuccessfully ();
149
+ } else {
150
+ protocolAdapterState .setConnectionStatus (ERROR );
151
+ output .failStart (new Plc4xException ("Unable to connect to device" ), "Unable to connect to device" );
152
+ }
153
+
154
+ this .connection = connection ;
155
+ }
156
+ }
157
+ } else {
158
+ output .startedSuccessfully ();
159
+ }
141
160
} catch (final Exception e ) {
142
161
output .failStart (e , null );
143
162
}
@@ -164,26 +183,6 @@ public void stop(final @NotNull ProtocolAdapterStopInput input, final @NotNull P
164
183
return adapterInformation ;
165
184
}
166
185
167
- private Plc4xConnection <T > initConnection () {
168
- if (connection == null ) {
169
- synchronized (lock ) {
170
- if (connection == null ) {
171
- try {
172
- if (log .isTraceEnabled ()) {
173
- log .trace ("Creating new instance of Plc4x connector with {}." , adapterConfig );
174
- }
175
- connection = createConnection ();
176
- protocolAdapterState .setConnectionStatus (CONNECTED );
177
- return connection ;
178
- } catch (final Plc4xException e ) {
179
- throw new RuntimeException (e );
180
- }
181
- }
182
- }
183
- }
184
- return connection ;
185
- }
186
-
187
186
protected @ NotNull Plc4xConnection <T > createConnection () throws Plc4xException {
188
187
return new Plc4xConnection <>(driverManager ,
189
188
adapterConfig ,
0 commit comments