I have an arduino program that displays the data about my control element(temperature) on a web page through the arduino Wifi Shield. Kindly tell me how to create a login with password page before entering my temperature control page for security reasons. Kindly suggest on how I can implement this in my wifi shield programming.
satarun:
I have an arduino program that displays the data about my control element(temperature) on a web page through the arduino Wifi Shield. Kindly tell me how to create a login with password page before entering my temperature control page for security reasons.
Thanks for the reply jurs. But the problem I am facing is in the implementation of this code in IDE. How do I link the login page and my program page?
satarun:
Thanks for the reply jurs. But the problem I am facing is in the implementation of this code in IDE. How do I link the login page and my program page?
Here is an example program doing a"HTTP Basic Authentication":
#include <SPI.h>
#include <Ethernet.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,2, 111);
// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
}
void SendOKpage(EthernetClient &client)
{
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connnection: close");
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
// add a meta refresh tag, so the browser pulls again every 5 seconds:
client.println("<meta http-equiv=\"refresh\" content=\"5\">");
// output the value of each analog input pin
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.println("</html>");
}
void SendAuthentificationpage(EthernetClient &client)
{
client.println("HTTP/1.1 401 Authorization Required");
client.println("WWW-Authenticate: Basic realm=\"Secure Area\"");
client.println("Content-Type: text/html");
client.println("Connnection: close");
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<HTML> <HEAD> <TITLE>Error</TITLE>");
client.println(" </HEAD> <BODY><H1>401 Unauthorized.</H1></BODY> </HTML>");
}
char linebuf[80];
int charcount=0;
boolean authentificated=false;
void loop() {
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
Serial.println("new client");
memset(linebuf,0,sizeof(linebuf));
charcount=0;
authentificated=false;
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
linebuf[charcount]=c;
if (charcount<sizeof(linebuf)-1) charcount++;
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) {
if (authentificated)
SendOKpage(client);
else
SendAuthentificationpage(client);
break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
if (strstr(linebuf,"Authorization: Basic")>0 && strstr(linebuf,"c2F0YXJ1bjpwYXNzd29yZA==")>0)
authentificated=true;
memset(linebuf,0,sizeof(linebuf));
charcount=0;
}
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();
Serial.println("client disonnected");
}
}
Basically this is the 'Webserver" example program from Arduino, with some additional security.
You would have to know Username and Password to enter the website.
In this example use these data to get access to your Arduino webserver:
User: satarun
Pass: password
I know, the password "password" is not very secure, but this code is for demonstration only, you can change it as you like.
Thank you Jurs. When i implement the code a pop-up asks for login id and password. But when i use the login id(satarun) and password(password) i am again asked for the same authorization by the same pop-up.
Kindly guide me as to How and where i should implement the user id and password in the code!
satarun:
Thank you Jurs. When i implement the code a pop-up asks for login id and password. But when i use the login id(satarun) and password(password) i am again asked for the same authorization by the same pop-up.
Kindly guide me as to How and where i should implement the user id and password in the code!
Did you also "implement the code" with a datailed scanning and evaluation of the GET request, as I posted it in the example?
You'd have to do it like that:
1st step when the client connect: set the authentication state to 'false'
EthernetClient client = server.available();
if (client) {
Serial.println("new client");
memset(linebuf,0,sizeof(linebuf));
charcount=0;
authentificated=false; // state after starting a request ==> not authenticated
2nd step when scanning the request lines for the clients "Authorization: Basic"
if (strstr(linebuf,"Authorization: Basic")>0 && strstr(linebuf,"c2F0YXJ1bjpwYXNzd29yZA==")>0)
authentificated=true;
If the client
- has sent his authorization code
- and if the authorization code is correct
==> send the requested file to the client
if (c == '\n' && currentLineIsBlank)
{
if (authentificated)
SendOKpage(client);
else
SendAuthentificationpage(client);
break; // break the loop from scanning the client request, we have seen enough
}
And if the client
- has either not sent his authorization code
- or if the authorization code was wrong
==> send another authentication response to the client
And the client then can retry with sending a correct authorization code.
Easy as that. And always the same since the Stone Age of the WWW, never had any specification change, so since 25 years until nowadays every webbrowser is able to handle that correctly.
If your server can handle it correctly too, it will work.
thank you jurs, i will try once again and get you
ya jurs i got it right this time,thank you very much.I am currently doing temperature control process using arduino mega. i want to plot that values using simple xy graph in my webpage.i dont know how to build the graph.Can u suggest me some steps to build the graph in my webpage using wifi shield? thank you ![]()
satarun:
![]()
ya jurs i got it right this time,thank you very much.I am currently doing temperature control process using arduino mega. i want to plot that values using simple xy graph in my webpage.i dont know how to build the graph.Can u suggest me some steps to build the graph in my webpage using wifi shield? thank you
Congratulations to a working user-login on your Arduino!
But about the imaging I don't quite understand:
Do you want a xy-plotted image created by the Arduino webserver itself?
Or do you have a real full-featured webserver on the Internet, that is PHP enabled and can do all the sophisticated things that a PHP enabled webserver can do? In that case you would do it like that:
- the PHP enabled webserver catches raw data (txt file) from your Arduino webserver
- then the PHP enabled webserver does the xy-graphing
Or do you want some stand-alone graphing done by the Arduino without any external calculating and graphing power?
I am using plot.ly website for plotting my data.thanks for your guidance
hi satarun,
I am working on an arduino project wich serves data from temperatures sensors on a webpage hosted on arduino SDcard. I try to use plotly to create graph on this page but I experience problems. I understand you manage to do this. Could you give me some advice or some code examplel I can learn with.
Many thanks
jurs:
Here is an example program doing a"HTTP Basic Authentication":#include <SPI.h>
#include <Ethernet.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,2, 111);
// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
}
void SendOKpage(EthernetClient &client)
{
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connnection: close");
client.println();
client.println("");
client.println("");
// add a meta refresh tag, so the browser pulls again every 5 seconds:
client.println("<meta http-equiv="refresh" content="5">");
// output the value of each analog input pin
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.println("");
}
void SendAuthentificationpage(EthernetClient &client)
{
client.println("HTTP/1.1 401 Authorization Required");
client.println("WWW-Authenticate: Basic realm="Secure Area"");
client.println("Content-Type: text/html");
client.println("Connnection: close");
client.println();
client.println("");
client.println(" Error");
client.println("
401 Unauthorized.
");}
char linebuf[80];
int charcount=0;
boolean authentificated=false;
void loop() {
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
Serial.println("new client");
memset(linebuf,0,sizeof(linebuf));
charcount=0;
authentificated=false;
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
linebuf[charcount]=c;
if (charcount<sizeof(linebuf)-1) charcount++;
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) {
if (authentificated)
SendOKpage(client);
else
SendAuthentificationpage(client);
break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
if (strstr(linebuf,"Authorization: Basic")>0 && strstr(linebuf,"c2F0YXJ1bjpwYXNzd29yZA==")>0)
authentificated=true;
memset(linebuf,0,sizeof(linebuf));
charcount=0;
}
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();
Serial.println("client disonnected");
}
}
Basically this is the 'Webserver" example program from Arduino, with some additional security. You would have to know Username and Password to enter the website. In this example use these data to get access to your Arduino webserver: User: satarun Pass: password I know, the password "password" is not very secure, but this code is for demonstration only, you can change it as you like.
I would like to use this on my webpage but I was wondering if there was a way to make a logout button or if you could make it log you in everytime you visit the webpage?
zward:
I would like to use this on my webpage but I was wondering if there was a way to make a logout button
The "Basic Authentication" is so very, very old, it was never intended to log out the user during a session.
Typically the only way to "log out" is to close the webbrowser and then re-open the webbrowser. Then the browser has forgotten all the authentication credentials used since last starting the webbrowser and will ask again for user/password. That's the only way I know about.
It should be possible to circumvent that with some efforts and knowledge about HTML, HTTP, webservers and webbrowsers, but possibly the solution would be browser-dependent and won't work with every browser. Just closing the browser and opening it again should work to log out the user with each and every webbrowser. Isn't that enough for you?
zward:
if you could make it log you in everytime you visit the webpage?
It would be a function of your webbrowser to remember your login data for user/password.
For "Google Chrome" Android (mobile) webbrowser see here about enabling or disabling and using the "save passwords" function. For other webbrowsers refer to the manual of your webbrowser.
In default configuration all of the commonly used webbrowsers should handle it like that:
- After entering a user authentication the browser will ask you "Save Password? Yes - No - Never"
- If you answer "Yes", your username/password will be filled in next time automatically, you just enter OK.
- If you answer "No", you will have to enter username/password manually and will be asked again
- If you answer "Never", you will have to enter username/password manually every time and will never be asked again about "Save Password for this website?" in the future.
In case you made the "Never Save Password" decision in Google Chrome earlier, but you make up your mind and now want to fill in the password from this browser automatically, you will have to edit the "Never Saved List" in your "Saved passwords" configuration of Google Chrome.
Saving and automatically filling in or even automatically sending of passwords is always a function of your webbrowser and not a function of the webserver.
jurs:
I know, the password "password" is not very secure, but this code is for demonstration only, you can change it as you like.
Thank you for your nice sketch.
Could somebody kindly explain me how to change this id and password? I'm stuck in this!
Stex
Just found how to change id and pass!
if (strstr(linebuf,"Authorization: Basic")>0 && strstr(linebuf,"PHN0ZXgyMDA1Pjo8ZnJhdGF0MjAwNT4NCg==")>0)
Although, the string PHN0ZXgyMDA1Pjo8ZnJhdGF0MjAwNT4NCg== may look encrypted it is simply a base64 encoded version of :.
Just go to https://www.base64encode.org/ , encode your : and replace it with the Authentication string.
satarun:
I have an arduino program that displays the data about my control element(temperature) on a web page through the arduino Wifi Shield. Kindly tell me how to create a login with password page before entering my temperature control page for security reasons. Kindly suggest on how I can implement this in my wifi shield programming.
Why do you need login with password?
Why not just use the password itself as the temperature control?
Like "blackjack" for 21 degrees, "catch" for 22 degrees, "skidoo" for 23 degrees...
Dear Jurs, thanks for your help. However, when i try to incorporate the HTTP authentication in my code, I'm facing problems. Here's the description :
I have an "index.htm" file loaded onto an SD card in an Ethernet shield.It serves the purpose of sending text from a webpage to the Arduino for display on an LCD. It works fine till here. The problem arises when I try to add basic HTTP authentication to the Arduino web server. The website loads but the text I type there doesn't get displayed on the LCD. I have checked the LCD connections and there are no problems with it. I think it's a problem with my code on the Arduino. Here's the Arduino code without the HTTP authentication :
#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>
#include <LiquidCrystal.h>
// size of buffer used to capture HTTP requests
#define REQ_BUF_SZ 40
// size of buffer that stores a line of text for the LCD + null terminator
#define LCD_BUF_SZ 17
// MAC address from Ethernet shield sticker under board
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1,6); // IP address, may need to change depending on network
EthernetServer server(80); // create a server at port 80
File webFile; // the web page file on the SD card
char HTTP_req[REQ_BUF_SZ] = {0}; // buffered HTTP request stored as null terminated string
char req_index = 0; // index into HTTP_req buffer
char lcd_buf_1[LCD_BUF_SZ] = {0};// buffer to save LCD line 1 text to
char lcd_buf_2[LCD_BUF_SZ] = {0};// buffer to save LCD line 2 text to
LiquidCrystal lcd(10,9,8,7,6,5);
void setup()
{
// disable Ethernet chip
pinMode(10, OUTPUT);
digitalWrite(10, HIGH);
Serial.begin(115200); // for debugging
lcd.begin(16, 2);
// Message on LCD
lcd.print(F("Initializing"));
// initialize SD card
Serial.println("Initializing SD card...");
if (!SD.begin(4)) {
Serial.println("ERROR - SD card initialization failed!");
lcd.print(F("SD init failed"));
return; // init failed
}
Serial.println("SUCCESS - SD card initialized.");
// check for index.htm file
if (!SD.exists("index.htm")) {
Serial.println("ERROR - Can't find index.htm file!");
return; // can't find index file
}
Serial.println("SUCCESS - Found index.htm file.");
Ethernet.begin(mac, ip); // initialize Ethernet device
server.begin(); // start to listen for clients
// End of initialization message on LCD + print IP address
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(F("Done."));
lcd.setCursor(0, 1);
lcd.print(ip);
}
void loop()
{
EthernetClient client = server.available(); // try to get client
if (client) { // got client?
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) { // client data available to read
char c = client.read(); // read 1 byte (character) from client
// limit the size of the stored received HTTP request
// buffer first part of HTTP request in HTTP_req array (string)
// leave last element in array as 0 to null terminate string (REQ_BUF_SZ - 1)
if (req_index < (REQ_BUF_SZ - 1)) {
HTTP_req[req_index] = c; // save HTTP request character
req_index++;
}
// last line of client request is blank and ends with \n
// respond to client only after last line received
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
// remainder of header follows below, depending on if
// web page or XML page is requested
// Ajax request - send XML file
if (StrContains(HTTP_req, "ajax_inputs")) {
// send rest of HTTP header
client.println("Content-Type: text/xml");
client.println("Connection: keep-alive");
client.println();
// print the received text to the LCD if found
if (GetLcdText(lcd_buf_1, lcd_buf_2, LCD_BUF_SZ)) {
// lcd_buf_1 and lcd_buf_2 now contain the text from
// the web page
// write the received text to the LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(lcd_buf_1);
lcd.setCursor(0, 1);
lcd.print(lcd_buf_2);
}
}
else { // web page request
// send rest of HTTP header
client.println("Content-Type: text/html");
client.println("Connection: keep-alive");
client.println();
// send web page
webFile = SD.open("index.htm"); // open web page file
if (webFile) {
Serial.println("Successfully opened webfile");
while(webFile.available()) {
client.write(webFile.read()); // send web page to client
}
webFile.close();
}
}
// reset buffer index and all buffer elements to 0
req_index = 0;
StrClear(HTTP_req, REQ_BUF_SZ);
break;
}
// every line of text received from the client ends with \r\n
if (c == '\n') {
// last character on line of received text
// starting new line with next character read
currentLineIsBlank = true;
}
else if (c != '\r') {
// a text character was received from client
currentLineIsBlank = false;
}
} // end if (client.available())
} // end while (client.connected())
delay(1); // give the web browser time to receive the data
client.stop(); // close the connection
} // end if (client)
}
// get the two strings for the LCD from the incoming HTTP GET request
boolean GetLcdText(char *line1, char *line2, int len)
{
...
}
// searches for the string sfind in the string str
// returns 1 if string found
// returns 0 if string not found
char StrContains(char *str, char *sfind)
{...
}
Here's the code after adding authentication:
#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>
#include <LiquidCrystal.h>
// size of buffer used to capture HTTP requests
#define REQ_BUF_SZ 40
// size of buffer that stores a line of text for the LCD + null terminator
#define LCD_BUF_SZ 17
// MAC address from Ethernet shield sticker under board
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1,12); // IP address, may need to change depending on network
EthernetServer server(80); // create a server at port 80
File webFile; // the web page file on the SD card
char HTTP_req[REQ_BUF_SZ] = {0}; // buffered HTTP request stored as null terminated string
char req_index = 0; // index into HTTP_req buffer
char lcd_buf_1[LCD_BUF_SZ] = {0};// buffer to save LCD line 1 text to
char lcd_buf_2[LCD_BUF_SZ] = {0};// buffer to save LCD line 2 text to
LiquidCrystal lcd(10,9,8,7,6,5);
void setup()
{
// disable Ethernet chip
pinMode(10, OUTPUT);
digitalWrite(10, HIGH);
Serial.begin(115200); // for debugging
lcd.begin(16, 2);
// Message on LCD
lcd.print(F("Initializing"));
// initialize SD card
Serial.println(F("Initializing SD card..."));
if (!SD.begin(4)) {
Serial.println(F("ERROR - SD card initialization failed!"));
lcd.print(F("SD init failed"));
return; // init failed
}
Serial.println(F("SUCCESS - SD card initialized."));
// check for index.htm file
if (!SD.exists("index.htm")) {
Serial.println(F("ERROR - Can't find index.htm file!"));
return; // can't find index file
}
Serial.println(F("SUCCESS - Found index.htm file."));
Ethernet.begin(mac, ip); // initialize Ethernet device
server.begin(); // start to listen for clients
// End of initialization message on LCD + print IP address
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(F("Done."));
lcd.setCursor(0, 1);
lcd.print(ip);
}
void SendAuthentificationpage(EthernetClient &client)
{
client.println("HTTP/1.1 401 Authorization Required");
client.println("WWW-Authenticate: Basic realm=\"Secure Area\"");
client.println("Content-Type: text/html");
client.println("Connnection: close");
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<HTML> <HEAD> <TITLE>Error</TITLE>");
client.println(" </HEAD> <BODY><H1>401 Unauthorized.</H1></BODY> </HTML>");
}
boolean authentificated=false;
void loop()
{
EthernetClient client = server.available(); // try to get client
if (client) { // got client?
memset(HTTP_req,0,sizeof(HTTP_req));
authentificated=false;
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) { // client data available to read
char c = client.read(); // read 1 byte (character) from client
// limit the size of the stored received HTTP request
// buffer first part of HTTP request in HTTP_req array (string)
// leave last element in array as 0 to null terminate string (REQ_BUF_SZ - 1)
if (req_index < (REQ_BUF_SZ - 1)) {
HTTP_req[req_index] = c; // save HTTP request character
req_index++;
}
Serial.println(HTTP_req);
// last line of client request is blank and ends with \n
// respond to client only after last line received
if (c == '\n' && currentLineIsBlank) {
if(authentificated){
// send a standard http response header
client.println("HTTP/1.1 200 OK");
// remainder of header follows below, depending on if
// web page or XML page is requested
// Ajax request - send XML file
if (StrContains(HTTP_req, "ajax_inputs")) {
// send rest of HTTP header
Serial.println(F("Receiving text"));
client.println("Content-Type: text/xml");
client.println("Connection: keep-alive");
client.println();
// print the received text to the LCD if found
if (GetLcdText(lcd_buf_1, lcd_buf_2, LCD_BUF_SZ)) {
// lcd_buf_1 and lcd_buf_2 now contain the text from
// the web page
// write the received text to the LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(lcd_buf_1);
//lcd.setCursor(0, 1);
//lcd.print(lcd_buf_2);
}
}
else { // web page request
// send rest of HTTP header
client.println("Content-Type: text/html");
client.println("Connection: keep-alive");
client.println();
// send web page
webFile = SD.open("index.htm"); // open web page file
if (webFile) {
Serial.println(F("Successfully opened webfile"));
while(webFile.available()) {
client.write(webFile.read()); // send web page to client
}
webFile.close();
}
}
// reset buffer index and all buffer elements to 0
req_index = 0;
StrClear(HTTP_req, REQ_BUF_SZ);
break;
}
else {
SendAuthentificationpage(client);
}
break;
}
// every line of text received from the client ends with \r\n
if (c == '\n') {
// last character on line of received text
// starting new line with next character read
if (strstr(HTTP_req,"Authorization: Basic")>0 && strstr(HTTP_req,"ZWNlOm5vdGljZQ==")>0)
authentificated=true;
memset(HTTP_req,0,sizeof(HTTP_req));
req_index=0;
currentLineIsBlank = true;
}
else if (c != '\r') {
// a text character was received from client
currentLineIsBlank = false;
}
} // end if (client.available())
} // end while (client.connected())
delay(1); // give the web browser time to receive the data
client.stop(); // close the connection
} // end if (client)
} // rest of the code is same as without authentication
The website loads properly. In the code, if the GET request contains the string "ajax_input", then the text I type in the website must be displayed on the LCD. However, this is not happening. I'm struck here. Kindly help guys !
hello jurst . you can help me expand more examples :
" How to make a sign in using HTML forms that connect to the next page ," ... on the sd memory card
code wants to expand
#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>
#define REQ_BUF_SZ 60
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 102);
EthernetServer server(80);
File webFile;
char HTTP_req[REQ_BUF_SZ] = {0};
char req_index = 0;
boolean LED_state[4] = {0};
void setup()
{
pinMode(10, OUTPUT);
digitalWrite(10, HIGH);
Serial.begin(9600);
Serial.println("Initializing SD card...");
if (!SD.begin(4)) {
Serial.println("ERROR - SD card initialization failed!");
return;
}
Serial.println("SUCCESS - SD card initialized.");
if (!SD.exists("index.htm")) {
Serial.println("ERROR - Can't find index.htm file!");
return; //
}
Serial.println("SUCCESS - Found index.htm file.");
pinMode(2, INPUT);
pinMode(3, INPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
Ethernet.begin(mac, ip);
server.begin();
}
void loop()
{
EthernetClient client = server.available();
if (client) {
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
if (req_index < (REQ_BUF_SZ - 1)) {
HTTP_req[req_index] = c;
req_index++;
}
if (c == '\n' && currentLineIsBlank) {
client.println("HTTP/1.1 200 OK");
if (StrContains(HTTP_req, "ajax_inputs")) {
client.println("Content-Type: text/xml");
client.println("Connection: keep-alive");
client.println();
SetLEDs();
XML_response(client);
}
else {
client.println("Content-Type: text/html");
client.println("Connection: keep-alive");
client.println();
webFile = SD.open("index.htm");
if (webFile) {
while(webFile.available()) {
client.write(webFile.read());
}
webFile.close();
}
}
Serial.print(HTTP_req);
req_index = 0;
StrClear(HTTP_req, REQ_BUF_SZ);
break;
}
if (c == '\n') {
currentLineIsBlank = true;
}
else if (c != '\r') {
currentLineIsBlank = false;
}
}
}
delay(1);
client.stop();
}
}
void SetLEDs(void)
{
// LED 1 (pin 6)
if (StrContains(HTTP_req, "LED1=1")) {
LED_state[0] = 1; // save LED state
digitalWrite(6, HIGH);
}
else if (StrContains(HTTP_req, "LED1=0")) {
LED_state[0] = 0; // save LED state
digitalWrite(6, LOW);
}
// LED 2 (pin 7)
if (StrContains(HTTP_req, "LED2=1")) {
LED_state[1] = 1; // save LED state
digitalWrite(7, HIGH);
}
else if (StrContains(HTTP_req, "LED2=0")) {
LED_state[1] = 0; // save LED state
digitalWrite(7, LOW);
}
// LED 3 (pin 8)
if (StrContains(HTTP_req, "LED3=1")) {
LED_state[2] = 1; // save LED state
digitalWrite(8, HIGH);
}
else if (StrContains(HTTP_req, "LED3=0")) {
LED_state[2] = 0;
digitalWrite(8, LOW);
}
if (StrContains(HTTP_req, "LED4=1")) {
LED_state[3] = 1;
digitalWrite(9, HIGH);
}
else if (StrContains(HTTP_req, "LED4=0")) {
LED_state[3] = 0;
digitalWrite(9, LOW);
}
}
void XML_response(EthernetClient cl)
{
int analog_val;
int count;
int sw_arr[] = {2, 3};
cl.print("<?xml version = \"1.0\" ?>");
cl.print("");
for (count = 0; count < 2; count++) {
cl.print("");
if (digitalRead(sw_arr[count])) {
cl.print("bật");
}
else {
cl.print("tắt");
}
cl.println("");
}
cl.print("");
if (LED_state[0]) {
cl.print("checked");
}
else {
cl.print("unchecked");
}
cl.println("");
cl.print("");
if (LED_state[1]) {
cl.print("checked");
}
else {
cl.print("unchecked");
}
cl.println("");
cl.print("");
if (LED_state[2]) {
cl.print("on");
}
else {
cl.print("off");
}
cl.println("");
cl.print("");
if (LED_state[3]) {
cl.print("on");
}
else {
cl.print("off");
}
cl.println("");
cl.print("");
}
void StrClear(char *str, char length)
{
for (int i = 0; i < length; i++) {
str = 0;
-
}*
}
char StrContains(char *str, char *sfind)
{ -
char found = 0;*
-
char index = 0;*
-
char len;*
-
len = strlen(str);*
-
if (strlen(sfind) > len) {*
-
return 0;*
-
}*
-
while (index < len) {*
-
if (str[index] == sfind[found]) {*
-
found++;*
-
if (strlen(sfind) == found) {*
-
return 1;*
-
}*
-
}*
-
else {*
-
found = 0;*
-
}*
-
index++;*
-
}*
-
return 0;*
}
help me
thıs ıs my code