OSDN Git Service

lejos_NXJ_win32_0_5_0beta.zip
[nxt-jsp/lejos_nxj.git] / nxtOSEK / lejos_nxj / src / java / classes / lejos / nxt / comm / BTInputStream.java
1 package lejos.nxt.comm;
2
3 import java.io.*;
4
5 /**
6  * Extends InputStream for BlueTooth; implements available()
7  * @author   Roger Glassey revised on june 23, 2007, modified for Bluetooth2
8  */
9 public class BTInputStream extends InputStream {
10         private byte buf[] = new byte[256];
11         private int bufIdx = 0, bufSize = 0;
12         private BTConnection conn = null;
13     
14         BTInputStream(BTConnection conn)
15         {
16                 this.conn = conn;
17         }
18     /**
19      * Returns one byte as an integer between 0 and 255.  
20      * Returns -1 if the end of the stream is reached.
21      * Does not return till some bytes are available.
22      */
23         public int read() 
24     {
25            if (bufIdx >= bufSize) bufSize = 0;
26            if (bufSize <= 0)
27            {
28                    bufSize = conn.read(buf, buf.length, true);
29                    if (bufSize <= 0) return -1;
30                    bufIdx = 0;
31            }
32        return buf[bufIdx++] & 0xFF;
33         }
34         
35     /**
36      * returns the number of bytes in the input buffer - can be read without blocking
37      */
38     public int available()
39     {
40        if (bufIdx >= bufSize) bufSize = 0;
41        if (bufSize == 0) {
42            bufIdx = 0;
43            bufSize = conn.read(buf, buf.length, false);
44        }
45        return bufSize - bufIdx;
46     }
47     
48     /**
49      * the stream is restored to its original state - ready to receive more data.
50      */
51     public void close()
52     { 
53        bufIdx = 0;
54        bufSize = 0;
55     }
56 }