Application Note 704 Asynchronous Serial-to-Ethernet Device Servers www.maxim-ic.com OVERVIEW The sheer number of devices that use a serial port as a means for communicating with other electronic equipment is staggering. In fact, for many, a serial port provides the sole mechanism of communicating with the outside world. These devices include thermostats, point-of-sale systems, remote data loggers, barcode readers, receipt printers, RFID transceivers, blood-pressure meters, and many more in fields as diverse as legacy test tools to the latest in building automation. Such devices have no direct means of participating in a larger computer network, yet new applications demand TCP/IP connectivity and Ethernet capabilities. Often, an expensive and time-consuming redesign is not an option.
This article explores an easy and economical way to migrate standalone serial devices to the Ethernet byretrofitting legacy systems that build on top of the Tiny InterNet Interface (TINI®) platform using theDS80C390 or DS80C400 microcontrollers. Once a device connects to the Ethernet, implementing TINIweb services such as an HTTP server is very straightforward. TINI AND NETWORKING TINI is a technology platform developed by Dallas Semiconductor to allow rapid development on the DS80C390 and DS80C400 microcontrollers. Specifically, TINI encompasses a chipset definition and an embedded operating system integrated with a highly optimized Java™ runtime environment. Using Java, programmers benefit from powerful features not commonly found in embedded development: multithreading, garbage collection, inheritance, virtualization, cross-platform capabilities, powerful networking support, and, last but not least, a multitude of free development tools. TINI users are usually shielded from assembly language coding. However, native language subroutines are supported and encouraged to optimize speed-critical paths or low-level hardware access (the TINI operating system is written in native code, resulting in serial I/O throughput not significantly different from modern PCs).
Besides full support of the java.net package, the TINI Java runtime contains the javax.comm subsystem. Since both TCP/IP and the serial ports are effortlessly accessible from Java, the TINI system easily lendsitself to implementing serial-to-Ethernet bridges.
The TINIm390 verification module on an E10 socket used in the examples later in the article is thehardware portion of the DS80C390 TINI development platform (the TINIm400 uses the DS80C400). Inaddition to SRAM, flash memory, Ethernet, CAN-bus, 1-Wire®, etc., the system also has four serial ports;two of the UARTs are internal to the DS80C390 (called serial0 and serial1). Two ports are external(using a 16550 build option). It is important to note that both serial connectors on the E10 socket arewired to serial0 and just differ in DTE/DCE pin assignment.
The TINI environment is documented in The TINI Specification and Developer's Guide (Addison-Wesley, 2001). A free copy can be downloaded
RS-232 Serial Port The asynchronous serial communication discussed in this article is based on the RS-232-C standard that dates back to the earliest days of recorded computer history; RS-232-C was published in 19691. Most modern serial ports do not support all of the signals defined in the standard—and the signals that are implemented are used in a fashion that is merely “fairly close” to that defined in the standard. We’ll ignore the purely historical definitions and concentrate on the way RS-232 is used today. Space and Mark: RS-232-C specifies a voltage level of +3V to +25V as “SPACE” (binary 0) and -3V to -25V as “MARK” (binary 1). The region between -3V and +3V is the “switching region.” Many universal asynchronous receiver transmitters (UARTs) use the relatively modern TTL voltage levels of 0V and +5V for 0 and 1. Special-purpose level translators like the MAX-232 convert between TTL and RS-232 levels. Because serial ports on the DS80C390 and DS80C400 are TTL-level, no level translators are needed for interfacing to another TTL-level UART. DCE and DTE: DCE (data communications equipment) and DTE (data terminal equipment) are the two endpoints of a communications channel. The main difference is the serial connector pinout (a so-called null-modem can be used to convert between the two). Table 1 shows the signals on a DB-9 DTE serial connector and the corresponding signals on another DTE when using a null-modem. Table 1. A null-modem can connect the corresponding signals of two DB-9 DTE serial ports. SIGNAL NAME NULL-MODEM Flow Control: You can communicate serially by sending on one pin (TD) and listening on another (RD). However, when two devices that communicate over RD, TD transmit at will, one might overrun the other, resulting in data loss. There are two ways flow control is commonly implemented:
§ XON/XOFF (often loosely termed software flow control)
§ RTS/CTS (often loosely termed hardware flow control)
The XON/XOFF flow control scheme transmits in-band characters that cause the other side to pause(XOFF, 13h) and resume (XON, 11h) transmission. The XON and XOFF characters must be escaped insoftware by the sender and unwrapped by the receiver if they occur in a binary data stream. RTS/CTSuses extra signaling lines. RTS (request to send) is asserted by the sender. The receiver responds withCTS (clear to send) when it is ready to receive data and clears CTS when its receive buffer is full.
Some devices support flow control, some do not. The defaults are, therefore, usually set to “no flowcontrol,” which should be overridden if a device is known to implement flow control.
1 NASA has trouble deciphering computer tapes from this era, so the comparison is valid. Speed, Data Bits, Stop Bits, and Parity: Other parameters that must be set correctly for successful communications are the transmission speed (bit rate), the number of data and stop bits, and the type of parity checking (if any). Most new devices use a setting of “8N1,” which means 8 data bits, no parity, and 1 stop bit. However, legacy systems are known to use the full range of possibilities, so the correct setting actually might not be trivial. EXAMPLES Some basic networking knowledge and programming experience are required if you plan to modify the examples. Operational sample code can be downloaded from the
We will start with two concrete applications and then present a short excerpt from a generic serial-to-Ethernet program that can be modified to suit almost any particular application. The examples are builtusing the TINIm390/400 verification modules. Figure 1. The TINI Verification Module bridges serial device and Ethernet.
The TINI verification module can be used as “black box” to connect multiple serial devices to theEthernet. Depending on the needs of the end equipment, the TINI can either pass the data straight throughor parse, interpret and modify the data stream.
Note that although you can run the examples from the slush developer’s shell on the TINIm390/400, amore polished application would reside in flash, be self-starting in the event of a power loss, and useother TINI construction techniques to make the finished product virtually indestructible. Virtual Modems The first example, a “Virtual Modem,”2 uses the TINIm390/400 to replace a physical modem and telephone line with TCP/IP connectivity. Assume a legacy device like a factory “machine status monitor” that uses a modem to dial into a central server several times a day to report machine status, load and efficiency data. To eliminate the need for an ever-growing modem bank on the server side and to be able to use an existing LAN instead of phone lines to the equipment, one could
§ rewrite the server software to be TCP/IP based and
§ use TINI virtual modems to replace the original modems at each machine
The machine status monitors, however, do not have to be modified since the virtual modem behaves likea real modem as far as the end equipment is concerned.
Virtual modems can of course also be used in pairs instead of the configuration described above. Whenusing two virtual modems, no server software needs to be changed at all and the TINI modules are a drop-in replacement for existing modems.
Behind the scenes, a virtual modem establishes a TCP connection whenever it receives the “ATD”modem dial command. An “ATH” disconnect command closes the TCP connection. The software alsoimplements a number of other classic AT modem commands and is recognized as a true modem byMicrosoft Windows® networking, for example. In addition, a virtual modem listens on a TCP port itselfand can answer incoming “calls” that are signaled by a “RING” to the end equipment.
The following code fragments show how to initialize a serial port on the TINIm390:
public static void main(String args[]) { TINIOS.setSerialBootMessagesState(false); TINIOS.setDebugMessagesState(false); TINIOS.setConsoleOutputEnabled(false);
System.out.println("Connecting to serial0 at 9600bps, " "listening on TCP port 8001");
try { CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier("serial0"); SerialPort port = (SerialPort) portId.open("VModemTINI", 10000);
TINIOS.setRTSCTSFlowControlEnable(1, false); TINIOS.setRTSCTSFlowControlEnable(0, true);
TCPSerialVirtualModem modem = new TCPSerialVirtualModem(port, /* Comm speed */ 9600, /*TCP Port */ 8001); modem.processInput(); } catch (Exception e) { System.out.println("Exception: "+e.toString()); } }
The code first disables all TINI OS debug output, standard practice on the TINI. After getting a portidentifier, the port is then opened (the second parameter tells open how long to wait if the port is currently
in use by another application). Next, the state of the hardware flow control is set. Since the TINIm390only has one set of RTS/CTS lines for serial ports 0 and 1, a program should always disable flow controlon the other port before enabling it on the desired port. Next, a Java virtual modem is instantiated.
The virtual modem class consists of an AT command interpreter (not shown here, although by far thelargest part of the example) and networking code. The following code sets the serial port bit rate, data andstop bits as well as parity and shows how easy it is to handle inbound connections:
/** Creates a new VirtualModem connected to a serial port on * one end and a TCP port on the data side. * serial -- the serial port this VirtualModem talks to. * speed -- the speed the serial port should be set to. * tcpport -- the TCP port this VirtualModem listens on. * throws IOException when there's a problem with the serial or TCP port. */ public TCPSerialVirtualModem(SerialPort serial, int speed, int tcpport) throws IOException { super(serial);
try { serial.setSerialPortParams(speed, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); } catch (UnsupportedCommOperationException e) { throw new IOException(); }
serverSock = new ServerSocket(tcpport, 1); // backlog of one listenThread = new listenInbound(); listenThread.start(); }
Finally, the following excerpt of the listenThread() accepts an incoming connection request:
while (running) { s = null; // No incoming connection request try { answered = false; s = serverSock.accept();
// Discard incoming connection if already connected if (connected) throw new IOException();
UPS Monitor The second example connects a TINIm390/400 to a serial port of an uninterruptible power supply. The software implements the Network UPS Tools protocol3, allowing a variety of clients on a variety of platforms to monitor the UPS state and health (this project originated from the need to monitor an existing UPS from a new Macintosh computer without any serial ports).
There are two basic kinds of UPS devices: So-called “smart” ones and simple (or “dumb”) ones. A simpleUPS signals its state on several serial pins, it does not actually send any ASCII data. Because there arenot many serial pins, it can only report a very limited set of information, for example:
The javax.comm.notifyOn…() methods can be used in Java to easily implement code that reacts tostatus changes, for example:
. // Listen for DTR changes try { port.addEventListener(this); } catch (TooManyListenersException e) { . } port.notifyOnDSR(true); .
public void serialEvent(SerialPortEvent ev) { try { if (ev.getEventType() == SerialPortEvent.DSR) . } catch . . }
A smart UPS is more interesting, because it implements a serial protocol and can return values like thebattery charge percentage or the temperature. Protocols are vastly different between different vendorsand, often enough, undocumented. The UPSMonitor example on the Dallas ftp site supports an APCSmartUPS, but could be easily modified for other brands.
The following code shows how to receive UDP requests and send out UPS status information over UDP.
// Listen to incoming UDP requests private class listenUDPThread extends Thread { private DatagramSocket sock; private byte[] buffer; private DatagramPacket dp;
public listenUDPThread(DatagramSocket s) { sock = s; buffer = new byte[BUF_SIZE]; dp = new DatagramPacket(buffer, buffer.length); }
public void run() { while (running) { try { sock.receive(dp); byte[] data = parseCommand(buffer, dp.getLength()); sock.send(new DatagramPacket(data, data.length, dp.getAddress(), dp.getPort())); } catch (Exception e) { } } try { sock.close(); } catch (Exception e) { } } }
Because of the powerful networking support built into Java, this example is almost self-explanatory. Thecode in the while() loop waits until it receives a UDP request, parses it and sends out an answer to theoriginator of the request (using getAddress() on the incoming packet). Black-Box Serial-to-Ethernet Reference Design A complete serial-to-Ethernet example is beyond the scope of this article. (A complete example is shown and explained in The TINI Specification and Developer's Guide.) However, the following code fragment shows how to efficiently use multithreading to transfer data between the serial and networking portions of a serial-to-Ethernet bridge. The serial and TCP ports are abstracted as Input/OutputStreams dataIn and dataOut, so this layer of the code does not actually need to know anything about the network at all and
could also bridge data between the CAN and 1-Wire, for example.
public GenericBridge() { . running = true; dcThread = new dataCopy(); dcThread.start(); }
// Thread that copies everything from dataIn to dataOut private class dataCopy extends Thread { public void run() { int r = 0; while (running && r >= 0) { try { synchronized (threadLock) { r = dataIn.read(dataBuffer); if (r > 0) dataOut.write(dataBuffer, 0, r); } } catch (Exception e) { r = -1; . // Handle error } } } } }
CONCLUSION Many legacy devices only support asynchronous serial communications, yet current applications demand Ethernet connectivity and TCP/IP networking. Using the powerful Java runtime and the TINI technology on the DS80C390 and DS80C400 microcontrollers, developing a serial-to-Ethernet converter so easy it can be done in a matter of hours. TINI and 1-Wire are registered trademarks of Dallas Semiconductor. Java is a trademark of Sun Microsystems. Windows is a registered trademark of Microsoft Corp.
PATIENT INFORMATION Please complete all 4 pages and return to front desk upon arrival. Email address: _________________________________________________________ Mr/Mrs/Ms: _______________________________________ Date: ______________ Home Phone: ______________________ Work Phone: ________________________ Home Address: ________________________________________________________ City: __________
Do not use these oils if you have the following health problems: Do not use: Basil, Eucalyptus, Fennel, Hyssop, Sage, Rosemary• High Blood pressureDo not use: Red Thyme, Hyssop, Pine, Rosemary, Sage • HypoglycemicDo not use: Basil, Birch, Camphor, Cassia, Cedarwood, Clary Sage, Clove Bud, Coriander Fennel, Sweet Hyssop, Jasmine, Juniper, Lemon Marjoram, Myrrh, Peppermint, Rose, Rosemary, S