4 public class FtdiUart {
6 private SWIGTYPE_p_ftdi_context context = example.new_ftdi_context();
8 public OutputStream getOutputStream() { return out; }
9 public InputStream getInputStream() { return in; }
11 public FtdiUart(int vendor, int product, int baud) {
12 example.ftdi_init(context);
13 example.ftdi_usb_open(context, vendor, product);
14 example.ftdi_usb_reset(context);
15 example.ftdi_set_baudrate(context, baud);
16 example.ftdi_set_line_property(context, 8, 0, 0);
20 public synchronized int readPins() {
22 getOutputStream().flush();
23 } catch (IOException e) {
24 throw new RuntimeException(e);
26 byte[] b = new byte[1];
27 example.ftdi_read_pins(context, b);
31 public synchronized void purge() {
32 example.ftdi_usb_purge_buffers(context);
34 public synchronized void uart(int cbus_mask, int cbus_bits) {
35 example.ftdi_set_bitmode(context, (short)((cbus_mask << 4) | cbus_bits), (short)0x20);
37 public synchronized void dbangmode(int dmask) {
38 example.ftdi_set_bitmode(context, (short)dmask, (short)0x01);
41 protected int dbits = 0;
43 protected synchronized void dbang(int bit, boolean val) {
44 dbits = val ? (dbits | (1 << bit)) : (dbits & (~(1 << bit)));
46 out.write((byte)dbits);
47 } catch (IOException e) { throw new RuntimeException(e); }
51 private final InputStream in = new InputStream() {
52 public int available() throws IOException {
56 public int read() throws IOException {
57 byte[] b = new byte[1];
59 while(result==0) result = read(b, 0, 1);
62 public int read(byte[] b, int off, int len) throws IOException {
63 // FIXME: blocking reads?
67 byte[] b0 = new byte[len];
68 synchronized(FtdiUart.this) {
69 result = example.ftdi_read_data(context, b0, len);
72 System.arraycopy(b0, 0, b, off, result);
75 try { Thread.sleep(50); } catch (Exception e) { e.printStackTrace(); }
80 private final OutputStream out = new BufferedOutputStream(new OutputStream() {
81 public void write(int b) throws IOException {
82 byte[] d = new byte[1];
86 public void write(byte[] b, int off, int len) throws IOException {
87 byte[] b2 = new byte[64];
89 System.arraycopy(b, off, b2, 0, Math.min(b2.length, len));
91 synchronized(FtdiUart.this) {
92 result = example.ftdi_write_data(context, b2, Math.min(b2.length, len));