Cure Your Waba Woes with a Serial Socket (Continued)
The first thing to note as you look through the source code for spSocket is that I've commented out some of the response command finals (see Listing 1). The proxy indicates a successful execution of a command by placing the same command code in the response packet. So the spSocket class methods simply recognize an error by a response command code that does not match the one sent.
The methods are fairly straightforward; all method prototypes look like their Socket counterparts. I did have to modify the constructor and add a baudrate parameter. I hardcoded the timeout for the serial port to 10 seconds, which seemed more than enough time and worked fine in all my tests. (If you decide to create a setTimeOut() method, you'll have to figure out which timeout is being set—the socket's or the serial port's. I'll leave that for someone else to do.) Each method simply creates a request packet, transmits it to the proxy, gathers the response, and returns it to the application. As you'll see shortly, if your application already uses the Socket class, very little modification is needed for it to run the spSocket class.
The server-side code consists of two classes: pspSocket and pspSocketMain (see Listing 2). The pspSocket class is the server counterpart to spSocket. Methods in pspSocket have a near one-to-one correspondence to methods in spSocket. Each pspSocket unpacks a request packet, calls the proper Socket method, retrieves the result, packages the result into a response, and ships it back to the client.
The pspSocketMain class is the proxy's outer loop. It executes forever, looking for input from the serial port. When pspSocketMain receives a packet header, it reads and decodes the header, reads the payload, and dispatches control to the appropriate pspSocket method. The pspSocketMain class also provides "I'm alive" output by displaying a string that indicates which command is being processed.
Easy Modification
Modifying an application to use spSocket is reasonably simple. I'll use the Web application that is available with the Waba download as an example. This application consists of two classfiles, Web and WebPage. The only file that you have to change is WebPage.java.
First, toward the top of the application where class-wide variables and objects are defined, change the Socket object to an spSocket object. Next, in the load() method, find the location where the Socket object is instantiated. Change the constructor call to:
socket = new
spSocket(host,80,19200);
Back to top
|