WTK emulator bluetooth connection - java

I'm developing a J2ME program with eclipse / WTK 2.5.2 and having problem with connecting two emulators using bluetooth. There is one server and one .client running on two different emulators.
The problem is client program cannot discover any bluetooth device. Here is the server and client codes:
public Server()
{
try
{
LocalDevice local = LocalDevice.getLocalDevice();
local.setDiscoverable(DiscoveryAgent.GIAC);
server = (StreamConnectionNotifier)
Connector.open("btspp://localhost:"
+ UUID_STRING + ";name=" + SERVICE_NAME);
Util.Log("EchoServer() Server connector open!");
}
catch (Exception e)
{}
}
after calling Connector.open, I get following warning in console, which i believe is related:
Warning: Unregistered device: unspecified
and client code that searches for devices:
public SearchForDevices(String uuid, String nm)
{
UUIDStr = uuid;
srchServiceName = nm;
try
{
LocalDevice local = LocalDevice.getLocalDevice();
agent = local.getDiscoveryAgent();
deviceList = new Vector();
agent.startInquiry(DiscoveryAgent.GIAC, this); // non-blocking
}
catch (Exception e)
{}
}
system never calls deviceDiscovered, but calls inquiryCompleted() with INQUIRY_COMPLETED parameter, so I suppose client program runs fine.
Bluetooth is enabled at emulator settings..

I tested almost same code from NetBeans IDE 6.8 with WTK 2.5.2_01 emulator and it works well. (I mean it discovered device)
public void startBTServer() {
try
{
LocalDevice local = LocalDevice.getLocalDevice();
local.setDiscoverable(DiscoveryAgent.GIAC);
StreamConnectionNotifier server = (StreamConnectionNotifier)
Connector.open("btspp://localhost:F0E0D0C0B0A000908070605040302010"
+ ";name=" + ";test");
}
catch (Exception e)
{}
}
public void startBTClient() {
String UUIDStr = "F0E0D0C0B0A000908070605040302010";
try
{
LocalDevice local = LocalDevice.getLocalDevice();
DiscoveryAgent agent = local.getDiscoveryAgent();
agent.startInquiry(DiscoveryAgent.GIAC, (DiscoveryListener) this);
}
catch (Exception e)
{}
}
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
System.out.println("device discovered:" + btDevice.toString());
}
This code print out the below log:
From server:
Running in the identified_third_party security domain
Device Bluetooth Address: 0000000DECAF
From client:
Device Bluetooth Address: 0123456789AF
device discovered:RemoteDevice[address=0000000DECAF, name=null, encrypted=false, authenticated=false]

Related

Using AWS in an Android app and running my own Python server on AWS

I've built my Android app and it's nearly done and now I have decided that I'd like to store the Python server I wrote on an AWS server.
Till now the server ran on the same network as the Android app and I connected them with a TCP socket. The server and client work perfectly fine together as long as they're in the same private network.
I tried changing the IP in the socket definition to the public IPv4 of the AWS server I launched and changing the port to the listening port that's defined in the server's code but it couldn't connect.
The server I launched on AWS is EC2 with Ubuntu.
The connection methods I used before:
Connection(){ //a c'tor of the Connection class
serverIP = IP_CONST;
serverPort = PORT_CONST;
try{
serverAddress = InetAddress.getByName(serverIP);
}
catch (UnknownHostException e){
Toast.makeText(getApplicationContext(), "Unknown host", Toast.LENGTH_SHORT).show();
connectionError = true;
}
}
public void run(){
isTheServerFree = false;
try {
if (!connectionError) {
socket = new Socket(serverAddress, serverPort);
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
if (socket == null){
connectionError = true;
}
}
catch (Exception e){
Toast.makeText(getApplicationContext(), "Can't connect", Toast.LENGTH_SHORT).show();
connectionError = true;
}
isTheServerFree = true;
}
}

Thread stucks at serversocket.accept() in android

I want to create communication android app using tcp server-client. I am using android phone as server and linux pc as client, I have created application on linux which works as client.When I Try to create server, it stuck at serversocket.accept(). So client is not able to connect server. I am using following code for server creation
class Thread1 implements Runnable {
int dsport = 48618
#Override
public void run() {
try {
server_socket = new ServerSocket(dsport);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = server_socket.accept();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
And I am using qt creator on client side
void run()
{
Qstring iplist;
QList<QHostAddress> ipadd = QNetworkInterface::allAddress();
socket = new QTcpSocket(this);
connect(socket,SIGNAL(connected()),this,SLOT(newConnection)));
socket->connectToHost(ipadd.at(0),48618);
}
void newConnection()
{
qDebug()<<"socket connected";
}
here ipadd.at(0) gives me local host address. Is there any issue with port I am using? if yes then how to get reliable port for server creation.
How can I resolve this issue ?

Server exception: The connection implementation for btspp cannot be found

I am developing a BluetoothServer using Raspberry, bluecove-2.1.0.jar
java version "1.8.0_06"
Java(TM) SE Runtime Environment (build 1.8.0_06-b23)
Java HotSpot(TM) Client VM (build 25.6-b23, mixed mode)
Here the server java code:
public class BluetoothServer extends Thread {
UUID uuid = new UUID("0000110100001000800000805F9B34FB", false); // This is a magic number
String url = "btspp://localhost:" + uuid.toString() + ";name=xxxx";
Security security = new Security();
/** Constructor */
public BluetoothServer() {
}
#Override
public void run() {
waitForConnection();
}
/** Waiting for connection from devices */
private void waitForConnection() {
// retrieve the local Bluetooth device object
LocalDevice local = null;
StreamConnectionNotifier notifier = null;
StreamConnection connection = null;
// setup the server to listen for connection
try {
local = LocalDevice.getLocalDevice();
local.setDiscoverable(DiscoveryAgent.GIAC); // generally discoverable, discoveryTimeout should be disabled - but isn't.
notifier = (StreamConnectionNotifier) Connector.open(url);
// Bluetooth may go undiscoverable after 180sec default discoveryTimeout, so reset it on separate thread every 179sec.
new Timer().schedule(new TimerTask(){
#Override
public void run() {
try {
LocalDevice.getLocalDevice().setDiscoverable(DiscoveryAgent.GIAC);
} catch (BluetoothStateException e) {
System.out.println("TimerTask exception: " + e.getMessage());
e.printStackTrace();
}
}
}, 0, 179000);
} catch (Exception e) {
System.out.println("Server exception: " + e.getMessage());
e.printStackTrace();
}
// waiting for connection
while (true) {
try {
System.out.println("waiting for connection...");
connection = notifier.acceptAndOpen();
Thread processThread = new Thread(new ProcessConnectionThread(
connection, this));
processThread.start();
System.out.println("processThread.started...");
// bluetooth may have been set undiscoverable after connection
local.setDiscoverable(DiscoveryAgent.GIAC);
} catch (Exception e) {
System.out.println("Server exception: " + e.getMessage());
e.printStackTrace();
return;
}
}
}
public static void main(String[] args) {
System.out.println("Server startup now");
new BluetoothServer().start();
}
public Security getSecurity() {
return security;
}
}
When I Start the server on the command line:
sudo java -cp /jars:/jars/bluetoothserver.jar:/jars/bluecove-2.1.0.jar:/jars/pi4j-core.jar com.bluetoothserver.BluetoothServer
I get this error:
BlueCove version 2.1.0 on bluez
Server exception: The connection implementation for btspp cannot be found.
javax.microedition.io.ConnectionNotFoundException: The connection implementation for btspp cannot be found.
at javax.microedition.io.Connector.open(Connector.java:238)
at javax.microedition.io.Connector.open(Connector.java:181)
at javax.microedition.io.Connector.open(Connector.java:162)
at com.bluetoothserver.BluetoothServer.waitForConnection(BluetoothServer.java:56)
at com.bluetoothserver.BluetoothServer.run(BluetoothServer.java:32)
waiting for connection...
Server exception: null
java.lang.NullPointerException
at com.bluetoothserver.BluetoothServer.waitForConnection(BluetoothServer.java:87)
at com.bluetoothserver.BluetoothServer.run(BluetoothServer.java:32)
Any ideas ? Thanks
Had the same issue.
JDK 1.8.0_06 has the implementation of javax.microedition.io.Connector in it's rt.jar. In my case the solution was to remove javax.microedition package from rt.jar to use BlueCove implementation.

acceptAndOpen() method error

I am making a bluetooth related application to browse the internet.. With Server as laptop/desktop and client as the mobile phone.. i need to establish a connection between client and server.. but the execution of the server suddenly stops at the method acceptAndOpen() .. Please help to solve the problem.. this is the code where it stops in the server side:
while (mServerState) {
StreamConnection btConn = null;
try {
updateStatus("[server:] Now waiting for a client to connect");
//here is the error
btConn = (StreamConnection) btServerNotifier.acceptAndOpen();
RemoteDevice dev = RemoteDevice.getRemoteDevice(btConn);
System.out.println("Remote device address: " + dev.getBluetoothAddress());
updateStatus("Remote device " + dev.getFriendlyName(true) + "connected");
} catch (IOException ioe) {
}
if (btConn != null) {
processConnection(btConn);
}
}

Android application Wi-Fi device - AP connectivity

I am building an application which can transfer data between a mobile and a Wi-Fi device... The mobile has got the AP enabled (through code) and another device connects to this specific network... How can I detect through code to see the details of the devices connected to the network(AP)?** Is there a solution for this?
I have seen an application called Wifi Hot spot in HTC Desire that does this functionality of showing the IP addresses of the devices connected to the network. How can this be achieved?
Check out Review: Sprint Mobile Hotspot on HTC EVO 4G.
It shows an application that can actually display the connected users. How can we do that programmatically? Is there an API for that?
For creating an access point:
private void createWifiAccessPoint() {
if (wifiManager.isWifiEnabled())
{
wifiManager.setWifiEnabled(false);
}
Method[] wmMethods = wifiManager.getClass().getDeclaredMethods(); //Get all declared methods in WifiManager class
boolean methodFound = false;
for (Method method: wmMethods){
if (method.getName().equals("setWifiApEnabled")){
methodFound = true;
WifiConfiguration netConfig = new WifiConfiguration();
netConfig.SSID = "\""+ssid+"\"";
netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
//netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
//netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
//netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
//netConfig.preSharedKey = password;
//netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
//netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
//netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
//netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
try {
boolean apstatus = (Boolean) method.invoke(wifiManager, netConfig,true);
//statusView.setText("Creating a Wi-Fi Network \""+netConfig.SSID+"\"");
for (Method isWifiApEnabledmethod: wmMethods)
{
if (isWifiApEnabledmethod.getName().equals("isWifiApEnabled")){
while (!(Boolean)isWifiApEnabledmethod.invoke(wifiManager)){
};
for (Method method1: wmMethods){
if(method1.getName().equals("getWifiApState")){
int apstate;
apstate = (Integer)method1.invoke(wifiManager);
// netConfig = (WifiConfiguration)method1.invoke(wifi);
//statusView.append("\nSSID:"+netConfig.SSID+"\nPassword:"+netConfig.preSharedKey+"\n");
}
}
}
}
if(apstatus)
{
System.out.println("SUCCESSdddd");
//statusView.append("\nAccess Point Created!");
//finish();
//Intent searchSensorsIntent = new Intent(this,SearchSensors.class);
//startActivity(searchSensorsIntent);
}
else
{
System.out.println("FAILED");
//statusView.append("\nAccess Point Creation failed!");
}
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
if (!methodFound){
//statusView.setText("Your phone's API does not contain setWifiApEnabled method to configure an access point");
}
}
You could read the /proc/net/arp file to read all the ARP entries. See the example in the blog post Android: Howto find the hardware MAC address of a remote host. In the ARP table, search for all the hosts that belong to your Wi-Fi network based on the IP address.
Here is example code, which counts the number of hosts connected to the AP. This code assumes that one ARP entry is for the phone connected to the network and the remaining ones are from hosts connected to the AP.
private int countNumMac()
{
int macCount = 0;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("/proc/net/arp"));
String line;
while ((line = br.readLine()) != null) {
String[] splitted = line.split(" +");
if (splitted != null && splitted.length >= 4) {
// Basic sanity check
String mac = splitted[3];
if (mac.matches("..:..:..:..:..:..")) {
macCount++;
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
if (macCount == 0)
return 0;
else
return macCount-1; //One MAC address entry will be for the host.
}
You could ping the device if you know its host-name or its IP address.
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("ping -c 1 " + hostname);
proc.waitFor();
You could do an IP address scan, trying every IP address on the network for a response using a ping like above or trying to connect using TCP or UDP.
If you know the MAC address, you could use the ARP table.
If you got some own software running on the devices, you could send out UDP packets on every device and listen for them on your Android device. See Sending and receiving UDP broadcast packets in Android on how to do this.
You can use accesspoint:
WifiApControl apControl = WifiApControl.getInstance(context);
// These are cached and may no longer be connected, see
// WifiApControl.getReachableClients(int, ReachableClientListener)
List<WifiApControl.Client> clients = apControl.getClients()

Categories