Source code: org/bluej/core/Hci.java
1 package org.bluej.core;
2 import java.util.*;
3
4 public class Hci {
5 static { System.loadLibrary("bluej"); }
6
7 protected String address; // address of the device
8 protected int peer; // the C data structure
9 protected boolean closed; // has this been closed
10 protected Monitor mon = new Monitor();
11 protected Set connections = new HashSet(); // active connections
12 protected L2CAPLstn listener = null;
13 protected Thread monThread;
14
15 public Hci(int devid, L2CAPLstn lstn) throws BlueJException {
16 address = initialize(devid);
17 closed = false;
18 listener = lstn;
19 if (lstn != null) {
20 monThread = new Thread(mon, "Bluetooth Connection Monitor");
21 monThread.start();
22 }
23 }
24 public Hci() throws BlueJException { this(0, null); }
25 public Hci(int devid) throws BlueJException { this(devid, null); }
26 public Hci(L2CAPLstn lstn) throws BlueJException { this(0, lstn); }
27
28 public String getAddress() {
29 return address;
30 }
31 public void close() {
32 Iterator it = connections.iterator();
33 while (it.hasNext()) {
34 L2CAPConn conn = (L2CAPConn)it.next();
35 conn.close();
36 }
37 closed = true;
38 closeDev();
39 }
40
41 synchronized native String
42 initialize(int devid) throws BlueJException;
43
44 synchronized public native L2CAPConn
45 connectL2CAP(long psm, String address, int mtuIn, int mtuOut)
46 throws BlueJException;
47
48 synchronized public native void
49 listenStartL2CAP(long psm, int mtuIn, int mtuOut)
50 throws BlueJException;
51
52 synchronized public native void
53 listenStopL2CAP(long psm) throws BlueJException;
54
55 synchronized protected native L2CAPConn
56 acceptL2CAP() throws BlueJException;
57
58 synchronized public native String[]
59 discoverDevices(int inqSecs, int maxDev) throws BlueJException;
60
61 synchronized native void closeDev();
62
63 void connectionChange(L2CAPConn conn, boolean up) {
64 if (up)
65 connections.add(conn);
66 else
67 connections.remove(conn);
68 }
69 protected void finalize() {
70 if (!closed) close();
71 }
72
73 class Service implements Runnable {
74 L2CAPConn conn;
75 Service(L2CAPConn conn) {
76 this.conn = conn;
77 }
78 public void run() {
79 listener.newConnection(conn);
80 conn.close();
81 }
82 }
83 class Monitor implements Runnable {
84 public void run () {
85 while (!closed) {
86 try {
87 try { Thread.sleep(1000); } catch (Exception e) {}
88 L2CAPConn conn = acceptL2CAP();
89 if (conn != null) {
90 listener.newConnection(conn);
91 }
92 }
93 catch (BlueJException e) {
94 e.printStackTrace();
95 }
96 }
97 }
98 }
99 }