Small Internet Protocol Stack using a standard serial port.

Dependencies:   mbed

PPP-Blinky - TCP/IP Networking Over a Serial Port

Note: The source code is at the bottom of this page.

/media/uploads/nixnax/blinky-connected.gif
A Windows desktop showing PPP-Blinky in the network connections list.

Describe PPP-Blinky in Three Sentences

PPP-Blinky is a tiny library that enables Internet protocols (IPv4) to any mbed target hardware by using only a serial port.

The code runs on processors with as little as 8k RAM, for example the Nucleo-L053R8 board.

PPP-Blinky uses the industry-standard PPP (Point-to-Point) Protocol and a tiny "stateless" TCP/IP stack.

No Ethernet Port Required

No ethernet port is required - PPP-Blinky uses a serial port to send IP packets to your PC.

PPP-Blinky emulates a standard dial-up modem and therefore connects to Windows, Linux or Adroid machines.

The code runs on most ARM mbed platforms such as the LPC11U24 shown in the picture below:

/media/uploads/nixnax/blinky-to-laptop1.jpg mbed LPC11u24 acting as a webserver to a Windows laptop.

Webserver

The Webserver and WebSocket functions are ideal for building browser-based GUIs on mbed-enabled hardware.

PPP-Blinky's HTTP webserver works with most web clients such as Internet Explorer, Mozilla Firefox, Google Chrome, Safari, Curl, wget and Lynx as well as Microsoft Powershell Invoke-Webrequest command.

In the image below Firefox web browser displays the main web page embedded into PPP-Blinky's code:

/media/uploads/nixnax/ppp-blinky-firefox.jpg Firefox web browser displays a web page embedded into PPP-Blinky's code

WebSocket Service

WebSocket is the most popular protocol standard for real-time bidirectional TCP/IP communication between clients and servers.
In the image below a small Internet Explorer script has connected to PPP-Blinky's WebSocket Service.
A websocket message was then sent by the browser and was echoed back by the WebSocket, triggering the onmessage event in the script.
The WebSocket service enables bidirectional real-time interaction between PPP-Blinky and any element in the browser DOM via JavaScript.
If you already have PPP-Blinky up and running you can test your WebSocket service using this: http://jsfiddle.net/d26cyuh2/112/embedded/result
Websockets are ideal for building browser-based GUIs for mbed hardware.

/media/uploads/nixnax/ppp-blinky-websocke-2.gif

Trying PPP-Blinky on your mbed board

You will need an mbed-enabled hardware board: https://developer.mbed.org/platforms/

Establish a serial port connection between your host PC and your mbed board. The easiest way is to use mbed hardware with a USB serial debug port. I've tried the ST-Micro Nucleo-L476RG, Nucleo-L152RE, Nucleo-F401RE, Nucleo-L432KC, Nucleo-L053R8, mbed-LPC11U24 and mbed-LPC1768 boards and they all work out of the box. Use the mbed online compiler to compile the software for your target board. Save the compiled binary to your hardware.

Before establishing a network connection, you can verify the operation of the code by opening a terminal program such as Tera Term, and setting the baud rate of the COM port on your mbed board to 115200 baud. LED1 should toggle for every two 0x7E (~) (i.e. tilde) characters you type, as 0x7E is the PPP frame start/end marker. Don't forget to close the port when your'e done testing, or else Windows Dial-up Networking will report that the COM port is in use by another program when you try to connect.

Once you are certain that the serial port and firmware is working, proceed to creating a new network connection on your PC -see below.

Creating a Dial-up Connection in Windows

/media/uploads/nixnax/modem.jpg

Setting up Dial-Up Networking (DUN) on your Windows 7 or 8 PC is essentially a two-step process: First, you create a new modem device, because PPP-blinky partially emulates a standard Windows serial port modem device. Second, you create a new Internet connection (in practice, a new network adapter) which is associated with your new "modem".

Step-by-step description of how to configure Windows for PPP-Blinky here:

/users/nixnax/code/PPP-Blinky/wiki/Configuring-Windows-Dial-Up-Networking

There is also a screen on how to set up Linux dial-up networking near the bottom of this page.

Connecting to PPP-Blinky from your PC

Once Windows networking is configured you can establish a dial-up connection to your mbed board over the USB virtual com port.

The IP address you manually assigned to the new dial-up network adapter (172.10.10.1) functions as a gateway to any valid IP address on that subnet. In the screen capture below, I'm sending pings from the Windows 8 command line to my ST-Micro Nucleo-L476RG board over the USB virtual serial Port. I'm also using a second serial port and Tera Term to capture the debug output from a second serial port on the hardware. The optional debug output from the board prints out the IP source and destination address and the first few bytes of the data payload. Note that the source is the adapter IP address, (172.10.10.1 in this case) and the destination is some other address on that subnet - all packets to the subnet are sent to our mbed hardware. For example, you could also ping 172.10.10.123 or, if your PPP-Blinky is running, simply click on this link: http://172.10.10.123

/media/uploads/nixnax/ping-cap-3.gif

One Million Pings!

In the image below the ICMP ("ping") echo reply service was tested by sending one million pings to ppp-Blinky. This took over two hours.
The ping tool used on the Windows 8 PC was psping.exe from PsTools by Mark Russinovich - http://bit.ly/PingFast
The average reply time for a short ping (1 byte of payload data) was 11 milliseconds at 115200 baud on the $10 Nucleo-L053R8 board - barely enough time for 130 bytes to be sent over the port!

/media/uploads/nixnax/ppp-blinky-ping-results.jpg

Monitoring PPP-Blinky Packets

The image below is from a Microsoft Network Monitor 3.4 capture session.

Responses from PPP-Blinky are shown in blue.

Frame 2 - Internet Explorer at IP 172.10.10.1 (the Dial-Up Adapter IP) requests a TCP connection by sending an S (SYN) flag.
Frame 3 - PPP-Blinky at IP 172.10.10.2 responds with an ACK in frame 3. One direction of the link is now established.
Frame 4 - The PC acknowledges the SYN sent by PPP-Blinky in frame 3. The TCP link is now fully established.
Frame 5 - The browser "pushes" (P flag is set) an HTTP GET request to PPP-Blinky.
Frame 6 - PPP-Blinky responds with a standard HTTP response "pushes" (P flag set) back a small web page. It also sets the A (ACK) flag to acknowledge the message sent in frame 6.
Frame 7 - The PC acknowledges reception of the HTTP payload.
Frame 8 - The PC starts to shut down the TCP connection by sending a FIN flag.
Frame 9 - PPP-Blinky acknowledges the FIN request - the connection is now closed in one direction. It also sets a FIN flag in the response to request closure of the opposite direction of the connection.
Frame 10 - The PC acknowledges the FIN request. The closing of the TCP connection is now confirmed in both directions.

/media/uploads/nixnax/ms-network-monitor-http-get-1.gif

Debug Output

PPP-Blinky can output handy debug information to an optional second serial port.
The image below shows the debug output (Ident, Source, Destination, TCP Flags) for a complete HTTP conversation.
The PC messages are displayed in black. PPP-Blinky messages are blue.
Notice how PPP-blinky automatically inserts a blank line after each full HTTP conversation.

/media/uploads/nixnax/tcp-data-3.gif

Creating a Dial-Up Connection in Linux

The screen below shows the required pppd command to connect to PPP-Blinky from a Linux machine. This was much simpler than Windows! The USB serial port of the mbed LPC1768 board registered as /dev/ttyACM0 on my Linux box. Do a websearch on pppd if you want to learn more about pppd, the Linux PPP handler. Near the bottom of the screen below, two webpages are fetched (/ and /y) by using the curl command on the command line. Gnome Webkit and Firefox work fine, too. Also try echo GET / HTTP/1.1 | nc 172.10.10.2 which uses netcat, the "Swiss army knife" of networking tools. PPP-Blinky was also tested with ApacheBench, the Apache server benchmark software. After 100000 fetches, the mean page fetch rate was reported as 6 page fetches per second for a small page.

/media/uploads/nixnax/pppd-screen.png

Caveats

PPP Blinky is an extremely sparse implementation (1.5k lines) of HTTP,WebSocket,TCP, UDP, ICMP, IPCP and LCP over PPP, requiring around 8kB of RAM. The minimum functionality required to establish connectivity is implemented. These are often acceptable tradeoffs for embedded projects as well as a handy tool to learn the practical details of everyday networking implementations.

Revision:
160:bd701ad564cb
Parent:
159:4d1bf96a59cd
Child:
161:d59f778bc8ab
--- a/PPP-Blinky/ppp-blinky.cpp	Sat Sep 02 07:48:53 2017 +0000
+++ b/PPP-Blinky/ppp-blinky.cpp	Sat Sep 02 17:35:29 2017 +0000
@@ -166,7 +166,7 @@
     union {
         tcpHeaderType * tcp; // pointer to tcp header struct
         char * tcpStart; // char pointer to tcp header struct (need a char pointer for byte offset calculations)
-    };         
+    };
     int online; // we hunt for a PPP connection if this is zero
     int hostIP; // ip address of host
     int fcs; // PPP "frame check sequence" - a 16-bit HDLC-like checksum used in all PPP frames
@@ -703,14 +703,13 @@
     n=n+sprintf(pbuf+n, "%05d ",IPv4Id); // IPv4Id is a good way to correlate our dumps with net monitor or wireshark traces
 #define DUMP_FULL_IP_ADDRESS_YES
 #ifdef DUMP_FULL_IP_ADDRESS_YES
-    char * srcAdr =     (char *)&ppp.ip->srcAdrR; // 4 bytes
-    char * dstAdr =     (char *)&ppp.ip->dstAdrR; // 4 bytes = total of 20 bytes
-    //n=n+sprintf(pbuf+n, " %x %x ", ppp.pkt.ip.x, ppp.pkt.ip.y);
+    char * srcAdr = (char *)&ppp.ip->srcAdrR; 
+    char * dstAdr = (char *)&ppp.ip->dstAdrR; 
     n=n+sprintf(pbuf+n, " %d.%d.%d.%d %d.%d.%d.%d ",srcAdr[0],srcAdr[1],srcAdr[2],srcAdr[3], dstAdr[0],dstAdr[1],dstAdr[2],dstAdr[3]); // full ip addresses
 #endif
     putsWhileCheckingInput( pbuf );
 #ifndef TCP_HEADER_DUMP_YES
-    putsWhileCheckingInput('\x1b[30m\n'); // there is no TCP header dump, so terminate the line with \n and VT100 code for black
+    putsWhileCheckingInput('\x1b[30m\n'); // if there's no TCP header dump we terminate the line with \n and VT100 code for black
 #endif
 #endif
 }
@@ -744,9 +743,11 @@
 #define EVERY_PACKET_ON_A_NEW_LINE_YES
 #ifdef EVERY_PACKET_ON_A_NEW_LINE_YES
     putsWhileCheckingInput("\x1b[30m\n"); // write a black color and newline after every packet
+#else
+    putsWhileCheckingInput("\x1b[30m"); // write a black color after every packet
 #endif
     if( outGoing && ppp.tcp->flag.fin ) { // ACK/FIN - if this is an outgoing FIN it's the end of a tcp conversation
-        putcWhileCheckingInput('\n'); // insert an extra new line to mark the end of an HTTP conversation
+        putcWhileCheckingInput('\n'); // insert an extra new line to mark the end (except for final ack) of an HTTP conversation
     }
 #endif
 }
@@ -778,8 +779,8 @@
     out[j]=0;
 }
 
-/// handle a request for an http websocket
-/// we end up here if we enter the following javascript in a web browser console: x = new WebSocket("ws://172.10.10.2");
+/// Handle a request for an http websocket.
+/// We end up here if we enter the following javascript in a web browser console: x = new WebSocket("ws://172.10.10.2");
 int webSocketHandler(char * dataStart)
 {
     int n=0; // byte counter
@@ -821,7 +822,7 @@
 {
     int n=0; // number of bytes we have printed so far
     n = webSocketHandler( dataStart ); // test for and handle WebSocket upgrade requests
-    if (n>0) return n; // if it's a WebSocket we already have the response, so return
+    if (n>0) return n; // if n>0 we already have a response, so return
 
     int nHeader; // byte size of HTTP header
     int contentLengthStart; // index where HTML starts
@@ -880,33 +881,27 @@
     return n; // total byte size of our response
 }
 
-/// handle TCP data that is not an HTTP get
-/// this is the response if we have TCP data but it's not an HTTP GET
-/// this is handy when you for example want to use netcat (nc.exe) to talk to PPP-Blinky
-/// this could also be a websocket receive event - especially if the first byte is 0x81 (websocket data push)
+/// Handle TCP data that is not an HTTP GET.
+/// This is handy when for example you want to use netcat (nc.exe) to talk to PPP-Blinky.
+/// This could also be a websocket receive event - especially if the first byte is 0x81 (websocket data push)
 int tcpResponse(char * dataStart, int len, int * outFlags)
 {
     int n=0; // number of bytes we have printed so far
     if (dataStart[0] == 0x81) { // check if this is a websocket push message
-        // this is most likely a websocket push message. you get this when you enter this in your browser console: x.send("my message");
-        if (0) putsWhileCheckingInput( "Got data from websocket send()\n" );
-
-        // for now we simply echo the websocket data back to the client - the client should therefore see an onmessage event
-        // to display the echoed data in your browser, enter the following into the browser console: x.onmessage = function(msg){ console.log( msg.data ); }
-        if (1) {
-            char mask [4];
-            memcpy ( mask, dataStart+2, 4); // websocket messages are "masked", so first we obtain the 4-byte mask
-            int websocketMessageSize = len - 6;  // 1 byte prefix (0x81), 1 byte, 4 bytes mask = 6 bytes
-            if((dataStart[1]&0x80)==0x80) // test if the mask bit is set, which means all data is xor'ed with the mask
-                for (int i=0; i<websocketMessageSize; i++) dataStart[i+6]^= mask[i%4]; // unmask each byte with one of the mask bytes
-            dataStart[1] = len-2; // add four extra bytes to the message length because we don't use mask bytes for the send
-            memcpy(dataStart+2, "Got:",4); // insert our own text into the four mask bytes
-            n = len; // our response size remains exactly the same length as what we received
-        }
+        char mask [4];
+        memcpy ( mask, dataStart+2, 4); // websocket messages are "masked", so first we obtain the 4-byte mask
+        int websocketMessageSize = len - 6;  // 1 byte prefix (0x81), 1 byte, 4 bytes mask = 6 bytes
+        if((dataStart[1]&0x80)==0x80) // test if the mask bit is set, which means all data is xor'ed with the mask
+            for (int i=0; i<websocketMessageSize; i++) dataStart[i+6]^= mask[i%4]; // unmask each byte with one of the mask bytes
+        dataStart[1] = len-2; // add four extra bytes to the message length because we don't use mask bytes for the send
+        memcpy(dataStart+2, "Got:",4); // insert our own text into the four mask bytes
+        n = len; // our response size remains exactly the same length as what we received
     } else if ( (dataStart[0]==0x88) && (dataStart[1]==0x80) && (len == 6) ) { // test for a websocket close request
         n=2; // our close command is only two bytes long because we don't use the four mask bytes
         dataStart[1]=0; // we don't have mask bytes on
-    } else if (v1) putsWhileCheckingInput("TCP data received\n");
+    } else {
+        if (v1) putsWhileCheckingInput("TCP data received\n"); // all other tcp push packets
+    }        
     return n; // total byte size of our response
 }
 
@@ -915,17 +910,14 @@
 void tcpHandler()
 {
     // IP header
-    char * ipPkt = ppp.pkt.buf+4; // ip packet start
-    char * protocol =   ipPkt+9;  // 1 byte
-    char protocolIP = protocol[0];
     int packetLengthIp = __REV16(ppp.ip->lengthR ); // size of ip packet
     int headerSizeIp = 4 * ppp.ip->headerLength;  // size of ip header
 
     // TCP header
-    
+
     ppp.tcpStart = ppp.ipStart + headerSizeIp; // calculate where the TCP header starts
     int tcpSize = packetLengthIp - headerSizeIp; // tcp size = size of ip payload
-    char * tcp           = ppp.ipStart+headerSizeIp; // start of tcp packet
+    char * tcp = ppp.ipStart+headerSizeIp; // calculate start of tcp packet
 
     int headerSizeTcp = 4 * (ppp.tcp->offset); // tcp "offset" for start of data is also the header size
 
@@ -950,7 +942,7 @@
     int dataLen = 0; // most of our responses will have zero TCP data, only a header
     int flagsOut = TCP_FLAG_ACK; // the default case is an ACK packet
     //int flagsTCP = ((flagbitstcp[0]&1)<<8)|flagbitstcp[1]; // the tcp flags we received
-    
+
     ppp.tcp->windowR = __REV16( 700 ); // set tcp window size to 700 bytes
 
     // A sparse TCP flag interpreter that implements stateless TCP connections
@@ -988,7 +980,7 @@
 
     ppp.tcp->ackTcpR = __REV( ack_out ); // byte reversed - tcp/ip messages are big-endian (high byte first)
     ppp.tcp->seqTcpR = __REV( seq_out ); // byte reversed - tcp/ip messages are big-endian (high byte first)
-    
+
     ppp.tcp->flag.All = flagsOut; // update the TCP flags
 
     // recalculate all the header sizes
@@ -1006,13 +998,13 @@
     pseudoHeader.srcAdrR = ppp.ip->srcAdrR; // copy in ip source address
     pseudoHeader.dstAdrR = ppp.ip->dstAdrR; // copy in ip dest address
     pseudoHeader.zero = 0; // padding
-    pseudoHeader.protocol = protocolIP; // protocol number
+    pseudoHeader.protocol = ppp.ip->protocol; // protocol number
     pseudoHeader.lengthR = __REV16( tcpSize ); // size of tcp packet
     dataCheckSum(pseudoHeader.start, 12, 1); // start with the TCP checksum of the pseudoheader
     ppp.tcp->checksumR = 0; // before TCP checksum calculations the checksum bytes must be set cleared
     unsigned int pseudoHeaderSum=dataCheckSum((unsigned char *)ppp.tcpStart,tcpSize, 0); // continue the TCP checksum on the whole TCP packet
     ppp.tcp->checksumR = __REV16( pseudoHeaderSum); // tcp checksum done, store it in the TCP header
-   
+
     dumpHeaderIP(1); // dump outgoing IP header
     dumpHeaderTCP(1); // dump outgoing TCP header
     for (int i=0; i<45*1000/10; i++) { // 45 ms delay before sending frame - a typical internet delay time