Windows Mobile Support

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Saturday, 10 August 2013

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

Posted on 01:32 by Unknown
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.  
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Posted in | No comments
Newer Post Older Post Home

0 comments:

Post a Comment

Subscribe to: Post Comments (Atom)

Popular Posts

  • Service Bus Topic - Automatic forward messages from a subscription to a topic
    Windows Azure Service Bus Topic is a service that enables us to distribute the same messages to different consumers without having to know e...
  • CDN is not the only solution to improve the page speed - Reverse Caching Proxy
    I heard more and more often think like this: “If your website is to slow, you should use a CDN.” Great, CDN is THE solution for any kind of ...
  • Content Types - Level 6: Rich Media
    Level 6: Rich Media NOTE: This is part 7 of 7 and the conclusion of this continuing series; please see earlier posts for more background inf...
  • Publishing our CellCast Widget for iPad
    The rush has been on this week as our development team worked to design a new version of our CellCast Widget specifically for Apple's up...
  • Patterns in Windows Azure Service Bus - Message Splitter Pattern
    In one of my post about Service Bus Topics from Windows Azure I told you that I will write about a post that describe how we can design an a...
  • E-Learning Vendors Attempt to Morph Mobile
    The sign should read: " Don't touch! Wet Paint !" I had a good chuckle today after receiving my latest emailed copy of the eLe...
  • SQL - UNION and UNION ALL
    I think that all of us used until now UNION in a SQLstatement. Using this operator we can combine the result of 2 queries. For example we wa...
  • Cum sa salvezi un stream direct intr-un fisier
    Cred ca este a 2-a oara când întâlnesc aceasta cerința in decurs de câteva săptămâni. Se da un stream și o locație unde trebuie salvat, se c...
  • Task.Yield(...), Task.Delay(...)
    I think that a lot of person already heard about these new methods. In this post I want to clarify some things about these new methods that ...
  • Content Types - Level 4: Reference
    Level 4: Reference Materials & Static Content NOTE: This is part 5 of 7 in a continuing series; please see earlier posts for more backgr...

Categories

  • .NET
  • .NET nice to have
  • #if DEBUG
  • 15 iunie 2011
  • 15 octombrie 2011
  • 2011
  • abstracta
  • action
  • adaugare
  • ajax
  • Amsterdam
  • Android
  • aplicatii
  • App Fabric
  • Apple iSlate
  • array
  • as
  • ASP.NET
  • AsReadOnly
  • Assembly comun
  • async
  • Asynchronous programming
  • asyncron
  • Autofac
  • AutoMapper
  • az
  • Azure
  • Azure AppFabric Cache
  • Azure backup solution
  • Azure Storage Explorer
  • azure. cloud
  • backup
  • BCP utility
  • bing maps v7
  • BitArray
  • BlackBerry
  • blob
  • BlobContainerPublicAccessType
  • breakpoint
  • bucuresti
  • C#
  • cache
  • CallerMemberName
  • CellCast
  • Certificate
  • CES
  • change
  • ChannelFactory
  • clasa
  • classinitialize
  • clean code
  • click event
  • close
  • Cloud
  • Cluj
  • cluj-napoca
  • Code contracts
  • code retrat
  • codecamp
  • CollectionAssert
  • Compact Edition
  • compara
  • Comparer T .Default
  • CompareTo
  • comparison
  • comunitate
  • concurs
  • Conditional attribute
  • configurare
  • connection string
  • container
  • content type
  • control
  • Convert
  • convertAll
  • convertor
  • cross platform
  • CRUD
  • css
  • custom properties
  • custom request
  • DACPAC
  • Daniel Andres
  • data sync service
  • database
  • date time
  • datetime
  • debug
  • default
  • delegate
  • dependency injection
  • deploy
  • DeploymentItem
  • design patterns
  • Dev de Amsterdam
  • development stoage
  • dictionary
  • diferente
  • digging
  • director
  • Directory.Exist
  • disable
  • dispatcher
  • dispose
  • dropdown
  • dynamic
  • EF
  • email
  • encoding
  • entity framework
  • enum
  • enumerable
  • Environment.NewLine
  • error
  • error 404
  • error handling
  • eveniment
  • event
  • ews
  • excel
  • exception
  • exchange
  • exita
  • explicit
  • export
  • extension
  • field
  • File.Exist
  • finalize
  • fire and forget
  • Fluent interface pattern
  • format
  • func
  • GC.SuppressFinalize
  • generic
  • getdirectoryname
  • globalization
  • gmail
  • hackathon
  • Hadoop
  • handle
  • HTML
  • html 5
  • Html.ActionLink
  • http://www.blogger.com/img/blank.gif
  • HttpModule
  • IComparable
  • IE
  • ienumerable
  • IIS
  • image
  • implicit
  • import
  • int
  • internationalization
  • Internet Explorer
  • interop
  • Ioc
  • IP Filter
  • iPhone
  • iQuest
  • IStructuralEquatable
  • ITCamp
  • itspark
  • java script
  • javascript
  • July 2012
  • KeyedByTypeCollection
  • KeyNotFoundException
  • Kinect SDK
  • lambda expression
  • LightSwitch Microsoft Silverlight
  • linq
  • list
  • lista
  • lista servicii
  • liste
  • Live Connect
  • Live ID
  • load
  • localization
  • lock
  • m-learning
  • MAC
  • Mango
  • map
  • mapare
  • mapare propietati
  • messagequeue
  • meta properties
  • method
  • MethodImpl
  • Metro App
  • Microsoft
  • Microsoft Sync Framework
  • mlearning
  • mlearning devices
  • Mobile Apps
  • mobile in the cloud
  • mobile learning
  • mobile services
  • Mobile Web
  • mongoDb
  • monitorizare
  • msmq
  • multitasking
  • MVC
  • MVC 3
  • MVVM
  • namespace
  • nextpartitionkey
  • nextrowkey
  • Ninject
  • nivel acces
  • no result
  • normalize
  • nosql
  • null expcetion
  • null object pattern
  • NullReferenceException
  • OAuth API
  • office
  • offline
  • Open ID
  • openhackeu2011
  • operations
  • operator
  • optimization
  • option
  • outputcache
  • OutputCacheProvider
  • override
  • paginare
  • pagination
  • path
  • persistare
  • Portable Library tool
  • Post event – CodeCamp Cluj-Napoca
  • predicate
  • predictions
  • prezentare
  • process
  • proiect
  • property
  • propietati
  • query
  • ReadOnlyCollection
  • ReadOnlyDictionary
  • referinta
  • reflection
  • remote
  • reply command
  • request
  • request response
  • resouce
  • REST
  • REST Client
  • RESTSharp
  • ronua
  • rss
  • rulare
  • salvare in fisier
  • sc
  • schimbare timp
  • select
  • select nodes
  • send
  • serializare
  • serialization
  • Server.Transfer. Resposen.Redirect
  • service bus
  • ServiceBase
  • servicecontroller
  • sesiune
  • session
  • Session_End
  • Session_Start
  • setup
  • Sibiu
  • signalR
  • Silverlight
  • sincronizare
  • Single Responsibility Principle
  • SkyDrive
  • skype
  • smartphones
  • smtp
  • Snapguide
  • sniffer
  • socket
  • solid
  • spec#
  • sql
  • Sql Azure
  • SQL CE
  • sql server 2008 RC
  • SRP
  • startuptype
  • stateful
  • stateless
  • static
  • stergere
  • store
  • store procedure
  • stream
  • string
  • string.join
  • struct
  • StructuralEqualityComparer
  • submit
  • switch
  • Symbian
  • Synchronized
  • system
  • tabele
  • table
  • techEd 2012
  • tempdata
  • test
  • testcleanup
  • testinitialize
  • testmethod
  • thread
  • timer
  • ToLower
  • tool
  • tostring
  • Total Cost Calculator
  • trace ASP.NET
  • transcoding
  • tuplu
  • tutorial
  • TWmLearning
  • type
  • unit test
  • unittest
  • UrlParameter.Optional
  • Validate
  • validation
  • verificare
  • video
  • view
  • ViewBag
  • virtual
  • visual studio
  • VM role
  • Vunvulea Radu
  • wallpaper
  • WCF
  • WebBrower
  • WebRequest
  • where clause
  • Windows
  • windows 8
  • Windows Azure
  • Windows Azure Service Management CmdLets
  • windows live messenger
  • Windows Mobile
  • Windows Phone
  • windows service
  • windows store application
  • Windows Task
  • WinRT
  • word
  • workaround
  • XBox
  • xml
  • xmlns
  • XNA
  • xpath
  • YMesseger
  • Yonder
  • Zip

Blog Archive

  • ▼  2013 (139)
    • ►  November (17)
    • ►  October (12)
    • ►  September (10)
    • ▼  August (7)
      • More about 'OnMessage' method of Service Bus
      • Http Request in .NET Compact Edition ended with "U...
      • Control the color of Philips Hue Lamp based on th...
      • Today Software Magazine - number 14 is launched
      • Legacy code, improvement task that are not finished
      • Load Test using Windows Azure and Visual Studio 2013
      • [Post Event] Summer Codecamp at Cluj-Napoca (July ...
    • ►  July (8)
    • ►  June (15)
    • ►  May (12)
    • ►  April (17)
    • ►  March (16)
    • ►  February (9)
    • ►  January (16)
  • ►  2012 (251)
    • ►  December (9)
    • ►  November (19)
    • ►  October (26)
    • ►  September (13)
    • ►  August (35)
    • ►  July (28)
    • ►  June (27)
    • ►  May (24)
    • ►  April (18)
    • ►  March (17)
    • ►  February (20)
    • ►  January (15)
  • ►  2011 (127)
    • ►  December (11)
    • ►  November (20)
    • ►  October (8)
    • ►  September (8)
    • ►  August (8)
    • ►  July (10)
    • ►  June (5)
    • ►  May (8)
    • ►  April (9)
    • ►  March (14)
    • ►  February (20)
    • ►  January (6)
  • ►  2010 (26)
    • ►  December (1)
    • ►  November (1)
    • ►  October (1)
    • ►  June (2)
    • ►  May (1)
    • ►  April (4)
    • ►  March (1)
    • ►  February (1)
    • ►  January (14)
Powered by Blogger.

About Me

Unknown
View my complete profile