LED Controller – Android & Netduino

In Visual Studio (for the Netduino) you need to write the following code:

Class: Program.cs


using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.Netduino;

namespace NetduinoApplication2WebServer
{
    public class Program
    {

        //the output ports that control the LEDs on the breadboard
        static OutputPort greenLED = new OutputPort(Pins.GPIO_PIN_D0, false);
        static OutputPort redLED = new OutputPort(Pins.GPIO_PIN_D1, false);

        public static void Main()
        {
            //set up the LED and turn it off by default
            OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);
           

            // configure the port # (the standard web server port is 80)
            int port = 80;

            // wait a few seconds for the Netduino Plus to get a network address.
            Thread.Sleep(5000);

            // display the IP address
            Microsoft.SPOT.Net.NetworkInformation.NetworkInterface networkInterface = Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0];
            Debug.Print("my ip address: " + networkInterface.IPAddress.ToString());

            // create a socket to listen for incoming connections
            Socket listenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            IPEndPoint listenerEndPoint = new IPEndPoint(IPAddress.Any, port);

            // bind to the listening socket
            listenerSocket.Bind(listenerEndPoint);

            // and start listening for incoming connections
            listenerSocket.Listen(1);


            // listen for and process incoming requests
            while (true)
            {
                // wait for a client to connect
                Socket clientSocket = listenerSocket.Accept();


                // wait for data to arrive
                bool dataReady = clientSocket.Poll(5000000, SelectMode.SelectRead);

                // if dataReady is true and there are bytes available to read,
                // then you have a good connection.
                if (dataReady && clientSocket.Available > 0)
                {

                    byte[] buffer = new byte[clientSocket.Available];
                    int bytesRead = clientSocket.Receive(buffer);

                    string request = new string(System.Text.Encoding.UTF8.GetChars(buffer));

                    Debug.Print(request);
                    string response = String.Empty;

                    if (request.ToLower().IndexOf("bulbname=") != -1 && request.ToLower().IndexOf("bulbstatus=") != -1)
                    {
                        //filter the request message
                        string bulbName = request.Substring(request.IndexOf("bulbName="), (request.IndexOf("&") - request.IndexOf("bulbName=")));
                        bulbName = bulbName.Substring(bulbName.IndexOf("=") + 1, (bulbName.Length - 1) - bulbName.IndexOf("="));

                        string bulbStatus = request.Substring(request.IndexOf("bulbStatus="), request.Length - request.IndexOf("bulbStatus="));
                        bulbStatus = bulbStatus.Substring(bulbStatus.IndexOf("=") + 1, (bulbStatus.Length - 1) - bulbStatus.IndexOf("="));


                        //turn on/off LEDs 
                        if (bulbName.ToLower() == "green")
                        {
                            LedController(greenLED, bulbStatus.ToLower() == "true");
                        }
                        else
                        {
                            LedController(redLED, bulbStatus.ToLower() == "true");
                        }


                        string statusMessage = "greenLed=" + greenLED.Read() + "&redLed=" + redLED.Read();
                                                
                        response= "HTTP/1.1 200 OK\r\n" +
                            "Content-Type: text/html; charset=utf-8\r\n\r\n" + statusMessage;
                    }
                    else
                    {
                        response = "HTTP/1.1 200 OK\r\n" +
                        "Content-Type: text/html; charset=utf-8\r\n\r\n" + "error";
                    }


                    clientSocket.Send(System.Text.Encoding.UTF8.GetBytes(response));
                }

           
                // important: close the client socket
                clientSocket.Close();

            }

     
        }

        private static void  LedController(OutputPort led, bool ledStatus)
        {
            led.Write(ledStatus);
        }

    }
}




In Android Studio you need to write the following code:

Class: MainActivity.java


package com.controller.bulbs.bulbscontroller;

import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;



public class MainActivity extends ActionBarActivity {

    Boolean bulbGreenOn =false;
    Boolean bulbRedOn =false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }
    }


    public void ButtonRed_ClickEvent(View view) throws IOException {

        bulbRedOn = !bulbRedOn;
        sendPostRequest("red",bulbRedOn.toString(), ((EditText) findViewById(R.id.txtIpAddressNetduino)).getText().toString());

    }

    public void ButtonGreen_ClickEvent(View view) throws IOException {

        bulbGreenOn = !bulbGreenOn;
        sendPostRequest("green",bulbGreenOn.toString(),((EditText) findViewById(R.id.txtIpAddressNetduino)).getText().toString());
    }


    private void sendPostRequest(String bulbName, String bulbStatus, String IpAddressNetduino) {

        //Async Task needs to be created because Android needs to have a seperate thread and avoid problems with the GUI thread
        class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {

            @Override
            protected String doInBackground(String... params) {

                String bulbName = params[0];
                String bulbStatus = params[1];
                String IpAddressNetduino = params[2];

                HttpClient httpClient = new DefaultHttpClient();

                // create HttpPost
                HttpPost httpPost = new HttpPost("http://" + IpAddressNetduino+"/BulbController");
                httpPost.removeHeaders("Content-Length");


                //Paramaters we need to pass with the POST request
                BasicNameValuePair bulbNameBasicNameValuePair = new BasicNameValuePair("bulbName",  bulbName);
                BasicNameValuePair bulbStatusBasicNameValuePAir = new BasicNameValuePair("bulbStatus", bulbStatus);


                List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
                nameValuePairList.add(bulbNameBasicNameValuePair);
                nameValuePairList.add(bulbStatusBasicNameValuePAir);

                try {
                    //An entity composed of a list of url-encoded pairs. This is typically useful while sending an HTTP POST request.
                    UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);

                    httpPost.setEntity(urlEncodedFormEntity);

                    try {

                        HttpResponse httpResponse = httpClient.execute(httpPost);

                        InputStream inputStream = httpResponse.getEntity().getContent();

                        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

                        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

                        StringBuilder stringBuilder = new StringBuilder();

                        String bufferedStrChunk = null;

                        while((bufferedStrChunk = bufferedReader.readLine()) != null){
                            stringBuilder.append(bufferedStrChunk);
                        }

                        return stringBuilder.toString();

                    } catch (ClientProtocolException cpe) {

                        cpe.printStackTrace();
                    } catch (IOException ioe) {

                        ioe.printStackTrace();
                    }

                } catch (UnsupportedEncodingException uee) {

                    uee.printStackTrace();
                }

                return null;
            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);

                if(!result.equals("error"))
                {
                    //Analyse response by netduino
                    String [] strarr = result.split("&");
                    Boolean greenLedStatus =  strarr[0].replace("greenLed=","").toLowerCase().equals("true");
                    Boolean redLedStatus = strarr[1].replace("redLed=","").toLowerCase().equals("true");

                    bulbGreenOn = greenLedStatus;
                    bulbRedOn = redLedStatus;

                    //visually turn on/off bulbs on the app
                    if(greenLedStatus)
                    {
                        ((ImageButton)findViewById(R.id.imgBtnGreen)).setImageResource(R.drawable.greenbulb);
                    }
                    else
                    {
                        ((ImageButton)findViewById(R.id.imgBtnGreen)).setImageResource(R.drawable.greybulb);
                    }

                    if(redLedStatus)
                    {
                        ((ImageButton)findViewById(R.id.imgBtnRed)).setImageResource(R.drawable.redbulb);
                    }
                    else
                    {
                        ((ImageButton)findViewById(R.id.imgBtnRed)).setImageResource(R.drawable.greybulb);
                    }
                }

            }
        }

        SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
        sendPostReqAsyncTask.execute(bulbName, bulbStatus, IpAddressNetduino);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }
    }
}


Fragment_main.XML


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity$PlaceholderFragment">


    <ImageButton
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:id="@+id/imgBtnGreen"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:scaleType="fitCenter"
        android:src="@drawable/greybulb"
        android:onClick="ButtonGreen_ClickEvent"/>

    <ImageButton
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:id="@+id/imgBtnRed"
        android:layout_below="@+id/imgBtnGreen"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="25dp"
        android:scaleType="fitCenter"
        android:src="@drawable/greybulb"
        android:onClick="ButtonRed_ClickEvent"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="IP Address of Netduino"
        android:id="@+id/textView"
        android:layout_below="@+id/imgBtnRed"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="35dp" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/txtIpAddressNetduino"
        android:layout_below="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignRight="@+id/textView"
        android:layout_alignEnd="@+id/textView" />


</RelativeLayout>


Bibliography
Walker, C. (2012). Getting started with Netduino. O’Reilly Media.

Advertisements

2 thoughts on “LED Controller – Android & Netduino

  1. Hi,
    could you please upload the entire project?
    Because the resourses on drawable are missing.
    Thnak you!

    One more thing, do you connect yournetduino directly to the router?

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s