Skip to content

Commit

Permalink
Merge pull request #2 from Bounz/light-dim-fix
Browse files Browse the repository at this point in the history
Light dim fix
  • Loading branch information
Bounz authored Feb 1, 2019
2 parents 29a2eb0 + 70b51ed commit 7b668e4
Show file tree
Hide file tree
Showing 61 changed files with 43 additions and 83,749 deletions.
78 changes: 35 additions & 43 deletions EchoBridge/Controllers/LightsController.cs
Original file line number Diff line number Diff line change
@@ -1,23 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Net.Http;
using System.Net;
using NLog;
using System.Web.Http.Cors;

namespace HGEchoBridge
{
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class LightsController : ApiController
{
private static string INTENSITY_PERCENT = "${intensity.percent}";
private static string INTENSITY_BYTE = "${intensity.byte}";
private static Logger logger = LogManager.GetCurrentClassLogger();


// GET api/{userId}/lights
public HttpResponseMessage Get()
{
Expand Down Expand Up @@ -59,96 +54,93 @@ public HttpResponseMessage Get(string id)
logger.Info("LightsController GET: Returned DeviceResponse for device named[{0}], with id [{1}]", device.name, device.id);
DeviceResponse response = DeviceResponse.createResponse(device.name, device.id);
return Request.CreateResponse(System.Net.HttpStatusCode.OK, response);


}


// PUT api/{userId}/lights/5/
public HttpResponseMessage Put(string id)
{
logger.Info("LightsController PUT called. Updating light with id{0}]...", id);
Device device = Globals.DeviceList.FindById(id);
var device = Globals.DeviceList.FindById(id);
if (device == null)
{
logger.Warn("LightsController PUT: Could not locate a light with id [{0}].", id);
return new HttpResponseMessage()
return new HttpResponseMessage
{
StatusCode = System.Net.HttpStatusCode.NotFound,
StatusCode = HttpStatusCode.NotFound,
ReasonPhrase = "Could locate a device with that id."
};
}

//the echo PUTs json data but does so in application/x-www-form-urlencoded instead of JSON
//so we have to read the data from the body then convert it properly from a JSON object.
HttpContent requestContent = Request.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;
DeviceState deviceState=Newtonsoft.Json.JsonConvert.DeserializeObject<DeviceState>(jsonContent);


string url = deviceState.on ? device.onUrl: device.offUrl;
url = replaceIntensityValue(url, deviceState);

string body = replaceIntensityValue(device.contentBody, deviceState);
var requestContent = Request.Content;
var jsonContent = requestContent.ReadAsStringAsync().Result;
logger.Info($"Alexa request: {jsonContent}");
var deviceState=Newtonsoft.Json.JsonConvert.DeserializeObject<DeviceState>(jsonContent);

var url = string.IsNullOrEmpty(device.DimUrl)
? deviceState.on
? device.onUrl
: device.offUrl
: device.DimUrl;

url = ReplaceIntensityValue(url, deviceState);
var body = ReplaceIntensityValue(device.contentBody, deviceState);

if (HGEchoBridge.Utilities.MakeHttpRequest(url, device.httpVerb, device.contentType, body))
if (Utilities.MakeHttpRequest(url, device.httpVerb, device.contentType, body))
{

logger.Info("LightsController PUT: Successfully updated state of device via HTTP request.");
string responseString = "[{\"success\":{\"/lights/" + device.id.ToString() + "/state/on\":" + deviceState.on.ToString().ToLower() + "}}]";
return new HttpResponseMessage()
var responseString = "[{\"success\":{\"/lights/" + device.id + "/state/on\":" + deviceState.on.ToString().ToLower() + "}}]";
return new HttpResponseMessage
{
Content = new StringContent(responseString, Encoding.UTF8, "application/json"),
StatusCode = System.Net.HttpStatusCode.OK
StatusCode = HttpStatusCode.OK
};

}
else
{
logger.Warn("LightsController PUT: Failed to change state of device using HTTP request. URL:[{0}], Method: [{1}], ContentType: [{2}], Body: [{3}]", url, device.httpVerb, device.contentType, body);
return new HttpResponseMessage()
return new HttpResponseMessage
{
StatusCode = System.Net.HttpStatusCode.NotFound,
StatusCode = HttpStatusCode.NotFound,
ReasonPhrase = "Failed to change state of device."
};

}




}


protected string replaceIntensityValue(String request, DeviceState deviceState)
private static string ReplaceIntensityValue(string request, DeviceState deviceState)
{
logger.Info("Replacing IntensityValue...");
logger.Info($"Replacing IntensityValue for request \"{request}\"");
/* currently provides only two variables:
intensity.byte : 0-255 brightness. this is raw from the echo
intensity.percent : 0-100, adjusted for the vera
*/
int intensity = deviceState.bri;
var intensity = deviceState.bri;
if (deviceState.on && intensity == 0)
{
logger.Info("DeviceState was on but brightness value was zero. Setting to default brightness.");
intensity = Globals.DefaultIntensity; //205 is about 80% of 255
}


if (String.IsNullOrEmpty(request))
if (string.IsNullOrEmpty(request))
{
logger.Info("Empty request. No intensity value to replace.");
return "";
}
if (request.Contains(INTENSITY_BYTE))
if (request.Contains(Device.INTENSITY_BYTE))
{
logger.Info("Request contained [{0}] byte value. Replacing with intensity [{1}].", INTENSITY_BYTE, intensity);
request = request.Replace(INTENSITY_BYTE, intensity.ToString());
logger.Info("Request contained [{0}] byte value. Replacing with intensity [{1}].", Device.INTENSITY_BYTE, intensity);
request = request.Replace(Device.INTENSITY_BYTE, intensity.ToString());
}
else if (request.Contains(INTENSITY_PERCENT))
else if (request.Contains(Device.INTENSITY_PERCENT))
{
int percentBrightness = (int)Math.Round(intensity / 255.0 * 100);
logger.Info("Request contained [{0}] percent value. Scaling and Replacing with intensity [{1}].", INTENSITY_PERCENT, percentBrightness);
request = request.Replace(INTENSITY_PERCENT, percentBrightness.ToString());
var percentBrightness = (int)Math.Round(intensity / 255.0 * 100);
logger.Info("Request contained [{0}] percent value. Scaling and Replacing with intensity [{1}].", Device.INTENSITY_PERCENT, percentBrightness);
request = request.Replace(Device.INTENSITY_PERCENT, percentBrightness.ToString());
}
return request;
}
Expand Down
9 changes: 5 additions & 4 deletions EchoBridge/Devices/Device.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HGEchoBridge
{
public class Device
{
public const string INTENSITY_PERCENT = "${intensity.percent}";
public const string INTENSITY_BYTE = "${intensity.byte}";

public Device()
{
_id = Guid.NewGuid();
Expand Down Expand Up @@ -37,6 +36,8 @@ public string id
public String deviceType {get; set;}
public String offUrl {get; set;}
public String onUrl {get; set;}

public string DimUrl { get; set; }
public String httpVerb {get; set;}
public String contentType{get; set;}
public String contentBody {get; set;}
Expand Down

This file was deleted.

Binary file not shown.

This file was deleted.

Binary file not shown.

This file was deleted.

Empty file.
Empty file.
Empty file.
9 changes: 3 additions & 6 deletions MIG-Interface/HgHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,7 @@ public static List<Device> GetDevicesFromHg(string hgEndpoint)
try
{
var api = new HgApiHelper(hgEndpoint);

// Get available modules from HG
var modules = api.GetModules();

// Filter modules to ones we are interested in
var filteredModules = FilterModules(modules); // TODO: Add filter here with enum..

return GenerateDevicesFromModules(filteredModules, hgEndpoint);
Expand Down Expand Up @@ -51,7 +47,6 @@ private static List<Device> GenerateDevicesFromModules(IEnumerable<Module> modul
var device = CreateDevice(module, hgEndpoint);
deviceList.Add(device);
}

return deviceList;
}

Expand All @@ -62,6 +57,9 @@ private static Device CreateDevice(Module module, string hgEndpoint)
name = module.Name,
offUrl = $"http://{hgEndpoint}/api/{module.Domain}/{module.Address}/Control.Off",
onUrl = $"http://{hgEndpoint}/api/{module.Domain}/{module.Address}/Control.On",
DimUrl = module.DeviceType == "Dimmer"
? $"http://{hgEndpoint}/api/{module.Domain}/{module.Address}/Control.Level/{Device.INTENSITY_PERCENT}"
: null,
deviceType = "switch"
};

Expand Down Expand Up @@ -136,6 +134,5 @@ private static bool IsGuidValid(string myGuid)
var isValid = Guid.TryParse(myGuid, out guidOutput);
return isValid;
}

}
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loading

0 comments on commit 7b668e4

Please # to comment.