Sunday, 7 July 2013

Accessing the web with Gadgeteer ethernet module

I've discovered just how easy it is to use the Gadgeteer Ethernet J11D module from GHI Electronics to retrieve resources from the web. As ever, here's the project designer:

As for the code, it can be summed up in 3 steps:

  1. Get/supply an IP address
  2. Send a HTTP request to the URI
  3. Handle the HTTP response

using Gadgeteer.Networking;
using NetworkModule = Gadgeteer.Modules.Module.NetworkModule;
using Gadgeteer;

namespace Demo
{
    public partial class Program
    {
        void ProgramStarted()
        {
            //The other option is UseStaticIP
            ethernet.UseDHCP();

            //Set a handler for when the network is available
            ethernet.NetworkUp += ethernet_NetworkUp;
        }

        void ethernet_NetworkUp(NetworkModule sender, NetworkModule.NetworkState state)
        {
            //Set the URI for the resource
            var url = "http://i1072.photobucket.com/albums/w367/"
                + "M_J_O_N_E_S/MeGadgeteerSize_zps23202046.jpg?t=1373144748";

            //Create a web request
            var request = WebClient.GetFromWeb(url);

            //This is async, so set the 
            //handler for when the response received
            request.ResponseReceived += request_ResponseReceived;

            //Send the request
            request.SendRequest();
        }

        void request_ResponseReceived(HttpRequest sender, HttpResponse response)
        {
            if (response.StatusCode == "200")
            {
                //This only works if the bitmap is the 
                //same size as the screen it's flushing to
                response.Picture.MakeBitmap().Flush();
            }
            else
            {
                //Show a helpful error message
                lcd.SimpleGraphics.DisplayText("Request failed with status code " + response.StatusCode
                    , Resources.GetFont(Resources.FontResources.NinaB), Color.White, 0, 0);

                lcd.SimpleGraphics.DisplayText("Response text: " + response.Text
                       , Resources.GetFont(Resources.FontResources.NinaB), Color.White, 0, 50);

            }
        }
    }
}

Here's the result of the code:

And an example of when things don't go according to plan:

The web request can't only be used to download picture resources; if you request a run-of-the-mill HTML page, you are able to access the streamed response:


The code for this demo is available here on GitHub

No comments:

Post a Comment