Skip to content

Commit

Permalink
Filled out Configuration API
Browse files Browse the repository at this point in the history
  • Loading branch information
preardon committed Nov 8, 2020
1 parent 72b6b9c commit 30d0882
Show file tree
Hide file tree
Showing 21 changed files with 737 additions and 140 deletions.
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,32 @@
# HueController
a .Net API for controlling Philips Hue

## Register your Application

```cs
var hue = new HueAPI();
var user = await hue.Configuration.CreateUserAsync(new CreateUserRequest { DeviceType = "my_hue_Application#Computer1" });

var userName = user["success"].UserName;
//Save the above UserName for later user
```

## Control a Group of Lights
In the following example we are going to Turn on all of the lights in the Study over 1 second with full brightness

```cs
//User the Username that was returned from the Register Application
var hue = new HueAPI(_userName);

//Get a list of all Groups
var groups = await hue.Groups.GetAllGroupsAsync();

//Find a the group named Study
var studyId = groups.Where(g => g.Value.Name == "Study").Select(g => g.Key).First();

var builder = new GroupStateBuilder(studyId);
await builder.TurnOn()
.WithBrightness(254)
.WithTransitionTime(10)
.SendAsync(hueController);
```
32 changes: 17 additions & 15 deletions src/HueController.ScratchPad/Program.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
using PReardon.HueController.Builders;
using System;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace HueController.ScratchPad
Expand All @@ -14,9 +12,13 @@ static async Task Main(string[] args)
Console.WriteLine("Hello World!");


var hueController = new PReardon.HueController.HueController(_userName);
await hueController.Disco();
var lights = await hueController.Lights.GetAllLightsAsync();
//var hue = new HueAPI(_userName);
//var user = await hue.Configuration.CreateUserAsync(new CreateUserRequest { DeviceType = "my_hue_Application#Computer1" });

var cfg = await hue.Configuration.GetConfigurationAsync();
var state = await hue.Configuration.GetFullStateAsync();

var lights = await hue.Lights.GetAllLightsAsync();

var onLights = lights.Where(l => l.Value.State.On == true).Select(l => l.Key).ToList();

Expand All @@ -26,7 +28,7 @@ static async Task Main(string[] args)
//}

Console.WriteLine("Looking for Groups");
var groups = await hueController.Groups.GetAllGroupsAsync();
var groups = await hue.Groups.GetAllGroupsAsync();

foreach (var group in groups)
{
Expand All @@ -35,16 +37,16 @@ static async Task Main(string[] args)

var studyId = groups.Where(g => g.Value.Name == "Study").Select(g => g.Key).First();

var builder = new GroupStateBuilder(studyId);
await builder.TurnOff()
.WithTransitionTime(10)
.SendAsync(hueController);
//var builder = new GroupStateBuilder(studyId);
//await builder.TurnOff()
// .WithTransitionTime(10)
// .SendAsync(hueController);

Thread.Sleep(1500);
//Thread.Sleep(1500);

await builder.TurnOn()
.WithBrightness(254)
.SendAsync(hueController);
//await builder.TurnOn()
// .WithBrightness(254)
// .SendAsync(hueController);

}
}
Expand Down
2 changes: 1 addition & 1 deletion src/HueController/Builders/GroupStateBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ private void SetGroupId(string groupId)
_groupId = groupId;
}

public async Task SendAsync(HueController controller)
public async Task SendAsync(HueAPI controller)
{
await controller.Groups.SetGroupStateAsync(_groupId, GroupState);
}
Expand Down
90 changes: 0 additions & 90 deletions src/HueController/Configuration/Configuration.cs

This file was deleted.

125 changes: 125 additions & 0 deletions src/HueController/Configuration/ConfigurationAPI.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
using PReardon.HueController.Configuration.Model;
using PReardon.HueController.Groups.Model;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

namespace PReardon.HueController.Configuration
{
public class ConfigurationAPI
{
private readonly HttpClient _httpClient;
private readonly string _userName;
private readonly JsonSerializerOptions _jsonSerializerOptions;

public ConfigurationAPI(HttpClient httpClient, string username, JsonSerializerOptions jso)
{
_httpClient = httpClient;
_userName = username;

_jsonSerializerOptions = jso;
}

/// <summary>
/// Creates a new user. The link button on the bridge must be pressed and this command executed within 30 seconds.
/// Once a new user has been created, the user key is added to a ‘whitelist’, allowing access to API commands that require a whitelisted user.At present, all other API commands require a whitelisted user.
/// We ask that published apps use the name of their app as the devicetype
/// </summary>
/// <param name="request">Create User Request</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<Dictionary<string, CreateUserResponseItem>> CreateUserAsync(CreateUserRequest request, CancellationToken cancellationToken = default(CancellationToken))
{
var requestContent = new StringContent(JsonSerializer.Serialize(request), Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync($"/api", requestContent, cancellationToken);

if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<Dictionary<string, CreateUserResponseItem>>(content, _jsonSerializerOptions);
}

return null;
}

/// <summary>
/// Returns list of all configuration elements in the bridge. Note all times are stored in UTC.
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<BridgeConfiguration> GetConfigurationAsync(CancellationToken cancellationToken = default(CancellationToken))
{
var response = await _httpClient.GetAsync($"/api/{_userName}/config", cancellationToken);

if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<BridgeConfiguration>(content, _jsonSerializerOptions);
}

return null;
}

/// <summary>
/// Allows the user to set some configuration values.
/// </summary>
/// <param name="config">Configuration to Update the Bridge with</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<bool> UpdateConfigurationAsync(BridgeConfigurationUpdate config, CancellationToken cancellationToken = default(CancellationToken))
{
var requestContent = new StringContent(JsonSerializer.Serialize(config), Encoding.UTF8, "application/json");
var response = await _httpClient.PutAsync($"/api/{_userName}/config", requestContent, cancellationToken);

if (response.IsSuccessStatusCode)
{
//ToDo: fix return
var content = await response.Content.ReadAsStringAsync();
return true;
//return JsonSerializer.Deserialize<Dictionary<string, CreateUserResponseItem>>(content, _jsonSerializerOptions);
}

return false;
}

/// <summary>
/// Deletes the specified user, <element>, from the whitelist.
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<List<GenericSuccessResponseItem>> DeleteUserFromWhitelistAsync(string applicationKey, string user, CancellationToken cancellationToken = default(CancellationToken))
{
//ToDo: the Docco specifics Application key not UserName Check this
var response = await _httpClient.GetAsync($"/api/{applicationKey}/config/whitelist/{user}", cancellationToken);

if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<List<GenericSuccessResponseItem>>(content, _jsonSerializerOptions);
}

return null;
}

/// <summary>
/// This command is used to fetch the entire datastore from the device, including settings and state information for lights, groups, schedules and configuration. It should only be used sparingly as it is resource intensive for the bridge, but is supplied e.g. for synchronization purposes.
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<HueState> GetFullStateAsync(CancellationToken cancellationToken = default(CancellationToken))
{
var response = await _httpClient.GetAsync($"/api/{_userName}", cancellationToken);

if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<HueState>(content, _jsonSerializerOptions);
}

return null;
}
}
}
21 changes: 21 additions & 0 deletions src/HueController/Configuration/Model/AutoInstall.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System;
using System.Text.Json.Serialization;

namespace PReardon.HueController.Configuration.Model
{
public class AutoInstall
{
/// <summary>
/// Indicates if automatic update is activated. Default is false
/// </summary>
[JsonPropertyName("on")]
public bool On { get; set; }

/// <summary>
/// T[hh]:[mm]:[ss] Local time of day.
/// The bridge auto.updates for bridge and zigbee devices.The installation time will be randomized between updatetime and updatetime+T01:00:00. Default is T14:00:00.
/// </summary>
[JsonPropertyName("updatetime")]
public string UpdateTime { get; set; }
}
}
Loading

0 comments on commit 30d0882

Please sign in to comment.