Go Down

Topic: Arduino WiFi Shield (Read 3 times) previous topic - next topic

kazimurtaza

just so you guys could understand the whole app, I will the android side of code as well;

MainActivity
Code: [Select]

package com.lamp.test.v1;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.mycar.other.ConnectionManager;
import com.mycar.other.HttpManager;

public class MainActivity extends Activity implements OnClickListener {

public Button on;
public Button off;

public List<NameValuePair> data;

@SuppressLint({ "NewApi", "NewApi", "NewApi" })
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

setTitle("My Lamp Test v1");

this.on = (Button) findViewById(R.id.on);
this.off = (Button) findViewById(R.id.off);

this.on.setOnClickListener(this);
this.off.setOnClickListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

public void onClick(View v) {

switch(v.getId()){
case R.id.on:
//final Handler myHandler = new Handler();
(new Thread(new Runnable() {
public void run() {
lightOn();
}
public List<NameValuePair> data;
private void lightOn() {
if(ConnectionManager.isOnline(getApplicationContext())){
this.data = new ArrayList<NameValuePair>(1);
this.data.add(new BasicNameValuePair("8", "1"));
//call the service
@SuppressWarnings("unused")
InputStream is = HttpManager.callService(getString(R.string.url), this.data);
}
}
})).start();
break;
case R.id.off:
//final Handler myHandler1 = new Handler();
(new Thread(new Runnable() {
public void run() {
lightOff();
}
public List<NameValuePair> data;
private void lightOff() {
if(ConnectionManager.isOnline(getApplicationContext())){
this.data = new ArrayList<NameValuePair>(1);
this.data.add(new BasicNameValuePair("8", "0"));
//call the service
@SuppressWarnings("unused")
InputStream is = HttpManager.callService(getString(R.string.url), this.data);
}
}
})).start();
break;
}
}

}



HttpManager
Code: [Select]

package com.mycar.other;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

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 android.util.Log;

public class HttpManager {
public static InputStream callService(String Url, List<NameValuePair> data){
HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(Url);
    try{
    httppost.setEntity(new UrlEncodedFormEntity(data));
    Log.v("Hello",String.valueOf(data));
    //HttpResponse response =
    httpclient.execute(httppost);
        //HttpEntity entity = response.getEntity();
       // return entity.getContent();
    } catch (ClientProtocolException e) {
    Log.v("Came in here","Exception for protocol");
    } catch (IOException e) {
    Log.v("Came in here with IOEXception",e.getMessage());
    }
    return null;
}
}


Connection Manager
Code: [Select]

package com.mycar.other;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class ConnectionManager {
public static boolean isOnline(Context ctx) {
    ConnectivityManager cm =
        (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}
}


if you have some suggestion on how to make this more robust let me know .. this is my first test, upon perfecting it, I will convert my whole room :)

pylon

Quote
could you explain more on than, may b with a code, if its not to much trouble.
thank you.


I have no ready made code for an HTTP server accepting POST requests on the Arduino. If it's possible for you, it's much easier to parse a GET request than to provide all the code to correctly parse and analyze a POST request. So change the HttpPost to a HttpGet and send the data in the query parameter of the URL.

kazimurtaza

if its not much trouble I was hoping to see how are you parsing get request on arduino :)

pgaston

Here's my code for parsing out and responding to a GET request...

Near the top
Code: [Select]

char aSet[] = "GET /setServo.htm";             // set the Servos and also return sensor readings
char aGet[] = "GET /getReadings.htm";       // just return sensor readings
char aSetRudder[] = "rudder=";
char aSetSail[] = "sail=";

// http://192.168.1.101/setServo.htm?rudder=45&sail=70   
// http://192.168.1.101/getReadings.htm


Here's code that's called from the 'loop'
Code: [Select]

  WiFiClient client = server.available();    // listen for incoming clients
  if (client) {
    int index=0;
    int lineNo=0;
    boolean weLike = false;  // only respond to messages that pertain to us (i.e., would like to ignore favicon.ico requests if possible...
   
    //  Serial.println("new client: ");    // try to reduce extra cruft to speed things up???
   
    long start = millis();
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();      // read character
    //    Serial.print(c);
        if ( c != '\r' ) {           // ignore \r characters
          inBuff[index++] = c;       // save line in buffer
          if ( index >= 80 )         // ignore really long lines
            index=70;
          if ( c == '\n' )           // make into true string
            inBuff[index] = 0;

          if (c == '\n' && (index <= 1)) {  // http request ends with a blank line, implies time for us to respond - always send back our readings           
            client.println("HTTP/1.1 200 OK");
            client.println("Content-Type: text/html");
            client.println("Access-Control-Allow-Origin: *");    // to allow XMLHTTPRequest       
            client.println("Connnection: close");
            client.println();
            if ( weLike )  {           
              int anaValue1 = analogRead(pinRelativeWind1);
              int anaValue2 = analogRead(pinRelativeWind2);
              int iWater1 = digitalRead(pinWater1);
              int iWater2 = digitalRead(pinWater2);
             
              client.print("{\"ArdRelativeWind1\":");
              client.print(anaValue1);
              client.print(",\"ArdRelativeWind2\":");
              client.print(anaValue2);
              client.print(",\"ArdWater1\":");
              client.print(iWater1);
              client.print(",\"ArdWater2\":");
              client.print(iWater2);
              client.println("}");
            } else {
              Serial.println("WE DO NOT LIKE!!");
            } 
            break;
          }
          if (c == '\n') {
            if ( lineNo == 0 )  {    // first line - this holds the GET url ...           
              char *get = strstr( inBuff, aGet);
              char *set = strstr( inBuff, aSet);             
              if ( get )  {                // just get values
                weLike = true;
              } else if ( set )  {    // read value to set servos
                 char *rudder = strstr( inBuff, aSetRudder);
                 char *sail = strstr( inBuff, aSetSail);
                 int iRudder = atoi( rudder + 7 );  // move past the 'rudder='
                 int iSail = atoi( sail + 5 );      // move past the 'sail='
                 if ( (iRudder>=0) && (iSail>=0) )  {  // dbl check for good values
                   vServosOut( iRudder, iSail );
                 }     
              }
            } else {
                 // skip line - other heading information
            }
           
            lineNo++;
            index=0;
          }
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    //  Serial.println("client disonnected");
     
    Serial.println("Msg:"+String(++iMsgCount)+",  elapsed: "+String(millis()-start)+" ms");
    iBlinkAction = !iBlinkAction;
    digitalWrite(pinLEDAction,iBlinkAction?HIGH:LOW);  // flips every time a request is received
  }


Not guaranteed to be efficient - but given how slow the wifiserver / wifi shield is it could go out for coffee halfway through and no one would notice...   :)


Go Up