Acknowledgments We would like to gratefully acknowledge … the fine folks at Dallas Semiconductor for squeezing such a capable JVM on an 8-bit microcontroller. … all of the hard work proofreading and organizing the draft for the book by the folks at Newnes (Kelly, Carol, Harry).
Dedication Dan To Keisha and Emily Brian To Linda, whose love and support made this possible.
............................ Dedication Whats .............................................. on the CD-ROM? 1 Introduction ................................................................
1
Why should you read this book? ............................................... What this book will do for you ................................................... How this book is laid out ........................................................... How to get the most out of this book ......................................... What you should already know .................................................
A really simple network ............................................................. A small office and home network .............................................. Connecting a LAN to the Internet (or a LAN, MAN, WAN) ........
The 10/100 Base- T cable ......................................................... Ethernet address ....................................................................... Internet addresses .................................................................... Domain names .......................................................................... Network classes ........................................................................ Subnetworks ............................................................................. DHCP ........................................................................................ Protocols ................................................................................... Client/server ..............................................................................
11 13 14 14 14 16 17 18 20
3 Java Essentials for Embedded Networked Devices ..........................................................................
25
For Windows .............................................................................
26
Windows 95/98 ........................................................................................ Windows 2000, Windows NT, Windows XP .............................................
26 26
For Linux ................................................................................... For Windows .............................................................................
28 31
Windows 95/98 ........................................................................................ Windows 2000, Windows NT, Windows XP .............................................
32 32
For Linux ................................................................................... Classes, objects, methods, constructors ................................... OOP diagrams .......................................................................... Inheritance ................................................................................ Errors, exceptions, and exception handling .............................. Network Programming ..............................................................
34 37 39 41 51 59
Reading and writing to a socket (a simple client) .....................................
60
Reading and writing to a socket (a simple server) ................................... Reading and writing to a socket (a slightly less simple server) ................ Programming with URLs ..........................................................................
Implementing threads by extending the thread class ............................... Implementing threads by implementing the runnable interface ...............
75 82
Serial ports ................................................................................
85
4 Overview of Embedded Networked Devices ...........
93
5 Getting Started with TINI ...........................................
101
The TINI SIMM .......................................................................... The socket board ...................................................................... Get your TINI running ................................................................ For Windows ............................................................................. Windows 95/98 .......................................................................... Windows 2000, Windows NT, Windows XP .............................. Linux .......................................................................................... Running JavaKit ........................................................................ Your first TINI program .............................................................. Windows ....................................................................................
102 103 105 107 107 108 108 109 114 117
Windows 95/98 ........................................................................................ Windows 2000, Windows NT, Windows XP .............................................
118 118
Linux .......................................................................................... Hardware ................................................................................... First 1-Wire program ................................................................. Compile from Windows, run from Windows .............................. Compile from Windows, run from TINI ...................................... Compile from Linux, run from Linux .......................................... Compile from Linux, run from TINI ............................................
119 119 120 122 122 124 124
6 The TINI Hardware .....................................................
127
Versions .................................................................................... A high-level look at TINI ............................................................
128 129
Whats in a TINI stick? ............................................................................. A quick look at how it works .....................................................................
129 130
The SIMM (Single Inline Memory Module) edge connector ...... The processor and oscillator module ........................................
130 133
Programming example: the watchdog timer ............................................ A few words about the TINI address space ............................................. The TINI memory map ............................................................................. Flash ROM ............................................................................................... Static RAM ...............................................................................................
137 139 140 141 143
The RAM nonvolatizer ............................................................... The CPU Reset circuitry ............................................................ The internal 1-Wire net .............................................................. The external 1-Wire I/O, or iButton interface ............................. The RS232 interface ................................................................. The real-time clock ....................................................................
144 146 147 149 150 151
Programming example: using the real-time clock ..................... The Ethernet controller .............................................................. The I2C interface ....................................................................... The CAN interface ..................................................................... Whats in an E20 socket board? ............................................... The E20 in greater detail ...........................................................
153 155 157 158 158 160
The serial interface and DTR reset enable .............................................. The external 1-Wire interface ................................................................... The Ethernet interface ............................................................................. The CAN interface ................................................................................... The regulated power supply ..................................................................... Additional FLASH ..................................................................................... Support for Serial2 and Serial3 ................................................................ External interrupt selection circuitry ......................................................... Internal 1-Wire interface ........................................................................... The parallel IO section ............................................................................. The LCD interface from earlier versions ..................................................
160 162 162 163 164 164 167 168 169 169 172
Vinculum Technologies Group .................................................. Systronix ................................................................................... Additional products and vendors ............................................... Making a custom TINI socket ....................................................
173 174 174 175
7 The TINI Software .......................................................
Slush files and environment ......................................................
199
passwd ..................................................................................................... startup file ................................................................................................ tininet file .................................................................................................. User Home ............................................................................................... login file .................................................................................................... Servers in slush .......................................................................................
199 200 201 201 202 202
Tips for your programs ..............................................................
205
Threads .................................................................................................... Memory .................................................................................................... Networking ............................................................................................... Good ideas ............................................................................................... Java classes/methods (API 1.02d) .......................................................... File system ...............................................................................................
205 205 206 206 206 207
TINIConvertor ............................................................................ BuildDependency ...................................................................... A TINI example ......................................................................... Modifying slush .........................................................................
208 209 211 219
Recompiling Slush ................................................................................... Modifying the slush command set ............................................................ Adding optional commands to slush ........................................................ Adding new commands to slush ..............................................................
Using DOS batch files .............................................................................. Using FTP ................................................................................................ Using the DOS command window ...........................................................
232 235 236
GNUmake ................................................................................. Linux .......................................................................................... Windows .................................................................................... JEdit .......................................................................................... TiniHttpServer ........................................................................... TiniInstaller ................................................................................ TINIAnt ......................................................................................
237 237 237 240 242 242 242
8 Enhancing TINI ...........................................................
245
Adding data bus buffer .............................................................. The address decoder ................................................................ Adding an LCD display .............................................................. Adding buttons .......................................................................... Adding a keypad ....................................................................... Add an LED display ...................................................................
256 256 260 273 280 286
9 TINI Serial and Parallel I/O ........................................
295
A few serial port details .............................................................
296
The UART ................................................................................................ Flow control, parity, stop bits, data format ............................................... Serial line voltages ................................................................................... Cables and connectors ............................................................................
296 296 298 300
TINI serial ports .........................................................................
Serial communication software (API) ........................................ A serial example ........................................................................
311 313
Serial0 ...................................................................................................... Serial1 ...................................................................................................... Serial2 and serial3 ...................................................................................
313 321 328
A parting word on serial ports ................................................... TINI parallel ports ......................................................................
330 332
Port control ............................................................................................... Parallel I/O buffers/drivers .......................................................................
332 332
Parallel communication software (API) ..................................... A simple parallel device example .............................................. Another example ....................................................................... Other ways of handling parallel I/O ...........................................
334 337 341 344
10 Wire Basics for TINI .................................................
345
Wire Reset Details .................................................................... Wire Data Communication Details ............................................ The Read ROM command ........................................................ The Search ROM command .....................................................
350 350 354 356
Match ROM ............................................................................... Skip ROM .................................................................................. Memory commands ................................................................... DS2405 Addressable Switch ROM commands ......................... The DS2405 Match ROM command ......................................... The DS2405 Search ROM command .......................................
358 358 359 363 364 364
The Active Only Search ROM command .................................................
364
DS1920 ROM commands ......................................................... The DS1920 Alarm Search command ...................................... Communication ports on the PC ...............................................
367 367 371
The RS232 or serial (COM) ports ............................................................ The parallel or printer port ........................................................................ PC universal serial bus, or USB ............................................................... Cables and connectors ............................................................................
372 375 377 378
The 1-Wire Java API, TMEX drivers, and these mysterious things called port adapters ........................................................ Example: finding all 1-Wire devices on a specific port ..............
380 382
The DSPortAdapter class ........................................................................ The OneWireAccessProvider class ......................................................... The Enumeration class ............................................................................ The OneWireContainer class ...................................................................
383 384 385 385
Example: Finding devices by family on a specific port .............. Example: Identifying all software port adapters present ........... Example: Finding the default adapter ....................................... Example: Finding all 1-Wire devices on any port ...................... Example: Controlling the DS2405 addressable switch .............
394 396 398 400 401
The OneWireContainer05 class ...............................................................
402
Example: Measuring temperature with a DS1920 temperature iButton ...................................................................
411
The OneWireContainer10 class ...............................................................
411
The TINI external 1-Wire bus .................................................... The TINI internal 1-Wire bus ..................................................... TINI port adapter objects ........................................................... The TINI API .............................................................................
419 420 420 421
Example: A Java program for TINI that identifies port adapters .............. Example: Determining the default port on TINI ........................................ Example: Determining the ROM ID for all 1-Wire devices attached to TINI ..........................................................................................................
421 421
Example: Another way of determining the ROM ID for all 1Wire devices attached to TINI ................................................... Example: Yet another way of determining the ROM ID for all 1- Wire devices attached to TINI .......................................... Example: Controlling a DS2405 addressable switch from TINI ........................................................................................... Example: Using a temperature iButton with TINI ......................
422
425 428 430 430
11 The I2C Bus ..............................................................
433
The master/slave concept in I2C ............................................... The I2C data format ..................................................................
434 435
A few words about addressing .................................................. A typical I2C bus configuration .................................................. Extensions to the basic concept ................................................ TINI and I2C: Hardware ............................................................
439 439 440 440
Direct use of microcontroller port pins for I2C .......................................... Memory-mapped driver for I2C ................................................................
440 441
TINI and I2C: Software .............................................................. Example: Using TINI and I2C to drive a 7-segment LED display ....................................................................................... Example: A TINI digital thermometer ........................................ Example: Extending TINIs parallel I/O .....................................
442
12 Controller Area Network ..........................................
467
General overview ...................................................................... CAN versions ............................................................................ Bus states ................................................................................. Message coding ........................................................................ Frames ...................................................................................... Priority and arbitration ............................................................... Error detection and handling ..................................................... Synchronization and bit stuffing ................................................ Bit timing ................................................................................... Physical layers and media ........................................................ Higher-layer protocols ............................................................... C390 CAN controllers ...............................................................
Another word on bit timing ........................................................ A CAN bus monitor ................................................................... Another CAN example ..............................................................
488 490 500
13 Connecting TINI to an IP Network ..........................
511
Other relevant network commands ........................................... A simple TINI network ............................................................... A slightly more elaborate TINI network ..................................... The TINI networking classes ..................................................... How TINI does PPP ..................................................................
514 514 517 518 520
The six states of the PPPEventListener FSM ..........................................
521
The physical interface (cabling and modems) ...........................
523
Cables ...................................................................................................... Modem AT commands/HyperTerminal .................................................... Getting TINI to talk to a modem: The Modem class ................................. Testing the Modem class: The ModemATTest ........................................
523 524 528 535
A Modem Dialing Test: The ModemDialTest class ..................................
536
Example: Dialing out to an ISP (TINI as a PPP Client) ............. Example: Dialing into TINI from a PC (TINI as a PPP Server) ......................................................................................
538
A Modem Call Answering Test: The ModemAnswerTest class ............... The PPPServer class ...............................................................................
546 548
Example: Dialing into TINI from a PC (With Authentication) ..... Rebuilding Slush to include PPP ...............................................
554 561
The Optional Slush Command ppp .......................................................... The PPPCommand.java code .................................................................. TINI as a PPP client using the Slush command ppp ............................... TINI as a PPP server using the slush command ppp ..............................
561 563 564 565
14 A Few Final Thoughts ..............................................
TINI Ethernet MP3 Player4 ...................................................................... TINI CAN Monitor5 ................................................................................... Servertec Web Server for TINI6 ............................................................... X10 Libraries for TINI7 ............................................................................. TINI WAP Server8 ................................................................................... TINI Beer Keg9 ........................................................................................ TINI Drink machine10 .............................................................................. Toasty11 ..................................................................................................
574 574 574 574 574 574 575 575
Index ...............................................................................
577
545
What’s on the CD-ROM?
Included on the accompanying CD-ROM: • A directory containing all of the example programs in the book organized by chapter. • A full searchable eBook version of the text in Adobe pdf format. • Appendix A, providing information on TINI components and pinout • Appendix B, a listing of ByteUtils.java, which is used in a number of the example programs. • Appendix C, a compilation of simple input/output circuits that can be easily connected to various types of I/O for sensing or controlling external devices. Each example from the book is in a separate folder that is named according to the program name and the corresponding listing number from each chapter, so the proper listing ought to be very easy to find. To compile these listings using the supplied makefile (for linux) or build.bat (for Windows) you will need to set your environment variable as instructed in Chapter 3 of the book. Specifically, TINI_HOME must be set to point to the TINI API installation directory and OW_HOME must be set to point to the 1-wire API installation directory. The build.bat and Makefiles included with the compile instructions for each listing assume that you are using API 1.02d or e. On Windows/DOS, if you get an “Out of environment space” error, then you will need to increase the default environment space available for MS-DOS programs. To do this, add this line to your config.sys and then reboot your system: SHELL=C:\COMMAND.COM C:\ /E:2048 /P
See http://support.microsoft.com/default.aspx?scid=kb;EN-US;q230205 for more information. This is how we are setting the CLASSPATH for Windows (95/98/2000/NT/XP): SET SET SET SET SET
This is how we are setting the CLASSPATH for Linux: CLASSPATH=/usr/java/jdk1.3/lib/: /usr/java/jdk1.3/commapi/comm.jar OW_HOME=/opt/onewire CLASSPATH=$CLASSPATH:$OW_HOME/lib/OneWireAPI.jar. TINI_HOME=/opt/tini CLASSPATH=$CLASSPATH:$TINI_HOME/bin/tini.jar: $TINI_HOME/bin/tiniclasses.jar export TINI_HOME OW_HOME CLASSPATH
xii
CHAPTER
1
Introduction Why should you read this book? The target audience of this book is anyone interested in merging practical electronic devices with the Internet: students, teachers, home automation enthusiasts, hobbyists, and small businesses. Computer programmers looking for a gentle introduction to the world of hardware will benefit, as will hardware designers looking to expand their skills into the realm of JAVA programming. College engineering and computer science departments will find in this book a wealth of possibilities for lab projects that expose students to cutting-edge technology with minimal expense. Why should you read this book? The best reason of all: fun. This book will provide anyone interested in tinkering with hardware on the net hours of fun. Another reason: the future. Even if you’re not interested in making hardware, this book will give you a practical glimpse into what the real future and potential of the Internet is. The first Internet wave connected people via computer, popularizing things such as email, search engines, and online shopping. The next wave is going to be Internet appliances: electronic devices connected to the Internet. Ever wondered how those “live internet cams” work? They’re probably the most recognizable example of hardware connected to the web. In the past they were tremendously expensive and tended to be supported by engineering departments as an experimental thing. The future is going to see a tremendous expansion of low-cost, practical devices, connected to the Internet for home use. A good example might be a future VCR. Have you ever found yourself at work, wishing you had set the VCR to program your favorite show? A VCR that was an Internet appliance would give you the capability of programming your VCR from a web page, wherever you may be. Another good example of an Internet appliance might be a piece of hardware that allows you to control your thermostat, your lights,
1
Designing Embedded Internet Devices and your water heater from a web site. Cheap Internet appliance technology will make controlling devices in your home from a web page commonplace. Will everything in your house be “on the web” in the future? Probably not. But the growing number of people with Internet on their desk and the proliferation of cell phones and PDAs that can interact with web pages represents a growing market. That market is raising the attention of countless companies both large and small, looking to make products to put into every home. This book will examine commercial technology, discussing in great detail an inexpensive web-enabled microcontroller that can be used to connect a variety of devices to the web. Why should you read this book? So when the next big Internet wave happens, you’ll be in front of it! (And, there is that fun thing, too.)
What this book will do for you This book is a complete introduction to Internet-enabled devices. We provide all of the information you need to inexpensively build your own web-enabled hardware. Specifically, we’ll show you: 1. The basic terms and concepts required to understand the technology of webenabled devices. This includes detailed sections on networking and Java programming. 2. A quick overview of commercially available, web-enabled, microcontrollers, comparing their price and availability. 3. A step-by-step examination of TINI1, the Tiny InterNet Interface, a commercially available hardware/software package designed for use as a web interface to hardware. We’ll examine the hardware, software, and available enhancements in detail.
How this book is laid out The information in this book is divided into 14 chapters. Chapters 1 through 4 provide basic technical definitions with respect to networking and Internet clients and servers. We’re going to go into some detail on Java, the modern object-oriented, internet-ready, programming language rapidly becoming the language of choice for network applications. We’re not going to teach you Java, but we are going to cover some of the key features of the language that are very relevant to our topic, and are frequently not taught in the average Java course.
1
TINI is a registered trademark of Dallas Semiconductor. TINI can be purchased on the iButton website, http://www.ibutton.com/TINI/
2
Introduction Chapters 5 through 8 discuss, in great detail, the hardware and software behind TINI, Dallas Semiconductor’s commercially available, web-enabled microcontroller. This will include a high-level discussion of how the system works and an explanation of how to obtain and set up the hardware and software on your own Windows or Linux PC. Following that, we’ll present an indepth discussion of the TINI hardware. We’re going to explain what it is and how it works. Then, in a similar fashion, we’re going to take apart the TINI software. Finally, with detailed technical discussions of the TINI hardware and software as background, we’ll present detailed sections on how to upgrade the TINI hardware. Chapters 9 through 12 consist of detailed technical discussions of the various I/O busses provided by TINI. These include 1-Wire, CAN, I2C, and standard serial and parallel ports. Every topic is profusely illustrated, and filled with examples. Chapter 13 discusses how to connect TINI to a network, including how to attach a modem to TINI. This allows you to dial-in to TINI and have it act as a PPP server, or dial-out to an Internet service provider (ISP) allowing PPP clients to run on TINI. Finally, Chapter 14 provides a summary.
How to get the most out of this book Our book is not a novel, requiring cover-to-cover reading; rather, it’s a combination technology intro, how-to guide, and reference manual. What one needs to read, and how to get the most out of that reading, depends on who you are and what your goals are. 1. For those who are simply curious about how web-enabled devices might be implemented, chapters 1, 2, 4, and 5 should be read. They will give the necessary background and technical depth. Chapters 10, 11, and 12 can be skimmed to provide additional information on the breadth of devices that can be connected to a web-enabled device. 2. For those who are unfamiliar with microcontrollers but plan on implementing a web-enabled device of some sort, chapters 1 through 7 should be read. There’s enough information there to get you up and running. The remaining chapters can be skimmed to provide technical ideas, and serve as an excellent reference. 3. For those who are familiar with TINI, chapters 6 through 13 are an excellent reference.
3
Designing Embedded Internet Devices
What you should already know While you don’t have to be an engineer or computer scientist to have a lot of fun with this book, there are a few prerequisites. First, we assume that you understand basic electronics such as how to read circuit diagrams and how to use a soldering iron to build simple electronic circuits. Lastly, but most importantly, we assume basic knowledge of the Java programming language. We’re going to provide detailed explanations of how to get and install the Java language for your Windows or Linux computer, as well as how to obtain the appropriate technology-specific software and class libraries. We do this to provide a solid foundation on which to build our later examples. We’re going to explain in detail the Java examples we provide. But our book isn’t going to teach you Java. If you’re unfamiliar with Java, you may want to consider the following references. 1. Java 2 Platform, Standard Edition, v 1.3 API Specification. http://java.sun.com/j2se/1.3/docs/api/index.html 2. Campione, Mary and Walrath, Kathy. The Java Tutorial Second Edition: Object-Oriented Programming for the Internet, http://web2.java.sun.com/docs/books/tutorial/. Addison-Wesley, 1998. 3. Flanagan, David. Java in a Nutshell: A Desktop Quick Reference, O’Reilly & Associates, 1999. 4. Flanagan, David. Java Examples in a Nutshell, O’Reilly & Associates, 1999. 5. Wu, C. Thomas. An Introduction to Object Oriented Programming with Java, McGraw Hill College Div, 1998. We hope you enjoy this book.
4
CHAPTER
2
Computer Networks Since this book is about designing network-enabled devices, it probably makes some sense to start with a little discussion about networks. This is not a substitute for a complete lesson in building computer networks, but just enough to establish some terms and common ground to get you through this book. Throughout this book we’ll be talking primarily about 10base-T Ethernet networks using the TCP/IP protocols (there are many other ways to network computers together that are far beyond the scope of this book; see the reference section at the end of the chapter).
Network Hardware So what is a computer network? A network is a collection (two or more) of computers that are connected together for sharing data and resources. Networks are commonly categorized by their geographical size. A local area network (a LAN) is a group of computers and associated devices that share a common communication line and are typically located within a small geographic area, such as in your home or in an office building, or even a single department in a company. A local area network may connect as few as two or three users, as in a home network, or as many as several hundred users, as in a business. A metropolitan area network (a MAN) is a bit more diverse, incorporating computers and LANs that are distributed over a few miles of area, as you would find between corporate buildings or on a college campus. A wide area network (a WAN) is a widely geographically dispersed computer network that is composed of multiple LANs and MANs and can be spread across a country or around the globe. The Internet (sometimes simply referred to as “the Net”) is a worldwide network of many computer networks (LANs, MANs, and WANs) that is accessible to hundreds of millions of people worldwide.
5
Designing Embedded Internet Devices
A really simple network Connecting two computers together forms the simplest computer network, as shown in Figure 2-1. The computers, often referred to as hosts or nodes on a network, are connected to the network through a network interface card (NIC). The network interface is a computer circuit board or card (or sometimes a single integrated circuit) that provides the logic for sending and receiving data from and to the host computer. There are a number of ways to connect these computers but by far the most common way is by using an Ethernet connection.
192.168.27.86
192.168.27.99 NIC
NIC Network Cable
Computer #1
Computer #2
Figure 2-1: A really simple computer network
Ethernet is the most widely used local area network technology these days, particularly for home networks and small offices. It is fully described and specified in IEEE standard 802.3 (if knowing that sort of thing is important to you). The most commonly installed Ethernet system is called 10BASE-T and provides transmission speeds up to 10 Mbps. The designation 10BASE-T is a shorthand identifier: The “10” in the media type designation refers to the transmission speed of 10 Mbps, the “BASE” refers to baseband signaling (not broadband), which simply means that only a single Ethernet signal set is carried on the cable, and the “T” represents twistedpair. The reason we even mention this is because other types of Ethernet are becoming more popular like 100BASE-T (100 mbps) and 100BASE-F (“F” for fiber) but for this book we are only really concerned with 10Base-T and 100 Base-T (often printed as 10/100Base-T). Another thing we need to note about this simple network of two computers is the cable directly connecting the two computers, commonly called a crossover cable. A crossover cable is a special type of Ethernet cable that is used to interconnect two computers by “crossing over” (reversing) their respective pin contacts for transmitted and received data. It allows the data transmitted by one computer to be connected to the receiving pin on the other and vice-versa. While this may seem like a trivial point, it is important to know that this is a crossover cable and what it does.
6
Computer Networks One last thing: each node in the network has a unique address, its network address. This is not a big deal with a simple network of two computers but as the networks expand and LANs are connected to other LANs and WANs, this is increasingly important. We will talk more about this address in a subsequent section.
A small office and home network Connecting multiple computers together to form a home or small office network is almost as simple as the previous two-computer network, just involving a few more components. Refer to Figure 2-2 for a slightly more complex network configuration. The first thing you will notice is the use of a network hub, usually simply called a Computer #5
Computer #1
NIC NIC
Computer #6 Hub
192.168.27.89
NIC
192.168.27.90
192.168.27.34 Hub Computer #2 NIC Computer #3
192.168.27.99 NIC
Computer #4 NIC
192.168.27.16
192.168.27.33
Figure 2-2: A complex network
hub. A hub is a connector where network data arrives from one or more directions and is forwarded out in all of the other directions. Each of the computers in our network is connected to the network through a hub. Internal to the hub, the transmit wires from one computer are connected to the receive wires of the others; in others words the hub also performs the crossover function that the crossover cable did in the two-computer network. So this network is connected with network cables that are “straight through.” The wires on pin 1 through 8 are connected to pins 1 through 8 on the opposite end, with no crossover. Hubs are connected to each other through an uplink port. The uplink port is similar to an ordinary port but the wires have not internally been reversed so it can be connected to another hub to increase the number of nodes in your network. If the hub does not have an uplink port then hubs can be connected to each other with a crossover cable.
7
Designing Embedded Internet Devices Again, notice that each node in the network has a unique address, its network address. We will talk more about this address in a subsequent section.
Connecting a LAN to the Internet (or a LAN, MAN, WAN) Broadband connection Now that we have our local area network as discussed above, how would we then connect this to other networks, either another LAN or a WAN or even the Internet? This is done with a wide variety of network devices. Some of these are: •
Hub – A hub is the generic name for a device where several nodes are connected to a network. A hub may be a repeater, switch, or a router. A hub may perform the function of several of these components.
•
Gateway – A gateway is a generic name for a device that is used to connect multiple networks together. A gateway may be a repeater, bridge or router.
•
Repeater – A repeater is a network hub that serves as a connection between 2 segments of a network. Repeaters only amplify all information they receive and pass it through to all of its ports.
•
Router – A router is a smart hub, which can connect segments of different networks that use a different protocol.
•
Switch – A switch is a network hub that acts like a repeater but instead of passing information on to all of its ports, it establishes a direct connection to the destination port.
•
Bridge – A bridge is a device for connecting segments of a network or multiple networks that use the same protocol.
All of these devices are somewhat similar—in fact, the functions of several are often combined in one device. We will connect our LAN to the Internet with one of these generic network gateway devices. There are several types of gateways: repeaters, bridges, and routers. The technical distinction between these components is based on which layer of the Internet Protocol they operate on and that is really beyond the scope of this chapter. We will then connect our gateway to a modem. A modem (and there are many types of modems) can also act as a gateway from a LAN to a WAN but are usually separate devices. The modem modulates outgoing digital signals from a computer or other digital device to analog signals suitable for transmission on conventional telephone lines, cable TV coax, Digital Subscriber Line (DSL) or fiber and then demodulates the incoming analog signal and converts it to a digital signal. This is the type of gateway shown in the following network, Figure 2-3. This LAN could also be connected to another LAN or WAN with a simple hub or gateway without the modem. But if we opt for the hub, then this would not keep this
8
Computer Networks 192.168.27.89
Computer #1 NIC
Hub/Router Broadband Modem Computer #2
If Router, router has IP address (208.185.127.162)
NIC
Twisted Pair, Coax Cable, Fiber Optic cable, etc
192.168.27.99 If Hub, all IP addresses are visible to WAN
Computer #3
Broadband Modem
NIC 192.168.27.16
To WAN or Internet
Figure 2-3: Broadband network
local area network as a separate network. This network would then be a part of the larger WAN. The hub passes all data from its input to all of the lines on the network. This is one of the reasons for creating smaller networks or sub-networks—to isolate data transmission between computers.
Alternate broadband connection An alternate way to connect a simple network is to use a computer with two network interface cards as shown in Figure 2-4. In essence, this computer (and appropriate software) acts as the gateway and router for your local area network. It is important to note that one NIC has a network address that is known only to the WAN or Internet and the other NIC has a network address that is known only to the LAN. These addresses can be either static or dynamically allocated. This would allow you to use static IP addresses on your LAN and connect to your ISP with static or dynamic addresses. Windows 98 Second Edition directly supports multiple NICs and Internet sharing, and there are numerous software packages that can add this function to either Windows or Linux.
Dial up connection A final alternative for connecting your LAN to a WAN or Internet is the use of a PPP connection through a dial-up modem. This is shown in Figure 2-5. Point-to-Point Protocol (PPP) is a protocol for communication between two computers using a serial interface, typically a personal computer connected by phone line to a service provider. But this can be as simple as a serial line with no modem. Essentially, it packages your computer’s TCP/IP packets and forwards them to the server.
9
Designing Embedded Internet Devices Computer #1
To WAN or Internet
192.168.27.89 NIC Hub Broadband Modem
Computer #2
Twisted Pair, Coax Cable, Fiber Optic cable, etc
NIC 192.168.27.99 Computer #3
192.168.27.16 NIC Broadband Modem
NIC 208.185.127.162
Figure 2-4: Alternate broadband network
To WAN or Internet
192.168.27.86
Computer #1 NIC
Hub/Router
Telephone Modem
Computer #2
Twisted Pair telephone line
NIC 192.168.27.99 192.168.27.16
Computer #3 NIC
PPP connection Modem
Telephone Modem
Apparent IP Address 208.185.127.162
Figure 2-5: PPP network connection
10
Computer Networks
The 10/100 Base-T cable Ethernet uses a special type of cable called twisted pair. Twisted pair cable is made of four pairs (in this case) of insulated copper wires that are twisted around each other in pairs to reduce electromagnetic induction between pairs of wires. The combination of these four sets of twisted wires forms a network cable that is commonly referred to as Category-5 or CAT 5 cable. It derives that name from the American National Standards Institute/Electronic Industries Association (ANSI/EIA) Standard 568, in which this cable is specified. That same specification lists several standards that specify categories of twisted pair cabling systems (wires and connectors) in terms of the maximum data rates that they can reliably sustain. This specification describes the cable material as well as the types of connectors and junction blocks to be used in order to conform to a particular category. CAT5 cable is different from the wire you buy at your local hardware store for connecting your phone or computer modems to a wall jack, which is not twisted pair, but is a side-byside wire also known as silver satin. The two most popular specifications are CAT 3 and CAT 5. While the two cables may look identical, CAT 3 is intended for a lower data rate and can cause transmission errors if used for faster speeds. CAT 3 cabling is for signals that are 16 MHz or less and is suitable for 10base-T networks, while CAT 5 cable must pass a 100-MHz test to be suitable for 100base-T networks. The connector on a 10/100 BASE-T cable is an RJ45, which is short for Registered Jack-45. This is an eight-pin connector that is commonly used for network cables, especially Ethernet. The RJ-45 connectors look very much like the modular connectors Table 2-1: Network cable wire categories Category
Maximum Data Rate
Typical Applications
CAT 1
< 1 Mbps
CAT 2
4 Mbps
CAT 3
16 Mbps
CAT 4
20 Mbps
CAT 5
100 Mbps
100Base-T Ethernet
CAT5e
100 Mbps
100Base-T Ethernet with improved transmission
CAT6
250 Mbps
Proposed Standard
CAT7
600 Mbps
Proposed Standard
Voice telephone service Integrated Services Digital Network (ISDN)
10Base-T Ethernet
11
Designing Embedded Internet Devices on modern telephones (RJ-11), but they are somewhat wider as they have eight wires in them. There are many, many types of RJ style connectors and they vary widely. Since we have talked about twisted pair cable and all that, perhaps it would make sense if we also discussed the detail of the Ethernet cable (the wire colors/order) and crossover cable so you can wire up your network. Essentially, the difference between 10Base-T and 100Base-T is the data rate. In Table 2-1 we can see that 10base-T needs at least a CAT3 cable to support the 10 mbps data rate error free and 100BaseT needs CAT5 wire. If you are wiring up a new network it is probably better to make it with CAT5 and wire it for 100 mbps, even if you are going to use it for 10Base-T communications. It will work just fine for 10 mbps and it’s ready to upgrade to 100Base-T. It’s also easier to find CAT5 cable and it is not noticeably more expensive. If you use CAT3 cable for a 10Base-T, when you upgrade you will need new wires and you run the risk of getting all of your 10-mbps wiring confused with 100mbps wire—and you’ll just have a great big mess on your hands. Shown in Figure 2-6 is the wiring for a straight-through (not a crossover) cable that is more typical for network connections. The wire color order is the same for both ends of the cable.
RD-
RD+ TDTD+
8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8
TD+ TDRD+
RD-
Figure 2-6: 10/100Base-T Straight-through cable
Shown in Figure 2-7 is the wiring for the crossover cable that we used for our simple two-node network above. You will notice that the wire color order is not the same for both ends of this cable. You should carefully label or mark your crossover cables so that they are not easily confused with straight-through cables. I make mine from a different color cable so that they are immediately obvious.
RD-
RD+ TDTD+
8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8
Figure 2-7: 10/100Base-T Crossover cable
12
TD+ TDRD+
RD-
Computer Networks Table 2-2 lists the wire colors and pin numbers for both straight-through and crossover cables. You may find reference to that fact that only pins 1, 2, 3 and 6 are used in 10/100 Base-T network cables. This is generally true but there are some networks like 100Base-T4 that use the remaining wires, and faster networks like 1000Base-T also use all four pairs and are capable of supporting error-free transmission using CAT5e cable (“e” means “enhanced” for lower crosstalk between the conductors of the neighboring twisted pairs in the same cable). If you completely wire the connector, you will maximize the usefulness of your cables by allowing them to be used in many possible network configurations. Table 2-2: 10/100 Base-T cable wire color code Straight-through Cable (Both Ends)
Crossover Cable (One End)
1 – White/Orange 2 – Orange 3 – White/Green 4 – Blue 5 – White/Blue 6 – Green 7 – White/Brown 8 – Brown
1 – White/Green 2 – Green 3 – White/Orange 4 – Blue 5 – White/Blue 6 – Orange 7 – White/Brown 8 – Brown
Network Addresses Each computer or node in a network really has two addresses. Actually, each interface in a computer or node has two addresses, as a single computer (or any network device) can have multiple network interfaces. These addresses are the Internet Address and the Ethernet address. The Ethernet address is a hardware address that identifies this specific network interface. The Internet address is a logical address that provides routing information so other computers on the network can find it.
Ethernet address An Ethernet hardware address is also known as the Media Access Control (MAC) Address. This is a 12-digit hexadecimal (0-9, A-F) number that uniquely identifies your (and every other) Ethernet adapter. Manufacturers are assigned Ethernet address blocks to use, and they are used to identify each machine on the network. Ethernet addresses are usually shown as bytes separated by a colon or a dash, like this: 00:06:35:00:6B:BF
or
00-06-35-00-6B-BF
The Ethernet address is always exactly 12 hexadecimal digits, so all leading zeroes are significant and must be entered. Since this address is a physical address it is
13
Designing Embedded Internet Devices programmed into the network interface card and generally cannot be changed, while the Internet Address is a logical address and can be reassigned as needed. Also, there is no direct correlation between the Ethernet and Internet address and one cannot be calculated based on the other. Ethernet addresses are unique and never reused, unlike an Internet address that can be used on sub-networks and isolated networks. For the scope of this book it is not necessary to know more detail about the Ethernet address.
Internet addresses The Internet Address is also called an IP address or Host Address. It is a logical address assigned to the network interface card in your computer. An IP address (where IP means Internet Protocol) is how one computer can find another computer on a network. Each node must know its own address on the network and that of any other computer with which it will communicate. The IP address is a 32-bit binary number that identifies each packet of information sent across the network. The IP address is usually expressed as four decimal numbers, each representing eight bits, separated by periods. This is sometimes known as the “dot address” or as “dotted quad notation.” For instance, in the example network shown in Figure 2-2, address 192.168.27.16 is the IP address of one of the machines. This is internally stored and used as the integer 3,232,242,448 which is 11000000.10101000.00011011.00010000. This can be represented in decimal numbers as shown: 1100 0000 . 1010 1000 . 0001 1011 . 0001 0000 192 . 168 . 27 . 16
Domain names The numerical version of the IP address is usually represented by a name or series of names called the domain name—for instance, www.someplace.com or ftp. filearchive.edu, which is mapped into a static IP address using the Domain Name System (DNS). The DNS is a hierarchical database used for translating the domain name to an IP address. When your computer needs to translate a domain name into a numerical IP address, it asks a domain name server to provide this information.
Network classes The original Internet Protocol defines IP addresses in five major classes of address structure, Classes A through E. This has been named classful routing (probably in hindsight considering some of the improvements made to IP addressing that we will get to in a minute). Each of these classes allocates one portion of the 32-bit Internet address format to a network address and the remaining portion to the specific host machines within the network specified by the address. Class E is reserved for experimental use. Class D addresses are used for multicasting. Multicasting is data transmission between a single sender and multiple receivers on a network.
14
Computer Networks Class A networks use the 8 leftmost bits (the leftmost of the dotted quads) to designate the network number. The leftmost bit of these 8 bits is always 0, so Class A IP addresses range from 0.x.x.x to 127.x.x.x, except that address 0.x.x.x and 127.x.x.x are reserved for special use so this means there are 126 possible Class A networks. The rest of the dotted quads refer to the specific hosts or nodes on a large network. Since there are 24 bits in the remaining address, this means there can be 224 possible hosts in each class A network, except that the all 0’s case is reserved and means “this network” and the all 1’s case is used for broadcasting, which leaves 16,777,214 possible hosts. So, a portion of the IP address represents the network number or address and a portion represents the local machine address. Class B networks use the 16 leftmost bits (the leftmost two dotted quads) to designate the network number. The leftmost two of these 16 bits are always 10 so Class B addresses range from 128.0.x.x to 191.255.x.x, which means there are 16,384 possible Class B networks. The remaining two dotted quads (16 bits) refer to specific hosts or nodes on these networks. These 16 bits means there are 216 possible hosts in each Class B network, except that the all 0’s case is reserved and means “this network” and the all 1’s case is used for broadcasting, which leaves 65,534 possible hosts. Using the above example, here’s how the IP address is divided: 155.185 . 127.162 Network Host Address Address
Class C networks use the 24 leftmost bits (the leftmost three dotted quads) to designate the network number. The leftmost three of these 24 bits are always 110 so Class C addresses range from 192.0.0.x to 223.255.255.x, which means there are 2,097,152 possible Class C networks. The remaining 8 bits (the right most dotted quad) refers to the specific hosts or nodes on each of these networks. These 8 bits means that there are 28 possible hosts in each class C network or 254 possible hosts (256 minus the all 0’s and all 1’s case as in the Class A and B networks). In the class C network the addresses from 192.168.0.0 to 192.168.255.0 are reserved for networks not directly connected to the Internet. If you are really curious, you can look up the addresses in the different classes and see who they are assigned to on the “IP Network Index”1 web page. Not considering all of the reserved addresses in class A, B and C, there are 223 or 4,294,967,296 possible IP addresses. While this might seem like a lot of addresses, many were not being used by the Class A address owners and with the rapid growth of broadband users and dedicated network devices, it turns out this is not enough addresses to support the future growth of the Internet. To overcome this limited 1
IP Network Index, http://ipindex.dragonstar.net/
15
Designing Embedded Internet Devices address space, a number of fixes have been devised, such as Subnetworking and Classless Inter-Domain Routing.
Subnetworks A subnetwork is a logically separate portion of a larger network. It is a way of taking a single network address and splitting it so that a single network address can be used on several local networks. While not 100% technically accurate, it is kind of like splitting a class A or B network into smaller networks (or subnetworks). If you wanted to a add subnet to the sample address above, then some portion of the host address could be used for a subnet address. A company with a Class B address who needed more than 254 host machines, but far fewer than the 65,533 host addresses possible, would essentially be “wasting” most of the block of addresses allocated. That company could use several subnets and the remaining could be allocated to another company. A class A network address could be subnetted by allocating the second and maybe even the third dotted quad for a subnet address. A class B network address could be subnetted by allocating the third dotted quad for the subnet address as shown in this example: 155.185 Network Address
.
127 . Subnet Address
162 Host Address
To determine which part of the IP address was the host address and which was the subnet address, the IP address was paired with a subnet mask. This mask was used to separate the extended-network prefix (the network address and the subnet address) from the host address (logically ANDing the address and the subnet mask returns just the extended network prefix). With this technique, each of the quads of the subnet mask was either all binary 1’s or all 0’s (255 or 0). IP address Subnet mask
Classless Inter-Domain Routing (CIDR) was developed to effectively solve some of the problems with classful routing and some of the limitations of subnetting and extended network prefix by providing a new and more flexible way to specify network addresses in routers. CIDR uses a variable-length subnet mask that does not necessarily have to be divided on any of the whole byte boundaries of the dotted quads. CIDR essentially eliminates classful routing (class A, B, D networks) by allowing the subnet mask to be any size. With CIDR a network address might look like this:
This could also be specified by simply saying how many bits were 1’s. In the example above, this is 21. So a CIDR address is also shown like this. 155.185.127.162/21 The “155.185.127.162” is the network address and the “21” means that the first 21 bits are the network part of the address, leaving the last 11 bits for the host addresses. There are also a number of other benefits of CIDR supporting route aggregation, which greatly simplifies network router routing tables.
DHCP So far, our IP address discussion above assumes that IP addresses are assigned on a static basis, that you get a specific address for each node in your network and things stay that way. Dynamic Host Configuration Protocol (DHCP) is a protocol that lets a network automatically assign an IP address to each node in a network as it is connected to the network. With the growing number of Internet users these days, many IP addresses are assigned dynamically from a pool of allocated address. This lets many corporate networks and online services economize on the number of IP addresses they use by sharing the pool of IP addresses with a large number of users. This is very often the case if you use a dial-up TCP/IP connection. Here your IP address will vary from one login session to the next because it is assigned to you from a pool that is much smaller than the total number of users. DHCP lets a network administrator supervise and distribute IP addresses from a central point and automatically sends a new IP address when a computer is plugged into a different place in the network. Understanding IP addressing thoroughly could certainly take up this entire book and that’s not the point of this book. If you need to know more about IP addressing you are encouraged to read some of the material listed in the reference section of the chapter.
Network Communication We now turn our attention to the inner workings of TCP/IP, mostly because we will need it when we talk about sockets and some of the different protocols later on in the book. TCP/IP is named after the most commonly used protocols in the Internet Protocol set: • TCP = Transmission Control Protocol • IP = Internet Protocol 17
Designing Embedded Internet Devices TCP/IP is the basic communication language or protocol of the Internet. It can also be used as a communications protocol in a private network (either an intranet or an extranet). TCP/IP is a two-layer protocol. The higher layer, Transmission Control Protocol, manages the assembling of a message or file into smaller packets (see packet) that are transmitted over the Internet and received by a TCP layer that reassembles the packets into the original message. The lower layer, Internet Protocol, handles the address part of each packet so that it gets to the right destination. Each gateway computer on the network checks this address to see where to forward the message. Even though some packets from the same message are routed differently than others, they’ll be reassembled at the destination.
Protocols Discussions of network communications often center on what is known as a protocol stack. A protocol is the set of rules that computers (or other network devices) in a network use when they communicate. In essence, a protocol is the language the network devices use to talk to each other. A protocol stack is an abstract model that divides the network up into layers, based on functions and communication protocols used in those functions. Each layer in the stack only talks to the layer above or below it, using the protocols defined in those layers. As information is passed down the stack, it is encapsulated. Encapsulation is basically a process of adding a protocol specific header to the information received from the layer above. As information is passed up the stack, the header specific to the current layer is stripped off and the data is sent to the layer above. By adhering to this protocol stack concept, software and hardware can be designed without worrying about the details of what’s going on in all the layers, just the neighboring layers. Things become reusable, transportable, device independent. The OSI (Open Systems Interconnection) reference model is an ideal protocol stack of sorts. You will see this model in most discussions and textbooks on network protocols. Its purpose is to guide software developers and hardware designers so that their products will consistently work with other products. The reference model defines seven layers of functions that take place at each end of a communication. Although OSI is not always strictly adhered to in terms of keeping related functions together in a well-defined layer, many if not most products involved in telecommunications make an attempt to describe them in relation to the OSI model. The software and hardware that furnishes these seven layers of functions are usually a combination of the computer operating system, applications (such as your Web browser), TCP/IP or alternative transport and network protocols, and the software and hardware that enable you to put a signal on one of the lines attached to your computer. The OSI reference model is shown in Figure 2-8 and each layer is described below.
18
Computer Networks •
The application layer is where common services of the operating system are offered to all applications. This layer is not the application itself, although some applications may perform application layer functions.)
•
The presentation layer is usually the part of an operating system that converts incoming and outgoing data from one format to another (for example, from a text stream into a popup window with the newly arrived text). This is sometimes called the syntax layer. Compression/decompression and encryption/decryption are performed in this layer.
•
The session layer initiates, coordinates, synchronizes and terminates conversations and exchanges between the applications at each end. It deals with session and connection coordination.
•
The transport layer manages the transmission of messages, determining whether all packets have arrived, and checks for errors.
•
The network layer handles the routing and forwarding of the data on the network.
•
The data-link layer is the layer that provides synchronization for the physical level. It provides data transmission protocol knowledge and management.
•
The physical layer conveys the data stream through the network at the electrical and mechanical level.
What is essential about TCP/IP is that it is a layered protocol that loosely follows this OSI Reference model. Each layer adds information onto the previous layers without modifying the contents of the previous layer. TCP/IP is actually (some will argue this point) implemented in four layers as shown in Figure 2-8. At the top of this stack is the application layer. It is so named because it is at this highest level where we run user applications such as web browsers, Telnet, and FTP programs. The communications protocols associated with the application layer are the related HTTP, Telnet and FTP protocols specific to those applications. At the bottom of the stack is hardware, requiring vendor-specific device drivers. In between are the transport, network and link layers. Each is designed to introduce another level of modularity from top to bottom. Our discussion is going to focus on the transport layer. The transport layer uses communication protocols such as TCP (transport control protocol) and UDP (user datagram protocol) to encapsulate data in the various application layer protocols and forward it to the Internet layer for encapsulation into the Internet Protocol. TCP is considered a connection based protocol, because when two entities communicate using TCP, there is guaranteed receipt of the information, or errors are reported. UDP is not a connection-based protocol. Packets of data are sent and there is no acknowledgement of receipt of data.
Part of the application layer has some very useful functions that we will make extensive use of throughout this book: Telnet, HTTP, FTP and SMTP. •
Telnet is the way to access another computer on a network. Telnet is both a user application and an underlying TCP/IP protocol for accessing remote computers.
•
Hypertext Transfer Protocol (HTTP) is the set of rules for exchanging multimedia files (text, graphic images, sound, video) on the World Wide Web. A web server delivers files to your web browser using the HTTP protocol.
•
Simple Mail Transfer Protocol (SMTP) is a TCP/IP protocol used for sending and receiving e-mail messages.
•
File Transfer Protocol (FTP) is the simple protocol for exchanging files between computers on a network.
Client/server All of the above listed protocols (Telnet, FTP, HTTP, SMTP) are used in a client/ server relationship. In the computing sense, a client is a program or computer that is requesting information (data) or a service from another program or another computer. A web browser is
20
Computer Networks the most commonly recognized client these days. A server is a computer or program (the term can apply to either) that provides information or services to other computer programs on the same computer or to another computer in a network. A web server is a common example. The client/server relationship describes the relationship between two computer programs in which one program, the client, makes a service request from another program, the server, which fulfills the request. There are many, many types of clients and servers, each specializing in receiving and processing or storing and distributing a certain king of information.
Ports and Sockets The means by which these client/server computers communicate over the network is through sockets, and the language they speak are protocols (more on those in the next section). Client
Server Reply
Request
Rest of network
Figure 2-9: Client/server
A socket is a logical connection for computer applications to pass information back and forth between networked computers. In a similar fashion, a serial port is a physical connection for passing information between a computer and a peripheral device. A socket is one endpoint of a two-way communication link between two programs running on the network. Two-way communication over the Internet is typically performed by client-server pairs. A server creates a socket that can listen for connection requests from clients. When a client creates a socket, a connection request is made. The mechanism that associates a specific client socket to a specific server socket is a port. A port is a 16-bit number typically associated with a particular application layer service such as web browsing (the HTTP protocol), Telnet, or FTP. Client/server communication proceeds as follows. A server creates a special server socket that is associated with, or binds, to a specific port number. It then listens for client requests for connections to that port. When a client wants to communicate with
21
Designing Embedded Internet Devices the service offered the server, it creates a socket to that port. The server accepts the connection and responds with information. Port numbers 1-1023 are reserved and correspond to pre-defined services such as email, web pages, Telnet, FTP, ping, finger, time, etc. Table 2-3 lists port numbers and services for some well-known ports. Use these port numbers with caution! Unless you are trying to write programs to communicate with these predefined services, choose a port number 1024 or higher. Table 2-3: Some common ports
Port
Service
7 13 20 21 23 25 53 70 79 80 119
Echo Daytime FTP Data FTP Control Telnet SNMP DNS Gopher Finger http NNTP
A very detailed (and long) list of port assignments can be found on the “Assigned Port Numbers”2 page and also in RFC1700. Port numbers 1024 –65,535 are available for use in your own programs to form custom services.
Summary So now you have a nice quick overview of networks. This really was not intended to be a complete lesson in building computer networks; in fact, we have just barely scraped the surface. Hopefully, however, you now have enough information to successfully complete the projects in the rest of this book and the background to understand them. We would encourage you to examine some of the references listed next if you need more information or are just curious.
References 1. Charles Spurgeon’s Ethernet Web Site. http://wwwhost.ots.utexas.edu/ethernet/
Computer Networks 2. Configuring the DNS Service. http://www.cisco.com/univercd/cc/td/doc/product/iaabu/cddm/cddm111/ adguide/dns.htm 3. TechFest Ethernet Technical Summary. http://www.techfest.com/networking/lan/ethernet.htm 4. Bennett, Geoff. Designing TCP/IP Networks. Van Nostrand Reinhold, 1995 5. Semeria, Chuck. Understanding IP Addresses: Everything You Ever Wanted To Know. 3Com Corporation, April 26, 1996. http://www.3com.com/nsc/501302.html 6. A Request for Comments (RFC) is a document written by the Internet Engineering Task Force. These are the result of a committee drafting and subsequently reviewed by interested parties. Some become Internet standards, however, through subsequent RFCs that supercede an existing RFC. You can view the RFCs online in a number of places; one of the more complete is “Internet RFC/STD/FYI/BCP Archives,” http://www.faqs.org/rfcs/ These are some common RFCs that you might want to know about if you are working on a project that uses a specific protocol for communication: • • • • •
Java Essentials for Embedded Networked Devices Throughout this book, we will be using Java1 as the language of choice for controlling our network-enabled devices. In this chapter, we will discuss getting the Java Development Kit (JDK version 1.3) and the Java runtime environment up and running on your computer, for both Microsoft Windows2 and Linux. If you already have Java installed, and are familiar with programming in Java, then you can probably skip this chapter (or just skim through it so you know what’s here).
The Java Development Kit Java is distributed by Sun Microsystems in the form of the Software Development Kit (SDK). The SDK includes the Java compiler, Java debugger, a number of development tools, and the Java Runtime Environment (JRE). The JRE consists of the Java virtual machine, the Java platform core classes, and supporting files. Along with the base Java classes, we will be using a number of the Application Programming Interfaces (API). An API is the interface through which an application program accesses the operating system and other services. In other words, an API is like a library of subroutine packages for a specific purpose. An example would be the class libraries used for accessing a computer’s serial ports. The API provides a level of abstraction between the application and the lower-level software, hardware, or privileged utilities to ensure the portability of the code. You will need to download the current version of the Java Software Development Kit from Sun’s “Java Products & API’s” web page3. This is also called the J2SE for “Java 2 Platform, Standard Edition.” This book is based on the Java 2 Software Development Kit (SDK) version 1.3 for your platform (Windows or Linux). The 1 2
3
Java is a registered trademark of Sun Microsystems. Windows 95, Windows 98, Windows XP, Windows 2000 and Windows NT are registered trademarks of Microsoft Corporation. Java Products & API’s, http://java.sun.com/products/
25
Designing Embedded Internet Devices basic installation steps are listed here but if you run into difficulties, you should follow the more detailed installation instructions listed on the Sun web page.
For Windows Remove any older version of the Java Development Kit you may have installed on your computer. (Click on the START button and select Settings, Control Panel, Add/ Remove Programs and examine this list of installed applications.) Go to the “Java Products & API’s” web page and click on the link for “Java 2 SDK, Standard Edition.” Download Java 2 SDK, saving the file (j2sdk1_3_0-win.exe) in a temporary directory. Using Windows Explorer, double-click on the file you just downloaded to execute the Java SDK installer. This will install Java on your computer. Follow the instructions. This will create a directory hierarchy on your disk starting in C:\JDK1.3 (or a different disk if your disks are labeled differently). If you download and install a newer version, then some of the filenames and path names will change to reflect the version number.
Windows 95/98 On Windows 95/98 you must edit your Autoexec.bat file and add a folder to your PATH environment variable. Using Notepad (or some other ASCII editor), open your c:\autoexec.bat file. If you already have a PATH environment variable set, then you will need to add the location of the Java binaries. After the PATH environment variable, insert a new line that will append the c:\jdk1.3\bin\ directory to the existing path. SET PATH=c:\jdk1.3\bin\;%PATH%
If you don’t have a PATH environment variable, add one by inserting a line at the bottom of the autoexec.bat file like this: SET PATH=c:\jdk1.3\bin\;c:\windows
Save the file and exit the editor. This PATH environment variable tells the operating system where to find the Java programs when you need them.
Windows 2000, Windows NT, Windows XP For Windows 2000 and Windows NT you will have to use the “System” tool in the “Control Panel.” Select the “Environment” tab and look for “Path” in the User Variables and System Variables. If a path variable exists, add the location of the Java binaries (c:\jdk1.3\bin\, unless you installed Java someplace else). If you don’t have a path variable, create one. For Windows XP, use the “System” tool in the “Control Panel.” Select the “Advanced” tab and click on the “Environment” button (under “startup and recovery”). Modify or create the path variable as above.
26
Java Essentials for Embedded Networked Devices At this point, you don’t need to have the CLASSPATH variable set. We will cover that in a later section. To test out your installation of the Java SDK you need to restart your computer. Do that and then create a simple test program to verify that all is well so far. A simple “HelloWorld” program like the following should work just fine. Listing 3-1: HelloWorld.java public class HelloWorld { // Simple program to make sure compiler is installed ok public static void main( String args[] ) { System.out.println( “Hello, World!” ); } }
Open a DOS command window. c:\> notepad HelloWorld.java
Enter the Java program above into the text editor. Save the file and exit the editor. Then compile and run the program: c:\> javac HelloWorld.java c:\> java HelloWorld
If there were no errors from either of the last two commands above, then you are all set to move on to installing the serial port API for Java. If you saw any errors when compiling or running the program, then you should carefully check the program you entered to see that you typed it correctly. Also check to see that you installed the Java Software Development Kit properly. While these instructions are for J2SE version 1.3, by the time you read this book Sun will probably have released a newer version. It is likely that the installation procedures will be slightly different. These are some common errors and their solutions: C:\> javac HelloWorld.java Bad command or file name
• c:\jdk1.3\bin is not in your PATH environment variable. Or you added it but you didn’t restart your computer. Check your current PATH with this DOS command: echo %PATH% C:\chapter03> java HelloWorld Exception in thread “main” java.lang.NoClassDefFoundError: HelloWorld
• Didn’t compile HelloWorld.java (javac HelloWorld.java). • HelloWorld.java had errors so the compiler didn’t write the class file.
27
Designing Embedded Internet Devices • You have a CLASSPATH environment variables set and “.” (current folder) is not in the CLASSPATH or there are errors in your CLASSPATH (like not separating folders with a semicolon). Check your current CLASSPATH with this DOS command: echo %CLASSPATH%
For Linux Go to Sun’s “Java Products & API’s” web page4 and click on the link for “Java 2 SDK, Standard Edition.” Download the Java 2 SDK tar file (j2sdk-1_3_0-linuxrpm.bin) to a temporary directory. Be sure to select the Linux (for Intel x86) version. In these instructions we will be using the RPM file but you can just as easily download the GNUZIP Tar shell script (but many of these instructions will not apply). Change to the temporary directory you saved this file in. Change the permissions of the file so it is now executable (chmod +x j2sdk-1_3_0-linux-rpm.bin) and then execute it (./j2sdk-1_3_0-linux-rpm.bin). This will unpack and verify the RPM file. You will have the file j2sdk-1_3_0-linux.rpm placed in the current directory. If you download and install a newer version then some of the filenames and path names will change to reflect the version number. You will need to be root to complete the installation. Install the RPM file (rpm -iv This will install Java in /usr/java subdirectory.
j2sdk-1_3_0-linux.rpm).
On Linux you will need to edit your shell startup file and add the directory of the Java binaries to your PATH environment variable. Using vi (or some other ASCII editor), edit your $HOME/.cshrc (for C shell, or $HOME/.profile for ksh, sh or bash). You should already have a PATH environment variable set so you will need to add the location of the Java binaries to it. After the PATH environment variable, insert a new line that will append the /opt/jdk/bin/ directory to the existing path. For C shell: set path = ($path /usr/java/jdk1.3/bin)
For ksh, sh and bash shells: PATH=$PATH:/usr/java/jdk1.3/bin
Save the file and exit the editor. This PATH environment variable tells the operating system where to find the Java programs when you need them. At this point, you don’t need to have the CLASSPATH variable set. We will do that in a following section. To test out your installation of the Java SDK, you will need to logout and log in again to load your new startup file. Do that and then create a simple test program to verify that all is well so far. We will use the “HelloWorld” program from listing 3-1. 4
Java Products & API’s web page, http://java.sun.com/products/
28
Java Essentials for Embedded Networked Devices Create a subdirectory and create a test Java program: % vi HelloWorld.java
Enter the Java program above into the text editor. Save the file and exit the editor. Then compile and run the program: % javac HelloWorld.java % java HelloWorld
If there were no errors from either of the last two commands, then you are all set to move on to installing the serial port API for Java. If there were error messages, then read the installation instructions above and on the Sun web pages and try to figure out what went wrong and fix it. Most likely you overlooked a step or mistyped something. Some common mistakes are: Not properly editing the PATH environment variable, or not rebooting the computer after editing the PATH. If you saw any errors when compiling or running the program then you should carefully check the program you entered to see that you typed it correctly. Also check to see that you installed the Java Software Development Kit properly. While these instructions are for J2SE version 1.3, by the time you read this book Sun may have released a newer version. It is likely that the installation procedures will be slightly different. These are some common errors and their solutions: % javac HelloWorld.java javac: Command not found
• /usr/java/jdk1.3/bin is not in your PATH environment variable. Or you added it but you didn’t restart your computer. Check your current PATH with this command: echo $PATH % java HelloWorld Exception in thread “main” java.lang.NoClassDefFoundError: HelloWorld
• Didn’t compile HelloWorld.java (javac HelloWorld.java) • HelloWorld.java had errors so the compiler didn’t write the class file. • You have a CLASSPATH environment variable set and “.” (the current folder) is not in the CLASSPATH or there are errors in your CLASSPATH (like not separating the directories with a colon). Check your current CLASSPATH with this command: echo $CLASSPATH Now that we have the Java compiler and runtime environment going, it may interest you to know about the various options you can use when compiling programs with javac and running programs with Java. Typing javac –help or java –help will display the command options you can use.
29
Designing Embedded Internet Devices % javac -help Usage: javac
null
62
Java Essentials for Embedded Networked Devices The program we just described represents about the simplest client we could construct. In creating a socket connection to port 80 on a remote machine, it asks to be connected to the service provided at port 80. That service is an HTTP web server. Next we will construct the corresponding server.
Reading and writing to a socket (a simple server) The program below represents a very simple server. It listens on port 80 for clients requesting connections. When it detects a client connection request, it creates a socket to communicate with the client, creates a BufferedWriter, and then writes a simple web page to that socket. It doesn’t actually read anything from the client. Listing 3-16: HttpSocketServer.java import java.util.*; import java.io.*; import java.net.*; public class HttpSocketServer { public static void main(String[] args) { int port = 80; try { ServerSocket srv = new ServerSocket(port); Date currentDate; String currentTime; while (true) { currentDate = new Date(); currentTime = currentDate.toString(); Socket mySocket = srv.accept(); System.out.println(“Connection Accepted @” + currentTime); BufferedWriter serverResponse = new BufferedWriter( new OutputStreamWriter(mySocket.getOutputStream())); writePage(serverResponse, currentTime); mySocket.close(); } } catch (IOException e) { e.printStackTrace(); System.out.println(“There is an IOException in HttpSocketServer”); } } public static void writePage(BufferedWriter wr, String ct) { try { wr.write(“HTTP/1.0 200 OK\n”); wr.write(“Content-type: text/html\n\n”); wr.write(“
\n”);
63
Designing Embedded Internet Devices wr.write(“
Hello Web Client!
\n”); wr.write(“
Hello Web Client!
\n”); wr.write(“\n”); wr.write(“
\n”); wr.write(“The current time is “ + ct); wr.write(“