Mostrando entradas con la etiqueta java. Mostrar todas las entradas
Mostrando entradas con la etiqueta java. Mostrar todas las entradas

16 sept 2009

Bluetooth Obex con BlueCove JSR 82 API

Aqui les dejo el codigo para comunicarnos a travez de bluetooth con la implementacion del API JSR82 de Bluecove, lo necesario para poder realizar esta operación es agregar a nuestra extension de java la libreria (javahome\jre\lib\ext) de bluecove esta libreria incluye clases que se utilizan para la implementacion de este tipo de soluciones, el siguiente programa contiene la informacion necesaria para realizar la comunicacion con dispositivos bluetooth

Clase que se encarga de la busqueda de los dispositivos


/**
* BlueCove - Java library for Bluetooth
* Copyright (C) 2006-2007 Vlad Skarzhevskyy
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* @version $Id: RemoteDeviceDiscovery.java 974 2007-08-23 21:28:54Z skarzhevskyy $
*/
package com.intel.bluetooth.javadoc;

import java.io.IOException;
import java.util.Vector;

import javax.bluetooth.*;

/**
* @author vlads
*
* Minimal DeviceDiscovery example for javadoc.
*/
public class RemoteDeviceDiscovery {

public static final Vector/**/ devicesDiscovered = new Vector();

public static void main(String[] args) throws IOException, InterruptedException {

final Object inquiryCompletedEvent = new Object();

devicesDiscovered.clear();

DiscoveryListener listener = new DiscoveryListener() {

public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
System.out.println("Device " + btDevice.getBluetoothAddress() + " found");
devicesDiscovered.addElement(btDevice);
try {
System.out.println(" name " + btDevice.getFriendlyName(false));
} catch (IOException cantGetDeviceName) {
}
}

public void inquiryCompleted(int discType) {
System.out.println("Device Inquiry completed!");
synchronized(inquiryCompletedEvent){
inquiryCompletedEvent.notifyAll();
}
}

public void serviceSearchCompleted(int transID, int respCode) {
}

public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
}
};

synchronized(inquiryCompletedEvent) {
boolean started = LocalDevice.getLocalDevice().getDiscoveryAgent().startInquiry(DiscoveryAgent.GIAC, listener);
if (started) {
System.out.println("wait for device inquiry to complete...");
inquiryCompletedEvent.wait();
System.out.println(devicesDiscovered.size() + " device(s) found");
}
}
}
}


Busqueda de los servicios, los servicios es el medio de coneccion que tiene cada dispositivo para su comunicacion e interaccion, el siquiente codigo muestra como realizar esta comunicacion


/**
* BlueCove - Java library for Bluetooth
* Copyright (C) 2006-2007 Vlad Skarzhevskyy
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* @version $Id: ServicesSearch.java 974 2007-08-23 21:28:54Z skarzhevskyy $
*/
package com.intel.bluetooth.javadoc;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Vector;

import javax.bluetooth.*;

/**
* @author vlads
*
* Minimal ServicesSearch example for javadoc.
*/
public class ServicesSearch {

static final UUID OBEX_OBJECT_PUSH = new UUID(0x1105);

public static final Vector/**/ serviceFound = new Vector();

public static void main(String[] args) throws IOException, InterruptedException {

// First run RemoteDeviceDiscovery and use discoved device
RemoteDeviceDiscovery.main(null);

serviceFound.clear();

UUID serviceUUID = OBEX_OBJECT_PUSH;
if ((args != null) && (args.length > 0)) {
serviceUUID = new UUID(args[0], false);
}

final Object serviceSearchCompletedEvent = new Object();

DiscoveryListener listener = new DiscoveryListener() {

public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
}

public void inquiryCompleted(int discType) {
}

public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
for (int i = 0; i < servRecord.length; i++) {
String url = servRecord[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
if (url == null) {
continue;
}
serviceFound.add(url);
DataElement serviceName = servRecord[i].getAttributeValue(0x0100);
if (serviceName != null) {
System.out.println("service " + serviceName.getValue() + " found " + url);
} else {
System.out.println("service found " + url);
}
}
}

public void serviceSearchCompleted(int transID, int respCode) {
System.out.println("service search completed!");
synchronized(serviceSearchCompletedEvent){
serviceSearchCompletedEvent.notifyAll();
}
}

};

UUID[] searchUuidSet = new UUID[] { serviceUUID };
int[] attrIDs = new int[] {
0x0100 // Service name
};

for(Enumeration en = RemoteDeviceDiscovery.devicesDiscovered.elements(); en.hasMoreElements(); ) {
RemoteDevice btDevice = (RemoteDevice)en.nextElement();

synchronized(serviceSearchCompletedEvent) {
System.out.println("search services on " + btDevice.getBluetoothAddress() + " " + btDevice.getFriendlyName(false));
LocalDevice.getLocalDevice().getDiscoveryAgent().searchServices(attrIDs, searchUuidSet, btDevice, listener);
serviceSearchCompletedEvent.wait();
}
}

}

}



Luego toca crea un clase que es la engargada de crear el servidor de OBEX que se encarga de realizar el push de la información que vamos a enviar desde el cliente


/**
* BlueCove - Java library for Bluetooth
* Copyright (C) 2006-2007 Vlad Skarzhevskyy
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* @version $Id: OBEXPutServer.java 974 2007-08-23 21:28:54Z skarzhevskyy $
*/
package com.intel.bluetooth.javadoc;

import java.io.IOException;
import java.io.InputStream;

import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.obex.*;

/**
* @author vlads
*
* Minimal OBEX Server that accept Put commands and print it to standard out for javadoc.
*
*/
public class OBEXPutServer {

static final String serverUUID = "11111111111111111111111111111123";

public static void main(String[] args) throws IOException {

LocalDevice.getLocalDevice().setDiscoverable(DiscoveryAgent.GIAC);

SessionNotifier serverConnection = (SessionNotifier) Connector.open("btgoep://localhost:"
+ serverUUID + ";name=ObexExample");

int count = 0;
while (count < 2) {
RequestHandler handler = new RequestHandler();
serverConnection.acceptAndOpen(handler);
System.out.println("Received OBEX connection " + (++count));
}
}

private static class RequestHandler extends ServerRequestHandler {

public int onPut(Operation op) {
try {
HeaderSet hs = op.getReceivedHeaders();
String name = (String) hs.getHeader(HeaderSet.NAME);
if (name != null) {
System.out.println("put name:" + name);
}

InputStream is = op.openInputStream();

StringBuffer buf = new StringBuffer();
int data;
while ((data = is.read()) != -1) {
buf.append((char) data);
}

System.out.println("got:" + buf.toString());

op.close();
return ResponseCodes.OBEX_HTTP_OK;
} catch (IOException e) {
e.printStackTrace();
return ResponseCodes.OBEX_HTTP_UNAVAILABLE;
}
}
}
}



y luego nuestra clase cliente que es la encargada de llamar a todos los servicios, para enviar la informacion al servidor.


/**
* BlueCove - Java library for Bluetooth
* Copyright (C) 2006-2007 Vlad Skarzhevskyy
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* @version $Id: ObexPutClient.java 974 2007-08-23 21:28:54Z skarzhevskyy $
*/
package com.intel.bluetooth.javadoc;

import java.io.IOException;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.obex.*;

/**
* @author vlads
*
* Minimal OBEX Put Client example for javadoc.
*/
public class ObexPutClient {

public static void main(String[] args) throws IOException, InterruptedException {

String serverURL = null; // = "btgoep://0019639C4007:6";
if ((args != null) && (args.length > 0)) {
serverURL = args[0];
}
if (serverURL == null) {
String[] searchArgs = null;
// Connect to OBEXPutServer from examples
// searchArgs = new String[] { "11111111111111111111111111111123" };
ServicesSearch.main(searchArgs);
if (ServicesSearch.serviceFound.size() == 0) {
System.out.println("OBEX service not found");
return;
}
// Select the first service found
serverURL = (String)ServicesSearch.serviceFound.elementAt(0);
}

System.out.println("Connecting to " + serverURL);

ClientSession clientSession = (ClientSession) Connector.open(serverURL);
HeaderSet hsConnectReply = clientSession.connect(null);
if (hsConnectReply.getResponseCode() != ResponseCodes.OBEX_HTTP_OK) {
System.out.println("Failed to connect");
return;
}

HeaderSet hsOperation = clientSession.createHeaderSet();
hsOperation.setHeader(HeaderSet.NAME, "Hello.txt");
hsOperation.setHeader(HeaderSet.TYPE, "text");

//Create PUT Operation
Operation putOperation = clientSession.put(hsOperation);

// Send some text to server
byte data[] = "Hello world!".getBytes("iso-8859-1");
OutputStream os = putOperation.openOutputStream();
os.write(data);
os.close();

putOperation.close();

clientSession.disconnect(null);

clientSession.close();
}
}



aca les dejo unas lecturas que le ayudaran a comprender mejor el procedimiento:

Bluetooth for Obex with Bluecove - Bluetooth Definition - Codigo de ayuda