Refactoring ready for testing

This commit is contained in:
bwssystems
2016-12-26 22:34:19 -06:00
parent d827605fa5
commit 2e177f3d4a
8 changed files with 197 additions and 229 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>3.5.1o</version> <version>3.5.1p</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>HA Bridge</name> <name>HA Bridge</name>

View File

@@ -54,6 +54,7 @@ public class BridgeSettings extends BackupHandler {
configFileProperty = Configuration.CONFIG_FILE; configFileProperty = Configuration.CONFIG_FILE;
} }
String serverPortOverride = System.getProperty("server.port"); String serverPortOverride = System.getProperty("server.port");
String serverIpOverride = System.getProperty("server.ip");
if(configFileProperty != null) if(configFileProperty != null)
{ {
log.info("reading from config file: " + configFileProperty); log.info("reading from config file: " + configFileProperty);
@@ -154,6 +155,8 @@ public class BridgeSettings extends BackupHandler {
theBridgeSettings.setHassconfigured(theBridgeSettings.isValidHass()); theBridgeSettings.setHassconfigured(theBridgeSettings.isValidHass());
if(serverPortOverride != null) if(serverPortOverride != null)
theBridgeSettings.setServerPort(serverPortOverride); theBridgeSettings.setServerPort(serverPortOverride);
if(serverIpOverride != null)
theBridgeSettings.setWebaddress(serverIpOverride);
setupParams(Paths.get(theBridgeSettings.getConfigfile()), ".cfgbk", "habridge.config-"); setupParams(Paths.get(theBridgeSettings.getConfigfile()), ".cfgbk", "habridge.config-");
} }

View File

@@ -57,22 +57,22 @@ public class HABridge {
// setup system control api first // setup system control api first
theSystem = new SystemControl(bridgeSettings, theVersion); theSystem = new SystemControl(bridgeSettings, theVersion);
theSystem.setupServer(); theSystem.setupServer();
//Setup the device connection homes through the manager
homeManager = new HomeManager();
homeManager.buildHomes(bridgeSettings.getBridgeSettingsDescriptor());
// setup the class to handle the resource setup rest api
theResources = new DeviceResource(bridgeSettings.getBridgeSettingsDescriptor(), homeManager);
// setup the class to handle the upnp response rest api
theSettingResponder = new UpnpSettingsResource(bridgeSettings.getBridgeSettingsDescriptor());
theSettingResponder.setupServer();
// setup the UDP Datagram socket to be used by the HueMulator and the upnpListener // setup the UDP Datagram socket to be used by the HueMulator and the upnpListener
udpSender = UDPDatagramSender.createUDPDatagramSender(bridgeSettings.getBridgeSettingsDescriptor().getUpnpResponsePort()); udpSender = UDPDatagramSender.createUDPDatagramSender(bridgeSettings.getBridgeSettingsDescriptor().getUpnpResponsePort());
if(udpSender == null) { if(udpSender == null) {
bridgeSettings.getBridgeControl().setStop(true); bridgeSettings.getBridgeControl().setStop(true);
} }
else { else {
//Setup the device connection homes through the manager
homeManager = new HomeManager();
homeManager.buildHomes(bridgeSettings.getBridgeSettingsDescriptor(), udpSender);
// setup the class to handle the resource setup rest api
theResources = new DeviceResource(bridgeSettings.getBridgeSettingsDescriptor(), homeManager);
// setup the class to handle the upnp response rest api
theSettingResponder = new UpnpSettingsResource(bridgeSettings.getBridgeSettingsDescriptor());
theSettingResponder.setupServer();
// setup the class to handle the hue emulator rest api // setup the class to handle the hue emulator rest api
theHueMulator = new HueMulator(bridgeSettings.getBridgeSettingsDescriptor(), theResources.getDeviceRepository(), homeManager, udpSender); theHueMulator = new HueMulator(bridgeSettings.getBridgeSettingsDescriptor(), theResources.getDeviceRepository(), homeManager);
theHueMulator.setupServer(); theHueMulator.setupServer();
// wait for the sparkjava initialization of the rest api classes to be complete // wait for the sparkjava initialization of the rest api classes to be complete
awaitInitialization(); awaitInitialization();
@@ -85,11 +85,11 @@ public class HABridge {
bridgeSettings.getBridgeControl().setStop(true); bridgeSettings.getBridgeControl().setStop(true);
if(bridgeSettings.getBridgeSettingsDescriptor().isSettingsChanged()) if(bridgeSettings.getBridgeSettingsDescriptor().isSettingsChanged())
bridgeSettings.save(bridgeSettings.getBridgeSettingsDescriptor()); bridgeSettings.save(bridgeSettings.getBridgeSettingsDescriptor());
homeManager.closeHomes();
udpSender.closeResponseSocket();
} }
bridgeSettings.getBridgeControl().setReinit(false); bridgeSettings.getBridgeControl().setReinit(false);
stop(); stop();
homeManager.closeHomes();
udpSender.closeResponseSocket();
} }
log.info("HA Bridge (v" + theVersion.getVersion() + ") exiting...."); log.info("HA Bridge (v" + theVersion.getVersion() + ") exiting....");
System.exit(0); System.exit(0);

View File

@@ -14,6 +14,7 @@ import com.bwssystems.hue.HueHome;
import com.bwssystems.mqtt.MQTTHome; import com.bwssystems.mqtt.MQTTHome;
import com.bwssystems.tcp.TCPHome; import com.bwssystems.tcp.TCPHome;
import com.bwssystems.udp.UDPHome; import com.bwssystems.udp.UDPHome;
import com.bwssystems.util.UDPDatagramSender;
import com.bwssystems.vera.VeraHome; import com.bwssystems.vera.VeraHome;
public class HomeManager { public class HomeManager {
@@ -26,7 +27,7 @@ public class HomeManager {
} }
// factory method // factory method
public void buildHomes(BridgeSettingsDescriptor bridgeSettings) { public void buildHomes(BridgeSettingsDescriptor bridgeSettings, UDPDatagramSender aUdpDatagramSender) {
Home aHome = null; Home aHome = null;
//setup the harmony connection if available //setup the harmony connection if available
aHome = new HarmonyHome(bridgeSettings); aHome = new HarmonyHome(bridgeSettings);
@@ -69,10 +70,10 @@ public class HomeManager {
homeList.put(DeviceMapTypes.VERA_SCENE[DeviceMapTypes.typeIndex], aHome); homeList.put(DeviceMapTypes.VERA_SCENE[DeviceMapTypes.typeIndex], aHome);
homeList.put(DeviceMapTypes.DEFAULT_DEVICE[DeviceMapTypes.typeIndex], aHome); homeList.put(DeviceMapTypes.DEFAULT_DEVICE[DeviceMapTypes.typeIndex], aHome);
//setup the tcp handler Home //setup the tcp handler Home
aHome = new TCPHome().createHome(bridgeSettings); aHome = new TCPHome(bridgeSettings);
homeList.put(DeviceMapTypes.TCP_DEVICE[DeviceMapTypes.typeIndex], aHome); homeList.put(DeviceMapTypes.TCP_DEVICE[DeviceMapTypes.typeIndex], aHome);
//setup the udp handler Home //setup the udp handler Home
aHome = new UDPHome().createHome(bridgeSettings); aHome = new UDPHome(bridgeSettings, aUdpDatagramSender);
homeList.put(DeviceMapTypes.UDP_DEVICE[DeviceMapTypes.typeIndex], aHome); homeList.put(DeviceMapTypes.UDP_DEVICE[DeviceMapTypes.typeIndex], aHome);
aHome = new VeraHome(bridgeSettings); aHome = new VeraHome(bridgeSettings);

View File

@@ -4,7 +4,6 @@ import com.bwssystems.HABridge.BridgeSettingsDescriptor;
import com.bwssystems.HABridge.DeviceMapTypes; import com.bwssystems.HABridge.DeviceMapTypes;
import com.bwssystems.HABridge.HomeManager; import com.bwssystems.HABridge.HomeManager;
import com.bwssystems.HABridge.api.CallItem; import com.bwssystems.HABridge.api.CallItem;
import com.bwssystems.HABridge.api.NameValue;
import com.bwssystems.HABridge.api.UserCreateRequest; import com.bwssystems.HABridge.api.UserCreateRequest;
import com.bwssystems.HABridge.api.hue.DeviceResponse; import com.bwssystems.HABridge.api.hue.DeviceResponse;
import com.bwssystems.HABridge.api.hue.DeviceState; import com.bwssystems.HABridge.api.hue.DeviceState;
@@ -21,7 +20,6 @@ import com.bwssystems.hue.HueDeviceIdentifier;
import com.bwssystems.hue.HueHome; import com.bwssystems.hue.HueHome;
import com.bwssystems.hue.HueUtil; import com.bwssystems.hue.HueUtil;
import com.bwssystems.util.JsonTransformer; import com.bwssystems.util.JsonTransformer;
import com.bwssystems.util.UDPDatagramSender;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@@ -36,10 +34,6 @@ import org.apache.http.client.methods.HttpGet;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
@@ -48,8 +42,6 @@ import java.util.Set;
import java.util.StringTokenizer; import java.util.StringTokenizer;
import java.util.UUID; import java.util.UUID;
import javax.xml.bind.DatatypeConverter;
/** /**
* Based on Armzilla's HueMulator - a Philips Hue emulator using sparkjava rest server * Based on Armzilla's HueMulator - a Philips Hue emulator using sparkjava rest server
*/ */
@@ -62,20 +54,15 @@ public class HueMulator {
private HomeManager homeManager; private HomeManager homeManager;
private HueHome myHueHome; private HueHome myHueHome;
private BridgeSettingsDescriptor bridgeSettings; private BridgeSettingsDescriptor bridgeSettings;
private UDPDatagramSender theUDPDatagramSender;
private byte[] sendData;
private Gson aGsonHandler; private Gson aGsonHandler;
private HTTPHandler anHttpHandler; private HTTPHandler anHttpHandler;
public HueMulator(BridgeSettingsDescriptor theBridgeSettings, DeviceRepository aDeviceRepository, HomeManager aHomeManager, UDPDatagramSender aUdpDatagramSender) { public HueMulator(BridgeSettingsDescriptor theBridgeSettings, DeviceRepository aDeviceRepository, HomeManager aHomeManager) {
repository = aDeviceRepository; repository = aDeviceRepository;
bridgeSettings = theBridgeSettings; bridgeSettings = theBridgeSettings;
theUDPDatagramSender = aUdpDatagramSender;
homeManager= aHomeManager; homeManager= aHomeManager;
myHueHome = (HueHome) homeManager.findHome(DeviceMapTypes.HUE_DEVICE[DeviceMapTypes.typeIndex]); myHueHome = (HueHome) homeManager.findHome(DeviceMapTypes.HUE_DEVICE[DeviceMapTypes.typeIndex]);
aGsonHandler = aGsonHandler = new GsonBuilder().create();
new GsonBuilder()
.create();
anHttpHandler = new HTTPHandler(); anHttpHandler = new HTTPHandler();
} }
@@ -277,29 +264,6 @@ public class HueMulator {
}); });
} }
private String doExecRequest(String anItem, int intensity, String lightId) {
log.debug("Executing request: " + anItem);
String responseString = null;
if (anItem != null && !anItem.equalsIgnoreCase("")) {
try {
Process p = Runtime.getRuntime().exec(BrightnessDecode.replaceIntensityValue(anItem, intensity, false));
log.debug("Process running: " + p.isAlive());
} catch (IOException e) {
log.warn("Could not execute request: " + anItem, e);
responseString = "[{\"error\":{\"type\": 6, \"address\": \"/lights/" + lightId
+ "\",\"description\": \"Error on calling out to device\", \"parameter\": \"/lights/" + lightId
+ "state\"}}]";
}
} else {
log.warn("Could not execute request. Request is empty.");
responseString = "[{\"error\":{\"type\": 6, \"address\": \"/lights/" + lightId
+ "\",\"description\": \"Error on calling out to device\", \"parameter\": \"/lights/" + lightId
+ "state\"}}]";
}
return responseString;
}
private String formatSuccessHueResponse(StateChangeBody state, String body, String lightId, private String formatSuccessHueResponse(StateChangeBody state, String body, String lightId,
DeviceState deviceState) { DeviceState deviceState) {
@@ -571,12 +535,14 @@ public class HueMulator {
deviceResponse = DeviceResponse.createResponse(device); deviceResponse = DeviceResponse.createResponse(device);
} else { } else {
deviceResponse = aGsonHandler.fromJson(responseString, DeviceResponse.class); deviceResponse = aGsonHandler.fromJson(responseString, DeviceResponse.class);
if (deviceResponse != null)
deviceResponse.setName(device.getName());
}
}
}
if (deviceResponse == null) if (deviceResponse == null)
deviceResponse = DeviceResponse.createResponse(device); deviceResponse = DeviceResponse.createResponse(device);
}
}
} else
deviceResponse = DeviceResponse.createResponse(device);
deviceResponseMap.put(device.getId(), deviceResponse); deviceResponseMap.put(device.getId(), deviceResponse);
} }
} }
@@ -786,7 +752,6 @@ public class HueMulator {
private String changeState(String userId, String lightId, String body, String ipAddress) { private String changeState(String userId, String lightId, String body, String ipAddress) {
String responseString = null; String responseString = null;
String url = null; String url = null;
NameValue[] theHeaders = null;
StateChangeBody theStateChanges = null; StateChangeBody theStateChanges = null;
DeviceState state = null; DeviceState state = null;
MultiCommandUtil aMultiUtil = new MultiCommandUtil(); MultiCommandUtil aMultiUtil = new MultiCommandUtil();
@@ -827,8 +792,6 @@ public class HueMulator {
if (state == null) if (state == null)
state = DeviceState.createDeviceState(); state = DeviceState.createDeviceState();
theHeaders = aGsonHandler.fromJson(device.getHeaders(), NameValue[].class);
if (stateHasBri) { if (stateHasBri) {
if(!state.isOn()) if(!state.isOn())
state.setOn(true); state.setOn(true);
@@ -851,12 +814,9 @@ public class HueMulator {
if (theStateChanges.isOn()) { if (theStateChanges.isOn()) {
url = device.getOnUrl(); url = device.getOnUrl();
state.setOn(true); state.setOn(true);
// if (state.getBri() <= 0)
// state.setBri(255);
} else if (!theStateChanges.isOn()) { } else if (!theStateChanges.isOn()) {
url = device.getOffUrl(); url = device.getOffUrl();
state.setOn(false); state.setOn(false);
// state.setBri(0);
} }
} }
@@ -865,14 +825,7 @@ public class HueMulator {
if(url == null) if(url == null)
url = device.getOnUrl(); url = device.getOnUrl();
} }
CallItem[] callItems = null; if (url != null) {
if (url == null) {
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 + "\"}}]";
}
else {
if (!url.startsWith("[")) { if (!url.startsWith("[")) {
if (url.startsWith("{\"item")) if (url.startsWith("{\"item"))
url = "[" + url + "]"; url = "[" + url + "]";
@@ -880,10 +833,8 @@ public class HueMulator {
url = "[{\"item\":\"" + url + "\"}]"; url = "[{\"item\":\"" + url + "\"}]";
} }
// CallItem[] callItems = callItemGson.fromJson(url, CallItem[] callItems = null;
// CallItem[].class);
callItems = aGsonHandler.fromJson(url, CallItem[].class); callItems = aGsonHandler.fromJson(url, CallItem[].class);
}
for (int i = 0; callItems != null && i < callItems.length; i++) { for (int i = 0; callItems != null && i < callItems.length; i++) {
if(!filterByRequester(callItems[i].getFilterIPs(), ipAddress)) { if(!filterByRequester(callItems[i].getFilterIPs(), ipAddress)) {
@@ -904,128 +855,15 @@ public class HueMulator {
callItems[i].setType(DeviceMapTypes.CUSTOM_DEVICE[DeviceMapTypes.typeIndex]); callItems[i].setType(DeviceMapTypes.CUSTOM_DEVICE[DeviceMapTypes.typeIndex]);
} }
if (callItems[i].getType() != null && callItems[i].getType().trim().equalsIgnoreCase(DeviceMapTypes.HUE_DEVICE[DeviceMapTypes.typeIndex])) { if (callItems[i].getType() != null) {
return homeManager.findHome(DeviceMapTypes.HUE_DEVICE[DeviceMapTypes.typeIndex]).deviceHandler(callItems[i], aMultiUtil, lightId, i, state, theStateChanges, stateHasBri, stateHasBriInc, device, body); responseString = homeManager.findHome(callItems[i].getType().trim()).deviceHandler(callItems[i], aMultiUtil, lightId, i, state, theStateChanges, stateHasBri, stateHasBriInc, device, body);
} else if (callItems[i].getType() != null && callItems[i].getType().trim().equalsIgnoreCase(DeviceMapTypes.HARMONY_ACTIVITY[DeviceMapTypes.typeIndex])) {
return homeManager.findHome(DeviceMapTypes.HARMONY_ACTIVITY[DeviceMapTypes.typeIndex]).deviceHandler(callItems[i], aMultiUtil, lightId, i, state, theStateChanges, stateHasBri, stateHasBriInc, device, body);
} else if (callItems[i].getType() != null && callItems[i].getType().trim().equalsIgnoreCase(DeviceMapTypes.HARMONY_BUTTON[DeviceMapTypes.typeIndex])) {
return homeManager.findHome(DeviceMapTypes.HARMONY_BUTTON[DeviceMapTypes.typeIndex]).deviceHandler(callItems[i], aMultiUtil, lightId, i, state, theStateChanges, stateHasBri, stateHasBriInc, device, body);
} else if (callItems[i].getType() != null && callItems[i].getType().trim().equalsIgnoreCase(DeviceMapTypes.NEST_HOMEAWAY[DeviceMapTypes.typeIndex])) {
return homeManager.findHome(DeviceMapTypes.NEST_HOMEAWAY[DeviceMapTypes.typeIndex]).deviceHandler(callItems[i], aMultiUtil, lightId, i, state, theStateChanges, stateHasBri, stateHasBriInc, device, body);
} else if (callItems[i].getType() != null && callItems[i].getType().trim().equalsIgnoreCase(DeviceMapTypes.NEST_THERMO_SET[DeviceMapTypes.typeIndex])) {
return homeManager.findHome(DeviceMapTypes.NEST_THERMO_SET[DeviceMapTypes.typeIndex]).deviceHandler(callItems[i], aMultiUtil, lightId, i, state, theStateChanges, stateHasBri, stateHasBriInc, device, body);
} else if (callItems[i].getType() != null && callItems[i].getType().trim().equalsIgnoreCase(DeviceMapTypes.MQTT_MESSAGE[DeviceMapTypes.typeIndex])) {
return homeManager.findHome(DeviceMapTypes.MQTT_MESSAGE[DeviceMapTypes.typeIndex]).deviceHandler(callItems[i], aMultiUtil, lightId, i, state, theStateChanges, stateHasBri, stateHasBriInc, device, body);
} else if (callItems[i].getType() != null && callItems[i].getType().trim().equalsIgnoreCase(DeviceMapTypes.HASS_DEVICE[DeviceMapTypes.typeIndex])) {
responseString = homeManager.findHome(DeviceMapTypes.HASS_DEVICE[DeviceMapTypes.typeIndex]).deviceHandler(callItems[i], aMultiUtil, lightId, i, state, theStateChanges, stateHasBri, stateHasBriInc, device, body);
} else if (callItems[i].getType() != null && callItems[i].getType().trim().equalsIgnoreCase(DeviceMapTypes.EXEC_DEVICE[DeviceMapTypes.typeIndex])) {
responseString = homeManager.findHome(DeviceMapTypes.EXEC_DEVICE[DeviceMapTypes.typeIndex]).deviceHandler(callItems[i], aMultiUtil, lightId, i, state, theStateChanges, stateHasBri, stateHasBriInc, device, body);
} else // This section allows the usage of http/tcp/udp/exec
// calls in a given set of items
{
log.debug("executing HUE api request for network call: " + url);
for (int x = 0; x < aMultiUtil.getSetCount(); x++) {
if (x > 0 || i > 0) {
try {
Thread.sleep(aMultiUtil.getTheDelay());
} catch (InterruptedException e) {
// ignore
} }
} }
if (callItems[i].getDelay() != null && callItems[i].getDelay() > 0)
aMultiUtil.setTheDelay(callItems[i].getDelay());
else
aMultiUtil.setTheDelay(bridgeSettings.getButtonsleep());
try {
if (callItems[i].getItem().getAsString().contains("udp://")
|| callItems[i].getItem().getAsString().contains("tcp://")) {
String intermediate = callItems[i].getItem().getAsString()
.substring(callItems[i].getItem().getAsString().indexOf("://") + 3);
String hostPortion = intermediate.substring(0, intermediate.indexOf('/'));
String theUrlBody = intermediate.substring(intermediate.indexOf('/') + 1);
String hostAddr = null;
String port = null;
if (hostPortion.contains(":")) {
hostAddr = hostPortion.substring(0, intermediate.indexOf(':'));
port = hostPortion.substring(intermediate.indexOf(':') + 1);
} else
hostAddr = hostPortion;
InetAddress IPAddress = InetAddress.getByName(hostAddr);
if (theUrlBody.startsWith("0x")) {
theUrlBody = BrightnessDecode.calculateReplaceIntensityValue(theUrlBody,
state, theStateChanges, stateHasBri, stateHasBriInc,
true);
sendData = DatatypeConverter.parseHexBinary(theUrlBody.substring(2));
} else {
theUrlBody = BrightnessDecode.calculateReplaceIntensityValue(theUrlBody,
state, theStateChanges, stateHasBri, stateHasBriInc,
false);
sendData = theUrlBody.getBytes();
}
if (callItems[i].getItem().getAsString().contains("udp://")) {
log.debug("executing HUE api request to UDP: " + callItems[i].getItem().getAsString());
theUDPDatagramSender.sendUDPResponse(new String(sendData), IPAddress,
Integer.parseInt(port));
} else if (callItems[i].getItem().getAsString().contains("tcp://")) {
log.debug("executing HUE api request to TCP: " + callItems[i].getItem().getAsString());
Socket dataSendSocket = new Socket(IPAddress, Integer.parseInt(port));
DataOutputStream outToClient = new DataOutputStream(
dataSendSocket.getOutputStream());
outToClient.write(sendData);
outToClient.flush();
dataSendSocket.close();
}
} else if (callItems[i].getItem().getAsString().contains("exec://")) {
String intermediate = callItems[i].getItem().getAsString()
.substring(callItems[i].getItem().getAsString().indexOf("://") + 3);
String anError = doExecRequest(intermediate,
BrightnessDecode.calculateIntensity(state, theStateChanges, stateHasBri, stateHasBriInc),
lightId);
if (anError != null) {
responseString = anError;
x = aMultiUtil.getSetCount();
}
} else { } else {
log.debug("executing HUE api request to Http " log.warn("Could not find url: " + lightId + " for hue state change request: " + userId + " from "
+ (device.getHttpVerb() == null ? "GET" : device.getHttpVerb()) + ": " + ipAddress + " body: " + body);
+ callItems[i].getItem().getAsString()); responseString = "[{\"error\":{\"type\": 3, \"address\": \"/lights/" + lightId
+ "\",\"description\": \"Could not find url\", \"resource\": \"/lights/" + lightId + "\"}}]";
String anUrl = BrightnessDecode.calculateReplaceIntensityValue(callItems[i].getItem().getAsString(),
state, theStateChanges, stateHasBri, stateHasBriInc, false);
String aBody;
if (stateHasBri || stateHasBriInc)
aBody = BrightnessDecode.calculateReplaceIntensityValue(device.getContentBodyDim(),
state, theStateChanges, stateHasBri, stateHasBriInc,
false);
else if (state.isOn())
aBody = BrightnessDecode.calculateReplaceIntensityValue(device.getContentBody(),
state, theStateChanges, stateHasBri, stateHasBriInc,
false);
else
aBody = BrightnessDecode.calculateReplaceIntensityValue(device.getContentBodyOff(),
state, theStateChanges, stateHasBri, stateHasBriInc,
false);
// make call
if (anHttpHandler.doHttpRequest(anUrl, device.getHttpVerb(), device.getContentType(), aBody,
theHeaders) == 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\"}}]";
x = aMultiUtil.getSetCount();
}
}
} catch (Exception e) {
log.warn("Change device state, Could not send data for network request: "
+ callItems[i].getItem().getAsString() + " with Message: " + e.getMessage());
responseString = "[{\"error\":{\"type\": 6, \"address\": \"/lights/" + lightId
+ "\",\"description\": \"Error on calling out to device\", \"parameter\": \"/lights/"
+ lightId + "state\"}}]";
x = aMultiUtil.getSetCount();
}
}
}
} }
if (responseString == null || !responseString.contains("[{\"error\":")) { if (responseString == null || !responseString.contains("[{\"error\":")) {
@@ -1036,5 +874,4 @@ public class HueMulator {
return responseString; return responseString;
} }
} }

View File

@@ -90,14 +90,12 @@ public class HarmonyHome implements Home {
ArrayList<HarmonyActivity> activityList = new ArrayList<HarmonyActivity>(); ArrayList<HarmonyActivity> activityList = new ArrayList<HarmonyActivity>();
while(keys.hasNext()) { while(keys.hasNext()) {
String key = keys.next(); String key = keys.next();
Iterator<Activity> activities = hubs.get(key).getMyHarmony().getActivities().iterator(); Activity theActivity = hubs.get(key).getMyHarmony().getCurrentActivity();
while(activities.hasNext()) {
HarmonyActivity anActivity = new HarmonyActivity(); HarmonyActivity anActivity = new HarmonyActivity();
anActivity.setActivity(activities.next()); anActivity.setActivity(theActivity);
anActivity.setHub(key); anActivity.setHub(key);
activityList.add(anActivity); activityList.add(anActivity);
} }
}
return activityList; return activityList;
} }
public List<HarmonyDevice> getDevices() { public List<HarmonyDevice> getDevices() {

View File

@@ -1,29 +1,94 @@
package com.bwssystems.tcp; package com.bwssystems.tcp;
import java.io.DataOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.xml.bind.DatatypeConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bwssystems.HABridge.BridgeSettingsDescriptor; import com.bwssystems.HABridge.BridgeSettingsDescriptor;
import com.bwssystems.HABridge.Home; import com.bwssystems.HABridge.Home;
import com.bwssystems.HABridge.api.CallItem; import com.bwssystems.HABridge.api.CallItem;
import com.bwssystems.HABridge.api.hue.DeviceState; import com.bwssystems.HABridge.api.hue.DeviceState;
import com.bwssystems.HABridge.api.hue.StateChangeBody; import com.bwssystems.HABridge.api.hue.StateChangeBody;
import com.bwssystems.HABridge.dao.DeviceDescriptor; import com.bwssystems.HABridge.dao.DeviceDescriptor;
import com.bwssystems.HABridge.hue.BrightnessDecode;
import com.bwssystems.HABridge.hue.MultiCommandUtil; import com.bwssystems.HABridge.hue.MultiCommandUtil;
public class TCPHome implements Home { public class TCPHome implements Home {
private static final Logger log = LoggerFactory.getLogger(TCPHome.class);
private byte[] sendData;
public TCPHome() {
// TODO Auto-generated constructor stub public TCPHome(BridgeSettingsDescriptor bridgeSettings) {
super();
createHome(bridgeSettings);
} }
@Override @Override
public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int iterationCount, public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int iterationCount,
DeviceState state, StateChangeBody theStateChanges, boolean stateHasBri, boolean stateHasBriInc, DeviceDescriptor device, String body) { DeviceState state, StateChangeBody theStateChanges, boolean stateHasBri, boolean stateHasBriInc,
// TODO Auto-generated method stub DeviceDescriptor device, String body) {
log.debug("executing HUE api request to TCP: " + anItem.getItem().toString());
for (int x = 0; x < aMultiUtil.getSetCount(); x++) {
if (x > 0 || iterationCount > 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());
String intermediate = anItem.getItem().toString().substring(anItem.getItem().toString().indexOf("://") + 3);
String hostPortion = intermediate.substring(0, intermediate.indexOf('/'));
String theUrlBody = intermediate.substring(intermediate.indexOf('/') + 1);
String hostAddr = null;
String port = null;
InetAddress IPAddress = null;
if (hostPortion.contains(":")) {
hostAddr = hostPortion.substring(0, intermediate.indexOf(':'));
port = hostPortion.substring(intermediate.indexOf(':') + 1);
} else
hostAddr = hostPortion;
try {
IPAddress = InetAddress.getByName(hostAddr);
} catch (UnknownHostException e) {
// noop
}
if (theUrlBody.startsWith("0x")) {
theUrlBody = BrightnessDecode.calculateReplaceIntensityValue(theUrlBody, state, theStateChanges,
stateHasBri, stateHasBriInc, true);
sendData = DatatypeConverter.parseHexBinary(theUrlBody.substring(2));
} else {
theUrlBody = BrightnessDecode.calculateReplaceIntensityValue(theUrlBody, state, theStateChanges,
stateHasBri, stateHasBriInc, false);
sendData = theUrlBody.getBytes();
}
try {
Socket dataSendSocket = new Socket(IPAddress, Integer.parseInt(port));
DataOutputStream outToClient = new DataOutputStream(dataSendSocket.getOutputStream());
outToClient.write(sendData);
outToClient.flush();
dataSendSocket.close();
} catch (Exception e) {
// noop
}
}
return null; return null;
} }
@Override @Override
public Home createHome(BridgeSettingsDescriptor bridgeSettings) { public Home createHome(BridgeSettingsDescriptor bridgeSettings) {
// TODO Auto-generated method stub // noop
return null; return null;
} }
@@ -35,7 +100,7 @@ public class TCPHome implements Home {
@Override @Override
public void closeHome() { public void closeHome() {
// TODO Auto-generated method stub // noop
} }

View File

@@ -1,23 +1,87 @@
package com.bwssystems.udp; package com.bwssystems.udp;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.xml.bind.DatatypeConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bwssystems.HABridge.BridgeSettingsDescriptor; import com.bwssystems.HABridge.BridgeSettingsDescriptor;
import com.bwssystems.HABridge.Home; import com.bwssystems.HABridge.Home;
import com.bwssystems.HABridge.api.CallItem; import com.bwssystems.HABridge.api.CallItem;
import com.bwssystems.HABridge.api.hue.DeviceState; import com.bwssystems.HABridge.api.hue.DeviceState;
import com.bwssystems.HABridge.api.hue.StateChangeBody; import com.bwssystems.HABridge.api.hue.StateChangeBody;
import com.bwssystems.HABridge.dao.DeviceDescriptor; import com.bwssystems.HABridge.dao.DeviceDescriptor;
import com.bwssystems.HABridge.hue.BrightnessDecode;
import com.bwssystems.HABridge.hue.MultiCommandUtil; import com.bwssystems.HABridge.hue.MultiCommandUtil;
import com.bwssystems.util.UDPDatagramSender;
public class UDPHome implements Home { public class UDPHome implements Home {
private static final Logger log = LoggerFactory.getLogger(UDPHome.class);
private UDPDatagramSender theUDPDatagramSender;
private byte[] sendData;
public UDPHome() { public UDPHome(BridgeSettingsDescriptor bridgeSettings, UDPDatagramSender aUDPDatagramSender) {
// TODO Auto-generated constructor stub super();
theUDPDatagramSender = aUDPDatagramSender;
createHome(bridgeSettings);
} }
@Override @Override
public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int iterationCount, public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int iterationCount,
DeviceState state, StateChangeBody theStateChanges, boolean stateHasBri, boolean stateHasBriInc, DeviceDescriptor device, String body) { DeviceState state, StateChangeBody theStateChanges, boolean stateHasBri, boolean stateHasBriInc, DeviceDescriptor device, String body) {
// TODO Auto-generated method stub log.debug("executing HUE api request to UDP: " + anItem.getItem().toString());
for (int x = 0; x < aMultiUtil.getSetCount(); x++) {
if (x > 0 || iterationCount > 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());
String intermediate = anItem.getItem().getAsString()
.substring(anItem.getItem().getAsString().indexOf("://") + 3);
String hostPortion = intermediate.substring(0, intermediate.indexOf('/'));
String theUrlBody = intermediate.substring(intermediate.indexOf('/') + 1);
String hostAddr = null;
String port = null;
InetAddress IPAddress = null;
if (hostPortion.contains(":")) {
hostAddr = hostPortion.substring(0, intermediate.indexOf(':'));
port = hostPortion.substring(intermediate.indexOf(':') + 1);
} else
hostAddr = hostPortion;
try {
IPAddress = InetAddress.getByName(hostAddr);
} catch (UnknownHostException e) {
// noop
}
if (theUrlBody.startsWith("0x")) {
theUrlBody = BrightnessDecode.calculateReplaceIntensityValue(theUrlBody,
state, theStateChanges, stateHasBri, stateHasBriInc, true);
sendData = DatatypeConverter.parseHexBinary(theUrlBody.substring(2));
} else {
theUrlBody = BrightnessDecode.calculateReplaceIntensityValue(theUrlBody,
state, theStateChanges, stateHasBri, stateHasBriInc, false);
sendData = theUrlBody.getBytes();
}
try {
theUDPDatagramSender.sendUDPResponse(new String(sendData), IPAddress,
Integer.parseInt(port));
} catch (NumberFormatException e) {
// noop
} catch (IOException e) {
// noop
}
}
return null; return null;
} }