Skip to main content

Control the color of Philips Hue Lamp based on the user status - Friday night undercover project

Yesterday I had the opportunity to put my hands on some lamp from Philips – Hue Lamps. Basically, you have one or more lamps that can be controlled over the network. For each lamp you can control the color, brightness and so on. The communication is done over a simple HTTP API that is well documented. When you will buy one or more lamps you will receive also a small device that needs to be connected to your network. That small device is used to communicate by wireless with your lamps.
I had the idea to write an application which controls the color of the lamp based on user status. For example when you are in a call, the color of the lamp will be red, otherwise green. I integrated the application with Skype, Outlook calendar and Lync.
If you want to play with this application you can download it from here: https://huelampstatus.codeplex.com/
You will need to install Skype API SDK, Lync 2013 API SDK and you need to have Outlook 2013. The application is not finished yet, but is a good starting point. Until now, on my machine worked pretty okay. Because of Skype API SDK don’t forget to build solution for a 86x processor (COM Nightmare).

Demo Video


Hue Lamp Integration
The communication with Hue Lamp is made pretty simple, you only need to make a PUT request.
 public class HueControl
    {
        private const string MessageBody = @"
{{
    ""hue"": {0},
    ""on"": true,
    ""bri"": 200
}}";
        private const int RedCode = 50;
        private const int GreenCode = 26000;

        public void SetColor(Color color)
        {
            if (color != Color.Red
                && color != Color.Green)
            {
                throw new ArgumentException("Color is not supported", "color");
            }
            try
            {
                byte[] messageContent = UTF8Encoding.UTF8.GetBytes(string.Format(MessageBody,
                    color == Color.Red ? RedCode : GreenCode));
                WebRequest request = WebRequest.Create(new Uri(
                                        string.Format("http://{0}/api/{1}/lights/{2}/state",
                                        ConfigurationManager.AppSettings["hueIP"],
                                        ConfigurationManager.AppSettings["hueUser"],
                                        ConfigurationManager.AppSettings["hueNumber"])));
                request.Method = "PUT";
                request.Timeout = 10000;
                request.ContentType = "application/json";
                request.ContentLength = messageContent.Length;
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(messageContent, 0, messageContent.Length);
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.Message);
            }
        }
    }
The time consuming things are integration with Skype, Lync and Outlook calendar.

Skype Integration
For Skype, the hardest thing is to put your hands on the SDK (they don't accept new members anymore). You can use this sample code to put the hands on the SDK: http://archive.msdn.microsoft.com/SEHE/Release/ProjectReleases.aspx?ReleaseId=1871
After this all that you need to do is:
public class SkypeStatusChecker : IStatusChecker
    {
        private Skype _skype;

        public SkypeStatusChecker()
        {
            _skype = new Skype();
            _skype.Client.Start(true, true);
            _skype.Attach(6, true);

            _skype.CallStatus += OnCallStatusChange;
        }

        public ChangeStatus ChangeStatus { get; set; }

        private void OnCallStatusChange(Call pCall, TCallStatus status)
        {
            Trace.TraceInformation("Skype statusType: " + status);
            if (status == TCallStatus.clsInProgress)
            {
                SendNotification(StatusType.Busy);
                return;
            }

            if (status == TCallStatus.clsFinished)
            {
                SendNotification(StatusType.Free);
                return;
            }
        }

        private void SendNotification(StatusType statusType)
        {
            if (ChangeStatus != null)
            {
                ChangeStatus.Invoke(this, new ChangeStatusEventArgs(statusType));
            }
        }
    }
When the user will be involved in a call the status of Skype call is “clsInProgress”. When a call is finished the notification status that you receive from Skype is “clsFinished”. I used this to states to change the lamp color.

Lync Integration
In the Lync case you will need to get your activities and check if the status is “Available” or not.
 public class LyncStatusChecker : IStatusChecker
    {
        private StatusType _oldStatusType = StatusType.Free;
        private object _padLock = new object();

        public LyncStatusChecker()
        {
            Timer timer = new Timer();
            timer.Interval = TimeSpan.FromSeconds(1).TotalMilliseconds;
            timer.Elapsed += OnTimeElapsed;
            timer.Start();
        }

        public ChangeStatus ChangeStatus { get; set; }

        private void OnTimeElapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                LyncClient client = LyncClient.GetClient();

                List<object> states = (List<object>)client.Self.
                    Contact.GetContactInformation(ContactInformationType.CustomActivity);

                var status = GetStatus(states);

                lock (_padLock)
                {
                    if (status == _oldStatusType)
                    {
                        return;
                    }

                    Trace.TraceInformation("Lync statusType: {0}", status);
                    SendNotification(status);
                    _oldStatusType = status;
                }
            }
            catch (Exception err)
            {
                Trace.TraceError(err.ToString());
            }
        }

        private StatusType GetStatus(List<object> states)
        {
            StatusType statusType = StatusType.Free;
            if (states.Count == 0)
            {
                throw new Exception("States of Lync is 0");
            }
            if (states.FirstOrDefault(x => ((LocaleString) x).Value == "Available") == null)
            {
                statusType = StatusType.Busy;
            }
            return statusType;
        }

        private void SendNotification(StatusType statusType)
        {
            if (ChangeStatus != null)
            {
                ChangeStatus.Invoke(this, new ChangeStatusEventArgs(statusType));
            }
        }
    }


Outlook Integration
As I expected, the Outlook API is a nightmare, is very complicated and is pretty hard to find what you are looking for. The solution that I implemented gets the Outlook calendar and check if the user has a meeting in this moment. I don't like how I get the current user status, but it works.
    public class OutlookStatusChecker : IStatusChecker
    {
        private StatusType _oldStatusType = StatusType.Free;
        private object _padLock = new object();

        public OutlookStatusChecker()
        {
            Timer timer = new Timer();
            timer.Interval = TimeSpan.FromSeconds(1).TotalMilliseconds;
            timer.Elapsed += OnTimeElapsed;
            timer.Start();
        }

        public ChangeStatus ChangeStatus { get; set; }

        private void OnTimeElapsed(object sender, ElapsedEventArgs e)
        {
            CheckStatus();
        }

        private void CheckStatus()
        {
            try
            {
                Application outlookApp = new Application();
                NameSpace nameSpace = outlookApp.GetNamespace("MAPI");

                MAPIFolder calendarFolder = nameSpace.GetDefaultFolder(OlDefaultFolders.olFolderCalendar);
                Items calendarItems = calendarFolder.Items;
                calendarItems.IncludeRecurrences = true;
                calendarItems.Sort("[Start]", Type.Missing);
                DateTime now = DateTime.Now;
                DateTime todayStart = new DateTime(now.Year, now.Month, now.Day, 00, 00, 01);
                DateTime todayEnds = new DateTime(now.Year, now.Month, now.Day, 23, 59, 58);

                Items currentCalendarItems = calendarItems.Restrict(
                            string.Format(@"[Start] < ""{0}"" AND [End] > ""{1}"" AND [Start] >=""{2}"" AND [End] < ""{3}"" ",
                                    now.ToString("g"), now.AddMinutes(1).ToString("g"),
                                    todayStart.ToString("g"), todayEnds.ToString("g")));

                IEnumerator itemsEnumerator = currentCalendarItems.GetEnumerator();
                itemsEnumerator.MoveNext();

                StatusType statusType = itemsEnumerator.Current == null ? StatusType.Free : StatusType.Busy;

                lock (_padLock)
                {
                    if (statusType == _oldStatusType)
                    {
                        return;
                    }

                    Trace.TraceInformation("Outlook statusType: {0}", statusType);
                    SendNotification(statusType);
                    _oldStatusType = statusType;
                }
            }
            catch (Exception err)
            {
                Trace.TraceError(err.ToString());
            }
        }

        private void SendNotification(StatusType statusType)
        {
            if (ChangeStatus != null)
            {
                ChangeStatus.Invoke(this, new ChangeStatusEventArgs(statusType));
            }
        }
    }

Conclusion
 The things that I really liked was the API of Hue Lamps, that is very simple to use and well documented. Great job Philips.  

Comments

  1. Looks cool :-) Can you choose which user's status to show?

    ReplyDelete
    Replies
    1. In this moment is not supported. But is pretty simple to extend and add features like this.

      Delete
  2. Did you run the code in debug and release mode? I had no issues in debug mode, but the release mode won't work. It loses references with Lync. Any advice?

    ReplyDelete
    Replies
    1. It may be related to Lync component. What version of Lync are you using?

      Delete
  3. 2013. I fixed that issue and now it is able to run in release mode. Now, I'm just working on being able to run it on another computer without c# software. The .exe file in the bin/release only works on my computer (with Visual Studio software.) This is really neat by the way! I love the way it works with the Hues. I wonder if something similar could be done with Lifx, not sure about the Lifx API though since it is still a startup.

    ReplyDelete
    Replies
    1. any updates on this or LIFX control? I'd love to be able to set LIFX colors automatically by Skype status, and get other informative updates by light color/intensity. Thx!

      Delete
    2. No, there are no updated. I don't have anymore this lamps. But feel free to improve the existing sample.

      Delete

Post a Comment

Popular posts from this blog

How to check in AngularJS if a service was register or not

There are cases when you need to check in a service or a controller was register in AngularJS.
For example a valid use case is when you have the same implementation running on multiple application. In this case, you may want to intercept the HTTP provider and add a custom step there. This step don’t needs to run on all the application, only in the one where the service exist and register.
A solution for this case would be to have a flag in the configuration that specify this. In the core you would have an IF that would check the value of this flag.
Another solution is to check if a specific service was register in AngularJS or not. If the service was register that you would execute your own logic.
To check if a service was register or not in AngularJS container you need to call the ‘has’ method of ‘inhector’. It will return TRUE if the service was register.
if ($injector.has('httpInterceptorService')) { $httpProvider.interceptors.push('httpInterceptorService&#…

ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

Today blog post will be started with the following error when running DB tests on the CI machine:
threw exception: System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information. at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName) This error happened only on the Continuous Integration machine. On the devs machines, everything has fine. The classic problem – on my machine it’s working. The CI has the following configuration:

TeamCity.NET 4.51EF 6.0.2VS2013
It seems that there …

Run native .NET application in Docker (.NET Framework 4.6.2)

Scope
The main scope of this post is to see how we can run a legacy application written in .NET Framework in Docker.

Context
First of all, let’s define what is a legacy application in our context. By a legacy application we understand an application that runs .NET Framework 3.5 or higher in a production environment where we don’t have any more the people or documentation that would help us to understand what is happening behind the scene.
In this scenarios, you might want to migrate the current solution from a standard environment to Docker. There are many advantages for such a migration, like:

Continuous DeploymentTestingIsolationSecurity at container levelVersioning ControlEnvironment Standardization
Until now, we didn’t had the possibility to run a .NET application in Docker. With .NET Core, there was support for .NET Core in Docker, but migration from a full .NET framework to .NET Core can be costly and even impossible. Not only because of lack of features, but also because once you…