Using HTTP with the LinkIt ONE development board

Introduction

This tutorial uses the LinkIt ONE development board’s Wi-Fi features to send and receive Hypertext Transfer Protocol (HTTP) requests to enable communications between clients and servers. For example, a web browser may be the client, and an application on a computer that hosts a website may be the server. In this case a client (browser) submits an HTTP request to the server, then the server returns a response to the client. The response contains status information about the request and may also contain the requested content.

By the end of this tutorial you’ll have a full understanding on how to send HTTP request and read the response from the server.

This tutorial guides you through:

  • Building the prototype, with details of the hardware requirements and how to put them together to enable sending and receiving HTTP requests.
  • Creating the software to provide the interfaces with the client and the server.

At the end of the tutorial there are details on where to go for additional information on the LinkIt ONE development board and how to create software for it.

Before you start

If you haven't built a LinkIt ONE project before, download and install the Arduino IDE and LinkIt ONE SDK then configure the IDE and upgrade the board’s firmware. Details on how to do this are provided in the LinkIt ONE get started guide.

Building the HTTP communication hardware

This section describes the hardware and electronics needed to build the HTTP communication hardware and provides details on how to put them together.

What you need

To build the HTTP communication hardware, you’ll need LinkIt ONE development board with the following components:

ComponentDescriptionSource
AntennasWi-Fi/Bluetooth antennaLinkIt ONE HDK
CableMicro-USB cable 
PowerPolymer Li-ion 1000mAh batteryLinkIt ONE HDK

Putting the components together

Setup the LinkIt ONE development board as follows.

  1. Attach the dual purpose Wi-Fi/Bluetooth antenna its corresponding pins on the LinkIt ONE development board.
  2. Attach the power source. In this tutorial a polymer lithium-ion battery is used, one is included in the LinkIt ONE HDK. Attach the battery source to the Li-Battery (3.7~4.2V) socket.

The final setup of the components is shown below.

Hardware setup for the HTTP communication 

Create your HTTP communication software

Your HTTP send and receive requests need an Arduino Sketch to connect to a website using the Wi-Fi functionality of the LinkIt ONE development board. Two commonly used methods for a request-response between a client and server are GET and POST.

  • GET — Requests data from a specified resource.
  • POST — Submits data to be processed to a specified resource.

This section describes the software required to GET and POST requests with three different Arduino sketches:

  • Obtain JSON object from the server using GET.
  • Download and read a file from the server using GET.
  • POST a JSON object to the server and receive a response.

A detailed overview of each Arduino sketch is provided.

Create the Arduino sketch

To send an HTTP request and read a response from the server an Arduino sketch is needed. This tutorial uses one of the example sketches included in the Arduino IDE, which is opened as follow

  1. Open the Arduino IDE and by default a new sketch is created and displayed.
  2. On the File menu click Examples, then point to LWiFi to list the available examples.
  3. Click WifiWebClient.ino to open the example project as shown below.

Example application from LWiFi library in the Arduino IDE

Overview of the Arduino sketch

The content of the sketch is as follows:

  • Definitions of header files.
  • Definitions of variables.
  • setup() function that initializes resources, such as the Wi-Fi module.
  • loop() function where you add the code to continuously listen to and process events from hardware and software modules, such as those for Wi-Fi and HTTP communications. The loop() function runs forever — until the device is shutdown.

Add the header files for the supporting libraries

The first part of your code adds the libraries required for the WifiWebClient.ino Arduino sketch. LWiFi and LwiFiClient provide the Wi-Fi connectivity support.

#include "LTask.h" 
#include "LWiFi.h" 
#include "LWiFiClient.h"

Define the variables that configure the AP settings

Next the definitions provide the SSID and password to connect to an available AP, the connectivity method and the site URL to connect to. The site URL will be modified depending on the application requirements in the following sections.

#define WIFI_AP "your_ap_ssid"
#define WIFI_PASSWORD "your_password" 
#define WIFI_AUTH LWIFI_WPA  // choose from LWIFI_OPEN, LWIFI_WPA, or LWIFI_WEP. 
#define SITE_URL "labs.mediatek.com" 

Define LWiFiClient object c for further use.

LWiFiClient c;

Initiate the setup() function

Now the setup() function is defined, to start the various services that will be used by the sketch.

  1. Initiates Wi-Fi communication followed by Serial communication with a baud rate of 115200.

    void setup() 
    {
      LWiFi.begin(); 
      Serial.begin(115200);
  2. Prints a message “Connecting to AP” to the serial output and in a while loop calls the connect() method of the LWiFi class every second until a connection is established.

      // keep retrying until connected to AP 
      Serial.println("Connecting to AP"); 
      while (0 == LWiFi.connect(WIFI_AP, LWiFiLoginInfo(WIFI_AUTH, WIFI_PASSWORD))) 
      { 
        delay(1000); 
      } 
  3. In a while loop attempts to connect to the website once a second, by calling the connect() method of the LWiFiClient object c until a connection is established.

      // keep retrying until connected to website 
      Serial.println("Connecting to website");
      while (0 == c.connect(SITE_URL, 80))
      {
        Serial.println("Re-Connecting to website");
        delay(1000);
      } 

  4. Sends the HTTP GET request. Here you’ll implement one of the three options for using the HTTP GET method in your Arduino sketch, as follows:
    1. Send a HTTP GET request to the defined URL using this code.

        Serial.println("send HTTP GET request");
        c.println("GET / HTTP/1.1");
        c.println("Host: " SITE_URL);
        c.println("Connection: close");
        c.println();
    2. Obtain a JSON object from the server using HTTP GET method, using this code.
      • Replace the SITE_URL (set up in Define the variables that configure the AP settings) with the following:

        #define SITE_URL "download.labs.mediatek.com "  //configure the hostname
      • Send a HTTP GET for a specific file to the defined URL using this code:

          Serial.println("send HTTP GET request");
          c.println("GET /package_mtk_linkit_index.json HTTP/1.1");//modify the GET path
          c.println("Host: " SITE_URL);
          c.println("Connection: close");
          c.println();
    3. Read and download a file from the server using HTTP GET method, using this code:
      • Replace the SITE_URL (set up in Define the variables that configure the AP settings) with the following:

        #define SITE_URL "textfiles.com"            //configure the hostname
      • Send a HTTP GET for a specific file to the defined URL using this code:

          // send HTTP request, ends with 2 CR/LF
          Serial.println("Connected. Sending HTTP GET Request ....");
          c.println("GET /100/ad.txt HTTP/1.1"); //modify the GET path
          c.println("Host: " SITE_URL);
          c.println("Connection: close");
          c.println();
    Once one of these options is implemented in your setup() function, proceed with the rest of the code.

  5. The HTTP POST method.

    char thisData[128];                     //create a char array for sending data 
    //send the header
    c.println("POST / HTTP/1.1");           //define POST path
     
    c.println("Host: " SITE_URL);           //define hostname  
    c.println("Connection: close");
     
    c.println(“Content-Type: application/json”);     //define Content-Type 
    c.print("Content-Length: ");                     //define Content-Length 
    c.println(strlen(thisData));
    c.println();
     
    // send the body (variables)
    c.print(thisData);
  6. Waits for the server to respond. Checks in the while loop if the LWiFiClient object is still available every 100 milliseconds.

      Serial.println("waiting HTTP response:");
      while (!c.available())
      {
        delay(100);
      }

Add the loop() function

Declare a global boolean variable that will be used later to indicate if the connection was disconnected.

boolean disconnectedMsg = false;

The loop() function executes continuously, printing the HTTP response content on the Serial output. It does this by calling theread() method of the LWiFiClient object to read the response from the server.

  // Make sure we are connected, and dump the response content to Serial
  while (c)
  {
    int v = c.read();
    if (v != -1)
    {
      Serial.print((char)v);
    }

If there is no more content to present, call the stop() method of the LWiFiClient object.

  else
  {
    Serial.println("no more content, disconnect");
    c.stop();
    while (1)
    {
      delay(1);
    }
  }
}

But, it nothing was returned, assume the server disconnected before responding.

if (!disconnectedMsg)
  {
    Serial.println("disconnected by server");
    disconnectedMsg = true;
  }
  delay(500);
}

Post a JSON object to a server and receive a response

Now that you’ve learned the basics of HTTP GET and POST methods here is a more advanced implementation to post a JSON object to the server and receive a response. In addition to sections Add the header files for the supporting libraries and Define the variables that configure the AP settings define the site URL as follows.

#define SITE_URL "httpbin.org"     //configure the hostname

Define parameters for temperature in Fahrenheit (tempF) and Celsius (tempC), pressure (pressure) and humidity (humidity).

int tempF = 50;
int tempC = 15;
int pressure = 15;
int humidity = 15;  

Create a JSON object by calling the buildJson() method to format the data as follows.

//build JSON method
String buildJson() {
  String data = "{";
  data+="\n";
  data+= "\"d\": {";
  data+="\n";
  data+="\"temperature (F)\": ";
  data+=tempF;
  data+= ",";
  data+="\n";
  data+="\"temperature (C)\": ";
  data+=tempC;
  data+= ",";
  data+="\n";
  data+="\"pressure\": ";
  data+=pressure;
  data+= ",";
  data+="\n";
  data+="\"humidity\": ";
  data+=humidity;
  data+="\n";
  data+="}";
  data+="\n";
  data+="}";
  return data;
}

Follow the description in Initiate the setup() function and Add the loop() function to replace the POST method with:

  // send HTTP request, ends with 2 CR/LF
  String PostData = buildJson();
  Serial.println("Connected. Sending HTTP GET Request ...."); 
  c.println("POST /post HTTP/1.1");  //modify the POST path
  c.println("Host: " SITE_URL);
  c.println("Connection: close");
  c.print("Content-Length: ");
  c.println(PostData.length());
  c.println();
  c.println(PostData);  //send the HTTP POST body
   
  // waiting for server response
  Serial.println("waiting HTTP response:");
  while (!c.available())
  {
    delay(100);
  }
}

Run your application

With the code complete, you can now upload the sketch to your board.

  • Ensure that you board is connected to your computer with the micro-USB cable.
  • Confirm that your board is in SPI mode, by checking the SPI/SD Card switch. The switch should be in the position closest the LED.
  • On the Arduino IDE File menu, click Upload, or click the upload icon.
  • Wait for a moment. If everything is correct, a Done Uploading message will display in the Arduino IDE.

Once this is completed, the application will be running on the board. You can then monitor the serial output in the Arduino IDE's serial monitor, which is opened from the File menu by clicking Serial Monitor. There you’ll see something similar to the following:

Obtaining a JSON object from the server using GET

Read and download a file from the server using the HTTP GET method

POST JSON object to the server and receive a response

Your next steps

In this tutorial you’ve implemented the GET and POST HTTP methods using the Wi-Fi functionality of the LinkIt ONE development board using the Arduino IDE.

You can modify and run the same application using the GSM/GPRS connectivity capabilities of the LinkIt ONE development board. The implementation will require use of the GSM/GPRS antenna (included in the LinkIt ONE HDK) and a micro-SIM card supporting GSM/GPRS communication with a network provider operating in the 850/900/1800/1900 MHz frequency range and classified as Class 12 with 2G data plan enabled.

For more information on MediaTek LinkIt ONE development and creating proof-of-concepts with the board refer to LinkIt ONE developer’s guide.