enc28J60 e Arduino (17)

luca 19/12/2013 18

In alcuni tutorial precedenti, avete già imparato a realizzare semplici pagine web per comandare a distanza led, relay… oggi vi mostrerò come rendere queste pagine sicure grazie ad una password.

Form web

La pagina web pubblicata da Arduino contiene una semplice form, composta da due pulsanti e da un campo di input per la password:

Alla pressione del pulsante, viene inviato ad Arduino un comando POST contenente – oltre ad informazioni del browser – i dati della form:

Dallo screenshot si può notare come i dati siano concatenati dal carattere & e il valore del campo password sia specificato dopo l’etichetta pwd=.

Sketch

Il codice in esecuzione su Arduino (lo trovate nel repository Github), alla ricezione di una nuova richiesta, esegue le seguenti operazioni:

  • verifica se la richiesta è di tipo POST
  • in questo caso, estrae dalla richiesta il valore della password e la confronta con quella memorizzata
  • se la password è corretta, estrae dalla richiesta il pulsante (ON|OFF) premuto
  • modifica lo stato dell’uscita
  • restituisce la pagina HTML

Vediamolo nel dettaglio:

char* led_password = "SesamE";

la password è inserita hardcoded nello sketch, di default sarà SesamE

pinMode(led_pin, OUTPUT);
digitalWrite(led_pin, LOW);
led_status = false;

all’interno del setup() avviene l’inizializzazione del PIN e dello stato dell’uscita (di default spenta)

if(strstr((char *)Ethernet::buffer + pos, "POST /") != 0) {

lo sketch verifica – tramite la funzione strstr() – se il pacchetto ricevuto contiene il comando POST /

char* password_position = strstr((char *)Ethernet::buffer + pos, "&pwd=");
if(password_position != 0) {
  strcpy(password, password_position + 5);
  if(strcmp(password, led_password) == 0) Serial.println("Valid password :)");

lo sketch cerca la stringa &pwd= nel pacchetto; se la trova estrae la password e la memorizza nella variabile password. Le due password sono quindi confrontate

if(strstr((char *)Ethernet::buffer + pos, "OFF=") != 0) {
digitalWrite(led_pin, LOW);
led_status = false;

se la password è corretta e il pacchetto contiene il comando OFF=, l’uscita viene spenta. Lo stesso controllo avviene per il comando ON=

if(led_status == true) bfill.emit_p(PSTR(
[...]

infine viene generata la pagina HTML, resa dinamica da due if:

  • in base allo stato dell’uscita, uno dei due pulsanti viene disabilitato (aggiungendo l’attributo disabled)
  • se la password non è corretta, viene visualizzato un messaggio di errore

Funzionamento

Ecco due screenshot relativi all’inserimento di una password valida e una sbagliata:

18 Comments »

  1. nasim 20/12/2013 at 10:43 - Reply

    hi …
    i just want to simulate …
    how i get enc28j60 mac address for proteus simulation..

    • luca 23/12/2013 at 08:41 - Reply

      Hi Nasim,

      I never used Proteus but the MAC I think you can use the same mac address I use in my sketches… while the IP address must belong to the same network (simulated one?) you’re using.

  2. jmv 23/01/2014 at 17:26 - Reply

    hi, luca, great site!.
    how I send a TCP packet to a client tcp.
    I intend to make a Modbus server.
    sorry bad english.
    thanks.

    • luca 27/01/2014 at 22:14 - Reply

      Hi Jonas,

      mmm are you asking how to send a tcp packet to a server? give a look to my examples, basically you have to “create” the packet in a Stash object and send to the server using the tcpSend() method.

  3. Tony 22/02/2014 at 16:57 - Reply

    Hi Luca

    how to keep password remember? each time i press the button, the password cleared and i have to enter again and again to control the LED

    • luca 02/03/2014 at 13:44 - Reply

      Hi Tony

      you can include the password in the html page:

      if(password_valid == true) bfill.emit_p(PSTR("

      "), password);

  4. Tunir Saha 08/03/2014 at 08:04 - Reply

    [backSoon]
    DHCP failed
    IP: 0.0.0.0
    GW: 0.0.0.0
    DNS: 0.0.0.0

    Sir any explanation for this ? I don’t know how to figure this out.

    • luca 15/03/2014 at 10:45 - Reply

      Hi Tunir,

      it seems Arduino can’t obtain an IP address from your DHCP: have you a DHCP server in your network?

  5. meka 27/04/2014 at 21:19 - Reply

    luca
    how to add multiple input
    if i use 3 input type time
    like this
    “”
    “”
    “”
    if i am runing com serial only see
    ON=&tm1=01%3A02
    i this only receive input time 1
    do you any solution???
    thanks luca

    • luca 29/04/2014 at 21:01 - Reply

      hi meka, unfortunately your code was lost, by the way in this example you can see how I control two leds… you can easily adapt it for more outputs.

  6. Krunal 14/05/2014 at 13:24 - Reply

    Hi Luca…
    Very Good Tutorials for a Ethernet beginner like me…
    You have presented everything in very simple & understandable language.
    Thanks a lot for posting them & making them available to all of us…
    Have you compiled all the examples in one single document including codes?
    can I get the link for the same?
    Thanks a lot again…

    • luca 19/05/2014 at 20:30 - Reply

      Hi Krunal,

      all the examples are on Github, you can download a zip with all the sources from there.

  7. sergio 11/07/2014 at 16:06 - Reply

    hello, sorry for my english, I’m brasilian and were eliminated from the World Cup by Germany 7 x 1 shame. :-(

    you are my last hope, sorry.

    I’m trying to connect a one arduno a ENC28J60 (http://www.dx.com/p/pcb-arduino-enc28j60-ethernet-module-blue-140971. U7_6DnWx3wI) module and a sd card.

    The card will record data from a temperature sensor from time to time, so I can turn off the card most of the time.

    Can you help me? I found a lot of theory about SPI but nothing practical that can help me, I am beginner.

    I would be very grateful for your help, having seen his experience with the module ENC28J60, parabens, your site has helped much mem.

    Thank you

    Sergio

    • luca 14/07/2014 at 15:23 - Reply

      Hi Sergio,

      the only problem is if SD card and enc28j60 share the same “CS” pin… otherwise you can simply connect both to the other SPI pins without any problems. Are you using a shield for SD card?

  8. Sérgio 14/07/2014 at 22:23 - Reply

    Hi Luca, thanks for your reply.

    I’m using a sd done with resistors like this: http://forum.allaboutcircuits.com/showthread.php?t=27913

    Today I called just the network module and tried to control port 8 which is the default (on and off with LOW and HIGH) but could not.

    pinMode (chipSelectRede, OUTPUT);
    digitalWrite (chipSelectRede, HIGH);

    It still works, also tried to connect on port 10 and the same thing.

    Should not have the right network?

    thanks for your help. I’m desperate for this to work.

    • luca 16/07/2014 at 08:41 - Reply

      Hi Sergio,

      which is the error you get from the sketch? Are you trying the most basic one (static or dinamic IP)?

      • sergio 16/07/2014 at 15:50 - Reply

        hello, I’m using testeDHCP, did some adaptation.
        Follow but he printa MAC and.

        I realized that if I comment out the lines:
        pinMode (SD_SS, OUTPUT); / / 8
        digitalWrite (SD_SS, HIGH);
        the sample back to work.

        Thank you for everything

        Code —-
        #include
        #include //add
        #include //add

        const int NW_SS = 10; //add
        const int SD_SS = 4; //add
        File myFile; //add

        static byte mymac[] = { 0×74,0×69,0×69,0x2D,0×30,0×31 };

        byte Ethernet::buffer[700];

        void setup () {
        Serial.begin(9600);
        SPI.begin(); //add
        Serial.println(“\n[testDHCP]“);

        //add

        Serial.println(“— STATUS —”);
        pinMode(NW_SS, OUTPUT); //8
        digitalWrite(NW_SS, HIGH);
        Serial.print(“NW_SS apos pinMode = “);Serial.println(digitalRead(NW_SS));
        pinMode(SD_SS, OUTPUT); //8
        digitalWrite(SD_SS, HIGH);
        Serial.print(“SD_SS apos pinMode = “);Serial.println(digitalRead(SD_SS));

        digitalWrite(SD_SS, HIGH);
        digitalWrite(NW_SS, LOW);

        //add

        Serial.print(“MAC: “);
        for (byte i = 0; i < 6; ++i) {
        Serial.print(mymac[i], HEX);
        if (i < 5)
        Serial.print(':');
        }
        Serial.println();

        if (ether.begin(sizeof Ethernet::buffer, mymac, NW_SS) == 0)
        Serial.println( "Failed to access Ethernet controller");

        Serial.println("Setting up DHCP");
        if (!ether.dhcpSetup())
        Serial.println( "DHCP failed");

        ether.printIp("My IP: ", ether.myip);
        ether.printIp("Netmask: ", ether.netmask);
        ether.printIp("GW IP: ", ether.gwip);
        ether.printIp("DNS IP: ", ether.dnsip);

        // testa_sd();
        }

        void loop () {}

        /*
        void testa_sd(){
        Serial.print("Initializing SD card…");
        if (!SD.begin(SD_SS)) {
        Serial.println("initialization failed!");
        return;
        }
        Serial.println("initialization done.");
        if (SD.exists("example.txt")) {
        Serial.println("example.txt exists.");
        }
        // open a new file and immediately close it:
        Serial.println("Creating example.txt…");
        myFile = SD.open("example.txt", FILE_WRITE);
        myFile.close();
        // chech if the file created
        if (SD.exists("example.txt")){
        Serial.println("example.txt createdexists.");
        }
        else {
        Serial.println("example.txt doesn't exist.");
        }
        }
        */

  9. Ricardo 26/10/2014 at 20:18 - Reply

    This post is perfect, literally! Sending info to the Arduino Webserver without having info on the url is a very good practice. There is a nice post on arduino forum by DaveO, with Zoomkat help, and they use millis() to provide session ID. Joining that with your code, we can make a login form and then turn off or on leds while the session is active. Maybe you can make one tutorial with this in mind. I’ll start my own and share it also.
    Thanks.

Leave A Response »