Webserver - AJAX Wertübergabe

Guten Morgen,

ich programmiere derzeit mein Arduino Mega und versuche mit AJAX und JAVA Werte aus dem Browser an das Arduinoboard und umgekehert zu übergeben, für die Anzeige von Analogwerten und das Schalten von Relais.

Leider gelingt es mir nicht, für jeden Analogeingang und für jedes Relais eine JAVA Funktion zu erstellen, so dass ich per Hyperlink die Funktion aufrufen kann, um dann den jeweiligen Rückgabewert zu erhalten.

Wenn ich nur eine Funktion nutze funktioniert es einwandfrei.

Habt ihr eine Idee für mich?

Vielen Dank!

LG

Arduino Code

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


// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 178, 210);

// Initialize the Ethernet server library
// (port 80 is default for HTTP):
EthernetServer server(80);

File webPage;
int RED = 7;              //LED to turn on/off
int RED2 = 8;              //LED to turn on/off
String HTTP_req;          // stores the HTTP request

void setup()
{
  Ethernet.begin(mac, ip);  // initialize Ethernet device
  server.begin();           // start to listen for clients
  Serial.begin(9600);       // for debugging
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  // initialize SD card
  Serial.println("Checking SD card is accessible...");
  if (!SD.begin(4)) {
    Serial.println("ERROR - SD card initialization failed!");
    return;    // init failed
  }
  Serial.println("SUCCESS - SD card initialized.");
  HTTP_req = "";
  //Set LED to output
  pinMode(RED, OUTPUT);
}

void loop()
{
  // listen for incoming clients
  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(); // read 1 byte (character) from client
        // 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 ( HTTP_req.length() < 80)
          HTTP_req += c;  // save the HTTP request 1 char at a time
        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();
          // send web page
          if (HTTP_req.indexOf("ajaxrefresh") >= 0 ) {
            ajaxRequest(client);  //update the analog values
            break;
          }
          if (HTTP_req.indexOf("ajaxrefresh2") >= 0 ) {
            ajaxRequest2(client);  //update the analog values
            break;
          }
          if (HTTP_req.indexOf("ledstatus") > 0 ) {
            ledChangeStatus(client); //change the LED state
            break;
          }
          if (HTTP_req.indexOf("ledzwei") > 0 ) {
            ledChangeStatus2(client); //change the LED state
            break;
          }
          else {
            webPage = SD.open("index.htm");        // open web page file
            if (webPage) {
              while (webPage.available()) {
                client.write(webPage.read()); // send web page to client
              }
              webPage.close();
            }
            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();
    HTTP_req = "";
    Serial.println("client disconnected");
  } // end if (client)
}

// send the state of the switch to the web browser
void ajaxRequest(EthernetClient client)
{
 // for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
 //   int sensorReading = analogRead(analogChannel);
//    client.print("analog input ");
//    client.print(analogChannel);
//    client.print(" is ");
 //   client.print(sensorReading);
//    client.println(",");
    
 // }
  client.print(analogRead(6));
}

void ajaxRequest2(EthernetClient client)
{
  client.print(analogRead(7));
}

void ledChangeStatus(EthernetClient client)
{
  int state = digitalRead(RED);
  Serial.println(state);
  if (state == 1) {
    digitalWrite(RED, LOW);
    client.print("OFF");
  }
  else {
    digitalWrite(RED, HIGH);
    client.print("ON");
  }
}

void ledChangeStatus2(EthernetClient client)
{
  int state = digitalRead(RED2);
  Serial.println(state);
  if (state == 1) {
    digitalWrite(RED2, LOW);
    client.print("OFF");
  }
  else {
    digitalWrite(RED2, HIGH);
    client.print("ON");
  }
}

HTML Datei

<!DOCTYPE HTML>
<html lang="en">
<script>window.setInterval(function(){
nocache = "&nocache=" + Math.random() * 10;
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {
if (this.responseText != null) {
document.getElementById("analoge_data").innerHTML = this.responseText;
}}}}
request.open("GET", "ajaxrefresh" + nocache, true);
request.send(null);
}, 5000);
function changeLEDStatus() {
nocache = "&nocache=" + Math.random() * 10;
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {
if (this.responseText != null) {
document.getElementById("led_status").innerHTML = this.responseText;
}}}}
request.open("GET", "?ledstatus=1" + nocache, true);
request.send(null);
}
function changeLEDStatus2() {
nocache = "&nocache=" + Math.random() * 10;
var request2 = new XMLHttpRequest();
request2.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {
if (this.responseText != null) {
document2.getElementById("led_status2").innerHTML = this.responseText;
}}}}
request2.open("GET", "?ledzwei=1" + nocache, true);
request2.send(null);
}
</script></head>
<h1>Analogue Values</h1><div id="analoge_data">Arduino analog input values loading.....</div>
<h1>Arduino LED Status</h1>
<div><span id="led_status">
Off
</span> | <button onclick="changeLEDStatus()">Change Status</button> </div>


<div><span id="led_status2">


Off
</span> | <button onclick="changeLEDStatus2()">Change Status 2</button> </div>
</html>

hast ein document2?

ich würde eher der JavaScript-Funktion (nicht JAVA!) einen Parameter übergeben und nicht zwei separte Funktionen machen.

Vieleicht passt es nicht ganz (weil für den ESP), aber hier beschreibe ich in Schritt 3 von 7 unter anderem das Schalten

das JavaScript sollte eigentlich so auch auf UNO/MEGA laufen können.

Danke für die schnelle Antwort. Was meinst Du mit document2?
Das Projekt besteht aus 2 Dateien. Der Arduino INO Datei und dem index.htm File.

Dennis2015:
Was meinst Du mit document2?

document

In deiner Html Datei steht "document2"

Gruß Fips

noiasca:
das JavaScript sollte eigentlich so auch auf UNO/MEGA laufen können.

Das JavaScript läuft im Browser. Der ESP/MEGA,... stellt lediglich den Text zur Verfügung. Der Inhalt ist ihm völlig egal.

Gruß Tommy

Dennis2015:
ich programmiere ...

Der Arduino-Code sieht für mich eher nach copy+paste aus. Und zum HTML-Code fällt mir eigentlich nur mein Geschreibsel von neulich ein.

Gruß

Gregor