tested moziot and working

This commit is contained in:
BWS Systems
2019-06-03 16:06:03 -05:00
parent f266945b7e
commit 3e76e6298a
12 changed files with 2783 additions and 2460 deletions

View File

@@ -1431,7 +1431,7 @@ public class HueMulator {
anHSL.setSat(sat);
else
anHSL.setSat(state.getSat());
log.info("hue/sat request - " + anHSL);
log.debug("hue/sat request - " + anHSL);
colorData = new ColorData(ColorData.ColorMode.HS, anHSL);
} else if (hueInc != null || satInc != null) {
anHSL = new HueSatBri();

View File

@@ -5,8 +5,6 @@ import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import javax.net.ssl.SSLContext;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
@@ -154,7 +152,7 @@ public class HTTPHandler {
} catch (ClientProtocolException e) {
log.warn("Client Protocol Exception received, retyring....");
} catch (IOException e) {
log.warn("Error calling out to HA gateway: IOException in log: " + e.getMessage());
log.warn("Error calling out to HA gateway: IOException in log: " + e.getMessage(), e);
retryCount = 2;
}

View File

@@ -62,9 +62,9 @@ public final class HttpClientPool {
// Just one of me so constructor will be called once.
SSLClient;
// The thread-safe client.
private final CloseableHttpClient threadSafeClient;
private CloseableHttpClient threadSafeClient;
// The pool monitor.
private final IdleConnectionMonitorThread monitor;
private IdleConnectionMonitorThread monitor = null;
private TrustStrategy acceptingTrustStrategy = null;
private SSLContext sslContext = null;
private SSLConnectionSocketFactory sslsf = null;
@@ -73,27 +73,33 @@ public final class HttpClientPool {
// The constructor creates it - thus late
private SingletonSSL() {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
// Increase max total connection to 200
cm.setMaxTotal(200);
// Increase default max connection per route to 20
cm.setDefaultMaxPerRoute(20);
try {
acceptingTrustStrategy = (cert, authType) -> true;
hostnameVerifier = new NoopHostnameVerifier();
sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
HttpClientPool.log.info("Instantiated SSL components.");
final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", new PlainConnectionSocketFactory())
.register("https", sslsf)
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
// Increase max total connection to 200
cm.setMaxTotal(200);
// Increase default max connection per route to 20
cm.setDefaultMaxPerRoute(20);
// Build the client.
threadSafeClient = HttpClients.custom().setSSLSocketFactory(sslsf).setConnectionManager(cm).build();
// Start up an eviction thread.
monitor = new IdleConnectionMonitorThread(cm);
// Don't stop quitting.
monitor.setDaemon(true);
monitor.start();
} catch (Exception e) {
HttpClientPool.log.warn("SingletonSSL failed on SSL init");
threadSafeClient = null;
}
// Build the client.
threadSafeClient = HttpClients.custom().setConnectionManager(cm).setSSLSocketFactory(sslsf)
.setSSLHostnameVerifier(hostnameVerifier).build();
// Start up an eviction thread.
monitor = new IdleConnectionMonitorThread(cm);
// Don't stop quitting.
monitor.setDaemon(true);
monitor.start();
}
public CloseableHttpClient get() {

View File

@@ -1,18 +1,25 @@
package com.bwssystems.HABridge.plugins.moziot;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class MozIotCommand {
@SerializedName("url")
@Expose
private String url;
private String command;
@SerializedName("command")
@Expose
private MozIotCommandDetail command;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getCommand() {
public MozIotCommandDetail getCommand() {
return command;
}
public void setCommand(String command) {
public void setCommand(MozIotCommandDetail command) {
this.command = command;
}

View File

@@ -0,0 +1,54 @@
package com.bwssystems.HABridge.plugins.moziot;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class MozIotCommandDetail {
@SerializedName("on")
@Expose
private boolean on;
@SerializedName("level")
@Expose
private String level;
@SerializedName("color")
@Expose
private String color;
public boolean isOn() {
return on;
}
public void setOn(boolean on) {
this.on = on;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getBody() {
String theBody = "";
if(level != null && level != "") {
theBody = "{\"level\":" + level + "}";
}
else if(color != null && color != "") {
theBody = "{\"color\":\"" + color + "\"}";
} else {
theBody = "{\"on\":" + on + "}";
}
return theBody;
}
}

View File

@@ -0,0 +1,29 @@
package com.bwssystems.HABridge.plugins.moziot;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class MozIotDevice {
@SerializedName("gatewayName")
@Expose
private String gatewayName;
@SerializedName("deviceDetail")
@Expose
private MozillaThing deviceDetail;
public String getGatewayName() {
return gatewayName;
}
public void setGatewayName(String gatewayName) {
this.gatewayName = gatewayName;
}
public MozillaThing getDeviceDetail() {
return deviceDetail;
}
public void setDeviceDetail(MozillaThing deviceDetail) {
this.deviceDetail = deviceDetail;
}
}

View File

@@ -26,13 +26,13 @@ import com.bwssystems.HABridge.plugins.http.HTTPHandler;
import com.bwssystems.HABridge.plugins.http.HTTPHome;
import com.google.gson.Gson;
public class MozIotHome implements Home {
private static final Logger log = LoggerFactory.getLogger(MozIotHome.class);
public class MozIotHome implements Home {
private static final Logger log = LoggerFactory.getLogger(MozIotHome.class);
private Map<String, MozIotInstance> moziotMap;
private Boolean validMoziot;
private HTTPHandler httpClient;
private HTTPHandler httpClient;
private boolean closed;
public MozIotHome(BridgeSettings bridgeSettings) {
super();
closed = true;
@@ -47,71 +47,68 @@ public class MozIotHome implements Home {
String theUrl = anItem.getItem().getAsString();
String responseString = null;
if(theUrl != null && !theUrl.isEmpty()) {
if (theUrl != null && !theUrl.isEmpty()) {
String anUrl = BrightnessDecode.calculateReplaceIntensityValue(theUrl, intensity, targetBri, targetBriInc,
false);
if (colorData != null) {
anUrl = ColorDecode.replaceColorData(anUrl, colorData,
BrightnessDecode.calculateIntensity(intensity, targetBri, targetBriInc), true);
}
anUrl = DeviceDataDecode.replaceDeviceData(anUrl, device);
anUrl = TimeDecode.replaceTimeValue(anUrl);
anUrl = BrightnessDecode.calculateReplaceIntensityValue(anUrl, intensity, targetBri, targetBriInc, false);
if (colorData != null) {
anUrl = ColorDecode.replaceColorData(anUrl, colorData,
BrightnessDecode.calculateIntensity(intensity, targetBri, targetBriInc), false);
}
anUrl = DeviceDataDecode.replaceDeviceData(anUrl, device);
anUrl = TimeDecode.replaceTimeValue(anUrl);
MozIotCommand theCommand = null;
try {
theUrl = theUrl.replaceAll("^\"|\"$", "");
theCommand = new Gson().fromJson(theUrl, MozIotCommand.class);
} catch(Exception e) {
log.warn("Cannot parse command to Mozilla IOT <<<" + theUrl + ">>>", e);
theCommand = new Gson().fromJson(anUrl, MozIotCommand.class);
} catch (Exception e) {
log.warn("Cannot parse command to Mozilla IOT <<<" + theUrl + ">>>", e);
responseString = new Gson().toJson(HueErrorResponse.createResponse("6", "/lights/" + lightId,
"Error on calling url to change device state", "/lights/"
+ lightId + "/state", null, null).getTheErrors(), HueError[].class);
"Error on calling url to change device state", "/lights/" + lightId + "/state", null, null)
.getTheErrors(), HueError[].class);
return responseString;
}
String intermediate = theCommand.getUrl().substring(theCommand.getUrl().indexOf("://") + 3);
String hostPortion = intermediate.substring(0, intermediate.indexOf('/'));
String theUrlBody = intermediate.substring(intermediate.indexOf('/') + 1);
String hostAddr = null;
if (hostPortion.contains(":")) {
hostAddr = hostPortion.substring(0, intermediate.indexOf(':'));
} else
hostAddr = hostPortion;
MozIotInstance theHandler = findHandlerByAddress(hostAddr);
if(theHandler != null) {
String anUrl = BrightnessDecode.calculateReplaceIntensityValue(theUrlBody,
intensity, targetBri, targetBriInc, false);
if (colorData != null) {
anUrl = ColorDecode.replaceColorData(anUrl, colorData, BrightnessDecode.calculateIntensity(intensity, targetBri, targetBriInc), false);
}
anUrl = DeviceDataDecode.replaceDeviceData(anUrl, device);
anUrl = TimeDecode.replaceTimeValue(anUrl);
String aCommand = null;
if(theCommand.getCommand() != null && !theCommand.getCommand().isEmpty()) {
aCommand = BrightnessDecode.calculateReplaceIntensityValue(theCommand.getCommand(),
intensity, targetBri, targetBriInc, false);
if (colorData != null) {
aCommand = ColorDecode.replaceColorData(aCommand, colorData, BrightnessDecode.calculateIntensity(intensity, targetBri, targetBriInc), false);
}
aCommand = DeviceDataDecode.replaceDeviceData(aCommand, device);
aCommand = TimeDecode.replaceTimeValue(aCommand);
}
try {
boolean success = theHandler.callCommand(anUrl, aCommand, httpClient);
if(!success) {
log.warn("Comand had error to Mozilla IOT");
String intermediate = theCommand.getUrl().substring(theCommand.getUrl().indexOf("/things/") + 8);
String devicePortion = intermediate.substring(0, intermediate.indexOf('/'));
String theUrlCommand = intermediate.substring(intermediate.indexOf('/') + 1);
MozIotInstance theHandler = moziotMap.get(device.getTargetDevice());
if (theHandler != null) {
try {
boolean success = theHandler.callCommand(devicePortion, theUrlCommand, theCommand.getCommand(), httpClient);
if (!success) {
log.warn("Comand had error to Mozilla IOT");
responseString = new Gson().toJson(HueErrorResponse.createResponse("6", "/lights/" + lightId,
"Error on calling url to change device state", "/lights/"
+ lightId + "state", null, null).getTheErrors(), HueError[].class);
}
} catch (Exception e) {
log.warn("Cannot send comand to Mozilla IOT", e);
"Error on calling url to change device state", "/lights/" + lightId + "/state", null,
null).getTheErrors(), HueError[].class);
}
} catch (Exception e) {
log.warn("Cannot send comand to Mozilla IOT", e);
responseString = new Gson().toJson(HueErrorResponse.createResponse("6", "/lights/" + lightId,
"Error on calling url to change device state", "/lights/"
+ lightId + "state", null, null).getTheErrors(), HueError[].class);
}
"Error on calling url to change device state", "/lights/" + lightId + "/state", null, null)
.getTheErrors(), HueError[].class);
}
} else {
log.warn("Mozilla IOT Call could not complete, no address found: " + theUrl);
responseString = new Gson().toJson(HueErrorResponse.createResponse("6", "/lights/" + lightId,
"Error on calling url to change device state", "/lights/"
+ lightId + "state", null, null).getTheErrors(), HueError[].class);
"Error on calling url to change device state", "/lights/" + lightId + "/state", null, null)
.getTheErrors(), HueError[].class);
}
} else {
log.warn("Mozilla IOT Call to be presented as http(s)://<ip_address>(:<port>)/payload, format of request unknown: " + theUrl);
log.warn(
"Mozilla IOT Call to be presented as http(s)://<ip_address>(:<port>)/payload, format of request unknown: "
+ theUrl);
responseString = new Gson().toJson(HueErrorResponse.createResponse("6", "/lights/" + lightId,
"Error on calling url to change device state", "/lights/"
+ lightId + "state", null, null).getTheErrors(), HueError[].class);
"Error on calling url to change device state", "/lights/" + lightId + "/state", null, null)
.getTheErrors(), HueError[].class);
}
return responseString;
}
@@ -119,16 +116,16 @@ public class MozIotHome implements Home {
@Override
public Object getItems(String type) {
if(!validMoziot)
if (!validMoziot)
return null;
log.debug("consolidating devices for Mozilla IOT");
List<MozillaThing> theResponse = null;
Iterator<String> keys = moziotMap.keySet().iterator();
List<MozillaThing> deviceList = new ArrayList<MozillaThing>();
while(keys.hasNext()) {
List<MozIotDevice> deviceList = new ArrayList<MozIotDevice>();
while (keys.hasNext()) {
String key = keys.next();
theResponse = moziotMap.get(key).getDevices(httpClient);
if(theResponse != null)
if (theResponse != null)
addMozIotDevices(deviceList, theResponse, key);
else {
log.warn("Cannot get devices for Mozilla IOT with name: " + key + ", skipping this Mozilla IOT.");
@@ -137,11 +134,15 @@ public class MozIotHome implements Home {
}
return deviceList;
}
private Boolean addMozIotDevices(List<MozillaThing> theDeviceList, List<MozillaThing> theSourceList, String theKey) {
Iterator<MozillaThing> devices = theSourceList.iterator();
while(devices.hasNext()) {
MozillaThing theDevice = devices.next();
private Boolean addMozIotDevices(List<MozIotDevice> theDeviceList, List<MozillaThing> theSourceList,
String theKey) {
Iterator<MozillaThing> things = theSourceList.iterator();
while (things.hasNext()) {
MozillaThing theThing = things.next();
MozIotDevice theDevice = new MozIotDevice();
theDevice.setDeviceDetail(theThing);
theDevice.setGatewayName(theKey);
theDeviceList.add(theDevice);
}
return true;
@@ -152,57 +153,42 @@ public class MozIotHome implements Home {
moziotMap = null;
validMoziot = bridgeSettings.getBridgeSettingsDescriptor().isValidMozIot();
log.info("Mozilla IOT Home created." + (validMoziot ? "" : " No Mozilla IOTs configured."));
if(validMoziot) {
moziotMap = new HashMap<String,MozIotInstance>();
httpClient = HTTPHome.getHandler();
Iterator<NamedIP> theList = bridgeSettings.getBridgeSettingsDescriptor().getMoziotaddress().getDevices().iterator();
while(theList.hasNext() && validMoziot) {
if (validMoziot) {
moziotMap = new HashMap<String, MozIotInstance>();
httpClient = HTTPHome.getHandler();
Iterator<NamedIP> theList = bridgeSettings.getBridgeSettingsDescriptor().getMoziotaddress().getDevices()
.iterator();
while (theList.hasNext() && validMoziot) {
NamedIP aMoziot = theList.next();
try {
moziotMap.put(aMoziot.getName(), new MozIotInstance(aMoziot, httpClient));
try {
moziotMap.put(aMoziot.getName(), new MozIotInstance(aMoziot, httpClient));
} catch (Exception e) {
log.error("Cannot get Mozilla IOT (" + aMoziot.getName() + ") setup, Exiting with message: " + e.getMessage(), e);
validMoziot = false;
log.error("Cannot get Mozilla IOT (" + aMoziot.getName() + ") setup, Exiting with message: "
+ e.getMessage(), e);
validMoziot = false;
}
}
}
return this;
}
private MozIotInstance findHandlerByAddress(String hostAddress) {
MozIotInstance aHandler = null;
boolean found = false;
Iterator<String> keys = moziotMap.keySet().iterator();
while(keys.hasNext()) {
String key = keys.next();
aHandler = moziotMap.get(key);
if(aHandler != null && aHandler.getMozIotIP().getIp().equals(hostAddress)) {
found = true;
break;
}
}
if(!found)
aHandler = null;
return aHandler;
return this;
}
@Override
public void closeHome() {
log.debug("Closing Home.");
if(!closed && validMoziot) {
if (!closed && validMoziot) {
log.debug("Home is already closed....");
return;
}
if(httpClient != null)
if (httpClient != null)
httpClient.closeHandler();
moziotMap = null;
closed = true;
closed = true;
}
@Override
public void refresh() {
// noop
// noop
}
}

View File

@@ -26,8 +26,8 @@ public class MozIotInstance {
gatewayLogin(httpClient);
}
public Boolean callCommand(String aCommand, String commandData, HTTPHandler httpClient) {
log.debug("calling Mozilla IOT: " + mozIotIP.getIp() + ":" + mozIotIP.getPort() + aCommand);
public Boolean callCommand(String deviceId, String aCommand, MozIotCommandDetail commandData, HTTPHandler httpClient) {
log.debug("calling Mozilla IOT: {}:{}{}{}", mozIotIP.getIp(), mozIotIP.getPort(), aCommand, commandData.getBody());
String aUrl = null;
if (mozIotIP.getSecure() != null && mozIotIP.getSecure())
@@ -36,9 +36,9 @@ public class MozIotInstance {
aUrl = "http://";
headers = getAuthHeader();
aUrl = aUrl + mozIotIP.getIp() + ":" + mozIotIP.getPort() + "/" + aCommand;
String theData = httpClient.doHttpRequest(aUrl, HttpPut.METHOD_NAME, "application/json", commandData, headers);
log.debug("call Command return is: <" + theData + ">");
aUrl = aUrl + mozIotIP.getIp() + ":" + mozIotIP.getPort() + "/things/" + deviceId + "/" + aCommand;
String theData = httpClient.doHttpRequest(aUrl, HttpPut.METHOD_NAME, "application/json", commandData.getBody(), headers);
log.debug("call Command return is: <<<{}>>>", theData);
if (theData.contains("error") || theData.contains("ERROR") || theData.contains("Error"))
return false;
return true;
@@ -70,7 +70,7 @@ public class MozIotInstance {
}
}
} catch (Exception e) {
log.warn("Cannot get an devices for Mozilla IOT " + mozIotIP.getName() + " Gson Parse Error.");
log.warn("Cannot get an devices for Mozilla IOT {} Gson Parse Error.", mozIotIP.getName());
}
}
return deviceList;
@@ -78,11 +78,17 @@ public class MozIotInstance {
private NameValue[] getAuthHeader() {
if (headers == null) {
headers = new NameValue[1];
headers = new NameValue[3];
headers[0] = new NameValue();
headers[0].setName("Authorization");
headers[0].setValue("Bearer " + moziotToken.getJwt());
}
headers[1] = new NameValue();
headers[1].setName("Content-Type");
headers[1].setValue("application/json");
headers[2] = new NameValue();
headers[2].setName("Accept");
headers[2].setValue("application/json");
}
return headers;
}
@@ -102,20 +108,20 @@ public class MozIotInstance {
headers[1].setName("Accept");
headers[1].setValue("application/json");
aUrl = aUrl + mozIotIP.getIp() + ":" + mozIotIP.getPort() + "/login";
log.info("gateway login URL: " + aUrl);
log.debug("gateway login URL: {}", aUrl);
String commandData = "{\"email\": \"" + mozIotIP.getUsername() + "\", \"password\":\"" + mozIotIP.getPassword()
+ "\"}";
log.info("The login body: " + commandData);
log.debug("The login body: {}", commandData);
String theData = httpClient.doHttpRequest(aUrl, HttpPost.METHOD_NAME, "application/json", commandData, headers);
if (theData != null) {
log.info("GET Mozilla login - data: " + theData);
log.debug("GET Mozilla login - data: {}", theData);
try {
moziotToken = new Gson().fromJson(theData, JWT.class);
} catch (Exception e) {
log.warn("Cannot get login for Mozilla IOT " + mozIotIP.getName() + " Gson Parse Error.");
log.warn("Cannot get login for Mozilla IOT {} Gson Parse Error.", mozIotIP.getName());
}
} else {
log.warn("Could not login " + mozIotIP.getName() + " error: <<<" + theData + ">>>");
log.warn("Could not login {} error: <<<{}>>>", mozIotIP.getName(), theData);
}
headers = null;