Update TCP handling to save connection. Added debug to http handler.

This commit is contained in:
Admin
2017-03-06 16:30:23 -06:00
parent 7b97bd75ae
commit a578aa9fd8
3 changed files with 82 additions and 66 deletions

View File

@@ -5,7 +5,7 @@
<groupId>com.bwssystems.HABridge</groupId> <groupId>com.bwssystems.HABridge</groupId>
<artifactId>ha-bridge</artifactId> <artifactId>ha-bridge</artifactId>
<version>4.2.0b</version> <version>4.2.0c</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>HA Bridge</name> <name>HA Bridge</name>

View File

@@ -5,16 +5,6 @@ import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig;
@@ -34,21 +24,11 @@ import com.bwssystems.HABridge.api.NameValue;
public class HTTPHandler { public class HTTPHandler {
private static final Logger log = LoggerFactory.getLogger(HTTPHandler.class); private static final Logger log = LoggerFactory.getLogger(HTTPHandler.class);
// private HttpClient httpClient;
private CloseableHttpClient httpClient; private CloseableHttpClient httpClient;
// private SSLContext sslcontext;
// private SSLConnectionSocketFactory sslsf;
private RequestConfig globalConfig; private RequestConfig globalConfig;
public HTTPHandler() { public HTTPHandler() {
// httpClient = HttpClients.createDefault();
// Removed Specific SSL as Apache HttpClient automatically uses SSL if the URI starts with https://
// Trust own CA and all self-signed certs
// sslcontext = SSLContexts.createDefault();
// Allow TLSv1 protocol only
// sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLS" }, null,
// SSLConnectionSocketFactory.getDefaultHostnameVerifier());
globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build(); globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig).build(); httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig).build();
} }
@@ -101,14 +81,11 @@ public class HTTPHandler {
request.setHeader(headers[i].getName(), headers[i].getValue()); request.setHeader(headers[i].getName(), headers[i].getValue());
} }
} }
try {
HttpResponse response; HttpResponse response;
// Removed Specific SSL as Apache HttpClient automatically uses SSL if the URI starts with https:// try {
// if (url.startsWith("xyzhttps")) for(int retryCount = 0; retryCount < 2; retryCount++) {
// response = httpclientSSL.execute(request);
// else
response = httpClient.execute(request); response = httpClient.execute(request);
log.debug((httpVerb == null ? "GET" : httpVerb) + " execute on URL responded: " log.debug((httpVerb == null ? "GET" : httpVerb) + " execute (" + retryCount + ") on URL responded: "
+ response.getStatusLine().getStatusCode()); + response.getStatusLine().getStatusCode());
if (response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300) { if (response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300) {
if (response.getEntity() != null) { if (response.getEntity() != null) {
@@ -125,17 +102,35 @@ public class HTTPHandler {
log.debug("Error ocurred in handling response entity after successful call, still responding success. " log.debug("Error ocurred in handling response entity after successful call, still responding success. "
+ e.getMessage(), e); + e.getMessage(), e);
} }
log.debug("Successfull response - The http response is <<<" + theContent + ">>>");
} }
retryCount = 2;
} else { } else {
log.warn("HTTP response code was not an expected successful response of between 200 - 299, the code was: " + response.getStatusLine()); log.warn("HTTP response code was not an expected successful response of between 200 - 299, the code was: " + response.getStatusLine());
try { try {
String someContent = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8")); // read
// content
// for
// data
EntityUtils.consume(response.getEntity()); // close out EntityUtils.consume(response.getEntity()); // close out
// inputstream // inputstream
// ignore // ignore
// content // content
log.debug("Unsuccessfull response - The http response is <<<" + someContent + ">>>");
} catch (Exception e) { } catch (Exception e) {
//noop //noop
} }
if (response.getStatusLine().getStatusCode() == 504) {
log.warn("HTTP response code was 504, retrying...");
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// noop
}
}
else
retryCount = 2;
}
} }
} catch (IOException e) { } catch (IOException e) {
log.warn("Error calling out to HA gateway: IOException in log", e); log.warn("Error calling out to HA gateway: IOException in log", e);

View File

@@ -1,9 +1,13 @@
package com.bwssystems.HABridge.plugins.tcp; package com.bwssystems.HABridge.plugins.tcp;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.Socket; import java.net.Socket;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.xml.bind.DatatypeConverter; import javax.xml.bind.DatatypeConverter;
@@ -21,6 +25,7 @@ import com.bwssystems.HABridge.hue.TimeDecode;
public class TCPHome implements Home { public class TCPHome implements Home {
private static final Logger log = LoggerFactory.getLogger(TCPHome.class); private static final Logger log = LoggerFactory.getLogger(TCPHome.class);
private byte[] sendData; private byte[] sendData;
private Map<String, Socket> theSockets;
public TCPHome(BridgeSettingsDescriptor bridgeSettings) { public TCPHome(BridgeSettingsDescriptor bridgeSettings) {
@@ -31,6 +36,7 @@ public class TCPHome implements Home {
@Override @Override
public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int intensity, public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int intensity,
Integer targetBri,Integer targetBriInc, DeviceDescriptor device, String body) { Integer targetBri,Integer targetBriInc, DeviceDescriptor device, String body) {
Socket dataSendSocket = null;
log.debug("executing HUE api request to TCP: " + anItem.getItem().getAsString()); log.debug("executing HUE api request to TCP: " + anItem.getItem().getAsString());
String theUrl = anItem.getItem().getAsString(); String theUrl = anItem.getItem().getAsString();
if(theUrl != null && !theUrl.isEmpty () && theUrl.startsWith("tcp://")) { if(theUrl != null && !theUrl.isEmpty () && theUrl.startsWith("tcp://")) {
@@ -40,6 +46,8 @@ public class TCPHome implements Home {
String hostAddr = null; String hostAddr = null;
String port = null; String port = null;
InetAddress IPAddress = null; InetAddress IPAddress = null;
dataSendSocket = theSockets.get(hostPortion);
if(dataSendSocket == null) {
if (hostPortion.contains(":")) { if (hostPortion.contains(":")) {
hostAddr = hostPortion.substring(0, intermediate.indexOf(':')); hostAddr = hostPortion.substring(0, intermediate.indexOf(':'));
port = hostPortion.substring(intermediate.indexOf(':') + 1); port = hostPortion.substring(intermediate.indexOf(':') + 1);
@@ -51,6 +59,14 @@ public class TCPHome implements Home {
// noop // noop
} }
try {
dataSendSocket = new Socket(IPAddress, Integer.parseInt(port));
theSockets.put(hostPortion, dataSendSocket);
} catch (Exception e) {
// noop
}
}
theUrlBody = TimeDecode.replaceTimeValue(theUrlBody); theUrlBody = TimeDecode.replaceTimeValue(theUrlBody);
if (theUrlBody.startsWith("0x")) { if (theUrlBody.startsWith("0x")) {
theUrlBody = BrightnessDecode.calculateReplaceIntensityValue(theUrlBody, intensity, targetBri, targetBriInc, true); theUrlBody = BrightnessDecode.calculateReplaceIntensityValue(theUrlBody, intensity, targetBri, targetBriInc, true);
@@ -59,13 +75,10 @@ public class TCPHome implements Home {
theUrlBody = BrightnessDecode.calculateReplaceIntensityValue(theUrlBody, intensity, targetBri, targetBriInc, false); theUrlBody = BrightnessDecode.calculateReplaceIntensityValue(theUrlBody, intensity, targetBri, targetBriInc, false);
sendData = theUrlBody.getBytes(); sendData = theUrlBody.getBytes();
} }
try { try {
Socket dataSendSocket = new Socket(IPAddress, Integer.parseInt(port));
DataOutputStream outToClient = new DataOutputStream(dataSendSocket.getOutputStream()); DataOutputStream outToClient = new DataOutputStream(dataSendSocket.getOutputStream());
outToClient.write(sendData); outToClient.write(sendData);
outToClient.flush(); outToClient.flush();
dataSendSocket.close();
} catch (Exception e) { } catch (Exception e) {
// noop // noop
} }
@@ -77,6 +90,7 @@ public class TCPHome implements Home {
@Override @Override
public Home createHome(BridgeSettingsDescriptor bridgeSettings) { public Home createHome(BridgeSettingsDescriptor bridgeSettings) {
log.info("TCP Home created."); log.info("TCP Home created.");
theSockets = new HashMap<String, Socket>();
return this; return this;
} }
@@ -88,8 +102,15 @@ public class TCPHome implements Home {
@Override @Override
public void closeHome() { public void closeHome() {
Iterator<?> anIterator = theSockets.entrySet().iterator();
while(anIterator.hasNext()) {
Socket aSocket = (Socket) anIterator.next();
try {
aSocket.close();
} catch (IOException e) {
// noop // noop
}
}
} }
} }