terça-feira, 12 de agosto de 2014

Projeto Web Service - Continuação

            Faremos agora uma página mais complexa que a anterior, e alteraremos um pouco o código.

            Primeiramente retire o cartão de memória da Galileo com ela desligada, e coloque a seguinte página html na raiz do cartão.

<!DOCTYPE html>
<html lang="pt-br">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <link id="page_favicon" href="http://osx.wdfiles.com/local--files/icon:arduino-icon-small/arduino-icon-small.png" rel="icon" type="image/x-icon" />

    <title>Galileo na web!</title>

    <!-- Bootstrap core CSS -->
    <link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap theme -->
    <link href="http://getbootstrap.com/dist/css/bootstrap-theme.min.css" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="http://getbootstrap.com/examples/theme/theme.css" rel="stylesheet">

    <!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
    <!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
    <script src="http://getbootstrap.com/assets/js/ie-emulation-modes-warning.js"></script>

    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <script src="http://getbootstrap.com/assets/js/ie10-viewport-bug-workaround.js"></script>

    <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>

  <body role="document">

    <!-- Fixed navbar -->
    <div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">Galileo web</a>
        </div>
        <div class="navbar-collapse collapse">
          <ul class="nav navbar-nav">
            <li><a href="http://www.intel.com/content/www/us/en/embedded/products/galileo/galileo-overview.html" target="_blank">Galileo</a></li>
            <li><a href="arduino.cc" target="_blank">Arduino</a></li>
            <li><a href="http://www.intel.com.br/content/www/br/pt/homepage.html" target="_blank" >Intel</a></li>
            <li><a href="http://sistemas-producao.net/inovalab/" target="_blank">Inovalab</a></li>
            </li>
          </ul>
        </div><!--/.nav-collapse -->
      </div>
    </div>

    <div class="container theme-showcase" role="main">

      <!-- Main jumbotron for a primary marketing message or call to action -->
      <div class="jumbotron" align="center">
        <h1>Galileo na web!</h1>
        <p>Conheça o portal de projetos Inova Makers, e submeta seus projetos! </p>
        <p><center><a href="http://inovamakers.febrace.org.br/" class="btn btn-primary btn-lg" role="button">Veja mais</a></center></p>
      </div>


      <center>
      <div class="page-header">
        <h1>Acesso aos leds</h1>
      </div>
      <p>Clique em um botão e veja o efeito na placa! </p>
      <p>
        <button type="button" class="btn btn-lg btn-warning" onmousedown=location.href='?LED1;'>Led 1</button>
        <button type="button" class="btn btn-lg btn-success" onmousedown=location.href='?LED2;'>Led 2</button>
        <button type="button" class="btn btn-lg btn-primary" onmousedown=location.href='?LED3;'>Led 3</button>
        <button type="button" class="btn btn-lg btn-danger" onmousedown=location.href='?LED4;'>Led 13</button>
        
      </p>
      <center>
    </div> <!-- /container -->


    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="../../dist/js/bootstrap.min.js"></script>
    <script src="../../assets/js/docs.min.js"></script>
  </body>
</html>

            Nomeie o arquivo para index.htm, e recoloque o cartão na Galileo e ligue-a de acordo com o indicado anteriormente.

            Abra a IDE e faça upload do código abaixo:


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


// MAC address utilizado
byte mac[] = {0x6A, 0x11, 0x1l, 0x30, 0x12, 0x34};
EthernetServer server = EthernetServer(80); //servidor na porta 80

String readString; 

File webFile;

int led_state[4];


void setup()
{   
    int i;
    Serial.begin(9600);       
    
    pinMode(8, OUTPUT);
    pinMode(9, OUTPUT);
    pinMode(10, OUTPUT);
    pinMode(13, OUTPUT);
    
    for(i=0;i<4;i++)
      led_state[i] = 0;
    
    Ethernet.begin(mac);

    server.begin();
    
    Serial.println(Ethernet.localIP());

    initSDCard();
    
    // check for index.htm file
    if (!SD.exists("index.htm")) {
        Serial.println("ERRO - Nao foi possivel encontraro arquivo index.htm .");
        return;  // nao achou o arquivo
    }
    Serial.println("SUCESSO - Arquivo index.htm encontrado.");
}

void loop()
{
    EthernetClient client = server.available();  // verifica se tem cliente
    
    if (client) {  // se tiver cliente
        boolean currentLineIsBlank = true;
        while (client.connected()) {
            if (client.available()) {   // dados do cliente para ler
                char c = client.read(); // le um byte do cliente
                
                //read char by char HTTP request
                while (readString.length() < 100) {
                  char c = client.read();
                  //store characters to string 
                  readString += c; 
                  //Serial.print(c);
                  if(c == '\n' )
                    break;
                } 
                
                 //controle no led 1  (pino 2)
                if(readString.indexOf("LED1") >= 0 ){
                  if (led_state[0] == 0){
                    digitalWrite(8, HIGH);    
                    Serial.println("Led 1 On");
                    led_state[0] = 1;
                  }
                  else{
                    digitalWrite(8, LOW); 
                    Serial.println("Led 1 Off");
                    led_state[0] = 0;
                  }
                    readString = "";
                }
                
                //controle no led 2  (pino 3)
                if(readString.indexOf("LED2") >= 0 ){
                  if(led_state[1] == 0){
                    digitalWrite(9, HIGH);    
                    Serial.println("Led 2 On");
                    led_state[1] = 1;
                  }
                  else{
                    digitalWrite(9, LOW); 
                    Serial.println("Led 2 Off");
                    led_state[1] = 0;
                  }
                  readString = "";
                }
                
                //controle no led 3  (pino 4)
                if(readString.indexOf("LED3") >= 0 ){
                  if(led_state[2] == 0){
                    digitalWrite(10, HIGH);    
                    Serial.println("Led 3 On");
                    led_state[2] = 1;
                  }
                  else{
                    digitalWrite(10, LOW); 
                    Serial.println("Led 3 Off");
                    led_state[2] = 0;
                  }
                  readString = "";
                }
                
                //controle no led 13  (pino 13)
                if(readString.indexOf("LED4") >= 0 ){
                  if(led_state[3] == 0){
                    digitalWrite(13, HIGH);    
                    Serial.println("Led 13 On");
                    led_state[3] = 1;
                  }
                  else{
                    digitalWrite(13, LOW); 
                    Serial.println("Led 13 Off");
                    led_state[3] = 0;
                  }
                  readString = ""; 
                }

                
                if (c == '\n' && currentLineIsBlank) {
                  // http response header padrao
                  client.println("HTTP/1.1 200 OK");
                  client.println("Content-Type: text/html ; charset=utf-8");
                  client.println("Connection: close");
                  client.println();
                  // envia a web page
                  webFile = SD.open("index.htm");        // abre o arquivo da pagina
                  if (webFile) {
                      while(webFile.available()) {
                          client.write(webFile.read()); // envia a pagina pro cliente
                      }
                      webFile.close();
                  }
                  break;
                } 
                 
  
                if (c == '\n') {
                  currentLineIsBlank = true;
                }
                else if (c != '\r') {
                  currentLineIsBlank = false;
                }
            } 
        } 
        readString="";
        delay(1); // tempo para o browser receber os dados
        client.stop(); // fecha a conexão
               
    } 
}


void initSDCard()
{
    Serial.println("Inicializando SD card...");
    if (!SD.begin()) {
        Serial.println("ERRO - Inicializacao do SD card falhou!");
        return;    // init failed
    }
    Serial.println("SUCESSO - SD card inicializado.");
}

            No final do upload, abra rapidamente o Serial Monitor para descobrir o ip atribuído à Galileo. Cole este endereço na barra de endereços do browser e aperte enter, a seguinte página deverá ser apresentada:

Nova interface web

Nenhum comentário:

Postar um comentário