Java --- Bluetooth Device & Service Discovery Code examples

import java.io.IOException;
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;

/**
 * Class that discovers all bluetooth devices in the neighborhood and displays their name and
 * bluetooth address.
 */
public class BluetoothDeviceDiscovery implements DiscoveryListener {

        // object used for waiting
        private static Object lock = new Object();

        // vector containing the devices discovered
        private static Vector<RemoteDevice> vecDevices = new Vector<RemoteDevice>();

        /**
         * Lists nearby bluetooth devices
         * 
         * @return
         */
        public void listDevices() throws IOException {

                // display local device address and name
                LocalDevice localDevice = LocalDevice.getLocalDevice();
                System.out.println("Address: " + localDevice.getBluetoothAddress());
                System.out.println("Name: " + localDevice.getFriendlyName());

                // find devices
                DiscoveryAgent agent = localDevice.getDiscoveryAgent();
                System.out.println("Starting device inquiry...");
                agent.startInquiry(DiscoveryAgent.GIAC, this);

                // avoid callback conflicts
                try {
                        synchronized (lock) {
                                lock.wait();
                        }
                } catch (InterruptedException e) {
                        e.printStackTrace();
                }

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

                // print all devices in vecDevices
                int deviceCount = vecDevices.size();
                if (deviceCount <= 0) {
                        System.out.println("No Devices Found .");
                } else {
                        // print bluetooth device addresses and names in the format [ No. address (name) ]
                        System.out.println("Bluetooth Devices: ");
                        for (int i = 0; i < deviceCount; i++) {
                                RemoteDevice remoteDevice = (RemoteDevice) vecDevices.elementAt(i);
                                try {
                                        System.out.println((i + 1) + ". " + remoteDevice.getBluetoothAddress() + " (" + remoteDevice.getFriendlyName(true) + ")");
                                } catch (IOException ioe) {
                                        ioe.printStackTrace();
                                }
                        }
                }
        }

        /**
         * @return the vecDevices
         */
        public static Vector<RemoteDevice> getVecDevices() {
                return vecDevices;
        }

        /**
         * This call back method will be called for each discovered bluetooth devices.
         */
        public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
                System.out.println("Device discovered: " + btDevice.getBluetoothAddress());
                // add the device to the vector
                if (!vecDevices.contains(btDevice)) {
                        vecDevices.addElement(btDevice);
                }
        }

        // no need to implement this method since services are not being discovered
        public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
        }

        // no need to implement this method since services are not being discovered
        public void serviceSearchCompleted(int transID, int respCode) {
        }

        /**
         * This callback method will be called when the device discovery is completed.
         */
        public void inquiryCompleted(int discType) {
                synchronized (lock) {
                        lock.notify();
                }

                switch (discType) {
                case DiscoveryListener.INQUIRY_COMPLETED:
                        System.out.println("INQUIRY_COMPLETED");
                        break;

                case DiscoveryListener.INQUIRY_TERMINATED:
                        System.out.println("INQUIRY_TERMINATED");
                        break;

                case DiscoveryListener.INQUIRY_ERROR:
                        System.out.println("INQUIRY_ERROR");
                        break;

                default:
                        System.out.println("Unknown Response Code");
                        break;
                }
        }// end method

}



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
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;

/**
 * 
 * Class that discovers all bluetooth devices in the neighborhood,
 * 
 * Connects to the chosen device and checks for the presence of OBEX push service in it. and
 * displays their name and bluetooth address.
 * 
 * 
 */
public class BluetoothServiceDiscovery implements DiscoveryListener {

        // object used for waiting
        private static Object lock = new Object();

        // vector containing the devices discovered
        private static Vector<RemoteDevice> vecDevices = new Vector<RemoteDevice>();

        // device connection address
        private static String connectionURL = null;

        /**
         * Lists nearby bluetooth device services
         */
        public void listServices() throws IOException {

                // display local device address and name
                LocalDevice localDevice = LocalDevice.getLocalDevice();
                System.out.println("Address: " + localDevice.getBluetoothAddress());
                System.out.println("Name: " + localDevice.getFriendlyName());

                // find devices
                DiscoveryAgent agent = localDevice.getDiscoveryAgent();
                System.out.println("Starting device inquiry...");
                agent.startInquiry(DiscoveryAgent.GIAC, this);

                // avoid callback conflicts
                try {
                        synchronized (lock) {
                                lock.wait();
                        }
                } catch (InterruptedException e) {
                        e.printStackTrace();
                }

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

                // print all devices in vecDevices
                int deviceCount = vecDevices.size();
                if (deviceCount <= 0) {
                        System.out.println("No Devices Found .");
                } else {
                        // print bluetooth device addresses and names in the format [ No. address (name) ]
                        System.out.println("Bluetooth Devices: ");
                        for (int i = 0; i < deviceCount; i++) {
                                RemoteDevice remoteDevice = (RemoteDevice) vecDevices.elementAt(i);
                                try {
                                        System.out.println((i + 1) + ". " + remoteDevice.getBluetoothAddress() + " (" + remoteDevice.getFriendlyName(true) + ")");
                                } catch (IOException ioe) {
                                        ioe.printStackTrace();
                                }
                        }
                }

                // prompt user
                System.out.print("Choose the device to search for Obex Push service : ");
                BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
                String chosenIndex = bReader.readLine();
                int index = Integer.parseInt(chosenIndex.trim());

                // check for obex service
                RemoteDevice remoteDevice = (RemoteDevice) vecDevices.elementAt(index - 1);
                UUID[] uuidSet = new UUID[1];
                uuidSet[0] = new UUID("1105", true);
                System.out.println("\nSearching for service...");
                agent.searchServices(null, uuidSet, remoteDevice, this);

                // avoid callback conflicts
                try {
                        synchronized (lock) {
                                lock.wait();
                        }
                } catch (InterruptedException e) {
                        e.printStackTrace();
                }

                // notify
                if (connectionURL == null) {
                        System.out.println("Device does not support Object Push.");
                } else {
                        System.out.println("Device supports Object Push.");
                }
        }

        /**
         * Called when a bluetooth device is discovered. Used for device search.
         */
        public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
                // add the device to the vector
                if (!vecDevices.contains(btDevice)) {
                        vecDevices.addElement(btDevice);
                }
        }

        /**
         * Called when a bluetooth service is discovered. Used for service search.
         */
        public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
                if (servRecord != null && servRecord.length > 0) {
                        connectionURL = servRecord[0].getConnectionURL(0, false);
                }
                synchronized (lock) {
                        lock.notify();
                }
        }

        /**
         * Called when the service search is over.
         */
        public void serviceSearchCompleted(int transID, int respCode) {
                synchronized (lock) {
                        lock.notify();
                }
        }

        /**
         * Called when the device search is over.
         */
        public void inquiryCompleted(int discType) {
                synchronized (lock) {
                        lock.notify();
                }

        }// end method

}// end class

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;

import data.model.Node;
import data.parser.DataParser;



/**
 * A simple SPP client that connects with an SPP server
 */
public class SimpleSPPClient implements DiscoveryListener {

	// object used for waiting
	private static Object lock = new Object();

	// vector containing the devices discovered
	private static Vector<RemoteDevice> vecDevices = new Vector<RemoteDevice>();

	// device connection address
	private static String connectionURL = null;

	/**
	 * runs a bluetooth client that sends a string to a server and prints the
	 * response
	 */
	public void runClient() throws IOException {

		// display local device address and name
		LocalDevice localDevice = LocalDevice.getLocalDevice();
		System.out.println("Address: " + localDevice.getBluetoothAddress());
		System.out.println("Name: " + localDevice.getFriendlyName());

		// find devices
		DiscoveryAgent agent = localDevice.getDiscoveryAgent();
		System.out.println("Starting device inquiry...");
		agent.startInquiry(DiscoveryAgent.GIAC, this);

		// avoid callback conflicts
		try {
			synchronized (lock) {
				lock.wait();
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

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

		// print all devices in vecDevices
		int deviceCount = vecDevices.size();
		if (deviceCount <= 0) {
			System.out.println("No Devices Found .");
		} else {
			// print bluetooth device addresses and names in the format [ No.
			// address (name) ]
			System.out.println("Bluetooth Devices: ");
			for (int i = 0; i < deviceCount; i++) {
				RemoteDevice remoteDevice = (RemoteDevice) vecDevices
						.elementAt(i);
				try {
					System.out.println((i + 1) + ". "
							+ remoteDevice.getBluetoothAddress() + " ("
							+ remoteDevice.getFriendlyName(true) + ")");
				} catch (IOException ioe) {
					ioe.printStackTrace();
				}
			}
		}

		// prompt user
		System.out.print("Choose the device to search for service : ");
		BufferedReader bReader = new BufferedReader(new InputStreamReader(
				System.in));
		String chosenIndex = bReader.readLine();
		int index = Integer.parseInt(chosenIndex.trim());

		// check for services
		RemoteDevice remoteDevice = (RemoteDevice) vecDevices
				.elementAt(index - 1);
		UUID[] uuidSet = new UUID[1];

		uuidSet[0] = new UUID("1101", true); // serial, SPP
		// uuidSet[0] = new UUID("0003", true); // rfcomm
		// uuidSet[0] = new UUID("1106", true); // obex file transfer
		// uuidSet[0] = new UUID("1105", true); // obex obj push

		System.out.println("\nSearching for services...");
		agent.searchServices(null, uuidSet, remoteDevice, this);

		// avoid callback conflicts
		try {
			synchronized (lock) {
				lock.wait();
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		// check
		if (connectionURL == null) {
			System.out.println("Device does not support Service.");
			System.exit(0);
		}

		// connect to the server
		StreamConnection streamConnection = null;
		try {
			System.out.println("Connected to server. \nNow start reading data from " + connectionURL);
			
			streamConnection = (StreamConnection) Connector.open(connectionURL);
			
			System.out.println("open connection ok!");
			InputStream inStream = streamConnection.openInputStream();
			
//			DataParser dParser = new DataParser(inStream);
//			dParser.Parse();
			Node node = new Node(inStream);
			node.readFromPort();
			
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(0);
		}
		System.out.println("End connection to server.");

	}

	// methods of DiscoveryListener
	public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
		// add the device to the vector
		if (!vecDevices.contains(btDevice)) {
			vecDevices.addElement(btDevice);
		}
	}

	// implement this method since services are not being discovered
	public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
		if (servRecord != null && servRecord.length > 0) {
			connectionURL = servRecord[0].getConnectionURL(0, false);
		}
		synchronized (lock) {
			lock.notify();
		}
	}

	// implement this method since services are not being discovered
	public void serviceSearchCompleted(int transID, int respCode) {
		synchronized (lock) {
			lock.notify();
		}
	}

	public void inquiryCompleted(int discType) {
		synchronized (lock) {
			lock.notify();
		}

	}// end method
	
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

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

/**
 * Class that implements an SPP Server which accepts single line of message from
 * an SPP client and sends a single line of response to the client.
 */
public class SimpleSPPServer {

	/**
	 * runs a bluetooth server that accepts a string from a client and sends a
	 * response
	 */
	public void runServer() throws IOException {

		// display local device address and name
		LocalDevice localDevice = LocalDevice.getLocalDevice();
		System.out.println("Address: " + localDevice.getBluetoothAddress());
		System.out.println("Name: " + localDevice.getFriendlyName());

		// SimpleSPPServer sampleSPPServer = new SimpleSPPServer();
		// sampleSPPServer.startServer();
		this.startServer();

	} // runServer

	// start server
	private void startServer() throws IOException {

		// Create a UUID
		UUID uuid = new UUID("1101", true); // serial, SPP
		// UUID uuid = new UUID("1105", true); // obex obj push
		// UUID uuid = new UUID("0003", true); // rfcomm
		// UUID uuid = new UUID("1106", true); // obex file transfer

		// Create the service url
		String connectionString = "btspp://localhost:" + uuid
				+ ";name=Sample SPP Server";

		// open server url
		StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier) Connector
				.open(connectionString);

		// Wait for client connection
		System.out
				.println("\nServer Started. Waiting for clients to connect...");
		StreamConnection connection = streamConnNotifier.acceptAndOpen();

		// connect
		System.out.println("Connecting to client...");
		RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
		try {
			System.out.println("Remote device address: "
					+ dev.getBluetoothAddress());
			System.out.println("Remote device name: "
					+ dev.getFriendlyName(true));
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}

		// read string from spp client
		// InputStream inStream = connection.openInputStream();
		// BufferedReader bReader = new BufferedReader(new
		// InputStreamReader(inStream));
		// String lineRead = bReader.readLine();
		// System.out.println("TEST"+lineRead);

		// read string from spp client
		Thread recvT = new Thread(new recvLoop(connection));
		recvT.start();

		// send response to spp client
		// OutputStream outStream = connection.openOutputStream();
		// PrintWriter pWriter = new PrintWriter(new
		// OutputStreamWriter(outStream));
		// pWriter.write("Response String from SPP Server\r\n");
		// pWriter.flush();

		// send response to spp client
		// Thread sendT = new Thread(new sendLoop(connection));
		// sendT.start();

		// close connection
		// pWriter.close();
		// streamConnNotifier.close();

		System.out.println("\nServer threads started");

		while (true) {
			try {
				Thread.sleep(2000);
				// System.out.println("\nServer looping.");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	} // startServer

	private static class recvLoop implements Runnable {
		private StreamConnection connection = null;
		private InputStream inStream = null;

		public recvLoop(StreamConnection c) {
			this.connection = c;
			try {
				this.inStream = this.connection.openInputStream();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		public void run() {
			while (true) {
				try {

					BufferedReader bReader = new BufferedReader(
							new InputStreamReader(inStream));
					String lineRead = bReader.readLine();
					System.out.println("Server recv: " + lineRead);
					Thread.sleep(500);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	} // recvLoop

	private static class sendLoop implements Runnable {
		private StreamConnection connection = null;
		PrintWriter pWriter = null;

		public sendLoop(StreamConnection c) {
			this.connection = c;
			OutputStream outStream;
			try {
				outStream = this.connection.openOutputStream();
				this.pWriter = new PrintWriter(
						new OutputStreamWriter(outStream));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void run() {
			while (true) {
				try {
					String line = "Response String from SPP Server\r\n"; // "\r\n"
																			// important
					pWriter.write(line);
					pWriter.flush();
					System.out.println("Server send: " + line);
					Thread.sleep(500);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	} // recvLoop

} // class

import java.io.IOException;

public class SprimeBT {

        /**
         * Main
         * 
         * @param args
         */

        // main method of the application
        public static void main(String[] args) throws IOException {

                /*
                 * Test bed for BT classes. Set to true/false for testing
                 */

                if (false) {
                        // scan and print nearby bluetooth devices
                        System.out.println("\n" + "Testing BT Device Discovery" + "\n");
                        BluetoothDeviceDiscovery bluetoothDeviceDiscovery = new BluetoothDeviceDiscovery();
                        bluetoothDeviceDiscovery.listDevices();
                }

                if (false) {
                        // scan and print nearby bluetooth device services
                        System.out.println("\n" + "Testing BT Service Discovery" + "\n");
                        BluetoothServiceDiscovery bluetoothServiceDiscovery = new BluetoothServiceDiscovery();
                        bluetoothServiceDiscovery.listServices();
                }

                if (false) {
                        // start a bluetooth server
                        System.out.println("\n" + "Testing BT Server" + "\n");
                        SimpleSPPServer sppServer = new SimpleSPPServer();
                        sppServer.runServer();
                }

                if (true) {
                        // start a bluetooth client
                        System.out.println("\n" + "Testing BT Client" + "\n");
                        SimpleSPPClient sppClient = new SimpleSPPClient();
                        sppClient.runClient();
                }

        }// end main

}// end class


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值