Author Topic: Serving Web Pages Using Forms (POST)  (Read 16550 times)

Twistit

  • Newbie
  • *
  • Posts: 19
Serving Web Pages Using Forms (POST)
« on: June 20, 2014, 01:36:04 pm »
I was looking up on examples for controlling my terraria over wifi..

Really wanted to have te DigiX serve a website with buttons and forms and ofcourse data for example if i wanted to have one of the fans turn at 50% i'd fill 50 in the form for fan1 and well you get with i mean..

I found a perfect example for a regular arduino, but i have no clue on how to make this work for the DigiX with it's fancy wifi thingamajigs.

Anyone out there that could give me some pointers? Because this would be perfect for me to work off and understand how the DigiX handles this..

https://www.inkling.com/read/arduino-cookbook-michael-margolis-2nd/chapter-15/recipe-15-10

Twistit

  • Newbie
  • *
  • Posts: 19
Re: Serving Web Pages Using Forms (POST)
« Reply #1 on: June 22, 2014, 02:02:53 am »
For anyone interested I'm solving it by tearing up dbell's script, attached my rough draft for controlling a pc fan.
Any pointers on cleaning this up always welcome, i am no pro at programming arduino's hehe

I'm not using POST but hell, this works..
« Last Edit: June 22, 2014, 02:04:24 am by Twistit »

Amus3d

  • Newbie
  • *
  • Posts: 31
Re: Serving Web Pages Using Forms (POST)
« Reply #2 on: June 22, 2014, 05:45:14 am »
This works but not cleaned up yet.

all you need to do is add pinMode() to setup

and in the html function
copy this and add new buttons
 String body = "<lable>Digital Pin 4<button class='relay' pin='d4' val='0'>LOW</button><button class='relay' pin='d4' val='1'>HIGH</button></label";

change pin='d4' to d? . d= digital and ? = number of the pin you want to use.



Code: [Select]
#include <DigiFi.h>
DigiFi server;
void setup() {
 
  Serial.begin(9600);
  server.begin(9600);
 
  pinMode(7,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(5,OUTPUT);
  pinMode(4,OUTPUT);
 
  digitalWrite(7,HIGH);
  digitalWrite(6,LOW);
  digitalWrite(5,LOW);
  digitalWrite(4,LOW);

  //DigiX trick - since we are on serial over USB wait for character to be entered in serial terminal
  while(!Serial.available()){
    Serial.println("Enter any key to begin");
    delay(1000);
  }

  Serial.println("Starting");
  Serial.println("wifi inited");

  while (server.ready() != 1)
  {
    Serial.println("Error connecting to network");
    delay(15000);
  } 

  Serial.println("Connected to wifi!");
  Serial.print("Server running at: ");
  String address = server.server(8080);//sets up server and returns IP
  Serial.println(address);

}

void loop() {
  if ( server.serverRequest()){
    if( findOutHowManyCharInAString( server.serverRequestPath() , '=') !=0){
      getUrlVariablesFromWifiString( server.serverRequestPath() );
      server.serverResponse(htmlReturn()); //need relay so brouser dont hang
    }
    else
      server.serverResponse(htmlPage()); //defaults to 200
  }
}

void runVariableCommand(String string){
 if(string.charAt(0)=='d'){ // letter d = Digital
 
  int endOfVariableName = string.indexOf('=');
  int booleanValue = stringToInt(string.substring(endOfVariableName+1,string.length()));
  String variableName   = string.substring(0,endOfVariableName);
   digitalWrite( stringToInt( variableName.substring(1,variableName.length()) ), booleanValue );
   Serial.print("digital Pin ");
   Serial.print(stringToInt( variableName.substring(1,variableName.length()) ));
   Serial.print(" to ");
   Serial.println(booleanValue);
 }
}

boolean getUrlVariablesFromWifiString( String data ){
    Serial.print("Request = ");
    Serial.println(data);
    if(data.length()>=0){
      getEachVariable(data.substring(data.indexOf('?')+1, data.length()));
      return true;
    }else
    return false;
     
}


// split get Into smaller Chunks ie. ?d12=1&d13=0 into d12=1 and d13=0
String splitVariablesUP( String *str , String strTemp, int strLength ){
 
  String singleVariableAsString;
  int startIndex=0;
  //finds the first index of &
  int endIndex=strTemp.indexOf('&');
  // get the variable parts into a string
  singleVariableAsString = strTemp.substring( startIndex , endIndex );
 
  //now delete variable from reference string
  *str = strTemp.substring( endIndex+1 , strLength );// endIndex +1 is so we loose the & char as we do not need it
  return singleVariableAsString;
}

// break down GET sting into each variable + value
void getEachVariable(String strTemp){
  // returns variable count
  int variableCount = findOutHowManyCharInAString( strTemp , '=');
   Serial.print("Variable Count = ");
   Serial.println(variableCount);
 
  // loops through each variable
  for(int i=0;i<variableCount;i++){
   // assigns each variable and value to a string array
   runVariableCommand(splitVariablesUP( &strTemp , strTemp , strTemp.length() ));
  }
}
//return int value from string
int stringToInt(String thisString) {
  int i, value, length;
 
  length = thisString.length();
 
  char blah[(length+1)];
 
  for(i=0; i<length; i++) {
    blah[i] = thisString.charAt(i);
  }
  blah[i]=0;
 
  value = atoi(blah);
 
  return value;
}
//return how many variables are in the GET
int findOutHowManyCharInAString(String str, char findChar){
  int positionChar = 0;
  int count=0;
  while(positionChar != -1){
   positionChar = str.indexOf( findChar , positionChar+1 );
   if(positionChar!=-1)
    count++;
  }
  return count;
}

// html code
String htmlPage(){

 String startHtml = "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html xmlns='http://www.w3.org/1999/xhtml'><head><meta http-equiv='Content-Type' content='text/html;charset=utf-8' /><title>Arduino DigiX Wifi</title>";

 String jquery = "\n<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>"
                 "\n<script>\n$(function(){\n$('.relay').click( function(){"
                 "\najaxCallScript( $(this).attr('pin') + '=' + $(this).attr('val'));\n"
                 "});\n});\n"
                 "alert('jquery Loaded');"
                 "</script>";
 
 String ajax = "\n<script>\nfunction ajaxCallScript( get ){"
   
"\nfile = '?' + get;"

"\nif (window.XMLHttpRequest)"
  "\n{// code for IE7+, Firefox, Chrome, Opera, Safari"
  "\nxmlhttp=new XMLHttpRequest();"
  "\n}"
"\nelse"
  "\n{// code for IE6, IE5"
  "\nxmlhttp=new ActiveXObject('Microsoft.XMLHTTP');"
  "\n}"
"\nxmlhttp.onreadystatechange=function(){"
 
"\nif (xmlhttp.readyState==4 && xmlhttp.status==200){"
"\ndocument.getElementById(elementName).innerHTML = 'done';}"
  "\nelse"
   "\ndocument.getElementById(elementName).innerHTML = 'Sent';"
  "\n}"
"\nxmlhttp.open('GET',file,true);"
"\nxmlhttp.send();"
        "\n}\n</script>";

 String javascript = "";

 String body = "<lable>Digital Pin 4<button class='relay' pin='d4' val='0'>LOW</button><button class='relay' pin='d4' val='1'>HIGH</button></label";

 String endHtml = "\n</body>\n</html>";

 return startHtml+jquery+ajax+javascript+body+endHtml;
}

String htmlReturn(){
 return "hello";

}

« Last Edit: June 22, 2014, 05:50:33 am by Amus3d »

Amus3d

  • Newbie
  • *
  • Posts: 31
Re: Serving Web Pages Using Forms (POST)
« Reply #3 on: June 22, 2014, 06:13:41 am »
this one has anologWrite which is more what you was asking for.
only changes to need to make are in setup pinMode etc and

function htmlPage

 String body = "";   //add buttons selector

Code: [Select]
#include <DigiFi.h>
DigiFi server;
void setup() {
 
  Serial.begin(9600);
  server.begin(9600);
 
  pinMode(7,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(5,OUTPUT);
  pinMode(4,OUTPUT);
 
  digitalWrite(7,HIGH);
  digitalWrite(6,LOW);
  digitalWrite(5,LOW);
  digitalWrite(4,LOW);

  //DigiX trick - since we are on serial over USB wait for character to be entered in serial terminal
  while(!Serial.available()){
    Serial.println("Enter any key to begin");
    delay(1000);
  }

  Serial.println("Starting");
  Serial.println("wifi inited");

  while (server.ready() != 1)
  {
    Serial.println("Error connecting to network");
    delay(15000);
  } 

  Serial.println("Connected to wifi!");
  Serial.print("Server running at: ");
  String address = server.server(8080);//sets up server and returns IP
  Serial.println(address);

}

void loop() {
  if ( server.serverRequest()){
    if( findOutHowManyCharInAString( server.serverRequestPath() , '=') !=0){
      getUrlVariablesFromWifiString( server.serverRequestPath() );
      server.serverResponse(htmlReturn()); //need relay so brouser dont hang
    }
    else
      server.serverResponse(htmlPage()); //defaults to 200
  }
}

void runVariableCommand(String string){
 if(string.charAt(0)=='d'){ // letter d = Digital
 
   int endOfVariableName = string.indexOf('=');
   int booleanValue = stringToInt(string.substring(endOfVariableName+1,string.length()));
   String variableName   = string.substring(0,endOfVariableName);
   digitalWrite( stringToInt( variableName.substring(1,variableName.length()) ), booleanValue );
   Serial.print("digital Pin ");
   Serial.print(stringToInt( variableName.substring(1,variableName.length()) ));
   Serial.print(" to ");
   Serial.println(booleanValue);
 }
 if(string.charAt(0)=='a'){ // letter a = Analog
   int endOfVariableName = string.indexOf('=');
   int booleanValue = stringToInt(string.substring(endOfVariableName+1,string.length()));
   String variableName   = string.substring(0,endOfVariableName);
   analogWrite( stringToInt( variableName.substring(1,variableName.length()) ), booleanValue );
   Serial.print("Analog Pin ");
   Serial.print(stringToInt( variableName.substring(1,variableName.length()) ));
   Serial.print(" to ");
   Serial.println(booleanValue);
 }
}

boolean getUrlVariablesFromWifiString( String data ){
    Serial.print("Request = ");
    Serial.println(data);
    if(data.length()>=0){
      getEachVariable(data.substring(data.indexOf('?')+1, data.length()));
      return true;
    }else
    return false;
     
}


// split get Into smaller Chunks ie. ?d12=1&d13=0 into d12=1 and d13=0
String splitVariablesUP( String *str , String strTemp, int strLength ){
 
  String singleVariableAsString;
  int startIndex=0;
  //finds the first index of &
  int endIndex=strTemp.indexOf('&');
  // get the variable parts into a string
  singleVariableAsString = strTemp.substring( startIndex , endIndex );
 
  //now delete variable from reference string
  *str = strTemp.substring( endIndex+1 , strLength );// endIndex +1 is so we loose the & char as we do not need it
  return singleVariableAsString;
}

// break down GET sting into each variable + value
void getEachVariable(String strTemp){
  // returns variable count
  int variableCount = findOutHowManyCharInAString( strTemp , '=');
   Serial.print("Variable Count = ");
   Serial.println(variableCount);
 
  // loops through each variable
  for(int i=0;i<variableCount;i++){
   // assigns each variable and value to a string array
   runVariableCommand(splitVariablesUP( &strTemp , strTemp , strTemp.length() ));
  }
}
//return int value from string
int stringToInt(String thisString) {
  int i, value, length;
 
  length = thisString.length();
 
  char blah[(length+1)];
 
  for(i=0; i<length; i++) {
    blah[i] = thisString.charAt(i);
  }
  blah[i]=0;
 
  value = atoi(blah);
 
  return value;
}
//return how many variables are in the GET
int findOutHowManyCharInAString(String str, char findChar){
  int positionChar = 0;
  int count=0;
  while(positionChar != -1){
   positionChar = str.indexOf( findChar , positionChar+1 );
   if(positionChar!=-1)
    count++;
  }
  return count;
}

// html code
String htmlPage(){

 String startHtml = "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html xmlns='http://www.w3.org/1999/xhtml'><head><meta http-equiv='Content-Type' content='text/html;charset=utf-8' /><title>Arduino DigiX Wifi</title>";

 String jquery = "\n<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>"
                 "\n<script>\n"
                 "\n$(function(){"
                  "\nalert('jquery Loaded');"
                  "\n$('.relay').click( function(){"
                   "\najaxCallScript( $(this).attr('pin') + '=' + $(this).attr('val'));"
                  "\n});"
 
                " \n$('.selector').change(function(){\najaxCallScript( \n$(this).attr('pin') + '=' + $(this).val());"
                 "\n});"
                "\n});"
                 "\n</script>";
 
 String ajax = "\n<script>\nfunction ajaxCallScript( get ){"
   
"\nfile = '?' + get;"

"\nif (window.XMLHttpRequest)"
  "\n{// code for IE7+, Firefox, Chrome, Opera, Safari"
  "\nxmlhttp=new XMLHttpRequest();"
  "\n}"
"\nelse"
  "\n{// code for IE6, IE5"
  "\nxmlhttp=new ActiveXObject('Microsoft.XMLHTTP');"
  "\n}"
"\nxmlhttp.onreadystatechange=function(){"
 
"\nif (xmlhttp.readyState==4 && xmlhttp.status==200){"
"\ndocument.getElementById(elementName).innerHTML = 'done';}"
  "\nelse"
   "\ndocument.getElementById(elementName).innerHTML = 'Sent';"
  "\n}"
"\nxmlhttp.open('GET',file,true);"
"\nxmlhttp.send();"
        "\n}\n</script>";

 String javascript = "";

 String body = "<lable>Digital Pin 4<button class='relay' pin='d4' val='0'>LOW</button><button class='relay' pin='d4' val='1'>HIGH</button></label>"
               "<br><lable>Analog Pin 1<select class='selector' pin='a1'><option>0</option><option>50</option><option>100</option><option>150</option><option>200</option><option>255</option></select>";

 String endHtml = "\n</body>\n</html>";

 return startHtml+jquery+ajax+javascript+body+endHtml;
}

String htmlReturn(){
 return "hello";

}
« Last Edit: June 22, 2014, 06:21:40 am by Amus3d »

Twistit

  • Newbie
  • *
  • Posts: 19
Re: Serving Web Pages Using Forms (POST)
« Reply #4 on: June 23, 2014, 08:47:46 am »
Perfect! Thanks! Much better then what i had going  ;D

Amus3d

  • Newbie
  • *
  • Posts: 31
Re: Serving Web Pages Using Forms (POST)
« Reply #5 on: October 16, 2014, 03:35:18 pm »
how did youre code work out in the end

Twistit

  • Newbie
  • *
  • Posts: 19
Re: Serving Web Pages Using Forms (POST)
« Reply #6 on: October 18, 2014, 04:07:39 am »
Awesome, got it doing what i wanted ;)

Twistit

  • Newbie
  • *
  • Posts: 19
Re: Serving Web Pages Using Forms (POST)
« Reply #7 on: October 21, 2014, 02:12:16 pm »
Originally when i called the page for the first time i had to refresh to actually get the page.

Now that it's incorporated in my "large" script the above still applies but when i call for the page for a third time the DigiX freezes?
If i wait 5 minutes it will continue doing it's thing (serial console pops back to life and it responds to my button).

Sometimes when i refresh again it will continue sooner and i will actually get the page but that's a hit and miss,
most often i have to wait 5 minutes for the DigiX to do anything again.

I'm stumped -.-

Amus3d

  • Newbie
  • *
  • Posts: 31
Re: Serving Web Pages Using Forms (POST)
« Reply #8 on: October 21, 2014, 02:52:47 pm »
i gave up on digiX trying to a server & client, had problems with wifi crashing (can't do both at the same time). So i did this instead

digiX <---> raspberry Pi  <---> me

raspberry is setup with apache server, which is also going to do my smart home server(ie lights, heating, power usage and some security )

digiX talks to raspberyy every 5min( with data which is sorted by PHP into mySql )
- raspberry replies with variables ?tempMax=28&tempMin=15&lightsOn=13&lightsOff=23 the return GET can be passed to getUrlVariablesFromWifiString( String string to be sort )

I(me) talks to the raspberry(webpage is serverd from here). digiX has been runing for months now with no problems.

if you have a raspberry or host a webpage with php & mysql and can help you with the code needed to the server side :)
« Last Edit: October 21, 2014, 03:10:26 pm by Amus3d »

Amus3d

  • Newbie
  • *
  • Posts: 31
Re: Serving Web Pages Using Forms (POST)
« Reply #9 on: October 21, 2014, 03:41:35 pm »
using the tabs helps break down the code for easier reading

open the "WebNTPRelayTimersTempRev12.ino" not the others.

Amus3d

  • Newbie
  • *
  • Posts: 31
Re: Serving Web Pages Using Forms (POST)
« Reply #10 on: October 21, 2014, 06:40:20 pm »
example code will finsih rest off tomo,

what is TL1,Tl1, SPOT and NIGHT for.

and do you have a nokia 5110 screen?
« Last Edit: October 21, 2014, 06:41:58 pm by Amus3d »

Twistit

  • Newbie
  • *
  • Posts: 19
Re: Serving Web Pages Using Forms (POST)
« Reply #11 on: October 22, 2014, 12:31:43 am »
Goodmorning!
TL is what we call a fluorescent tube in the Netherlands, got 2 ;) So TL1 and TL2.
Spot is the spot light which the tortoise uses for basking and Night are the night leds.

I do have a nokia screen somewhere, but that was planned for later on. Still need to make a waterproof/tortoiseproof housing for it and fix wiring through the bottom.
I have a webhost with php and sql support.

I didn't even know i could use tabs... That's nifty!
The 2 Fluorescent tubes start and stop at the same time.
The Night leds start when the tubes stop.
The spot light starts with the tubes but stops earlier.

The temp sensors should turn on a pc fan and if that does not help turn off the spot and then one tube at a time when temps get to high. (depends on which sensor if spot or tubes go first)

The webpage was going to allow manual control over the lights and fan overruling the timer or temp and tell me what is on and what is off.

So you know what i was going for.
« Last Edit: October 22, 2014, 12:49:16 am by Twistit »

Amus3d

  • Newbie
  • *
  • Posts: 31
Re: Serving Web Pages Using Forms (POST)
« Reply #12 on: October 23, 2014, 12:35:11 pm »
done

Twistit

  • Newbie
  • *
  • Posts: 19
Re: Serving Web Pages Using Forms (POST)
« Reply #13 on: October 23, 2014, 02:09:03 pm »
Sweet! Started tinkering with it right away, question tho.. The cases you used like case 840: // lightsOn how do you calculate those?
[Edit] Got it, it's adding up the DEC value's! Smart hehe
[Edit 2] Under wifi tab i see updateData.php and test.php but i dont see the php code for those.

Toki said thank you ;)

« Last Edit: October 23, 2014, 02:36:36 pm by Twistit »

Amus3d

  • Newbie
  • *
  • Posts: 31
Re: Serving Web Pages Using Forms (POST)
« Reply #14 on: October 24, 2014, 04:39:39 am »
test.php is the same as getVariables.php just forgot to change it.

changes done and new index.php added and another sql db