Skip to content

Commit

Permalink
Code cleanup
Browse files Browse the repository at this point in the history
Fix returns on UI, fetch device state, etc.
  • Loading branch information
d8ahazard committed Nov 17, 2019
1 parent 5e1f4ff commit abf50ae
Show file tree
Hide file tree
Showing 18 changed files with 437 additions and 82 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@
bin/*
obj/*
huedream.ini
*.sln
*.sln
37 changes: 13 additions & 24 deletions Controllers/HueDataController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,16 @@ namespace HueDream.Controllers {
public class HueDataController : ControllerBase {
// GET: api/HueData/action?action=...
[HttpGet("action")]
public IActionResult Get(string action) {
public JsonResult Get(string action) {
string message = "Unrecognized action";
DreamData userData = new DreamData();
Console.Write("Now we're cooking: " + action);
if (action == "connectDreamScreen") {
Console.Write("Connecting dream screen?");
string dsIp = userData.DS_IP;
DreamScreenControl.DreamScreen ds = new DreamScreenControl.DreamScreen(dsIp);
if (dsIp == "0.0.0.0") {
List<string> devices = ds.findDevices();
if (devices.Count() > 0) {
if (devices.Count > 0) {
userData.DS_IP = devices[0].Split(":")[0];
Console.WriteLine("We have a DS IP: " + userData.DS_IP);
userData.saveData();
Expand All @@ -33,7 +32,6 @@ public IActionResult Get(string action) {
}
}
} else if (action == "authorizeHue") {
Console.WriteLine("Auth request");
if (userData.HUE_IP != "0.0.0.0") {
HueBridge hb = new HueBridge();
RegisterEntertainmentResult appKey = hb.checkAuth();
Expand All @@ -46,10 +44,10 @@ public IActionResult Get(string action) {
userData.HUE_AUTH = true;
userData.saveData();
}
} else {
message = "No Operation: Bridge Already Linked.";
}
Console.Write("Authorize hue");
} else if (action == "findHue") {
Console.Write("Find hue");
string bridgeIp = HueBridge.findBridge();
if (bridgeIp != "") {
userData.HUE_IP = bridgeIp;
Expand All @@ -63,30 +61,31 @@ public IActionResult Get(string action) {
HueBridge hb = new HueBridge();
userData.HUE_LIGHTS = hb.getLights();
userData.saveData();
return new JsonResult(userData.HUE_LIGHTS);
} else {
message = "Error: Link your hue bridge first.";
}
}
return Ok(message);
return new JsonResult(message);
}

// GET: api/HueData/json
[HttpGet("json")]
public IActionResult Get() {
Console.Write("Normal JSON request");
DreamData userData = new DreamData();
return Ok(userData);
}

[HttpGet("lights")]
public IActionResult GetWhatever() {
Console.Write("Light JSON request");
DreamData userData = new DreamData();
return Ok(userData);
}


// GET: api/HueData/5
[HttpGet("{id}", Name = "Get")]
public string Get(int id) {
public static string Get(int id) {
return "value";
}

Expand All @@ -100,13 +99,13 @@ public void Post(string value) {
foreach (string key in keys) {
Console.WriteLine("We have a key and value: " + key + " " + Request.Form[key]);
if (key.Contains("lightMap")) {
int lightId = Int32.Parse(key.Replace("lightMap", ""));
int lightId = int.Parse(key.Replace("lightMap", ""));
lightMap.Add(new KeyValuePair<int, string>(lightId, Request.Form[key]));
} else if (key == "ds_ip") {
userData.DS_IP = Request.Form[key];
} else if (key == "hue_ip") {
userData.HUE_IP = Request.Form[key];
} else if (key == "ds_sync") {
} else if (key == "hue_sync") {
string val = Request.Form[key];
bool res = false;
if (val == "on") {
Expand All @@ -122,7 +121,7 @@ public void Post(string value) {
CheckSync(userData);
}

private void CheckSync(DreamData userData) {
private static void CheckSync(DreamData userData) {
DreamSync ds = new DreamSync();
if (userData.DS_IP != "0.0.0.0" && userData.HUE_SYNC && !ds.doSync) {
Console.WriteLine("Starting Dreamscreen sync!");
Expand All @@ -131,16 +130,6 @@ private void CheckSync(DreamData userData) {
Console.WriteLine("Stopping sync.");
ds.StopSync();
}
}

// PUT: api/HueData/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value) {
}

// DELETE: api/ApiWithActions/5
[HttpDelete("{id}")]
public void Delete(int id) {
}
}
}
}
82 changes: 72 additions & 10 deletions DreamScreenControl/DreamScreen.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
Expand Down Expand Up @@ -36,22 +37,32 @@ class DreamScreen {
private byte groupNumber = 0;
private UdpClient receiver;
public bool listening = false;


public DreamScreen(string remoteIP) {
dreamScreenIp = IPAddress.Parse(remoteIP);
endPoint = new IPEndPoint(dreamScreenIp, Port);
groupNumber = 1;
colors = new string[12][];
colors = new string[12][];
for (int i = 0; i < colors.Length; i++) {
colors[i] = new string[] { "FF", "FF", "FF" };
}
dreamScreenSocket = new Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
dreamScreenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, (int)1);

getMode();
}

public void setMode(int mode) {
sendUDPWrite((byte)3, (byte)1, new byte[] { (byte)mode });
}

public void getMode() {
Console.WriteLine("Trying to get state...");
byte[] payload = Array.Empty<byte>();
requestState();
Listen();
}

public void startListening() {
sendUDPWrite((byte)0x01, (byte)0x0C, new byte[] { (byte)0x01 }, (byte)0x10);
Listen();
Expand Down Expand Up @@ -91,18 +102,16 @@ private void DataReceived(IAsyncResult ar) {
// This is hacky as hell
if (byteString == "FC-05-01-30-01-0C-FF") {
try {
//Console.WriteLine("Replying to subscription Message.");
sendUDPWrite((byte)0x01, (byte)0x0C, new byte[] { (byte)0x01 }, (byte)0x10);
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
// So is this, but it works.
// So is this, but it works.
} else if ($"{bytesString[4]}{bytesString[5]}" == "0316") {
IEnumerable<string> colorData = bytesString.Skip(6);
int lightCount = 0;
int count = 0;
string[] colorList = new string[3];
//Console.WriteLine("Updating color data on ds");
foreach (string colorValue in colorData) {
if (count == 0) {
colorList = new string[3];
Expand All @@ -117,6 +126,9 @@ private void DataReceived(IAsyncResult ar) {
count++;
}
}
} else {
DreamScreenState dState = new DreamScreenState(byteString);
Console.WriteLine("Device State: " + JsonConvert.SerializeObject(dState));
}

// Restart listening for udp data packages
Expand All @@ -140,13 +152,11 @@ public List<string> findDevices() {
var recvBuffer = udpClient.Receive(ref from);
string localAddress = GetLocalIPAddress() + ":8888";
if (from.ToString() != localAddress) {
//Console.WriteLine("Received from " + from + " " + Encoding.UTF8.GetString(recvBuffer));
devices.Add(from.ToString());
noDevice = false;
}
count++;
}
Console.WriteLine("Broke the loop");
return devices;
}

Expand Down Expand Up @@ -186,7 +196,28 @@ void sendUDPWrite(byte command1, byte command2, byte[] payload, byte flag = (byt
// CRC
response.Write(calculateCrc(byteSend));
string msg = BitConverter.ToString(stream.ToArray());
//Console.WriteLine("Sending " + stream.Length + " bytes: " + msg);
sendUDPUnicast(stream.ToArray());
}
}
}

void requestState() {

using (MemoryStream stream = new MemoryStream()) {
// : FC:05:FF:30:01:0A:2A
using (BinaryWriter response = new BinaryWriter(stream)) {
// Magic header
response.Write((byte)0xFC);
response.Write((byte)0x05);
response.Write((byte)0xFF);
response.Write((byte)0x30);
response.Write((byte)0x01);
response.Write((byte)0x0A);
response.Write((byte)0x2A);
var byteSend = stream.ToArray();
// CRC
response.Write(calculateCrc(byteSend));
string msg = BitConverter.ToString(stream.ToArray());
sendUDPUnicast(stream.ToArray());
}
}
Expand All @@ -204,6 +235,37 @@ private byte calculateCrc(byte[] data) {
private void sendUDPUnicast(byte[] data) {
dreamScreenSocket.SendTo(data, endPoint);
}

class DreamScreenState {
public string deviceType;
public string deviceState;
public DreamScreenState(string byteString) {
string[] bytesIn = byteString.Split("-");
string magic = bytesIn[0];
string type = bytesIn[bytesIn.Length - 2];
string state = bytesIn[33];
string typeString = "Unknown";
if (type == "01") {
typeString = "DreamScreen";
} else if (type == "02") {
typeString = "DreamScreen 4K";
} else if (type == "03") {
typeString = "Sidekick";
}
deviceType = typeString;
if (state == "00") {
deviceState = "Sleep";
} else if (state == "01") {
deviceState = "Video";
} else if (state == "02") {
deviceState = "Music";
} else if (state == "03") {
deviceState = "Ambient";
}
Console.WriteLine("Type is " + typeString + ", state is " + state);
}
}
}


}
14 changes: 1 addition & 13 deletions HueControl/HueBridge.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public async Task startEntertainment() {
}

if (targetGroup == "") {
Console.WriteLine("Creating target group?");
Console.WriteLine("Creating target group.");
string group = "";
try {
Dictionary<string, object> data = new Dictionary<string, object>();
Expand All @@ -68,7 +68,6 @@ public async Task startEntertainment() {
var content = JsonConvert.SerializeObject(data);
var response = await httpClient.PostAsync("http://" + bridgeIp + "/api/" + bridgeUser + "/groups/", new StringContent(content, Encoding.UTF8, "application/json"));
var responseString = await response.Content.ReadAsStringAsync();
Console.WriteLine("Response: " + responseString);
var responseData = JToken.Parse(JsonConvert.SerializeObject(responseString));
if (responseData["Success"] != null) {
group = (string) responseData["Success"]["id"];
Expand All @@ -93,30 +92,21 @@ public async Task startEntertainment() {
Console.WriteLine("AutoUpdate Enabled.");
EntertainmentLayer entertainmentLayer = entGroup.GetNewLayer(isBaseLayer: true);
while (true) {
Console.WriteLine("Looping Hue Bridge send..." + JsonConvert.SerializeObject(colors));
foreach(KeyValuePair<int, string> lights in bridgeLights) {
if (lights.Value != "-1") {
int mapId = Int32.Parse(lights.Value);
string[] colorString = colors[mapId];
Console.WriteLine("Color String for light" + mapId);
foreach(EntertainmentLight light in entertainmentLayer) {
Console.WriteLine("Light ID: " + light.Id);
if (light.Id == lights.Key) {
string colorStrings = string.Join("", colorString);
Console.WriteLine("We can map this: " + colorStrings);

light.State.SetRGBColor(new RGBColor(colorStrings));
light.State.SetBrightness(100);
}
}
//var light = entertainmentLayer.Where(x => x.Id == mapId).FirstOrDefault();

}
}

}
//foreach()
//var l1 = entLayer.Where(x => x.Id == 1);
} else {
Console.WriteLine("Target Group creation failed!");
}
Expand Down Expand Up @@ -159,9 +149,7 @@ public List<KeyValuePair<int, string>> getLights() {
var task = Task.Run(async () => await client.GetLightsAsync());
var lightArray = task.Result;
foreach (Light light in lightArray) {
Console.WriteLine("Got a light");
if (light.Type == "Extended color light") {
Console.WriteLine("And it's colored");
lights.Add(new KeyValuePair<int, string>(Int32.Parse(light.Id), light.Name));
}
}
Expand Down
32 changes: 32 additions & 0 deletions HueDream.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<StartupObject></StartupObject>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
Expand All @@ -25,4 +26,35 @@
<PackageReference Include="Q42.HueApi.Entertainment" Version="3.12.1" />
</ItemGroup>

<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>

<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>

<PropertyGroup Condition="'$(Configuration)' == 'Release'">
<TypeScriptTarget>ES5</TypeScriptTarget>
<TypeScriptJSXEmit>React</TypeScriptJSXEmit>
<TypeScriptModuleKind>None</TypeScriptModuleKind>
<TypeScriptCompileOnSaveEnabled>True</TypeScriptCompileOnSaveEnabled>
<TypeScriptNoImplicitAny>False</TypeScriptNoImplicitAny>
<TypeScriptRemoveComments>False</TypeScriptRemoveComments>
<TypeScriptOutFile />
<TypeScriptOutDir />
<TypeScriptGeneratesDeclarations>False</TypeScriptGeneratesDeclarations>
<TypeScriptNoEmitOnError>True</TypeScriptNoEmitOnError>
<TypeScriptSourceMap>True</TypeScriptSourceMap>
<TypeScriptMapRoot />
<TypeScriptSourceRoot />
</PropertyGroup>

</Project>
1 change: 1 addition & 0 deletions HueDream.csproj.user
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,6 @@
<Controller_SelectedScaffolderCategoryPath>root/Controller</Controller_SelectedScaffolderCategoryPath>
<WebStackScaffolding_ControllerDialogWidth>600</WebStackScaffolding_ControllerDialogWidth>
<WebStackScaffolding_IsAsyncSelected>False</WebStackScaffolding_IsAsyncSelected>
<NameOfLastUsedPublishProfile>LinuxProfile</NameOfLastUsedPublishProfile>
</PropertyGroup>
</Project>
Loading

0 comments on commit abf50ae

Please sign in to comment.