2 * Copyright (c) 2010-2020 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.lcn.internal.connection;
15 import java.io.IOException;
16 import java.net.InetSocketAddress;
17 import java.net.StandardSocketOptions;
18 import java.nio.channels.AsynchronousSocketChannel;
19 import java.nio.channels.CompletionHandler;
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.openhab.binding.lcn.internal.common.LcnException;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
28 * This state is active during the socket creation, host name resolving and waiting for the TCP connection to become
31 * @author Fabian Wolter - Initial Contribution
34 public class ConnectionStateConnecting extends AbstractConnectionState {
35 private final Logger logger = LoggerFactory.getLogger(ConnectionStateConnecting.class);
37 public ConnectionStateConnecting(ConnectionStateMachine context) {
42 public void startWorking() {
43 connection.clearRuntimeData();
45 logger.debug("Connecting to {}:{} ...", connection.getSettings().getAddress(),
46 connection.getSettings().getPort());
49 // Open Channel by using the system-wide default AynchronousChannelGroup.
50 // So, Threads are used or re-used on demand by the JVM.
51 AsynchronousSocketChannel channel = AsynchronousSocketChannel.open();
52 // Do not wait until some buffer is filled, send PCK commands immediately
53 channel.setOption(StandardSocketOptions.TCP_NODELAY, true);
54 connection.setSocketChannel(channel);
56 InetSocketAddress address = new InetSocketAddress(connection.getSettings().getAddress(),
57 connection.getSettings().getPort());
59 if (address.isUnresolved()) {
60 throw new LcnException("Could not resolve hostname");
63 channel.connect(address, null, new CompletionHandler<@Nullable Void, @Nullable Void>() {
65 public void completed(@Nullable Void result, @Nullable Void attachment) {
66 connection.readAndProcess();
67 nextState(ConnectionStateSendUsername::new);
71 public void failed(@Nullable Throwable e, @Nullable Void attachment) {
72 handleConnectionFailure(e);
75 } catch (IOException | LcnException e) {
76 handleConnectionFailure(e);
80 private void handleConnectionFailure(@Nullable Throwable e) {
83 logger.warn("Could not connect to {}:{}: {}", connection.getSettings().getAddress(),
84 connection.getSettings().getPort(), e.getMessage());
85 message = e.getMessage();
89 connection.getCallback().onOffline(message);
90 context.handleConnectionFailed(e);
94 public void onPckMessageReceived(String data) {