Continuation of refactoring hueMulator

This commit is contained in:
Admin
2016-12-22 16:13:01 -06:00
parent 4225f4554e
commit 40a9eb95ac
23 changed files with 816 additions and 710 deletions

View File

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

View File

@@ -1,167 +1,70 @@
package com.bwssystems.HABridge;
import java.util.ArrayList;
public class DeviceMapTypes {
public final static String[] CUSTOM_DEVICE = { "custom", "Custom"};
public final static String[] VERA_DEVICE = { "veraDevice", "Vera Device"};
public final static String[] VERA_SCENE = { "veraScene", "Vera Scene"};
public final static String[] HARMONY_ACTIVITY = { "harmonyActivity", "Harmony Activity"};
public final static String[] HARMONY_BUTTON = { "harmonyButton", "Harmony Button"};
public final static String[] NEST_HOMEAWAY = { "nestHomeAway", "Nest Home Status"};
public final static String[] NEST_THERMO_SET = { "nestThermoSet", "Nest Thermostat"};
public final static String[] HUE_DEVICE = { "hueDevice", "Hue Device"};
public final static String[] HAL_DEVICE = { "halDevice", "HAL Device"};
public final static String[] HAL_BUTTON = { "halButton", "HAL Button"};
public final static String[] HAL_HOME = { "halHome", "HAL Home Status"};
public final static String[] HAL_THERMO_SET = { "halThermoSet", "HAL Thermostat"};
public final static String[] MQTT_MESSAGE = { "mqttMessage", "MQTT Message"};
public final static String[] EXEC_DEVICE = { "exec", "Execute Script/Program"};
public final static String[] HASS_DEVICE = { "hassDevice", "HomeAssistant Device"};
public final static String[] CUSTOM_DEVICE = { "custom", "Custom", "none"};
public final static String[] VERA_DEVICE = { "veraDevice", "Vera Device", "vera"};
public final static String[] VERA_SCENE = { "veraScene", "Vera Scene", "vera"};
public final static String[] HARMONY_ACTIVITY = { "harmonyActivity", "Harmony Activity", "harmony"};
public final static String[] HARMONY_BUTTON = { "harmonyButton", "Harmony Button", "harmony"};
public final static String[] NEST_HOMEAWAY = { "nestHomeAway", "Nest Home Status", "nest"};
public final static String[] NEST_THERMO_SET = { "nestThermoSet", "Nest Thermostat", "nest"};
public final static String[] HUE_DEVICE = { "hueDevice", "Hue Device", "hue"};
public final static String[] HAL_DEVICE = { "halDevice", "HAL Device", "hal"};
public final static String[] HAL_BUTTON = { "halButton", "HAL Button", "hal"};
public final static String[] HAL_HOME = { "halHome", "HAL Home Status", "hal"};
public final static String[] HAL_THERMO_SET = { "halThermoSet", "HAL Thermostat", "hal"};
public final static String[] MQTT_MESSAGE = { "mqttMessage", "MQTT Message", "mqtt"};
public final static String[] EXEC_DEVICE = { "exec", "Execute Script/Program", "command"};
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[] UDP_DEVICE = { "udpDevice", "UDP Device", "none"};
public final static String[] HTTP_DEVICE = { "httpDevice", "HTTP Device", "none"};
public final static String[] DEFAULT_DEVICE = { "udpDevice", "Default Device", "none"};
public final static int typeIndex = 0;
public final static int displayIndex = 1;
public final static int resourceIndex = 1;
public String[] customDevice;
public String[] veraDevice;
public String[] veraScene;
public String[] harmonyActivity;
public String[] harmonyButton;
public String[] nestHomeAway;
public String[] nestThermoSet;
public String[] hueDevice;
public String[] halDevice;
public String[] halButton;
public String[] halHome;
public String[] halThermoSet;
public String[] mqttMessage;
public String[] execDevice;
public String[] hassDevice;
public int typeindex;
public int displayindex;
ArrayList<String[]> deviceMapTypes;
public DeviceMapTypes() {
super();
this.setCustomDevice(CUSTOM_DEVICE);
this.setDisplayindex(displayIndex);
this.setExecDevice(EXEC_DEVICE);
this.setHalButton(HAL_BUTTON);
this.setHalDevice(HAL_DEVICE);
this.setHalHome(HAL_HOME);
this.setHalThermoSet(HAL_THERMO_SET);
this.setHarmonyActivity(HARMONY_ACTIVITY);
this.setHarmonyButton(HARMONY_BUTTON);
this.setHueDevice(HUE_DEVICE);
this.setMqttMessage(MQTT_MESSAGE);
this.setNestHomeAway(NEST_HOMEAWAY);
this.setNestThermoSet(NEST_THERMO_SET);
this.setTypeindex(typeIndex);
this.setVeraDevice(VERA_DEVICE);
this.setVeraScene(VERA_SCENE);
this.setHassDevice(HASS_DEVICE);
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(HASS_DEVICE);
deviceMapTypes.add(HTTP_DEVICE);
deviceMapTypes.add(HUE_DEVICE);
deviceMapTypes.add(MQTT_MESSAGE);
deviceMapTypes.add(NEST_HOMEAWAY);
deviceMapTypes.add(NEST_THERMO_SET);
deviceMapTypes.add(TCP_DEVICE);
deviceMapTypes.add(UDP_DEVICE);
deviceMapTypes.add(VERA_DEVICE);
deviceMapTypes.add(VERA_SCENE);
deviceMapTypes.add(HAL_BUTTON);
deviceMapTypes.add(HARMONY_ACTIVITY);
deviceMapTypes.add(HARMONY_BUTTON);
}
public String[] getCustomDevice() {
return customDevice;
public static int getTypeIndex() {
return typeIndex;
}
public void setCustomDevice(String[] customDevice) {
this.customDevice = customDevice;
public static int getDisplayIndex() {
return displayIndex;
}
public String[] getVeraDevice() {
return veraDevice;
public static int getResourceindex() {
return resourceIndex;
}
public void setVeraDevice(String[] veraDevice) {
this.veraDevice = veraDevice;
public ArrayList<String[]> getDeviceMapTypes() {
return deviceMapTypes;
}
public String[] getVeraScene() {
return veraScene;
}
public void setVeraScene(String[] veraScene) {
this.veraScene = veraScene;
}
public String[] getHarmonyActivity() {
return harmonyActivity;
}
public void setHarmonyActivity(String[] harmonyActivity) {
this.harmonyActivity = harmonyActivity;
}
public String[] getHarmonyButton() {
return harmonyButton;
}
public void setHarmonyButton(String[] harmonyButton) {
this.harmonyButton = harmonyButton;
}
public String[] getNestHomeAway() {
return nestHomeAway;
}
public void setNestHomeAway(String[] nestHomeAway) {
this.nestHomeAway = nestHomeAway;
}
public String[] getNestThermoSet() {
return nestThermoSet;
}
public void setNestThermoSet(String[] nestThermoSet) {
this.nestThermoSet = nestThermoSet;
}
public String[] getHueDevice() {
return hueDevice;
}
public void setHueDevice(String[] hueDevice) {
this.hueDevice = hueDevice;
}
public String[] getHalDevice() {
return halDevice;
}
public void setHalDevice(String[] halDevice) {
this.halDevice = halDevice;
}
public String[] getHalButton() {
return halButton;
}
public void setHalButton(String[] halButton) {
this.halButton = halButton;
}
public String[] getHalHome() {
return halHome;
}
public void setHalHome(String[] halHome) {
this.halHome = halHome;
}
public String[] getHalThermoSet() {
return halThermoSet;
}
public void setHalThermoSet(String[] halThermoSet) {
this.halThermoSet = halThermoSet;
}
public String[] getMqttMessage() {
return mqttMessage;
}
public void setMqttMessage(String[] mqttMessage) {
this.mqttMessage = mqttMessage;
}
public String[] getExecDevice() {
return execDevice;
}
public void setExecDevice(String[] execDevice) {
this.execDevice = execDevice;
}
public String[] getHassDevice() {
return hassDevice;
}
public void setHassDevice(String[] hassDevice) {
this.hassDevice = hassDevice;
}
public int getTypeindex() {
return typeindex;
}
public void setTypeindex(int typeindex) {
this.typeindex = typeindex;
}
public int getDisplayindex() {
return displayindex;
}
public void setDisplayindex(int displayindex) {
this.displayindex = displayindex;
}
}

View File

@@ -9,12 +9,6 @@ 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.NestBridge.NestHome;
import com.bwssystems.hal.HalHome;
import com.bwssystems.harmony.HarmonyHome;
import com.bwssystems.hass.HassHome;
import com.bwssystems.hue.HueHome;
import com.bwssystems.mqtt.MQTTHome;
import com.bwssystems.util.UDPDatagramSender;
public class HABridge {
@@ -37,12 +31,7 @@ public class HABridge {
public static void main(String[] args) {
Logger log = LoggerFactory.getLogger(HABridge.class);
DeviceResource theResources;
HarmonyHome harmonyHome;
NestHome nestHome;
HueHome hueHome;
HalHome halHome;
MQTTHome mqttHome;
HassHome hassHome;
HomeManager homeManager;
HueMulator theHueMulator;
UDPDatagramSender udpSender;
UpnpSettingsResource theSettingResponder;
@@ -68,20 +57,11 @@ public class HABridge {
// setup system control api first
theSystem = new SystemControl(bridgeSettings, theVersion);
theSystem.setupServer();
//setup the harmony connection if available
harmonyHome = new HarmonyHome(bridgeSettings.getBridgeSettingsDescriptor());
//setup the nest connection if available
nestHome = new NestHome(bridgeSettings.getBridgeSettingsDescriptor());
//setup the hue passtrhu configuration if available
hueHome = new HueHome(bridgeSettings.getBridgeSettingsDescriptor());
//setup the hal configuration if available
halHome = new HalHome(bridgeSettings.getBridgeSettingsDescriptor());
//setup the mqtt handlers if available
mqttHome = new MQTTHome(bridgeSettings.getBridgeSettingsDescriptor());
//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
//setup the HomeAssistant configuration if available
hassHome = new HassHome(bridgeSettings.getBridgeSettingsDescriptor());
theResources = new DeviceResource(bridgeSettings.getBridgeSettingsDescriptor(), harmonyHome, nestHome, hueHome, halHome, mqttHome, hassHome);
theResources = new DeviceResource(bridgeSettings.getBridgeSettingsDescriptor(), homeManager);
// setup the class to handle the upnp response rest api
theSettingResponder = new UpnpSettingsResource(bridgeSettings.getBridgeSettingsDescriptor());
theSettingResponder.setupServer();
@@ -92,7 +72,7 @@ public class HABridge {
}
else {
// setup the class to handle the hue emulator rest api
theHueMulator = new HueMulator(bridgeSettings.getBridgeSettingsDescriptor(), theResources.getDeviceRepository(), harmonyHome, nestHome, hueHome, mqttHome, hassHome, udpSender);
theHueMulator = new HueMulator(bridgeSettings.getBridgeSettingsDescriptor(), theResources.getDeviceRepository(), homeManager, udpSender);
theHueMulator.setupServer();
// wait for the sparkjava initialization of the rest api classes to be complete
awaitInitialization();
@@ -108,12 +88,7 @@ public class HABridge {
}
bridgeSettings.getBridgeControl().setReinit(false);
stop();
nestHome.closeTheNest();
nestHome = null;
harmonyHome.shutdownHarmonyHubs();
harmonyHome = null;
mqttHome.shutdownMQTTClients();
mqttHome = null;
homeManager.closeHomes();
udpSender.closeResponseSocket();
}
log.info("HA Bridge (v" + theVersion.getVersion() + ") exiting....");

View File

@@ -1,7 +1,9 @@
package com.bwssystems.HABridge;
import com.bwssystems.HABridge.devicemanagmeent.ResourceHandler;
import com.bwssystems.HABridge.hue.HueMulatorHandler;
public interface Home extends HueMulatorHandler {
public interface Home extends HueMulatorHandler, ResourceHandler {
public Home createHome(BridgeSettingsDescriptor bridgeSettings);
public void closeHome();
}

View File

@@ -1,9 +1,92 @@
package com.bwssystems.HABridge;
public class HomeManager {
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.vera.VeraHome;
public class HomeManager {
Map<String, Home> homeList;
Map<String, Home> resourceList;
public HomeManager() {
// TODO Auto-generated constructor stub
homeList = new HashMap<String, Home>();
resourceList = new HashMap<String, Home>();
}
// factory method
public void buildHomes(BridgeSettingsDescriptor bridgeSettings) {
Home aHome = null;
//setup the harmony connection if available
aHome = new HarmonyHome(bridgeSettings);
resourceList.put(DeviceMapTypes.HARMONY_ACTIVITY[DeviceMapTypes.resourceIndex], aHome);
homeList.put(DeviceMapTypes.HARMONY_ACTIVITY[DeviceMapTypes.typeIndex], aHome);
homeList.put(DeviceMapTypes.HARMONY_BUTTON[DeviceMapTypes.typeIndex], aHome);
//setup the nest connection if available
aHome = new NestHome(bridgeSettings);
resourceList.put(DeviceMapTypes.NEST_HOMEAWAY[DeviceMapTypes.resourceIndex], aHome);
homeList.put(DeviceMapTypes.NEST_HOMEAWAY[DeviceMapTypes.typeIndex], aHome);
homeList.put(DeviceMapTypes.NEST_THERMO_SET[DeviceMapTypes.typeIndex], aHome);
//setup the hue passtrhu configuration if available
aHome = new HueHome(bridgeSettings);
resourceList.put(DeviceMapTypes.HUE_DEVICE[DeviceMapTypes.resourceIndex], aHome);
homeList.put(DeviceMapTypes.HUE_DEVICE[DeviceMapTypes.typeIndex], aHome);
//setup the hal configuration if available
aHome = new HalHome(bridgeSettings);
resourceList.put(DeviceMapTypes.HAL_DEVICE[DeviceMapTypes.resourceIndex], aHome);
homeList.put(DeviceMapTypes.HAL_DEVICE[DeviceMapTypes.typeIndex], aHome);
homeList.put(DeviceMapTypes.HAL_BUTTON[DeviceMapTypes.typeIndex], aHome);
homeList.put(DeviceMapTypes.HAL_HOME[DeviceMapTypes.typeIndex], aHome);
homeList.put(DeviceMapTypes.HAL_THERMO_SET[DeviceMapTypes.typeIndex], aHome);
//setup the mqtt handlers if available
aHome = new MQTTHome(bridgeSettings);
resourceList.put(DeviceMapTypes.MQTT_MESSAGE[DeviceMapTypes.resourceIndex], aHome);
homeList.put(DeviceMapTypes.MQTT_MESSAGE[DeviceMapTypes.typeIndex], aHome);
//setup the HomeAssistant configuration if available
aHome = new HassHome(bridgeSettings);
resourceList.put(DeviceMapTypes.HASS_DEVICE[DeviceMapTypes.resourceIndex], aHome);
homeList.put(DeviceMapTypes.HASS_DEVICE[DeviceMapTypes.typeIndex], aHome);
//setup the command execution Home
aHome = new CommandHome().createHome(bridgeSettings);
homeList.put(DeviceMapTypes.EXEC_DEVICE[DeviceMapTypes.typeIndex], aHome);
homeList.put(DeviceMapTypes.CMD_DEVICE[DeviceMapTypes.typeIndex], aHome);
//setup the http handler Home
aHome = new HTTPHome().createHome(bridgeSettings);
homeList.put(DeviceMapTypes.HTTP_DEVICE[DeviceMapTypes.typeIndex], aHome);
homeList.put(DeviceMapTypes.CUSTOM_DEVICE[DeviceMapTypes.typeIndex], aHome);
homeList.put(DeviceMapTypes.VERA_DEVICE[DeviceMapTypes.typeIndex], aHome);
homeList.put(DeviceMapTypes.VERA_SCENE[DeviceMapTypes.typeIndex], aHome);
homeList.put(DeviceMapTypes.DEFAULT_DEVICE[DeviceMapTypes.typeIndex], aHome);
//setup the tcp handler Home
aHome = new TCPHome().createHome(bridgeSettings);
homeList.put(DeviceMapTypes.TCP_DEVICE[DeviceMapTypes.typeIndex], aHome);
//setup the udp handler Home
aHome = new UDPHome().createHome(bridgeSettings);
homeList.put(DeviceMapTypes.UDP_DEVICE[DeviceMapTypes.typeIndex], aHome);
aHome = new VeraHome(bridgeSettings);
resourceList.put(DeviceMapTypes.VERA_DEVICE[DeviceMapTypes.resourceIndex], aHome);
}
public Home findHome(String type) {
return homeList.get(type);
}
public ResourceHandler findResource(String type) {
return resourceList.get(type);
}
public void closeHomes() {
}
}

View File

@@ -17,20 +17,12 @@ import org.slf4j.LoggerFactory;
import com.bwssystems.HABridge.BridgeSettingsDescriptor;
import com.bwssystems.HABridge.DeviceMapTypes;
import com.bwssystems.HABridge.HomeManager;
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.NestBridge.NestHome;
import com.bwssystems.hal.HalHome;
import com.bwssystems.harmony.HarmonyHome;
import com.bwssystems.hass.HassHome;
import com.bwssystems.hue.HueHome;
import com.bwssystems.luupRequests.Device;
import com.bwssystems.luupRequests.Scene;
import com.bwssystems.mqtt.MQTTHome;
import com.bwssystems.util.JsonTransformer;
import com.bwssystems.vera.VeraHome;
import com.google.gson.Gson;
/**
@@ -40,53 +32,12 @@ public class DeviceResource {
private static final String API_CONTEXT = "/api/devices";
private static final Logger log = LoggerFactory.getLogger(DeviceResource.class);
private DeviceRepository deviceRepository;
private VeraHome veraHome;
private HarmonyHome myHarmonyHome;
private NestHome nestHome;
private HueHome hueHome;
private HalHome halHome;
private MQTTHome mqttHome;
private HassHome hassHome;
private HomeManager homeManager;
private static final Set<String> supportedVerbs = new HashSet<>(Arrays.asList("get", "put", "post"));
public DeviceResource(BridgeSettingsDescriptor theSettings, HarmonyHome theHarmonyHome, NestHome aNestHome, HueHome aHueHome, HalHome aHalHome, MQTTHome aMqttHome, HassHome aHassHome) {
public DeviceResource(BridgeSettingsDescriptor theSettings, HomeManager aHomeManager) {
this.deviceRepository = new DeviceRepository(theSettings.getUpnpDeviceDb());
if(theSettings.isValidVera())
this.veraHome = new VeraHome(theSettings);
else
this.veraHome = null;
if(theSettings.isValidHarmony())
this.myHarmonyHome = theHarmonyHome;
else
this.myHarmonyHome = null;
if(theSettings.isValidNest())
this.nestHome = aNestHome;
else
this.nestHome = null;
if(theSettings.isValidHue())
this.hueHome = aHueHome;
else
this.hueHome = null;
if(theSettings.isValidHal())
this.halHome = aHalHome;
else
this.halHome = null;
if(theSettings.isValidMQTT())
this.mqttHome = aMqttHome;
else
this.mqttHome = null;
if(theSettings.isValidHass())
this.hassHome = aHassHome;
else
this.hassHome = null;
homeManager = aHomeManager;
setupEndpoints();
}
@@ -205,119 +156,66 @@ public class DeviceResource {
get (API_CONTEXT + "/vera/devices", "application/json", (request, response) -> {
log.debug("Get vera devices");
if(veraHome == null){
response.status(HttpStatus.SC_NOT_FOUND);
return new ErrorMessage("A Vera is not available.");
}
List<Device> theDevices = veraHome.getDevices();
if(theDevices == null) {
response.status(HttpStatus.SC_SERVICE_UNAVAILABLE);
return new ErrorMessage("A Vera request failed to get devices. Check your Vera IP addresses.");
}
else
response.status(HttpStatus.SC_OK);
return theDevices;
response.status(HttpStatus.SC_OK);
return homeManager.findResource(DeviceMapTypes.VERA_DEVICE[DeviceMapTypes.resourceIndex]).getItems(DeviceMapTypes.VERA_DEVICE[DeviceMapTypes.typeIndex]);
}, new JsonTransformer());
get (API_CONTEXT + "/vera/scenes", "application/json", (request, response) -> {
log.debug("Get vera scenes");
if(veraHome == null){
response.status(HttpStatus.SC_NOT_FOUND);
return new ErrorMessage("A Vera is not available.");
}
List<Scene> theScenes = veraHome.getScenes();
if(theScenes == null) {
response.status(HttpStatus.SC_SERVICE_UNAVAILABLE);
return new ErrorMessage("A Vera is not available and failed to get scenes. Check your Vera IP addresses.");
}
else
response.status(HttpStatus.SC_OK);
return theScenes;
response.status(HttpStatus.SC_OK);
return homeManager.findResource(DeviceMapTypes.VERA_DEVICE[DeviceMapTypes.resourceIndex]).getItems(DeviceMapTypes.VERA_SCENE[DeviceMapTypes.typeIndex]);
}, new JsonTransformer());
get (API_CONTEXT + "/harmony/activities", "application/json", (request, response) -> {
log.debug("Get harmony activities");
if(myHarmonyHome == null) {
response.status(HttpStatus.SC_NOT_FOUND);
return new ErrorMessage("A Harmony is not available.");
}
response.status(HttpStatus.SC_OK);
return myHarmonyHome.getActivities();
return homeManager.findResource(DeviceMapTypes.HARMONY_ACTIVITY[DeviceMapTypes.resourceIndex]).getItems(DeviceMapTypes.HARMONY_ACTIVITY[DeviceMapTypes.typeIndex]);
}, new JsonTransformer());
get (API_CONTEXT + "/harmony/show", "application/json", (request, response) -> {
log.debug("Get harmony current activity");
if(myHarmonyHome == null) {
response.status(HttpStatus.SC_NOT_FOUND);
return new ErrorMessage("A Harmony is not available.");
}
response.status(HttpStatus.SC_OK);
return myHarmonyHome.getCurrentActivities();
return homeManager.findResource(DeviceMapTypes.HARMONY_ACTIVITY[DeviceMapTypes.resourceIndex]).getItems("current_activity");
}, new JsonTransformer());
get (API_CONTEXT + "/harmony/devices", "application/json", (request, response) -> {
log.debug("Get harmony devices");
if(myHarmonyHome == null) {
response.status(HttpStatus.SC_NOT_FOUND);
return new ErrorMessage("A Harmony is not available.");
}
response.status(HttpStatus.SC_OK);
return myHarmonyHome.getDevices();
return homeManager.findResource(DeviceMapTypes.HARMONY_BUTTON[DeviceMapTypes.resourceIndex]).getItems(DeviceMapTypes.HARMONY_BUTTON[DeviceMapTypes.typeIndex]);
}, new JsonTransformer());
get (API_CONTEXT + "/nest/items", "application/json", (request, response) -> {
log.debug("Get nest items");
if(nestHome == null) {
response.status(HttpStatus.SC_NOT_FOUND);
return new ErrorMessage("A Nest is not available.");
}
response.status(HttpStatus.SC_OK);
return nestHome.getItems();
return homeManager.findResource(DeviceMapTypes.NEST_HOMEAWAY[DeviceMapTypes.resourceIndex]).getItems(DeviceMapTypes.NEST_HOMEAWAY[DeviceMapTypes.typeIndex]);
}, new JsonTransformer());
get (API_CONTEXT + "/hue/devices", "application/json", (request, response) -> {
log.debug("Get hue items");
if(hueHome == null) {
response.status(HttpStatus.SC_NOT_FOUND);
return new ErrorMessage("A Hue is not available.");
}
response.status(HttpStatus.SC_OK);
return hueHome.getDevices();
return homeManager.findResource(DeviceMapTypes.HUE_DEVICE[DeviceMapTypes.resourceIndex]).getItems(DeviceMapTypes.HUE_DEVICE[DeviceMapTypes.typeIndex]);
}, new JsonTransformer());
get (API_CONTEXT + "/hal/devices", "application/json", (request, response) -> {
log.debug("Get hal items");
if(halHome == null) {
response.status(HttpStatus.SC_NOT_FOUND);
return new ErrorMessage("A Hal is not available.");
}
response.status(HttpStatus.SC_OK);
return halHome.getDevices();
return homeManager.findResource(DeviceMapTypes.HAL_DEVICE[DeviceMapTypes.resourceIndex]).getItems(DeviceMapTypes.HAL_DEVICE[DeviceMapTypes.typeIndex]);
}, new JsonTransformer());
get (API_CONTEXT + "/mqtt/devices", "application/json", (request, response) -> {
log.debug("Get MQTT brokers");
if(mqttHome == null) {
response.status(HttpStatus.SC_NOT_FOUND);
return new ErrorMessage("A MQTT config is not available.");
}
response.status(HttpStatus.SC_OK);
return mqttHome.getBrokers();
return homeManager.findResource(DeviceMapTypes.MQTT_MESSAGE[DeviceMapTypes.resourceIndex]).getItems(DeviceMapTypes.MQTT_MESSAGE[DeviceMapTypes.typeIndex]);
}, new JsonTransformer());
get (API_CONTEXT + "/hass/devices", "application/json", (request, response) -> {
log.debug("Get HomeAssistant Clients");
if(hassHome == null) {
response.status(HttpStatus.SC_NOT_FOUND);
return new ErrorMessage("A HomeAssistant config is not available.");
}
response.status(HttpStatus.SC_OK);
return hassHome.getDevices();
return homeManager.findResource(DeviceMapTypes.HASS_DEVICE[DeviceMapTypes.resourceIndex]).getItems(DeviceMapTypes.HASS_DEVICE[DeviceMapTypes.typeIndex]);
}, new JsonTransformer());
get (API_CONTEXT + "/map/types", "application/json", (request, response) -> {
log.debug("Get map types");
return new DeviceMapTypes();
return new DeviceMapTypes().getDeviceMapTypes();
}, new JsonTransformer());
// http://ip_address:port/api/devices/exec/renumber CORS request

View File

@@ -0,0 +1,5 @@
package com.bwssystems.HABridge.devicemanagmeent;
public interface ResourceHandler {
public Object getItems(String type);
}

View File

@@ -100,4 +100,8 @@ public class BrightnessDecode {
return request;
}
// Helper Method
public static String calculateReplaceIntensityValue(String request, DeviceState state, StateChangeBody theChanges, boolean hasBri, boolean hasBriInc, boolean isHex) {
return replaceIntensityValue(request, calculateIntensity(state, theChanges, hasBri, hasBriInc), isHex);
}
}

View File

@@ -2,6 +2,7 @@ package com.bwssystems.HABridge.hue;
import com.bwssystems.HABridge.BridgeSettingsDescriptor;
import com.bwssystems.HABridge.DeviceMapTypes;
import com.bwssystems.HABridge.HomeManager;
import com.bwssystems.HABridge.api.CallItem;
import com.bwssystems.HABridge.api.NameValue;
import com.bwssystems.HABridge.api.UserCreateRequest;
@@ -15,29 +16,21 @@ 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.NestBridge.NestInstruction;
import com.bwssystems.NestBridge.NestHome;
import com.bwssystems.harmony.ButtonPress;
import com.bwssystems.harmony.HarmonyHandler;
import com.bwssystems.harmony.HarmonyHome;
import com.bwssystems.harmony.RunActivity;
import com.bwssystems.hass.HassCommand;
import com.bwssystems.hass.HassHome;
import com.bwssystems.hass.HomeAssistant;
import com.bwssystems.hue.HueDeviceIdentifier;
import com.bwssystems.hue.HueHome;
import com.bwssystems.hue.HueUtil;
import com.bwssystems.mqtt.MQTTHandler;
import com.bwssystems.mqtt.MQTTHome;
import com.bwssystems.mqtt.MQTTMessage;
import com.bwssystems.nest.controller.Nest;
import com.bwssystems.util.JsonTransformer;
import com.bwssystems.util.UDPDatagramSender;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.java.dev.eval.Expression;
import static spark.Spark.get;
import static spark.Spark.options;
import static spark.Spark.post;
@@ -65,8 +58,6 @@ import org.slf4j.LoggerFactory;
import java.io.DataOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URI;
@@ -89,19 +80,13 @@ import javax.xml.bind.DatatypeConverter;
public class HueMulator {
private static final Logger log = LoggerFactory.getLogger(HueMulator.class);
private static final String INTENSITY_PERCENT = "${intensity.percent}";
private static final String INTENSITY_BYTE = "${intensity.byte}";
private static final String INTENSITY_MATH = "${intensity.math(";
private static final String INTENSITY_MATH_VALUE = "X";
private static final String INTENSITY_MATH_CLOSE = ")}";
private static final String HUE_CONTEXT = "/api";
private DeviceRepository repository;
private HarmonyHome myHarmonyHome;
private Nest theNest;
private HomeManager homeManager;
private HueHome myHueHome;
private HarmonyHome myHarmonyHome;
private MQTTHome mqttHome;
private HassHome hassHome;
private HttpClient httpClient;
private CloseableHttpClient httpclientSSL;
private SSLContext sslcontext;
@@ -112,13 +97,9 @@ public class HueMulator {
private byte[] sendData;
private String hueUser;
private String errorString;
private Integer setCount;
private Integer theDelay;
private Gson aGsonHandler;
public HueMulator(BridgeSettingsDescriptor theBridgeSettings, DeviceRepository aDeviceRepository,
HarmonyHome theHarmonyHome, NestHome aNestHome, HueHome aHueHome, MQTTHome aMqttHome, HassHome aHassHome,
UDPDatagramSender aUdpDatagramSender) {
public HueMulator(BridgeSettingsDescriptor theBridgeSettings, DeviceRepository aDeviceRepository, HomeManager aHomeManager, UDPDatagramSender aUdpDatagramSender) {
httpClient = HttpClients.createDefault();
// Trust own CA and all self-signed certs
sslcontext = SSLContexts.createDefault();
@@ -129,28 +110,12 @@ public class HueMulator {
httpclientSSL = HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(globalConfig).build();
repository = aDeviceRepository;
if (theBridgeSettings.isValidHarmony())
this.myHarmonyHome = theHarmonyHome;
else
this.myHarmonyHome = null;
if (theBridgeSettings.isValidNest())
this.theNest = aNestHome.getTheNest();
else
this.theNest = null;
if (theBridgeSettings.isValidHue())
this.myHueHome = aHueHome;
else
this.myHueHome = null;
if (theBridgeSettings.isValidMQTT())
this.mqttHome = aMqttHome;
else
this.mqttHome = null;
if (theBridgeSettings.isValidHass())
this.hassHome = aHassHome;
else
this.hassHome = null;
bridgeSettings = theBridgeSettings;
theUDPDatagramSender = aUdpDatagramSender;
homeManager= aHomeManager;
myHueHome = (HueHome) homeManager.findHome(DeviceMapTypes.HUE_DEVICE[DeviceMapTypes.typeIndex]);
myHarmonyHome = (HarmonyHome) homeManager.findHome(DeviceMapTypes.HARMONY_ACTIVITY[DeviceMapTypes.typeIndex]);
mqttHome = (MQTTHome) homeManager.findHome(DeviceMapTypes.MQTT_MESSAGE[DeviceMapTypes.typeIndex]);
hueUser = null;
errorString = null;
aGsonHandler =
@@ -358,83 +323,6 @@ public class HueMulator {
});
}
private int calculateIntensity(DeviceState state, StateChangeBody theChanges, boolean hasBri, boolean hasBriInc) {
int setIntensity = state.getBri();
if (hasBri) {
setIntensity = theChanges.getBri();
} else if (hasBriInc) {
if ((setIntensity + theChanges.getBri_inc()) <= 0)
setIntensity = theChanges.getBri_inc();
else if ((setIntensity + theChanges.getBri_inc()) > 255)
setIntensity = theChanges.getBri_inc();
else
setIntensity = setIntensity + theChanges.getBri_inc();
}
return setIntensity;
}
/*
* light weight templating here, was going to use free marker but it was a
* bit too heavy for what we were trying to do.
*
* currently provides: intensity.byte : 0-255 brightness. this is raw from
* the echo intensity.percent : 0-100, adjusted for the vera
* intensity.math(X*1) : where X is the value from the interface call and
* can use net.java.dev.eval math
*/
protected String replaceIntensityValue(String request, int intensity, boolean isHex) {
if (request == null) {
return null;
}
if (request.contains(INTENSITY_BYTE)) {
if (isHex) {
BigInteger bigInt = BigInteger.valueOf(intensity);
byte[] theBytes = bigInt.toByteArray();
String hexValue = DatatypeConverter.printHexBinary(theBytes);
request = request.replace(INTENSITY_BYTE, hexValue);
} else {
String intensityByte = String.valueOf(intensity);
request = request.replace(INTENSITY_BYTE, intensityByte);
}
} else if (request.contains(INTENSITY_PERCENT)) {
int percentBrightness = (int) Math.round(intensity / 255.0 * 100);
if (isHex) {
BigInteger bigInt = BigInteger.valueOf(percentBrightness);
byte[] theBytes = bigInt.toByteArray();
String hexValue = DatatypeConverter.printHexBinary(theBytes);
request = request.replace(INTENSITY_PERCENT, hexValue);
} else {
String intensityPercent = String.valueOf(percentBrightness);
request = request.replace(INTENSITY_PERCENT, intensityPercent);
}
} else if (request.contains(INTENSITY_MATH)) {
Map<String, BigDecimal> variables = new HashMap<String, BigDecimal>();
String mathDescriptor = request.substring(request.indexOf(INTENSITY_MATH) + INTENSITY_MATH.length(),
request.indexOf(INTENSITY_MATH_CLOSE));
variables.put(INTENSITY_MATH_VALUE, new BigDecimal(intensity));
try {
log.debug("Math eval is: " + mathDescriptor + ", Where " + INTENSITY_MATH_VALUE + " is: "
+ String.valueOf(intensity));
Expression exp = new Expression(mathDescriptor);
BigDecimal result = exp.eval(variables);
Integer endResult = Math.round(result.floatValue());
if (isHex) {
BigInteger bigInt = BigInteger.valueOf(endResult);
byte[] theBytes = bigInt.toByteArray();
String hexValue = DatatypeConverter.printHexBinary(theBytes);
request = request.replace(INTENSITY_MATH + mathDescriptor + INTENSITY_MATH_CLOSE, hexValue);
} else {
request = request.replace(INTENSITY_MATH + mathDescriptor + INTENSITY_MATH_CLOSE,
endResult.toString());
}
} catch (Exception e) {
log.warn("Could not execute Math: " + mathDescriptor, e);
}
}
return request;
}
// This function executes the url from the device repository against the
// target as http or https as defined
protected String doHttpRequest(String url, String httpVerb, String contentType, String body, NameValue[] headers) {
@@ -518,7 +406,7 @@ public class HueMulator {
String responseString = null;
if (anItem != null && !anItem.equalsIgnoreCase("")) {
try {
Process p = Runtime.getRuntime().exec(replaceIntensityValue(anItem, intensity, false));
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);
@@ -750,21 +638,6 @@ public class HueMulator {
return false;
}
private Integer getSetCount() {
return setCount;
}
private void setSetCount(Integer setCount) {
this.setCount = setCount;
}
private Integer getTheDelay() {
return theDelay;
}
private void setTheDelay(Integer theDelay) {
this.theDelay = theDelay;
}
private String basicListHandler(String type, String userId, String requestIp) {
log.debug("hue " + type + " list requested: " + userId + " from " + requestIp);
HueError[] theErrors = validateWhitelistUser(userId, false);
@@ -1010,28 +883,12 @@ public class HueMulator {
}
responseString = this.formatSuccessHueResponse(theStateChanges, body, lightId,
device.getDeviceState());
device.getDeviceState().setBri(calculateIntensity(state, theStateChanges, stateHasBri, stateHasBriInc));
device.getDeviceState().setBri(BrightnessDecode.calculateIntensity(state, theStateChanges, stateHasBri, stateHasBriInc));
return responseString;
}
private String hassDeviceHandler(CallItem anItem, String lightId, int iterationCount, DeviceState state, StateChangeBody theStateChanges, boolean stateHasBri, boolean stateHasBriInc) {
String theReturn = null;
MultiCommandUtil aMultiCmdUtil = new MultiCommandUtil();
// TODO set multi ommmand util here
log.debug("executing HUE api request to send message to HomeAssistant: " + anItem.getItem().toString());
if (hassHome != null) {
hassHome.deviceHandler(anItem, aMultiCmdUtil, lightId, iterationCount, state, theStateChanges, stateHasBri, stateHasBriInc);
} else {
log.warn("Should not get here, no HomeAssistant clients configured");
theReturn = "[{\"error\":{\"type\": 6, \"address\": \"/lights/" + lightId
+ "\",\"description\": \"Should not get here, no HomeAssistants configured\", \"parameter\": \"/lights/"
+ lightId + "state\"}}]";
}
return theReturn;
}
private HueError[] validateHueUser(String userId, String ipAddress, String aName) {
String hueUser;
HueErrorResponse theErrorResp = null;
@@ -1056,10 +913,12 @@ public class HueMulator {
NameValue[] theHeaders = null;
StateChangeBody theStateChanges = null;
DeviceState state = null;
MultiCommandUtil aMultiUtil = new MultiCommandUtil();
boolean stateHasBri = false;
boolean stateHasBriInc = false;
this.setTheDelay(bridgeSettings.getButtonsleep());
this.setSetCount(1);
aMultiUtil.setTheDelay(bridgeSettings.getButtonsleep());
aMultiUtil.setDelayDefault(bridgeSettings.getButtonsleep());
aMultiUtil.setSetCount(1);
log.debug("hue state change requested: " + userId + " from " + ipAddress + " body: " + body);
HueError[] theErrors = validateWhitelistUser(userId, false);
if (theErrors != null)
@@ -1156,9 +1015,9 @@ public class HueMulator {
continue;
}
if (callItems[i].getCount() != null && callItems[i].getCount() > 0)
setCount = callItems[i].getCount();
aMultiUtil.setSetCount(callItems[i].getCount());
else
setCount = 1;
aMultiUtil.setSetCount(1);
// code for backwards compatibility
if((callItems[i].getType() == null || callItems[i].getType().trim().length() == 0)) {
if(device.getMapType() != null && device.getMapType().length() > 0)
@@ -1183,24 +1042,24 @@ public class HueMulator {
}
// make call
for (int x = 0; x < setCount; x++) {
for (int x = 0; x < aMultiUtil.getSetCount(); x++) {
if (x > 0 || i > 0) {
try {
Thread.sleep(this.getTheDelay());
Thread.sleep(aMultiUtil.getTheDelay());
} catch (InterruptedException e) {
// ignore
}
}
if (callItems[i].getDelay() != null && callItems[i].getDelay() > 0)
this.setTheDelay(callItems[i].getDelay());
aMultiUtil.setTheDelay(callItems[i].getDelay());
else
this.setTheDelay(bridgeSettings.getButtonsleep());
aMultiUtil.setTheDelay(bridgeSettings.getButtonsleep());
responseString = doHttpRequest(
"http://" + deviceId.getIpAddress() + "/api/" + myHueHome.getTheHUERegisteredUser()
+ "/lights/" + deviceId.getDeviceId() + "/state",
HttpPut.METHOD_NAME, device.getContentType(), body, null);
if (responseString.contains("[{\"error\":"))
x = setCount;
x = aMultiUtil.getSetCount();
}
if (responseString == null) {
log.warn("Error on calling url to change device state: " + url);
@@ -1237,18 +1096,18 @@ public class HueMulator {
+ "\",\"description\": \"Should not get here, no harmony hub available\", \"parameter\": \"/lights/"
+ lightId + "state\"}}]";
} else {
for (int x = 0; x < setCount; x++) {
for (int x = 0; x < aMultiUtil.getSetCount(); x++) {
if (x > 0 || i > 0) {
try {
Thread.sleep(this.getTheDelay());
Thread.sleep(aMultiUtil.getTheDelay());
} catch (InterruptedException e) {
// ignore
}
}
if (callItems[i].getDelay() != null && callItems[i].getDelay() > 0)
this.setTheDelay(callItems[i].getDelay());
aMultiUtil.setTheDelay(callItems[i].getDelay());
else
this.setTheDelay(bridgeSettings.getButtonsleep());
aMultiUtil.setTheDelay(bridgeSettings.getButtonsleep());
myHarmony.startActivity(anActivity);
}
}
@@ -1282,33 +1141,33 @@ public class HueMulator {
for(int y = 0; y < theCount; y++) {
if( y > 0 || z > 0) {
try {
Thread.sleep(this.getTheDelay());
Thread.sleep(aMultiUtil.getTheDelay());
} catch (InterruptedException e) {
// ignore
}
}
if (callItems[i].getDelay() != null && callItems[i].getDelay() > 0)
this.setTheDelay(callItems[i].getDelay());
aMultiUtil.setTheDelay(callItems[i].getDelay());
else
this.setTheDelay(bridgeSettings.getButtonsleep());
aMultiUtil.setTheDelay(bridgeSettings.getButtonsleep());
log.debug("pressing button: " + deviceButtons[z].getDevice() + " - " + deviceButtons[z].getButton() + " - iteration: " + String.valueOf(z) + " - count: " + String.valueOf(y));
myHarmony.pressButton(deviceButtons[z]);
}
}
}
else {
for (int x = 0; x < setCount; x++) {
for (int x = 0; x < aMultiUtil.getSetCount(); x++) {
if (x > 0 || i > 0) {
try {
Thread.sleep(this.getTheDelay());
Thread.sleep(aMultiUtil.getTheDelay());
} catch (InterruptedException e) {
// ignore
}
}
if (callItems[i].getDelay() != null && callItems[i].getDelay() > 0)
this.setTheDelay(callItems[i].getDelay());
aMultiUtil.setTheDelay(callItems[i].getDelay());
else
this.setTheDelay(bridgeSettings.getButtonsleep());
aMultiUtil.setTheDelay(bridgeSettings.getButtonsleep());
log.debug("pressing button: " + deviceButtons[i].getDevice() + " - "
+ deviceButtons[i].getButton() + " - iteration: " + String.valueOf(i)
+ " - count: " + String.valueOf(x));
@@ -1324,72 +1183,14 @@ public class HueMulator {
}
} else if (callItems[i].getType() != null && callItems[i].getType().trim().equalsIgnoreCase(DeviceMapTypes.NEST_HOMEAWAY[DeviceMapTypes.typeIndex])) {
log.debug("executing HUE api request to set away for nest home: " + url);
if (theNest == null) {
log.warn("Should not get here, no Nest available");
responseString = "[{\"error\":{\"type\": 6, \"address\": \"/lights/" + lightId
+ "\",\"description\": \"Should not get here, no Nest available\", \"parameter\": \"/lights/"
+ lightId + "state\"}}]";
} else {
NestInstruction homeAway = aGsonHandler.fromJson(url, NestInstruction.class);
theNest.getHome(homeAway.getName()).setAway(homeAway.getAway());
}
return homeManager.findHome(DeviceMapTypes.NEST_HOMEAWAY[DeviceMapTypes.typeIndex]).deviceHandler(callItems[i], aMultiUtil, lightId, i, state, theStateChanges, stateHasBri, stateHasBriInc);
} else if (callItems[i].getType() != null && callItems[i].getType().trim().equalsIgnoreCase(DeviceMapTypes.NEST_THERMO_SET[DeviceMapTypes.typeIndex])) {
log.debug("executing HUE api request to set thermostat for nest: " + url);
if (theNest == null) {
log.warn("Should not get here, no Nest available");
responseString = "[{\"error\":{\"type\": 6, \"address\": \"/lights/" + lightId
+ "\",\"description\": \"Should not get here, no Nest available\", \"parameter\": \"/lights/"
+ lightId + "state\"}}]";
} else {
NestInstruction thermoSetting = aGsonHandler.fromJson(url, NestInstruction.class);
if (thermoSetting.getControl().equalsIgnoreCase("temp")) {
if (body.contains("bri")) {
if (bridgeSettings.isFarenheit())
thermoSetting
.setTemp(
String.valueOf((Double
.parseDouble(replaceIntensityValue(thermoSetting.getTemp(),
calculateIntensity(state, theStateChanges,
stateHasBri, stateHasBriInc),
false))
- 32.0) / 1.8));
else
thermoSetting
.setTemp(
String.valueOf(Double.parseDouble(replaceIntensityValue(
thermoSetting.getTemp(), calculateIntensity(state,
theStateChanges, stateHasBri, stateHasBriInc),
false))));
log.debug("Setting thermostat: " + thermoSetting.getName() + " to "
+ thermoSetting.getTemp() + "C");
theNest.getThermostat(thermoSetting.getName())
.setTargetTemperature(Float.parseFloat(thermoSetting.getTemp()));
}
} else if (thermoSetting.getControl().contains("range")
|| thermoSetting.getControl().contains("heat")
|| thermoSetting.getControl().contains("cool")
|| thermoSetting.getControl().contains("off")) {
log.debug("Setting thermostat target type: " + thermoSetting.getName() + " to "
+ thermoSetting.getControl());
theNest.getThermostat(thermoSetting.getName()).setTargetType(thermoSetting.getControl());
} else if (thermoSetting.getControl().contains("fan")) {
log.debug("Setting thermostat fan mode: " + thermoSetting.getName() + " to "
+ thermoSetting.getControl().substring(4));
theNest.getThermostat(thermoSetting.getName())
.setFanMode(thermoSetting.getControl().substring(4));
} else {
log.warn("no valid Nest control info: " + thermoSetting.getControl());
responseString = "[{\"error\":{\"type\": 6, \"address\": \"/lights/" + lightId
+ "\",\"description\": \"no valid Nest control info\", \"parameter\": \"/lights/"
+ lightId + "state\"}}]";
}
}
return homeManager.findHome(DeviceMapTypes.NEST_THERMO_SET[DeviceMapTypes.typeIndex]).deviceHandler(callItems[i], aMultiUtil, lightId, i, state, theStateChanges, stateHasBri, stateHasBriInc);
} else if (callItems[i].getType() != null && callItems[i].getType().trim().equalsIgnoreCase(DeviceMapTypes.MQTT_MESSAGE[DeviceMapTypes.typeIndex])) {
log.debug("executing HUE api request to send message to MQTT broker: " + url);
if (mqttHome != null) {
MQTTMessage[] mqttMessages = aGsonHandler.fromJson(replaceIntensityValue(url,
calculateIntensity(state, theStateChanges, stateHasBri, stateHasBriInc), false), MQTTMessage[].class);
MQTTMessage[] mqttMessages = aGsonHandler.fromJson(BrightnessDecode.replaceIntensityValue(url,
BrightnessDecode.calculateIntensity(state, theStateChanges, stateHasBri, stateHasBriInc), false), MQTTMessage[].class);
MQTTHandler mqttHandler = mqttHome.getMQTTHandler(mqttMessages[i].getClientId());
if (mqttHandler == null) {
log.warn("Should not get here, no mqtt hanlder available");
@@ -1397,18 +1198,18 @@ public class HueMulator {
+ "\",\"description\": \"Should not get here, no mqtt handler available\", \"parameter\": \"/lights/"
+ lightId + "state\"}}]";
}
for (int x = 0; x < setCount; x++) {
for (int x = 0; x < aMultiUtil.getSetCount(); x++) {
if (x > 0 || i > 0) {
try {
Thread.sleep(this.getTheDelay());
Thread.sleep(aMultiUtil.getTheDelay());
} catch (InterruptedException e) {
// ignore
}
}
if (callItems[i].getDelay() != null && callItems[i].getDelay() > 0)
this.setTheDelay(callItems[i].getDelay());
aMultiUtil.setTheDelay(callItems[i].getDelay());
else
this.setTheDelay(bridgeSettings.getButtonsleep());
aMultiUtil.setTheDelay(bridgeSettings.getButtonsleep());
log.debug("publishing message: " + mqttMessages[i].getClientId() + " - "
+ mqttMessages[i].getTopic() + " - " + mqttMessages[i].getMessage()
+ " - iteration: " + String.valueOf(i) + " - count: " + String.valueOf(x));
@@ -1422,7 +1223,7 @@ public class HueMulator {
}
} else if (callItems[i].getType() != null && callItems[i].getType().trim().equalsIgnoreCase(DeviceMapTypes.HASS_DEVICE[DeviceMapTypes.typeIndex])) {
responseString = hassDeviceHandler(callItems[i], lightId, i, state, theStateChanges, stateHasBri, stateHasBriInc);
responseString = homeManager.findHome(DeviceMapTypes.HASS_DEVICE[DeviceMapTypes.typeIndex]).deviceHandler(callItems[i], aMultiUtil, lightId, i, state, theStateChanges, stateHasBri, stateHasBriInc);
} else if (callItems[i].getType() != null && callItems[i].getType().trim().equalsIgnoreCase(DeviceMapTypes.EXEC_DEVICE[DeviceMapTypes.typeIndex])) {
log.debug("Exec Request called with url: " + url);
String intermediate;
@@ -1430,41 +1231,41 @@ public class HueMulator {
intermediate = callItems[i].getItem().getAsString().substring(callItems[i].getItem().getAsString().indexOf("://") + 3);
else
intermediate = callItems[i].getItem().getAsString();
for (int x = 0; x < setCount; x++) {
for (int x = 0; x < aMultiUtil.getSetCount(); x++) {
if (x > 0 || i > 0) {
try {
Thread.sleep(this.getTheDelay());
Thread.sleep(aMultiUtil.getTheDelay());
} catch (InterruptedException e) {
// ignore
}
}
if (callItems[i].getDelay() != null && callItems[i].getDelay() > 0)
this.setTheDelay(callItems[i].getDelay());
aMultiUtil.setTheDelay(callItems[i].getDelay());
else
this.setTheDelay(bridgeSettings.getButtonsleep());
aMultiUtil.setTheDelay(bridgeSettings.getButtonsleep());
String anError = doExecRequest(intermediate,
calculateIntensity(state, theStateChanges, stateHasBri, stateHasBriInc), lightId);
BrightnessDecode.calculateIntensity(state, theStateChanges, stateHasBri, stateHasBriInc), lightId);
if (anError != null) {
responseString = anError;
x = setCount;
x = aMultiUtil.getSetCount();
}
}
} 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 < setCount; x++) {
for (int x = 0; x < aMultiUtil.getSetCount(); x++) {
if (x > 0 || i > 0) {
try {
Thread.sleep(this.getTheDelay());
Thread.sleep(aMultiUtil.getTheDelay());
} catch (InterruptedException e) {
// ignore
}
}
if (callItems[i].getDelay() != null && callItems[i].getDelay() > 0)
this.setTheDelay(callItems[i].getDelay());
aMultiUtil.setTheDelay(callItems[i].getDelay());
else
this.setTheDelay(bridgeSettings.getButtonsleep());
aMultiUtil.setTheDelay(bridgeSettings.getButtonsleep());
try {
if (callItems[i].getItem().getAsString().contains("udp://")
|| callItems[i].getItem().getAsString().contains("tcp://")) {
@@ -1482,13 +1283,13 @@ public class HueMulator {
InetAddress IPAddress = InetAddress.getByName(hostAddr);
if (theUrlBody.startsWith("0x")) {
theUrlBody = replaceIntensityValue(theUrlBody,
calculateIntensity(state, theStateChanges, stateHasBri, stateHasBriInc),
theUrlBody = BrightnessDecode.calculateReplaceIntensityValue(theUrlBody,
state, theStateChanges, stateHasBri, stateHasBriInc,
true);
sendData = DatatypeConverter.parseHexBinary(theUrlBody.substring(2));
} else {
theUrlBody = replaceIntensityValue(theUrlBody,
calculateIntensity(state, theStateChanges, stateHasBri, stateHasBriInc),
theUrlBody = BrightnessDecode.calculateReplaceIntensityValue(theUrlBody,
state, theStateChanges, stateHasBri, stateHasBriInc,
false);
sendData = theUrlBody.getBytes();
}
@@ -1509,31 +1310,31 @@ public class HueMulator {
String intermediate = callItems[i].getItem().getAsString()
.substring(callItems[i].getItem().getAsString().indexOf("://") + 3);
String anError = doExecRequest(intermediate,
calculateIntensity(state, theStateChanges, stateHasBri, stateHasBriInc),
BrightnessDecode.calculateIntensity(state, theStateChanges, stateHasBri, stateHasBriInc),
lightId);
if (anError != null) {
responseString = anError;
x = setCount;
x = aMultiUtil.getSetCount();
}
} else {
log.debug("executing HUE api request to Http "
+ (device.getHttpVerb() == null ? "GET" : device.getHttpVerb()) + ": "
+ callItems[i].getItem().getAsString());
String anUrl = replaceIntensityValue(callItems[i].getItem().getAsString(),
calculateIntensity(state, theStateChanges, stateHasBri, stateHasBriInc), false);
String anUrl = BrightnessDecode.calculateReplaceIntensityValue(callItems[i].getItem().getAsString(),
state, theStateChanges, stateHasBri, stateHasBriInc, false);
String aBody;
if (stateHasBri || stateHasBriInc)
aBody = replaceIntensityValue(device.getContentBodyDim(),
calculateIntensity(state, theStateChanges, stateHasBri, stateHasBriInc),
aBody = BrightnessDecode.calculateReplaceIntensityValue(device.getContentBodyDim(),
state, theStateChanges, stateHasBri, stateHasBriInc,
false);
else if (state.isOn())
aBody = replaceIntensityValue(device.getContentBody(),
calculateIntensity(state, theStateChanges, stateHasBri, stateHasBriInc),
aBody = BrightnessDecode.calculateReplaceIntensityValue(device.getContentBody(),
state, theStateChanges, stateHasBri, stateHasBriInc,
false);
else
aBody = replaceIntensityValue(device.getContentBodyOff(),
calculateIntensity(state, theStateChanges, stateHasBri, stateHasBriInc),
aBody = BrightnessDecode.calculateReplaceIntensityValue(device.getContentBodyOff(),
state, theStateChanges, stateHasBri, stateHasBriInc,
false);
// make call
if (doHttpRequest(anUrl, device.getHttpVerb(), device.getContentType(), aBody,
@@ -1542,7 +1343,7 @@ public class HueMulator {
responseString = "[{\"error\":{\"type\": 6, \"address\": \"/lights/" + lightId
+ "\",\"description\": \"Error on calling url to change device state\", \"parameter\": \"/lights/"
+ lightId + "state\"}}]";
x = setCount;
x = aMultiUtil.getSetCount();
}
}
} catch (Exception e) {
@@ -1551,7 +1352,7 @@ public class HueMulator {
responseString = "[{\"error\":{\"type\": 6, \"address\": \"/lights/" + lightId
+ "\",\"description\": \"Error on calling out to device\", \"parameter\": \"/lights/"
+ lightId + "state\"}}]";
x = setCount;
x = aMultiUtil.getSetCount();
}
}
}
@@ -1559,7 +1360,7 @@ public class HueMulator {
if (responseString == null || !responseString.contains("[{\"error\":")) {
responseString = this.formatSuccessHueResponse(theStateChanges, body, lightId, state);
state.setBri(calculateIntensity(state, theStateChanges, stateHasBri, stateHasBriInc));
state.setBri(BrightnessDecode.calculateIntensity(state, theStateChanges, stateHasBri, stateHasBriInc));
device.setDeviceState(state);
}
return responseString;

View File

@@ -5,5 +5,5 @@ import com.bwssystems.HABridge.api.hue.DeviceState;
import com.bwssystems.HABridge.api.hue.StateChangeBody;
public interface HueMulatorHandler {
public String deviceHandler(CallItem anItem, MultiCommandUtil multiComand, String lightId, int iterationCount, DeviceState state, StateChangeBody theStateChanges, boolean stateHasBri, boolean stateHasBriInc);
public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int iterationCount, DeviceState state, StateChangeBody theStateChanges, boolean stateHasBri, boolean stateHasBriInc);
}

View File

@@ -3,6 +3,7 @@ package com.bwssystems.HABridge.hue;
public class MultiCommandUtil {
private Integer setCount;
private Integer theDelay;
private Integer delayDefault;
public Integer getSetCount() {
return setCount;
@@ -19,4 +20,12 @@ public class MultiCommandUtil {
public void setTheDelay(Integer theDelay) {
this.theDelay = theDelay;
}
public Integer getDelayDefault() {
return delayDefault;
}
public void setDelayDefault(Integer delayDefault) {
this.delayDefault = delayDefault;
}
}

View File

@@ -1,7 +1,6 @@
package com.bwssystems.NestBridge;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
@@ -9,6 +8,12 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bwssystems.HABridge.BridgeSettingsDescriptor;
import com.bwssystems.HABridge.DeviceMapTypes;
import com.bwssystems.HABridge.api.CallItem;
import com.bwssystems.HABridge.api.hue.DeviceState;
import com.bwssystems.HABridge.api.hue.StateChangeBody;
import com.bwssystems.HABridge.hue.BrightnessDecode;
import com.bwssystems.HABridge.hue.MultiCommandUtil;
import com.bwssystems.nest.controller.Home;
import com.bwssystems.nest.controller.Nest;
import com.bwssystems.nest.controller.NestSession;
@@ -16,34 +21,26 @@ import com.bwssystems.nest.controller.Thermostat;
import com.bwssystems.nest.protocol.error.LoginException;
import com.bwssystems.nest.protocol.status.WhereDetail;
import com.bwssystems.nest.protocol.status.WhereItem;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class NestHome {
public class NestHome implements com.bwssystems.HABridge.Home {
private static final Logger log = LoggerFactory.getLogger(NestHome.class);
private NestSession theSession;
private Nest theNest;
private ArrayList<NestItem> nestItems;
private Gson aGsonHandler;
private Boolean isFarenheit;
private Boolean validNest;
public NestHome(BridgeSettingsDescriptor bridgeSettings) {
theSession = null;
theNest = null;
nestItems = null;
if(!bridgeSettings.isValidNest()) {
log.debug("not a valid nest");
return;
}
try {
theSession = new NestSession(bridgeSettings.getNestuser(), bridgeSettings.getNestpwd());
theNest = new Nest(theSession);
} catch (LoginException e) {
log.error("Caught Login Exception, exiting....");
theSession = null;
}
super();
createHome(bridgeSettings);
}
public List<NestItem> getItems() {
if(theNest == null)
@Override
public Object getItems(String type) {
if(!validNest)
return null;
if(nestItems == null) {
@@ -94,11 +91,8 @@ public class NestHome {
return nestItems;
}
public Nest getTheNest() {
return theNest;
}
public void closeTheNest() {
@Override
public void closeHome() {
if(theSession != null) {
theNest.endNestSession();
theNest = null;
@@ -106,5 +100,87 @@ public class NestHome {
nestItems = null;
}
}
@Override
public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int iterationCount,
DeviceState state, StateChangeBody theStateChanges, boolean stateHasBri, boolean stateHasBriInc) {
String responseString = null;
log.debug("executing HUE api request to set away for nest " + anItem.getType() + ": " + anItem.getItem().toString());
if(!validNest) {
log.warn("Should not get here, no Nest available");
responseString = "[{\"error\":{\"type\": 6, \"address\": \"/lights/" + lightId
+ "\",\"description\": \"Should not get here, no Nest available\", \"parameter\": \"/lights/"
+ lightId + "state\"}}]";
} else if (anItem.getType() != null && anItem.getType().trim().equalsIgnoreCase(DeviceMapTypes.NEST_HOMEAWAY[DeviceMapTypes.typeIndex])) {
NestInstruction homeAway = aGsonHandler.fromJson(anItem.getItem().toString(), NestInstruction.class);
theNest.getHome(homeAway.getName()).setAway(homeAway.getAway());
} else if (anItem.getType() != null && anItem.getType().trim().equalsIgnoreCase(DeviceMapTypes.NEST_THERMO_SET[DeviceMapTypes.typeIndex])) {
NestInstruction thermoSetting = aGsonHandler.fromJson(anItem.getItem().toString(), NestInstruction.class);
if (thermoSetting.getControl().equalsIgnoreCase("temp")) {
if (stateHasBri) {
if (isFarenheit)
thermoSetting
.setTemp(
String.valueOf((Double
.parseDouble(BrightnessDecode.calculateReplaceIntensityValue(thermoSetting.getTemp(),
state, theStateChanges, stateHasBri, stateHasBriInc, false)) - 32.0) / 1.8));
else
thermoSetting
.setTemp(
String.valueOf(Double.parseDouble(BrightnessDecode.calculateReplaceIntensityValue(thermoSetting.getTemp(),
state, theStateChanges, stateHasBri, stateHasBriInc, false))));
log.debug("Setting thermostat: " + thermoSetting.getName() + " to "
+ thermoSetting.getTemp() + "C");
theNest.getThermostat(thermoSetting.getName())
.setTargetTemperature(Float.parseFloat(thermoSetting.getTemp()));
}
} else if (thermoSetting.getControl().contains("range")
|| thermoSetting.getControl().contains("heat")
|| thermoSetting.getControl().contains("cool")
|| thermoSetting.getControl().contains("off")) {
log.debug("Setting thermostat target type: " + thermoSetting.getName() + " to "
+ thermoSetting.getControl());
theNest.getThermostat(thermoSetting.getName()).setTargetType(thermoSetting.getControl());
} else if (thermoSetting.getControl().contains("fan")) {
log.debug("Setting thermostat fan mode: " + thermoSetting.getName() + " to "
+ thermoSetting.getControl().substring(4));
theNest.getThermostat(thermoSetting.getName())
.setFanMode(thermoSetting.getControl().substring(4));
} else {
log.warn("no valid Nest control info: " + thermoSetting.getControl());
responseString = "[{\"error\":{\"type\": 6, \"address\": \"/lights/" + lightId
+ "\",\"description\": \"no valid Nest control info\", \"parameter\": \"/lights/"
+ lightId + "state\"}}]";
}
}
log.info("device handler not implemented");
return responseString;
}
@Override
public com.bwssystems.HABridge.Home createHome(BridgeSettingsDescriptor bridgeSettings) {
theSession = null;
theNest = null;
nestItems = null;
validNest = bridgeSettings.isValidNest();
aGsonHandler = null;
if(!validNest) {
log.debug("not a valid nest");
} else {
aGsonHandler = new GsonBuilder().create();
isFarenheit = bridgeSettings.isFarenheit();
try {
theSession = new NestSession(bridgeSettings.getNestuser(), bridgeSettings.getNestpwd());
theNest = new Nest(theSession);
} catch (LoginException e) {
log.error("Caught Login Exception, setting Nest to invalid....");
validNest = false;
theSession = null;
}
}
return this;
}
}

View File

@@ -0,0 +1,41 @@
package com.bwssystems.exec;
import com.bwssystems.HABridge.BridgeSettingsDescriptor;
import com.bwssystems.HABridge.Home;
import com.bwssystems.HABridge.api.CallItem;
import com.bwssystems.HABridge.api.hue.DeviceState;
import com.bwssystems.HABridge.api.hue.StateChangeBody;
import com.bwssystems.HABridge.hue.MultiCommandUtil;
public class CommandHome implements Home {
public CommandHome() {
// TODO Auto-generated constructor stub
}
@Override
public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int iterationCount,
DeviceState state, StateChangeBody theStateChanges, boolean stateHasBri, boolean stateHasBriInc) {
// TODO Auto-generated method stub
return null;
}
@Override
public Home createHome(BridgeSettingsDescriptor bridgeSettings) {
// TODO Auto-generated method stub
return null;
}
@Override
public Object getItems(String type) {
// Not a resource
return null;
}
@Override
public void closeHome() {
// TODO Auto-generated method stub
}
}

View File

@@ -10,30 +10,24 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bwssystems.HABridge.BridgeSettingsDescriptor;
import com.bwssystems.HABridge.Home;
import com.bwssystems.HABridge.NamedIP;
import com.bwssystems.HABridge.api.CallItem;
import com.bwssystems.HABridge.api.hue.DeviceState;
import com.bwssystems.HABridge.api.hue.StateChangeBody;
import com.bwssystems.HABridge.hue.MultiCommandUtil;
public class HalHome {
public class HalHome implements Home {
private static final Logger log = LoggerFactory.getLogger(HalHome.class);
private Map<String, HalInfo> hals;
public HalHome(BridgeSettingsDescriptor bridgeSettings) {
super();
hals = new HashMap<String, HalInfo>();
if(!bridgeSettings.isValidHal())
return;
Iterator<NamedIP> theList = bridgeSettings.getHaladdress().getDevices().iterator();
while(theList.hasNext()) {
NamedIP aHal = theList.next();
try {
hals.put(aHal.getName(), new HalInfo(aHal, bridgeSettings.getHaltoken()));
} catch (Exception e) {
log.error("Cannot get hal client (" + aHal.getName() + ") setup, Exiting with message: " + e.getMessage(), e);
return;
}
}
createHome(bridgeSettings);
}
public List<HalDevice> getDevices() {
@Override
public Object getItems(String type) {
log.debug("consolidating devices for hues");
List<HalDevice> theResponse = null;
Iterator<String> keys = hals.keySet().iterator();
@@ -110,4 +104,35 @@ public class HalHome {
}
return true;
}
@Override
public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int iterationCount,
DeviceState state, StateChangeBody theStateChanges, boolean stateHasBri, boolean stateHasBriInc) {
log.info("device handler not implemented");
return null;
}
@Override
public Home createHome(BridgeSettingsDescriptor bridgeSettings) {
hals = new HashMap<String, HalInfo>();
if(!bridgeSettings.isValidHal())
return null;
Iterator<NamedIP> theList = bridgeSettings.getHaladdress().getDevices().iterator();
while(theList.hasNext()) {
NamedIP aHal = theList.next();
try {
hals.put(aHal.getName(), new HalInfo(aHal, bridgeSettings.getHaltoken()));
} catch (Exception e) {
log.error("Cannot get hal client (" + aHal.getName() + ") setup, Exiting with message: " + e.getMessage(), e);
return null;
}
}
return this;
}
@Override
public void closeHome() {
// noop
}
}

View File

@@ -11,53 +11,40 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bwssystems.HABridge.BridgeSettingsDescriptor;
import com.bwssystems.HABridge.DeviceMapTypes;
import com.bwssystems.HABridge.Home;
import com.bwssystems.HABridge.IpList;
import com.bwssystems.HABridge.NamedIP;
import com.bwssystems.HABridge.api.CallItem;
import com.bwssystems.HABridge.api.hue.DeviceState;
import com.bwssystems.HABridge.api.hue.StateChangeBody;
import com.bwssystems.HABridge.hue.MultiCommandUtil;
import net.whistlingfish.harmony.config.Activity;
import net.whistlingfish.harmony.config.Device;
public class HarmonyHome {
public class HarmonyHome implements Home {
private static final Logger log = LoggerFactory.getLogger(HarmonyHome.class);
private Map<String, HarmonyServer> hubs;
private Boolean isDevMode;
private Boolean validHarmony;
public HarmonyHome(BridgeSettingsDescriptor bridgeSettings) {
super();
isDevMode = Boolean.parseBoolean(System.getProperty("dev.mode", "false"));
hubs = new HashMap<String, HarmonyServer>();
if(!bridgeSettings.isValidHarmony() && !isDevMode)
return;
if(isDevMode) {
NamedIP devModeIp = new NamedIP();
devModeIp.setIp("10.10.10.10");
devModeIp.setName("devMode");
List<NamedIP> theList = new ArrayList<NamedIP>();
theList.add(devModeIp);
IpList thedevList = new IpList();
thedevList.setDevices(theList);
bridgeSettings.setHarmonyAddress(thedevList);
}
Iterator<NamedIP> theList = bridgeSettings.getHarmonyAddress().getDevices().iterator();
while(theList.hasNext()) {
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);
return;
}
}
createHome(bridgeSettings);
}
public void shutdownHarmonyHubs() {
if(isDevMode)
@Override
public void closeHome() {
if(isDevMode || hubs == null)
return;
Iterator<String> keys = hubs.keySet().iterator();
while(keys.hasNext()) {
String key = keys.next();
hubs.get(key).getMyHarmony().shutdown();
}
hubs = null;
}
public HarmonyHandler getHarmonyHandler(String aName) {
@@ -124,4 +111,55 @@ public class HarmonyHome {
}
return deviceList;
}
@Override
public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int iterationCount,
DeviceState state, StateChangeBody theStateChanges, boolean stateHasBri, boolean stateHasBriInc) {
// TODO Auto-generated method stub
log.info("device handler not implemented");
return null;
}
@Override
public Home createHome(BridgeSettingsDescriptor bridgeSettings) {
isDevMode = Boolean.parseBoolean(System.getProperty("dev.mode", "false"));
validHarmony = bridgeSettings.isValidHarmony();
if(!validHarmony && !isDevMode) {
log.debug("No valid Harmony config");
} else {
hubs = new HashMap<String, HarmonyServer>();
if(isDevMode) {
NamedIP devModeIp = new NamedIP();
devModeIp.setIp("10.10.10.10");
devModeIp.setName("devMode");
List<NamedIP> theList = new ArrayList<NamedIP>();
theList.add(devModeIp);
IpList thedevList = new IpList();
thedevList.setDevices(theList);
bridgeSettings.setHarmonyAddress(thedevList);
}
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;
}
}
}
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();
return null;
}
}

View File

@@ -16,7 +16,6 @@ import com.bwssystems.HABridge.api.CallItem;
import com.bwssystems.HABridge.api.hue.DeviceState;
import com.bwssystems.HABridge.api.hue.StateChangeBody;
import com.bwssystems.HABridge.hue.BrightnessDecode;
import com.bwssystems.HABridge.hue.HueMulatorHandler;
import com.bwssystems.HABridge.hue.MultiCommandUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
@@ -34,23 +33,27 @@ public class HassHome implements Home {
@Override
public Home createHome(BridgeSettingsDescriptor bridgeSettings) {
hassMap = null;
aGsonHandler = null;
validHass = bridgeSettings.isValidHass();
if(!validHass)
return null;
hassMap = new HashMap<String,HomeAssistant>();
Iterator<NamedIP> theList = bridgeSettings.getHassaddress().getDevices().iterator();
while(theList.hasNext()) {
NamedIP aHass = theList.next();
try {
hassMap.put(aHass.getName(), new HomeAssistant(aHass));
} catch (Exception e) {
log.error("Cannot get hass (" + aHass.getName() + ") setup, Exiting with message: " + e.getMessage(), e);
return null;
if(!validHass){
log.debug("not a valid hass");
} else {
hassMap = new HashMap<String,HomeAssistant>();
aGsonHandler =
new GsonBuilder()
.create();
Iterator<NamedIP> theList = bridgeSettings.getHassaddress().getDevices().iterator();
while(theList.hasNext() && validHass) {
NamedIP aHass = theList.next();
try {
hassMap.put(aHass.getName(), new HomeAssistant(aHass));
} catch (Exception e) {
log.error("Cannot get hass (" + aHass.getName() + ") setup, Exiting with message: " + e.getMessage(), e);
validHass = false;
}
}
}
aGsonHandler =
new GsonBuilder()
.create();
}
return this;
}
@@ -69,7 +72,8 @@ public class HassHome implements Home {
return aHomeAssistant;
}
public List<HassDevice> getDevices() {
@Override
public Object getItems(String type) {
log.debug("consolidating devices for hass");
if(!validHass)
return null;
@@ -105,10 +109,17 @@ public class HassHome implements Home {
}
@Override
public String deviceHandler(CallItem anItem, MultiCommandUtil multiComand, String lightId, int iterationCount, DeviceState state,
public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int iterationCount, DeviceState state,
StateChangeBody theStateChanges, boolean stateHasBri, boolean stateHasBriInc) {
String theReturn = null;
log.debug("executing HUE api request to send message to HomeAssistant: " + anItem.getItem().toString());
if(!validHass) {
log.warn("Should not get here, no HomeAssistant clients configured");
theReturn = "[{\"error\":{\"type\": 6, \"address\": \"/lights/" + lightId
+ "\",\"description\": \"Should not get here, no HomeAssistants configured\", \"parameter\": \"/lights/"
+ lightId + "state\"}}]";
} else {
HassCommand hassCommand = aGsonHandler.fromJson(anItem.getItem(), HassCommand.class);
hassCommand.setBri(BrightnessDecode.replaceIntensityValue(hassCommand.getBri(),
BrightnessDecode.calculateIntensity(state, theStateChanges, stateHasBri, stateHasBriInc), false));
@@ -119,24 +130,34 @@ public class HassHome implements Home {
+ "\",\"description\": \"Should not get here, no HiomeAssistant clients available\", \"parameter\": \"/lights/"
+ lightId + "state\"}}]";
} else {
for (int x = 0; x < multiComand.getSetCount(); x++) {
if (x > 0 || iterationCount > 0) {
try {
Thread.sleep(multiComand.getTheDelay());
} catch (InterruptedException e) {
// ignore
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());
log.debug("calling HomeAssistant: " + hassCommand.getHassName() + " - "
+ hassCommand.getEntityId() + " - " + hassCommand.getState() + " - " + hassCommand.getBri()
+ " - iteration: " + String.valueOf(iterationCount) + " - count: " + String.valueOf(x));
homeAssistant.callCommand(hassCommand);
}
if (anItem.getDelay() != null && anItem.getDelay() > 0)
multiComand.setTheDelay(anItem.getDelay());
// else
// this.setTheDelay(bridgeSettings.getButtonsleep());
log.debug("calling HomeAssistant: " + hassCommand.getHassName() + " - "
+ hassCommand.getEntityId() + " - " + hassCommand.getState() + " - " + hassCommand.getBri()
+ " - iteration: " + String.valueOf(iterationCount) + " - count: " + String.valueOf(x));
homeAssistant.callCommand(hassCommand);
}
}
}
return theReturn;
}
@Override
public void closeHome() {
Iterator<String> keys = hassMap.keySet().iterator();
while(keys.hasNext()) {
String key = keys.next();
hassMap.get(key).closeClient();
}
}
}

View File

@@ -193,4 +193,14 @@ public class HomeAssistant {
}
return theContent;
}
protected void closeClient() {
httpClient = null;
try {
httpclientSSL.close();
} catch (IOException e) {
// noop
}
httpclientSSL = null;
}
}

View File

@@ -0,0 +1,41 @@
package com.bwssystems.http;
import com.bwssystems.HABridge.BridgeSettingsDescriptor;
import com.bwssystems.HABridge.Home;
import com.bwssystems.HABridge.api.CallItem;
import com.bwssystems.HABridge.api.hue.DeviceState;
import com.bwssystems.HABridge.api.hue.StateChangeBody;
import com.bwssystems.HABridge.hue.MultiCommandUtil;
public class HTTPHome implements Home {
public HTTPHome() {
// TODO Auto-generated constructor stub
}
@Override
public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int iterationCount,
DeviceState state, StateChangeBody theStateChanges, boolean stateHasBri, boolean stateHasBriInc) {
// TODO Auto-generated method stub
return null;
}
@Override
public Home createHome(BridgeSettingsDescriptor bridgeSettings) {
// TODO Auto-generated method stub
return null;
}
@Override
public Object getItems(String type) {
// Not a resource
return null;
}
@Override
public void closeHome() {
// TODO Auto-generated method stub
}
}

View File

@@ -3,35 +3,34 @@ package com.bwssystems.hue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bwssystems.HABridge.BridgeSettingsDescriptor;
import com.bwssystems.HABridge.Home;
import com.bwssystems.HABridge.NamedIP;
import com.bwssystems.HABridge.api.CallItem;
import com.bwssystems.HABridge.api.hue.DeviceResponse;
import com.bwssystems.HABridge.api.hue.DeviceState;
import com.bwssystems.HABridge.api.hue.HueApiResponse;
import com.bwssystems.HABridge.api.hue.StateChangeBody;
import com.bwssystems.HABridge.hue.MultiCommandUtil;
public class HueHome {
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;
public HueHome(BridgeSettingsDescriptor bridgeSettings) {
hues = new HashMap<String, HueInfo>();
if(!bridgeSettings.isValidHue())
return;
Iterator<NamedIP> theList = bridgeSettings.getHueaddress().getDevices().iterator();
while(theList.hasNext()) {
NamedIP aHue = theList.next();
hues.put(aHue.getName(), new HueInfo(aHue, this));
}
theHUERegisteredUser = null;
super();
createHome(bridgeSettings);
}
public List<HueDevice> getDevices() {
@Override
public Object getItems(String type) {
log.debug("consolidating devices for hues");
Iterator<String> keys = hues.keySet().iterator();
ArrayList<HueDevice> deviceList = new ArrayList<HueDevice>();
@@ -70,4 +69,35 @@ public class HueHome {
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) {
// TODO Auto-generated method stub
log.info("device handler not implemented");
return null;
}
@Override
public Home createHome(BridgeSettingsDescriptor bridgeSettings) {
validHue = bridgeSettings.isValidHue();
if(!validHue) {
log.debug("No Hue Configuration");
} else {
hues = new HashMap<String, HueInfo>();
Iterator<NamedIP> theList = bridgeSettings.getHueaddress().getDevices().iterator();
while(theList.hasNext()) {
NamedIP aHue = theList.next();
hues.put(aHue.getName(), new HueInfo(aHue, this));
}
theHUERegisteredUser = null;
}
return this;
}
@Override
public void closeHome() {
// TODO Auto-generated method stub
}
}

View File

@@ -3,37 +3,31 @@ package com.bwssystems.mqtt;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bwssystems.HABridge.BridgeSettingsDescriptor;
import com.bwssystems.HABridge.Home;
import com.bwssystems.HABridge.NamedIP;
import com.bwssystems.HABridge.api.CallItem;
import com.bwssystems.HABridge.api.hue.DeviceState;
import com.bwssystems.HABridge.api.hue.StateChangeBody;
import com.bwssystems.HABridge.hue.MultiCommandUtil;
public class MQTTHome {
public class MQTTHome implements Home {
private static final Logger log = LoggerFactory.getLogger(MQTTHome.class);
private Map<String, MQTTHandler> handlers;
private Boolean validMqtt;
public MQTTHome(BridgeSettingsDescriptor bridgeSettings) {
super();
validMqtt = bridgeSettings.isValidMQTT();
if(!validMqtt)
return;
handlers = new HashMap<String, MQTTHandler>();
Iterator<NamedIP> theList = bridgeSettings.getMqttaddress().getDevices().iterator();
while(theList.hasNext()) {
NamedIP aClientConfig = theList.next();
MQTTHandler aHandler = new MQTTHandler(aClientConfig);
if(aHandler != null)
handlers.put(aClientConfig.getName(), aHandler);
}
createHome(bridgeSettings);
}
public void shutdownMQTTClients() {
@Override
public void closeHome() {
if(!validMqtt)
return;
log.debug("Shutting down MQTT handlers.");
@@ -61,7 +55,8 @@ public class MQTTHome {
return aHandler;
}
public List<MQTTBroker> getBrokers() {
@Override
public Object getItems(String type) {
if(!validMqtt)
return null;
Iterator<String> keys = handlers.keySet().iterator();
@@ -74,4 +69,30 @@ public class MQTTHome {
}
return deviceList;
}
@Override
public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int iterationCount,
DeviceState state, StateChangeBody theStateChanges, boolean stateHasBri, boolean stateHasBriInc) {
// TODO Auto-generated method stub
log.info("device handler not implemented");
return null;
}
@Override
public Home createHome(BridgeSettingsDescriptor bridgeSettings) {
validMqtt = bridgeSettings.isValidMQTT();
if(!validMqtt) {
log.debug("No MQTT configuration");
} else {
handlers = new HashMap<String, MQTTHandler>();
Iterator<NamedIP> theList = bridgeSettings.getMqttaddress().getDevices().iterator();
while(theList.hasNext()) {
NamedIP aClientConfig = theList.next();
MQTTHandler aHandler = new MQTTHandler(aClientConfig);
if(aHandler != null)
handlers.put(aClientConfig.getName(), aHandler);
}
}
return this;
}
}

View File

@@ -0,0 +1,41 @@
package com.bwssystems.tcp;
import com.bwssystems.HABridge.BridgeSettingsDescriptor;
import com.bwssystems.HABridge.Home;
import com.bwssystems.HABridge.api.CallItem;
import com.bwssystems.HABridge.api.hue.DeviceState;
import com.bwssystems.HABridge.api.hue.StateChangeBody;
import com.bwssystems.HABridge.hue.MultiCommandUtil;
public class TCPHome implements Home {
public TCPHome() {
// TODO Auto-generated constructor stub
}
@Override
public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int iterationCount,
DeviceState state, StateChangeBody theStateChanges, boolean stateHasBri, boolean stateHasBriInc) {
// TODO Auto-generated method stub
return null;
}
@Override
public Home createHome(BridgeSettingsDescriptor bridgeSettings) {
// TODO Auto-generated method stub
return null;
}
@Override
public Object getItems(String type) {
// Not a resource
return null;
}
@Override
public void closeHome() {
// TODO Auto-generated method stub
}
}

View File

@@ -0,0 +1,41 @@
package com.bwssystems.udp;
import com.bwssystems.HABridge.BridgeSettingsDescriptor;
import com.bwssystems.HABridge.Home;
import com.bwssystems.HABridge.api.CallItem;
import com.bwssystems.HABridge.api.hue.DeviceState;
import com.bwssystems.HABridge.api.hue.StateChangeBody;
import com.bwssystems.HABridge.hue.MultiCommandUtil;
public class UDPHome implements Home {
public UDPHome() {
// TODO Auto-generated constructor stub
}
@Override
public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int iterationCount,
DeviceState state, StateChangeBody theStateChanges, boolean stateHasBri, boolean stateHasBriInc) {
// TODO Auto-generated method stub
return null;
}
@Override
public Home createHome(BridgeSettingsDescriptor bridgeSettings) {
// TODO Auto-generated method stub
return null;
}
@Override
public Object getItems(String type) {
// Not a resource
return null;
}
@Override
public void closeHome() {
// TODO Auto-generated method stub
}
}

View File

@@ -10,24 +10,25 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bwssystems.HABridge.BridgeSettingsDescriptor;
import com.bwssystems.HABridge.DeviceMapTypes;
import com.bwssystems.HABridge.Home;
import com.bwssystems.HABridge.NamedIP;
import com.bwssystems.HABridge.api.CallItem;
import com.bwssystems.HABridge.api.hue.DeviceState;
import com.bwssystems.HABridge.api.hue.StateChangeBody;
import com.bwssystems.HABridge.hue.MultiCommandUtil;
import com.bwssystems.luupRequests.Device;
import com.bwssystems.luupRequests.Scene;
import com.bwssystems.luupRequests.Sdata;
public class VeraHome {
public class VeraHome implements Home {
private static final Logger log = LoggerFactory.getLogger(VeraHome.class);
private Map<String, VeraInfo> veras;
private Boolean validVera;
public VeraHome(BridgeSettingsDescriptor bridgeSettings) {
veras = new HashMap<String, VeraInfo>();
if(!bridgeSettings.isValidVera())
return;
Iterator<NamedIP> theList = bridgeSettings.getVeraAddress().getDevices().iterator();
while(theList.hasNext()) {
NamedIP aVera = theList.next();
veras.put(aVera.getName(), new VeraInfo(aVera));
}
super();
createHome(bridgeSettings);
}
public List<Device> getDevices() {
@@ -70,4 +71,44 @@ public class VeraHome {
}
return sceneList;
}
@Override
public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int iterationCount,
DeviceState state, StateChangeBody theStateChanges, boolean stateHasBri, boolean stateHasBriInc) {
// Not a device handler
return null;
}
@Override
public Object getItems(String type) {
if(validVera) {
if(type.equalsIgnoreCase(DeviceMapTypes.VERA_DEVICE[DeviceMapTypes.typeIndex]))
return getDevices();
if(type.equalsIgnoreCase(DeviceMapTypes.VERA_SCENE[DeviceMapTypes.typeIndex]))
return getScenes();
}
return null;
}
@Override
public Home createHome(BridgeSettingsDescriptor bridgeSettings) {
validVera = bridgeSettings.isValidVera();
if(!validVera) {
log.debug("No valid veras");
} else {
veras = new HashMap<String, VeraInfo>();
Iterator<NamedIP> theList = bridgeSettings.getVeraAddress().getDevices().iterator();
while(theList.hasNext()) {
NamedIP aVera = theList.next();
veras.put(aVera.getName(), new VeraInfo(aVera));
}
}
return this;
}
@Override
public void closeHome() {
// TODO Auto-generated method stub
}
}