Fri Jul 25, 2008 6:43 pm
package sift;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
import javax.swing.ImageIcon;
/**
* A class that demonstrates Bluetooth communication between server mode PC and
* client mode device through serial port profile.
*
* @see sourceforge.net/projects/bluecove : BlueCove - JSR-82
* implementation</a>
*/
public class PCServerCOMM {
/*-
* ================
* Bluetooth Server
* ================
*
* This example application is a straighforward implementation of
* a bluetooth server.
*
*
* Usage
* =====
*
* Start the program. Events are logged by printing them out with standard
* output stream. Once the server is up and ready to accept connections,
* connect to server with client.
*
*
* How it Works
* ============
*
* The application starts a loop to wait for a new connection. After a new
* connection is reseived the connection is handled. In the handling
* operation few tokens and end token is written to connection stream.
* Each read token is logged to standard output. After handling session
* the loop continues by waiting for a new connection.
*
*/
/*-
*
* ---- Bluetooth attributes ----
*/
// serial port profile
protected String UUID = new UUID("1101", true).toString();
protected int discoveryMode = DiscoveryAgent.GIAC; // no paring needed
public static InputStream in;
public static OutputStream out;
private static boolean ServerRun = true;
Image aa;
MOBILEOR_GUI frame;
/*-
*
* ---- Connection handling attributes ----
*/
protected int endToken = 255;
public PCServerCOMM(MOBILEOR_GUI frame) {
this.frame = frame;
ServerRun = true;
try {
LocalDevice device = LocalDevice.getLocalDevice();
device.setDiscoverable(DiscoveryAgent.GIAC);
String url = "btspp://localhost:" + UUID + ";name=PCServerCOMM";
log("Create server by uri: " + url);
StreamConnectionNotifier notifier = (StreamConnectionNotifier) Connector.open(url);
serverLoop(notifier);
} catch (Throwable e) {
log(e);
}
}
private void serverLoop(final StreamConnectionNotifier notifier) {
Thread handler = new Thread() {
@Override
public void run() {
try {
while (ServerRun) { // infinite loop to accept connections.
log("Waiting for connection...");
handleConnection(notifier.acceptAndOpen());
}
} catch (Exception e) {
log(e);
}
try {
Thread.sleep(200);
} catch (InterruptedException ex) {
Logger.getLogger(PCServerCOMM.class.getName()).log(Level.SEVERE, null, ex);
}
}
};
handler.start();
}
private void handleConnection(StreamConnection conn) throws IOException {
out = conn.openOutputStream();
in = conn.openInputStream();
startReadThread(in);
log("Connection found...");
/*
try { // to write some tokens through the bluetooth link
int[] tokens = new int[] { 1, 3, 5, 7, endToken };
for (int i = 0; i < tokens.length; i++) {
out.write(tokens[i]);
out.flush();
log("write:" + tokens[i]);
// wait a sec before next write.
Thread.sleep(1 * 1000);
}
} catch (Exception e) {
log(e);
} finally {
log("Close connection.");
if (conn != null) {
try {
conn.close();
} catch (IOException e) {
}
}
}
* */
}
private void startReadThread(final InputStream in) {
Thread reader = new Thread() {
@Override
public void run() {
FileOutputStream f1 = null;
// System.out.println("Image data");
File directory = new File("C:/Image/");
String path = "image/image.png";
String image = "";
try {
f1 = new FileOutputStream(path,false);
} catch (FileNotFoundException ex) {
Logger.getLogger(PCServerCOMM.class.getName()).log(Level.SEVERE, null, ex);
}
byte[] s = new byte[512];
boolean falg = true;
log("Waiting for image data");
try {
while (true) {
int r = in.read(s);
if (r != -1) {
falg = false;
try {
//s=Base64.decode(new String(s).intern());
// image = image + new String(s,0,r);
f1.write(s, 0, r);
f1.flush();
} catch (IOException e) {
System.out.println("Problems creating the file");
}
}
if (!falg && (r < s.length)) {
// System.out.println("Frame !!!");
f1.flush();
f1.close();
aa = new ImageIcon(path).getImage();
new FrameImage(aa, 1);
SIFT sift = new SIFT(path, "scale2.jpg", "welcome");
frame.setImg(aa);
frame.repaint();
BufferedImage buff = new BufferedImage(aa.getWidth(null), aa.getHeight(null), BufferedImage.TYPE_INT_RGB);
// buff.createGraphics().drawImage(sift.oriented_Image(), 0, 0, null);
// OrientationForm orientionResult = new OrientationForm(buff);
// orientionResult.showOrientationResult();
MOBILEOR_GUI.AppendTostatus(sift.getATree().getMatchingInfo());
// setNearestImages(sift.getNearest_5_imgs());
// frame.createNearestWindow(sift.getNearest_5_imgs(), orientionResult);
// frame.getDisplayNearest().setSize(frame.getDesktopWidth(), 200);
// frame.getDisplayNearest().setLocation(0, orientionResult.getHeight() + 5);
// frame.getDesktop().add(frame.getDisplayNearest());
break;
}
}
} catch (Throwable e) {
log(e);
} finally {
if (in != null) {
try {
log("Image transfering done...");
in.close();
} catch (IOException e) {
}
}
}
}
};
reader.start();
}
/*-
* ------- Utility section -------
*/
private void log(String msg) {
MOBILEOR_GUI.AppendTostatus(msg + "\n");
}
private void log(Throwable e) {
log(e.getMessage());
e.printStackTrace();
}
public Image getImage() {
return aa;
}
public static void StopServer() {
ServerRun = false;
}
/*-
* ------- Bootstrap section, i.e., main method -------
*/
}
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Vector;
import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.List;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
/**
* A class that demonstrates Bluetooth communication between client mode device
* and server mode PC through serial port profile.
*/
public class DeviceClientCOMM implements DiscoveryListener, CommandListener {
/*-
* ================
* Bluetooth Client
* ================
*
* This example application is a straightforward implementation of
* making a connection throught bluetooth link and using it.
*
*
* Usage
* =====
*
* Once the system is started the information area is filled with logging
* information. Wait until combo box is enabled (if there's any bluetooth
* device around) and select a device from the combo box. A connection
* is constructed to selected device after selection.
*
* After connection is constructed succesfully the application
* operates as an echo client, i.e., everything that is read is written
* back to the server. All information is also written into the information
* area.
*
*
* How it Works
* ============
*
* The example consist of three different operations. Operations need to
* be executed in the dependency order.
*
* 1) *Inquiry method* is used to search all available devices. The combo
* box's data model is filled with found bluetooth devices.
*
* 2) *Service search* is used to search serial port profile service from the
* selected device. The search is started after the user selects the
* device from the combo box.
*
* 3) *Stream handling* communicates with the server through the bluetooth
* link. This example operates in echo loop until stop token is found.
*
*
* Special Debug Mode
* ==================
*
* There's a special debug mode which speeds up development by skipping the
* inquiry method to resolve the remote device. In the debug mode the device's
* bluetooth address is provided by the developer.
*/
/*-
*
* ---- Debug attributes ----
*/
static final boolean DEBUG = false;
static final String DEBUG_address = "0013FDC157C8"; // N6630
/*-
*
* ---- Bluetooth attributes ----
*/
protected UUID uuid = new UUID(0x1101); // serial port profile
protected int inquiryMode = DiscoveryAgent.GIAC; // no pairing is needed
protected int connectionOptions = ServiceRecord.NOAUTHENTICATE_NOENCRYPT;
/*-
*
* ---- Echo loop attributes ----
*/
protected int stopToken = 255;
/*-
*
* ---- GUI attributes ----
*/
private Command backCommand = new Command("Back", Command.BACK, 1);
protected Form infoArea = new Form("Bluetooth Client");
protected Vector deviceList = new Vector();
private CameraMIDlet mymidlet;
private byte[] imag;
public DeviceClientCOMM(CameraMIDlet m, byte[] imag) {
mymidlet = m;
this.imag = imag;
infoArea.setCommandListener(this);
infoArea.addCommand(backCommand);
try {
startApp();
} catch (MIDletStateChangeException ex) {
ex.printStackTrace();
}
}
protected void startApp() throws MIDletStateChangeException {
makeInformationAreaGUI();
if (DEBUG) // skip inquiry in debug mode
{
startServiceSearch(new RemoteDevice(DEBUG_address) {
});
} else {
try {
startDeviceInquiry();
} catch (Throwable t) {
log(t);
}
}
}
/*-
* ------- Device inquiry section -------
*/
private void startDeviceInquiry() {
try {
log("Start inquiry method - this will take few seconds...");
DiscoveryAgent agent = getAgent();
agent.startInquiry(inquiryMode, this);
} catch (Exception e) {
log(e);
}
}
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
log("A device discovered (" + getDeviceStr(btDevice) + ")");
deviceList.addElement(btDevice);
}
public void inquiryCompleted(int discType) {
log("Inquiry compeleted. Please select device from combo box.");
makeDeviceSelectionGUI();
}
/*-
* ------- Service search section -------
*/
private void startServiceSearch(RemoteDevice device) {
try {
log("Start search for Serial Port Profile service from " + getDeviceStr(device));
UUID uuids[] = new UUID[]{uuid};
getAgent().searchServices(null, uuids, device, this);
} catch (Exception e) {
log(e);
}
}
/**
* This method is called when a service(s) are discovered.This method starts
* a thread that handles the data exchange with the server.
*/
public void servicesDiscovered(int transId, ServiceRecord[] records) {
log("Service discovered.");
for (int i = 0; i < records.length; i++) {
ServiceRecord rec = records[i];
String url = rec.getConnectionURL(connectionOptions, false);
handleConnection(url);
}
}
public void serviceSearchCompleted(int transID, int respCode) {
String msg = null;
switch (respCode) {
case SERVICE_SEARCH_COMPLETED:
msg = "the service search completed normally";
break;
case SERVICE_SEARCH_TERMINATED:
msg = "the service search request was cancelled by a call to DiscoveryAgent.cancelServiceSearch()";
break;
case SERVICE_SEARCH_ERROR:
msg = "an error occurred while processing the request";
break;
case SERVICE_SEARCH_NO_RECORDS:
msg = "no records were found during the service search";
break;
case SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
msg = "the device specified in the search request could not be reached or the local device could not establish a connection to the remote device";
break;
}
log("Service search completed - " + msg);
}
/*-
* ------- The actual connection handling. -------
*/
private void handleConnection(final String url) {
Thread echo = new Thread() {
public void run() {
StreamConnection stream = null;
InputStream in = null;
OutputStream out = null;
try {
log("Connecting to server by url: " + url);
stream = (StreamConnection) Connector.open(url);
log("Bluetooth stream open.");
// InputStream in = stream.openInputStream();
out = stream.openOutputStream();
in = stream.openInputStream();
startReadThread(in);
// String stringImage = Base64.encode(imag);
log("Start echo loop.");
out.write(imag);
out.flush();
// out.flush();
// stream.close();
} catch (IOException e) {
log(e);
} finally {
log("Bluetooth stream closed.");
if (out != null) {
try {
out.close();
stream.close();
logSet("Image Transfer done\n----------------\n\nWaiting for results...");
} catch (IOException e) {
log(e);
}
}
}
}
};
echo.start();
}
private void startReadThread(final InputStream in) {
Thread reader = new Thread() {
public void run() {
byte[] s = new byte[512];
//boolean flag = true;
try {
while (true) {
int r = in.read(s);
if (r != -1) {
logSet(new String(s, 0, r));
} else {
break;
}
Thread.sleep(200);
}
} catch (Throwable e) {
log(e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
}
}
};
reader.start();
}
/*-
* ------- Graphic User Interface section -------
*/
private void makeInformationAreaGUI() {
infoArea.deleteAll();
Display.getDisplay(mymidlet).setCurrent(infoArea);
}
private void makeDeviceSelectionGUI() {
final List devices = new List("Select a device", List.IMPLICIT);
for (int i = 0; i < deviceList.size(); i++) {
devices.append(
getDeviceStr((RemoteDevice) deviceList.elementAt(i)), null);
}
devices.setCommandListener(new
CommandListener( ) {
public void commandAction(Command arg0,
Displayable arg1)
{
makeInformationAreaGUI();
startServiceSearch((RemoteDevice) deviceList.elementAt(devices.getSelectedIndex()));
}
});
Display.getDisplay(mymidlet).setCurrent(devices);
}
synchronized private void log(String msg) {
infoArea.append(msg);
infoArea.append("\n\n");
}
synchronized private void logSet(String msg) {
infoArea.deleteAll();
infoArea.append(msg);
infoArea.append("\n\n");
}
private void log(Throwable e) {
log(e.getMessage());
}
/*-
* ------- Utils section - contains utility functions -------
*/
private DiscoveryAgent getAgent() {
try {
return LocalDevice.getLocalDevice().getDiscoveryAgent();
} catch (BluetoothStateException e) {
throw new Error(e.getMessage());
}
}
private String getDeviceStr(RemoteDevice btDevice) {
return getFriendlyName(btDevice) + " - 0x" + btDevice.getBluetoothAddress();
}
private String getFriendlyName(RemoteDevice btDevice) {
try {
return btDevice.getFriendlyName(false);
} catch (IOException e) {
return "no name available";
}
}
public void commandAction(Command arg0, Displayable arg1) {
mymidlet.DisplayMainList();
}
}
Tue Jan 27, 2009 10:14 pm
MOBILEOR_GUI frame;
new FrameImage(aa, 1);
SIFT sift = new SIFT(path, "scale2.jpg", "welcome");
Tue Jan 27, 2009 10:26 pm
Sat Apr 18, 2009 8:59 pm
Mon Apr 20, 2009 6:59 pm
Mon Apr 27, 2009 8:34 am
Mon Apr 27, 2009 5:28 pm
Thu Oct 22, 2009 6:39 pm
Thu Oct 22, 2009 6:46 pm
Sat Nov 07, 2009 5:30 am
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com
Powered by phpBB © phpBB Group.