Receiving data through the connection between the Internet and the Internet (Ethernet Shield)

Asked

Viewed 991 times

1

I built an app to receive data from a sensor connected to the Antarctic over the Internet using a Shield Ethernet. For this I took the result of the page and separated only the sensor measure on android.

I managed to get the result of the page but only the pressing of a button. How it would be for it to update automatically?

Main class

        package com.example.appethernetsensor_;

        import android.app.Activity;
        import android.os.Bundle;
        import android.view.Menu;
        import android.view.MenuItem;
        import android.view.View;
        import android.widget.Button;
        import android.widget.TextView;

        import java.io.IOException;

        import android.app.Activity;
        import android.content.Context;
        import android.graphics.Color;
        import android.net.ConnectivityManager;
        import android.net.NetworkInfo;
        import android.os.AsyncTask;
        import android.os.Bundle;
        import android.view.Menu;
        import android.view.MenuItem;
        import android.view.View;
        import android.widget.Button;
        import android.widget.EditText;
        import android.widget.TextView;
        import android.widget.Toast;

        public class MainActivity extends Activity {

            Button btnAtualizar;
            TextView medidaSensor;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                btnAtualizar = (Button)findViewById(R.id.button1);
                medidaSensor= (TextView)findViewById(R.id.textViewMedida);

                btnAtualizar.setOnClickListener(new View.OnClickListener() {            
                    @Override
                    public void onClick(View v) {

                        String stringUrl = "http://192.168.25.85/";

                        //Verifica se há alguma conectividade de rede
                        ConnectivityManager connMgr = (ConnectivityManager) 
                            getSystemService(Context.CONNECTIVITY_SERVICE);

                        //Qual o tipo da rede, se é wifi, rede movel ...
                        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

                        //Se tiver conexão ...
                        if (networkInfo != null && networkInfo.isConnected()) {
                            new DownloadWebpageTask().execute(stringUrl);
                        } else {
                            Toast.makeText(getApplicationContext(), "Nenhma conexão disponível", Toast.LENGTH_LONG).show();
                        }


                    }
                });
            }


            private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
                @Override
                protected String doInBackground(String... urls) {

                    // params comes from the execute() call: params[0] is the url.
                    try {
                        Conexao conexao = new Conexao();
                        return conexao.downloadUrl(urls[0]);
                    } catch (IOException e) {
                        return "URL inválida";
                    }
                }

                protected void onPostExecute(String result) {

                    StringBuffer medida = new StringBuffer(result);            
                    replaceAll(medida, "<html>Sensor Ultrasonico : <b>", "");
                    replaceAll(medida, "</b></html>", "");

                    medidaSensor.setText(medida);
               }
            }
            /*
             *      protected void onPostExecute(String result) {

                    StringBuffer medida = new StringBuffer(result);            
                    replaceAll(medida, "<html>Sensor Ultrasonico : <b>", "");
                    replaceAll(medida, " cm", "");
                    replaceAll(medida, "</b></html>", "");

                    String s = medida.toString();//Converte a stringbuffer final para string

                    int i = Integer.parseInt(s);//Converte a string para inteiro

                    if(i>=0){
                    medidaSensor.setText(i + " cm");
                    }else{
                        medidaSensor.setText("Um momento...");
                    }

            @Override
            public boolean onCreateOptionsMenu(Menu menu) {
                // Inflate the menu; this adds items to the action bar if it is present.
                getMenuInflater().inflate(R.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();
                if (id == R.id.action_settings) {
                    return true;
                }
                return super.onOptionsItemSelected(item);
            }
            */
        }

Connection class

    package com.example.appethernetsensor_;

    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.Reader;
    import java.io.UnsupportedEncodingException;
    import java.net.HttpURLConnection;
    import java.net.URL;

    public class Conexao {

        // Given a URL, establishes an HttpUrlConnection and retrieves
        // the web page content as a InputStream, which it returns as
        // a string.
        public String downloadUrl(String myurl) throws IOException {
            InputStream is = null;
            // Only display the first 500 characters of the retrieved
            // web page content.
            int len = 5000;

            try {
                URL url = new URL(myurl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(10000 /* milliseconds */);
                conn.setConnectTimeout(15000 /* milliseconds */);
                conn.setRequestMethod("GET");
                conn.setDoInput(true);
                // Starts the query
                conn.connect();
                is = conn.getInputStream();

                // Convert the InputStream into a string
                String contentAsString = readIt(is, len);
                return contentAsString;

            // Makes sure that the InputStream is closed after the app is
            // finished using it.
            } finally {
                if (is != null) {
                    is.close();
                } 
            }
        }

        // Reads an InputStream and converts it to a String.
        public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
            Reader reader = null;
            reader = new InputStreamReader(stream, "UTF-8");        
            char[] buffer = new char[len];
            reader.read(buffer);
            return new String(buffer);
        }

    }

Code Arduin

  #include <Ultrasonic.h>
  #include <SPI.h>
  #include <Ethernet.h>

  //Define os parametros para o sensor ultrasonico HC-SR04
  #define PINO_TRIGGER  6 //Porta ligada ao pino Trigger do sensor
  #define PINO_ECHO     7 //Porta ligada ao pino Echo do sensor
  //Inicializa o sensor ultrasonico
  Ultrasonic ultrasonic(PINO_TRIGGER, PINO_ECHO);

  //Definicoes de IP, mascara de rede e gateway
  byte mac[] = {
    0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
  };
  IPAddress ip(192, 168, 25, 85);       //Define o endereco IP
  IPAddress gateway(192, 168, 25, 1);  //Define o gateway
  IPAddress subnet(255, 255, 255, 0); //Define a máscara de rede


  //Inicializa o servidor web na porta 80
  EthernetServer server(80);

  void setup()
  {
    //Inicializa a interface de rede
    Ethernet.begin(mac, ip, gateway, subnet);
    server.begin();
  }

  void loop() {
    float cmMsec;
    long microsec = ultrasonic.timing();
    //Le e armazena as informacoes do sensor ultrasonico
    cmMsec = ultrasonic.convert(microsec, Ultrasonic::CM);

//Aguarda conexao do browser
EthernetClient client = server.available();
if (client) {
  Serial.println("new client");
  // an http request ends with a blank line
  boolean currentLineIsBlank = true;
  while (client.connected()) {
    if (client.available()) {
      char c = client.read();
      Serial.write(c);
      // if you've gotten to the end of the line (received a newline
      // character) and the line is blank, the http request has ended,
      // so you can send a reply
      if (c == 'n' && currentLineIsBlank) {
        // send a standard http response header
        client.println("HTTP/1.1 200 OK");
        client.println("Content-Type: text/html");
        client.println("Connection: close");
        client.println("Refresh: 2"); //Recarrega a pagina a cada 2seg
        client.println();
        client.print("<html>");
        //Mostra as informacoes lidas pelo sensor ultrasonico
        client.print("Sensor Ultrasonico : ");
        client.print("<b>");
        client.print(cmMsec);
        client.print("000");
        client.print(" cm");
        client.println("</b></html>");
        break;
      }
      if (c == 'n') {
        // you're starting a new line
        currentLineIsBlank = true;
      }
      else if (c != 'r') {
        // you've gotten a character on the current line
        currentLineIsBlank = false;
      }
    }
  }
  // give the web browser time to receive the data
  delay(1);
  // close the connection:
  client.stop();
}

}

1 answer

1

package com.example.appethernetsensor_;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

 Button btnAtualizar;
 TextView medidaSensor;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  medidaSensor = (TextView) findViewById(R.id.textViewMedida);

 }

 TimerTask timerTask = new TimerTask() {

  @override
  public void run() {
   String stringUrl = "http://192.168.25.85/";

   //Verifica se há alguma conectividade de rede
   ConnectivityManager connMgr = (ConnectivityManager)
   getSystemService(Context.CONNECTIVITY_SERVICE);

   //Qual o tipo da rede, se é wifi, rede movel ...
   NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

   //Se tiver conexão ...
   if (networkInfo != null && networkInfo.isConnected()) {
    new DownloadWebpageTask().execute(stringUrl);
   } else {
    Toast.makeText(getApplicationContext(), "Nenhma conexão disponível", Toast.LENGTH_LONG).show();
   }
  }

 };

 Timer timer = new Timer();
 timer.schedule(timerTask, 2000, 2000);


 private class DownloadWebpageTask extends AsyncTask < String, Void, String > {
   @Override
   protected String doInBackground(String...urls) {

    // params comes from the execute() call: params[0] is the url.
    try {
     Conexao conexao = new Conexao();
     return conexao.downloadUrl(urls[0]);
    } catch (IOException e) {
     return "URL inválida";
    }
   }

   protected void onPostExecute(String result) {

    StringBuffer medida = new StringBuffer(result);
    replaceAll(medida, "<html>Sensor Ultrasonico : <b>", "");
    replaceAll(medida, "</b></html>", "");

    medidaSensor.setText(medida);
   }
  }
  /*
             *      protected void onPostExecute(String result) {

                    StringBuffer medida = new StringBuffer(result);            
                    replaceAll(medida, "<html>Sensor Ultrasonico : <b>", "");
                    replaceAll(medida, " cm", "");
                    replaceAll(medida, "</b></html>", "");

                    String s = medida.toString();//Converte a stringbuffer final para string

                    int i = Integer.parseInt(s);//Converte a string para inteiro

                    if(i>=0){
                    medidaSensor.setText(i + " cm");
                    }else{
                        medidaSensor.setText("Um momento...");
                    }

            @Override
            public boolean onCreateOptionsMenu(Menu menu) {
                // Inflate the menu; this adds items to the action bar if it is present.
                getMenuInflater().inflate(R.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();
                if (id == R.id.action_settings) {
                    return true;
                }
                return super.onOptionsItemSelected(item);
            }
            */
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.