OSDN Git Service

43161b908d3df63b4e7bce3946acceb9267e706a
[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
8  */
9 public class BTInputStream extends InputStream {
10         private byte buf[] = new byte[256];
11         private int bufIdx = 0, bufSize = 0;
12     
13     /**
14      * Returns one byte as an integer between 0 and 255.  
15      * Returns -1 if the end of the stream is reached.
16      * Does not return till some bytes are available.
17      */
18         public int read() 
19     {
20            if (bufIdx >= bufSize) bufSize = 0;
21        while(bufSize == 0) bufSize = available();
22        return buf[bufIdx++] & 0xFF;
23         }
24         
25     /**
26      * returns the number of bytes in the input buffer - can be read without blocking
27      */
28     public int available()
29     {
30        if (bufIdx >= bufSize) bufSize = 0;
31        if (bufSize == 0) {
32            bufIdx = 0;
33            bufSize = Bluetooth.readPacket(buf, 256);
34        }
35        return bufSize - bufIdx;
36     }
37     
38     /**
39      * the stream is restored to its original state - ready to receive more data.
40      */
41     public void close()
42     { 
43        bufIdx = 0;
44        bufSize = 0;
45     }
46 }