I want to start this post by telling you how far is the light switch in my bedroom from my bed: VERY FAR. Sometimes I'm all tired, lying in my bed thinking "wouldn't it be awesome if I could control that switch from here?", of course I can always use a broom stick or something like that, but when you have other options this kind of posts are born.

Now, the actual post: I decided to create an app to easily turn on or off my bedroom's light not only from my Windows Phone but from my iPod or any other device in my house. I'll try to explain how I did it.

Server (Netduino)

The system consists of two parts: Server and client. The server will be responsible of controlling the lightswitch and of always be listening for incoming requests.



Speaking of hardware, I used a Netduino Plus 2, a Groove Relay (to handle high voltages), some resistors and of course wire. I won't dig a lot on the wiring but if you want I could help you with that, just ask.

Speaking of software, this is really a simple app, I created a class that works as an interface, it abstracts the usage of stream sockets. Taking advantage of the multithreading capabilities of the NetMF I created thread in which a socket is always waiting for incoming connections, and when one arrives reads two bytes from it, the first one contains the operation to be performed and the second one contains data when is a writing operation. I make use of delegates to get or set the light switch status from the main thread.

byte[] data = new byte[2];
while (true)
{
    using (Socket client = server.Accept())
    {
        client.Receive(data, 0, 2, SocketFlags.None);
        if (((char)data[0]) == WriteLightSwitchState)
        {
            if (OnLampStatusChangeRequest != null)
            {
                OnLampStatusChangeRequest(this, new BooleanEventArgs(((char)data[1]) == ByteTrue));
            }
        }
        else if (((char)data[0]) == ReadLightSwitchState)
        {
            var args = new BooleanEventArgs(false);
            if (OnLampStateRequest != null)
            {
                // Using the delegate we should tell the app whether the switch is on or off
                OnLampStateRequest(this, args);
            }
            data[0] = args.Data ? ByteTrue : ByteFalse;
            client.Send(data, 0, 1, SocketFlags.None);
        }
    }
}

Client (Xamarin.Forms app)

The client only has a single purpose: replace the mechanical switch. It isn't very hard to think of the UI of an app to do that.

UI

I didn't burn my brain out thinking of the UI, after all it is just a switch, and that is precisely what I used, a Switch that will trigger a request to the Netduino on every toggle.

Using Sockets in a Xamarin.Forms app

Like the server, the client has a kind of "interface" that abstracts the usage of sockets in our app. Let's stop for a minute, when I first thought of this app I was wondering of how to manage sockets from a Forms application. I'd create a plugin and handle each platform indepently, but searching I came along with this really, really cool plugin: rda.SocketsForPcl, it provides a fully functional set of classes to deal with sockets in every platform (even on iOS!). It is great to have a community creating stuff that you can use in your projects. With the socket issue solved, let's move on.

There are two important methods whithin the "interface" class:

public async Task<bool> GetLightSwitchStatus()
{
    using (var s = new Sockets.Plugin.TcpSocketClient())
    {
        await s.ConnectAsync(NetduinoIp, Port);
        byte[] data = new byte[2];
        data[0] = ReadLightSwitchState;
        data[1] = ReadLightSwitchState;
        s.WriteStream.Write(data, 0, 2);
        s.ReadStream.Read(data, 0, 1);
        return data[0] == ByteTrue;
    }
}

The above piece of code request the switch status from the server and returns true or false, depending on the status of the light switch.

public async Task SetLightSwitchStatus(bool on)
{
    using (var s = new Sockets.Plugin.TcpSocketClient())
    {
        await s.ConnectAsync(NetduinoIp, Port);
        byte[] data = new byte[2];
        data[0] = WriteLightSwitchState;
        data[1] = (byte)(on ? ByteTrue : ByteFalse);
        s.WriteStream.Write(data, 0, 2);
    }
}

This piece of code sends a request to the server telling which state the light swich shoud be set to. Note how all the exchange of information is done via bytes, the first byte tells the server which operation is requested while the second one contains data when necessary. In the following vídeo I show the system working, though I still haven't wired the actual light bulb (since I'm scared of the high voltage), so I placed a 12V led instead for the demo.

What next?

Well, this isn't really IoT as you may know it because this has little to do with the internet since the traffic is local, but I consider it to be a good starting point to build something more complex. For the next Netduino + Xamarin post I'll create a system that sends a notification over to my phone everytime someone opens my bedroom door, for that I'll use Parse, please fill in the sign up if you want me to keep you updated.