Page 65 - The Definitive Guide to Building Java Robots
P. 65

Preston_5564C02.fm  Page 46  Wednesday, September 14, 2005  5:42 AM



                 46     CHAPTER 2  ■  SERIAL COMMUNICATION



                        Example 2-13. SimpleStamp.java
                        package com.scottpreston.javarobot.chapter2;

                        public class SimpleStamp extends Controller {

                            public static final int COMMAND_A = 'd';
                            public static final int COMMAND_B = 'e';
                            public static final int COMMAND_TERM = '!';

                            public SimpleStamp(int id) throws Exception {
                                super(SingleSerialPort.getInstance(id));
                            }

                            public String cmdA() throws Exception {
                                byte[] a = new byte[] { (byte) COMMAND_A, (byte) COMMAND_TERM };
                                return execute(a, 150);
                            }

                            public String cmdB() throws Exception {
                                byte[] b = new byte[] { (byte) COMMAND_B, (byte) COMMAND_TERM };
                                return execute(b, 150);

                            }

                            public static void main(String[] args) throws Exception {
                                SimpleStamp t = new SimpleStamp(1);
                                System.out.println(t.cmdA());
                                System.out.println(t.cmdB());
                                t.close();
                            }
                        }


                        Section Summary
                        In this section, we created a controller interface called JController that will specify behavior
                        between all controllers we will use in this book. We also created an abstract class that carries
                        with it two implementation methods for executing communication. With the two just imple-
                        menting different read methods, execute() will return a string, and execute2() will return a byte[].
                            Once the generic controller is created we can extend this class for our specific BASIC
                        Stamp program implementations, while just focusing on the bytes they need to send and the
                        method names we want to create that will correspond to commands in the Stamp program.
   60   61   62   63   64   65   66   67   68   69   70