Add Somfy devices

This commit is contained in:
Monica Goward
2017-02-04 18:29:50 +00:00
parent 1221df4c96
commit 805aac9fde
5 changed files with 505 additions and 0 deletions

View File

@@ -13,6 +13,7 @@ import com.bwssystems.HABridge.plugins.hass.HassHome;
import com.bwssystems.HABridge.plugins.http.HTTPHome; import com.bwssystems.HABridge.plugins.http.HTTPHome;
import com.bwssystems.HABridge.plugins.hue.HueHome; import com.bwssystems.HABridge.plugins.hue.HueHome;
import com.bwssystems.HABridge.plugins.mqtt.MQTTHome; import com.bwssystems.HABridge.plugins.mqtt.MQTTHome;
import com.bwssystems.HABridge.plugins.somfy.SomfyHome;
import com.bwssystems.HABridge.plugins.tcp.TCPHome; import com.bwssystems.HABridge.plugins.tcp.TCPHome;
import com.bwssystems.HABridge.plugins.udp.UDPHome; import com.bwssystems.HABridge.plugins.udp.UDPHome;
import com.bwssystems.HABridge.plugins.vera.VeraHome; import com.bwssystems.HABridge.plugins.vera.VeraHome;
@@ -86,6 +87,9 @@ public class HomeManager {
//setup the HomeAssistant configuration if available //setup the HomeAssistant configuration if available
aHome = new DomoticzHome(bridgeSettings); aHome = new DomoticzHome(bridgeSettings);
resourceList.put(DeviceMapTypes.DOMOTICZ_DEVICE[DeviceMapTypes.typeIndex], aHome); resourceList.put(DeviceMapTypes.DOMOTICZ_DEVICE[DeviceMapTypes.typeIndex], aHome);
//setup the Somfy configuration if available
aHome = new SomfyHome(bridgeSettings);
homeList.put(DeviceMapTypes.SOMFY_DEVICE[DeviceMapTypes.typeIndex], aHome);
} }
public Home findHome(String type) { public Home findHome(String type) {

View File

@@ -0,0 +1,67 @@
package com.bwssystems.HABridge.plugins.somfy;
public class SomfyDevice {
private String id;
private String room;
private String category;
private String somfyname;
private String name;
private String deviceUrl;
private String deviceType;
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setRoom(String room) {
this.room = room;
}
public String getRoom() {
return room;
}
public void setCategory(String category) {
this.category = category;
}
public String getCategory() {
return category;
}
public void setSomfyname(String somfyname) {
this.somfyname = somfyname;
}
public String getSomfyname() {
return somfyname;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setDeviceUrl(String deviceUrl) {
this.deviceUrl = deviceUrl;
}
public String getDeviceUrl() {
return deviceUrl;
}
public void setDeviceType(String deviceType) {
this.deviceType = deviceType;
}
public String getDeviceType() {
return deviceType;
}
}

View File

@@ -0,0 +1,103 @@
package com.bwssystems.HABridge.plugins.somfy;
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.dao.DeviceDescriptor;
import com.bwssystems.HABridge.hue.MultiCommandUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
public class SomfyHome implements Home {
private static final Logger log = LoggerFactory.getLogger(SomfyHome.class);
private Map<String, SomfyInfo> somfys;
private Boolean validSomfy;
public SomfyHome(BridgeSettingsDescriptor bridgeSettings) {
createHome(bridgeSettings);
}
public SomfyInfo getSomfyHandler(String somfyName) {
return somfys.get(somfyName);
}
public List<SomfyDevice> getDevices() {
log.debug("consolidating devices for somfy");
Iterator<String> keys = somfys.keySet().iterator();
ArrayList<SomfyDevice> deviceList = new ArrayList<>();
while(keys.hasNext()) {
String key = keys.next();
List<SomfyDevice> devices = somfys.get(key).getSomfyDevices();
deviceList.addAll(devices);
}
return deviceList;
}
@Override
public Object getItems(String type) {
if(validSomfy) {
if(type.equalsIgnoreCase(DeviceMapTypes.SOMFY_DEVICE[DeviceMapTypes.typeIndex]))
return getDevices();
}
return null;
}
@Override
public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int intensity, Integer targetBri, Integer targetBriInc, DeviceDescriptor device, String body) {
String responseString = null;
if (!validSomfy) {
log.warn("Should not get here, no somfy hub available");
responseString = "[{\"error\":{\"type\": 6, \"address\": \"/lights/" + lightId
+ "\",\"description\": \"Should not get here, no somfy hub available\", \"parameter\": \"/lights/"
+ lightId + "state\"}}]";
} 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().getAsString());
String jsonToPost = anItem.getItem().getAsString();
//RunActivity anActivity = new Gson().fromJson(url, RunActivity.class);
SomfyInfo somfyHandler = getSomfyHandler(device.getTargetDevice());
if(somfyHandler == null) {
log.warn("Should not get here, no Somfy configured");
responseString = "[{\"error\":{\"type\": 6, \"address\": \"/lights/" + lightId
+ "\",\"description\": \"Should not get here, no somfy configured\", \"parameter\": \"/lights/"
+ lightId + "state\"}}]";
} else {
try {
somfyHandler.execApply(jsonToPost);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
return responseString;
}
@Override
public Home createHome(BridgeSettingsDescriptor bridgeSettings) {
validSomfy = bridgeSettings.isValidSomfy();
log.info("Vera Home created." + (validSomfy ? "" : " No Veras configured."));
if(validSomfy) {
somfys = new HashMap<String, SomfyInfo>();
Iterator<NamedIP> theList = bridgeSettings.getSomfyAddress().getDevices().iterator();
while (theList.hasNext()) {
NamedIP aSomfy = theList.next();
somfys.put(aSomfy.getName(), new SomfyInfo(aSomfy, aSomfy.getName()));
}
}
return this;
}
@Override
public void closeHome() {
}
}

View File

@@ -0,0 +1,184 @@
package com.bwssystems.HABridge.plugins.somfy;
import com.bwssystems.HABridge.NamedIP;
import com.bwssystems.HABridge.plugins.somfy.jsonschema2pojo.getsetup.Device;
import com.bwssystems.HABridge.plugins.somfy.jsonschema2pojo.getsetup.GetSetup;
import com.google.gson.Gson;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import spark.utils.IOUtils;
import us.monoid.json.JSONException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;
public class SomfyInfo {
private static final Logger log = LoggerFactory.getLogger(SomfyInfo.class);
private final String somfyName;
private final NamedIP namedIP;
private HttpClient httpClient;
private static final String CONNECT_HOST = "https://www.tahomalink.com/";
private static final String BASE_URL = CONNECT_HOST + "enduser-mobile-web/externalAPI/";
private static final String BASE_URL_ENDUSER = CONNECT_HOST + "enduser-mobile-web/enduserAPI/";
public SomfyInfo(NamedIP namedIP, String somfyName) {
super();
this.somfyName = somfyName;
this.namedIP = namedIP;
}
private void initHttpClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
if(httpClient==null) {
httpClient = HttpClients.custom().
setHostnameVerifier(new AllowAllHostnameVerifier()).
setSslcontext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build()).build();
}
}
// This function executes the url against the vera
protected String doHttpGETRequest(String url) {
String theContent = null;
log.debug("calling GET on URL: " + url);
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = httpClient.execute(httpGet);
log.debug("GET on URL responded: " + response.getStatusLine().getStatusCode());
if(response.getStatusLine().getStatusCode() == 200){
theContent = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8")); //read content for data
EntityUtils.consume(response.getEntity()); //close out inputstream ignore content
}
} catch (IOException e) {
log.error("doHttpGETRequest: Error calling out to HA gateway: " + e.getMessage());
}
return theContent;
}
public List<SomfyDevice> getSomfyDevices() {
List<SomfyDevice> somfyDevices = new ArrayList<>();
try {
login(namedIP.getUsername(), namedIP.getPassword());
GetSetup setupData = getSetup();
for(Device device : setupData.getSetup().getDevices()) {
somfyDevices.add(mapDeviceToSomfyDevice(device));
}
} catch (Exception e) {
log.error("Could not get Somfy devices", e);
}
return somfyDevices;
}
public void login(String username, String password) throws Exception {
initHttpClient();
HttpPost httpPost = new HttpPost(BASE_URL + "json/login");
//HttpHost proxy = new HttpHost("127.0.0.1", 8888, "http");
RequestConfig config = RequestConfig.custom()
// .setProxy(proxy)
.build();
httpPost.setConfig(config);
httpPost.addHeader("User-Agent","mine");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("userId", username));
nvps.add(new BasicNameValuePair("userPassword", password));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
System.out.println("Making SOMFY http login call");
HttpResponse response = httpClient.execute(httpPost);
//try {
System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
//} finally {
// response.close();
//}
}
public GetSetup getSetup() throws IOException, JSONException {
HttpGet httpGet = new HttpGet(BASE_URL + "json/getSetup");
httpGet.addHeader("User-Agent","mine");
System.out.println("Making SOMFY http setup call");
HttpResponse response = httpClient.execute(httpGet);
//try {
System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
String json = IOUtils.toString(entity.getContent());
System.out.println(json);
GetSetup setupData = new Gson().fromJson(json, GetSetup.class);
return setupData;
//} finally {
// response.close();
//}
}
public void execApply(String jsonToPost) throws Exception {
login("house@edonica.com", "drawde123");
HttpPost httpPost = new HttpPost(BASE_URL_ENDUSER + "exec/apply");
//HttpHost proxy = new HttpHost("127.0.0.1", 8888, "http");
RequestConfig config = RequestConfig.custom()
// .setProxy(proxy)
.build();
httpPost.setConfig(config);
httpPost.addHeader("User-Agent", "mine");
httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
httpPost.setEntity(new StringEntity(jsonToPost, "UTF-8"));
System.out.println("Making SOMFY http exec call");
HttpResponse response = httpClient.execute(httpPost);
//try {
System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
//} finally {
//response.close();
//}
}
protected SomfyDevice mapDeviceToSomfyDevice(Device device) {
SomfyDevice somfyDevice = new SomfyDevice();
somfyDevice.setId(device.getOid());
somfyDevice.setCategory(device.getUiClass());
somfyDevice.setRoom("");
somfyDevice.setSomfyname(somfyName);
somfyDevice.setName(device.getLabel());
somfyDevice.setDeviceUrl(device.getDeviceURL());
somfyDevice.setDeviceType(device.getWidget());
return somfyDevice;
}
}

View File

@@ -0,0 +1,147 @@
<ul class="nav nav-pills" role="tablist">
<li role="presentation"><a href="#!/">Bridge Devices</a></li>
<li role="presentation"><a href="#!/system">Bridge Control</a></li>
<li role="presentation"><a href="#!/logs">Logs</a></li>
<li role="presentation"><a href="#!/veradevices">Vera
Devices</a></li>
<li role="presentation"><a href="#!/verascenes">Vera Scenes</a></li>
<li ng-if="bridge.showHarmony" role="presentation"><a
href="#!/harmonyactivities">Harmony Activities</a></li>
<li ng-if="bridge.showHarmony" role="presentation"><a
href="#!/harmonydevices">Harmony Devices</a></li>
<li ng-if="bridge.showNest" role="presentation"><a href="#!/nest">Nest</a></li>
<li ng-if="bridge.showHue" role="presentation"><a
href="#!/huedevices">Hue Devices</a></li>
<li ng-if="bridge.showHal" role="presentation"><a
href="#!/haldevices">HAL Devices</a></li>
<li ng-if="bridge.showMqtt" role="presentation"><a href="#!/mqttmessages">MQTT Messages</a></li>
<li ng-if="bridge.showHass" role="presentation"><a href="#!/hassdevices">HomeAssistant Devices</a></li>
<li ng-if="bridge.showDomoticz" role="presentation"><a href="#!/domoticzdevices">Domoticz Devices</a></li>
<li ng-if="bridge.showSomfy" role="presentation" class="active"><a href="#!/somfydevices">Somfy Devices</a></li>
<li role="presentation"><a href="#!/editdevice">Add/Edit</a></li>
</ul>
<div class="panel panel-default">
<div class="panel-heading">
<h2 class="panel-title">Somfy Device List
({{bridge.somfydevices.length}})</h2>
</div>
<div class="panel-body">
<p class="text-muted">For any Somfy 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 Somfy Devices' list below will show
what is already setup for your Somfy.</p>
<p>
Also, use this select menu for which type of dim control you would
like to be generated: <select name="device-somfy-dim-control"
id="device-somfy-dim-control" ng-model="device_somfy_dim_control">
<option value="">none</option>
<option value="${intensity.byte}">Pass-thru Value</option>
<option value="${intensity.percent}">Percentage</option>
<option value="${intensity.math(X*1)}">Custom Math</option>
</select>
</p>
<p>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 Somfy.</p>
</div>
<scrollable-table watch="bridge.somfydevices">
<table class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th>Row</th>
<th sortable-header col="name"><span><input type="checkbox" name="selectAll"
value="{{selectAll}}"
ng-checked="selectAll"
ng-click="toggleSelectAll()"> Name</span></th>
<th sortable-header col="id" comparator-fn="comparatorUniqueId">Id</th>
<th sortable-header col="category">Category</th>
<th sortable-header col="room">Room</th>
<th sortable-header col="somfyname">Somfy</th>
<th>Build Actions</th>
</tr>
</thead>
<tr
ng-repeat="somfydevice in bridge.somfydevices">
<td>{{$index+1}}</td>
<td><input type="checkbox" name="bulk.devices[]"
value="{{somfydevice.id}}"
ng-checked="bulk.devices.indexOf(somfydevice.id) > -1"
ng-click="toggleSelection(somfydevice.id)">
{{somfydevice.name}}</td>
<td>{{somfydevice.id}}</td>
<td>{{somfydevice.category}}</td>
<td>{{somfydevice.room}}</td>
<td>{{somfydevice.somfyname}}</td>
<td>
<button class="btn btn-success" type="submit"
ng-click="buildDeviceUrls(somfydevice, device_somfy_dim_control)">Build Item</button>
</td>
</tr>
</table>
</scrollable-table>
<div class="panel-footer">
<button class="btn btn-success" type="submit"
ng-click="bulkAddDevices(device_somfy_dim_control)">Bulk Add
({{bulk.devices.length}})</button>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h2 class="panel-title">
Already Configured Somfy Devices <a ng-click="toggleButtons()"><span
class={{imgButtonsUrl}} aria-hidden="true"></span></a></a>
</h2>
</div>
<div ng-if="buttonsVisible" class="panel-body">
<scrollable-table watch="bridge.devices">
<table class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th>Row</th>
<th sortable-header col="name">Name</th>
<th sortable-header col="id">Id</th>
<th sortable-header col="category">Category</th>
<th sortable-header col="room">Room</th>
<th sortable-header col="somfyname">Somfy</th>
<th>Actions</th>
</tr>
</thead>
<tr
ng-repeat="device in bridge.devices |configuredSomfyDevices">
<td>{{$index+1}}</td>
<td>{{device.name}}</td>
<td>{{device.id}}</td>
<td>{{device.category}}</td>
<td>{{device.room}}</td>
<td>{{device.somfyname}}</td>
<td>
<p>
<button class="btn btn-warning" type="submit"
ng-click="editDevice(device)">Edit</button>
<button class="btn btn-danger" type="submit"
ng-click="deleteDevice(device)">Delete</button>
</p>
</td>
</tr>
</table>
</scrollable-table>
</div>
</div>
<script type="text/ng-template" id="deleteMapandIdDialog">
<div class="ngdialog-message">
<h2>Device Map and Id?</h2>
<p>{{mapandid.mapType}} with {{mapandid.id}}</p>
<p>Are you Sure?</p>
</div>
<div class="ngdialog-buttons mt">
<button type="button" class="ngdialog-button ngdialog-button-error" ng-click="deleteMapandId(mapandid)">Delete</button>
</div>
</script>