From fe0b072b4ec03ad3b042da38df7ff9a137582ab5 Mon Sep 17 00:00:00 2001 From: BWS Systems Date: Tue, 4 Jun 2019 16:36:21 -0500 Subject: [PATCH] Add renumbering and HomeGenie Helper --- pom.xml | 2 +- .../bwssystems/HABridge/BridgeSettings.java | 6 - .../HABridge/BridgeSettingsDescriptor.java | 44 ++++ .../bwssystems/HABridge/DeviceMapTypes.java | 6 +- .../com/bwssystems/HABridge/HABridge.java | 25 +- .../com/bwssystems/HABridge/HomeManager.java | 13 +- .../java/com/bwssystems/HABridge/NamedIP.java | 51 +++- .../HABridge/dao/DeviceRepository.java | 227 +++++++++--------- .../devicemanagmeent/DeviceResource.java | 70 +++--- .../HABridge/plugins/NestBridge/NestHome.java | 2 +- .../plugins/broadlink/BroadlinkHome.java | 2 +- .../plugins/domoticz/DomoticzHome.java | 2 +- .../HABridge/plugins/exec/CommandHome.java | 9 +- .../HABridge/plugins/fhem/FHEMHome.java | 2 +- .../HABridge/plugins/hal/HalHome.java | 2 +- .../HABridge/plugins/harmony/HarmonyHome.java | 2 +- .../HABridge/plugins/hass/HassHome.java | 2 +- .../plugins/homegenie/HomeGenieCommand.java | 40 +++ .../homegenie/HomeGenieCommandDetail.java | 40 +++ .../plugins/homegenie/HomeGenieDevice.java | 29 +++ .../plugins/homegenie/HomeGenieHome.java | 190 +++++++++++++++ .../plugins/homegenie/HomeGenieInstance.java | 144 +++++++++++ .../HABridge/plugins/homegenie/Module.java | 99 ++++++++ .../HABridge/plugins/homegenie/Property.java | 76 ++++++ .../plugins/homewizard/HomeWizardHome.java | 4 +- .../HABridge/plugins/http/HTTPHome.java | 2 +- .../HABridge/plugins/hue/HueHome.java | 2 +- .../HABridge/plugins/lifx/LifxHome.java | 2 +- .../HABridge/plugins/moziot/MozIotHome.java | 2 +- .../HABridge/plugins/mqtt/MQTTHome.java | 2 +- .../HABridge/plugins/openhab/OpenHABHome.java | 2 +- .../HABridge/plugins/somfy/SomfyHome.java | 6 +- .../HABridge/plugins/somfy/SomfyInfo.java | 10 +- .../HABridge/plugins/tcp/TCPHome.java | 2 +- .../HABridge/plugins/udp/UDPHome.java | 2 +- src/main/resources/public/scripts/app.js | 14 ++ .../public/views/homegeniedevice.html | 140 +++++++++++ src/main/resources/public/views/system.html | 72 +++++- 38 files changed, 1147 insertions(+), 200 deletions(-) create mode 100644 src/main/java/com/bwssystems/HABridge/plugins/homegenie/HomeGenieCommand.java create mode 100644 src/main/java/com/bwssystems/HABridge/plugins/homegenie/HomeGenieCommandDetail.java create mode 100644 src/main/java/com/bwssystems/HABridge/plugins/homegenie/HomeGenieDevice.java create mode 100644 src/main/java/com/bwssystems/HABridge/plugins/homegenie/HomeGenieHome.java create mode 100644 src/main/java/com/bwssystems/HABridge/plugins/homegenie/HomeGenieInstance.java create mode 100644 src/main/java/com/bwssystems/HABridge/plugins/homegenie/Module.java create mode 100644 src/main/java/com/bwssystems/HABridge/plugins/homegenie/Property.java create mode 100644 src/main/resources/public/views/homegeniedevice.html diff --git a/pom.xml b/pom.xml index 0db4b1e..bcbaba2 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ com.bwssystems.HABridge ha-bridge - 5.2.next_b + 5.2.next_c jar HA Bridge diff --git a/src/main/java/com/bwssystems/HABridge/BridgeSettings.java b/src/main/java/com/bwssystems/HABridge/BridgeSettings.java index 2fe3326..076ddbb 100644 --- a/src/main/java/com/bwssystems/HABridge/BridgeSettings.java +++ b/src/main/java/com/bwssystems/HABridge/BridgeSettings.java @@ -77,7 +77,6 @@ public class BridgeSettings extends BackupHandler { } String serverPortOverride = System.getProperty("server.port"); String serverIpOverride = System.getProperty("server.ip"); - String upnpStrictOverride = System.getProperty("upnp.strict", "true"); if(configFileProperty != null) { log.info("reading from config file: " + configFileProperty); @@ -224,11 +223,6 @@ public class BridgeSettings extends BackupHandler { theBridgeSettings.setWebaddress(serverIpOverride); theBridgeSettings.setUpnpConfigAddress(serverIpOverride); } - - /* - if(upnpStrictOverride != null) - theBridgeSettings.setUpnpStrict(Boolean.parseBoolean(upnpStrictOverride)); - */ setupParams(Paths.get(theBridgeSettings.getConfigfile()), ".cfgbk", "habridge.config-"); diff --git a/src/main/java/com/bwssystems/HABridge/BridgeSettingsDescriptor.java b/src/main/java/com/bwssystems/HABridge/BridgeSettingsDescriptor.java index 41b608e..c43f5cb 100644 --- a/src/main/java/com/bwssystems/HABridge/BridgeSettingsDescriptor.java +++ b/src/main/java/com/bwssystems/HABridge/BridgeSettingsDescriptor.java @@ -111,6 +111,9 @@ public class BridgeSettingsDescriptor { @SerializedName("fhemaddress") @Expose private IpList fhemaddress; + @SerializedName("homegenieaddress") + @Expose + private IpList homegenieaddress; @SerializedName("lifxconfigured") @Expose private boolean lifxconfigured; @@ -123,6 +126,9 @@ public class BridgeSettingsDescriptor { @SerializedName("upnporiginal") @Expose private boolean upnporiginal; + @SerializedName("seedid") + @Expose + private Integer seedid; // @SerializedName("activeloggers") // @Expose // private List activeloggers; @@ -142,6 +148,7 @@ public class BridgeSettingsDescriptor { private boolean openhabconfigured; private boolean fhemconfigured; private boolean moziotconfigured; + private boolean homegenieconfigured; // Deprecated settings private String haltoken; @@ -167,6 +174,7 @@ public class BridgeSettingsDescriptor { this.lifxconfigured = false; this.openhabconfigured = false; this.moziotconfigured = false; + this.homegenieconfigured = false; this.farenheit = true; this.securityData = null; this.settingsChanged = false; @@ -179,6 +187,7 @@ public class BridgeSettingsDescriptor { this.broadlinkconfigured = false; this.tracestate = false; this.upnporiginal = false; + this.seedid = 100; } public String getUpnpConfigAddress() { @@ -791,4 +800,39 @@ public class BridgeSettingsDescriptor { public void setUpnporiginal(boolean upnporiginal) { this.upnporiginal = upnporiginal; } + + public Integer getSeedid() { + return seedid; + } + + public void setSeedid(Integer seedid) { + this.seedid = seedid; + } + + public IpList getHomegenieaddress() { + return homegenieaddress; + } + + public void setHomegenieaddress(IpList homegenieaddress) { + this.homegenieaddress = homegenieaddress; + } + + public boolean isHomegenieconfigured() { + return homegenieconfigured; + } + + public void setHomegenieconfigured(boolean homegenieconfigured) { + this.homegenieconfigured = homegenieconfigured; + } + public Boolean isValidHomeGenie() { + if (this.getHomegenieaddress() == null || this.getHomegenieaddress().getDevices().size() <= 0) + return false; + + List devicesList = this.getHomegenieaddress().getDevices(); + if (devicesList.get(0).getIp().contains(Configuration.DEFAULT_ADDRESS)) + return false; + + return true; + } + } diff --git a/src/main/java/com/bwssystems/HABridge/DeviceMapTypes.java b/src/main/java/com/bwssystems/HABridge/DeviceMapTypes.java index 9fc09ad..4664786 100644 --- a/src/main/java/com/bwssystems/HABridge/DeviceMapTypes.java +++ b/src/main/java/com/bwssystems/HABridge/DeviceMapTypes.java @@ -32,9 +32,10 @@ public class DeviceMapTypes { public final static String[] SOMFY_DEVICE = { "somfyDevice", "Somfy Device"}; public final static String[] LIFX_DEVICE = { "lifxDevice", "LIFX Device"}; public final static String[] OPENHAB_DEVICE = { "openhabDevice", "OpenHAB Device"}; - public final static String[] MOZIOT_DEVICE = { "moziotDevice", "Mozilla IOT Device"}; public final static String[] FHEM_DEVICE = { "fhemDevice", "FHEM Device"}; public final static String[] BROADLINK_DEVICE = { "broadlinkDevice", "Broadlink Device"}; + public final static String[] MOZIOT_DEVICE = { "moziotDevice", "Mozilla IOT Device"}; + public final static String[] HOMEGENIE_DEVICE = { "homegenieDevice", "HomeGenie Device"}; public final static int typeIndex = 0; public final static int displayIndex = 1; @@ -68,9 +69,10 @@ public class DeviceMapTypes { deviceMapTypes.add(FIBARO_SCENE); deviceMapTypes.add(SOMFY_DEVICE); deviceMapTypes.add(OPENHAB_DEVICE); - deviceMapTypes.add(MOZIOT_DEVICE); deviceMapTypes.add(FHEM_DEVICE); deviceMapTypes.add(BROADLINK_DEVICE); + deviceMapTypes.add(MOZIOT_DEVICE); + deviceMapTypes.add(HOMEGENIE_DEVICE); } public static int getTypeIndex() { return typeIndex; diff --git a/src/main/java/com/bwssystems/HABridge/HABridge.java b/src/main/java/com/bwssystems/HABridge/HABridge.java index 2e93760..5a937fb 100644 --- a/src/main/java/com/bwssystems/HABridge/HABridge.java +++ b/src/main/java/com/bwssystems/HABridge/HABridge.java @@ -56,7 +56,7 @@ public class HABridge { while(!bridgeSettings.getBridgeControl().isStop()) { bridgeSettings.buildSettings(); bridgeSettings.getBridgeSecurity().removeTestUsers(); - log.info("HA Bridge (v" + theVersion.getVersion() + ") initializing...."); + log.info("HA Bridge (v{}) initializing....", theVersion.getVersion() ); // sparkjava config directive to set ip address for the web server to listen on ipAddress(bridgeSettings.getBridgeSettingsDescriptor().getWebaddress()); // sparkjava config directive to set port for the web server to listen on @@ -94,10 +94,13 @@ public class HABridge { // wait for the sparkjava initialization of the rest api classes to be complete awaitInitialization(); - if(bridgeSettings.getBridgeSettingsDescriptor().isTraceupnp()) - log.info("Traceupnp: upnp config address: " + bridgeSettings.getBridgeSettingsDescriptor().getUpnpConfigAddress() + "-useIface:" + - bridgeSettings.getBridgeSettingsDescriptor().isUseupnpiface() + " on web server: " + - bridgeSettings.getBridgeSettingsDescriptor().getWebaddress() + ":" + bridgeSettings.getBridgeSettingsDescriptor().getServerPort()); + if(bridgeSettings.getBridgeSettingsDescriptor().isTraceupnp()) { + log.info("Traceupnp: upnp config address: {} -useIface: {} on web server: {}:{}", + bridgeSettings.getBridgeSettingsDescriptor().getUpnpConfigAddress(), + bridgeSettings.getBridgeSettingsDescriptor().isUseupnpiface(), + bridgeSettings.getBridgeSettingsDescriptor().getWebaddress(), + bridgeSettings.getBridgeSettingsDescriptor().getServerPort()); + } // setup the class to handle the upnp response rest api theSettingResponder = new UpnpSettingsResource(bridgeSettings); theSettingResponder.setupServer(); @@ -111,7 +114,7 @@ public class HABridge { theUpnpListener = null; } if(theUpnpListener != null && theUpnpListener.startListening()) - log.info("HA Bridge (v" + theVersion.getVersion() + ") reinitialization requessted...."); + log.info("HA Bridge (v{}) reinitialization requessted....", theVersion.getVersion()); else bridgeSettings.getBridgeControl().setStop(true); if(bridgeSettings.getBridgeSettingsDescriptor().isSettingsChanged()) @@ -126,7 +129,7 @@ public class HABridge { try { Thread.sleep(5000); } catch (InterruptedException e) { - log.error("Sleep error: " + e.getMessage()); + log.error("Sleep error: {}", e.getMessage()); } } } @@ -136,18 +139,18 @@ public class HABridge { try { HttpClientPool.shutdown(); } catch (InterruptedException e) { - log.warn("Error shutting down http pool: " + e.getMessage());; + log.warn("Error shutting down http pool: {}", e.getMessage());; } catch (IOException e) { - log.warn("Error shutting down http pool: " + e.getMessage());; + log.warn("Error shutting down http pool: {}", e.getMessage());; } thePool = null; - log.info("HA Bridge (v" + theVersion.getVersion() + ") exiting...."); + log.info("HA Bridge (v{}) exiting....", theVersion.getVersion()); System.exit(0); } private static void theExceptionHandler(Exception e, Integer thePort) { Logger log = LoggerFactory.getLogger(HABridge.class); - log.error("Could not start ha-bridge webservice on port [" + thePort + "] due to: " + e.getMessage()); + log.error("Could not start ha-bridge webservice on port [{}] due to: {}", thePort, e.getMessage()); System.exit(0); } } diff --git a/src/main/java/com/bwssystems/HABridge/HomeManager.java b/src/main/java/com/bwssystems/HABridge/HomeManager.java index a9e56fa..dc923c2 100644 --- a/src/main/java/com/bwssystems/HABridge/HomeManager.java +++ b/src/main/java/com/bwssystems/HABridge/HomeManager.java @@ -28,6 +28,7 @@ import com.bwssystems.HABridge.plugins.tcp.TCPHome; import com.bwssystems.HABridge.plugins.udp.UDPHome; import com.bwssystems.HABridge.plugins.vera.VeraHome; import com.bwssystems.HABridge.plugins.fibaro.FibaroHome; +import com.bwssystems.HABridge.plugins.homegenie.HomeGenieHome; import com.bwssystems.HABridge.util.UDPDatagramSender; public class HomeManager { @@ -121,10 +122,6 @@ public class HomeManager { aHome = new OpenHABHome(bridgeSettings); resourceList.put(DeviceMapTypes.OPENHAB_DEVICE[DeviceMapTypes.typeIndex], aHome); homeList.put(DeviceMapTypes.OPENHAB_DEVICE[DeviceMapTypes.typeIndex], aHome); - //setup the Mozilla IOT configuration if available - aHome = new MozIotHome(bridgeSettings); - resourceList.put(DeviceMapTypes.MOZIOT_DEVICE[DeviceMapTypes.typeIndex], aHome); - homeList.put(DeviceMapTypes.MOZIOT_DEVICE[DeviceMapTypes.typeIndex], aHome); //setup the FHEM configuration if available aHome = new FHEMHome(bridgeSettings); resourceList.put(DeviceMapTypes.FHEM_DEVICE[DeviceMapTypes.typeIndex], aHome); @@ -133,6 +130,14 @@ public class HomeManager { aHome = new BroadlinkHome(bridgeSettings); resourceList.put(DeviceMapTypes.BROADLINK_DEVICE[DeviceMapTypes.typeIndex], aHome); homeList.put(DeviceMapTypes.BROADLINK_DEVICE[DeviceMapTypes.typeIndex], aHome); + //setup the Mozilla IOT configuration if available + aHome = new MozIotHome(bridgeSettings); + resourceList.put(DeviceMapTypes.MOZIOT_DEVICE[DeviceMapTypes.typeIndex], aHome); + homeList.put(DeviceMapTypes.MOZIOT_DEVICE[DeviceMapTypes.typeIndex], aHome); + //setup the HomeGenie configuration if available + aHome = new HomeGenieHome(bridgeSettings); + resourceList.put(DeviceMapTypes.HOMEGENIE_DEVICE[DeviceMapTypes.typeIndex], aHome); + homeList.put(DeviceMapTypes.HOMEGENIE_DEVICE[DeviceMapTypes.typeIndex], aHome); } public Home findHome(String type) { diff --git a/src/main/java/com/bwssystems/HABridge/NamedIP.java b/src/main/java/com/bwssystems/HABridge/NamedIP.java index 507ee56..a5f8c89 100644 --- a/src/main/java/com/bwssystems/HABridge/NamedIP.java +++ b/src/main/java/com/bwssystems/HABridge/NamedIP.java @@ -11,53 +11,88 @@ public class NamedIP { private String password; private JsonObject extensions; private Boolean secure; - + private String httpPreamble; + public String getName() { return name; } + public void setName(String name) { this.name = name; } + public String getIp() { return ip; } + public void setIp(String ip) { this.ip = ip; } - public String getWebhook() { - return webhook; - } - public void setWebhook(final String webhook) { - this.webhook = webhook; - } - public String getPort() { + + public String getWebhook() { + return webhook; + } + + public void setWebhook(final String webhook) { + this.webhook = webhook; + } + + public String getPort() { return port; } + public void setPort(String port) { this.port = port; } + public String getUsername() { return username; } + public void setUsername(String username) { this.username = username; } + public String getPassword() { return password; } + public void setPassword(String password) { this.password = password; } + public Boolean getSecure() { return secure; } + public void setSecure(Boolean secure) { this.secure = secure; } + public JsonObject getExtensions() { return extensions; } + public void setExtensions(JsonObject extensions) { this.extensions = extensions; } + + public String getHttpPreamble() { + if (httpPreamble == null || httpPreamble.length() == 0) { + if (getSecure() != null && getSecure()) + httpPreamble = "https://"; + else + httpPreamble = "http://"; + + httpPreamble = httpPreamble + getIp(); + if (getPort() != null && getPort().length() > 0) { + httpPreamble = httpPreamble + ":" + getPort(); + } + } + return httpPreamble; + } + + public void setHttpPreamble(String httpPreamble) { + this.httpPreamble = httpPreamble; + } } diff --git a/src/main/java/com/bwssystems/HABridge/dao/DeviceRepository.java b/src/main/java/com/bwssystems/HABridge/dao/DeviceRepository.java index aafc0df..9755138 100644 --- a/src/main/java/com/bwssystems/HABridge/dao/DeviceRepository.java +++ b/src/main/java/com/bwssystems/HABridge/dao/DeviceRepository.java @@ -1,6 +1,5 @@ package com.bwssystems.HABridge.dao; - import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Files; @@ -38,48 +37,47 @@ import java.util.Arrays; */ public class DeviceRepository extends BackupHandler { private Map devices; - private Path repositoryPath; + private Path repositoryPath; private Gson gson; - private Integer nextId; - private Logger log = LoggerFactory.getLogger(DeviceRepository.class); - - public DeviceRepository(String deviceDb) { + private Integer nextId; + private Integer seedId; + private Logger log = LoggerFactory.getLogger(DeviceRepository.class); + + public DeviceRepository(String deviceDb, Integer seedid) { super(); - gson = - new GsonBuilder() - .excludeFieldsWithoutExposeAnnotation() - .create(); + gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); repositoryPath = null; repositoryPath = Paths.get(deviceDb); setupParams(repositoryPath, ".bk", "device.db-"); - nextId = 0; + nextId = seedid; + seedId = seedid; _loadRepository(repositoryPath); } - - public void loadRepository() { - if(repositoryPath != null) - _loadRepository(repositoryPath); - } - private void _loadRepository(Path aPath){ + + public void loadRepository() { + if (repositoryPath != null) + _loadRepository(repositoryPath); + } + + private void _loadRepository(Path aPath) { String jsonContent = repositoryReader(aPath); devices = new HashMap(); - - if(jsonContent != null) - { + + if (jsonContent != null) { DeviceDescriptor list[] = gson.fromJson(jsonContent, DeviceDescriptor[].class); - for(int i = 0; i < list.length; i++) { - if(list[i].getColorUrl() == null || list[i].getColorUrl().isEmpty()) + for (int i = 0; i < list.length; i++) { + if (list[i].getColorUrl() == null || list[i].getColorUrl().isEmpty()) list[i].setDeviceState(DeviceState.createDeviceState(false)); else list[i].setDeviceState(DeviceState.createDeviceState(true)); put(list[i].getId(), list[i]); - if(Integer.decode(list[i].getId()) > nextId) { + if (Integer.decode(list[i].getId()) > nextId) { nextId = Integer.decode(list[i].getId()); } } - } - } - + } + } + public List findAll() { List list = new ArrayList(devices.values()); return list; @@ -87,8 +85,8 @@ public class DeviceRepository extends BackupHandler { public List findActive() { List list = new ArrayList(); - for(DeviceDescriptor aDevice : new ArrayList(devices.values())) { - if(!aDevice.isInactive()) + for (DeviceDescriptor aDevice : new ArrayList(devices.values())) { + if (!aDevice.isInactive()) list.add(aDevice); } return list; @@ -105,12 +103,12 @@ public class DeviceRepository extends BackupHandler { DeviceDescriptor theDevice; String theRequesterAddress; - HashMap addressMap; + HashMap addressMap; while (anIterator.hasNext()) { theDevice = anIterator.next(); theRequesterAddress = theDevice.getRequesterAddress(); addressMap = new HashMap(); - if(theRequesterAddress != null) { + if (theRequesterAddress != null) { if (theRequesterAddress.contains(",")) { String[] theArray = theRequesterAddress.split(","); for (String v : theArray) { @@ -125,151 +123,164 @@ public class DeviceRepository extends BackupHandler { return theReturnList; } - public Map findAllByGroupWithState(String[] lightsInGroup, String anAddress, HueHome myHueHome, Gson aGsonBuilder) { + public Map findAllByGroupWithState(String[] lightsInGroup, String anAddress, + HueHome myHueHome, Gson aGsonBuilder) { return findAllByGroupWithState(lightsInGroup, anAddress, myHueHome, aGsonBuilder, false); } - public Map findAllByGroupWithState(String[] lightsInGroup, String anAddress, HueHome myHueHome, Gson aGsonBuilder, boolean ignoreAddress) { + public Map findAllByGroupWithState(String[] lightsInGroup, String anAddress, + HueHome myHueHome, Gson aGsonBuilder, boolean ignoreAddress) { Map deviceResponseMap = new HashMap(); Map lights = new HashMap(devices); lights.keySet().retainAll(Arrays.asList(lightsInGroup)); - for (DeviceDescriptor light : (ignoreAddress ? lights.values() : findAllByRequester(anAddress, lights.values()))) { + for (DeviceDescriptor light : (ignoreAddress ? lights.values() + : findAllByRequester(anAddress, lights.values()))) { DeviceResponse deviceResponse = null; - if(!light.isInactive()) { + if (!light.isInactive()) { if (light.containsType(DeviceMapTypes.HUE_DEVICE[DeviceMapTypes.typeIndex])) { CallItem[] callItems = null; try { - if(light.getOnUrl() != null) + if (light.getOnUrl() != null) callItems = aGsonBuilder.fromJson(light.getOnUrl(), CallItem[].class); - } catch(JsonSyntaxException e) { - log.warn("Could not decode Json for url items to get Hue state for device: " + light.getName()); + } catch (JsonSyntaxException e) { + log.warn("Could not decode Json for url items to get Hue state for device: {}", light.getName()); callItems = null; } for (int i = 0; callItems != null && i < callItems.length; i++) { - if((callItems[i].getType() != null && callItems[i].getType().equals(DeviceMapTypes.HUE_DEVICE[DeviceMapTypes.typeIndex])) || - (callItems[i].getItem() != null && callItems[i].getItem().getAsString() != null && callItems[i].getItem().getAsString().contains("hueName"))) { + if ((callItems[i].getType() != null + && callItems[i].getType().equals(DeviceMapTypes.HUE_DEVICE[DeviceMapTypes.typeIndex])) + || (callItems[i].getItem() != null && callItems[i].getItem().getAsString() != null + && callItems[i].getItem().getAsString().contains("hueName"))) { deviceResponse = myHueHome.getHueDeviceInfo(callItems[i], light); i = callItems.length; } } } - + if (deviceResponse == null) { deviceResponse = DeviceResponse.createResponse(light); } - deviceResponseMap.put(light.getId(), deviceResponse); + deviceResponseMap.put(light.getId(), deviceResponse); } } return (deviceResponseMap.size() == 0) ? null : deviceResponseMap; } public DeviceDescriptor findOne(String id) { - return devices.get(id); - } - + return devices.get(id); + } + private void put(String id, DeviceDescriptor aDescriptor) { - devices.put(id, aDescriptor); - } - + devices.put(id, aDescriptor); + } + public void save(DeviceDescriptor[] descriptors) { String theNames = ""; - for(int i = 0; i < descriptors.length; i++) { - if(descriptors[i].getId() != null && descriptors[i].getId().length() > 0) - devices.remove(descriptors[i].getId()); - else { - nextId++; - descriptors[i].setId(String.valueOf(nextId)); - } - if(descriptors[i].getUniqueid() == null || descriptors[i].getUniqueid().length() == 0) { - String hexValue = HexLibrary.encodeUsingBigIntegerToString(descriptors[i].getId()); + for (int i = 0; i < descriptors.length; i++) { + if (descriptors[i].getId() != null && descriptors[i].getId().length() > 0) + devices.remove(descriptors[i].getId()); + else { + descriptors[i].setId(String.valueOf(nextId)); + nextId++; + } + if (descriptors[i].getUniqueid() == null || descriptors[i].getUniqueid().length() == 0) { + String hexValue = HexLibrary.encodeUsingBigIntegerToString(descriptors[i].getId()); - descriptors[i].setUniqueid("00:17:88:5E:D3:" + hexValue + "-" + hexValue); - } - put(descriptors[i].getId(), descriptors[i]); - theNames = theNames + " " + descriptors[i].getName() + ", "; + descriptors[i].setUniqueid("00:17:88:5E:D3:" + hexValue + "-" + hexValue); + } + put(descriptors[i].getId(), descriptors[i]); + theNames = theNames + " " + descriptors[i].getName() + ", "; } - String jsonValue = gson.toJson(findAll()); - repositoryWriter(jsonValue, repositoryPath); - log.debug("Save device(s): " + theNames); - } - + String jsonValue = gson.toJson(findAll()); + repositoryWriter(jsonValue, repositoryPath); + log.debug("Save device(s): {}", theNames); + } + public void renumber() { List list = new ArrayList(devices.values()); Iterator deviceIterator = list.iterator(); - Map newdevices = new HashMap();; - nextId = 0; - log.debug("Renumber devices."); - while(deviceIterator.hasNext()) { - nextId++; - DeviceDescriptor theDevice = deviceIterator.next(); - theDevice.setId(String.valueOf(nextId)); - String hexValue = HexLibrary.encodeUsingBigIntegerToString(nextId.toString()); - - theDevice.setUniqueid("00:17:88:5E:D3:" + hexValue + "-" + hexValue); - newdevices.put(theDevice.getId(), theDevice); - } - devices = newdevices; - String jsonValue = gson.toJson(findAll()); - repositoryWriter(jsonValue, repositoryPath); - } - - public String delete(DeviceDescriptor aDescriptor) { - if (aDescriptor != null) { - devices.remove(aDescriptor.getId()); - JsonTransformer aRenderer = new JsonTransformer(); - String jsonValue = aRenderer.render(findAll()); - repositoryWriter(jsonValue, repositoryPath); - return "Device with id '" + aDescriptor.getId() + "' deleted"; - } else { - return "Device not found"; - } + Map newdevices = new HashMap(); + ; + nextId = seedId; + String hexValue; + Integer newValue; + DeviceDescriptor theDevice; + log.debug("Renumber devices with seed: {}", seedId); + while (deviceIterator.hasNext()) { + theDevice = deviceIterator.next(); + theDevice.setId(String.valueOf(nextId)); + newValue = nextId % 256; + if (newValue <= 0) + newValue = 1; + else if (newValue > 255) + newValue = 255; + hexValue = HexLibrary.encodeUsingBigIntegerToString(newValue.toString()); + + theDevice.setUniqueid("00:17:88:5E:D3:" + hexValue + "-" + hexValue); + newdevices.put(theDevice.getId(), theDevice); + nextId++; + } + devices = newdevices; + String jsonValue = gson.toJson(findAll()); + repositoryWriter(jsonValue, repositoryPath); + } + + public String delete(DeviceDescriptor aDescriptor) { + if (aDescriptor != null) { + devices.remove(aDescriptor.getId()); + JsonTransformer aRenderer = new JsonTransformer(); + String jsonValue = aRenderer.render(findAll()); + repositoryWriter(jsonValue, repositoryPath); + return "Device with id '" + aDescriptor.getId() + "' deleted"; + } else { + return "Device not found"; + } + + } - } - private void repositoryWriter(String content, Path filePath) { - if(Files.exists(filePath) && !Files.isWritable(filePath)){ - log.error("Error file is not writable: " + filePath); + if (Files.exists(filePath) && !Files.isWritable(filePath)) { + log.error("Error file is not writable: {}", filePath); return; } - - if(Files.notExists(filePath.getParent())) { + + if (Files.notExists(filePath.getParent())) { try { Files.createDirectories(filePath.getParent()); } catch (IOException e) { - log.error("Error creating the directory: " + filePath + " message: " + e.getMessage(), e); + log.error("Error creating the directory: {} message: {}", filePath, e.getMessage(), e); } } try { Path target = null; - if(Files.exists(filePath)) { + if (Files.exists(filePath)) { target = FileSystems.getDefault().getPath(filePath.getParent().toString(), "device.db.old"); Files.move(filePath, target); } Files.write(filePath, content.getBytes(), StandardOpenOption.CREATE); - if(target != null) + if (target != null) Files.delete(target); } catch (IOException e) { - log.error("Error writing the file: " + filePath + " message: " + e.getMessage(), e); + log.error("Error writing the file: {} message: {}", filePath, e.getMessage(), e); } } - + private String repositoryReader(Path filePath) { String content = null; - if(Files.notExists(filePath) || !Files.isReadable(filePath)){ - log.warn("Error reading the file: " + filePath + " - Does not exist or is not readable. continuing..."); + if (Files.notExists(filePath) || !Files.isReadable(filePath)) { + log.warn("Error reading the file: {} - Does not exist or is not readable. continuing...", filePath); return null; } - try { content = new String(Files.readAllBytes(filePath)); } catch (IOException e) { - log.error("Error reading the file: " + filePath + " message: " + e.getMessage(), e); + log.error("Error reading the file: {} message: {}", filePath, e.getMessage(), e); } - + return content; } } \ No newline at end of file diff --git a/src/main/java/com/bwssystems/HABridge/devicemanagmeent/DeviceResource.java b/src/main/java/com/bwssystems/HABridge/devicemanagmeent/DeviceResource.java index bad312f..692925b 100644 --- a/src/main/java/com/bwssystems/HABridge/devicemanagmeent/DeviceResource.java +++ b/src/main/java/com/bwssystems/HABridge/devicemanagmeent/DeviceResource.java @@ -44,13 +44,15 @@ public class DeviceResource { private BridgeSettings bridgeSettings; private Gson aGsonHandler; private static final Set supportedVerbs = new HashSet<>(Arrays.asList("get", "put", "post")); + private String errorMessage; public DeviceResource(BridgeSettings theSettings, HomeManager aHomeManager) { bridgeSettings = theSettings; - this.deviceRepository = new DeviceRepository(bridgeSettings.getBridgeSettingsDescriptor().getUpnpDeviceDb()); + this.deviceRepository = new DeviceRepository(bridgeSettings.getBridgeSettingsDescriptor().getUpnpDeviceDb(), bridgeSettings.getBridgeSettingsDescriptor().getSeedid()); this.groupRepository = new GroupRepository(bridgeSettings.getBridgeSettingsDescriptor().getUpnpGroupDb()); homeManager = aHomeManager; aGsonHandler = new GsonBuilder().create(); + errorMessage = null; setupEndpoints(); } @@ -83,7 +85,7 @@ public class DeviceResource { return ""; }); post(API_CONTEXT, "application/json", (request, response) -> { - log.debug("Create a Device(s) - request body: " + request.body()); + log.debug("Create a Device(s) - request body: {}", request.body()); DeviceDescriptor devices[]; if(request.body().substring(0,1).equalsIgnoreCase("[") == true) { devices = new Gson().fromJson(request.body(), DeviceDescriptor[].class); @@ -93,13 +95,12 @@ public class DeviceResource { } @SuppressWarnings("unused") CallItem[] callItems = null; - String errorMessage = null; for(int i = 0; i < devices.length; i++) { if(devices[i].getContentBody() != null ) { if (devices[i].getContentType() == null || devices[i].getHttpVerb() == null || !supportedVerbs.contains(devices[i].getHttpVerb().toLowerCase())) { response.status(HttpStatus.SC_BAD_REQUEST); errorMessage = "Bad http verb in create device(s) for name: " + devices[i].getName() + " with verb: " + devices[i].getHttpVerb(); - log.debug(errorMessage); + log.warn(errorMessage); return new ErrorMessage(errorMessage); } } @@ -109,7 +110,7 @@ public class DeviceResource { } catch(JsonSyntaxException e) { response.status(HttpStatus.SC_BAD_REQUEST); errorMessage = "Bad on URL JSON in create device(s) for name: " + devices[i].getName() + " with on URL: " + devices[i].getOnUrl(); - log.debug(errorMessage); + log.warn(errorMessage); return new ErrorMessage(errorMessage); } try { @@ -118,7 +119,7 @@ public class DeviceResource { } catch(JsonSyntaxException e) { response.status(HttpStatus.SC_BAD_REQUEST); errorMessage = "Bad dim URL JSON in create device(s) for name: " + devices[i].getName() + " with dim URL: " + devices[i].getDimUrl(); - log.debug(errorMessage); + log.warn(errorMessage); return new ErrorMessage(errorMessage); } try { @@ -127,7 +128,7 @@ public class DeviceResource { } catch(JsonSyntaxException e) { response.status(HttpStatus.SC_BAD_REQUEST); errorMessage = "Bad off URL JSON in create device(s) for name: " + devices[i].getName() + " with off URL: " + devices[i].getOffUrl(); - log.debug(errorMessage); + log.warn(errorMessage); return new ErrorMessage(errorMessage); } try { @@ -136,13 +137,13 @@ public class DeviceResource { } catch(JsonSyntaxException e) { response.status(HttpStatus.SC_BAD_REQUEST); errorMessage = "Bad color URL JSON in create device(s) for name: " + devices[i].getName() + " with color URL: " + devices[i].getColorUrl(); - log.debug(errorMessage); + log.warn(errorMessage); return new ErrorMessage(errorMessage); } } deviceRepository.save(devices); - log.debug("Created a Device(s): " + request.body()); + log.debug("Created a Device(s): {}", request.body()); response.header("Access-Control-Allow-Origin", request.headers("Origin")); response.status(HttpStatus.SC_CREATED); @@ -160,16 +161,17 @@ public class DeviceResource { return ""; }); put (API_CONTEXT + "/:id", "application/json", (request, response) -> { - log.debug("Edit a Device - request body: " + request.body()); + log.debug("Edit a Device - request body: {}", request.body()); DeviceDescriptor device = new Gson().fromJson(request.body(), DeviceDescriptor.class); if(deviceRepository.findOne(request.params(":id")) == null){ - log.debug("Could not save an edited device, Device Id not found: " + request.params(":id")); + errorMessage = "Could not save an edited device, Device Id not found: " + request.params(":id"); + log.warn(errorMessage); response.status(HttpStatus.SC_BAD_REQUEST); - return new ErrorMessage("Could not save an edited device, Device Id not found: " + request.params(":id") + " "); + return new ErrorMessage(errorMessage); } else { - log.debug("Saving an edited Device: " + device.getName()); + log.debug("Saving an edited Device: {}", device.getName()); if (device.getDeviceType() != null) device.setDeviceType(device.getDeviceType()); @@ -187,17 +189,19 @@ public class DeviceResource { log.debug("Get all devices"); JsonTransformer aRenderer = new JsonTransformer(); String theStream = aRenderer.render(deviceList); - log.debug("The Device List: " + theStream); + log.debug("The Device List: {}", theStream); response.status(HttpStatus.SC_OK); return deviceList; }, new JsonTransformer()); get (API_CONTEXT + "/:id", "application/json", (request, response) -> { - log.debug("Get a device"); + log.debug("Get a device: {}", request.params(":id")); DeviceDescriptor descriptor = deviceRepository.findOne(request.params(":id")); if(descriptor == null) { + errorMessage = "Could not find, id: " + request.params(":id"); + log.warn(errorMessage); response.status(HttpStatus.SC_NOT_FOUND); - return new ErrorMessage("Could not find, id: " + request.params(":id") + " "); + return new ErrorMessage(errorMessage); } else response.status(HttpStatus.SC_OK); @@ -206,11 +210,13 @@ public class DeviceResource { delete (API_CONTEXT + "/:id", "application/json", (request, response) -> { String anId = request.params(":id"); - log.debug("Delete a device: " + anId); + log.debug("Delete a device: {}", anId); DeviceDescriptor deleted = deviceRepository.findOne(anId); if(deleted == null) { + errorMessage = "Could not delete, id: " + anId + " not found. "; + log.warn(errorMessage); response.status(HttpStatus.SC_NOT_FOUND); - return new ErrorMessage("Could not delete, id: " + anId + " not found. "); + return new ErrorMessage(errorMessage); } else { @@ -321,12 +327,6 @@ public class DeviceResource { return homeManager.findResource(DeviceMapTypes.OPENHAB_DEVICE[DeviceMapTypes.typeIndex]).getItems(DeviceMapTypes.OPENHAB_DEVICE[DeviceMapTypes.typeIndex]); }, new JsonTransformer()); - get (API_CONTEXT + "/moziot/devices", "application/json", (request, response) -> { - log.debug("Get MOzilla IOT devices"); - response.status(HttpStatus.SC_OK); - return homeManager.findResource(DeviceMapTypes.MOZIOT_DEVICE[DeviceMapTypes.typeIndex]).getItems(DeviceMapTypes.MOZIOT_DEVICE[DeviceMapTypes.typeIndex]); - }, new JsonTransformer()); - get (API_CONTEXT + "/fhem/devices", "application/json", (request, response) -> { log.debug("Get FHEM devices"); response.status(HttpStatus.SC_OK); @@ -339,6 +339,18 @@ public class DeviceResource { return homeManager.findResource(DeviceMapTypes.BROADLINK_DEVICE[DeviceMapTypes.typeIndex]).getItems(DeviceMapTypes.BROADLINK_DEVICE[DeviceMapTypes.typeIndex]); }, new JsonTransformer()); + get (API_CONTEXT + "/moziot/devices", "application/json", (request, response) -> { + log.debug("Get Mozilla IOT devices"); + response.status(HttpStatus.SC_OK); + return homeManager.findResource(DeviceMapTypes.MOZIOT_DEVICE[DeviceMapTypes.typeIndex]).getItems(DeviceMapTypes.MOZIOT_DEVICE[DeviceMapTypes.typeIndex]); + }, new JsonTransformer()); + + get (API_CONTEXT + "/homegenie/devices", "application/json", (request, response) -> { + log.debug("Get HomeGenie devices"); + response.status(HttpStatus.SC_OK); + return homeManager.findResource(DeviceMapTypes.HOMEGENIE_DEVICE[DeviceMapTypes.typeIndex]).getItems(DeviceMapTypes.HOMEGENIE_DEVICE[DeviceMapTypes.typeIndex]); + }, new JsonTransformer()); + get (API_CONTEXT + "/map/types", "application/json", (request, response) -> { log.debug("Get map types"); return new DeviceMapTypes().getDeviceMapTypes(); @@ -346,7 +358,7 @@ public class DeviceResource { get (API_CONTEXT + "/refresh/:typeIndex", "application/json", (request, response) -> { String typeIndex = request.params(":typeIndex"); - log.debug("Refresh Home: " + typeIndex); + log.debug("Refresh Home: {}", typeIndex); response.status(HttpStatus.SC_OK); homeManager.findResource(typeIndex).refresh(); return null; @@ -368,7 +380,7 @@ public class DeviceResource { }, new JsonTransformer()); get (API_CONTEXT + "/backup/available", "application/json", (request, response) -> { - log.debug("Get backup filenames"); + log.debug("Get backup filenames."); response.status(HttpStatus.SC_OK); return deviceRepository.getBackups(); }, new JsonTransformer()); @@ -383,7 +395,7 @@ public class DeviceResource { return ""; }); put (API_CONTEXT + "/backup/create", "application/json", (request, response) -> { - log.debug("Create backup: " + request.body()); + log.debug("Create backup: {}", request.body()); BackupFilename aFilename = new Gson().fromJson(request.body(), BackupFilename.class); BackupFilename returnFilename = new BackupFilename(); returnFilename.setFilename(deviceRepository.backup(aFilename.getFilename())); @@ -400,7 +412,7 @@ public class DeviceResource { return ""; }); post (API_CONTEXT + "/backup/delete", "application/json", (request, response) -> { - log.debug("Delete backup: " + request.body()); + log.debug("Delete backup: {}", request.body()); BackupFilename aFilename = new Gson().fromJson(request.body(), BackupFilename.class); if(aFilename != null) deviceRepository.deleteBackup(aFilename.getFilename()); @@ -419,7 +431,7 @@ public class DeviceResource { return ""; }); post (API_CONTEXT + "/backup/restore", "application/json", (request, response) -> { - log.debug("Restore backup: " + request.body()); + log.debug("Restore backup: {}", request.body()); BackupFilename aFilename = new Gson().fromJson(request.body(), BackupFilename.class); if(aFilename != null) { deviceRepository.restoreBackup(aFilename.getFilename()); diff --git a/src/main/java/com/bwssystems/HABridge/plugins/NestBridge/NestHome.java b/src/main/java/com/bwssystems/HABridge/plugins/NestBridge/NestHome.java index 785f751..3abd438 100644 --- a/src/main/java/com/bwssystems/HABridge/plugins/NestBridge/NestHome.java +++ b/src/main/java/com/bwssystems/HABridge/plugins/NestBridge/NestHome.java @@ -125,7 +125,7 @@ public class NestHome implements com.bwssystems.HABridge.Home { if(anItem.getItem().isJsonObject()) homeAway = aGsonHandler.fromJson(anItem.getItem(), NestInstruction.class); else - homeAway = aGsonHandler.fromJson(anItem.getItem().getAsString(), NestInstruction.class); + homeAway = aGsonHandler.fromJson(anItem.getItem().getAsString().replaceAll("^\"|\"$", ""), 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 = null; diff --git a/src/main/java/com/bwssystems/HABridge/plugins/broadlink/BroadlinkHome.java b/src/main/java/com/bwssystems/HABridge/plugins/broadlink/BroadlinkHome.java index 76569a6..4c0b408 100644 --- a/src/main/java/com/bwssystems/HABridge/plugins/broadlink/BroadlinkHome.java +++ b/src/main/java/com/bwssystems/HABridge/plugins/broadlink/BroadlinkHome.java @@ -113,7 +113,7 @@ public class BroadlinkHome implements Home { if(anItem.getItem().isJsonObject()) broadlinkCommand = new Gson().fromJson(anItem.getItem(), BroadlinkEntry.class); else - broadlinkCommand = new Gson().fromJson(anItem.getItem().getAsString(), BroadlinkEntry.class); + broadlinkCommand = new Gson().fromJson(anItem.getItem().getAsString().replaceAll("^\"|\"$", ""), BroadlinkEntry.class); BLDevice theDevice = null; if(broadlinkMap != null && !broadlinkMap.isEmpty()) theDevice = broadlinkMap.get(broadlinkCommand.getId()); diff --git a/src/main/java/com/bwssystems/HABridge/plugins/domoticz/DomoticzHome.java b/src/main/java/com/bwssystems/HABridge/plugins/domoticz/DomoticzHome.java index 57f2afb..a4b7f41 100644 --- a/src/main/java/com/bwssystems/HABridge/plugins/domoticz/DomoticzHome.java +++ b/src/main/java/com/bwssystems/HABridge/plugins/domoticz/DomoticzHome.java @@ -88,7 +88,7 @@ public class DomoticzHome implements Home { Devices theDomoticzApiResponse = null; String responseString = null; - String theUrl = anItem.getItem().getAsString(); + String theUrl = anItem.getItem().getAsString().replaceAll("^\"|\"$", ""); if(theUrl != null && !theUrl.isEmpty () && (theUrl.startsWith("http://") || theUrl.startsWith("https://"))) { String intermediate = theUrl.substring(theUrl.indexOf("://") + 3); String hostPortion = intermediate.substring(0, intermediate.indexOf('/')); diff --git a/src/main/java/com/bwssystems/HABridge/plugins/exec/CommandHome.java b/src/main/java/com/bwssystems/HABridge/plugins/exec/CommandHome.java index 26340d1..c77e66e 100644 --- a/src/main/java/com/bwssystems/HABridge/plugins/exec/CommandHome.java +++ b/src/main/java/com/bwssystems/HABridge/plugins/exec/CommandHome.java @@ -31,13 +31,14 @@ public class CommandHome implements Home { @Override public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int intensity, Integer targetBri, Integer targetBriInc, ColorData colorData, DeviceDescriptor device, String body) { - log.debug("Exec Request called with url: " + anItem.getItem().getAsString() + " and exec Garden: " + (theSettings.getBridgeSecurity().getExecGarden() == null ? "not given" : theSettings.getBridgeSecurity().getExecGarden())); + String theItem = anItem.getItem().getAsString().replaceAll("^\"|\"$", ""); + log.debug("Exec Request called with url: {} and exec Garden: {}", theItem, (theSettings.getBridgeSecurity().getExecGarden() == null ? "not given" : theSettings.getBridgeSecurity().getExecGarden())); String responseString = null; String intermediate; - if (anItem.getItem().getAsString().contains("exec://")) - intermediate = anItem.getItem().getAsString().substring(anItem.getItem().getAsString().indexOf("://") + 3); + if (theItem.contains("exec://")) + intermediate = theItem.substring(anItem.getItem().getAsString().indexOf("://") + 3); else - intermediate = anItem.getItem().getAsString(); + intermediate = theItem; intermediate = BrightnessDecode.calculateReplaceIntensityValue(intermediate, intensity, targetBri, targetBriInc, false); if (colorData != null) { intermediate = ColorDecode.replaceColorData(intermediate, colorData, BrightnessDecode.calculateIntensity(intensity, targetBri, targetBriInc), false); diff --git a/src/main/java/com/bwssystems/HABridge/plugins/fhem/FHEMHome.java b/src/main/java/com/bwssystems/HABridge/plugins/fhem/FHEMHome.java index d2d514e..e464c23 100644 --- a/src/main/java/com/bwssystems/HABridge/plugins/fhem/FHEMHome.java +++ b/src/main/java/com/bwssystems/HABridge/plugins/fhem/FHEMHome.java @@ -58,7 +58,7 @@ public class FHEMHome implements Home { if(anItem.getItem().isJsonObject()) theCommand = new Gson().fromJson(anItem.getItem(), FHEMCommand.class); else - theCommand = new Gson().fromJson(anItem.getItem().getAsString(), FHEMCommand.class); + theCommand = new Gson().fromJson(anItem.getItem().getAsString().replaceAll("^\"|\"$", ""), FHEMCommand.class); } catch(Exception e) { log.warn("Cannot parse command to FHEM <<<" + theUrl + ">>>", e); responseString = new Gson().toJson(HueErrorResponse.createResponse("6", "/lights/" + lightId, diff --git a/src/main/java/com/bwssystems/HABridge/plugins/hal/HalHome.java b/src/main/java/com/bwssystems/HABridge/plugins/hal/HalHome.java index 4c5a091..77ae553 100644 --- a/src/main/java/com/bwssystems/HABridge/plugins/hal/HalHome.java +++ b/src/main/java/com/bwssystems/HABridge/plugins/hal/HalHome.java @@ -123,7 +123,7 @@ public class HalHome implements Home { Integer targetBri,Integer targetBriInc, ColorData colorData, DeviceDescriptor device, String body) { boolean halFound = false; String responseString = null; - String theUrl = anItem.getItem().getAsString(); + String theUrl = anItem.getItem().getAsString().replaceAll("^\"|\"$", ""); if(theUrl != null && !theUrl.isEmpty () && theUrl.contains("http")) { String intermediate = theUrl.substring(theUrl.indexOf("://") + 3); String hostPortion = intermediate.substring(0, intermediate.indexOf('/')); diff --git a/src/main/java/com/bwssystems/HABridge/plugins/harmony/HarmonyHome.java b/src/main/java/com/bwssystems/HABridge/plugins/harmony/HarmonyHome.java index 0ed07ce..8927bcc 100644 --- a/src/main/java/com/bwssystems/HABridge/plugins/harmony/HarmonyHome.java +++ b/src/main/java/com/bwssystems/HABridge/plugins/harmony/HarmonyHome.java @@ -194,7 +194,7 @@ public class HarmonyHome implements Home { if (anItem.getItem().isJsonObject()) anActivity = aGsonHandler.fromJson(anItem.getItem(), RunActivity.class); else - anActivity = aGsonHandler.fromJson(anItem.getItem().getAsString(), RunActivity.class); + anActivity = aGsonHandler.fromJson(anItem.getItem().getAsString().replaceAll("^\"|\"$", ""), RunActivity.class); if (anActivity.getHub() == null || anActivity.getHub().isEmpty()) anActivity.setHub(device.getTargetDevice()); HarmonyHandler myHarmony = getHarmonyHandler(anActivity.getHub()); diff --git a/src/main/java/com/bwssystems/HABridge/plugins/hass/HassHome.java b/src/main/java/com/bwssystems/HABridge/plugins/hass/HassHome.java index 292b32e..090f45d 100644 --- a/src/main/java/com/bwssystems/HABridge/plugins/hass/HassHome.java +++ b/src/main/java/com/bwssystems/HABridge/plugins/hass/HassHome.java @@ -138,7 +138,7 @@ public class HassHome implements Home { if(anItem.getItem().isJsonObject()) hassCommand = aGsonHandler.fromJson(anItem.getItem(), HassCommand.class); else - hassCommand = aGsonHandler.fromJson(anItem.getItem().getAsString(), HassCommand.class); + hassCommand = aGsonHandler.fromJson(anItem.getItem().getAsString().replaceAll("^\"|\"$", ""), HassCommand.class); hassCommand.setBri(BrightnessDecode.replaceIntensityValue(hassCommand.getBri(), BrightnessDecode.calculateIntensity(intensity, targetBri, targetBriInc), false)); HomeAssistant homeAssistant = getHomeAssistant(hassCommand.getHassName()); diff --git a/src/main/java/com/bwssystems/HABridge/plugins/homegenie/HomeGenieCommand.java b/src/main/java/com/bwssystems/HABridge/plugins/homegenie/HomeGenieCommand.java new file mode 100644 index 0000000..e6f6051 --- /dev/null +++ b/src/main/java/com/bwssystems/HABridge/plugins/homegenie/HomeGenieCommand.java @@ -0,0 +1,40 @@ +package com.bwssystems.HABridge.plugins.homegenie; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class HomeGenieCommand { + @SerializedName("moduleType") + @Expose + private String moduleType; + @SerializedName("deviceId") + @Expose + private String deviceId; + @SerializedName("command") + @Expose + private HomeGenieCommandDetail command; + + public String getModuleType() { + return moduleType; + } + + public void setModuleType(String moduleType) { + this.moduleType = moduleType; + } + + public String getDeviceId() { + return deviceId; + } + + public void setDeviceId(String deviceId) { + this.deviceId = deviceId; + } + + public HomeGenieCommandDetail getCommand() { + return command; + } + + public void setCommand(HomeGenieCommandDetail command) { + this.command = command; + } +} diff --git a/src/main/java/com/bwssystems/HABridge/plugins/homegenie/HomeGenieCommandDetail.java b/src/main/java/com/bwssystems/HABridge/plugins/homegenie/HomeGenieCommandDetail.java new file mode 100644 index 0000000..4e712ca --- /dev/null +++ b/src/main/java/com/bwssystems/HABridge/plugins/homegenie/HomeGenieCommandDetail.java @@ -0,0 +1,40 @@ +package com.bwssystems.HABridge.plugins.homegenie; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class HomeGenieCommandDetail { + @SerializedName("command") + @Expose + private String command; + @SerializedName("level") + @Expose + private String level; + @SerializedName("color") + @Expose + private String color; + + public String getLevel() { + return level; + } + + public void setLevel(String level) { + this.level = level; + } + + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + + public String getCommand() { + return command; + } + + public void setCommand(String command) { + this.command = command; + } +} \ No newline at end of file diff --git a/src/main/java/com/bwssystems/HABridge/plugins/homegenie/HomeGenieDevice.java b/src/main/java/com/bwssystems/HABridge/plugins/homegenie/HomeGenieDevice.java new file mode 100644 index 0000000..f19ccc3 --- /dev/null +++ b/src/main/java/com/bwssystems/HABridge/plugins/homegenie/HomeGenieDevice.java @@ -0,0 +1,29 @@ +package com.bwssystems.HABridge.plugins.homegenie; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class HomeGenieDevice { + @SerializedName("gatewayName") + @Expose + private String gatewayName; + @SerializedName("deviceDetail") + @Expose + private Module deviceDetail; + + public String getGatewayName() { + return gatewayName; + } + + public void setGatewayName(String gatewayName) { + this.gatewayName = gatewayName; + } + + public Module getDeviceDetail() { + return deviceDetail; + } + + public void setDeviceDetail(Module deviceDetail) { + this.deviceDetail = deviceDetail; + } +} \ No newline at end of file diff --git a/src/main/java/com/bwssystems/HABridge/plugins/homegenie/HomeGenieHome.java b/src/main/java/com/bwssystems/HABridge/plugins/homegenie/HomeGenieHome.java new file mode 100644 index 0000000..bbdaf8d --- /dev/null +++ b/src/main/java/com/bwssystems/HABridge/plugins/homegenie/HomeGenieHome.java @@ -0,0 +1,190 @@ +package com.bwssystems.HABridge.plugins.homegenie; + +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.BridgeSettings; +import com.bwssystems.HABridge.Home; +import com.bwssystems.HABridge.NamedIP; +import com.bwssystems.HABridge.api.CallItem; +import com.bwssystems.HABridge.api.hue.HueError; +import com.bwssystems.HABridge.api.hue.HueErrorResponse; +import com.bwssystems.HABridge.dao.DeviceDescriptor; +import com.bwssystems.HABridge.hue.BrightnessDecode; +import com.bwssystems.HABridge.hue.ColorData; +import com.bwssystems.HABridge.hue.ColorDecode; +import com.bwssystems.HABridge.hue.DeviceDataDecode; +import com.bwssystems.HABridge.hue.MultiCommandUtil; +import com.bwssystems.HABridge.hue.TimeDecode; +import com.bwssystems.HABridge.plugins.http.HTTPHandler; +import com.bwssystems.HABridge.plugins.http.HTTPHome; +import com.google.gson.Gson; + +public class HomeGenieHome implements Home { + private static final Logger log = LoggerFactory.getLogger(HomeGenieHome.class); + private Map homegenieMap; + private Boolean validHomeGenie; + private HTTPHandler httpClient; + private boolean closed; + + public HomeGenieHome(BridgeSettings bridgeSettings) { + super(); + closed = true; + createHome(bridgeSettings); + closed = false; + } + + @Override + public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int intensity, + Integer targetBri, Integer targetBriInc, ColorData colorData, DeviceDescriptor device, String body) { + + String theUrl = anItem.getItem().getAsString().replaceAll("^\"|\"$", ""); + String responseString = null; + + if (theUrl != null && !theUrl.isEmpty()) { + String anUrl = BrightnessDecode.calculateReplaceIntensityValue(theUrl, intensity, targetBri, targetBriInc, + false); + if (colorData != null) { + anUrl = ColorDecode.replaceColorData(anUrl, colorData, + BrightnessDecode.calculateIntensity(intensity, targetBri, targetBriInc), true); + } + anUrl = DeviceDataDecode.replaceDeviceData(anUrl, device); + anUrl = TimeDecode.replaceTimeValue(anUrl); + + anUrl = BrightnessDecode.calculateReplaceIntensityValue(anUrl, intensity, targetBri, targetBriInc, false); + if (colorData != null) { + anUrl = ColorDecode.replaceColorData(anUrl, colorData, + BrightnessDecode.calculateIntensity(intensity, targetBri, targetBriInc), false); + } + anUrl = DeviceDataDecode.replaceDeviceData(anUrl, device); + anUrl = TimeDecode.replaceTimeValue(anUrl); + + HomeGenieCommand theCommand = null; + try { + theCommand = new Gson().fromJson(anUrl, HomeGenieCommand.class); + } catch (Exception e) { + log.warn("Cannot parse command to HomeGenie <<<" + theUrl + ">>>", e); + responseString = new Gson().toJson(HueErrorResponse.createResponse("6", "/lights/" + lightId, + "Error on calling url to change device state", "/lights/" + lightId + "/state", null, null) + .getTheErrors(), HueError[].class); + return responseString; + } + + HomeGenieInstance theHandler = homegenieMap.get(device.getTargetDevice()); + if (theHandler != null) { + try { + boolean success = theHandler.callCommand(theCommand.getDeviceId(), theCommand.getModuleType(), theCommand.getCommand(), httpClient); + if (!success) { + log.warn("Comand had error to HomeGenie"); + responseString = new Gson().toJson(HueErrorResponse.createResponse("6", "/lights/" + lightId, + "Error on calling url to change device state", "/lights/" + lightId + "/state", null, + null).getTheErrors(), HueError[].class); + } + } catch (Exception e) { + log.warn("Cannot send comand to HomeGenie", e); + responseString = new Gson().toJson(HueErrorResponse.createResponse("6", "/lights/" + lightId, + "Error on calling url to change device state", "/lights/" + lightId + "/state", null, null) + .getTheErrors(), HueError[].class); + } + } else { + log.warn("HomeGenie Call could not complete, no address found: " + theUrl); + responseString = new Gson().toJson(HueErrorResponse.createResponse("6", "/lights/" + lightId, + "Error on calling url to change device state", "/lights/" + lightId + "/state", null, null) + .getTheErrors(), HueError[].class); + } + } else { + log.warn( + "HomeGenie Call to be presented as http(s)://(:)/payload, format of request unknown: " + + theUrl); + responseString = new Gson().toJson(HueErrorResponse.createResponse("6", "/lights/" + lightId, + "Error on calling url to change device state", "/lights/" + lightId + "/state", null, null) + .getTheErrors(), HueError[].class); + } + return responseString; + } + + @Override + public Object getItems(String type) { + + if (!validHomeGenie) + return null; + log.debug("consolidating devices for HomeGenie"); + List theResponse = null; + Iterator keys = homegenieMap.keySet().iterator(); + List deviceList = new ArrayList(); + while (keys.hasNext()) { + String key = keys.next(); + theResponse = homegenieMap.get(key).getDevices(httpClient); + if (theResponse != null) + addHomeGenieDevices(deviceList, theResponse, key); + else { + log.warn("Cannot get devices for HomeGenie with name: " + key + ", skipping this HomeGenie."); + continue; + } + } + return deviceList; + } + + private Boolean addHomeGenieDevices(List theDeviceList, List theSourceList, + String theKey) { + Iterator hgModules = theSourceList.iterator(); + while (hgModules.hasNext()) { + Module aModule = hgModules.next(); + HomeGenieDevice theDevice = new HomeGenieDevice(); + theDevice.setDeviceDetail(aModule); + theDevice.setGatewayName(theKey); + theDeviceList.add(theDevice); + } + return true; + } + + @Override + public Home createHome(BridgeSettings bridgeSettings) { + homegenieMap = null; + validHomeGenie = bridgeSettings.getBridgeSettingsDescriptor().isValidHomeGenie(); + log.info("HomeGenie Home created." + (validHomeGenie ? "" : " No HomeGenies configured.")); + if (validHomeGenie) { + homegenieMap = new HashMap(); + httpClient = HTTPHome.getHandler(); + Iterator theList = bridgeSettings.getBridgeSettingsDescriptor().getHomegenieaddress().getDevices() + .iterator(); + while (theList.hasNext() && validHomeGenie) { + NamedIP aHomeGenie = theList.next(); + try { + homegenieMap.put(aHomeGenie.getName(), new HomeGenieInstance(aHomeGenie, httpClient)); + } catch (Exception e) { + log.error("Cannot get HomeGenie (" + aHomeGenie.getName() + ") setup, Exiting with message: " + + e.getMessage(), e); + validHomeGenie = false; + } + } + } + return this; + } + + @Override + public void closeHome() { + log.debug("Closing Home."); + if (!closed && validHomeGenie) { + log.debug("Home is already closed...."); + return; + } + + if (httpClient != null) + httpClient.closeHandler(); + + homegenieMap = null; + closed = true; + } + + @Override + public void refresh() { + // noop + } +} diff --git a/src/main/java/com/bwssystems/HABridge/plugins/homegenie/HomeGenieInstance.java b/src/main/java/com/bwssystems/HABridge/plugins/homegenie/HomeGenieInstance.java new file mode 100644 index 0000000..b1ab499 --- /dev/null +++ b/src/main/java/com/bwssystems/HABridge/plugins/homegenie/HomeGenieInstance.java @@ -0,0 +1,144 @@ +package com.bwssystems.HABridge.plugins.homegenie; + +import java.util.ArrayList; +import java.util.List; + +import com.bwssystems.HABridge.NamedIP; +import com.bwssystems.HABridge.api.NameValue; +import com.bwssystems.HABridge.plugins.http.HTTPHandler; +import com.google.gson.Gson; + +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.client.methods.HttpPost; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class HomeGenieInstance { + private static final Logger log = LoggerFactory.getLogger(HomeGenieInstance.class); + private NamedIP homegenieIP; + private NameValue[] headers; + + public HomeGenieInstance(NamedIP theNamedIp, HTTPHandler httpClient) { + homegenieIP = theNamedIp; + headers = null; + // gatewayLogin(httpClient); + } + + public Boolean callCommand(String deviceId, String moduleType, HomeGenieCommandDetail commandData, HTTPHandler httpClient) { + log.debug("calling HomeGenie: {}:{}{}{}", homegenieIP.getIp(), homegenieIP.getPort(), moduleType, commandData.getCommand()); + String aUrl = null; + + headers = getAuthHeader(); + + aUrl = homegenieIP.getHttpPreamble() + "/api/" + moduleType + "/" + deviceId + "/" + commandData.getCommand(); + + String theLevel = commandData.getLevel(); + if(commandData.getCommand().contains("Level")) { + if(theLevel != null && theLevel.length() > 0) + aUrl = aUrl + "/" + theLevel; + else + aUrl = aUrl + "100"; + } + + String theData = httpClient.doHttpRequest(aUrl, HttpPut.METHOD_NAME, "application/json", null, headers); + log.debug("call Command return is: <<<{}>>>", theData); + if (!theData.contains("OK")) + return false; + return true; + } + + public List getDevices(HTTPHandler httpClient) { + log.debug("calling HomeGenie: " + homegenieIP.getIp() + ":" + homegenieIP.getPort()); + List deviceList = null; + Module[] hgModules; + String theUrl = null; + String theData; + + headers = getAuthHeader(); + + theUrl = theUrl + homegenieIP.getHttpPreamble() + "/api/HomeAutomation.HomeGenie/Config/Modules.List"; + + theData = httpClient.doHttpRequest(theUrl, HttpGet.METHOD_NAME, "application/json", null, headers); + if (theData != null) { + log.debug("GET HomeGenie Devices - data: " + theData); + try { + hgModules = new Gson().fromJson(theData, Module[].class); + if (hgModules != null && hgModules.length > 0) { + deviceList = new ArrayList(); + for (int i = 0; i < hgModules.length; i++) { + if(hgModules[i].isSwitch() || hgModules[i].isDimmer()) + deviceList.add(hgModules[i]); + } + } + } catch (Exception e) { + log.warn("Cannot get an devices for Homegenie {} Gson Parse Error.", homegenieIP.getName()); + } + } + return deviceList; + } + + private NameValue[] getAuthHeader() { + /* if (headers == null) { + headers = new NameValue[3]; + headers[0] = new NameValue(); + headers[0].setName("Authorization"); + headers[0].setValue("Bearer " + moziotToken.getJwt()); + headers[1] = new NameValue(); + headers[1].setName("Content-Type"); + headers[1].setValue("application/json"); + headers[2] = new NameValue(); + headers[2].setName("Accept"); + headers[2].setValue("application/json"); + } +*/ + return headers; + } + + private void gatewayLogin(HTTPHandler httpClient) { +/* String aUrl = null; + + if (homegenieIP.getSecure() != null && homegenieIP.getSecure()) + aUrl = "https://"; + else + aUrl = "http://"; + + headers = new NameValue[2]; + headers[0] = new NameValue(); + headers[0].setName("Content-Type"); + headers[0].setValue("application/json"); + headers[1] = new NameValue(); + headers[1].setName("Accept"); + headers[1].setValue("application/json"); + aUrl = aUrl + homegenieIP.getIp() + ":" + homegenieIP.getPort() + "/login"; + log.debug("gateway login URL: {}", aUrl); + String commandData = "{\"email\": \"" + homegenieIP.getUsername() + "\", \"password\":\"" + homegenieIP.getPassword() + + "\"}"; + log.debug("The login body: {}", commandData); + String theData = httpClient.doHttpRequest(aUrl, HttpPost.METHOD_NAME, "application/json", commandData, headers); + if (theData != null) { + log.debug("GET Mozilla login - data: {}", theData); + try { + moziotToken = new Gson().fromJson(theData, JWT.class); + } catch (Exception e) { + log.warn("Cannot get login for HomeGenie {} Gson Parse Error.", homegenieIP.getName()); + } + } else { + log.warn("Could not login {} error: <<<{}>>>", homegenieIP.getName(), theData); + } + + headers = null; +*/ + } + + public NamedIP getHomegenieIP() { + return homegenieIP; + } + + public void setHomegenieIP(NamedIP homegenieIP) { + this.homegenieIP = homegenieIP; + } + + protected void closeClient() { + } +} \ No newline at end of file diff --git a/src/main/java/com/bwssystems/HABridge/plugins/homegenie/Module.java b/src/main/java/com/bwssystems/HABridge/plugins/homegenie/Module.java new file mode 100644 index 0000000..77f9b5c --- /dev/null +++ b/src/main/java/com/bwssystems/HABridge/plugins/homegenie/Module.java @@ -0,0 +1,99 @@ + +package com.bwssystems.HABridge.plugins.homegenie; + +import java.util.List; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class Module { + + @SerializedName("Name") + @Expose + private String name; + @SerializedName("Description") + @Expose + private String description; + @SerializedName("DeviceType") + @Expose + private String deviceType; + @SerializedName("Domain") + @Expose + private String domain; + @SerializedName("Address") + @Expose + private String address; + @SerializedName("Properties") + @Expose + private List properties = null; + @SerializedName("RoutingNode") + @Expose + private String routingNode; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getDeviceType() { + return deviceType; + } + + public void setDeviceType(String deviceType) { + this.deviceType = deviceType; + } + + public String getDomain() { + return domain; + } + + public void setDomain(String domain) { + this.domain = domain; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public List getProperties() { + return properties; + } + + public void setProperties(List properties) { + this.properties = properties; + } + + public String getRoutingNode() { + return routingNode; + } + + public void setRoutingNode(String routingNode) { + this.routingNode = routingNode; + } + + public boolean isSwitch() { + return isPropertyType("Switch"); + } + + public boolean isDimmer() { + return isPropertyType("Dimmer"); + } + + private boolean isPropertyType(String theType) { + return false; + } +} diff --git a/src/main/java/com/bwssystems/HABridge/plugins/homegenie/Property.java b/src/main/java/com/bwssystems/HABridge/plugins/homegenie/Property.java new file mode 100644 index 0000000..38f00a3 --- /dev/null +++ b/src/main/java/com/bwssystems/HABridge/plugins/homegenie/Property.java @@ -0,0 +1,76 @@ + +package com.bwssystems.HABridge.plugins.homegenie; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class Property { + + @SerializedName("Name") + @Expose + private String name; + @SerializedName("Value") + @Expose + private String value; + @SerializedName("Description") + @Expose + private String description; + @SerializedName("FieldType") + @Expose + private String fieldType; + @SerializedName("UpdateTime") + @Expose + private String updateTime; + @SerializedName("NeedsUpdate") + @Expose + private Boolean needsUpdate; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getFieldType() { + return fieldType; + } + + public void setFieldType(String fieldType) { + this.fieldType = fieldType; + } + + public String getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(String updateTime) { + this.updateTime = updateTime; + } + + public Boolean getNeedsUpdate() { + return needsUpdate; + } + + public void setNeedsUpdate(Boolean needsUpdate) { + this.needsUpdate = needsUpdate; + } + +} diff --git a/src/main/java/com/bwssystems/HABridge/plugins/homewizard/HomeWizardHome.java b/src/main/java/com/bwssystems/HABridge/plugins/homewizard/HomeWizardHome.java index d13b9a8..b7c5210 100644 --- a/src/main/java/com/bwssystems/HABridge/plugins/homewizard/HomeWizardHome.java +++ b/src/main/java/com/bwssystems/HABridge/plugins/homewizard/HomeWizardHome.java @@ -54,8 +54,8 @@ public class HomeWizardHome implements Home { if (anItem.getType() != null && anItem.getType().trim().equalsIgnoreCase(DeviceMapTypes.HOMEWIZARD_DEVICE[DeviceMapTypes.typeIndex])) { - log.debug("Executing HUE api request to change activity to HomeWizard smart plug: " + anItem.getItem().toString()); - String jsonToPost = anItem.getItem().toString(); + String jsonToPost = anItem.getItem().getAsString().replaceAll("^\"|\"$", ""); + log.debug("Executing HUE api request to change activity to HomeWizard smart plug: {}", jsonToPost); HomeWizzardSmartPlugInfo homeWizzardHandler = getHomeWizzardHandler(device.getTargetDevice()); if(homeWizzardHandler == null) { diff --git a/src/main/java/com/bwssystems/HABridge/plugins/http/HTTPHome.java b/src/main/java/com/bwssystems/HABridge/plugins/http/HTTPHome.java index 0a70ee1..915b4d0 100644 --- a/src/main/java/com/bwssystems/HABridge/plugins/http/HTTPHome.java +++ b/src/main/java/com/bwssystems/HABridge/plugins/http/HTTPHome.java @@ -44,7 +44,7 @@ public class HTTPHome implements Home { Integer targetBri,Integer targetBriInc, ColorData colorData, DeviceDescriptor device, String body) { String responseString = null; - String theUrl = anItem.getItem().getAsString(); + String theUrl = anItem.getItem().getAsString().replaceAll("^\"|\"$", ""); if(theUrl != null && !theUrl.isEmpty () && (theUrl.startsWith("http://") || theUrl.startsWith("https://"))) { //Backwards Compatibility Items if(anItem.getHttpVerb() == null || anItem.getHttpVerb().isEmpty()) diff --git a/src/main/java/com/bwssystems/HABridge/plugins/hue/HueHome.java b/src/main/java/com/bwssystems/HABridge/plugins/hue/HueHome.java index 8a57eff..017a868 100644 --- a/src/main/java/com/bwssystems/HABridge/plugins/hue/HueHome.java +++ b/src/main/java/com/bwssystems/HABridge/plugins/hue/HueHome.java @@ -99,7 +99,7 @@ public class HueHome implements Home { if(anItem.getItem().isJsonObject()) deviceId = aGsonHandler.fromJson(anItem.getItem(), HueDeviceIdentifier.class); else - deviceId = aGsonHandler.fromJson(anItem.getItem().getAsString(), HueDeviceIdentifier.class); + deviceId = aGsonHandler.fromJson(anItem.getItem().getAsString().replaceAll("^\"|\"$", ""), HueDeviceIdentifier.class); if(deviceId.getHueName() == null || deviceId.getHueName().isEmpty()) deviceId.setHueName(device.getTargetDevice()); diff --git a/src/main/java/com/bwssystems/HABridge/plugins/lifx/LifxHome.java b/src/main/java/com/bwssystems/HABridge/plugins/lifx/LifxHome.java index 77dd83f..cd687fa 100644 --- a/src/main/java/com/bwssystems/HABridge/plugins/lifx/LifxHome.java +++ b/src/main/java/com/bwssystems/HABridge/plugins/lifx/LifxHome.java @@ -151,7 +151,7 @@ public class LifxHome implements Home { if(anItem.getItem().isJsonObject()) lifxCommand = aGsonHandler.fromJson(anItem.getItem(), LifxEntry.class); else - lifxCommand = aGsonHandler.fromJson(anItem.getItem().getAsString(), LifxEntry.class); + lifxCommand = aGsonHandler.fromJson(anItem.getItem().getAsString().replaceAll("^\"|\"$", ""), LifxEntry.class); LifxDevice theDevice = getLifxDevice(lifxCommand.getName()); if (theDevice == null) { log.warn("Should not get here, no LifxDevices available"); diff --git a/src/main/java/com/bwssystems/HABridge/plugins/moziot/MozIotHome.java b/src/main/java/com/bwssystems/HABridge/plugins/moziot/MozIotHome.java index 082e8a0..be22094 100644 --- a/src/main/java/com/bwssystems/HABridge/plugins/moziot/MozIotHome.java +++ b/src/main/java/com/bwssystems/HABridge/plugins/moziot/MozIotHome.java @@ -44,7 +44,7 @@ public class MozIotHome implements Home { public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int intensity, Integer targetBri, Integer targetBriInc, ColorData colorData, DeviceDescriptor device, String body) { - String theUrl = anItem.getItem().getAsString(); + String theUrl = anItem.getItem().getAsString().replaceAll("^\"|\"$", ""); String responseString = null; if (theUrl != null && !theUrl.isEmpty()) { diff --git a/src/main/java/com/bwssystems/HABridge/plugins/mqtt/MQTTHome.java b/src/main/java/com/bwssystems/HABridge/plugins/mqtt/MQTTHome.java index 46fba41..b4003c3 100644 --- a/src/main/java/com/bwssystems/HABridge/plugins/mqtt/MQTTHome.java +++ b/src/main/java/com/bwssystems/HABridge/plugins/mqtt/MQTTHome.java @@ -96,7 +96,7 @@ public class MQTTHome implements Home { mqttObject = aGsonHandler.toJson(anItem.getItem()); } else - mqttObject =anItem.getItem().getAsString(); + mqttObject = anItem.getItem().getAsString().replaceAll("^\"|\"$", ""); mqttObject = BrightnessDecode.calculateReplaceIntensityValue(mqttObject, intensity, targetBri, targetBriInc, false); mqttObject = DeviceDataDecode.replaceDeviceData(mqttObject, device); diff --git a/src/main/java/com/bwssystems/HABridge/plugins/openhab/OpenHABHome.java b/src/main/java/com/bwssystems/HABridge/plugins/openhab/OpenHABHome.java index be645f3..b588f6b 100644 --- a/src/main/java/com/bwssystems/HABridge/plugins/openhab/OpenHABHome.java +++ b/src/main/java/com/bwssystems/HABridge/plugins/openhab/OpenHABHome.java @@ -54,7 +54,7 @@ public class OpenHABHome implements Home { if(anItem.getItem().isJsonObject()) theCommand = new Gson().fromJson(anItem.getItem(), OpenHABCommand.class); else - theCommand = new Gson().fromJson(anItem.getItem().getAsString(), OpenHABCommand.class); + theCommand = new Gson().fromJson(anItem.getItem().getAsString().replaceAll("^\"|\"$", ""), OpenHABCommand.class); } catch(Exception e) { log.warn("Cannot parse command to OpenHAB <<<" + theUrl + ">>>", e); responseString = new Gson().toJson(HueErrorResponse.createResponse("6", "/lights/" + lightId, diff --git a/src/main/java/com/bwssystems/HABridge/plugins/somfy/SomfyHome.java b/src/main/java/com/bwssystems/HABridge/plugins/somfy/SomfyHome.java index 1ca4130..d786cef 100644 --- a/src/main/java/com/bwssystems/HABridge/plugins/somfy/SomfyHome.java +++ b/src/main/java/com/bwssystems/HABridge/plugins/somfy/SomfyHome.java @@ -76,8 +76,8 @@ public class SomfyHome implements Home { } else { if (anItem.getType() != null && anItem.getType().trim().equalsIgnoreCase(DeviceMapTypes.SOMFY_DEVICE[DeviceMapTypes.typeIndex])) { - log.debug("executing HUE api request to change activity to Somfy: " + anItem.getItem().toString()); - String jsonToPost = anItem.getItem().toString(); + String jsonToPost = anItem.getItem().getAsString().replaceAll("^\"|\"$", ""); + log.debug("executing HUE api request to change activity to Somfy: {}", jsonToPost); SomfyInfo somfyHandler = getSomfyHandler(device.getTargetDevice()); if(somfyHandler == null) { @@ -103,7 +103,7 @@ public class SomfyHome implements Home { @Override public Home createHome(BridgeSettings bridgeSettings) { validSomfy = bridgeSettings.getBridgeSettingsDescriptor().isValidSomfy(); - log.info("Somfy Home created." + (validSomfy ? "" : " No Somfys configured.")); + log.info("Somfy Home created. {}", (validSomfy ? "" : " No Somfys configured.")); if(validSomfy) { somfys = new HashMap<>(); Iterator theList = bridgeSettings.getBridgeSettingsDescriptor().getSomfyAddress().getDevices().iterator(); diff --git a/src/main/java/com/bwssystems/HABridge/plugins/somfy/SomfyInfo.java b/src/main/java/com/bwssystems/HABridge/plugins/somfy/SomfyInfo.java index be1d862..a2db134 100644 --- a/src/main/java/com/bwssystems/HABridge/plugins/somfy/SomfyInfo.java +++ b/src/main/java/com/bwssystems/HABridge/plugins/somfy/SomfyInfo.java @@ -74,8 +74,8 @@ public class SomfyInfo { ByteArrayOutputStream bos = new ByteArrayOutputStream(); urlEncodedFormEntity.writeTo(bos); String body = bos.toString(); - String response = httpClient.doHttpRequest(BASE_URL + "json/login",HttpPost.METHOD_NAME, "application/x-www-form-urlencoded", body,httpHeader); - log.debug("Somfy login response <<<" + response + ">>>"); + String response = httpClient.doHttpRequest(BASE_URL + "json/login", HttpPost.METHOD_NAME, "application/x-www-form-urlencoded", body,httpHeader); + log.debug("Somfy login response <<<{}>>>", response); } private NameValue[] getHttpHeaders() { @@ -89,16 +89,16 @@ public class SomfyInfo { NameValue[] httpHeader = getHttpHeaders(); log.info("Making SOMFY http setup call"); String response = httpClient.doHttpRequest(BASE_URL + "json/getSetup", HttpGet.METHOD_NAME, "", "", httpHeader ); - log.debug("Somfy getSetup response <<<" + response + ">>>"); + log.debug("Somfy getSetup response <<<{}>>>", response); GetSetup setupData = new Gson().fromJson(response, GetSetup.class); return setupData; } public void execApply(String jsonToPost) throws Exception { login(namedIP.getUsername(), namedIP.getPassword()); - log.info("Making SOMFY http exec call"); + log.info("Making SOMFY http exec call with json: {}", jsonToPost); String response = httpClient.doHttpRequest(BASE_URL_ENDUSER + "exec/apply", HttpPost.METHOD_NAME, "application/json;charset=UTF-8", jsonToPost, getHttpHeaders()); - log.debug("Somfy exec reply response <<<" + response + ">>>"); + log.debug("Somfy exec reply response <<<{}>>>", response); } diff --git a/src/main/java/com/bwssystems/HABridge/plugins/tcp/TCPHome.java b/src/main/java/com/bwssystems/HABridge/plugins/tcp/TCPHome.java index 21db858..d0e2f04 100644 --- a/src/main/java/com/bwssystems/HABridge/plugins/tcp/TCPHome.java +++ b/src/main/java/com/bwssystems/HABridge/plugins/tcp/TCPHome.java @@ -48,7 +48,7 @@ public class TCPHome implements Home { Integer targetBri,Integer targetBriInc, ColorData colorData, DeviceDescriptor device, String body) { Socket dataSendSocket = null; log.debug("executing HUE api request to TCP: " + anItem.getItem().getAsString()); - String theUrl = anItem.getItem().getAsString(); + String theUrl = anItem.getItem().getAsString().replaceAll("^\"|\"$", ""); if(theUrl != null && !theUrl.isEmpty () && theUrl.contains("tcp://")) { if(!theUrl.startsWith("{\"tcpDevice\"")) diff --git a/src/main/java/com/bwssystems/HABridge/plugins/udp/UDPHome.java b/src/main/java/com/bwssystems/HABridge/plugins/udp/UDPHome.java index 666521c..b59b8da 100644 --- a/src/main/java/com/bwssystems/HABridge/plugins/udp/UDPHome.java +++ b/src/main/java/com/bwssystems/HABridge/plugins/udp/UDPHome.java @@ -40,7 +40,7 @@ public class UDPHome implements Home { public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int intensity, Integer targetBri,Integer targetBriInc, ColorData colorData, DeviceDescriptor device, String body) { log.debug("executing HUE api request to UDP: " + anItem.getItem().getAsString()); - String theUrl = anItem.getItem().getAsString(); + String theUrl = anItem.getItem().getAsString().replaceAll("^\"|\"$", ""); if(theUrl != null && !theUrl.isEmpty () && theUrl.startsWith("udp://")) { String intermediate = theUrl.substring(theUrl.indexOf("://") + 3); String hostPortion = intermediate.substring(0, intermediate.indexOf('/')); diff --git a/src/main/resources/public/scripts/app.js b/src/main/resources/public/scripts/app.js index de16a17..725cf2a 100644 --- a/src/main/resources/public/scripts/app.js +++ b/src/main/resources/public/scripts/app.js @@ -5113,6 +5113,20 @@ app.filter('configuredBroadlinkItems', function (bridgeService) { }; }); +app.filter('configuredMozIotItems', function (bridgeService) { + return function (input) { + var out = []; + if (input === undefined || input === null || input.length === undefined) + return out; + for (var i = 0; i < input.length; i++) { + if (bridgeService.deviceContainsType(input[i], "moziot")) { + out.push(input[i]); + } + } + return out; + }; +}); + app.filter('filterDevicesByRequester', function () { return function (input, search, mustContain, deviceType) { var out = []; diff --git a/src/main/resources/public/views/homegeniedevice.html b/src/main/resources/public/views/homegeniedevice.html new file mode 100644 index 0000000..987c0a8 --- /dev/null +++ b/src/main/resources/public/views/homegeniedevice.html @@ -0,0 +1,140 @@ + + +
+
+

HomeGenie show Device List + ({{bridge.homegeniedevices.length}})

+
+
+

For any HomeGenie Device, use the build action buttons + to generate the item addition information into the ha-bridge device and this will put you into the edit + screen. Then + you can modify the name to anything you want that will be the keyword + for the Echo or Google Home. Also, you can go back to any helper tab and click a build + action button to add another item for a multi-command. After you are + done in the edit tab, click the 'Add Bridge Device' to finish that selection + setup. The 'Already Configured HomeGenie Devices' list below will show what + is already setup for your HomeGenie.

+

+ Also, use this select menu for which type of dim control you would + like to be generated: +

+

Use the check boxes by the names to use the bulk addition + feature. Select your items and dim control type if wanted, then click + bulk add below. Your items will be added with on and off or dim and + off if selected with the name of the device from the HomeGenie.

+ + + + + + + + + + + + + + + + + + +
Row + NameTypeHomeGenieBuild Actions
{{$index+1}} + {{homegeniedevice.deviceDetail.Name}}{{homegeniedevice.deviceDetail.DeviceType}}{{homegeniedevice.gatewayName}} + +
+
+ +
+
+
+
+

+ Already Configured OpenHAB Devices +

+
+
+ + + + + + + + + + + + + + + + + + + + + +
RowNameCategoryHomeGenieMap IdActions
{{$index+1}}{{device.name}}{{device.deviceType}}{{device.targetDevice}}{{device.mapId}} +

+ + +

+
+
+
+
+ \ No newline at end of file diff --git a/src/main/resources/public/views/system.html b/src/main/resources/public/views/system.html index fd4d5f7..5a3b5ec 100644 --- a/src/main/resources/public/views/system.html +++ b/src/main/resources/public/views/system.html @@ -21,6 +21,7 @@
  • FHEM Devices
  • Mozilla IOT Devices
  • Broadlink Devices
  • +
  • HomeGenie Devices
  • Add/Edit
  • @@ -763,7 +764,7 @@ placeholder="192.168.1.3"> + placeholder="4443"> @@ -785,7 +786,7 @@ placeholder="192.168.1.3"> + placeholder="4443"> @@ -800,6 +801,67 @@ + + HomeGenie Names and IP Addresses + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameIPPort (opt)Username (opt)Password (opt)Use SSLManage
    + Nest @@ -884,6 +946,12 @@ ng-model="bridge.settings.upnpsenddelay" min="100" max="15000"> + + + +
    ID Seed (start numbering from this value)
    My Echo URL