Lab2_web / Mbed 2 deprecated webserverBlinky

Dependencies:   mbed

Fork of webserverBlinky by RealTimeCompLab2

Revision:
81:9ede60e9a2c8
Parent:
80:753f5dd2e84e
Child:
82:051f77f7dd72
diff -r 753f5dd2e84e -r 9ede60e9a2c8 main.cpp
--- a/main.cpp	Wed Jul 12 05:08:51 2017 +0000
+++ b/main.cpp	Sat Jul 15 20:50:13 2017 +0000
@@ -1,12 +1,11 @@
-#include "mbed.h"
+// PPP-Blinky - "My Internet Of Thing"
 
-// Copyright 2016 Nicolas Nackel aka Nixnax. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-// PPP-Blinky - "My Internet Of Thing"
 // A Tiny Webserver Using Windows XP/7/8/10 Dial-Up Networking Over A Serial Port.
 
 // Also receives UDP packets and responds to ping (ICMP Echo requests)
 
+// Copyright 2016 Nicolas Nackel aka Nixnax. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
 // Notes and Instructions
 // http://bit.ly/PPP-Blinky-Instructions
 
@@ -26,10 +25,11 @@
 // https://technet.microsoft.com/en-us/sysinternals/pstools.aspx - psping for fast testing of ICMP ping function
 // https://eternallybored.org/misc/netcat/ - use netcat -u 172.10.10.1 80 to send/receive UDP packets from PPP-Blinky
 
+#include "mbed.h"
 
 // The #define below enables/disables a SECOND (optional) serial port that prints out interesting diagnostic messages.
 // Change to SERIAL_PORT_MONITOR_YES to enable diagnostics messages. You need to wire a second serial port to your mbed hardware to monitor this.
-#define SERIAL_PORT_MONITOR_NO /* or change to SERIAL_PORT_MONITOR_YES */
+#define SERIAL_PORT_MONITOR_YES /* or change to SERIAL_PORT_MONITOR_YES */
 
 #ifndef SERIAL_PORT_MONITOR_NO
 Serial xx(PC_10, PC_11); // Not required to run, if you get compile error here, change #define SERIAL_PORT_MONITOR_YES to #define SERIAL_PORT_MONITOR_NO
@@ -39,9 +39,9 @@
 #endif
 
 // verbosity flag used in debug printouts - change to 0 to see less debug info. Lots of interesting info.
-#define v0 1
+#define v0 0
 // verbosity flag used in debug printouts - change to 0 to see less debug info. Lots of interesting info.
-#define v1 1
+#define v1 0
 // verbosity flag used in debug printouts - change to 0 to see less debug info. Lots of interesting info.
 #define v2 0
 
@@ -89,11 +89,12 @@
     int crc; // for calculating IP and TCP CRCs
     int ledState; // state of LED1
     struct {
-#define BUFLEN (1<<13)
-        char buf[BUFLEN]; // BUFLEN MUST be a power of two because we use & operator for fast wrap-around in rxHandler
+#define RXBUFLEN (1<<14)
+        char buf[RXBUFLEN]; // RXBUFLEN MUST be a power of two because we use & operator for fast wrap-around in rxHandler
         //char * buf;
         volatile int head;
         volatile int tail;
+        volatile int buflevel;
     } rx; // serial port objects
     struct {
         int len; // number of bytes in buffer
@@ -105,7 +106,7 @@
     struct {
         int frameStartIndex; // frame start marker
         int frameEndIndex; // frame end marker
-        int frameBusy; // busy capturing a frame
+        int frameFound; // we have found at least one start of frame already
     } hdlc; // hdlc frame objects
 };
 
@@ -114,14 +115,18 @@
 // Initialize our globals
 void pppInitStruct()
 {
+    memset( ppp.rx.buf, 0, RXBUFLEN);
     ppp.online=0;
+    __disable_irq();
     ppp.rx.tail=0;
     ppp.rx.head=0;
+    __enable_irq();
+    ppp.rx.buflevel=0;
     ppp.pkt.len=0;
     ppp.ident=0;
-    ppp.seq=1000;
     ppp.ledState=0;
-    ppp.hdlc.frameBusy=0;
+    ppp.hdlc.frameFound=0;
+    ppp.hdlc.frameStartIndex=0;
 }
 
 void led1Toggle()
@@ -153,10 +158,11 @@
 void rxHandler() // serial port receive interrupt handler
 {
     while ( pc.readable() ) {
-        int hd = (ppp.rx.head+1)&(BUFLEN-1); // increment/wrap
+        int hd = (ppp.rx.head+1)&(RXBUFLEN-1); // increment/wrap
         if ( hd == ppp.rx.tail ) break; // watch for buffer full
         ppp.rx.buf[ppp.rx.head]=pc.getc(); // insert in rx buffer
         ppp.rx.head = hd; // update head pointer
+        ppp.rx.buflevel++;
     }
 }
 
@@ -170,10 +176,9 @@
 
 int pc_getBuf() // get one character from the buffer
 {
-    __disable_irq(); // critical section start
     int x = ppp.rx.buf[ ppp.rx.tail ];
-    ppp.rx.tail=(ppp.rx.tail+1)&(BUFLEN-1);
-    __enable_irq(); // critical section end
+    ppp.rx.tail=(ppp.rx.tail+1)&(RXBUFLEN-1);
+    ppp.rx.buflevel--;
     return x;
 }
 
@@ -204,7 +209,7 @@
             crcDo(ppp.rx.buf[idx]^0x20);
             unstuff=0;
         }
-        idx = (idx+1) & (BUFLEN-1);
+        idx = (idx+1) & (RXBUFLEN-1);
         if (idx == end) break;
     }
     ppp.pkt.crc = ppp.crc & 0xffff;
@@ -316,12 +321,12 @@
 #endif
 #define UDP_HEADER_SIZE 8
     int udpLength = ((udpLen[0]<<8) | udpLen[1]) - UDP_HEADER_SIZE; // size of the actual udp data
-    if(v1) debug("UDP %d.%d.%d.%d:%d ", srcIP[0],srcIP[1],srcIP[2],srcIP[3],srcPort);
-    if(v1) debug("%d.%d.%d.%d:%d ",     dstIP[0],dstIP[1],dstIP[2],dstIP[3],dstPort);
-    debug("Len %d ", udpLength);
+    if(v0) debug("UDP %d.%d.%d.%d:%d ", srcIP[0],srcIP[1],srcIP[2],srcIP[3],srcPort);
+    if(v0) debug("%d.%d.%d.%d:%d ",     dstIP[0],dstIP[1],dstIP[2],dstIP[3],dstPort);
+    if(v0) debug("Len %d ", udpLength);
     int printSize = udpLength;
     if (printSize > 20) printSize = 20; // print only first 20 characters
-    if (v0) {
+    if (v1) {
         for (int i=0; i<printSize; i++) {
             char ch = udpInf[i];
             if (ch>31 && ch<127) {
@@ -397,8 +402,8 @@
         int icmpIdent = (icmpType[4]<<8)|icmpType[5];
         int icmpSequence = (icmpType[6]<<8)|icmpType[7];
 #endif
-        debug("ICMP PING %d.%d.%d.%d %d.%d.%d.%d ", srcAdr[0],srcAdr[1],srcAdr[2],srcAdr[3],dstAdr[0],dstAdr[1],dstAdr[2],dstAdr[3]);
-        debug("Ident %04x Sequence %04d ",icmpIdent,icmpSequence);
+        if(v0) debug("ICMP PING %d.%d.%d.%d %d.%d.%d.%d ", srcAdr[0],srcAdr[1],srcAdr[2],srcAdr[3],dstAdr[0],dstAdr[1],dstAdr[2],dstAdr[3]);
+        if(v0) debug("Ident %04x Sequence %04d ",icmpIdent,icmpSequence);
         char src[4];
         char dst[4];
         memcpy(src, srcAdr,4);
@@ -489,34 +494,35 @@
 
 void dumpHeaderTCP()
 {
-    int headerSizeIP     = (ppp.pkt.buf[4]&0xf)*4; // header size of ip portion
-    char * tcpStart      =  ppp.pkt.buf+4+headerSizeIP; // start of tcp packet
+    if( v1 ) {
+
+        int headerSizeIP     = (ppp.pkt.buf[4]&0xf)*4; // header size of ip portion
+        char * tcpStart      =  ppp.pkt.buf+4+headerSizeIP; // start of tcp packet
 #ifndef SERIAL_PORT_MONITOR_NO
-    char * seqtcp        = tcpStart + 4;  // 4 bytes
-    char * acktcp        = tcpStart + 8;  // 4 bytes
+        char * seqtcp        = tcpStart + 4;  // 4 bytes
+        char * acktcp        = tcpStart + 8;  // 4 bytes
 #endif
-    char * flagbitstcp   = tcpStart + 12; // 9 bits
+        char * flagbitstcp   = tcpStart + 12; // 9 bits
 #ifndef SERIAL_PORT_MONITOR_NO
-    unsigned int seq = (seqtcp[0]<<24)|(seqtcp[1]<<16)|(seqtcp[2]<<8)|(seqtcp[3]);
-    unsigned int ack = (acktcp[0]<<24)|(acktcp[1]<<16)|(acktcp[2]<<8)|(acktcp[3]);
+        unsigned int seq = (seqtcp[0]<<24)|(seqtcp[1]<<16)|(seqtcp[2]<<8)|(seqtcp[3]);
+        unsigned int ack = (acktcp[0]<<24)|(acktcp[1]<<16)|(acktcp[2]<<8)|(acktcp[3]);
 #endif
-    int flags = ((flagbitstcp[0]&1)<<8)|flagbitstcp[1];
+        int flags = ((flagbitstcp[0]&1)<<8)|flagbitstcp[1];
 
-    char flagInfo[10]; // text string presentating the TCP flags
-    memset(flagInfo,'.', 9); // fill string with "........."
-    memset(flagInfo+9,0,1); // null terminate string
+        char flagInfo[10]; // text string presentating the TCP flags
+        memset(flagInfo,'.', 9); // fill string with "........."
+        memset(flagInfo+9,0,1); // null terminate string
 
-    if (flags & (1<<0)) flagInfo[0]='F';
-    if (flags & (1<<1)) flagInfo[1]='S';
-    if (flags & (1<<2)) flagInfo[2]='R';
-    if (flags & (1<<3)) flagInfo[3]='P';
-    if (flags & (1<<4)) flagInfo[4]='A';
-    if (flags & (1<<5)) flagInfo[5]='U';
-    if (flags & (1<<6)) flagInfo[6]='E';
-    if (flags & (1<<7)) flagInfo[7]='C';
-    if (flags & (1<<8)) flagInfo[8]='N';
-    if (v1) {
-        debug("Flags %s Seq %u Ack %u\n", flagInfo, seq, ack); // show the flags in debug
+        if (flags & (1<<0)) flagInfo[0]='F';
+        if (flags & (1<<1)) flagInfo[1]='S';
+        if (flags & (1<<2)) flagInfo[2]='R';
+        if (flags & (1<<3)) flagInfo[3]='P';
+        if (flags & (1<<4)) flagInfo[4]='A';
+        if (flags & (1<<5)) flagInfo[5]='U';
+        if (flags & (1<<6)) flagInfo[6]='E';
+        if (flags & (1<<7)) flagInfo[7]='C';
+        if (flags & (1<<8)) flagInfo[8]='N';
+        debug("TCP Flags %s Seq %u Ack %u\n", flagInfo, seq, ack); // show the flags in debug
     }
 }
 
@@ -599,10 +605,10 @@
 
     char * dataStart = ppp.pkt.buf + 4 + headerSizeIP + headerSizeTCP; // start of data block after TCP header
     int tcpDataSize = tcpSize - headerSizeTCP; // size of data block after TCP header
-    
+
     unsigned int ack = (seqtcp[0]<<24)|(seqtcp[1]<<16)|(seqtcp[2]<<8)|(seqtcp[3]) + tcpDataSize;
     unsigned int seq = (acktcp[0]<<24)|(acktcp[1]<<16)|(acktcp[2]<<8)|(acktcp[3]); // use their idea of our seq
-    
+
 
 #define TCP_FLAG_ACK (1<<4)
 #define TCP_FLAG_SYN (1<<1)
@@ -624,7 +630,7 @@
             ack++;
         case TCP_FLAG_SYN:
             flagsOut = TCP_FLAG_SYN | TCP_FLAG_ACK; // something wants to connect - ack it
-            ppp.seq = ppp.seq + 12345; // create a new sequence number (normally random)
+            ppp.seq = ppp.seq + 10000; // create a new sequence number (normally random)
             seq = ppp.seq; // create a new sequence number (normally random)
             ack++; // for SYN flag we have to increase their sequence by 1
             break;
@@ -648,7 +654,7 @@
         default:
             return; // ignore remaining packets
     }
-    
+
 
     // The TCP flag handling is now done
     // Now we have to recalculate all the header sizes, swap IP address/port source and destination, and do the IP and TCP checksums
@@ -709,11 +715,12 @@
     if (fastResponse==1) {
         fastResponse=0; // reset and skip 200 ms wait
     } else {
-        // normally, you wait 200 ms before sending a TCP packet
+        // normally, you wait 200 ms before responding to a TCP packet
         // remove the wait to respond faster
         // wait(0.2);
     }
-    sendFrame(); // All done! Send the TCP packet
+    dumpHeaderTCP();
+    sendFrame(); // All preparation complete - send the TCP response
 }
 
 void dumpDataTCP()
@@ -771,10 +778,7 @@
     if (v0) {
         debug("i%04x f%d t%d p%d C%04x\n",identIP,flagsIP,ttlIP,protocolIP,checksumIP);
     }
-    if (v1) {
-        dumpHeaderTCP();
-    }
-
+    dumpHeaderTCP();
     if (v2) {
         dumpDataTCP();
     }
@@ -831,10 +835,11 @@
 
 void LCPend()
 {
-    debug("LCP End\n");
-    ppp.online=0; // start hunting for connect string again
     ppp.pkt.buf[4]=6;
     sendFrame(); // acknowledge
+    ppp.online=0; // start hunting for connect string again
+    pppInitStruct(); // flush the receive buffer
+    debug("LCP End\n");
 }
 
 void LCPother()
@@ -900,40 +905,47 @@
 
 void wait_for_HDLC_frame()
 {
-    while ( rxbufNotEmpty() ) {
-        int rx = pc_getBuf();
-        if (ppp.hdlc.frameBusy) {
+    while(1)
+        if ( rxbufNotEmpty() ) {
+            int oldTail = ppp.rx.tail; // remember where the character is located in the buffer
+            int rx = pc_getBuf(); // get the character
             if (rx==FRAME_7E) {
-                if (ppp.rx.tail == 0) { // did we just wrap around?
-                    ppp.hdlc.frameEndIndex=BUFLEN-1; // wrap back to end of buffer
+                if (ppp.hdlc.frameFound == 0) { // we are still waiting for a frame start
+                    ppp.hdlc.frameFound = 1; // we found our first frame start
+                    ppp.hdlc.frameStartIndex=ppp.rx.tail;  // remember where the frame character is in the buffer
                 } else {
-                    ppp.hdlc.frameEndIndex=ppp.rx.tail-1; // remember where frame ends
+                    // we have previously found a frame start
+                    ppp.hdlc.frameEndIndex=oldTail; // mark the frame end character
+                    processHDLCFrame(ppp.hdlc.frameStartIndex, ppp.hdlc.frameEndIndex); // process the frame
+                    ppp.hdlc.frameStartIndex = ppp.rx.tail; // where next frame will start
+                    break;
                 }
-                processHDLCFrame(ppp.hdlc.frameStartIndex, ppp.hdlc.frameEndIndex);
-                ppp.hdlc.frameStartIndex = ppp.rx.tail; // where next frame will start
-            }
-        } else {
-            if (rx==FRAME_7E) {
-                ppp.hdlc.frameBusy=1; // start gathering frame
-                ppp.hdlc.frameStartIndex=ppp.rx.tail; // remember where frame started
             }
         }
-    }
 }
 
 void scanForConnectString()
 {
-    if ( ppp.online==0 ) {
-        // look for Windows Dialup Networking "Direct Connection Between Two Computers" expected connect string
-        char * clientFound = strstr( (char *)ppp.rx.buf, "CLIENTCLIENT" );
-        if( clientFound ) {
-            strcpy( clientFound, "FOUND!FOUND!" ); // overwrite so we don't find it again
-            // respond with Windows Dialup networking expected "Direct Connection Between Two Computers" response string
-            pc.printf("CLIENTSERVER");
+    while(ppp.online == 0) {
+        // search for Windows Dialup Networking "Direct Connection Between Two Computers" expected connect string
+        char * found1 = strstr( (char *)ppp.rx.buf, "CLIENTCLIENT" );
+        // also search for HDLC frame start character 0x7e
+        void * found2 = memchr( (char *)ppp.rx.buf, 0x7e, RXBUFLEN );
+        if( (found1 != NULL) | (found2 != NULL) ) {
+            if (found1 != NULL) {
+                //strcpy( found1, "FOUND!FOUND!" ); // overwrite so we don't find it again
+                // respond with Windows Dialup networking expected "Direct Connection Between Two Computers" response string
+                memset(ppp.rx.buf, 0, RXBUFLEN); // clear the receive buffer
+                pc.puts("CLIENTSERVER");
+                if (v0) debug("Found connect string \"CLIENTCLIENT\"\n");
+            }
+            if (found2 != NULL) {
+                if (v0) debug("Found HDLC frame start (7E)\n");
+            }
             ppp.online=1; // we are connected, so stop looking for the string
-            debug("Connect string found\n");
         }
     }
+
 }
 
 int main()
@@ -944,9 +956,15 @@
     xx.puts("\x1b[2J\x1b[HReady\n"); // VT100 code for clear screen & home
 #endif
     pppInitStruct(); // initialize all the PPP properties
+    ppp.seq=1000; // initial TCP sequence number
+
     pc.attach(&rxHandler,Serial::RxIrq); // start the receive handler
     while(1) {
+        debug("scan\n");
         scanForConnectString(); // respond to connect command from windows dial up networking
-        wait_for_HDLC_frame();
+        debug("found\n");
+        while(ppp.online) {
+            wait_for_HDLC_frame();
+        }
     }
 }