package net.sf.lab3f.bluetooth;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.util.HashMap;
import java.util.Map;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
public class Main {
private Map <String, StreamConnection> conns = new HashMap <String, StreamConnection> ();
private Map <String, InputStream> inputs = new HashMap <String, InputStream> ();
private Map <String, OutputStream> outputs = new HashMap <String, OutputStream> ();
private StreamConnectionNotifier notifier;
private Thread mainThread = new Thread(new Runnable(){
public void run(){
while(true){
try{
StreamConnection conn = notifier.acceptAndOpen();
System.out.println("New BT connection...");
byte[] ba = new byte[15];
InputStream is = conn.openInputStream();
OutputStream os = conn.openOutputStream();
is.read(ba);
String s = new String(ba);
conns.put(s, conn);
inputs.put(s, is);
outputs.put(s, os);
}
catch(IOException ex){System.out.println(ex);}
}
}
});
public BufferedWriter getWriter(String s) throws IOException{
OutputStream os = outputs.get(s);
if(os == null)return null;
return new BufferedWriter(new OutputStreamWriter(os));
}
public BufferedReader getReader(String s) throws IOException{
InputStream is = inputs.get(s);
if(is == null)return null;
return new BufferedReader(new InputStreamReader(is));
}
public void start() throws Exception {
String url = "btspp://localhost:0A1B2C3D4E5F60718293A4B5C6D7E8F9;name=bt_buttons_server";
notifier = (StreamConnectionNotifier)Connector.open(url);
mainThread.start();
System.out.println("[INFO] Bluetooth service starts.");
}
public void stop() throws Exception {
try{
mainThread.interrupt();
for(StreamConnection conn : conns.values())conn.close();
}
catch(IOException ex){System.out.println(ex);}
}
}