Control your Philips Hue Lights from Microsoft Power Platform and .NET

Philips Hue is a smart lighting solution provider with range of smart lights that can be controlled with your smart devices like your mobile phone, Google Home, Alexa etc through the applications developed by Philips. On top of applications from Philips, the Hue system also enables OAuth 2.0 to allow third party integrations to connect to Hue system resources. In this blog post, let us see how to use the Philips Hue OAuth 2.0 remote API to integrate with the Power Platform for controlling the lights.

Pre-Requisites:

  1. Lights connected to the Hue Bridge. Hue bridge is a device which is the brain of the Philips hue smart lighting system that links the lights to the internet.
  2. Register an account in the Philips Hue Developers portal

The first step is to create a Remote Hue API app which provides you with OAuth credentials to remote control the Hue lights.

Add Remote Hue API App:

After logging in to the Philips Hue Developers Portal, access the URL https://developers.meethue.com/my-apps/ to add the App. Click on the link Add new Remote Hue API app

After entering the App name, Callback URL and the description, click the Submit button. For the callback URL I have provided the Postman browser call back url https://oauth.pstmn.io/v1/browser-callback facilitating OAuth 2.0  token generation from Postman. You can also enter http://localhost/ as the callback url. Find below screenshot of the newly registered Remote Hue API app

Copy the ClientId & ClientSecret which will be required to generate access token for controlling the Hue lights. The next step is to generate the access token.

Access Token Generation:

To access a Philips Hue API endpoint to turn on/off or change colours of light, an access token is required. To generate an access token, the first step is to generate an authorization code. Construct the following URL

GET https://api.meethue.com/oauth2/auth?clientid=<clientid>&appid=<appid>&deviceid=<deviceid>&devicename=<devicename>&state=<state>&response_type=code
  • ClientId: From the app registration.
  • ClientSecret: From the app registration.
  • AppId: From the app registration, the name of the app. Per the above screenshot, it is myremotehueapp
  • DeviceId: The device identifier must be a unique identifier in a string format for the app or device accessing the Hue Remote API.
  • DeviceName: The name of the app accessing the remote api.
  • State: any string

The url should look something like

Access the URL in a browser, you will be prompted to accept or decline the permission grant to the created app.

Once the app is trusted, there will be an authorization code automatically generated on the browser address bar as shown below

Make a note of the code which will be used to generate access token. To Deactivate an existing App or see all the list of existing apps, login to https://account.meethue.com/apps.

To generate an access token using Basic Authentication, make the following HTTP request using Postman or any other tool

Type: POST

URL: https://api.meethue.com/oauth2/token?code= bsysFQ65 &grant_type=authorization_code

Replace the code value with yours generated from the authorization grant request.

Authorization Type: Basic Auth. Username should be ClientId of the App and Password should be ClientSecret

Find below screenshot from Postman with the above HTTP POST request, make a note of the access token and refresh token from the response section of the request.

The Access token is approximately valid for 7 days and the refresh token for 100 days. Let us now see, how to refresh the access token.

Refresh Access token:

The access token is valid only for 7 days, to use it beyond 7 days there must be a new access token generated using the Refresh token. Find below the request details using Basic Authentication

Type: POST

URL: https://api.meethue.com/oauth2/refresh?grant_type=refresh_token

Authorization Type: Basic Auth. Username should be ClientId of the App and Password should be ClientSecret

Headers:

Key: Content-Type

Value: application/x-www-form-urlencoded

Body:

refresh_token=refreshtokenfromthefirstrequest

Find below screenshot of the request

Besides Basic authentication, Hue Remote API supports Digest method. For more details on the remote authentication, go through the documentation https://developers.meethue.com/develop/hue-api/remote-authentication-oauth/

Control the Hue Lights using the generated Access token:

Till now we have seen how to register a remote API app, generate access token and to refresh it before it expires. Let us now see how to use the access token to turn on/off, change colours etc with the remote API endpoints. To enable this experience, there must be a username created first.

User Name Creation:

Find the HTTP request details to enable the Link button

Type: PUT

URL: https://api.meethue.com/bridge/0/config

Body-RAW: { “linkbutton”:true }

Headers:

Content-Type: application/json

Authorization: Bearer access_token

Immediately after the above request, make the following HTTP request to create the User Name

Type: POST

URL: https://api.meethue.com/bridge/

Body-RAW: { “devicetype”: “myremotehueapp” }

The devicetype is the appid or the name of the remote app

Headers:

Content-Type: application/json

Authorization: Bearer access_token

Copy the username from the above request response.

Turn On/Off Hue Lights:

To turn On/Off the light, the first step is to get the Light no you are trying to control. To get the list of lights, make the following request with the user name generated above

Type: GET

URL: https://api.meethue.com/bridge/username/lights/

Replace the username in the URL

Body: None

Headers:

Authorization: Bearer access_token

In the above request response, the light no is 1 which is the first light on my Hue system.

To Turn On/Off:

Find the HTTP request details to turn on/off

Type: PUT

URL: https://api.meethue.com/bridge/{{username}}/lights/{{lightno}}/state

Replace the username & lightno in the URL

Body-Raw: {“on”:true} or {“on”:false}

True for Turning On and False for Turning off

Headers:

Authorization: Bearer access_token

Content-Type: application/json

Set colours of the Hue Light:

The Philips Hue system uses Chromaticity to set the colour of the light. Chromaticity consists of two independent parameters, often specified as hue (h) and colourfulness, where the latter is alternatively called saturation, chroma. Find below diagram which will help you to set the colour of the light

Find below HTTP request details for setting the colour to RED

Type: PUT

URL: https://api.meethue.com/bridge/{{username}}/lights/{{lightno}}/state

Replace the username & lightno in the URL

Body-Raw:

{
"on":true,
        "xy": [
            0.720000,
            0.250000 
        ],
  "bri":100,
  "transitiontime": 0
}

Change the XY values for different colours. To increase/decrease brightness update the bri attribute. With the help of the above diagram, for colour GREEN the XY value is 0.350000, 0.550000

Headers:

Authorization: Bearer access_token

Content-Type: application/json

For information on the Light API, refer to the documentation https://developers.meethue.com/develop/hue-api/lights-api/

Control Lights in Power Platform:

As you have seen above, to control the lights an access token and username is required. Store the information in a SharePoint list which will make it easier to get the Client Id, Client Secret, light no, refresh token etc. Find below the list schema I have created to manage the Light configuration.

Refresh the Access Token:

As the token is valid only for 7 days, create a scheduled Power Automate cloud flow which can run once in 6 days to create a new token using the Refresh token. Refer to the earlier section for the API endpoint details to refresh the token.

  1. After the trigger is added, add the SharePoint connector to get values of the Refresh Token, Client Id, Client Sercret etc
  2. Initialize variables to store the values retrieved from the SharePoint list
  3. Add a Switch control to store the values on the variable.
  1. Add a HTTP action to refresh the token as shown below
  1. Add the JSON parse action to get the new token values including the new Refresh Token. Once the refresh token is used, it cannot be used again.
  1. After getting the new values, update the access token & Refresh token in the SharePoint list.
  2. The package of this cloud flow can be downloaded from here. https://github.com/ashiqf/PowerAutomate/tree/PhilipsHue-RefreshtheAccessToken

Turn On/Off from Power Automate or Power Apps:

To turn on/off or set different colours of the light from Power Automate or Power Apps, create a Flow with HTTP action & call the API given in the above section. To call the flow in Power Apps, use the Power Apps trigger or use a custom connector.

Control Lights from a .Net application:

Find code below to turn on/off light from a .NET application

private static async Task<string> TurnOnPhilipsHue(string accessTokenPhilipsHue, string userNamePhilipsHue, string lightNoPhilipsHue)
{
	string requestUrl = "https://api.meethue.com/bridge/" + userNamePhilipsHue + "/lights/"+ lightNoPhilipsHue + "/state";
	using var client = new HttpClient();

	var payload = "{\"on\": true,\"bri\": 102}";
	client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessTokenPhilipsHue);
	var requestData = new StringContent(payload, Encoding.UTF8, "application/json");
	var response = await client.PutAsync(String.Format(requestUrl), requestData);
	var result = await response.Content.ReadAsStringAsync();
	return result;
}

There is also SDK for C#, do look at it on this url https://developers.meethue.com/develop/tools-and-sdks/ for more details.

Summary:

I have used this light to build a Microsoft Teams status light, will post the link as soon as it is available. Hope you have found this informational & thanks for reading. If you are visiting my blog for the first time, please do look at my other blogposts.

Handle HTTP request failures in Power Automate

If the HTTP request you make in Power Automate cloud flow gets a 200 OK response, all is good but if the HTTP response has the status codes like 408 – Request Timeout, 429 – Too many requests, 522 – Connection Timeout, 404 – Not found, 400 – Bad request etc there is a problem which needs attention. This post will show you how to handle HTTP request failures using

  • Retry Policy
  • Custom Retry for requests which cannot be handled by Retry Policy
  • Take actions based on HTTP status code

Retry Policy:

A Retry Policy specifies how the action or trigger retries a request when the original request times out or fails. The retry policy handles the following HTTP status codes

  1. 408 – Request Timeout
  2. 429 – Too many requests
  3. 5xx – xx refers to any number like 500 – Internal server error, 503 – Service Unavailable, 522 – Connection timed out etc

HTTP Action supports retry policy and by default the action retries 4 times at exponentially increasing intervals if there is a request failure. To view or update the Retry Policy configuration settings for the HTTP action, navigate to settings as shown on below screenshot

If you have to retry the request for more than 4 times or set some custom interval between retries, you can do so by changing the retry policy from Default to Fixed interval or Exponential interval as shown below

Exponential Interval:

The policy waits for a random interval before sending the next request. The random interval is selected from an exponentially growing range.

Fixed Interval:

The policy waits for a specified interval before sending the next request.

There will not be any retry if the policy is set to None. For more details on the retry policies, go through this documentation from Microsoft. Find below screenshot of a Fixed Interval Retry Policy which attempts to make a HTTP request 5 more times after the first failed request with a 10-minute delay between each attempt.

The retry interval accepts value in ISO 8601 format. In the above screenshot for the interval field with value PT10M

P is the duration designator and T is the time designator, where M is the minute designator. PT5S translates to 5 seconds. For testing the policy with the HTTP action you can get sample http request links with different status codes request url’s from https://httpstat.us/.

The retry information will be logged in the flow Run history as shown below

Custom Retry for requests which cannot be handled by Retry Policy:

The retry policy handles only HTTP status codes 408, 429 and 5xx. On this section let us see how to handle the other types of HTTP status codes or non-retry-able errors. Let us take an example with a requirement to retry HTTP request with status code 400 – Bad request till the request succeeds.

Step 1: Initialize a boolean variable ExecuteHTTPAction with the default value true. For the Boolean value use the expression true.

Step 2: Add a Do until control. The loop runs for a maximum of 60 times (Default setting) until the HTTP request succeeds or the condition is met. The Left side placeholder should have the ExecuteHTTPAction variable as a value and the right side should have Boolean variable False. Use Expression to enter the Boolean variable false.

Toggle between Edit in advance mode and Edit in basic mode if the right side placeholder to enter value is disabled.

Step 3: Add the HTTP request action and an action to Set variable ExecuteHTTPAction named as Set Variable – HTTP Action Success. Set the value of the variable to boolean false which means on HTTP action success (200 OK), there should not be any retry.

Step 4: Once the Set variable action is added, just above the action click + and Add a parallel branch as shown in the above picture. On the other side of the branch add an action Set variable named as Set variable – HTTP Action Failure to set the ExecuteHTTPAction variable to true which means there should be retry

Step 5: The last step is to configure Run after for the action Set variable – HTTP Action Failure. Find below screenshot for the Run after configuration

No change is required for Set variable – HTTP Action Success, just ensure the Set variable – HTTP Action Failure has the Run After has failed. You can add a Delay action after the parallel branch to make sure the HTTP request is made after certain interval based on scenario. You can also add scope controls for TRY, RETRY etc.

Alternative Method:

The other way to do this without adding the parallel branch is as shown below

Take actions based on HTTP status code:

If you have to take different actions based on the HTTP status code, for example call a different API when there is an HTTP 404 – Not found etc. The quick way to do this is get the HTTP status code of the HTTP request by adding the Compose action below the HTTP request action and select the Status code from the Dynamic content which is an Output of the action HTTP.

Now configure the run after for the compose action as shown below

The compose action would now be able to capture all type of HTTP status code. With the status code in hand, add a switch control to take different actions based on HTTP status code.

Summary:

On this post we have seen how to handle different HTTP request failures codes with options to Retry in your Power Automate flow. You can apply this technique to handle HTTP request made via custom connector, SharePoint Connector etc.  Hope you have found this informational & thanks for reading. If you are visiting my blog for the first time, please do look at my other blogposts.