Continue Refactoring

This commit is contained in:
Admin
2016-12-28 16:44:41 -06:00
parent b7d6d099a6
commit 66d7306cda
68 changed files with 526 additions and 414 deletions

View File

@@ -94,6 +94,11 @@ java -jar -Dserver.port=80 ha-bridge-W.X.Y.jar
```
Note: if using with a Google Home device, port 80 *must* be used.
### -Dserver.ip=`<ip address>`
The default ip address for the bridge to listen on is all interfaces (0.0.0.0). To override what the default or what is in the configuration file for this parameter, specify -Dserver.ip=`<ip address>` explicitly. This is especially helpful if you are running the ha-bridge for the first time and have another application on that utilizes the default interface. The command line example:
```
java -jar -Dserver.ip=192.168.1.1 ha-bridge-W.X.Y.jar
```
## HA Bridge Usage and Configuration
This section will cover the basics of configuration and where this configuration can be done. This requires that you have started your bridge process and then have pointed your
favorite web interface by going to the http://<my ip address>:<port> or http://localhost:<port> with port you have assigned. The default quick link is http://localhost for yoru reference.

View File

@@ -5,7 +5,7 @@
<groupId>com.bwssystems.HABridge</groupId>
<artifactId>ha-bridge</artifactId>
<version>3.5.1p</version>
<version>3.5.1q</version>
<packaging>jar</packaging>
<name>HA Bridge</name>

View File

@@ -18,8 +18,8 @@ import org.apache.http.conn.util.InetAddressUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bwssystems.util.BackupHandler;
import com.bwssystems.util.JsonTransformer;
import com.bwssystems.HABridge.util.BackupHandler;
import com.bwssystems.HABridge.util.JsonTransformer;
import com.google.gson.Gson;
public class BridgeSettings extends BackupHandler {

View File

@@ -21,7 +21,9 @@ public class DeviceMapTypes {
public final static String[] CMD_DEVICE = { "cmdDevice", "Execute Command/Script/Program", "command"};
public final static String[] HASS_DEVICE = { "hassDevice", "HomeAssistant Device", "hass"};
public final static String[] TCP_DEVICE = { "tcpDevice", "TCP Device", "none"};
public final static String[] TCP_DEVICE_COMPAT = { "TCP", "TCP Device", "none"};
public final static String[] UDP_DEVICE = { "udpDevice", "UDP Device", "none"};
public final static String[] UDP_DEVICE_COMPAT = { "UDP", "UDP Device", "none"};
public final static String[] HTTP_DEVICE = { "httpDevice", "HTTP Device", "none"};
public final static String[] DEFAULT_DEVICE = { "udpDevice", "Default Device", "none"};
@@ -34,13 +36,12 @@ public class DeviceMapTypes {
public DeviceMapTypes() {
super();
deviceMapTypes = new ArrayList<String[]>();
deviceMapTypes.add(CUSTOM_DEVICE);
deviceMapTypes.add(CMD_DEVICE);
deviceMapTypes.add(DEFAULT_DEVICE);
deviceMapTypes.add(EXEC_DEVICE);
deviceMapTypes.add(HAL_DEVICE);
deviceMapTypes.add(HAL_HOME);
deviceMapTypes.add(HAL_THERMO_SET);
deviceMapTypes.add(HAL_BUTTON);
deviceMapTypes.add(HASS_DEVICE);
deviceMapTypes.add(HTTP_DEVICE);
deviceMapTypes.add(HUE_DEVICE);
@@ -51,7 +52,6 @@ public class DeviceMapTypes {
deviceMapTypes.add(UDP_DEVICE);
deviceMapTypes.add(VERA_DEVICE);
deviceMapTypes.add(VERA_SCENE);
deviceMapTypes.add(HAL_BUTTON);
deviceMapTypes.add(HARMONY_ACTIVITY);
deviceMapTypes.add(HARMONY_BUTTON);
}

View File

@@ -9,7 +9,7 @@ import com.bwssystems.HABridge.devicemanagmeent.*;
import com.bwssystems.HABridge.hue.HueMulator;
import com.bwssystems.HABridge.upnp.UpnpListener;
import com.bwssystems.HABridge.upnp.UpnpSettingsResource;
import com.bwssystems.util.UDPDatagramSender;
import com.bwssystems.HABridge.util.UDPDatagramSender;
public class HABridge {

View File

@@ -4,18 +4,18 @@ import java.util.HashMap;
import java.util.Map;
import com.bwssystems.HABridge.devicemanagmeent.ResourceHandler;
import com.bwssystems.NestBridge.NestHome;
import com.bwssystems.exec.CommandHome;
import com.bwssystems.hal.HalHome;
import com.bwssystems.harmony.HarmonyHome;
import com.bwssystems.hass.HassHome;
import com.bwssystems.http.HTTPHome;
import com.bwssystems.hue.HueHome;
import com.bwssystems.mqtt.MQTTHome;
import com.bwssystems.tcp.TCPHome;
import com.bwssystems.udp.UDPHome;
import com.bwssystems.util.UDPDatagramSender;
import com.bwssystems.vera.VeraHome;
import com.bwssystems.HABridge.plugins.NestBridge.NestHome;
import com.bwssystems.HABridge.plugins.exec.CommandHome;
import com.bwssystems.HABridge.plugins.hal.HalHome;
import com.bwssystems.HABridge.plugins.harmony.HarmonyHome;
import com.bwssystems.HABridge.plugins.hass.HassHome;
import com.bwssystems.HABridge.plugins.http.HTTPHome;
import com.bwssystems.HABridge.plugins.hue.HueHome;
import com.bwssystems.HABridge.plugins.mqtt.MQTTHome;
import com.bwssystems.HABridge.plugins.tcp.TCPHome;
import com.bwssystems.HABridge.plugins.udp.UDPHome;
import com.bwssystems.HABridge.plugins.vera.VeraHome;
import com.bwssystems.HABridge.util.UDPDatagramSender;
public class HomeManager {
Map<String, Home> homeList;
@@ -33,6 +33,7 @@ public class HomeManager {
aHome = new HarmonyHome(bridgeSettings);
resourceList.put(DeviceMapTypes.HARMONY_ACTIVITY[DeviceMapTypes.resourceIndex], aHome);
homeList.put(DeviceMapTypes.HARMONY_ACTIVITY[DeviceMapTypes.typeIndex], aHome);
resourceList.put(DeviceMapTypes.HARMONY_BUTTON[DeviceMapTypes.resourceIndex], aHome);
homeList.put(DeviceMapTypes.HARMONY_BUTTON[DeviceMapTypes.typeIndex], aHome);
//setup the nest connection if available
aHome = new NestHome(bridgeSettings);
@@ -72,9 +73,11 @@ public class HomeManager {
//setup the tcp handler Home
aHome = new TCPHome(bridgeSettings);
homeList.put(DeviceMapTypes.TCP_DEVICE[DeviceMapTypes.typeIndex], aHome);
homeList.put(DeviceMapTypes.TCP_DEVICE_COMPAT[DeviceMapTypes.typeIndex], aHome);
//setup the udp handler Home
aHome = new UDPHome(bridgeSettings, aUdpDatagramSender);
homeList.put(DeviceMapTypes.UDP_DEVICE[DeviceMapTypes.typeIndex], aHome);
homeList.put(DeviceMapTypes.UDP_DEVICE_COMPAT[DeviceMapTypes.typeIndex], aHome);
aHome = new VeraHome(bridgeSettings);
resourceList.put(DeviceMapTypes.VERA_DEVICE[DeviceMapTypes.resourceIndex], aHome);

View File

@@ -18,11 +18,11 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bwssystems.HABridge.dao.BackupFilename;
import com.bwssystems.HABridge.util.JsonTransformer;
import com.bwssystems.HABridge.util.TextStringFormatter;
import com.bwssystems.logservices.LoggerInfo;
import com.bwssystems.logservices.LoggingForm;
import com.bwssystems.logservices.LoggingManager;
import com.bwssystems.util.TextStringFormatter;
import com.bwssystems.util.JsonTransformer;
import com.google.gson.Gson;
import ch.qos.logback.classic.LoggerContext;

View File

@@ -19,8 +19,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bwssystems.HABridge.dao.DeviceDescriptor;
import com.bwssystems.util.BackupHandler;
import com.bwssystems.util.JsonTransformer;
import com.bwssystems.HABridge.util.BackupHandler;
import com.bwssystems.HABridge.util.JsonTransformer;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

View File

@@ -22,7 +22,7 @@ import com.bwssystems.HABridge.dao.BackupFilename;
import com.bwssystems.HABridge.dao.DeviceDescriptor;
import com.bwssystems.HABridge.dao.DeviceRepository;
import com.bwssystems.HABridge.dao.ErrorMessage;
import com.bwssystems.util.JsonTransformer;
import com.bwssystems.HABridge.util.JsonTransformer;
import com.google.gson.Gson;
/**

View File

@@ -15,11 +15,9 @@ import com.bwssystems.HABridge.api.hue.HuePublicConfig;
import com.bwssystems.HABridge.api.hue.StateChangeBody;
import com.bwssystems.HABridge.api.hue.WhitelistEntry;
import com.bwssystems.HABridge.dao.*;
import com.bwssystems.http.HTTPHandler;
import com.bwssystems.hue.HueDeviceIdentifier;
import com.bwssystems.hue.HueHome;
import com.bwssystems.hue.HueUtil;
import com.bwssystems.util.JsonTransformer;
import com.bwssystems.HABridge.plugins.hue.HueDeviceIdentifier;
import com.bwssystems.HABridge.plugins.hue.HueHome;
import com.bwssystems.HABridge.util.JsonTransformer;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
@@ -29,7 +27,6 @@ import static spark.Spark.post;
import static spark.Spark.put;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -55,7 +52,6 @@ public class HueMulator {
private HueHome myHueHome;
private BridgeSettingsDescriptor bridgeSettings;
private Gson aGsonHandler;
private HTTPHandler anHttpHandler;
public HueMulator(BridgeSettingsDescriptor theBridgeSettings, DeviceRepository aDeviceRepository, HomeManager aHomeManager) {
repository = aDeviceRepository;
@@ -63,7 +59,6 @@ public class HueMulator {
homeManager= aHomeManager;
myHueHome = (HueHome) homeManager.findHome(DeviceMapTypes.HUE_DEVICE[DeviceMapTypes.typeIndex]);
aGsonHandler = new GsonBuilder().create();
anHttpHandler = new HTTPHandler();
}
// This function sets up the sparkjava rest calls for the hue api
@@ -131,7 +126,7 @@ public class HueMulator {
response.header("Access-Control-Allow-Origin", request.headers("Origin"));
response.type("application/json");
response.status(HttpStatus.SC_OK);
return lightsListHandler("lights", request.params(":userid"), request.ip());
return lightsListHandler(request.params(":userid"), request.ip());
} , new JsonTransformer());
// http://ip_address:port/api/{userId}/lights/ returns json objects of
@@ -140,7 +135,7 @@ public class HueMulator {
response.header("Access-Control-Allow-Origin", request.headers("Origin"));
response.type("application/json");
response.status(HttpStatus.SC_OK);
return lightsListHandler("lights", request.params(":userid"), request.ip());
return lightsListHandler(request.params(":userid"), request.ip());
} , new JsonTransformer());
// http://ip_address:port/api CORS request
@@ -493,8 +488,7 @@ public class HueMulator {
theErrors = validateWhitelistUser(userId, false);
if (theErrors == null) {
if (groupId.equalsIgnoreCase("0")) {
GroupResponse theResponse = GroupResponse
.createGroupResponse(repository.findAll());
GroupResponse theResponse = GroupResponse.createGroupResponse(repository.findAll());
return theResponse;
}
theErrors = HueErrorResponse.createResponse("3", userId + "/groups/" + groupId, "Object not found", null, null, null).getTheErrors();
@@ -503,7 +497,7 @@ public class HueMulator {
return theErrors;
}
private Object lightsListHandler(String type, String userId, String requestIp) {
private Object lightsListHandler(String userId, String requestIp) {
HueError[] theErrors = null;
Map<String, DeviceResponse> deviceResponseMap = null;
if (bridgeSettings.isTraceupnp())
@@ -512,33 +506,12 @@ public class HueMulator {
theErrors = validateWhitelistUser(userId, false);
if (theErrors == null) {
List<DeviceDescriptor> deviceList = repository.findAll();
deviceResponseMap = new HashMap<>();
deviceResponseMap = new HashMap<String, DeviceResponse>();
for (DeviceDescriptor device : deviceList) {
DeviceResponse deviceResponse = null;
String responseString;
if ((device.getMapType() != null && device.getMapType().equalsIgnoreCase("hueDevice"))) {
if ((device.getMapType() != null && device.getMapType().equalsIgnoreCase(DeviceMapTypes.HUE_DEVICE[DeviceMapTypes.typeIndex]))) {
HueDeviceIdentifier deviceId = aGsonHandler.fromJson(device.getOnUrl(), HueDeviceIdentifier.class);
theErrors = validateHueUser(userId, deviceId.getIpAddress(), device.getName());
if (theErrors == null) {
// make call
responseString = anHttpHandler.doHttpRequest(
"http://" + deviceId.getIpAddress() + "/api/" + myHueHome.getTheHUERegisteredUser()
+ "/lights/" + deviceId.getDeviceId(),
HttpGet.METHOD_NAME, device.getContentType(), null, null);
if (responseString == null) {
log.warn("Error on calling hue device to get state: " + device.getName());
deviceResponse = DeviceResponse.createResponse(device);
} else if (responseString.contains("[{\"error\":") && responseString.contains("unauthorized user")) {
myHueHome.setTheHUERegisteredUser(null);
theErrors = validateHueUser(userId, deviceId.getIpAddress(), device.getName());
if (theErrors == null)
deviceResponse = DeviceResponse.createResponse(device);
} else {
deviceResponse = aGsonHandler.fromJson(responseString, DeviceResponse.class);
if (deviceResponse != null)
deviceResponse.setName(device.getName());
}
}
deviceResponse = myHueHome.getHueDeviceInfo(deviceId, device);
}
if (deviceResponse == null)
@@ -559,7 +532,7 @@ public class HueMulator {
String aDeviceType = null;
if (bridgeSettings.isTraceupnp())
log.info("Traceupnp: hue api/ user create requested: " + body + " from " + ipAddress);
log.info("Traceupnp: hue api user create requested: " + body + " from " + ipAddress);
log.debug("hue api user create requested: " + body + " from " + ipAddress);
if (body != null && !body.isEmpty()) {
@@ -576,7 +549,7 @@ public class HueMulator {
if (bridgeSettings.isTraceupnp())
log.info("Traceupnp: hue api user create requested for device type: " + aDeviceType + " and username: "
+ newUser + (followingSlash ? " /api/ called" : ""));
log.debug("hue api user create requested for device type: " + aDeviceType + " and username: " + newUser);
log.debug("hue api user create requested for device type: " + aDeviceType + " and username: " + newUser + (followingSlash ? " /api/ called" : ""));
return "[{\"success\":{\"username\":\"" + newUser + "\"}}]";
@@ -599,23 +572,24 @@ public class HueMulator {
return apiResponse.getConfig();
}
@SuppressWarnings("unchecked")
private Object getFullState(String userId, String ipAddress) {
log.debug("hue api full state requested: " + userId + " from " + ipAddress);
HueError[] theErrors = validateWhitelistUser(userId, false);
if (theErrors != null)
return theErrors;
List<DeviceDescriptor> descriptorList = repository.findAll();
HueApiResponse apiResponse = new HueApiResponse("Philips hue", bridgeSettings.getUpnpConfigAddress(),
bridgeSettings.getWhitelist(), bridgeSettings.getHubversion());
Map<String, DeviceResponse> deviceList = new HashMap<>();
if (descriptorList != null) {
descriptorList.forEach(descriptor -> {
DeviceResponse deviceResponse = DeviceResponse.createResponse(descriptor);
deviceList.put(descriptor.getId(), deviceResponse);
});
Object aReturn = this.lightsListHandler(userId, ipAddress);
Map<String, DeviceResponse> deviceList = new HashMap<String, DeviceResponse>();
if(aReturn.getClass() == deviceList.getClass()) {
deviceList = (Map<String, DeviceResponse>) aReturn;
apiResponse.setLights(deviceList);
}
else {
return aReturn;
}
return apiResponse;
}
@@ -634,39 +608,17 @@ public class HueMulator {
log.debug("found device named: " + device.getName());
}
DeviceResponse lightResponse = null;
String responseString;
if ((device.getMapType() != null && device.getMapType().equalsIgnoreCase("hueDevice"))) {
if ((device.getMapType() != null && device.getMapType().equalsIgnoreCase(DeviceMapTypes.HUE_DEVICE[DeviceMapTypes.typeIndex]))) {
HueDeviceIdentifier deviceId = aGsonHandler.fromJson(device.getOnUrl(), HueDeviceIdentifier.class);
theErrors = validateHueUser(userId, deviceId.getIpAddress(), device.getName());
if (theErrors == null) {
// make call
responseString = anHttpHandler.doHttpRequest("http://" + deviceId.getIpAddress() + "/api/"
+ myHueHome.getTheHUERegisteredUser() + "/lights/" + deviceId.getDeviceId(),
HttpGet.METHOD_NAME, device.getContentType(), null, null);
if (responseString == null) {
log.warn("Error on calling hue device to get state: " + device.getName());
lightResponse = DeviceResponse.createResponse(device);
} else if (responseString.contains("[{\"error\":") && responseString.contains("unauthorized user")) {
myHueHome.setTheHUERegisteredUser(null);
theErrors = validateHueUser(userId, deviceId.getIpAddress(), device.getName());
if (theErrors == null)
lightResponse = DeviceResponse.createResponse(device);
} else {
lightResponse = aGsonHandler.fromJson(responseString, DeviceResponse.class);
if (lightResponse == null)
lightResponse = DeviceResponse.createResponse(device);
}
}
lightResponse = myHueHome.getHueDeviceInfo(deviceId, device);
} else
lightResponse = DeviceResponse.createResponse(device);
if(theErrors != null)
return theErrors;
return lightResponse;
}
private String updateState(String userId, String lightId, String body,String ipAddress) {
private String updateState(String userId, String lightId, String body, String ipAddress) {
String responseString = null;
StateChangeBody theStateChanges = null;
DeviceState state = null;
@@ -679,9 +631,8 @@ public class HueMulator {
theStateChanges = aGsonHandler.fromJson(body, StateChangeBody.class);
if (theStateChanges == null) {
log.warn("Could not parse state change body. Light state not changed.");
responseString = "[{\"error\":{\"type\": 2, \"address\": \"/lights/" + lightId
+ "\",\"description\": \"Could not parse state change body.\"}}]";
return responseString;
return aGsonHandler.toJson(HueErrorResponse.createResponse("2", "/lights/" + lightId,
"Could not parse state change body.", null, null, null).getTheErrors(), HueError[].class);
}
if (body.contains("\"bri\"")) {
@@ -697,9 +648,8 @@ public class HueMulator {
if (device == null) {
log.warn("Could not find device: " + lightId + " for hue state change request: " + userId + " from "
+ ipAddress + " body: " + body);
responseString = "[{\"error\":{\"type\": 3, \"address\": \"/lights/" + lightId
+ "\",\"description\": \"Could not find device\", \"resource\": \"/lights/" + lightId + "\"}}]";
return responseString;
return aGsonHandler.toJson(HueErrorResponse.createResponse("3", "/lights/" + lightId,
"Could not find device.", "/lights/" + lightId, null, null).getTheErrors(), HueError[].class);
}
state = device.getDeviceState();
if (state == null)
@@ -723,32 +673,13 @@ public class HueMulator {
state.setBri(0);
}
}
responseString = this.formatSuccessHueResponse(theStateChanges, body, lightId,
device.getDeviceState());
responseString = this.formatSuccessHueResponse(theStateChanges, body, lightId, device.getDeviceState());
device.getDeviceState().setBri(BrightnessDecode.calculateIntensity(state, theStateChanges, stateHasBri, stateHasBriInc));
return responseString;
}
private HueError[] validateHueUser(String userId, String ipAddress, String aName) {
String hueUser;
HueErrorResponse theErrorResp = null;
if (myHueHome.getTheHUERegisteredUser() == null) {
hueUser = HueUtil.registerWithHue(anHttpHandler, ipAddress, aName,
myHueHome.getTheHUERegisteredUser());
if (hueUser == null) {
theErrorResp = HueErrorResponse.createResponse("901", "/api/" + userId, "Could not register proxy to other hue hub", null, null, null);
} else
myHueHome.setTheHUERegisteredUser(hueUser);
}
if(theErrorResp != null)
return theErrorResp.getTheErrors();
return null;
}
private String changeState(String userId, String lightId, String body, String ipAddress) {
String responseString = null;
String url = null;
@@ -768,9 +699,8 @@ public class HueMulator {
theStateChanges = aGsonHandler.fromJson(body, StateChangeBody.class);
if (theStateChanges == null) {
log.warn("Could not parse state change body. Light state not changed.");
responseString = "[{\"error\":{\"type\": 2, \"address\": \"/lights/" + lightId
+ "\",\"description\": \"Could not parse state change body.\"}}]";
return responseString;
return aGsonHandler.toJson(HueErrorResponse.createResponse("2", "/lights/" + lightId,
"Could not parse state change body.", null, null, null).getTheErrors(), HueError[].class);
}
if (body.contains("\"bri\"")) {
@@ -783,9 +713,8 @@ public class HueMulator {
if (device == null) {
log.warn("Could not find device: " + lightId + " for hue state change request: " + userId + " from "
+ ipAddress + " body: " + body);
responseString = "[{\"error\":{\"type\": 3, \"address\": \"/lights/" + lightId
+ "\",\"description\": \"Could not find device\", \"resource\": \"/lights/" + lightId + "\"}}]";
return responseString;
return aGsonHandler.toJson(HueErrorResponse.createResponse("3", "/lights/" + lightId,
"Could not find device.", "/lights/" + lightId, null, null).getTheErrors(), HueError[].class);
}
state = device.getDeviceState();
@@ -829,8 +758,15 @@ public class HueMulator {
if (!url.startsWith("[")) {
if (url.startsWith("{\"item"))
url = "[" + url + "]";
else
url = "[{\"item\":\"" + url + "\"}]";
else {
if(url.startsWith("{"))
url = "[{\"item\":" + url + "}]";
else
url = "[{\"item\":\"" + url + "\"}]";
}
} else {
if(!url.startsWith("[{\"item\""))
url = "[{\"item\":" + url + "}]";
}
CallItem[] callItems = null;
@@ -862,8 +798,8 @@ public class HueMulator {
} else {
log.warn("Could not find url: " + lightId + " for hue state change request: " + userId + " from "
+ ipAddress + " body: " + body);
responseString = "[{\"error\":{\"type\": 3, \"address\": \"/lights/" + lightId
+ "\",\"description\": \"Could not find url\", \"resource\": \"/lights/" + lightId + "\"}}]";
responseString = aGsonHandler.toJson(HueErrorResponse.createResponse("3", "/lights/" + lightId,
"Could not find url.", "/lights/" + lightId, null, null).getTheErrors(), HueError[].class);
}
if (responseString == null || !responseString.contains("[{\"error\":")) {

View File

@@ -1,4 +1,4 @@
package com.bwssystems.NestBridge;
package com.bwssystems.HABridge.plugins.NestBridge;
import java.util.ArrayList;
import java.util.ListIterator;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.NestBridge;
package com.bwssystems.HABridge.plugins.NestBridge;
public class NestInstruction {
private String name;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.NestBridge;
package com.bwssystems.HABridge.plugins.NestBridge;
import java.io.UnsupportedEncodingException;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.exec;
package com.bwssystems.HABridge.plugins.exec;
import java.io.IOException;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.hal;
package com.bwssystems.HABridge.plugins.hal;
import java.util.List;
import com.google.gson.annotations.SerializedName;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.hal;
package com.bwssystems.HABridge.plugins.hal;
import com.google.gson.annotations.SerializedName;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.hal;
package com.bwssystems.HABridge.plugins.hal;
public class HalDevice {
private String haldevicetype;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.hal;
package com.bwssystems.HABridge.plugins.hal;
import java.util.ArrayList;
import java.util.HashMap;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.hal;
package com.bwssystems.HABridge.plugins.hal;
import java.util.ArrayList;
import java.util.Iterator;
@@ -8,8 +8,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bwssystems.HABridge.NamedIP;
import com.bwssystems.http.HTTPHandler;
import com.bwssystems.util.TextStringFormatter;
import com.bwssystems.HABridge.plugins.http.HTTPHandler;
import com.bwssystems.HABridge.util.TextStringFormatter;
import com.google.gson.Gson;
public class HalInfo {

View File

@@ -1,4 +1,4 @@
package com.bwssystems.hal;
package com.bwssystems.HABridge.plugins.hal;
public class StatusDescription {
private String Status;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.harmony;
package com.bwssystems.HABridge.plugins.harmony;
public class ButtonPress {
private String device;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.harmony;
package com.bwssystems.HABridge.plugins.harmony;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.harmony;
package com.bwssystems.HABridge.plugins.harmony;
import java.io.UnsupportedEncodingException;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.harmony;
package com.bwssystems.HABridge.plugins.harmony;
import java.io.UnsupportedEncodingException;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.harmony;
package com.bwssystems.HABridge.plugins.harmony;
import java.util.List;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.harmony;
package com.bwssystems.HABridge.plugins.harmony;
import java.util.ArrayList;
import java.util.HashMap;
@@ -118,7 +118,7 @@ public class HarmonyHome implements Home {
public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int iterationCount,
DeviceState state, StateChangeBody theStateChanges, boolean stateHasBri, boolean stateHasBriInc, DeviceDescriptor device, String body) {
String responseString = null;
log.debug("executing HUE api request to change " + anItem.getType() + " to Harmony: " + device.getTargetDevice());
log.debug("executing HUE api request to change " + anItem.getType() + " to Harmony: " + device.getName());
if(!validHarmony) {
log.warn("Should not get here, no harmony configured");
responseString = "[{\"error\":{\"type\": 6, \"address\": \"/lights/" + lightId
@@ -128,7 +128,9 @@ public class HarmonyHome implements Home {
if(anItem.getType().trim().equalsIgnoreCase(DeviceMapTypes.HARMONY_ACTIVITY[DeviceMapTypes.typeIndex]))
{
RunActivity anActivity = aGsonHandler.fromJson(anItem.getItem().toString(), RunActivity.class);
HarmonyHandler myHarmony = getHarmonyHandler(device.getTargetDevice());
if(anActivity.getHub() == null || anActivity.getHub().isEmpty())
anActivity.setHub(device.getTargetDevice());
HarmonyHandler myHarmony = getHarmonyHandler(anActivity.getHub());
if (myHarmony == null) {
log.warn("Should not get here, no harmony hub available");
responseString = "[{\"error\":{\"type\": 6, \"address\": \"/lights/" + lightId
@@ -156,36 +158,34 @@ public class HarmonyHome implements Home {
url = "[" + url + "]";
}
ButtonPress[] deviceButtons = aGsonHandler.fromJson(url, ButtonPress[].class);
HarmonyHandler myHarmony = getHarmonyHandler(device.getTargetDevice());
if (myHarmony == null) {
log.warn("Should not get here, no harmony hub available");
responseString = "[{\"error\":{\"type\": 6, \"address\": \"/lights/" + lightId
+ "\",\"description\": \"Should not get here, no harmony hub available\", \"parameter\": \"/lights/"
+ lightId + "state\"}}]";
} else {
Integer theCount = 1;
for(int z = 0; z < deviceButtons.length; z++) {
if(deviceButtons[z].getCount() != null && deviceButtons[z].getCount() > 0)
theCount = deviceButtons[z].getCount();
else
theCount = aMultiUtil.getSetCount();
for(int y = 0; y < theCount; y++) {
if( y > 0 || z > 0) {
try {
Thread.sleep(aMultiUtil.getTheDelay());
} catch (InterruptedException e) {
// ignore
}
Integer theCount = 1;
for(int z = 0; z < deviceButtons.length; z++) {
if(deviceButtons[z].getCount() != null && deviceButtons[z].getCount() > 0)
theCount = deviceButtons[z].getCount();
else
theCount = aMultiUtil.getSetCount();
for(int y = 0; y < theCount; y++) {
if( y > 0 || z > 0) {
try {
Thread.sleep(aMultiUtil.getTheDelay());
} catch (InterruptedException e) {
// ignore
}
if (anItem.getDelay() != null && anItem.getDelay() > 0)
aMultiUtil.setTheDelay(anItem.getDelay());
else
aMultiUtil.setTheDelay(aMultiUtil.getDelayDefault());
log.debug("pressing button: " + deviceButtons[z].getDevice() + " - " + deviceButtons[z].getButton() + " - iteration: " + String.valueOf(z) + " - count: " + String.valueOf(y));
myHarmony.pressButton(deviceButtons[z]);
}
}
if (anItem.getDelay() != null && anItem.getDelay() > 0)
aMultiUtil.setTheDelay(anItem.getDelay());
else
aMultiUtil.setTheDelay(aMultiUtil.getDelayDefault());
log.debug("pressing button: " + deviceButtons[z].getDevice() + " - " + deviceButtons[z].getButton() + " - iteration: " + String.valueOf(z) + " - count: " + String.valueOf(y));
if(deviceButtons[z].getHub() == null || deviceButtons[z].getHub().isEmpty())
deviceButtons[z].setHub(device.getTargetDevice());
HarmonyHandler myHarmony = getHarmonyHandler(deviceButtons[z].getHub());
if (myHarmony == null)
log.warn("Button Press - Should not get here, no harmony hub available");
else
myHarmony.pressButton(deviceButtons[z]);
}
}
}
}
}
return responseString;
@@ -215,25 +215,44 @@ public class HarmonyHome implements Home {
Iterator<NamedIP> theList = bridgeSettings.getHarmonyAddress().getDevices().iterator();
while(theList.hasNext() && validHarmony) {
NamedIP aHub = theList.next();
try {
hubs.put(aHub.getName(), HarmonyServer.setup(bridgeSettings, isDevMode, aHub));
} catch (Exception e) {
log.error("Cannot get harmony client (" + aHub.getName() + ") setup, Exiting with message: " + e.getMessage(), e);
validHarmony = false;
boolean loopControl = true;
int retryCount = 0;
while(loopControl) {
try {
hubs.put(aHub.getName(), HarmonyServer.setup(bridgeSettings, isDevMode, aHub));
loopControl = false;
} catch (Exception e) {
if(retryCount > 3) {
log.error("Cannot get harmony client (" + aHub.getName() + ") setup, Exiting with message: " + e.getMessage(), e);
loopControl = false;
} else {
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
// ignore
}
}
retryCount++;
}
}
}
if(hubs.isEmpty())
validHarmony = false;
}
return this;
}
@Override
public Object getItems(String type) {
if(type.equalsIgnoreCase(DeviceMapTypes.HARMONY_ACTIVITY[DeviceMapTypes.resourceIndex]))
return getActivities();
if(type.equalsIgnoreCase(DeviceMapTypes.HARMONY_BUTTON[DeviceMapTypes.resourceIndex]))
return getDevices();
if(type.equalsIgnoreCase("current_activity"))
return getCurrentActivities();
if(validHarmony) {
if(type.equalsIgnoreCase(DeviceMapTypes.HARMONY_ACTIVITY[DeviceMapTypes.typeIndex]))
return getActivities();
if(type.equalsIgnoreCase(DeviceMapTypes.HARMONY_BUTTON[DeviceMapTypes.typeIndex]))
return getDevices();
if(type.equalsIgnoreCase("current_activity"))
return getCurrentActivities();
}
return null;
}
}

View File

@@ -1,4 +1,4 @@
package com.bwssystems.harmony;
package com.bwssystems.HABridge.plugins.harmony;
import static java.lang.String.format;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.harmony;
package com.bwssystems.HABridge.plugins.harmony;
public class RunActivity {
private String name;

View File

@@ -1,5 +1,5 @@
package com.bwssystems.hass;
package com.bwssystems.HABridge.plugins.hass;
import java.util.Map;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.hass;
package com.bwssystems.HABridge.plugins.hass;
import java.lang.reflect.Type;
import java.util.HashMap;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.hass;
package com.bwssystems.HABridge.plugins.hass;
public class HassCommand {
private String entityId;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.hass;
package com.bwssystems.HABridge.plugins.hass;
public class HassDevice {
private State deviceState;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.hass;
package com.bwssystems.HABridge.plugins.hass;
import java.util.ArrayList;
import java.util.HashMap;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.hass;
package com.bwssystems.HABridge.plugins.hass;
import java.util.ArrayList;
import java.util.Arrays;
@@ -11,7 +11,7 @@ import org.slf4j.LoggerFactory;
import com.bwssystems.HABridge.NamedIP;
import com.bwssystems.HABridge.api.NameValue;
import com.bwssystems.http.HTTPHandler;
import com.bwssystems.HABridge.plugins.http.HTTPHandler;
import com.google.gson.Gson;
public class HomeAssistant {

View File

@@ -1,5 +1,5 @@
package com.bwssystems.hass;
package com.bwssystems.HABridge.plugins.hass;
import java.util.Map;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.hass;
package com.bwssystems.HABridge.plugins.hass;
import java.lang.reflect.Type;
import java.util.HashMap;

View File

@@ -1,5 +1,5 @@
package com.bwssystems.hass;
package com.bwssystems.HABridge.plugins.hass;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.hass;
package com.bwssystems.HABridge.plugins.hass;
import java.util.Map;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.http;
package com.bwssystems.HABridge.plugins.http;
import java.io.IOException;
import java.net.URI;
@@ -56,7 +56,7 @@ public class HTTPHandler {
URI theURI = null;
ContentType parsedContentType = null;
StringEntity requestBody = null;
if (contentType != null && contentType.length() > 0) {
if (contentType != null && !contentType.trim().isEmpty()) {
parsedContentType = ContentType.parse(contentType);
if (body != null && body.length() > 0)
requestBody = new StringEntity(body, parsedContentType);
@@ -68,7 +68,7 @@ public class HTTPHandler {
return null;
}
try {
if (HttpGet.METHOD_NAME.equalsIgnoreCase(httpVerb) || httpVerb == null) {
if (httpVerb == null || httpVerb.trim().isEmpty() || HttpGet.METHOD_NAME.equalsIgnoreCase(httpVerb)) {
request = new HttpGet(theURI);
} else if (HttpPost.METHOD_NAME.equalsIgnoreCase(httpVerb)) {
HttpPost postRequest = new HttpPost(theURI);
@@ -81,6 +81,9 @@ public class HTTPHandler {
putRequest.setEntity(requestBody);
request = putRequest;
}
else
request = new HttpGet(theURI);
} catch (IllegalArgumentException e) {
log.warn("Error creating outbound http request: IllegalArgumentException in log", e);
return null;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.http;
package com.bwssystems.HABridge.plugins.http;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -8,6 +8,8 @@ import com.bwssystems.HABridge.Home;
import com.bwssystems.HABridge.api.CallItem;
import com.bwssystems.HABridge.api.NameValue;
import com.bwssystems.HABridge.api.hue.DeviceState;
import com.bwssystems.HABridge.api.hue.HueError;
import com.bwssystems.HABridge.api.hue.HueErrorResponse;
import com.bwssystems.HABridge.api.hue.StateChangeBody;
import com.bwssystems.HABridge.dao.DeviceDescriptor;
import com.bwssystems.HABridge.hue.BrightnessDecode;
@@ -27,6 +29,19 @@ public class HTTPHome implements Home {
public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int iterationCount,
DeviceState state, StateChangeBody theStateChanges, boolean stateHasBri, boolean stateHasBriInc, DeviceDescriptor device, String body) {
String responseString = null;
//Backwards Compatibility Items
if(anItem.getHttpVerb() == null || anItem.getHttpVerb().isEmpty())
{
if(device.getHttpVerb() != null && !device.getHttpVerb().isEmpty())
anItem.setHttpVerb(device.getHttpVerb());
}
if(anItem.getHttpHeaders() == null || anItem.getHttpHeaders().isEmpty()) {
if(device.getHeaders() != null && !device.getHeaders().isEmpty() )
anItem.setHttpHeaders(device.getHeaders());
}
log.debug("executing HUE api request to Http "
+ (anItem.getHttpVerb() == null ? "GET" : anItem.getHttpVerb()) + ": "
+ anItem.getItem().getAsString());
@@ -53,9 +68,9 @@ public class HTTPHome implements Home {
if (anHttpHandler.doHttpRequest(anUrl, anItem.getHttpVerb(), anItem.getContentType(), aBody,
new Gson().fromJson(anItem.getHttpHeaders(), NameValue[].class)) == null) {
log.warn("Error on calling url to change device state: " + anUrl);
responseString = "[{\"error\":{\"type\": 6, \"address\": \"/lights/" + lightId
+ "\",\"description\": \"Error on calling url to change device state\", \"parameter\": \"/lights/"
+ lightId + "state\"}}]";
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);
x = aMultiUtil.getSetCount();
}
}

View File

@@ -1,4 +1,4 @@
package com.bwssystems.hue;
package com.bwssystems.HABridge.plugins.hue;
import com.bwssystems.HABridge.api.hue.DeviceResponse;

View File

@@ -1,8 +1,15 @@
package com.bwssystems.hue;
package com.bwssystems.HABridge.plugins.hue;
public class HueDeviceIdentifier {
private String hueName;
private String ipAddress;
private String deviceId;
public String getHueName() {
return hueName;
}
public void setHueName(String hueName) {
this.hueName = hueName;
}
public String getIpAddress() {
return ipAddress;
}

View File

@@ -1,11 +1,10 @@
package com.bwssystems.hue;
package com.bwssystems.HABridge.plugins.hue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.http.client.methods.HttpPut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -19,17 +18,14 @@ import com.bwssystems.HABridge.api.hue.HueApiResponse;
import com.bwssystems.HABridge.api.hue.StateChangeBody;
import com.bwssystems.HABridge.dao.DeviceDescriptor;
import com.bwssystems.HABridge.hue.MultiCommandUtil;
import com.bwssystems.http.HTTPHandler;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class HueHome implements Home {
private static final Logger log = LoggerFactory.getLogger(HueHome.class);
private Map<String, HueInfo> hues;
private String theHUERegisteredUser;
private Boolean validHue;
private Gson aGsonHandler;
private HTTPHandler anHttpHandler;
public HueHome(BridgeSettingsDescriptor bridgeSettings) {
super();
@@ -69,28 +65,22 @@ public class HueHome implements Home {
return deviceList;
}
public String getTheHUERegisteredUser() {
return theHUERegisteredUser;
public DeviceResponse getHueDeviceInfo(HueDeviceIdentifier deviceId, DeviceDescriptor device) {
DeviceResponse deviceResponse = null;
HueInfo aHueInfo = hues.get(device.getTargetDevice());
deviceResponse = aHueInfo.getHueDeviceInfo(deviceId.getDeviceId(), device);
return deviceResponse;
}
public void setTheHUERegisteredUser(String theHUERegisteredUser) {
this.theHUERegisteredUser = theHUERegisteredUser;
}
@Override
public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int iterationCount,
DeviceState state, StateChangeBody theStateChanges, boolean stateHasBri, boolean stateHasBriInc, DeviceDescriptor device, String body) {
String responseString = null;
String hueUser;
HueDeviceIdentifier deviceId = aGsonHandler.fromJson(anItem.getItem(), HueDeviceIdentifier.class);
if (getTheHUERegisteredUser() == null) {
hueUser = HueUtil.registerWithHue(anHttpHandler, deviceId.getIpAddress(), device.getName(),
getTheHUERegisteredUser());
if (hueUser == null) {
return responseString;
}
setTheHUERegisteredUser(hueUser);
}
if(deviceId.getHueName() == null || deviceId.getHueName().isEmpty())
deviceId.setHueName(device.getTargetDevice());
HueInfo theHue = hues.get(deviceId.getHueName());
// make call
for (int x = 0; x < aMultiUtil.getSetCount(); x++) {
@@ -105,31 +95,11 @@ public class HueHome implements Home {
aMultiUtil.setTheDelay(anItem.getDelay());
else
aMultiUtil.setTheDelay(aMultiUtil.getDelayDefault());
responseString = anHttpHandler.doHttpRequest(
"http://" + deviceId.getIpAddress() + "/api/" + getTheHUERegisteredUser()
+ "/lights/" + deviceId.getDeviceId() + "/state",
HttpPut.METHOD_NAME, "application/json", body, null);
responseString = theHue.changeState(deviceId, lightId, body);
if (responseString.contains("[{\"error\":"))
x = aMultiUtil.getSetCount();
}
if (responseString == null) {
log.warn("Error on calling Hue passthru to change device state: " + device.getName());
responseString = "[{\"error\":{\"type\": 6, \"address\": \"/lights/" + lightId
+ "\",\"description\": \"Error on calling HUE to change device state\", \"parameter\": \"/lights/"
+ lightId + "state\"}}]";
} else if (responseString.contains("[{\"error\":")) {
if(responseString.contains("unauthorized user")) {
setTheHUERegisteredUser(null);
hueUser = HueUtil.registerWithHue(anHttpHandler, deviceId.getIpAddress(), device.getName(),
getTheHUERegisteredUser());
if (hueUser == null) {
return responseString;
}
setTheHUERegisteredUser(hueUser);
}
else
log.warn("Error occurred when calling Hue Passthru: " + responseString);
}
return responseString;
}
@@ -143,19 +113,19 @@ public class HueHome implements Home {
Iterator<NamedIP> theList = bridgeSettings.getHueaddress().getDevices().iterator();
while(theList.hasNext()) {
NamedIP aHue = theList.next();
hues.put(aHue.getName(), new HueInfo(aHue, this));
hues.put(aHue.getName(), new HueInfo(aHue));
}
theHUERegisteredUser = null;
aGsonHandler =
new GsonBuilder()
// .registerTypeAdapter(CallItem.class, new CallItemDeserializer())
.create();
aGsonHandler = new GsonBuilder().create();
}
return this;
}
@Override
public void closeHome() {
anHttpHandler.closeHandler();
Iterator<String> keys = hues.keySet().iterator();
while(keys.hasNext()) {
String key = keys.next();
hues.get(key).closeHue();;
}
}
}

View File

@@ -0,0 +1,198 @@
package com.bwssystems.HABridge.plugins.hue;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bwssystems.HABridge.NamedIP;
import com.bwssystems.HABridge.api.SuccessUserResponse;
import com.bwssystems.HABridge.api.UserCreateRequest;
import com.bwssystems.HABridge.api.hue.DeviceResponse;
import com.bwssystems.HABridge.api.hue.HueApiResponse;
import com.bwssystems.HABridge.dao.DeviceDescriptor;
import com.bwssystems.HABridge.plugins.http.HTTPHandler;
import com.google.gson.Gson;
public class HueInfo {
private static final Logger log = LoggerFactory.getLogger(HueInfo.class);
private HTTPHandler httpClient;
private NamedIP hueAddress;
private String theUser;
public static final String HUE_REQUEST = "/api";
public HueInfo(NamedIP addressName) {
super();
httpClient = new HTTPHandler();
hueAddress = addressName;
theUser = null;
}
public HueApiResponse getHueApiResponse() {
HueApiResponse theHueApiResponse = null;
if(theUser == null) {
registerWithHue();
if(theUser == null) {
log.warn("Could not register with hue: " + hueAddress.getName());
}
}
String theUrl = "http://" + hueAddress.getIp() + HUE_REQUEST + "/" + theUser;
String theData;
boolean loopControl = true;
int retryCount = 0;
while(loopControl) {
if(retryCount > 3) {
log.warn("Max Retry reached to get Hue data from " + hueAddress.getName());
loopControl = false;
break;
} else if (retryCount > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// ignore
}
}
theUrl = "http://" + hueAddress.getIp() + HueUtil.HUE_REQUEST + "/" + theUser;
theData = httpClient.doHttpRequest(theUrl, null, null, null, null);
if(theData != null) {
log.debug("GET HueApiResponse - data: " + theData);
if(theData.contains("[{\"error\":")) {
if(theData.contains("unauthorized user")) {
theUser = registerWithHue();
if(theUser == null) {
log.warn("Retry Register to Hue for " + hueAddress.getName() + " returned error: " + theData);
}
retryCount++;
}
else {
log.warn("GET HueApiResponse for " + hueAddress.getName() + " - returned error: " + theData);
return null;
}
}
else {
theHueApiResponse = new Gson().fromJson(theData, HueApiResponse.class);
log.debug("GET HueApiResponse for " + hueAddress.getName() + " - Gson parse - name: " + theHueApiResponse.getConfig().getName() + ", mac addr: " + theHueApiResponse.getConfig().getMac());
loopControl = false;
}
}
else {
log.warn("GET HueApiResponse for " + hueAddress.getName() + " - returned null, no data.");
loopControl = false;
}
}
return theHueApiResponse;
}
public String registerWithHue() {
UserCreateRequest theLogin = new UserCreateRequest();
theLogin.setDevicetype("HABridge#MyMachine");
HttpPost postRequest = new HttpPost("http://" + hueAddress.getIp() + HUE_REQUEST);
ContentType parsedContentType = ContentType.parse("application/json");
StringEntity requestBody = new StringEntity(new Gson().toJson(theLogin), parsedContentType);
HttpResponse response = null;
postRequest.setEntity(requestBody);
HttpClient anHttpClient = httpClient.getHttpClient();
try {
response = anHttpClient.execute(postRequest);
log.debug("POST execute on URL responded: " + response.getStatusLine().getStatusCode());
if(response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300){
String theBody = EntityUtils.toString(response.getEntity());
log.debug("registerWithHue response data: " + theBody);
if(theBody.contains("[{\"error\":")) {
if(theBody.contains("link button not")) {
log.warn("registerWithHue needs link button pressed on HUE bridge: " + hueAddress.getName());
}
else
log.warn("registerWithHue returned an unexpected error: " + theBody);
}
else {
SuccessUserResponse[] theResponses = new Gson().fromJson(theBody, SuccessUserResponse[].class); //read content for data, SuccessUserResponse[].class);
theUser = theResponses[0].getSuccess().getUsername();
}
}
EntityUtils.consume(response.getEntity()); //close out inputstream ignore content
} catch (IOException e) {
log.warn("Error logging into HUE: IOException in log", e);
}
return theUser;
}
public DeviceResponse getHueDeviceInfo(String hueDeviceId, DeviceDescriptor device) {
String responseString = null;
DeviceResponse deviceResponse = null;
if(theUser == null)
registerWithHue();
if (theUser != null) {
// make call
responseString = httpClient.doHttpRequest(
"http://" + hueAddress.getIp() + "/api/" + theUser
+ "/lights/" + hueDeviceId,
HttpGet.METHOD_NAME, "application/json", null, null);
if (responseString == null) {
log.warn("Error on calling hue device to get state: " + device.getName());
deviceResponse = DeviceResponse.createResponse(device);
} else if (responseString.contains("[{\"error\":") && responseString.contains("unauthorized user")) {
log.warn("Error on calling hue device to get state: " + device.getName() + " with errors: " + responseString);
deviceResponse = DeviceResponse.createResponse(device);
} else {
deviceResponse = new Gson().fromJson(responseString, DeviceResponse.class);
if (deviceResponse != null)
deviceResponse.setName(device.getName());
}
} else {
log.warn("Error on calling hue device to get state: " + device.getName() + " Could not register with hue: " + hueAddress.getName());
deviceResponse = DeviceResponse.createResponse(device);
}
return deviceResponse;
}
public String changeState(HueDeviceIdentifier deviceId, String lightId, String body) {
String responseString = null;
if(theUser == null)
registerWithHue();
if (theUser != null) {
responseString = httpClient.doHttpRequest(
"http://" + deviceId.getIpAddress() + "/api/" + theUser
+ "/lights/" + deviceId.getDeviceId() + "/state",
HttpPut.METHOD_NAME, "application/json", body, null);
if (responseString == null) {
log.warn("Error on calling Hue passthru to change device state: " + deviceId.getHueName());
responseString = "[{\"error\":{\"type\": 6, \"address\": \"/lights/" + lightId
+ "\",\"description\": \"Error on calling HUE to change device state\", \"parameter\": \"/lights/"
+ lightId + "state\"}}]";
} else if (responseString.contains("[{\"error\":")) {
if(responseString.contains("unauthorized user")) {
}
log.warn("Error occurred when calling Hue Passthru: " + responseString);
}
} else {
log.warn("Error on calling hue device to change state: " + deviceId.getHueName() + " Could not register with hue: " + hueAddress.getName());
}
return responseString;
}
public void closeHue() {
httpClient.closeHandler();
httpClient = null;
}
public NamedIP getHueAddress() {
return hueAddress;
}
public void setHueAddress(NamedIP hueAddress) {
this.hueAddress = hueAddress;
}
}

View File

@@ -1,4 +1,4 @@
package com.bwssystems.hue;
package com.bwssystems.HABridge.plugins.hue;
import java.io.IOException;
@@ -13,7 +13,7 @@ import org.slf4j.LoggerFactory;
import com.bwssystems.HABridge.api.SuccessUserResponse;
import com.bwssystems.HABridge.api.UserCreateRequest;
import com.bwssystems.http.HTTPHandler;
import com.bwssystems.HABridge.plugins.http.HTTPHandler;
import com.google.gson.Gson;
public class HueUtil {

View File

@@ -1,4 +1,4 @@
package com.bwssystems.mqtt;
package com.bwssystems.HABridge.plugins.mqtt;
import com.bwssystems.HABridge.NamedIP;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.mqtt;
package com.bwssystems.HABridge.plugins.mqtt;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
@@ -30,6 +30,7 @@ public class MQTTHandler {
}
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
connOpts.setAutomaticReconnect(true);
if(aConfig.getUsername() != null && aConfig.getUsername().trim().length() > 0) {
if(aConfig.getPassword() != null && aConfig.getPassword().trim().length() > 0) {
connOpts.setUserName(aConfig.getUsername().trim());

View File

@@ -1,4 +1,4 @@
package com.bwssystems.mqtt;
package com.bwssystems.HABridge.plugins.mqtt;
import java.util.ArrayList;
import java.util.HashMap;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.mqtt;
package com.bwssystems.HABridge.plugins.mqtt;
public class MQTTMessage {
private String clientId;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.tcp;
package com.bwssystems.HABridge.plugins.tcp;
import java.io.DataOutputStream;
import java.net.InetAddress;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.udp;
package com.bwssystems.HABridge.plugins.udp;
import java.io.IOException;
import java.net.InetAddress;
@@ -17,7 +17,7 @@ import com.bwssystems.HABridge.api.hue.StateChangeBody;
import com.bwssystems.HABridge.dao.DeviceDescriptor;
import com.bwssystems.HABridge.hue.BrightnessDecode;
import com.bwssystems.HABridge.hue.MultiCommandUtil;
import com.bwssystems.util.UDPDatagramSender;
import com.bwssystems.HABridge.util.UDPDatagramSender;
public class UDPHome implements Home {
private static final Logger log = LoggerFactory.getLogger(UDPHome.class);

View File

@@ -1,4 +1,4 @@
package com.bwssystems.vera;
package com.bwssystems.HABridge.plugins.vera;
import java.util.ArrayList;
import java.util.HashMap;
@@ -18,9 +18,9 @@ import com.bwssystems.HABridge.api.hue.DeviceState;
import com.bwssystems.HABridge.api.hue.StateChangeBody;
import com.bwssystems.HABridge.dao.DeviceDescriptor;
import com.bwssystems.HABridge.hue.MultiCommandUtil;
import com.bwssystems.luupRequests.Device;
import com.bwssystems.luupRequests.Scene;
import com.bwssystems.luupRequests.Sdata;
import com.bwssystems.HABridge.plugins.vera.luupRequests.Device;
import com.bwssystems.HABridge.plugins.vera.luupRequests.Scene;
import com.bwssystems.HABridge.plugins.vera.luupRequests.Sdata;
public class VeraHome implements Home {
private static final Logger log = LoggerFactory.getLogger(VeraHome.class);

View File

@@ -1,4 +1,4 @@
package com.bwssystems.vera;
package com.bwssystems.HABridge.plugins.vera;
import java.util.HashMap;
import java.util.ListIterator;
@@ -8,12 +8,12 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bwssystems.HABridge.NamedIP;
import com.bwssystems.http.HTTPHandler;
import com.bwssystems.luupRequests.Categorie;
import com.bwssystems.luupRequests.Device;
import com.bwssystems.luupRequests.Room;
import com.bwssystems.luupRequests.Scene;
import com.bwssystems.luupRequests.Sdata;
import com.bwssystems.HABridge.plugins.http.HTTPHandler;
import com.bwssystems.HABridge.plugins.vera.luupRequests.Categorie;
import com.bwssystems.HABridge.plugins.vera.luupRequests.Device;
import com.bwssystems.HABridge.plugins.vera.luupRequests.Room;
import com.bwssystems.HABridge.plugins.vera.luupRequests.Scene;
import com.bwssystems.HABridge.plugins.vera.luupRequests.Sdata;
import com.google.gson.Gson;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.luupRequests;
package com.bwssystems.HABridge.plugins.vera.luupRequests;
public class Categorie {
private String name;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.luupRequests;
package com.bwssystems.HABridge.plugins.vera.luupRequests;
public class Device {

View File

@@ -1,4 +1,4 @@
package com.bwssystems.luupRequests;
package com.bwssystems.HABridge.plugins.vera.luupRequests;
public class Room {
private String name;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.luupRequests;
package com.bwssystems.HABridge.plugins.vera.luupRequests;
public class Scene {
private String active;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.luupRequests;
package com.bwssystems.HABridge.plugins.vera.luupRequests;
import java.util.List;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.luupRequests;
package com.bwssystems.HABridge.plugins.vera.luupRequests;
public class Section {
private String name;

View File

@@ -8,7 +8,7 @@ import com.bwssystems.HABridge.BridgeSettingsDescriptor;
import com.bwssystems.HABridge.Configuration;
import com.bwssystems.HABridge.api.hue.HueConstants;
import com.bwssystems.HABridge.api.hue.HuePublicConfig;
import com.bwssystems.util.UDPDatagramSender;
import com.bwssystems.HABridge.util.UDPDatagramSender;
import java.io.IOException;
import java.net.*;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.util;
package com.bwssystems.HABridge.util;
import java.io.IOException;
import java.nio.file.DirectoryStream;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.util;
package com.bwssystems.HABridge.util;
import com.google.gson.Gson;
import spark.ResponseTransformer;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.util;
package com.bwssystems.HABridge.util;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

View File

@@ -1,4 +1,4 @@
package com.bwssystems.util;
package com.bwssystems.HABridge.util;
import java.io.IOException;
import java.net.DatagramPacket;

View File

@@ -1,82 +0,0 @@
package com.bwssystems.hue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bwssystems.HABridge.NamedIP;
import com.bwssystems.HABridge.api.hue.HueApiResponse;
import com.bwssystems.http.HTTPHandler;
import com.google.gson.Gson;
public class HueInfo {
private static final Logger log = LoggerFactory.getLogger(HueInfo.class);
private HTTPHandler httpClient;
private NamedIP hueAddress;
private String theUser;
private HueHome theHueHome;
private String errorString = null;
public HueInfo(NamedIP addressName, HueHome aHueHome) {
super();
httpClient = new HTTPHandler();
hueAddress = addressName;
theUser = "habridge";
theHueHome = aHueHome;
}
public HueApiResponse getHueApiResponse() {
HueApiResponse theHueApiResponse = null;
String theUrl = "http://" + hueAddress.getIp() + HueUtil.HUE_REQUEST + "/" + theUser;
String theData;
boolean loopControl = true;
int retryCount = 0;
while(loopControl) {
if(retryCount > 3) {
log.warn("Max Retry reached to get Hue data from " + hueAddress.getName());
loopControl = false;
break;
}
theUrl = "http://" + hueAddress.getIp() + HueUtil.HUE_REQUEST + "/" + theUser;
theData = httpClient.doHttpRequest(theUrl, null, null, null, null);
if(theData != null) {
log.debug("GET HueApiResponse - data: " + theData);
if(theData.contains("[{\"error\":")) {
if(theData.contains("unauthorized user")) {
theUser = HueUtil.registerWithHue(httpClient, hueAddress.getIp(), hueAddress.getName(), theHueHome.getTheHUERegisteredUser());
if(theUser == null) {
log.warn("Register to Hue for " + hueAddress.getName() + " returned error: " + errorString);
return null;
}
else
theHueHome.setTheHUERegisteredUser(theUser);
retryCount++;
}
else {
log.warn("GET HueApiResponse for " + hueAddress.getName() + " - returned error: " + theData);
return null;
}
}
else {
theHueApiResponse = new Gson().fromJson(theData, HueApiResponse.class);
log.debug("GET HueApiResponse for " + hueAddress.getName() + " - Gson parse - name: " + theHueApiResponse.getConfig().getName() + ", mac addr: " + theHueApiResponse.getConfig().getMac());
loopControl = false;
}
}
else {
log.warn("GET HueApiResponse for " + hueAddress.getName() + " - returned null, no data.");
loopControl = false;
}
}
return theHueApiResponse;
}
public NamedIP getHueAddress() {
return hueAddress;
}
public void setHueAddress(NamedIP hueAddress) {
this.hueAddress = hueAddress;
}
}

View File

@@ -997,43 +997,80 @@ app.controller('VeraController', function ($scope, $location, $http, bridgeServi
};
$scope.buildDeviceUrls = function (veradevice, dim_control) {
bridgeService.clearDevice();
$scope.device.deviceType = "switch";
$scope.device.name = veradevice.name;
$scope.device.targetDevice = veradevice.veraname;
$scope.device.mapType = "veraDevice";
$scope.device.mapId = veradevice.id;
if(dim_control.indexOf("byte") >= 0 || dim_control.indexOf("percent") >= 0 || dim_control.indexOf("math") >= 0)
$scope.device.dimUrl = "http://" + veradevice.veraaddress + ":" + $scope.vera.port
+ "/data_request?id=action&output_format=json&DeviceNum="
+ veradevice.id
+ "&serviceId=urn:upnp-org:serviceId:Dimming1&action=SetLoadLevelTarget&newLoadlevelTarget="
+ dim_control;
else
$scope.device.dimUrl = "http://" + veradevice.veraaddress + ":" + $scope.vera.port
var currentOn = $scope.device.onUrl;
var currentDim = $scope.device.dimUrl;
var currentOff = $scope.device.offUrl;
if( $scope.device.mapType !== undefined && $scope.device.mapType != null && $scope.device.mapType != "") {
$scope.device.mapId = $scope.device.mapId + "-" + veradevice.id;
if(dim_control.indexOf("byte") >= 0 || dim_control.indexOf("percent") >= 0 || dim_control.indexOf("math") >= 0)
$scope.device.dimUrl = currentDim.substr(0, currentDim.indexOf("]")) + ",{\"item\":\"http://" + veradevice.veraaddress + ":" + $scope.vera.port
+ "/data_request?id=action&output_format=json&DeviceNum="
+ veradevice.id
+ "&serviceId=urn:upnp-org:serviceId:Dimming1&action=SetLoadLevelTarget&newLoadlevelTarget="
+ dim_control + "\"},\"type\":\"veraDevice\"}]";
else
$scope.device.dimUrl = currentDim.substr(0, currentDim.indexOf("]")) + ",{\"item\":\"http://" + veradevice.veraaddress + ":" + $scope.vera.port
+ "/data_request?id=action&output_format=json&serviceId=urn:upnp-org:serviceId:SwitchPower1&action=SetTarget&newTargetValue=1&DeviceNum="
+ veradevice.id + "\"},\"type\":\"veraDevice\"}]";
$scope.device.onUrl = currentOn.substr(0, currentOn.indexOf("]")) + ",{\"item\":\"http://" + veradevice.veraaddress + ":" + $scope.vera.port
+ "/data_request?id=action&output_format=json&serviceId=urn:upnp-org:serviceId:SwitchPower1&action=SetTarget&newTargetValue=1&DeviceNum="
+ veradevice.id;
$scope.device.onUrl = "http://" + veradevice.veraaddress + ":" + $scope.vera.port
+ "/data_request?id=action&output_format=json&serviceId=urn:upnp-org:serviceId:SwitchPower1&action=SetTarget&newTargetValue=1&DeviceNum="
+ veradevice.id;
$scope.device.offUrl = "http://" + veradevice.veraaddress + ":" + $scope.vera.port
+ "/data_request?id=action&output_format=json&serviceId=urn:upnp-org:serviceId:SwitchPower1&action=SetTarget&newTargetValue=0&DeviceNum="
+ veradevice.id;
+ veradevice.id + "\"},\"type\":\"veraDevice\"}]";
$scope.device.offUrl = currentOff.substr(0, currentOff.indexOf("]")) + ",{\"item\":\"http://" + veradevice.veraaddress + ":" + $scope.vera.port
+ "/data_request?id=action&output_format=json&serviceId=urn:upnp-org:serviceId:SwitchPower1&action=SetTarget&newTargetValue=0&DeviceNum="
+ veradevice.id + "\"},\"type\":\"veraDevice\"}]";
}
else if ($scope.device.mapType === undefined || $scope.device.mapType == null || $scope.device.mapType == "") {
bridgeService.clearDevice();
$scope.device.deviceType = "switch";
$scope.device.name = veradevice.name;
$scope.device.targetDevice = veradevice.veraname;
$scope.device.mapType = "veraDevice";
$scope.device.mapId = veradevice.id;
if(dim_control.indexOf("byte") >= 0 || dim_control.indexOf("percent") >= 0 || dim_control.indexOf("math") >= 0)
$scope.device.dimUrl = "[{\"item\":\"http://" + veradevice.veraaddress + ":" + $scope.vera.port
+ "/data_request?id=action&output_format=json&DeviceNum="
+ veradevice.id
+ "&serviceId=urn:upnp-org:serviceId:Dimming1&action=SetLoadLevelTarget&newLoadlevelTarget="
+ dim_control + "\"},\"type\":\"veraDevice\"}]";
else
$scope.device.dimUrl = "[{\"item\":\"http://" + veradevice.veraaddress + ":" + $scope.vera.port
+ "/data_request?id=action&output_format=json&serviceId=urn:upnp-org:serviceId:SwitchPower1&action=SetTarget&newTargetValue=1&DeviceNum="
+ veradevice.id + "\"},\"type\":\"veraDevice\"}]";
$scope.device.onUrl = "[{\"item\":{\"clientId\":\"http://" + veradevice.veraaddress + ":" + $scope.vera.port
+ "/data_request?id=action&output_format=json&serviceId=urn:upnp-org:serviceId:SwitchPower1&action=SetTarget&newTargetValue=1&DeviceNum="
+ veradevice.id + "\"},\"type\":\"veraDevice\"}]";
$scope.device.offUrl = "[{\"item\":\"http://" + veradevice.veraaddress + ":" + $scope.vera.port
+ "/data_request?id=action&output_format=json&serviceId=urn:upnp-org:serviceId:SwitchPower1&action=SetTarget&newTargetValue=0&DeviceNum="
+ veradevice.id + "\"},\"type\":\"veraDevice\"}]";
}
};
$scope.buildSceneUrls = function (verascene) {
bridgeService.clearDevice();
$scope.device.deviceType = "scene";
$scope.device.name = verascene.name;
$scope.device.targetDevice = verascene.veraname;
$scope.device.mapType = "veraScene";
$scope.device.mapId = verascene.id;
$scope.device.onUrl = "http://" + verascene.veraaddress + ":" + $scope.vera.port
+ "/data_request?id=action&output_format=json&serviceId=urn:micasaverde-com:serviceId:HomeAutomationGateway1&action=RunScene&SceneNum="
+ verascene.id;
$scope.device.offUrl = "http://" + verascene.veraaddress + ":" + $scope.vera.port
+ "/data_request?id=action&output_format=json&serviceId=urn:micasaverde-com:serviceId:HomeAutomationGateway1&action=RunScene&SceneNum="
+ verascene.id;
var currentOn = $scope.device.onUrl;
var currentOff = $scope.device.offUrl;
if( $scope.device.mapType !== undefined && $scope.device.mapType != null && $scope.device.mapType != "") {
$scope.device.mapId = $scope.device.mapId + "-" + verascene.id;
$scope.device.onUrl = currentOn.substr(0, currentOn.indexOf("]")) + ",{\"item\":\"http://" + verascene.veraaddress + ":" + $scope.vera.port
+ "/data_request?id=action&output_format=json&serviceId=urn:micasaverde-com:serviceId:HomeAutomationGateway1&action=RunScene&SceneNum="
+ verascene.id+ "\"},\"type\":\"veraDevice\"}]";
$scope.device.offUrl = currentOff.substr(0, currentOff.indexOf("]")) + ",{\"item\":\"http://" + verascene.veraaddress + ":" + $scope.vera.port
+ "/data_request?id=action&output_format=json&serviceId=urn:micasaverde-com:serviceId:HomeAutomationGateway1&action=RunScene&SceneNum="
+ verascene.id+ "\"},\"type\":\"veraDevice\"}]";
}
else if ($scope.device.mapType === undefined || $scope.device.mapType == null || $scope.device.mapType == "") {
bridgeService.clearDevice();
$scope.device.deviceType = "scene";
$scope.device.name = verascene.name;
$scope.device.targetDevice = verascene.veraname;
$scope.device.mapType = "veraScene";
$scope.device.mapId = verascene.id;
$scope.device.onUrl = "[{\"item\":\"http://" + verascene.veraaddress + ":" + $scope.vera.port
+ "/data_request?id=action&output_format=json&serviceId=urn:micasaverde-com:serviceId:HomeAutomationGateway1&action=RunScene&SceneNum="
+ verascene.id+ "\"},\"type\":\"veraDevice\"}]";
$scope.device.offUrl = "[{\"item\":\"http://" + verascene.veraaddress + ":" + $scope.vera.port
+ "/data_request?id=action&output_format=json&serviceId=urn:micasaverde-com:serviceId:HomeAutomationGateway1&action=RunScene&SceneNum="
+ verascene.id+ "\"},\"type\":\"veraDevice\"}]";
}
};
$scope.addDevice = function () {

View File

@@ -3,11 +3,11 @@ package com.bwssystems.hass.test;
import java.util.Map;
import java.util.Map.Entry;
import com.bwssystems.hass.Field;
import com.bwssystems.hass.FieldDeserializer;
import com.bwssystems.hass.Service;
import com.bwssystems.hass.ServiceDeserializer;
import com.bwssystems.hass.ServiceElement;
import com.bwssystems.HABridge.plugins.hass.Field;
import com.bwssystems.HABridge.plugins.hass.FieldDeserializer;
import com.bwssystems.HABridge.plugins.hass.Service;
import com.bwssystems.HABridge.plugins.hass.ServiceDeserializer;
import com.bwssystems.HABridge.plugins.hass.ServiceElement;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;

View File

@@ -2,7 +2,7 @@ package com.bwssystems.hass.test;
import java.util.Map.Entry;
import com.bwssystems.hass.State;
import com.bwssystems.HABridge.plugins.hass.State;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;