Exercise 7 Solution: Network code

BendySender:

  1 /*
  2 * Copyright (c) 2007 Sun Microsystems, Inc.
  3 *
  4 * Permission is hereby granted, free of charge, to any person
  5 * obtaining a copy of this software and associated documentation
  6 * files (the "Software"), to deal in the Software without
  7 * restriction, including without limitation the rights to use, copy,
  8 * modify, merge, publish, distribute, sublicense, and/or sell copies
  9 * of the Software, and to permit persons to whom the Software is
 10 * furnished to do so, subject to the following conditions:
 11 *
 12 * The above copyright notice and this permission notice shall be
 13 * included in all copies or substantial portions of the Software.
 14 *
 15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 19 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 20 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 21 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 22 * SOFTWARE.
 23 */
 24 
 25 
 26 package org.sunspotworld;
 27 
 28 import com.sun.spot.io.j2me.radiostream.RadiostreamConnection;
 29 import com.sun.spot.peripheral.NoRouteException;
 30 import com.sun.spot.peripheral.Spot;
 31 import com.sun.spot.util.IEEEAddress;
 32 import com.sun.squawk.VM;
 33 import java.io.DataInputStream;
 34 import java.io.DataOutputStream;
 35 import java.io.IOException;
 36 import javax.microedition.io.Connector;
 37 
 38 /**
 39  * Main Sensor networking code for sending sensor values to the remote SPOT
 40  */
 41 public class BendySender {
 42 
 43     private String myAddress;
 44     private String otherAddress;
 45     private long ourAddr;
 46     private final int PORT = 33;
 47     private static final int XMIT_POWER = -31; // keep it low to prevent interference
 48     private String otherSPOTAddress;
 49     private boolean connected;
 50     private RadiostreamConnection conn = null;
 51     private DataInputStream dis = null;
 52     private DataOutputStream dos = null;
 53     private Bendy sensor;
 54 
 55   /**
 56    * Create a new Sender Object and initialize the radio
 57    */
 58     public BendySender() {
 59         init();
 60     }
 61 
 62   /**
 63    * Initialize the radio stack for connecting to the remote Sun SPOT
 64    */
 65     public void init() {
 66         ourAddr = Spot.getInstance().getRadioPolicyManager().getIEEEAddress(); // we need our own address
 67         Spot.getInstance().getRadioPolicyManager().setOutputPower(XMIT_POWER);
 68         System.out.println("Our radio address = " + IEEEAddress.toDottedHex(ourAddr));
 69         myAddress = IEEEAddress.toDottedHex(ourAddr);
 70         otherSPOTAddress = VM.getManifestProperty("ServoSPOT");
 71         System.out.println("Other radio address = " + otherSPOTAddress);
 72         try {
 73             conn = (RadiostreamConnection) Connector.open("radiostream://" + getOtherAddress() + ":" + PORT);
 74             dis = (DataInputStream) conn.openDataInputStream();
 75             dos = (DataOutputStream) conn.openDataOutputStream();
 76         } catch (IOException e) {
 77             e.printStackTrace();
 78         }
 79     }
 80 
 81 
 82 
 83   /**
 84    * Connect to the remote SPOT and send configuration data. 
 85    * This method can be called at any time to re-send the 
 86    * configuration data.
 87    * 
 88    * This method will block on a read from the remote SPOT until the remote
 89    * SPOT replies with the 'GO' command indicating that the configuration
 90    * data has been received.
 91    * @return True if connection succeeded,  false otherwise
 92    */
 93     public boolean connect() {
 94         System.out.println("Starting connection to " + getOtherAddress() + " on port " + PORT);
 95         connected = false;
 96         while (!connected) {
 97 
 98             try {
 99                 System.out.println("Sending min:" + sensor.getBendMin() + ";center:" + sensor.getBendCenter() + ";max:"
» + sensor.getBendMax());
100                 dos.writeUTF("min:" + sensor.getBendMin() + ";center:" + sensor.getBendCenter() + ";max:" +
» sensor.getBendMax());
101                 dos.flush();
102                 String response = dis.readUTF();
103                 if (response.equalsIgnoreCase("GO")) {
104                     System.out.println("Calibration complete!");
105                     connected = true;
106                 }
107             } catch (IOException ex) {
108                 ex.printStackTrace();
109             }
110 
111         }
112         return connected;
113     }
114 
115   /**
116    * Close the connection to the remote Sun SPOT
117    */
118     public void closeConnection() {
119         if (connected == false) {
120             return;
121         }
122         connected = false;
123         try {
124             dos.close();
125             dis.close();
126             conn.close();
127         } catch (IOException e) {
128             e.printStackTrace();
129         }
130     }
131 
132   /**
133    * Send sensor or configuration data to the remote Sun SPOT.
134    * @param message The sensor or configuration data to send to the remote Sun SPOT
135    * @throws com.sun.spot.peripheral.NoRouteException Thrown if no route is found for the remote SPOT
136    * @throws java.io.IOException Thrown if the send to the remote SPOT Failed
137    */
138     public void send(String message) throws IOException, NoRouteException {
139         dos.writeUTF(message);
140         dos.flush();
141     }
142 
143     public String getAddress() {
144         return myAddress;
145     }
146 
147     public String getOtherAddress() {
148         return otherAddress;
149     }
150 
151 }

Servo Receiver:

          1 /*
  2 * Copyright (c) 2007 Sun Microsystems, Inc.
  3 *
  4 * Permission is hereby granted, free of charge, to any person
  5 * obtaining a copy of this software and associated documentation
  6 * files (the "Software"), to deal in the Software without
  7 * restriction, including without limitation the rights to use, copy,
  8 * modify, merge, publish, distribute, sublicense, and/or sell copies
  9 * of the Software, and to permit persons to whom the Software is
 10 * furnished to do so, subject to the following conditions:
 11 *
 12 * The above copyright notice and this permission notice shall be
 13 * included in all copies or substantial portions of the Software.
 14 *
 15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 19 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 20 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 21 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 22 * SOFTWARE.
 23 */
 24 
 25 package org.sunspotworld;
 26 
 27 import com.sun.spot.io.j2me.radiostream.RadiostreamConnection;
 28 import com.sun.spot.peripheral.NoRouteException;
 29 import com.sun.spot.peripheral.Spot;
 30 import com.sun.spot.peripheral.TimeoutException;
 31 import com.sun.spot.util.IEEEAddress;
 32 import com.sun.spot.util.Utils;
 33 import com.sun.squawk.VM;
 34 import java.io.DataInputStream;
 35 import java.io.DataOutputStream;
 36 import java.io.IOException;
 37 import javax.microedition.io.Connector;
 38 
 39 
 40 /**
 41  * Main Radio code for connecting to the Remote Sending Sun SPOT and for reading sensor values from it.
 42  * The addresses for this SPOT and the remote (sending) SPOT should be defined in the Manifest file
 43  * as 'BendySPOT'(remote SPOT) and 'ServoSPOT' (this SPOT)
 44  */
 45 public class ServoReceiver implements Runnable {
 46 
 47     private String myAddress;
 48     private String otherAddress;
 49     private final int PORT = 33;
 50   /**
 51    * Radio power. Set to near minimum to reduce interference
 52    */
 53     private static int XMIT_POWER = -31;
 54   /**
 55    * Set when connected to the remote sending SPOT
 56    */
 57     private boolean connected;
 58     private RadiostreamConnection conn = null;
 59     private DataInputStream dis = null;
 60     private DataOutputStream dos = null;
 61     private int max = 0;
 62     private int min = 0;
 63     private int center = 0;
 64     private ServoMover owner;
 65 
 66     
 67     
 68   /**
 69    * Set up a new ServoReceiver
 70    * @param owner The class contining the servo to be controlled
 71    */
 72     public ServoReceiver(ServoMover owner) {
 73         setOwner(owner);
 74         init();
 75 
 76     }
 77 
 78     
 79 
 80   /**
 81    * Initialize the radio connection
 82    */
 83     public void init() {
 84         long ourAddr = Spot.getInstance().getRadioPolicyManager().getIEEEAddress();
 85         Spot.getInstance().getRadioPolicyManager().setOutputPower(XMIT_POWER);
 86         System.out.println("Our radio address = " + IEEEAddress.toDottedHex(ourAddr));
 87         otherAddress = VM.getManifestProperty("BendySPOT");
 88         System.out.println("Other radio address = " + otherAddress);
 89         System.out.println("Starting connection to " + getOtherAddress() + " on port " + PORT);
 90         try {
 91             conn = (RadiostreamConnection) Connector.open("radiostream://" + getOtherAddress() + ":" + PORT);     
 92             dis = (DataInputStream) conn.openDataInputStream();
 93             dos = (DataOutputStream) conn.openDataOutputStream();
 94         } catch (IOException e) {
 95             e.printStackTrace();
 96         }
 97     }
 98 
 99   /**
100    * Connect to the remote Sun SPOT
101    * @return True if connection was successful, false otherwise.
102    */
103     public boolean connect() {
104         connected = false;
105         String tmp = null;
106 
107         while (!connected) {
108             try {
109                 tmp = dis.readUTF();
110                 System.out.println("Received: " + tmp);
111             } catch (TimeoutException e) {
112                 System.out.println("Timeout... other end is not responding");
113             } catch (IOException e1) {
114                 System.out.println("Exception on readUTF");
115             }
116 
117             if (tmp != null) {
118                 if (tmp.startsWith("min")) {
119                     parseConfig(tmp);
120                     try {
121                         send("GO");
122                         connected = true;
123                     } catch (IOException ex) {
124                         ex.printStackTrace();
125                     }
126                 }
127             }
128         }
129         return connected;
130     }
131     
132   /**
133    * continually read values from the network connection and send them to the Servo
134    */
135     public void run() {
136         
137         while (true) {
138             try {
139                 owner.moveServo(readValue());
140             } catch (IOException ex) {
141                 ex.printStackTrace();
142             }
143         }
144     }
145     
146   /**
147    * Read the value of the remote sensor from the network connection
148    * @return Return the value read from the remote sensor
149    * @throws java.io.IOException Reading failed
150    */
151     private int readValue() throws IOException {
152         String val = dis.readUTF();
153         if (val.startsWith("min")) {
154             parseConfig(val);
155             try {
156                 send("GO");
157             } catch (IOException ex) {
158                 ex.printStackTrace();
159             }
160             return this.getCenter();
161         } else {
162             return Integer.parseInt(val);
163         }
164     }
165 
166   /**
167    * parse the variuous parse of a configuration message into min, center and max values and set them.
168    * @param config The String containing the config message
169    */
170     private void parseConfig(String config) {
171         String[] vals = Utils.split(config, ';');
172         this.min = Integer.parseInt(Utils.split(vals[0], ':')[1]);
173         this.center = Integer.parseInt(Utils.split(vals[1], ':')[1]);
174         this.max = Integer.parseInt(Utils.split(vals[2], ':')[1]);
175         System.out.println("Received Configuration data ... Min: " + this.min + " Center: " + this.center + " Max: " +
» this.max);
176     }
177     
178     
179 
180   /**
181    * Close the radio connection to the remote Sun SPOT
182    */
183     public void closeConnection() {
184         if (connected == false) {
185             return;
186         }
187         connected = false;
188         try {
189             dos.close();
190             dis.close();
191             conn.close();
192         } catch (IOException e) {
193             e.printStackTrace();
194         }
195     }
196 
197   /**
198    * Send a message to the other Sun SPOT
199    * @param message The message to send to the other Sun SPOT
200    * @throws com.sun.spot.peripheral.NoRouteException Sending of the message failed because the other SPOT could not be
» found
201    * @throws java.io.IOException Writing of the message failed
202    */
203     public void send(String message) throws IOException, NoRouteException {
204         dos.writeUTF(message);
205         dos.flush();
206     }
207 
208    
209   /**
210    * Return the address of this Sun SPOT as a String
211    * @return IEEE Address of this Sun SPOT as a String
212    */
213     public String getMyAddress() {
214         return myAddress;
215     }
216 
217   /**
218    * Setter for my address
219    * @param myAddress IEEE Address of this Sun SPOT
220    */
221     public void setMyAddress(String myAddress) {
222         this.myAddress = myAddress;
223     }
224 
225   /**
226    * Return the address of the sending Sun SPOT
227    * @return Sending Address as a String
228    */
229     public String getOtherAddress() {
230         return otherAddress;
231     }
232 
233   /**
234    * The address of the Bend Sensor Sun SPOT
235    * @param otherAddress The address of the sending Sun SPOT
236    */
237     public void setOtherAddress(String otherAddress) {
238         this.otherAddress = otherAddress;
239     }
240 
241   /**
242    * Return the maximum value that the Bend Sensor will send
243    * @return Max value that the Bend Sensor will send
244    */
245     public int getMax() {
246         return max;
247     }
248 
249   /**
250    * the minimum value that the bend sensor will send
251    * @return Minimum bend sensor value
252    */
253     public int getMin() {
254         return min;
255     }
256 
257   /**
258    * get the center point of the bend sensor as sent by the bend sensor
259    * @return Center point of the bend sensor
260    */
261     public int getCenter() {
262         return center;
263     } 
264 
265   /**
266    * Set the controlling servo class
267    * @param owner The class which controls the servo itself.
268    */
269     public void setOwner(ServoMover owner) {
270         this.owner = owner;
271     }
272 }

        

Go on to summary