Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Using jQuery Mobile with MVC and Netduino for Home Automation

4.88/5 (52 votes)
14 Dec 2012CPOL9 min read 405.4K   4.8K  
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

Introduction

How often do you lose your remote control?  I hate looking for the remote and family members always seem to hide it from me.  I decided to turn my smartphone into the universal remote control for the house which is perfect for me because I'm almost always an arm's length away from it.  My wife does not feel the same way about her phone so I had to build external controls as well for our home automation.  So far my home automation includes remote controlling a squirt gun for my pool, opening my garage door, watering the garden and I just added control for my gas fireplace!  Be sure to see my article entitled Home Automation with Netduino and Kinect for more information and code examples.

My first attempts at building mobile apps for my home automation projects involved building native apps for Windows Phone 7 and Android.  The apps served their purpose, but other than the backend web services there was no reuse of the code between the apps written for the different mobile operating systems.  The problem was compounded because each family member had their own favorite mobile device with different mobile operating systems.  jQuery Mobile and HTML5 solved the problem of making the remote work across a wide variety of devices.  Now I have one codebase that works on iOS, Android, Windows Phone, and most of the relevant mobile devices. 

Self-Destructing QR Code

QR codes and other 2D barcodes such as Microsoft Tag and Datamatrix have fascinated me for a long time.  Almost any mobile device with a camera can read the 2D QR codes which can direct you to a website, contact information, email address, or Geo Location, just to name a few.  I decided to use a QR code to direct users to my jQuery Mobile website for my home automation.  I did not want anybody who found a printed copy of the QR code to have access to control the home automation, so for extra fun I added a new self-destructing twist like in the old spy movies!

Image 1

Image 2

Scan this QR code or click the link to see a video of the world’s first self-destructing QR code.

jQuery and jQuery Mobile 

jQuery is an extremely popular JavaScript library for building very rich Ajax based web applications.  It is a great library which simplifies the development of building rich web 2.0 applications and it helps the software developers to keep the code simple and concise.  The problem with jQuery alone is that it was written primarily for desktop applications and doesn't have many of the features desired for mobile applications, that is where jQuery Mobile comes into play.  jQuery Mobile is a framework built on top of jQuery and it address the mobile gaps of jQuery.  jQuery Mobile 1.0 was released in November of 2011 and represents a significant milestone in the mobile web space.

The beauty of jQuery Mobile is that it is easy to develop with and that it works well on most relevant mobile devices. The interface configuration is markup driven and you can create basic apps in HTML without adding custom JavaScript.  You can extend your mobile app with JavaScript, but it is surprising how much you can do with plain old HTML.  I only needed to write 2 JavaScript functions for my home automation project and I could have done the entire project without custom JavaScript if I did not have the countdown display for the self-destruct page.

Using jQuery Mobile with MVC3

ASP.NET MVC 3 is a framework for building scalable, standards-based web applications using well-established design patterns. The MVC framework is also great for building mobile web applications with jQuery Mobile. The Razor view engine in particular is extremely helpful to keep you from writing duplicate markup. Razor partial views and custom written @helper methods help you create re-usable templates for your HTML markup. They enable better code reuse, and can also facilitate more readable code. Razor partial views allow you to define common shared parts of a page that can be leveraged by multiple pages in your site or multiple times on the same page in your site.  Razor @helper methods that are placed in the \app_code directory can be re-used across all the views in the project.  I wrote simple @helper methods to make the code cleaner for adding JavaScript and CSS files to the project.  The ASP.NET runtime complies any Razor views in the \app_code directory and makes their helpers available as static methods.

HTML
@helper Script(string scriptName, UrlHelper url) {
    <script src="@url.Content("~/Scripts/" + scriptName)" type="text/javascript"></script>
}

@helper Css(string cssName, UrlHelper url) {
    <link href="@url.Content("~/Content/" + cssName)" rel="stylesheet" type="text/css" />
}

Razor layouts are analogous to the familiar ASPX master page. They allow you to define elements you want to be common across your site and define the regions of a page that you want specific views to render.  For a jQuery Mobile site the layout needs to include the CSS files for the app, the JavaScript libraries for the app, and set the viewport so that the app displays sized correctly on a mobile device.  I have 3 CSS files for the app.  jQuery Mobile has its own styles that you must include.  I themed the site using the ThemeRoller tool which generated the CSS for the theme.  The ThemeRoller tool will be talked about in greater detail later in the article.  The third CSS file is the Site.css file for any additional CSS that I needed that the ThemeRoller tool did not generate for me.

HTML
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    
    @Content.Css("jquery.mobile-1.0.min.css", Url)
    @Content.Css("themes/LogicalLiving.css", Url)
    @Content.Css("Site.css", Url)
    @Content.Script("jquery-1.7.1.min.js", Url)
    @Content.Script("jquery.unobtrusive-ajax.min.js", Url)
    @Content.Script("jquery.mobile-1.0.min.js", Url)
    @Content.Script("LogicalLiving.js",Url)
 
    <meta name="viewport" content="initial-scale=1, maximum-scale=1">
</head>
<body>
    @RenderBody()
</body>
</html>

All jQuery Mobile sites require references to the jQuery JavaScript file and the jQuery mobile JavaScript file.  I added a reference to the jquery.unobtrusive-ajax for additional Ajax functionality and to LogicalLiving.js JavaScript file for the custom JavaScript for my project. In HTML5, the <meta> tag is used to define metadata for the HTML document.  The <meta name="viewport"/> meta tag is used to control how HTML content will appear in mobile browsers so that the content is sized correctly for the device.

Data Attributes

The jQuery Mobile framework uses HTML5 "data-" attributes to allow for markup-based initialization and configuration. The data attributes allow you to add simple metadata to individual elements that are interpreted by the jQuery Mobile JavaScript functions.

HTML
<div data-role="header">Defines a header toolbar for the app</div>


<div data-role="header" data-position="fixed">Defines a header toolbar for the app that holds its position when the user scrolls down</div>


<div data-role="content">Defines a content area for the mobile page</div>


<div data-role="footer">Defines a footer area for the mobile page</div> 

Pages in jQuery Mobile can be single pages or internal linked pages within a page. A single HTML document can contain multiple pages that are loaded together and separated out by <div> tags. jQuery Mobile uses Ajax to show the appropriate page. I load all of my pages into <div>s for the mobile app in the Index.cshtml view. 

HTML
@{ ViewBag.Title = "Logical Living"; }
 
<div data-role="page" id="home" data-theme="a">
    @Html.Partial("_Menu")
</div>
 
<div data-role="page" id="pool" data-theme="a">
    @Html.Partial("_Pool")
</div>
 
<div data-role="page" id="garden" data-theme="a">
    @Html.Partial("_Garden")
</div>
 
<div data-role="page" id="fireplace" data-theme="a">
    @Html.Partial("_Fireplace")
</div>
 
<div data-role="page" id="garage" data-theme="a">
    @Html.Partial("_Garage")
</div>
 
<div data-role="page" id="about" data-theme="a">
    @Html.Partial("_About")
</div>
 
<div data-role="page" id="contact" data-theme="a">
    @Html.Partial("_Contact")
</div>
 
<div data-role="page" id="destruct" data-theme="a">
    @Html.Partial("_Destruct");
</div>

I organized each page as a partial view to break the code into more manageable segments. Below is a sample of the _About.cshtml partial view:

HTML
@Html.Partial("_Header", new Netduino.LogicalLiving.Models.HeaderModel { HeaderText = "About" ,ShowBackButton=true})
<div data-role="content"> 
    <div class="center-text">
        <p><b>Logical Living</b></p>
        <div>Version 1.0</div>
        <p>This app rocks!</p> 
        <div>Written by:</div>
        <div><a href="#contact">Dan Thyer</a></div>   
    </div>
</div>
@Html.Partial("_Footer")

Each page includes partial views for the _Header.cshtml and the _Footer.cshtml. This allowed me to write the header and footer one time and have them re-used on all of the internal pages. Notice the hyperlink: <a href="#contact">Dan Thyer</a> jQuery Mobile knows that to display the "#contact" page means to display the HTML inside the <div> tag with the data-role="page" with an id of "contact".

HTML
<div data-role="page" id="contact" data-theme="a"> 

Talking to the Hardware

With my jQuery Mobile app, most of the code is running locally on the device.  I wrote a MVC controller method that runs on the server to talk to the Netduino called SendMessageToNetduino.  The method is called using Ajax from the mobile device.  

C#
public ContentResult SendMessageToNetduino(string message, string status)
{
    bool sendToNetduino = bool.Parse(WebConfigurationManager.AppSettings["SendToNetduino"]);
    if (sendToNetduino)
    {
        CommunicateWithNetduino.GetInstance().SendMessage(message);
    }

    return Content(status);
}
The method is a simple pass-through that takes a message sent from Ajax from the mobile device over the internet, and then relays the message behind the firewall over the local network to the Netduino .net microcontroller. The Netduino Plus is a microcontroller that runs C# in the .Net Micro Framework. The Netduino Plus has a built in Ethernet adapter for network communication. For more information and code examples of how to talk with the microcontroller, please read my article entitled Home Automation with Netduino and Kinect

Image 3

The above image shows the communication between the jQuery Mobile app and the Netduino microcontroller.  Note that the same jQuery Mobile app runs on multiple devices with different mobile operating systems.

I wrote a MVC Razor @helper method to encapsulate the logic required to talk to the Netduino.  

HTML
@helper NetduinoButton(string buttonText, string netduinoMessage, string statusMessage, string dataIcon, AjaxHelper ajax) {
    @ajax.ActionLink(buttonText, "SendMessageToNetduino", "Home",
        new {
            message = netduinoMessage,
            status = statusMessage
        },
        new AjaxOptions {
            UpdateTargetId = "serverMessage",
            InsertionMode = InsertionMode.Replace,
            HttpMethod = "Get"
        },
        new { 
            data_role = "button", 
            rel = "external", 
            data_icon = dataIcon,
            data_theme ="a"
        })
} 

With my NetduinoButton @helper method, adding a button to control a device can be done in view by adding a simple line of code.  The code below adds a button the open the garage door.

HTML
@Content.NetduinoButton("Garage", "C", "Garage Door.", "", Ajax) 

Below is the _Pool.cshtml view to control the squirt gun. Notice how nicely the logic is encapsulated into the @Content.NetduinoButton method call to prevent duplication of the code.

HTML
@Html.Partial("_Header", new Netduino.LogicalLiving.Models.HeaderModel { HeaderText = "Pool" ,ShowBackButton=true})
<div data-role="content"> 
    <div data-role="controlgroup">
        @Content.NetduinoButton("Trace Shallow End","1","Trace shallow end.","", Ajax)
        @Content.NetduinoButton("Trace Pool", "2", "Trace pool.", "", Ajax)
        @Content.NetduinoButton("Get People Wet", "3", "Get people wet!", "", Ajax)
    </div>
    <br />
    
    <div style="margin-left:max;margin-right:max;">
    @Content.NetduinoButton("Up", "U 5", "Move up.", "arrow-u", Ajax)
    
    <div data-role="controlgroup" data-type="horizontal" style="text-align:center">
        @Content.NetduinoButton("Left", "L 5", "Move left.", "arrow-l", Ajax)
        @Content.NetduinoButton("Home", "H", "Move home.", "home", Ajax)
        @Content.NetduinoButton("Right", "R 5", "Move right.", "arrow-r", Ajax)
    </div>

    @Content.NetduinoButton("Down", "D 5", "Move down.", "arrow-d", Ajax)
    </div>

    <br />
    <div data-role="controlgroup" data-type="horizontal">
        @Content.NetduinoButton("On", "O", "Turned water on.", "", Ajax)
        @Content.NetduinoButton("Off", "F", "Turned water off.", "", Ajax)
    </div>
</div>
@Html.Partial("_Footer") 

The screen shots below show several samples of the pages in the application. All of the buttons in the body of the pool and fireplace pages are samples of the NetduinoButton.

Image 4

Theming

jQuery Mobile is designed around an object-oriented CSS framework that applies a theme to your mobile applications. The theming takes advantage of CSS3 properties to add good looking rounded corners, box and text shadows, and gradients. It takes advantage of CSS3 properties as much as possible to reduce need for images which have heaver server requests for downloading.

ThemeRoller

jQuery Mobile provides a cool web tool to help developers create nice themes for their mobile sites. This tool is called the ThemeRoller, http://jquerymobile.com/themeroller/index.php, and it can be utilized by programmers, graphic designers or even novices to create good looking themes for mobile sites.

Image 5

The image above shows two swatches labeled A and B for the ThemeRoller. Each swatch can have its own styles applied to it. jQuery Mobile can have up to 26 swatches (A-Z) in an application. The theme can be set for the HTML elements on the page by setting the elements data-theme attribute to its swatch letter: data-theme="a" or data-theme="b". From the swatches shown in the theme above, the button style can be set to orange by setting the data-theme="a" or the white by setting data-theme="b".

Conclusion

With jQuery Mobile and HTML5 you can build mobile websites and applications that work on most of the relevant mobile operating systems and devices. The MVC framework works well with jQuery Mobile to keep you from writing duplicate code. The Razor view engine enables better code reuse and also facilitates more readable code. jQuery Mobile allows you to theme your mobile websites/apps to look great like native apps.

Microsoft MSDN Channel9 Coding4Fun featured my project: Home Automation with some help from jQuery Mobile MVC and Netduino

License

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