0% found this document useful (0 votes)
52 views8 pages

Bluetooth Document

This document contains code for creating a Bluetooth chat service and client in Java. The code defines a ServerChat class that opens a Bluetooth service for chatting and listens for incoming connections. It also defines a ClientChat class that discovers nearby Bluetooth devices, searches for services, and finds the chat service. The code handles connecting, listening, discovery, and service searching functionality for a basic Bluetooth chat application.

Uploaded by

Hitesh Prajapati
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views8 pages

Bluetooth Document

This document contains code for creating a Bluetooth chat service and client in Java. The code defines a ServerChat class that opens a Bluetooth service for chatting and listens for incoming connections. It also defines a ClientChat class that discovers nearby Bluetooth devices, searches for services, and finds the chat service. The code handles connecting, listening, discovery, and service searching functionality for a basic Bluetooth chat application.

Uploaded by

Hitesh Prajapati
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 8

creating service

import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.LocalDevice;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;

public class ServerChat


{
private static final String CHATTANDO_UUID = "A1A2A3A4A5A6A7A8A9A0B1B2B3B4B5B6";
private static final String CHATTANDO_SERVICE = "Chattando";

private boolean isReady = false;

private StreamConnection stream_connection;


private StreamConnectionNotifier stream_connection_notifier;

public ServerChat()
{
startServerChatBluetooth();
}

// It opens the service for the Chat


public void startServerChatBluetooth()
{
new Thread()
{
public void run()
{
try
{

LocalDevice.getLocalDevice().setDiscoverable(DiscoveryAgent.GIAC);
}
catch(Exception error)
{
error.printStackTrace();
}

try
{
stream_connection_notifier = (StreamConnectionNotifier)
Connector.open("btspp://localhost:" + CHATTANDO_UUID + ";name=" + CHATTANDO_SERVICE);
}
catch(Exception error)
{
error.printStackTrace();
}

stopServerChatBluetooth();

// It puts in listen to the Server of the Chat


isReady = true;
try
{
while(isReady)
{
System.out.println("They are in listen...");

stream_connection =
stream_connection_notifier.acceptAndOpen();

System.out.println("Client Connected");
}
}
catch(Exception error)
{
error.printStackTrace();
}
}

}.start();
}

// It closes the service for the Chat


public void stopServerChatBluetooth()
{
if(isReady)
{
isReady = false;

try
{
stream_connection_notifier.close();
}
catch(Exception error)
{
error.printStackTrace();
}
}
}
}

search service......
import java.util.Vector;

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;

public class ClientChat implements DiscoveryListener


{
private static final String CHATTANDO_UUID = "A1A2A3A4A5A6A7A8A9A0B1B2B3B4B5B6";
private static final String CHATTANDO_SERVICE = "Chattando";

protected Chattando midlet;

private boolean searchDone = false;

private DiscoveryAgent discovery_agent;

private Vector remote_device;


private Vector device_found;

public ClientChat(Chattando midlet)


{
this.midlet = midlet;

startScanBluetoothDevices();
}

// bluetooth starts seach devices


public void startScanBluetoothDevices()
{
try
{
remote_device = new Vector();
device_found = new Vector();

discovery_agent = LocalDevice.getLocalDevice().getDiscoveryAgent();
discovery_agent.startInquiry(DiscoveryAgent.GIAC, this);
}
catch(Exception error)
{
error.printStackTrace();
}
}

// Stoppa la ricerca dei dispositivi Bluetooth


public void stopScanBluetoothDevices()
{
discovery_agent.cancelInquiry(this);
}

public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod)


{
// Aggiungo il dispositivo solo se e' un computer (0x0100) o un cellulare (0x0200)
if(cod.getMajorDeviceClass() == 0x0100 || cod.getMajorDeviceClass() == 0x0200)
remote_device.addElement(btDevice);
}

public void inquiryCompleted(int discType)


{
switch(discType)
{
case DiscoveryListener.INQUIRY_COMPLETED:

System.out.println("Device Search Completed");


break;

case DiscoveryListener.INQUIRY_ERROR:

System.out.println("Device Search Error");

break;

case DiscoveryListener.INQUIRY_TERMINATED:

System.out.println("Device Search Terminated");

break;
}

try
{
for(int i=0, cnt=remote_device.size(); i<cnt; i++)
{
discovery_agent.searchServices(new int[]{ 0x0100, 0x0200 }, new
UUID[]{ new UUID(0x0003), new UUID(CHATTANDO_UUID, false) }, (RemoteDevice)
remote_device.elementAt(i), this);
waitForSearchDone();
}
}
catch(Exception error)
{
error.printStackTrace();
}
}

// Aspetta che la ricerca dei servizi per il dispositivo sia terminata


private void waitForSearchDone()
{
searchDone = false;

try
{
while(!searchDone)
{
synchronized(this)
{
this.wait();
}
}
}
catch(Exception error)
{

}
}

public void serviceSearchCompleted(int transID, int respCode)


{
switch(respCode)
{
case DiscoveryListener.SERVICE_SEARCH_COMPLETED:

System.out.println("Service Search Completed");


break;

case DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE:

System.out.println("Service Search Device not Reachable");


break;

case DiscoveryListener.SERVICE_SEARCH_ERROR:

System.out.println("Service Search Error");


break;

case DiscoveryListener.SERVICE_SEARCH_NO_RECORDS:

System.out.println("Service Search No Records");

break;

case DiscoveryListener.SERVICE_SEARCH_TERMINATED:

System.out.println("Service Search Terminated");


break;
}

searchDone = true;

// Risveglia il processo in attesa del completamento della ricerca dei servizi per un
dispositivo
synchronized(this)
{
this.notifyAll();
}
}

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


{
for(int i=0, cnt=servRecord.length; i<cnt; i++)
{
if(((String)
servRecord[i].getAttributeValue(0x0100).getValue()).equalsIgnoreCase(CHATTANDO_SERVICE))
{
device_found.addElement(servRecord[i].getHostDevice());
}
}
}
}
J2ME System Properties...
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
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.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class SystemProperties extends MIDlet implements CommandListener


{
private Command esci;

private Display display;

private Form form;

protected void startApp() throws MIDletStateChangeException


{
display = Display.getDisplay(this);

form = new Form("System Propiertis");


form.setCommandListener(this);

esci = new Command("Esci", Command.EXIT, 0);


form.addCommand(esci);

Runtime rt = Runtime.getRuntime();
rt.gc(); // Garbage Collection

form.append("Free Memory: " + rt.freeMemory() + "\n");


form.append("Total Memory: " + rt.totalMemory() + "\n");
form.append(showProp("microedition.configuration"));
form.append(showProp("microedition.platform"));
form.append(showProp("microedition.locale"));
form.append(showProp("microedition.encoding"));
form.append(showProp("microedition.encodingClass"));
form.append(showProp("microedition.http_proxy"));

display.setCurrent(form);
}

protected void pauseApp()


{

protected void destroyApp(boolean unconditional) throws MIDletStateChangeException


{
notifyDestroyed();
}
public String showProp(String str)
{
String value = System.getProperty(str);
StringBuffer stringbuffer = new StringBuffer(50);

stringbuffer.setLength(0);
stringbuffer.append(str);
stringbuffer.append(" = ");

if(value == null)
stringbuffer.append("<undefined>");
else
{
stringbuffer.append("\"");
stringbuffer.append(value);
stringbuffer.append("\"");
}

stringbuffer.append("\n");

return stringbuffer.toString();
}

public void commandAction(Command c, Displayable d)


{
if(c == esci)
{
try
{
destroyApp(true);
}
catch(MIDletStateChangeException e)
{
showException(e);
}
}
}

public void showException(Exception e)


{
Alert alert = new Alert("Errore !!!");
alert.setString(e.getMessage());
alert.setType(AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);

display.setCurrent(alert);
}
}

Send sms over Bluetooth


import bluetooth

sockfd = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sockfd.connect(('00:00:00:00:00:00', 1)) # BT Address
sockfd.send('ATZ\r')
sockfd.send('AT+CMGF=1\r')
sockfd.send('AT+CSCA="+393359609600"\r') # Client TIM ITA
sockfd.send('AT+CMGS="+39xxxxxxxxxx"\r') # TO PhoneNumber
sockfd.send('Messaggio da mandare...\n')
sockfd.send(chr(26)) # CTRL+Z
sockfd.close()

You might also like