domingo, 22 de julho de 2012

Arduino como WebServer utilizando Ethernet Shield

Tutorial muito bem feito sobre como utilizar o Arduino con o Ethernet Shield para enviar e receber dados pelo browser.
Composto de 3 vídeos no YouTube com código fonte disponível.

http://g33k.blogspot.com.br/2010/09/arduino-data-webserver-sample-web.html

Código fonte:
http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1284844153/0#0



/*
 Arduino Data Web Server

 Performs actions on Arduino and/or returns data from Arduino to a webbrowser request URL:
  - To turn on LED on pin 8, use web browser to visit your Arduino via: http://x.x.x.x/digitalWrite/7/1
  - To turn it off send: http://x.x.x.x/digitalWrite/7/0
  - To read analog0 value, send: http://x.x.x.x/analogRead/0

 IMPORTANT:
 Commands are case sensitive, but I wrote this as simple as possible so it can be easily adapted to your needs.  
 Have fun!

 created Sept 17, 2010
 by Hari Wiguna, g33k.blogspot.com
*/

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

// MAC address can be anything that is unique within your network.
// IP is the address the Arduino Ethernet Card would respond to.  It needs to be an unused address within your network.
byte mac[] = {0x00, 0x1E, 0x2A, 0x77, 0x24, 0x02 };
byte ip[] = {192,168,7,12 }; // This is typically 10.0.0.x

Server server(80); // Port 80 is http.

//-- Commands and parameters (sent by browser) --
char cmd[15];    // Nothing magical about 15, increase these if you need longer commands/parameters
char param1[15];
char param2[15];

//-- Sample Ports ---
void SetupSamplePorts()
{
  // To illustrate how to use this, I have an LED and a Potentiometer.
  // The 10K potentiometer left lead is connected to GND, right lead to +5V, and middle lead to Analog 0.
  // The LED cathode is on digital pin 7 and anode is on pin 8.
  pinMode(7,OUTPUT); digitalWrite(7,LOW);  // I use this pin as GND for the LED.
  pinMode(8,OUTPUT); // Sample output, unable to use built-in LED at pin 13 because Ethernet Shield uses pins 10,11,12,13.
}

void setup()
{
  Ethernet.begin(mac, ip);
  server.begin();

  Serial.begin(57600);
  SetupSamplePorts();
}

#define bufferMax 128
int bufferSize;
char buffer[bufferMax];

void loop()
{
  Client client = server.available();
  if (client)
  {
    WaitForRequest(client);
    ParseReceivedRequest();
    PerformRequestedCommands();
    
    client.stop();
  }
}

void WaitForRequest(Client client) // Sets buffer[] and bufferSize
{
  bufferSize = 0;

  while (client.connected()) {
    if (client.available()) {
      char c = client.read();
      if (c == '\n')
        break;
      else
        if (bufferSize < bufferMax)
          buffer[bufferSize++] = c;
        else
          break;
    }
  }
  
  PrintNumber("bufferSize", bufferSize);
}

void ParseReceivedRequest()
{
  Serial.println("in ParseReceivedRequest");
  Serial.println(buffer);
  
  //Received buffer contains "GET /cmd/param1/param2 HTTP/1.1".  Break it up.
  char* slash1;
  char* slash2;
  char* slash3;
  char* space2;
  
  slash1 = strstr(buffer, "/") + 1; // Look for first slash
  slash2 = strstr(slash1, "/") + 1; // second slash
  slash3 = strstr(slash2, "/") + 1; // third slash
  space2 = strstr(slash2, " ") + 1; // space after second slash (in case there is no third slash)
  if (slash3 > space2) slash3=slash2;

  PrintString("slash1",slash1);
  PrintString("slash2",slash2);
  PrintString("slash3",slash3);
  PrintString("space2",space2);
  
  // strncpy does not automatically add terminating zero, but strncat does! So start with blank string and concatenate.
  cmd[0] = 0;
  param1[0] = 0;
  param2[0] = 0;
  strncat(cmd, slash1, slash2-slash1-1);
  strncat(param1, slash2, slash3-slash2-1);
  strncat(param2, slash3, space2-slash3-1);
  
  PrintString("cmd",cmd);
  PrintString("param1",param1);
  PrintString("param2",param2);
}

void PerformRequestedCommands()
{
  if ( strcmp(cmd,"digitalWrite") == 0 ) RemoteDigitalWrite();
  if ( strcmp(cmd,"analogRead") == 0 ) RemoteAnalogRead();
}

void RemoteDigitalWrite()
{
  int ledPin = param1[0] - '0'; // Param1 should be one digit port
  int ledState = param2[0] - '0'; // Param2 should be either 1 or 0
  digitalWrite(ledPin, ledState);

  //-- Send response back to browser --
  server.print("D");
  server.print(ledPin, DEC);
  server.print(" is ");
  server.print( (ledState==1) ? "ON" : "off" );

  //-- Send debug message to serial port --
  Serial.println("RemoteDigitalWrite");
  PrintNumber("ledPin", ledPin);
  PrintNumber("ledState", ledState);
}

void RemoteAnalogRead()
{
  // If desired, use more server.print() to send http header instead of just sending the analog value.
  int analogPin = param1[0] - '0'; // Param1 should be one digit analog port
  int analogValue = analogRead(analogPin);
  
  //-- Send response back to browser --
  server.print("A");
  server.print(analogPin, DEC);
  server.print(" is ");
  server.print(analogValue,DEC);
  
  //-- Send debug message to serial port --
  Serial.println("RemoteAnalogRead");
  PrintNumber("analogPin", analogPin);
  PrintNumber("analogValue", analogValue);
}

void PrintString(char* label, char* str)
{
  Serial.print(label);
  Serial.print("=");
  Serial.println(str);
}

void PrintNumber(char* label, int number)
{
  Serial.print(label);
  Serial.print("=");
  Serial.println(number, DEC);
} 



Dica:
Nos comentários do primeiro link há algumas alterações no código-fonte para a compilação do sketch.

Apenas alguns simples ajustes reproduzidos abaixo:

Good job, great.
But, for compiling you must change :
- Line 26,
Server server(80); // Port 80 is http.
by
EthernetServer server(80); // Port 80 is http.
- Line 58,
Client client = server.available();
by
EthernetClient client = server.available();
- Line 69
void WaitForRequest(Client client) // Sets buffer[] and bufferSize
by
void WaitForRequest(EthernetClient client) // Sets buffer[] and bufferSize




Bem tranquilo e bem didático!


Abraço

terça-feira, 15 de novembro de 2011

GWT - Adicionando um MenuItemSeparator utilizando o UIBinder


Não é possível incuir uma tag<g:MenuItemSeparator> no UIBinder.

Para contornar essa limitação achei um truque legal no link abaixo:

http://osdir.com/ml/Google-Web-Toolkit/2010-07/msg01290.html


Segue um trecho do meu código para facilitar sua pesquisa:


<g:AbsolutePanel >
    <g:MenuBar ui:field="menu" vertical="true" styleName="{res.css.menuBar}">
        <g:MenuItem ui:field="item1">Item1</g:MenuItem>
        <g:MenuItem ui:field="item2">Item2</g:MenuItem>
        <g:MenuItem styleName="gwt-MenuItemSeparator">
             <div class="menuSeparatorInner"></div>
        </g:MenuItem>
        <g:MenuItem ui:field="item3">Item3</g:MenuItem>
    </g:MenuBar>
</g:AbsolutePanel>


Até a próxima!

GWT - AddStyleName no UIBinder

Normalmente setamos um estilo no uibinder através do atributo styleName.

Mas e se você quiser adicionar um estilo ao invés de simplesmente setar um estilo?

Utilize o atributo addStyleNames como no exemplo abaixo

<g:Anchor addStyleNames="{res.css.linkSair}" href='javascript:;'>Sair</g:Anchor>



Tenho que dar o crédito ao link onde aprendi esse truque:

http://stackoverflow.com/questions/1899007/add-class-name-to-element-in-uibinder-xml-file



Espero ter ajudado!


GWT - Background Image no CSS utilizando UIBinder e ImageResource

Em meu projeto GWT tenho imagens e css utilizando um ClientBundle.

Perdi algum tempo fazendo pesquisas para inseir uma imagem de fundo através do arquivo de CSS.

Cconhecimento aprendido é conhecimento compartilhado!

O link abaixo foi muito útil:

http://stackoverflow.com/questions/4535094/how-do-i-use-image-sprites-in-gwt


Trechos do meu código:

Arquivo de Recursos
----------------------------------------------------------------------------------------------
 public interface Resources extends ClientBundle{
     public static final Resources INSTANCE = GWT.create(Resource.class);

    @Source("br/com/inaciojr9/client/resources/circuito1.png")
     @ImageOptions(repeatStyle=RepeatStyle.Both)
     ImageResource circuito1();

    @Source("br/com/inaciojr9/client/resources/GlobalStyles.css")
     @CssResource.NotStrict
     GlobalStylesheet css();
}
----------------------------------------------------------------------------------------------

Arquivo GlobalStyles.css
----------------------------------------------------------------------------------------------
@sprite .painelRegistro{
     background-color: #FFFFFF;
     color: #660066;
     border-color: #660066;
     border-style: dotted;
     border-width: 1px;
     padding: 1px;
     margin: 3px;
     border-collapse: collapse;
     font-family: tahoma;
     font-size: 11px;
     gwt-image: "circuito1";
     height: auto;
     width: auto;
}
 ----------------------------------------------------------------------------------------------

Arquivo UIBinder
-----------------------------------------------------------------------------------------------
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui">
     <ui:with field='res' type='br.com.inaciojr9.client.resources.Resources' />

     <g:HTMLPanel styleName="{res.css.painelRegistro}">
         <g:Label ui:field="loginTitle">REGISTRO</g:Label>
     </g:HTMLPanel>
</ui:UiBinder>
-----------------------------------------------------------------------------------------------

Espero ter ajudado!

sábado, 8 de outubro de 2011

Bem-vindo ao Blog do Inacio

Blog para troca de informações sobre as áreas de conhecimento que norteiam minhas pesquisas e estudos: Tecnologia e Educação Física.

Portanto mãos à obra, vamos conversar muito sobre Java, Pilates, Mobile, Preparação Física, Computação Física, Frequência Cardíaca, Cloud Computing, Fisiologia do Exercício, Android, Anatomia, Orientação a Objetos, Futebol, Arduino, Surf, Automação Residencial, Postura, Redes Sociais, Alongamento, Engenharia de Software, Corrida, Arquitetura de Sistemas, Caminhada, GWT, Respiração, JBoss, Biomecânica, Hibernate, Musculação, Google AppEngine, Natação, JBoss Seam, Treinamento Funcional e muito mais, não necessariamente nessa mesma ordem!!