loewen108

Upload: hossam-fadeel

Post on 06-Apr-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/2/2019 Loewen108

    1/1124 Issue 108 July 1999 CIRCUIT CELLAR www.circuitcellar.com

    Internet

    Appliance Interface

    FEATUREARTICLE

    Myron Loew en

    fInternet appliancesstill arent the mostreasonable thingsout there. (Why payhundreds more for a$20 toaster?) But,Myron uses a PIC anda 2400-bps modemto make an Internetinterface that leads theway to less-expensiveInternet appliances.

    or years, wevebeen hearing about

    the promises of every-thin g from coffee m akers

    to lawn sprinklers being connected to

    the Internet for remote control andm onitoring. Yet, non e of these devicesever became a commercial product.

    Two major roadblocks have pre-vented this dream from coming truethe cost of connecting to th e Int ernetand the cost of an Internet terminal.N o one want s to pay an extra $300 fora $40 appliance, plus $25 a month forthe Internet service, just to have theability to check on their home appli-ances from work.

    But, things are changing in the mar-ket t hat could clear this roadblock forever. Cable modems are bringingcontinuous Internet connections intohomes without the hassles of extratelephone lines and hourly billing.

    Another recent change is free webaccess by local telephone num bers insome cities, if you can t olerate a littleadvertising. A dumb terminal like acoffee maker could care less how manybanner ads it has t o ignore. And thecost of the Internet in terface is drop-ping to under $50 with the introduc-

    tion of systems-on-a-chip com pletewith TCP/IP stacks.

    In this article, I show how theInternet in terface can be m ade evencheaper and simplified to run on a $2PIC processor and a retired 2400-bpsm odem. Th e PIC dials and establishesa point-to-point protocol (PPP) connec-tion w ith an ISP and exchanges datawith remot e servers. I dont h ave acable modem or access to free webbrowsing yet, but there are manyother applications that already need asmall or ch eap Int ernet int erface.

    Even t hough t his project was con-ceived solely for the Circuit CellarDesign98 contest, it has since founduse in everything from industrialcontrols to surveillance cameras. Itsmost suited for remote data collection,

    where the samples are stored until analarm trigger point and then dumpedto a cent ral database through a localISP. This has huge cost savings overleased lines.

    My design, shown in Photo 1, usesthe PIC12C672 to emphasize how smallthe device can beonly eight pins andunder $2. Even with such a simpleprocessor, I managed 2400-bps serialcommunications with the modem,three analog inputs, one digital output,

    and some of th e Internet protocols.The serial communications had to

    go through a software-emulated serialport (bit banging) because this devicehas no USART. The result was a demoInternet node with a remote-controlledred LED indicator and remote monitor-ing of three potentiometer settingswith 8-bit resolution.

    SIMPLE INTERNETPacking this kind of functionality

    into su ch t iny resources required a lotof tradeoffs. I studied a ton of InternetRequest for Comment (RFC) docu-ments, the public source code to Wat-TCP and Linux TCP/ IP stacks, andTCP/IP Illustrated Volumes I, II, andIII. Then, I whittled it down to the bareessentials, making many assumptionsand forfeiting universal compatibility.

    Heres a sum m ary of how I imple-mented the Internet protocols and adescription of the software. If you wantto learn m ore, read a book like t heone in t he references and download

  • 8/2/2019 Loewen108

    2/11www.circuitcellar.com CIRCUIT CELLAR Issue 108 July 1999 25

    some of the Internet documentationlisted in the Digging Deeper sidebar.

    If youve read th is far, you probablyhave quite an interest in TCP/IP pro-tocols, but bear with m e as I cover thebasics. If it doesnt make sense to you,remember that this protocol stack isfar from conventional. Try instead tofocus on the flow of data instead of whatsoftware layers and state m achines aremissing.

    I justify this reckless abandon of standards as necessary to shrink thecode to the point where connectionscan barely be made wit h a m ajority of ISP servers. This w ill not endanger thestandards of the Internet because theseare end-user devices that perform norouting and are tweaked until theysatisfy the end user. There are already

    inconsistencies between products fromm ajor brand nam es, which prevent t heappliance from being able to log intosome ISP servers.

    Lets first look at how the Internetworks and how data can cross such amaze of distant computers with vary-ing physical connections and operatingsystems. Each computer gets a uniqueIP address, mu ch like your m ailingaddress. The data t o be sent is brokeninto chu nks t hat are stuffed in specially

    marked small envelopes that indicatethe type of data (e.g., web page, e-mail).

    Each of these goes into a m edium-sized envelope, specially marked to getit to the right program on the remotecomputer. The type of data determinesif the m edium-sized envelope is asimpler UDP type or m ore robust TC Ptype. The TC P packet generates extrapackets to open and close transmis-sions and resends packets that get lost.

    The medium envelopes go into

    larger envelopes with source and des-tination Internet addresses on them.This is called the IP packet. Its likeinternat ional m ail; th e address gets itto any destination on the Internet.

    But, the Internet works more likepassing notes in class. The large enve-lope goes in a bigger one with yourfriends name on it. Your friend opensthe big envelope, sees where the largeenvelope want s to go, and puts it intoa new big one.

    Your friend then passes it to anotherfriend wh o is closer to the final desti-

    nation, and t he process repeats. Themail doesnt always take the samepath and sometimes it gets lost alongthe way. With luck, the large envelopeeventually ends up at its destination.

    When it arrives, it is opened andthe medium envelope is removed tosee what program gets th e data. Thatprogram then opens the little envelopeto gets its data. Most OSs do this wit ha TCP/ IP stack like WinSock. To saveall the envelope handling, m y algo-rithm puts on x-ray glasses and looksthrough all th e layers for th e data inthe middle. The format of the enve-lopes or packets is shown in Figure 1.

    There are protocols for th e datafollowing th e IP header (e.g., ICMP forpinging, TCP for web browsing, andUDP for voice over Internet). You need

    to im plement ping to test the Internetconnection and send keep-alive packetsto prevent t he server from disconnect-ing. You also need a way to send datato t he appliance and receive data back.

    Youre probably familiar with ftpfor transferring files. It runs over TCP,which handles opening a high-levelconnection across the Internet witherror detection and retransmission.

    TCP h as large RAM and ROMrequirem ents t o keep track of open

    connections and packets that have notyet been acknowledged by the rem otecomputer. It turns out that theresanother less popular file transfer pro-tocol, called tftp, which runs over UDP.UDP is mu ch simpler to implementthan TCP because each packet is sentin response to th e last one receivedand th ere is no retransmit buffer ortable of connections t o keep track of.

    I couldnt choose tftp without clientsoftw are for people to access t heir n ewappliances. With a quick search, I foundseveral freeware, shareware, and demotftp servers and client s for various OSs.The http links to these packages areavailable via the Circuit Cellar web site.

    Another protocol I considered wasSNMP. It is much more popular, hasbuilt in remote alarm monitoring andreporting, and lots of shareware cli-ents, but is a little more complicated.

    If you need it to be even simpler, just return data appended to pings.But then , you need to write a customping routine.

    tftp has another advantage over pingand SNM P. It provides simple datalogging of daily uploads on a central

    tftp server. tftp clients just h ave toupload files with unique filenamesand th ey are stored on t he server.

    NEGOTIATING PPPA modem connection to the Internet

    is used because its the most commonm ethod for remote data collectors. If we go back to the envelope analogy,th e Internet appliance and th e ISP

    Figure 1 The tftp packet shows how the A/D readings are wrapped in layers of packets to get a PPP packet.

    A/D readings

    tftp header Filename

    data

    data

    data

    data

    UDP header

    IP header

    7E PPP header CRC 7E

    Photo 1 The first prototype of the Internet Appliance uses three potentiometers for remote inputs and an LED to test remote control. The 2400-bps Cermetek modem provides a fast enough

    Internet connection to ex- change the control packets.

  • 8/2/2019 Loewen108

    3/11

  • 8/2/2019 Loewen108

    4/11www.circuitcellar.com CIRCUIT CELLAR Issue 108 July 1999 27

    m odem server are the close friendsexchanging the big envelopes. Theenvelopes used in dialup connectionscome in two formsSLIP and PPP.More acronyms are listed in Table 1.

    I only had room for one protocol,so I chose PPP because som e ISPsprevent SLIP from establishing a con-nection. The PPP connection can alsogo straight to a local servers serialport to save the cost of a modem.

    PPP is a protocol to encapsulate IPpackets on a serial link. On an asyn-chronous link (like the modem serialconnection), it requires the data formatto be 8 data bits with no parity.

    The sample packet in Figure 1 showsthat character 0x7e starts and stops apacket. All other instan ces of 0x7e mu stbe changed to the t wo-byte sequence

    0x7d 0x5e to prevent false starts. Thecharacter 0x7d becomes an escapecharacter that m eans complement bit6 in t he following byte.

    Any original instance of 0x7d, 0x7e,or bytes inclusively between 0x00 and0x1f, must be changed to 0x7d followedby the original XORed with 0x20.This bit stuffing eliminates falsepacket breaks, false characters, andRS-232 control characters under 0x20.

    The PPP connection procedure can

    be broken into several phases. First, if th e link is dead, carrier detect is one of the st imu li that m oves us to the nextphase. The link establishment phaseuses LCP to detect and n egotiate link options with the remote comput er.

    Next, th e authentication phaseverifies your password using PAP.Although it is n ot one of the phases,this is where ISPs generally configuredata compression with CCP packets.

    The final phase is the network-

    layer protocol (e.g., IP). Each protocolis configured with its protocol; IPCPin the case of IP. Of course, theres alsothe terminate phase to close the link.

    The LCP, PAP, CCP, and IPCP pack-ets look similar and negotiate optionsin the same way. Only the protocolfield and the m eanings of the optionsare different. Figure 2 illustrates whatan LCP packet looks like and howoptions are negotiated across the se-rial link.

    Basically, the packet can request,deny, and accept options. Both sides

    m ust issue an accept before the LCPnegotiation is complete. Figure 3depicts t he packet exchanges.

    Negotiation starts with one siderequesting a list of options in a REQrequest packet. Each option consistsof a length byte, option num ber, andoption parameters. The other sideresponds wit h an ACK if it accepts allthe options. If it doesnt like anoptions paramet ers, it responds with

    a N AK and a list of the options t hat itrejected with parameters that wouldbe acceptable.

    If required options are missing, itadds those to th e rejected list in th eNAK reply. If some options are notrecognized or are considered nonnego-tiable, the oth er side should respondwith a REJ reply and list the bad options.

    The first side resubmits updatedoption lists un til it gets an ACK reply.

    Digging DeeperAnyone trying to build an Internet appliance will find that this article

    barely scratches th e surface of the Internet protocols. Fortunat ely, theInternet is fairly well docum ented an d, best of all, the st andards are freein the form of request-for-comm ents documen ts (RFCs).

    RFCs are th e working not es of the Internet research and developmentcommunity. RFCs can be written by anyone to introduce a new protocol,

    m odifications, new m ethods, or explanations. They are often updated bylater RFCs with higher numbers, so make sure you use the latest revisionand refer back to updated RFCs.

    You can find RFCs on several Internet sites including w ww.cis.ohio-state.edu/hypertext/information/rfc.html or by emailing:

    To : r fc-in [email protected]: gett ing rfcsMessage body: help: ways_to_get_rfcs

    Here are some h elpful RFCs to get you st arted:

    RFC 768 U D P specificat ionRFC 791 IP specificat ionRFC 792 ICMP specifica t ion , updated by RFC 950RFC 867 Ge t t ing t ime and dat e from the se rverRFC 1055 Serial link IP (SLIP)RFC 1 07 1 In t er ne t c he ck su m sRFC 1144 Compressing TCP/IP headersRFC 1157 Simple network management protocol (SNMP)RFC 1332 PPP Internet protocol control protocol (IPCP)RFC 1334 PPP authent ica t ion protocols (PAP)RFC 13 50 t ft p ve rs io n 2RFC 1 54 7 P PP r eq ui re m en t s

    RFC 1570 LCP extens ions, updates RFC 1548RFC 1624 Internet checksum via incremental update; updates RFC 1141RFC 1661 PPP, the protocol itself; obsoletes RFCs 1548, 1331, 1172,

    1171, 1134RFC 1662 PPP framing, the CRC checksum ; obsoletes RFC 1549RFC 1663 PPP re liable t ransmiss ionRFC 1700 Assigned num bers, parameters, and keywordsRFC 1962 Compression control protocol (CCP)RFC 1989 PPP link quali ty monitoring; obsoletes RFC 1333RFC 1990 PPP mul t i l ink protocol (LCP s tuff)RFC 1994 PPP challenge handshake authentication protocol (CHAP)RFC 2153 PPP vendor ext ensionsRFC 2484 LCP in ternat ional extens ion

  • 8/2/2019 Loewen108

    5/1128 Issue 108 July 1999 CIRCUIT CELLAR www.circuitcellar.com

    The ot her side can start negotiat-ing its options at any time. Theresulting link m ay have differ-ent options for each direction.

    I didnt implement the ter-minate, code reject, protocolreject, echo, and discard pack-ets. The terminate packets canbe replaced by disconnectingthe modem. The code and pro-tocol reject packets are possiblyrequired to connect to updatedservers in th e future. The echoand discard packets are for test-ing the serial path and can beignored for most ISP connections.

    The only LCP option that Iaccepted and required was num-ber three for authenticationusing PAP. Authentication with

    PAP is as simple as sending aPAP request wit h a user ID andpassword and then waiting foran acknowledge. I had to force thisoption to avoid the alternative (CHAP),which appeared more complicated andrequired more RAM and ROM.

    The MRU option was omittedbecause, although my receive bufferwas only 49 bytes, all the packets Iused were small. On top of that, I didnthave enough RAM or ROM to recon-

    struct fragmented packets.My ISP want ed to negotiate the

    character-map option to reduce thenum ber of characters under 0x20 th athad to be bit-stuffed and sent as t wobytes. They also wanted to compressthe protocol, address, and control fields.Although t hese would h ave been goodat the low 2400-bps bandwidth, it wasnot worth the extra software.

    The magic-number option may berequired by a few ISP servers, but I

    ignored it because it needed four extrabytes of RAM and a lot of ROM. Th ereare a lot m ore options, and this isdefinitely one area where youll needto play with t he code to m ake i t morecompatible with your ISP servers.

    Once the LCP options are agreedon, th e PAP authorizes your user IDand password as I described. Then, theCCP compression options are negoti-ated. These options compress theentire serial stream an d could easilyuse up the entire memory space byth emselves. Because my packets are

    tin y and t raffic is low, I chose t o disablethem and go under the puddle-jumperoption n um ber three.

    The final group of options configurethe IPP settings with IPCP. I disabledthe TCP/IP header-compression optionto keep t he softw are simpler and be-cause I dont intend to transmit anyTCP packets. I do, however, use this

    protocol to get the IP address of theInternet appliance. After this, only IPpackets are sent and t here is no harm inignoring the servers rare LCP packets.

    IP PACKETSThe IP packets st art wit h a 20-byte

    header followed by data. The data iseither an ICMP, UD P, or TCP headerfollowed by its data. The IP headerdirects the data to the destination andkeeps m ultiple data packets from

    arriving out of order.The first four bits are th e IP version.The n ext four bits are the header length,always equal to 20 in th is application.The 8-bit type of service field sets therouting priority to minimize delay andcost as well as maximize throughputand reliability. Then comes the total16-bit length of the h eader plus data,about 40 for m ost of the Internet-appliance packets.

    The 16-bit identification identifieseach packet and is used with t he fol-lowing flags and fragment offset to

    reassemble fragm ented packets.Following all that is the time-to-live byte, which sets the maxi-m um num ber of hops this packetcan be routed toward the desti-nation before giving up. The n extbyte indicates wh at t ype of pro-tocol is riding in th e IP data.

    Next, comes a 16-bit check-sum of the 20-byte IP header. Becarefulthis is a 16-bit onescomplement checksum , not yourordinary math (described later).After t hat is the 32-bit source IPaddress and finally the 32-bitdestination. Youre probably usedto seeing these addresses in aform like 10.97.123.67.

    The easiest to understandprotocol that rides th e IP header

    is ICMP, wh ich is used to pingInternet nodes. Named after thesonar m ethod for locating ob-

    jects, it sends out a packet and w aitsfor a reply.

    You n eed ICMP in this applicationto keep the Internet connection aliveand respond to ot hers that are lookingfor th e health of your Internet node.The test is usually repeated severaltimes indicating pass or fail and re-sponse time.

    The ping packet is 20 bytes of IPheader, then 8 bytes of ICMP headerand some data to echo. The first twobytes of the ICMP header are type=8and code=0 for the ping request. Typeis 0 for the ping reply.

    After that comes a 16-bit onescomplement checksum of the ICMPheader and echo data. Then, an ident i-fier for mu ltiprocessing systems an d asequence number increment eachiteration.

    The ot her protocol essential here isUDP, wh ich is used to send data overtftp. Because of its simplicity, thisprotocol is used for everything fromH.323 multimedia applications toSNMP network management.

    Each output operation produces onlyone packet. Like IP headers, it cantensure that the data gets to the desti-nation, but it does check the data forerrors.

    The protocol simply takes the IPheader, adds four 16-bit param eters anda string of data. The four paramet ers

    Table 1 These are the acronyms used in this article. Check the Digging Deeper sidebar for where to find full descriptions and technical details.

    ACK acknowledgementCRC cyclic redundancy checkCHAP challenge-handshake authentication protocolftp file transfer protocolICMP Internet control message protocolIP Internet protocolIPCP Internet protocol control protocolISP Internet service providerLCP link control protocolMRU maximum receive unitNAK negative acknowledgementPAP password authentication protocolPPP point-to-point protocolREQ requestREJ rejectRFC request for commentSLIP serial line Internet protocolSNMP simple network management protocolTCP transmission control protocoltftp trivial file transfer protocolUDP user datagram protocolUSART universal synchronous asynchronous receiver

    transmitter

  • 8/2/2019 Loewen108

    6/11

  • 8/2/2019 Loewen108

    7/1130 Issue 108 July 1999 CIRCUIT CELLAR www.circuitcellar.com

    are a source-port number, destination-port number, length, and ones comple-ment checksum.

    The port numbers identify whichprocess gets the data in a multiprocess-ing system. The length is redundantwith data in the IP headereight forthe UDP header plus the number of data bytes. You may want to bury yourown CRC checksum in important databecause UDP and TCP only use aninferior checksum.

    TCP is the protocol for transferringweb pages and e-mail across the Inter-net. TCP negotiates a connection,transfers the data, does error checking,retransmits bad or missing packets,and closes the connection.

    A m ore complex protocol has tohandle a lot of special cases and keep

    track of lots of data, which takes moreRAM and ROM t han is available inth e PIC. But, it would be an int erest-ing project to see just how small TC Pcould be implemented in anotherprocessor.

    EXCHANGING DATAI already indicated how data

    could be transferred using th e echodata on the ping command and whyI chose tftp instead. This section isa look at how tftp works and howthe Internet appliance uses it.

    tftp is int ended for bootstrap-ping diskless workstat ions, so it issmall and easily fits on a ROM .Each data exchange begins withthe client asking the server to reador write a file. There are five pack-ets used t o transfer the data, ReadRequest (RRQ), Writ e Requ est (WRQ),Data, Acknowledge (ACK), and error.

    The packet is laid out as 20 bytes of IP header, 8 bytes of UDP header, andthe opcode for type of packet. Opcode1 is for RRQ and is followed by a null-

    terminated filename, and a null-termi-nated ASCII or binary transfer mode.Opcode 2 is for WRQ and it h as thesame format as an RRQ packet.

    Opcode 3 indicates a data packet andis followed by th e block n um ber and

    up to 512 data bytes. Opcode 4 isfor ACK and is followed by theblock number being acknowledged.Opcode 5 indicates an error and isfollowed by the error num ber anda null-terminated error message.

    All data packets must have512 bytes of data except th e lastpacket in t he file. A packet lengthunder 512 bytes indicates th e endof the file. Lost packets are detectedwhen the sender has a time-outand the last packet is resent.

    Just like ftp, there is no security.Instead, the t ftp server usu allylimits transfers to files with world-read and w orld-write permissions.

    For this Internet appliance, you

    want to read three analog inputs andset one digital out put. T heres evena way to do both in one operation.

    Reading a filename t hat endswith a 0 clears the output. If thefilename ends with a 1, the outputis set; otherwise the output isunch anged. The ret urned file con-tains the output sett ing and thethree A/ D readings in ASCII format .

    Many variations of this processcan be implemented. If the outputwas a PWM analog output, the digitin th e filename can be extended to

    a three-digit value. The digits can bemoved anywhere in the filename. Thenumber of outputs and inputs is onlylimited by the transmit buffer size andmaximum filename length.

    The appliance can dump its data tothe server by writing a file with a

    unique filename based on date. Theserver would have a directory of fileslogging the daily data of the appliance.The appliance doesnt n eed a real-tim eclock because the date and time can beretrieved from m ost Internet serversfrom UDP port 13 [1].

    THE HARDWAREI chose to implement this project

    in t he sm allest processor I could find(the 8-pin PIC12C family) to empha-

    size how compact t he code is. In t hePIC12C fam ily, I chose th e device withthe m ost RAM and ROM (at the time),the PIC12C672. Although it only has128 bytes of RAM, th at shou ld beenough for the variables, a small trans-mit buffer, and a small receive buffer.

    At first I was scared th at t he codewouldnt fit and it would force m e toa larger processor. Th e 2 KB of ROMturned out to be plenty and left thepossibility of a m ore robust PPP stack,

    EEPROM routines, SNMP routines,and other options. If I could start over,Id choose a processor with a USARTto simplify and speed up the serial I/O.

    The other main component is themodem. I had plenty of old 2400-bpsmodems to choose from, but I wentwith the Cermetek for its small size(and because there were several layingaround the lab from old projects). If youre not as lu cky, you should stillbe able to locate a 2400-bps externalmodem. You could add RS-232 driversto the circuit or, even better, bury the

    Internet provider Internet appliance

    LCP-REQ1 2 3 7 8 19 LCP-REJ1 1 2 7 8 19

    LCP-REQ2 3 LCP-ACK2 3

    LCP-ACK3

    LCP-REQ3

    Connection established

    PAP-REQ1 userid password

    PAP-ACK1

    User authenticated

    CCP-REQ1 17CCP-REJ1

    Compression negotiatedIPCP-REQ1 2 3

    IPCP-REJ1 2

    IPCP-REQ2 3IPCP-ACK2 3

    IPCP-NAK 3 real IP address

    IPCP-REQ3 3 fake IP address

    IPCP-REQ4 3real IP address

    IPCP-ACK

    IP address found, ready for ping

    Figure 3 This is a typical exchange of option requests in the negotiation of a PPP connection. Each request (REQ) is numbered and the replying acknowledgment (ACK) or reject (REJ) must reference the same number. The list of numbers at

    the end of a packet identify each option as highlighted in Figure 2.

    Figure 2 The LCP packet shows how the configuration options are sent in a PPP packet. This example highlights the MRU option.

    Type Length

    LengthId

    Data

    Option Option Option More options

    LCP packet

    Code

    PPP Protocol Checksum

    7E FE

    01 04 05 F4

    01 01 00 1B 07 02

    FF 03 C0 21 5C 6D

    08 02

  • 8/2/2019 Loewen108

    8/11

  • 8/2/2019 Loewen108

    9/11

  • 8/2/2019 Loewen108

    10/11www.circuitcellar.com CIRCUIT CELLAR Issue 108 July 1999 33

    whole circuit inside the m odem case.The schem atic for th is project is shownin Figure 4.

    Open the external modem case,remove the RS-232 driver chip, attachthe circuit, connect the Tx and Rx pinsto t he correct driver chip pins, andconnect power and ground. Be sure tostay away from the high voltages on theincoming power and telephone lines.

    Also, use potentiometers that fitand mount nicely on the m odem case.You w ont n eed the resett able fusesand overvoltage limit componentsbecause the modem already has them.

    I used 10-k potentiometers fromTocos. Th ese are nice for breadboardingbecause they h ave through-hole leadsand a nice knob for days when you cantfind your pot tw eaker. You can u se any

    LED to indicate th e digital outpu t,including one already in t he case if youuse the modified external modem.

    The circuit is quite simple so Ibreadboarded it instead of waiting fora PCB. You could go even smaller andmake it all surface mount.

    Dont worry about finding the exactcomponents. Any 110-k potentiom-eter will do, as will any n ormal LED.You can even om it sidactor U3 andreplace the resettable fuses wit h 5-

    resistors. Note that this circuit is notFCC approved and th us should not beconnected directly to your local tele-phone service.

    THE SOFTWAREI wrote the software in C because

    the contest deadline was approaching.I intended to rewrite it in assemblerto squeeze in some more options. Afterworking with the AN555 serial I/Oapp note from Microchip, I decided

    that future implementations wouldhave to h ave a serial port.If you are going to experiment with

    this project, choose a flash-memorybased micro with a serial port and atleast 500 bytes of RAM. The codeshould com pile with m ost C compil-ers for any common microcontroller,so use one youre familiar with . Onceyou get it w orking, scale it down t o asmaller processor with OTP memory.

    I did all the PPP algorithm develop-ment on a laptop computer with Bor-lands Turbo C. It was great because I

    could use the internal m odem , sprinkleprintf s everywhere, and trace throughthe problem areas of code. This methodworked so well th at I logged onto t heInternet after only two weekends of coding and debugging.

    The software is set up to have theserial bit-banging routines runn ing inthe background and the IP state m a-chine running in the foreground. Thereare only a couple of subroutin es totransmit a serial string, calculate CRCchecksums, create a new packet, check for config options, and remove a configoption. You can check out the codedetails via the Circuit Cellar ftp site.

    The software in itializes the globalvariables and m odem and redials every30 s until it connects to t he ISP m odembank. When state is set to 0 for no

    connection, the state machine takesover and loops forever, checking forreceived characters, transmitting thenext queued character, generating replypackets, and initiating its own packets.

    The state m achine keeps the valueof the current state in none other thanthe state variable. Another importantvariable is the in counter, which incre-ments on every pass through the mainloop. This variable is for triggering theappliance-generated packets and is

    zeroed so th e packets will be retrans-m itted if the stack gets stuck in a stat e.

    The IP state machine is initializedto state 0 after the modem connectswith the ISP server. This state waitsfor an LCP packet from the ISP.

    Getting an LCP packet moves it tostate 1 (i.e., server detected). Also,getting an LCP request (REQ) packetmeans that the server is negotiating aPPP connection and it jumps to state 2.If th e only ISP connection is requesting

    option 3, reply with an ACK; other-wise reject (REJ) the other options.If you stay in state 0 too long, you

    send an LCP REJ to kickstart the ISPserver into sending an LCP REQ. Afteryouve been in state 2 long enough,make your own LCP REQ with nooptions. If you receive an LCP ACKpacket, it m eans the server acceptedyour connection options and you en-ter state 3.

    After entering state 3, send a PAPREQ packet with the user ID and pass-word. If the password is rejected, the

  • 8/2/2019 Loewen108

    11/11

    SOURCEPIC12C672Microchip Technology, Inc.

    (602) 786-7200Fax: (602) 899-9210www.microchip.com

    ModemCermetek (408) 752-5000Fax: (408) 752-5004www.cermetek.com

    PotentiometersTocos(847) 884-6664Fax: (847) 884-6665www.tocos.com

    SOFTWARESource code and information regard-ing embedded Internet solutionsand tftp resources is available viathe Circuit Cellar web site.

    Myron Loewen is a design engineer at Norscan Instrum ents, a leader in fiber-optic cable m anagem ent syst em s. He enjoys sim plifying com plex prob-lem s to find the optim al solution. Youm ay reach him at m [email protected] .

    REFERENCES[1] W.R. Stevens, TCP/IP Illustrated ,

    Vol. 1, Addison Wesley, Reading,MA, 1994.

    RESOURCESMicrochip PIC12C672 datasheet,

    www.microchip.com/download/ lit/picmicro/12c67x/30561a.pdf

    Cermatek 1786LC datasheet,www.cermetek.com/pdf/ ch1786%20rev%20o.pdf

    in and ended up with little more thanthe PPP negotiation, ping, and tftp. Iwas excited at how easily it workedwith one ISP server but was frustratedby differences between other servers.

    The books and RFCs have a lot of information, but some is hard to digestand some is hard to find. I hope thisarticle provides the extra informationthat inspires new ideas or bridges agap in your im plement ation of the IPand PPP protocols. I

    state machine locks up in state 4. Other-wise, the ISP server sends a PAP ACKfollowed by a CCP REQ. If the CCPrequests only option 3, its acceptedwith a CCP ACK. All other options getrejected with a CCP REJ. The server willretry CCP REQ with reduced optionsunt il it gets a CCP ACK reply.

    With CCP negotiated, the serverattempts to negotiate IPCP with anIPCP REQ. Again, you negotiate theoptions down to number 3 using IPCPREJ and IPCP ACK. After you acceptth e server s options, the st ate m ovesinto position 5. After waiting in state 5,the state machine generates its IPCPREQ t o th e server.

    The server replies to the IPCP REQwith an IPCP NAK because you didntknow your IP address. The stack gets

    th e right IP address from the N AKpacket, u pdates its global address vari-ables, and makes another IPCP REQwith a good IP address. When it getsthe IPCP ACK from the server, it jumpsto the final state.

    In state 6, it sends out a periodicping or tftp packet, depending on whichline is REMed out. A tftp server cancapture the packets to log the potenti-ometer positions. If the appliance getsan IP packet, it t reats it as a ping and

    bounces back a reply.

    MakePacket creates an out goingpacket in t he tran smit buffer. Everyloop of the state m achine checks if the transmitter is ready for anothercharacter. If the transm it bu ffer hascharacters, it transmits the next char-acter and resets the buffer on th e finalcharacter in th e packet, 0x7e.

    Every loop of the stat e m achine alsochecks the modem for received charac-ters. Bit-stuffed characters are imme-diately converted from their two-byteform to t he original character.

    Some ISP servers compress the PPPcontrol and protocol from 0x038021 to0x21, others from 0x038021 to 0x0322.The state machine decompresses thecontrol and protocol so th e IP headeralways starts at the same buffer offset.

    The CRC checksum is immediately

    calculated as the bytes come in so thatthere is no pause for a big calculationat t he end of a packet. If the packetsare longer than the receive buffer, theCRC is still calculated but the extrabytes are lost. Instead of calculatingthe C RC checksum over the final 0x7e,it st ops a character early and shouldbe 0xf0b8 instead of 0x0000.

    OptionTest is true if the configu-ration option is in th e string and noother options are present. Remove-

    Option removes t he specified configu-ration option from t he option list.

    The rest of the code is prettybasic, but youll want a fair under-standing of the protocols beforemaking modifications. A lot canbe im proved on, especially m ak-ing it robust enough to connect t oany PPP server. You m ay even beable to squeeze TCP into a t inymicro for the worlds smallestweb server.

    More important are the enduses for this kind of technology.I chose to use the technology forlow-cost remote data collection.

    Because it uses a normal mo-dem for dial out only, you shouldbe able to string a hun dred of themin parallel along a 5-mi. tw istedpair. It would also be a simple wayfor ut ility companies t o read resi-dential meters. Maybe itll evenfind use in everyday appliances.

    I started off thinking the wholeTCP/ IP stack could be squeezed

    Figure 4This schematic shows the details of the prototype in Photo 1. These processor ports were chosen to maximize the versatility of the remote accessible pins. Pins AN1, AN2, AN3,and GP5 can be configured as digital inputs or outputs, or pins

    AN1, AN2, or AN3 can be 8-bit analog inputs. R5 limits the current to the modem during in-circuit programming.