Click here to Skip to main content
12,502,346 members (51,503 online)
Click here to Skip to main content

Stats

204.6K views
4.5K downloads
152 bookmarked
Posted

Using jQuery Mobile with MVC and Netduino for Home Automation

, 14 Dec 2012 CPOL
This article is great for anybody learning jQuery Mobile or building mobile applications with MVC3. I built a remote control for my phone to control a squirt gun for my pool, open my garage door, water the garden and control for my gas fireplace using jQuery Mobile with MVC and a Netduino
jQueryMobileCode
LogicalLiving.sln.docstates.suo
LogicalLiving.suo
Netduino.Communication
Properties
Netduino.LogicalLiving
app_code
Content
images
ajax-loader.png
bg-dot.png
btn-facebook.png
btn-flickr.png
btn-twitter.png
ico-book.png
ico-call.png
ico-contact.png
ico-map.png
ico-menu.png
icons-18-white.png
ico-star.png
LA_Logo_Small.jpg
themes
base
images
ui-bg_flat_0_aaaaaa_40x100.png
ui-bg_flat_75_ffffff_40x100.png
ui-bg_glass_55_fbf9ee_1x400.png
ui-bg_glass_65_ffffff_1x400.png
ui-bg_glass_75_dadada_1x400.png
ui-bg_glass_75_e6e6e6_1x400.png
ui-bg_glass_95_fef1ec_1x400.png
ui-bg_highlight-soft_75_cccccc_1x100.png
ui-icons_222222_256x240.png
ui-icons_2e83ff_256x240.png
ui-icons_454545_256x240.png
ui-icons_888888_256x240.png
ui-icons_cd0a0a_256x240.png
images
ajax-loader.png
icons-18-black.png
icons-18-white.png
icons-36-black.png
icons-36-white.png
Controllers
Global.asax
Models
Netduino.LogicalLiving.csproj.user
Properties
Scripts
Views
Home
Shared
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.ComponentModel;

namespace Netduino.Communication
{
   public class MessageEventArgs : EventArgs 
   {
        private string _message;
        public string Message
        {
            get { return _message; }
        }
        public MessageEventArgs(string Message)
        {
            _message = Message;
        }
    }

    public class CommunicateWithNetduino
    {
        #region Private Variables
        private static CommunicateWithNetduino _communicateWithNetduino;
        private Socket _clientSocket = null;
        private Thread _listeningThread;
        private int _port = 80;
        private string _netduinoAddress = null;
        private ISynchronizeInvoke _callingThreadContextToInvoke;
        #endregion

        #region Constructors
        //Enforce that this class is a singleton that other classes can’t instantiate 
        private CommunicateWithNetduino()
        {
        }
        #endregion

        #region Public Properties
        public int Port
        {
            set { _port = value; }
            get { return _port; }
        }
        public string NetduinoAddress
        {
            set { _netduinoAddress = value; }
            get { return _netduinoAddress; }
        }
        #endregion

        #region Events
        public event EventHandler<MessageEventArgs> EventHandlerMessageReceived;
        public event EventHandler<MessageEventArgs> EventHandlerStatusUpdate;
        #endregion

        #region Public Methods
        //Singleton factory method to load and get the single instance
        public static CommunicateWithNetduino GetInstance()
        {
            if (_communicateWithNetduino == null)
            {
                _communicateWithNetduino = new CommunicateWithNetduino();
                _communicateWithNetduino.Port = 8000;
                _communicateWithNetduino.NetduinoAddress = "192.168.40.100";  //IP Address Must be valid for your network

            }

            return _communicateWithNetduino;
        }

        public void StartListening(ISynchronizeInvoke CallingThreadContextToInvoke)
        {
            _listeningThread = new Thread(new ThreadStart(ReceiveSocketsInBackgroundThread));
            _listeningThread.IsBackground = true;
            _listeningThread.Start();
            _callingThreadContextToInvoke = CallingThreadContextToInvoke;
        }

        public void SendMessage(string message)
        {
            if (_netduinoAddress != null && _port > 0)
            {
                using (System.Net.Sockets.Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {

                    //IPHostEntry entry = Dns.GetHostEntry(_netduinoAddress);
                    //IPAddress address = entry.AddressList[0];
                    IPAddress address = IPAddress.Parse(_netduinoAddress);
                    IPEndPoint endpoint = new IPEndPoint(address, _port);

                    try
                    {
                        socket.Connect(endpoint);
                        socket.Send(Encoding.UTF8.GetBytes(message));
                        socket.Close();
                    }
                    catch (SocketException se)
                    {
                        RaiseEvent(EventHandlerStatusUpdate, "Socket Exception! Probably bad ip or netduino not ready?");
                    }
                }
            }
        }
        #endregion

        #region Private Methods
        private bool IsSocketConnected(Socket socket)
        {
            bool connectionNotClosedResetOrTerminated = !socket.Poll(1000, SelectMode.SelectRead);
            bool socketHasDataAvailableToRead = (socket.Available != 0);
            return (connectionNotClosedResetOrTerminated || socketHasDataAvailableToRead);
        }

        private void ReceiveSocketsInBackgroundThread()
        {
            string receiveMessage = "";

            using (System.Net.Sockets.Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                socket.Bind(new IPEndPoint(IPAddress.Any, _port));
                socket.Listen(10);

                while (true)
                {
                    RaiseEvent(EventHandlerStatusUpdate, "Waiting for connection...");
                    _clientSocket = socket.Accept();  //This call is "blocking" and will will wait for a connection, which also means the thread hangs around
                    RaiseEvent(EventHandlerStatusUpdate, "Connection Accepted!");

                    using (_clientSocket)
                    {
                        while (IsSocketConnected(_clientSocket))
                        {
                            int availablebytes = _clientSocket.Available;
                            byte[] buffer = new byte[availablebytes];
                            _clientSocket.Receive(buffer);
                            if (buffer.Length > 0)
                            {
                                receiveMessage = Encoding.UTF8.GetString(buffer);
                                RaiseEvent(EventHandlerMessageReceived, receiveMessage);
                            }
                        }
                    }
                }
            }
        }

        private void RaiseEvent(EventHandler<MessageEventArgs> handler, string message)
        {
            // Event will be null if there are no subscribers
            if (handler != null)
            {
                MessageEventArgs e = new MessageEventArgs(message);
                if (_callingThreadContextToInvoke == null)
                {
                    handler(this, e);
                }
                else
                {
                    //handle cross-thread communication back to the main thread
                    _callingThreadContextToInvoke.Invoke(handler, new object[] { this, e });
                }
            }
        }
        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Dan Thyer
Chief Technology Officer Logical Advantage
United States United States
Dan graduated summa cum laude from North Carolina State University with dual degrees in Electrical Engineering and Computer Engineering. Dan attended NC State on full scholarship program with General Motors. After working with GM, Dan served as application development director for the largest Microsoft Business Solutions Partner in the Carolinas. During this time, Dan's team won two Microsoft Pinnacle awards. For the past 10 years, as Co-Founder and Chief Technology Officer of, Logical Advantage (www.logicaladvantage.com), a software consulting business, Dan has successfully architected and delivered web-based and mobile applications for many Fortune 500 companies. Dan focuses his energies on emerging technologies, and ensuring that all projects are architected to meet the client's current and future needs. Dan collaborates with his Chief Solutions Officer and other architects to create technical standards, including coding standards, tools, and platforms. He holds a leadership role in the local Microsoft Enterprise Developer's Guild and has been on the steering committee for over a dozen years.

You may also be interested in...

Pro
Pro
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160919.1 | Last Updated 14 Dec 2012
Article Copyright 2012 by Dan Thyer
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid