OSDN Git Service

lejos_NXJ_win32_0_5_0beta.zip
[nxt-jsp/lejos_nxj.git] / nxtOSEK / lejos_nxj / src / java / pccomms / lejos / pc / comm / NXTCommBluecove.java
1 package lejos.pc.comm;
2
3 import javax.microedition.io.*;
4 import javax.bluetooth.*;
5 import java.io.*;
6 import java.util.Vector;
7 import java.util.Enumeration;
8
9 public class NXTCommBluecove implements NXTComm, DiscoveryListener {
10         private static Vector devices, nxtInfos;
11         private StreamConnection con;
12         private OutputStream os;
13         private InputStream is;
14         private NXTInfo nxtInfo;
15
16         public NXTInfo[] search(String name, int protocol) throws NXTCommException {
17
18                 devices = new Vector();
19                 nxtInfos = new Vector();
20
21                 if ((protocol | NXTCommFactory.BLUETOOTH) == 0)
22                         return new NXTInfo[0];
23
24                 synchronized (this) {
25                         try {
26                                 LocalDevice.getLocalDevice().getDiscoveryAgent().startInquiry(
27                                                 DiscoveryAgent.GIAC, this);
28                                 try {
29                                         wait();
30                                 } catch (InterruptedException e) {
31                                         System.err.println(e.getMessage());
32                                 }
33                         } catch(Throwable t) {
34                                 //System.err.println(e.getMessage());
35                                 throw new NXTCommException("Bluetooth stack not detected",t); 
36                         }
37                 }
38
39                 for (Enumeration enum_d = devices.elements(); enum_d.hasMoreElements();) {
40                         RemoteDevice d = (RemoteDevice) enum_d.nextElement();
41
42                         try {
43                                 nxtInfo = new NXTInfo();
44
45                                 nxtInfo.name = d.getFriendlyName(false);
46                                 if (nxtInfo.name == null || nxtInfo.name.length() == 0)
47                                         nxtInfo.name = "Unknown";
48                                 nxtInfo.btDeviceAddress = d.getBluetoothAddress();
49                                 nxtInfo.protocol = NXTCommFactory.BLUETOOTH;
50
51                                 if (name == null || name.equals(nxtInfo.name))
52                                         nxtInfos.addElement(nxtInfo);
53                                 else
54                                         continue;
55
56                                 System.out.println("Found: " + nxtInfo.name);
57
58                                 // We want additional attributes, ServiceName (0x100),
59                                 // ServiceDescription (0x101) and ProviderName (0x102).
60
61                                 int[] attributes = { 0x100, 0x101, 0x102 };
62
63                                 UUID[] uuids = new UUID[1];
64                                 uuids[0] = new UUID("1101", true); // Serial Port
65                                 synchronized (this) {
66                                         try {
67                                                 LocalDevice.getLocalDevice().getDiscoveryAgent()
68                                                                 .searchServices(attributes, uuids, d, this);
69                                                 try {
70                                                         wait();
71                                                 } catch (InterruptedException e) {
72                                                         System.err.println(e.getMessage());
73                                                 }
74                                         } catch (BluetoothStateException e) {
75                                                 System.err.println(e.getMessage());
76                                         }
77                                 }
78
79                                 try {
80                                         Thread.sleep(100);
81                                 } catch (InterruptedException e) {
82                                         System.err.println(e.getMessage());
83                                 }
84
85                         } catch (IOException e) {
86                                 System.err.println(e.getMessage());
87
88                         }
89
90                 }
91                 NXTInfo[] nxts = new NXTInfo[nxtInfos.size()];
92                 for (int i = 0; i < nxts.length; i++)
93                         nxts[i] = (NXTInfo) nxtInfos.elementAt(i);
94                 return nxts;
95         }
96
97         public boolean open(NXTInfo nxt) throws NXTCommException {
98
99                 // Construct URL if not present
100
101                 if (nxt.btResourceString == null || nxt.btResourceString.length() < 5
102                                 || !(nxt.btResourceString.substring(0, 5).equals("btspp"))) {
103                         nxt.btResourceString = "btspp://"
104                                         + stripColons(nxt.btDeviceAddress)
105                                         + ":1;authenticate=false;encrypt=false";
106                 }
107
108                 try {
109                         con = (StreamConnection) Connector.open(nxt.btResourceString);
110                         os = con.openOutputStream();
111                         is = con.openInputStream();
112                         return true;
113                 } catch (IOException e) {
114                         throw new NXTCommException("Open of " + nxt.name + " failed");
115                 }
116         }
117
118         public void close() throws IOException {
119                 if (os != null)
120                         os.close();
121                 if (is != null)
122                         is.close();
123                 if (con != null)
124                         con.close();
125         }
126
127         /**
128          * Sends a request to the NXT brick.
129          * 
130          * @param message
131          *            Data to send.
132          */
133         public synchronized byte[] sendRequest(byte[] message, int replyLen)
134                         throws IOException {
135
136                 // length of packet (Least and Most significant byte)
137                 // * NOTE: Bluetooth only. 
138                 int LSB = message.length;
139                 int MSB = message.length >>> 8;
140
141                 if (os == null)
142                         return new byte[0];
143
144                 // Send length of packet:
145                 os.write((byte) LSB);
146                 os.write((byte) MSB);
147
148                 os.write(message);
149
150                 if (replyLen == 0)
151                         return new byte[0];
152
153                 byte[] reply = null;
154                 int length = -1;
155
156                 if (is == null)
157                         return new byte[0];
158
159                 do {
160                         length = is.read(); // First byte specifies length of packet.
161                 } while (length < 0);
162
163                 int lengthMSB = is.read(); // Most Significant Byte value
164                 length = (0xFF & length) | ((0xFF & lengthMSB) << 8);
165                 reply = new byte[length];
166                 is.read(reply);
167
168                 return (reply == null) ? new byte[0] : reply;
169         }
170
171         public byte[] read() throws IOException {
172
173                 int lsb = is.read();
174                 if (lsb < 0) return null;
175                 int msb = is.read();
176                 if (msb != 0)
177                         throw new IOException("Packet more than 255 bytes");
178                 byte[] bb = new byte[lsb];
179                 for (int i=0;i<lsb;i++) bb[i] = (byte) is.read();
180
181                 return bb;
182         }
183         
184     public int available() throws IOException {
185         if (is.available() > 2) return is.available() -2;
186         else return 0;
187     }
188
189         public void write(byte[] data) throws IOException {
190                 os.write(data);
191                 os.flush();
192         }
193
194         public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
195                 // System.out.println("Found Device, class: " +
196                 // cod.getMajorDeviceClass() + "/" + cod.getMinorDeviceClass());
197                 if (cod.getMajorDeviceClass() == 2048 && cod.getMinorDeviceClass() == 4)
198                         devices.addElement(btDevice);
199         }
200
201         public synchronized void inquiryCompleted(int discType) {
202                 // if (discType == INQUIRY_COMPLETED) System.out.println("Inquiry
203                 // completed");
204                 // else System.out.println("Inquiry Failed");
205                 notifyAll();
206         }
207
208         public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
209                 // System.out.println(servRecord.length + " service(s) discovered");
210                 // Should only be one service on a NXT
211                 if (servRecord.length != 1)
212                         return;
213                 nxtInfo.btResourceString = servRecord[0].getConnectionURL(
214                                 ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
215                 // System.out.println("Setting url to : " + nxtInfo.btResourceString);
216         }
217
218         public synchronized void serviceSearchCompleted(int transID, int respCode) {
219                 // System.out.println("Service search completed: respCode = " +
220                 // respCode);
221                 notifyAll();
222         }
223
224         public OutputStream getOutputStream() {
225                 return new NXTCommBTOutputStream(this);
226         }
227
228         public InputStream getInputStream() {
229                 return new NXTCommBTInputStream(this);
230         }
231
232         public String stripColons(String s) {
233                 StringBuffer sb = new StringBuffer();
234
235                 for (int i = 0; i < s.length(); i++) {
236                         char c = s.charAt(i);
237
238                         if (c != ':') {
239                                 sb.append(c);
240                         }
241                 }
242
243                 return sb.toString();
244         }
245 }