- The Communications API
- Uploading Map Data
- Controlling the RCX Through a Network
- Controlling the RCX from a Web Page
- RCX Bean
- Alternate Data Transfer Methods
- Alternate Communication Uses
Controlling the RCX Through a Network
Data communications is great for sending sensor readings back to the PC for analysis, but it can also be used for direct control of the RCX brick. In this project we take it one step further by controlling the RCX from another PC across a networkincluding the Internet (Figure 117). This type of control, where the controller is not present in the same space as the robot, is known as telerobotics. The NASA Mars mission controlled Sojourner using telero-botics, as the robot could not be controlled in real time due to the time it takes for radio signals to travel from Earth to Mars. Instead, Sojourner was given a series of instructions to complete on its own, depending on what the NASA controllers chose to do from the pictures they received. It was left up to the internal code of the robot to navigate around obstacles it encountered along the way to its destination.
Figure 117 Architecture for robot control over the Internet.
In this project we have a problem similar to the problem encountered by NASA. We don't have a time delay factor, as a robot could be controlled over a network almost real time, even across the Internet. The problem is that when our rover turns away from the IR tower we lose contact. The best we can do is give the robot a series of instructions, then wait for it to return to the IR tower and report back with some results.
The robot in this project can be any of the Navigator robots we programmed in Chapters 7, 8, and 10. This project is specifically programmed for the rotation sensor robot used in Chapter 8, which has been modified slightly to include a light sensor (Figure 118). The robot is given an array of coordinates to move to. Once it reaches the final coordinate it captures a light reading and then uses the coordinates in reverse to make its way back to the IR tower. Once there, it transmits the light reading to the PC. The code for the RCX side is simple, and uses the same concepts introduced in the explanation of leJOS RCX communications.
Figure 11-8 Tippy Senior modified with a light sensor.
The architecture for this project is a little more complex than the other projects in this book. It requires code to run on three separate platformsa client computer, a server, and the RCX brick (Figure 117). There are also two separate media used for data transferthe Internet and IR light. The client application sends user commands from the client to the server. The server acts as a sort of middle man, shuffling commands from the user to the RCX and vice versa. The robot just sits in front of the IR tower waiting for a destination. When it has some coordinates it takes off and records a light reading at the farthest point. Let's examine this code first:
1. import josx.platform.rcx.*; 2. import josx.robotics.*; 3. import josx.platform.rcx.comm.*; 4. import java.io.*; 5. 6. public class RCXExplorer { 7. DataInputStream in; 8. DataOutputStream out; 9. Navigator robot; 10. final byte ARRAY_SIZE = 4; 11. short [] xCoords; 12. short [] yCoords; 13. 14. public RCXExplorer() { 15. // TimingNavigator Constructor for Tippy Senior: 16. robot = new TimingNavigator(Motor.C, Motor.A, 4.475f, 1.61f); 17. RCXDataPort dp = new RCXDataPort(); 18. in = new DataInputStream(dp.getInputStream()); 19. out = new DataOutputStream(dp.getOutputStream()); 20. xCoords = new short [ARRAY_SIZE]; 21. yCoords = new short [ARRAY_SIZE]; 22. } 23. 24. public static void main(String [] args) { 25. RCXExplorer re = new RCXExplorer(); 26. while(true) { 27. re.readCoordinates(); 28. short lightValue = re.fetchValue(); 29. re.returnValue(lightValue); 30. } 31. } 32. 33. /** Reads coordinates from PC into arrays.*/ 34. public void readCoordinates() { 35. try { 36. for(int i=0;i<ARRAY_SIZE;++i) { 37. xCoords[i] = in.readShort(); 38. yCoords[i] = in.readShort(); 39. } 40. } catch(IOException e) {} 41. } 42. 43. /** Sends bot to destination to sample light value.*/ 44. public short fetchValue() { 45. Sensor.S2.activate(); 46. for(int i=0;i<ARRAY_SIZE;++i) 47. robot.gotoPoint(xCoords[i],yCoords[i]); 48. short light = (short)Sensor.S2.readRawValue(); 49. Sensor.S2.passivate(); 50. return light; 51. } 52. 53. /** Sends bot back to starting point and sends value to PC.*/ 54. public void returnValue(short val) { 55. for(int i=ARRAY_SIZE-1;i>-1;--i) 56. robot.gotoPoint(xCoords[i],yCoords[i]); 57. robot.gotoPoint(0,0); 58. robot.gotoAngle(0); 59. try { 60. out.writeShort(val); 61. out.flush(); 62. } catch(IOException ioe) {} 63. } 64. }
The next part of our project is the server code. It is responsible for accepting an array of coordinates from a client on another PC and passing those to the RCX. It is also responsible for waiting for the RCX and sending the light reading back to the client computer. Let's examine this code:
1. import java.net.*; 2. import java.io.*; 3. import pc.irtower.comm 4. 5. public class ExplorerServer { 6. 7. ServerSocket server; 8. Socket client; 9. DataOutputStream clientOutStream; 10. DataInputStream clientInStream; 11. PCDataPort port; 12. DataInputStream inRCX; 13. DataOutputStream outRCX; 14. 15. public ExplorerServer(int portNumber) { 16. try { 17. // Internet connection: 18. server = new ServerSocket(portNumber); 19. 20. // RCX Connection: 21. port = new PCDataPort("COM2"); 22. inRCX = new DataInputStream(port.getInputStream()); 23. outRCX = new DataOutputStream(port.getOutputStream()); 24. } 25. catch (IOException io){ 26. io.printStackTrace(); 27. System.exit(0); 28. } 29. } 30. 31. public static void main(String [] args) { 32. ExplorerServer host = new ExplorerServer(ExplorerCommand.PORT); 33. while(true) { 34. host.waitForConnection(); 35. while(host.client!=null) 36. host.waitForCommands(); 37. } 38. } 39. 40. /** Wait for a connection from the Client machine */ 41. public void waitForConnection() { 42. try { 43. System.out.println("Listening for client."); 44. client = server.accept(); 45. clientOutStream = new DataOutputStream(client.getOutputStream()); 46. clientInStream = new DataInputStream(client.getInputStream()); 47. System.out.println("Client connected."); 48. } catch(IOException io) { 49. io.printStackTrace(); 50. } 51. } 52. 53. /** Wait for coordinates from the Client machine */ 54. public void waitForCommands() { 55. int [] x = new int[ExplorerCommand.ARRAY_SIZE]; 56. int [] y = new int[ExplorerCommand.ARRAY_SIZE]; 57. try { 58. for(int i=0;i<ExplorerCommand.ARRAY_SIZE;++i) { 59. x[i] = clientInStream.readInt(); 60. y[i] = clientInStream.readInt(); 61. } 62. } catch(IOException io) { 63. System.out.println("Client disconnected."); 64. System.exit(0); 65. } 66. sendCommandsToRCX(x, y); 67. waitForRCX(); 68. } 69. 70. /** Send coordinates to the RCX */ 71. public void sendCommandsToRCX(int [] x, int [] y) { 72. System.out.println("Sending data to rcx: "); 73. for(int i=0;i<ExplorerCommand.ARRAY_SIZE;++i) { 74. System.out.println(x[i] + " " + y[i]); 75. try { 76. outRCX.writeShort(x[i]); 77. outRCX.writeShort(y[i]); 78. outRCX.flush(); 79. } catch (Exception e) { 80. e.printStackTrace(); 81. break; 82. } 83. } 84. } 85. 86. /** Wait for light reading from the RCX */ 87. public void waitForRCX() { 88. System.out.println("Waiting for RCX reply."); 89. 90. try { 91. short value = inRCX.readShort(); 92. System.out.println("Got value " + value + ".Sending to user."); 93. clientOutStream.writeInt(value); 94. } catch(IOException io) { 95. io.printStackTrace(); 96. } 97. } 98. }
NOTE
In Line 21 the string must be the port your RCX tower is attached to (e.g., COM1 or USB).
The final part of the project is the client GUI, which resides somewhere across a network. This GUI includes an area to type in a series of coordinates, and also a series of shortcut buttons to send the robot to predesignated areas (Figure 119). Ideally this GUI would also include a map of the area with measurements, or even a live feed of the floor space from a Web cam. For the purposes of keeping this short, however, we omit these features and leave it up to the programmer to implement. Let's examine this program, which is called the Explorer Command Console:
1 import java.awt.*; 2. import java.awt.event.*; 3. import java.io.*; 4. import java.net.Socket; 5. 6. public class ExplorerCommand extends Panel { 7. public static final int PORT = 5067; 8. public static final int ARRAY_SIZE = 4; 9. 10. Button btnConnect; 11. Button btnGo; 12. Button btnKitchen; 13. Button btnLivingRoom; 14. Button btnBedRoom; 15. TextField txtX; 16. TextField txtY; 17. TextField txtIPAddress; 18. TextArea messages; 19. 20. private Socket socket; 21. private DataOutputStream outStream; 22. private DataInputStream inStream; 23. 24. public ExplorerCommand(String ip) { 25. super(new BorderLayout()); 26. 27. ControlListener cl = new ControlListener(); 28. 29. btnConnect = new Button("Connect"); 30. btnConnect.addActionListener(cl); 31. btnGo = new Button("Go!"); 32. btnGo.addActionListener(cl); 33. btnKitchen = new Button("Kitchen"); 34. btnKitchen.addActionListener(cl); 35. btnLivingRoom = new Button("Living Room"); 36. btnLivingRoom.addActionListener(cl); 37. btnBedRoom = new Button("Bed Room"); 38. btnBedRoom.addActionListener(cl); 39. 40. txtX = new TextField("",20); 41. txtY = new TextField("",20); 42. txtIPAddress = new TextField(ip,16); 43. 44. messages = new TextArea("status: DISCONNECTED"); 45. 46. Panel north = new Panel(new FlowLayout(FlowLayout.LEFT)); 47. north.add(btnConnect); 48. north.add(txtIPAddress); 49. 50. Panel south = new Panel(new FlowLayout()); 51. south.add(btnKitchen); 52. south.add(btnLivingRoom); 53. south.add(btnBedRoom); 54. 55. Panel center = new Panel(new GridLayout(4,1)); 56. center.add(new Label("Enter coordinates separated by commas (e.g. 40,70,10,35)")); 57. 58. Panel center1 = new Panel(new FlowLayout(FlowLayout.LEFT)); 59. center1.add(new Label("X:")); 60. center1.add(txtX); 61. 62. Panel center2 = new Panel(new FlowLayout(FlowLayout.LEFT)); 63. center2.add(new Label("Y:")); 64. center2.add(txtY); 65. 66. Panel center3 = new Panel(new FlowLayout(FlowLayout.LEFT)); 67. center3.add(btnGo); 68. center3.add(messages); 69. 70. center.add(center1); 71. center.add(center2); 72. center.add(center3); 73. 74. this.add(north, "North"); 75. this.add(south, "South"); 76. this.add(center, "Center"); 77. } 78. 79. public static void main(String args[]) { 80. System.out.println("Starting Explorer Command..."); 81. Frame mainFrame = new Frame("Explorer Command Console"); 82. mainFrame.addWindowListener(new WindowAdapter() { 83. public void windowClosing(WindowEvent e) { 84. System.exit(0); 85. } 86. }); 87. mainFrame.setSize(400, 300); 88. mainFrame.add(new ExplorerCommand("127.0.0.1")); 89. mainFrame.setVisible(true); 90. } 91. 92. /** Sends coordinates to the server, then waits for 93. * the server to return a light value. */ 94. private int fetchLightReading(short [] x, short [] y){ 95. // Send coordinates to Server: 96. messages.setText("status: SENDING Coordinates."); 97. try { 98. for(int i=0;i<ARRAY_SIZE;++i){ 99. outStream.writeInt(x[i]); 100. outStream.writeInt(y[i]); 101. } 102. } catch(IOException io) { 103. messages.setText("status: ERROR Problems occurred sending data."); 104. return 0; 105. } 106. 107. // Wait for server to return light reading: 108. int light = 0; 109. try { 110. messages.setText("status: WAITING for rover to return."); 111. light = inStream.readInt(); 112. } catch(IOException io) { 113. messages.setText("status: ERROR Data transfer of light reading failed."); 114. } 115. messages.setText("status: COMPLETE The light reading was " + light); 116. return light; 117. } 118. 119. /** A listener class for all the buttons of the GUI. */ 120. private class ControlListener implements ActionListener{ 121. public void actionPerformed(ActionEvent e) { 122. String command = e.getActionCommand(); 123. int light = 0; 124. if (command.equals("Connect")) { 125. try { 126. socket = new Socket(txtIPAddress.getText(), PORT); 127. outStream = new DataOutputStream(socket.getOutputStream()); 128. inStream = new DataInputStream(socket.getInputStream()); 129. messages.setText("status: CONNECTED"); 130. btnConnect.setLabel("Disconnect"); 131. } catch (Exception exc) { 132. messages.setText("status: FAILURE Error establishing connection with server."); 133. System.out.println("Error: " + exc); 134. } 135. } 136. else if (command.equals("Disconnect")) { 137. try { 138. outStream.close(); 139. inStream.close(); 140. socket.close(); 141. btnConnect.setLabel("Connect"); 142. messages.setText("status: DISCONNECTED"); 143. } catch (Exception exc) { 144. messages.setText("status: FAILURE Error closing connection with server."); 145. System.out.println("Error: " + exc); 146. } 147. } 148. else if (command.equals("Go!")) { 149. short [] x = parseArray(txtX.getText()); 150. short [] y = parseArray(txtY.getText()); 151. fetchLightReading(x,y); 152. } 153. else if (command.equals("Kitchen")) { 154. short [] x = {-100,-100,-300,-310}; 155. short [] y = {0,100,100,100}; 156. fetchLightReading(x,y); 157. } 158. else if (command.equals("Bed Room")) { 159. short [] x = {0,200,200,250}; 160. short [] y = {-100,-100,-200,-250}; 161. fetchLightReading(x,y); 162. } 163. else if (command.equals("Living Room")) { 164. short [] x = {-50,-50,-150,-150}; 165. short [] y = {0,-300,-300,-310}; 166. fetchLightReading(x,y); 167. } 168. } 169. 170. /** Takes a string of coordinates and parses out 171. * the short values (using commas) and assembles 172. * them into an array. */ 173. public short [] parseArray(String coords) { 174. int order = 0; 175. short [] ar = new short[ARRAY_SIZE]; 176. for(int i=0;i<coords.length();++i) { 177. int firstComma = coords.indexOf(",",i); 178. 179. String leading; 180. if(firstComma < 0) { 181. leading = coords.substring(i); 182. i = coords.length(); 183. } 184. else { 185. leading = coords.substring(i,firstComma); 186. i = firstComma; 187. } 188. ar[order++] = Short.parseShort(leading); 189. } 190. return ar; 191. } 192. } 193. }
Figure 11-9 The Explorer Command Console
NOTE
In the preceding code, I used several locations in my home for the shortcut buttons, so feel free to customize the locations in Lines 153 to 166 according to your own location.
Now that we have all the code ready, it's time to test it. First, upload the code to the RCX, sit it in front of the IR tower, and press the Run button. The robot waits patiently for a series of coordinates from the PC. Next, run the server code on your PC. It will sit waiting for an Explorer Command Console to connect to it. Finally, run the Command Explorer Console (either on the same machine or on a different machine on the network). Type in the IP address (or leave it as 127.0.0.1 if on the same machine) and click Connect. You can now click one of the shortcut buttons, or alternately enter a series of four coordinates. Once the coordinates have been entered click Go. The robot heads to the location and records a light reading. When the robot returns you are presented with the result. If it fails to return, try using the TimingNavigator.setDelay() method.
NOTE
This project really taxes the RCX memory. It uses several large classes, including TimingNavigator, which also uses the Math class. I wasn't even able to use the Sound or LCD class in this project because they pushed memory usage over the limit. This project works with the current release of leJOS, but if leJOS changes in the future and takes up more space, you might see a dreaded exception, which means out of memory. Chapter 12, "Advanced Topics," gives some explanations on how to free up memory in leJOS if you wish to expand this code.