List of usage examples for android.bluetooth BluetoothDevice createRfcommSocketToServiceRecord
@RequiresPermission(Manifest.permission.BLUETOOTH) public BluetoothSocket createRfcommSocketToServiceRecord(UUID uuid) throws IOException
From source file:edu.stanford.junction.provider.bluetooth.Junction.java
private BluetoothSocket createBluetoothSocket(BluetoothDevice device, UUID uuid) throws IOException { BluetoothSocket tmp;/*w ww . j a v a2 s . com*/ if (mConfig.securePairingRequired() || VERSION.SDK_INT < VERSION_CODES.GINGERBREAD_MR1) { tmp = device.createRfcommSocketToServiceRecord(uuid); if (DBG) Log.d(TAG, "Using secure bluetooth socket"); } else { try { // compatibility with pre SDK 10 devices Method listener = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", UUID.class); tmp = (BluetoothSocket) listener.invoke(device, uuid); if (DBG) Log.d(TAG, "Using insecure bluetooth socket"); } catch (NoSuchMethodException e) { Log.wtf(TAG, "createInsecureRfcommSocketToServiceRecord not found"); throw new IOException(e); } catch (InvocationTargetException e) { Log.wtf(TAG, "createInsecureRfcommSocketToServiceRecord not available on mBtAdapter"); throw new IOException(e); } catch (IllegalAccessException e) { Log.wtf(TAG, "createInsecureRfcommSocketToServiceRecord not available on mBtAdapter"); throw new IOException(e); } } return tmp; }
From source file:com.google.android.apps.mytracks.util.Api8Adapter.java
@Override public BluetoothSocket getBluetoothSocket(BluetoothDevice bluetoothDevice) throws IOException { try {//from w w w.ja v a 2 s .co m Class<? extends BluetoothDevice> c = bluetoothDevice.getClass(); Method insecure = c.getMethod("createInsecureRfcommSocket", Integer.class); insecure.setAccessible(true); return (BluetoothSocket) insecure.invoke(bluetoothDevice, 1); } catch (SecurityException e) { Log.d(Constants.TAG, "Unable to create insecure connection", e); } catch (NoSuchMethodException e) { Log.d(Constants.TAG, "Unable to create insecure connection", e); } catch (IllegalArgumentException e) { Log.d(Constants.TAG, "Unable to create insecure connection", e); } catch (IllegalAccessException e) { Log.d(Constants.TAG, "Unable to create insecure connection", e); } catch (InvocationTargetException e) { Log.d(Constants.TAG, "Unable to create insecure connection", e); } return bluetoothDevice.createRfcommSocketToServiceRecord(BluetoothConnectionManager.MY_TRACKS_UUID); }
From source file:mobi.monaca.framework.plugin.BluetoothPlugin.java
/** * Execute a bluetooth function/*from w w w. j a v a 2s. c o m*/ */ @Override public PluginResult execute(String action, JSONArray args, String callbackId) { PluginResult pluginResult = null; Log.d("BluetoothPlugin", "Action: " + action); if (ACTION_ENABLE.equals(action)) { // Check if bluetooth isn't disabled already if (!m_bluetoothAdapter.isEnabled()) { m_stateChanging = true; ctx.startActivityForResult(this, new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), 1); while (m_stateChanging) { } ; } // Check if bluetooth is enabled now if (m_bluetoothAdapter.isEnabled()) { pluginResult = new PluginResult(PluginResult.Status.OK); } else { pluginResult = new PluginResult(PluginResult.Status.ERROR); } } // Want to disable bluetooth? else if (ACTION_DISABLE.equals(action)) { if (!m_bluetoothAdapter.disable() && m_bluetoothAdapter.isEnabled()) { pluginResult = new PluginResult(PluginResult.Status.ERROR); } else { pluginResult = new PluginResult(PluginResult.Status.OK); } } else if (ACTION_DISCOVERDEVICES.equals(action)) { m_discoveredDevices = new JSONArray(); if (!m_bluetoothAdapter.startDiscovery()) { pluginResult = new PluginResult(PluginResult.Status.ERROR, "Unable to start discovery"); } else { m_discovering = true; // Wait for discovery to finish while (m_discovering) { } Log.d("BluetoothPlugin", "DiscoveredDevices: " + m_discoveredDevices.length()); pluginResult = new PluginResult(PluginResult.Status.OK, m_discoveredDevices); } } // Want to list UUIDs of a certain device else if (ACTION_GETUUIDS.equals(action)) { try { String address = args.getString(0); Log.d("BluetoothPlugin", "Listing UUIDs for: " + address); // Fetch UUIDs from bluetooth device BluetoothDevice bluetoothDevice = m_bluetoothAdapter.getRemoteDevice(address); Method m = bluetoothDevice.getClass().getMethod("fetchUuidsWithSdp"); Log.d("BluetoothPlugin", "Method: " + m); m.invoke(bluetoothDevice); m_gettingUuids = true; while (m_gettingUuids) { } pluginResult = new PluginResult(PluginResult.Status.OK, m_gotUUIDs); } catch (Exception e) { Log.e("BluetoothPlugin", e.toString() + " / " + e.getMessage()); pluginResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); } } // Connect to a given device & uuid endpoint else if (ACTION_CONNECT.equals(action)) { try { String address = args.getString(0); UUID uuid = UUID.fromString(args.getString(1)); Log.d("BluetoothPlugin", "Connecting..."); BluetoothDevice bluetoothDevice = m_bluetoothAdapter.getRemoteDevice(address); BluetoothSocket bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(uuid); bluetoothSocket.connect(); m_bluetoothSockets.add(bluetoothSocket); int socketId = m_bluetoothSockets.indexOf(bluetoothSocket); pluginResult = new PluginResult(PluginResult.Status.OK, socketId); } catch (Exception e) { Log.e("BluetoothPlugin", e.toString() + " / " + e.getMessage()); pluginResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); } } else if (ACTION_READ.equals(action)) { try { int socketId = args.getInt(0); BluetoothSocket bluetoothSocket = m_bluetoothSockets.get(socketId); InputStream inputStream = bluetoothSocket.getInputStream(); char[] buffer = new char[128]; for (int i = 0; i < buffer.length; i++) { buffer[i] = (char) inputStream.read(); } //Log.d( "BluetoothPlugin", "Buffer: " + String.valueOf(buffer) ); pluginResult = new PluginResult(PluginResult.Status.OK, String.valueOf(buffer)); } catch (Exception e) { Log.e("BluetoothPlugin", e.toString() + " / " + e.getMessage()); pluginResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); } } else if (ACTION_DISCONNECT.equals(action)) { try { int socketId = args.getInt(0); // Fetch socket & close it BluetoothSocket bluetoothSocket = m_bluetoothSockets.get(socketId); bluetoothSocket.close(); // Remove socket from internal list m_bluetoothSockets.remove(socketId); // Everything went fine... pluginResult = new PluginResult(PluginResult.Status.OK); } catch (Exception e) { Log.e("BluetoothPlugin", e.toString() + " / " + e.getMessage()); pluginResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); } } return pluginResult; }
From source file:org.thecongers.mcluster.MainActivity.java
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException { if (Build.VERSION.SDK_INT >= 10) { try {/*from w w w. ja v a 2 s . c o m*/ final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class }); return (BluetoothSocket) m.invoke(device, MY_UUID); } catch (Exception e) { Log.e(TAG, "Could not create insecure RFComm Connection", e); } } return device.createRfcommSocketToServiceRecord(MY_UUID); }
From source file:org.metawatch.manager.MetaWatchService.java
@TargetApi(10) private boolean connect() { try {/* w w w. j a va 2 s. c o m*/ if (!Preferences.loaded) loadPreferences(this); MetaWatchService.fakeWatch = false; if (Preferences.watchMacAddress.equals("DIGITAL")) { MetaWatchService.fakeWatch = true; MetaWatchService.watchType = WatchType.DIGITAL; } if (Preferences.watchMacAddress.equals("ANALOG")) { MetaWatchService.fakeWatch = true; MetaWatchService.watchType = WatchType.ANALOG; } if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "Remote device address: '" + Preferences.watchMacAddress + "'"); if (!MetaWatchService.fakeWatch) { if (bluetoothAdapter == null) bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); BluetoothDevice bluetoothDevice = bluetoothAdapter.getRemoteDevice(Preferences.watchMacAddress); int currentapiVersion = android.os.Build.VERSION.SDK_INT; if (Preferences.skipSDP) { Method method; if (Preferences.insecureBtSocket && currentapiVersion >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) { method = bluetoothDevice.getClass().getMethod("createInsecureRfcommSocket", new Class[] { int.class }); } else { method = bluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[] { int.class }); } bluetoothSocket = (BluetoothSocket) method.invoke(bluetoothDevice, 1); } else { UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); if (Preferences.insecureBtSocket && currentapiVersion >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) { bluetoothSocket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(uuid); } else { bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(uuid); } } bluetoothAdapter.cancelDiscovery(); bluetoothSocket.connect(); inputStream = bluetoothSocket.getInputStream(); outputStream = bluetoothSocket.getOutputStream(); } connectionState = ConnectionState.CONNECTED; setPreviousConnectionState(this, true); updateNotification(); Protocol.getInstance(MetaWatchService.this).getDeviceType(); NavigationManagement.processWatchConnection(this); // Unblock the message protocol queue, and the notification queue. mPauseQueue.open(); return true; } catch (IOException ioexception) { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, ioexception.toString()); } catch (SecurityException e) { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, e.toString()); } catch (NoSuchMethodException e) { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, e.toString()); } catch (IllegalArgumentException e) { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, e.toString()); } catch (IllegalAccessException e) { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, e.toString()); } catch (InvocationTargetException e) { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, e.toString()); } catch (NullPointerException e) { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, e.toString()); } finally { } return false; }
From source file:com.megster.cordova.BluetoothPlugin.java
/** * Execute a bluetooth function/*from w ww.j a v a2 s . co m*/ */ @SuppressWarnings({ "null", "deprecation" }) @Override public PluginResult execute(String action, JSONArray args, String callbackId) { PluginResult pluginResult = null; //Log.d("BluetoothPlugin", "Action: " + action); // Check if bluetooth is supported at all if (m_bluetoothAdapter == null) { pluginResult = new PluginResult(PluginResult.Status.ILLEGAL_ACCESS_EXCEPTION, "No bluetooth adapter found"); } else { if (ACTION_ENABLE.equals(action)) { // Check if bluetooth isn't disabled already if (!m_bluetoothAdapter.isEnabled()) { m_stateChanging = true; ctx.startActivityForResult(this, new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), 1); while (m_stateChanging) { } ; } // Check if bluetooth is enabled now if (m_bluetoothAdapter.isEnabled()) { //start(); pluginResult = new PluginResult(PluginResult.Status.OK, "OK"); } else { pluginResult = new PluginResult(PluginResult.Status.ERROR, "Bluetooth not enabled"); } } // Want to disable bluetooth? else if (ACTION_DISABLE.equals(action)) { if (!m_bluetoothAdapter.disable() && m_bluetoothAdapter.isEnabled()) { pluginResult = new PluginResult(PluginResult.Status.ERROR, "Unable to disable bluetooth"); } else { pluginResult = new PluginResult(PluginResult.Status.OK, "OK"); } } else if (ACTION_DISCOVERDEVICES.equals(action)) { m_discoveredDevices = new JSONArray(); if (!m_bluetoothAdapter.startDiscovery()) { pluginResult = new PluginResult(PluginResult.Status.ERROR, "Unable to start discovery"); } else { m_discovering = true; // Wait for discovery to finish while (m_discovering) { } Log.d("BluetoothPlugin", "DiscoveredDevices: " + m_discoveredDevices.length()); pluginResult = new PluginResult(PluginResult.Status.OK, m_discoveredDevices); } } // Want to list UUIDs of a certain device else if (ACTION_GETUUIDS.equals(action)) { try { String address = args.getString(0); Log.d("BluetoothPlugin", "Listing UUIDs for: " + address); // Fetch UUIDs from bluetooth device BluetoothDevice bluetoothDevice = m_bluetoothAdapter.getRemoteDevice(address); Method m = bluetoothDevice.getClass().getMethod("fetchUuidsWithSdp"); Log.d("BluetoothPlugin", "Method: " + m); m.invoke(bluetoothDevice); m_gettingUuids = true; while (m_gettingUuids) { } pluginResult = new PluginResult(PluginResult.Status.OK, m_gotUUIDs); } catch (Exception e) { Log.e("BluetoothPlugin", e.toString() + " / " + e.getMessage()); pluginResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); } } else if (ACTION_GETBONDEDDEVICES.equals(action)) { JSONArray bondedDevices = new JSONArray(); Log.d("BluetoothPlugin", "Getting Bonded List..."); Set<BluetoothDevice> bondSet = m_bluetoothAdapter.getBondedDevices(); for (Iterator<BluetoothDevice> it = bondSet.iterator(); it.hasNext();) { BluetoothDevice bluetoothDevice = (BluetoothDevice) it.next(); JSONObject deviceInfo = new JSONObject(); try { deviceInfo.put("name", bluetoothDevice.getName()); deviceInfo.put("address", bluetoothDevice.getAddress()); deviceInfo.put("isBonded", true); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } bondedDevices.put(deviceInfo); pluginResult = new PluginResult(PluginResult.Status.OK, bondedDevices); } } // Connect to a given device & uuid endpoint else if (ACTION_CONNECT.equals(action)) { try { String address = args.getString(0); UUID uuid = UUID.fromString(args.getString(1)); //UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); Log.d("BluetoothPlugin", "Connecting..."); BluetoothDevice bluetoothDevice = m_bluetoothAdapter.getRemoteDevice(address); BluetoothSocket bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(uuid); bluetoothSocket.connect(); m_bluetoothSockets.add(bluetoothSocket); int socketId = m_bluetoothSockets.indexOf(bluetoothSocket); pluginResult = new PluginResult(PluginResult.Status.OK, socketId); } catch (Exception e) { Log.e("BluetoothPlugin", e.toString() + " / " + e.getMessage()); pluginResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); } } else if (ACTION_READ.equals(action)) { try { int socketId = args.getInt(0); //Log.d( "BluetoothPlugin", "Get Data..." ); BluetoothSocket bluetoothSocket = m_bluetoothSockets.get(socketId); InputStream inputStream = bluetoothSocket.getInputStream(); Calendar cal = Calendar.getInstance(); Date startTime = cal.getTime(); byte[] buffer = new byte[1024]; // char [] buffer = new char[1024]; String recvdString = ""; int i = 0; int k = 0; int byteCnt = 0; boolean j = true; char buf = 0; boolean timeOut = false; while (j) { Calendar newCal = Calendar.getInstance(); Date endTime = newCal.getTime(); if ((endTime.getTime() - startTime.getTime()) < 60000) { if (inputStream.available() > 0) { // Log.d( "BluetoothPlugin", "Time Increment: " + format.format(endTime)); i += inputStream.read(buffer, k, inputStream.available()); k = i; Log.d("BluetoothPlugin", "i=" + i); buf = (char) (buffer[i - 1] & 0xFF); Log.d("BluetoothPlugin", "buf=" + Integer.toHexString(buffer[i - 1] & 0xFF)); if ((buf == '#') || (buf == 0x0A) || (buf == (char) 0xBB) || (buf == (char) 0xAA)) { //if (timeOut == true) Log.d( "BluetoothPlugin", "Time Out"); j = false; } } } else { timeOut = true; j = false; } /* buffer[i]= (char) inputStream.read(); if ((buffer[i] == '#') || (buffer[i]==0x0A)) { j=false; } i++; */ } if (timeOut) { Log.d("BluetoothPlugin", "Time Out"); recvdString = "Timeout"; } else { byteCnt = i; recvdString = new String(buffer, 0, i);//.toString();//"KBytes" + byteCnt; i = 0; String stringByteCnt = String.valueOf(byteCnt); } //buffer = b.toString(); Log.d("BluetoothPlugin", "String: " + recvdString); pluginResult = new PluginResult(PluginResult.Status.OK, recvdString); } catch (Exception e) { Log.e("BluetoothPlugin", e.toString() + " / " + e.getMessage()); pluginResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); } } else if (ACTION_READ2.equals(action)) { try { int socketId = args.getInt(0); Calendar cal = Calendar.getInstance(); Date startTime = cal.getTime(); //Log.d( "BluetoothPlugin", "Get Data..." ); BluetoothSocket bluetoothSocket = m_bluetoothSockets.get(socketId); InputStream inputStream = bluetoothSocket.getInputStream(); // DataInputStream dataInputStream = new DataInputStream(inputStream); //char[] buffer = new char[15000]; byte[] buf = new byte[55000]; //byte[] buffer2 = new byte[128]; String recvdString = ""; int i = 0; int k = 0; int byteCnt = 0; boolean j = true; SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Log.d("BluetoothPlugin", "StartTime: " + format.format(startTime)); boolean timeOut = false; while (j) { Calendar newCal = Calendar.getInstance(); Date endTime = newCal.getTime(); if ((endTime.getTime() - startTime.getTime()) < 12000) { if (inputStream.available() > 0) { // Log.d( "BluetoothPlugin", "Time Increment: " + format.format(endTime)); i += inputStream.read(buf, k, inputStream.available()); k = i; Log.d("BluetoothPlugin", "i=" + i); } //Log.d( "BluetoothPlugin", "i="+dataInputStream); //inputStream.close(); if (i > 51180) { //Log.d( "BluetoothPlugin", "i="+i); j = false; //i++; } } else { j = false; timeOut = true; Log.d("BluetoothPlugin", "ECG Read TimeOut"); } } if (timeOut) { recvdString = "Aborted"; } else { File ecgPath = Environment.getExternalStorageDirectory(); File ecg = new File(ecgPath, "/prago/ecg.txt"); FileWriter fos = new FileWriter(ecg, false); String stringBuf = new String(""); //long byteCnt byteCnt = (i - 1) / 3; long[] buf2 = new long[byteCnt]; for (k = 0; k < byteCnt; k++) { int firstByte = 0; int secondByte = 0; int thirdByte = 0; int fourthByte = 0; int index = k * 3; firstByte = (0x000000FF & ((int) buf[index + 1])); secondByte = (0x000000FF & ((int) buf[index + 2])); thirdByte = (0x000000FF & ((int) buf[index + 3])); buf2[k] = ((long) (firstByte << 16 | secondByte << 8 | thirdByte)) & 0xFFFFFFFFL; stringBuf = buf2[k] + ","; fos.write(stringBuf); } fos.flush(); fos.close(); byteCnt = i; recvdString = ecg.getPath(); } i = 0; pluginResult = new PluginResult(PluginResult.Status.OK, recvdString); } catch (Exception e) { Log.e("BluetoothPlugin", e.toString() + " / " + e.getMessage()); pluginResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); } } else if (ACTION_READ3.equals(action)) { try { int socketId = args.getInt(0); Log.d("BluetoothPlugin", "Get Steth Data..."); BluetoothSocket bluetoothSocket = m_bluetoothSockets.get(socketId); //bluetoothSocket.close(); //bluetoothSocket = m_bluetoothSockets.get(socketId); //bluetoothSocket.connect(); InputStream inputStream = bluetoothSocket.getInputStream(); //inputStream.reset(); //int server_port = 9999; //DatagramSocket s = new DatagramSocket(); //InetAddress local = InetAddress.getByName("192.168.2.7"); //s.connect(local,server_port); //int msg_length=messageStr.length(); //byte[] message = messageStr.getBytes(); //char[] buffer = new char[15000]; //byte [] buf = new byte[10000]; //byte[] buffer2 = new byte[128]; // String recvdString; Calendar cal = Calendar.getInstance(); //byte [] buf = new byte[245000]; Date startTime = cal.getTime(); String recvdString = ""; int i = 0; int endofFileDetect = 0; byte[] firstChar = new byte[1]; int writetoFile = 0; int k = 0; long finalbytes = 0; boolean startdetect = false; int byteCnt = 0; boolean j = true; boolean ecgRec = false; byte[] buf = new byte[10000]; firstChar[0] = 0x52; File stethPath = Environment.getExternalStorageDirectory(); File steth = new File(stethPath, "/prago/steth.wav"); FileOutputStream fos = new FileOutputStream(steth); while (j) { Calendar newCal = Calendar.getInstance(); Date endTime = newCal.getTime(); if ((endTime.getTime() - startTime.getTime()) < 90000) { if (inputStream.available() > 0) { //Log.d( "BluetoothPlugin", "inputStream.available="+inputStream.available()); //byte [] buf = new byte[inputStream.available()]; k = inputStream.read(buf, 0, inputStream.available()); //Log.d( "BluetoothPlugin", "buf[0]="+buf[0]); if ((writetoFile == 0)) { if ((buf[0] & 0xFF) == 0x52) { if (k > 1) { if ((buf[1] & 0xFF) == 0x49) { writetoFile = 1; i = 0; } } else { startdetect = true; } } else if (((buf[0] & 0xFF) == 0x49) && startdetect == true) { fos.write(firstChar, 0, 1); writetoFile = 1; i = 0; } else { startdetect = false; } } if (writetoFile == 1) { i += k; //Log.d( "BluetoothPlugin", "i="+i); //Log.d( "BluetoothPlugin", "k="+k); fos.write(buf, 0, k); //if (k>1)Log.d( "BluetoothPlugin", "buf[k-2]="+Integer.toHexString(buf[k-2]&0xFF)); //Log.d( "BluetoothPlugin", "buf[k-1]="+Integer.toHexString(buf[k-1]&0xFF)); if ((k > 1) && ((buf[k - 2] & 0xFF) == 0xAA) && ((buf[k - 1] & 0xFF) == 0xBB)) { endofFileDetect = 2; // Log.d( "BluetoothPlugin", "EoF Detected Multibyte"); } else if ((k == 1) && ((buf[0] & 0xFF) == 0xAA)) { endofFileDetect = 1; // Log.d( "BluetoothPlugin", "EoF Detected Firstbyte"); } else if (((buf[0] & 0xFF) == 0xBB) && (endofFileDetect == 1)) { endofFileDetect += 1; // Log.d( "BluetoothPlugin", "EoF Detected Sectbyte"); } else { endofFileDetect = 0; } if (endofFileDetect == 2) { Log.d("BluetoothPlugin", "File Write Complete"); //Log.d( "BluetoothPlugin", "i="+i); fos.flush(); fos.close(); j = false; //i++; recvdString = steth.getPath(); } } // DatagramPacket p = new DatagramPacket(buf, k,local,server_port); // s.send(p);// DataInputStream dataInputStream = new DataInputStream(inputStream); } //Log.d( "BluetoothPlugin", "i="+dataInputStream); //inputStream.close(); } else { j = false; //timeOut=true; Log.d("BluetoothPlugin", "Steth Read TimeOut"); //bluetoothSocket.close(); // recvdString= "Aborted"; fos.flush(); fos.close(); recvdString = steth.getPath(); } } pluginResult = new PluginResult(PluginResult.Status.OK, recvdString); } catch (Exception e) { Log.e("BluetoothPlugin", e.toString() + " / " + e.getMessage()); pluginResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); } } //--change--// else if (ACTION_READ5.equals(action)) { try { int socketId = args.getInt(0); Log.d("BluetoothPlugin", "Transfer Steth Data..."); BluetoothSocket bluetoothSocket = m_bluetoothSockets.get(socketId); //bluetoothSocket.close(); //bluetoothSocket = m_bluetoothSockets.get(socketId); //bluetoothSocket.connect(); InputStream inputStream = bluetoothSocket.getInputStream(); //inputStream.reset(); //int server_port = 9999; //DatagramSocket s = new DatagramSocket(); //InetAddress local = InetAddress.getByName("192.168.2.7"); //s.connect(local,server_port); //int msg_length=messageStr.length(); //byte[] message = messageStr.getBytes(); //char[] buffer = new char[15000]; //byte [] buf = new byte[10000]; //byte[] buffer2 = new byte[128]; //String recvdString; Calendar cal = Calendar.getInstance(); //byte [] buf = new byte[245000]; Date startTime = cal.getTime(); String recvdString = ""; int i = 0; int endofFileDetect = 0; byte[] firstChar = new byte[1]; int writetoFile = 0; int k = 0; long finalbytes = 0; boolean startdetect = false; int byteCnt = 0; boolean j = true; boolean ecgRec = false; byte[] buf = new byte[10000]; firstChar[0] = 0x52; File stethPath = Environment.getExternalStorageDirectory(); File steth = new File(stethPath, "/prago/steth.wav"); FileOutputStream fos = new FileOutputStream(steth); while (j) { Calendar newCal = Calendar.getInstance(); Date endTime = newCal.getTime(); if ((endTime.getTime() - startTime.getTime()) < 5000) { if (inputStream.available() > 0) { // Log.d( "BluetoothPlugin", "inputStream.available="+inputStream.available()); cal = Calendar.getInstance(); startTime = cal.getTime(); //byte [] buf = new byte[inputStream.available()]; k = inputStream.read(buf, 0, inputStream.available()); //Log.d( "BluetoothPlugin", "buf[0]="+buf[0]); if ((writetoFile == 0)) { if ((buf[0] & 0xFF) == 0x52) { if (k > 1) { if ((buf[1] & 0xFF) == 0x49) { writetoFile = 1; i = 0; } } else { startdetect = true; } } else if (((buf[0] & 0xFF) == 0x49) && startdetect == true) { fos.write(firstChar, 0, 1); writetoFile = 1; i = 0; } else { startdetect = false; } } if (writetoFile == 1) { i += k; //Log.d( "BluetoothPlugin", "i="+i); //Log.d( "BluetoothPlugin", "k="+k); fos.write(buf, 0, k); //if (k>1)Log.d( "BluetoothPlugin", "buf[k-2]="+Integer.toHexString(buf[k-2]&0xFF)); //Log.d( "BluetoothPlugin", "buf[k-1]="+Integer.toHexString(buf[k-1]&0xFF)); if ((k > 1) && ((buf[k - 2] & 0xFF) == 0xAA) && ((buf[k - 1] & 0xFF) == 0xBB)) { endofFileDetect = 2; // Log.d( "BluetoothPlugin", "EoF Detected Multibyte"); } else if ((k == 1) && ((buf[0] & 0xFF) == 0xAA)) { endofFileDetect = 1; // Log.d( "BluetoothPlugin", "EoF Detected Firstbyte"); } else if (((buf[0] & 0xFF) == 0xBB) && (endofFileDetect == 1)) { endofFileDetect += 1; // Log.d( "BluetoothPlugin", "EoF Detected Sectbyte"); } else { endofFileDetect = 0; } if (endofFileDetect == 2) { Log.d("BluetoothPlugin", "File Write Complete"); //Log.d( "BluetoothPlugin", "i="+i); fos.flush(); fos.close(); j = false; //i++; recvdString = steth.getPath(); } } // DatagramPacket p = new DatagramPacket(buf, k,local,server_port); // s.send(p);// DataInputStream dataInputStream = new DataInputStream(inputStream); } //Log.d( "BluetoothPlugin", "i="+dataInputStream); //inputStream.close(); } else { j = false; //timeOut=true; Log.d("BluetoothPlugin", "Steth Read TimeOut"); //bluetoothSocket.close(); // recvdString= "Aborted"; fos.flush(); fos.close(); recvdString = steth.getPath(); } } pluginResult = new PluginResult(PluginResult.Status.OK, recvdString); } catch (Exception e) { Log.e("BluetoothPlugin", e.toString() + " / " + e.getMessage()); pluginResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); } } //--change--// else if (ACTION_READ4.equals(action)) { try { start(); // int socketId = args.getInt(0); Log.d("BluetoothPlugin", "Make Discoverable"); BluetoothAdapter mBluetoothAdapter = null; ctx.startActivityForResult(this, new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE), 1); m_discoverable = true; Calendar cal = Calendar.getInstance(); Date startTime = cal.getTime(); Calendar newCal = Calendar.getInstance(); String recvdString = ""; Date endTime = newCal.getTime(); while (m_discoverable && ((endTime.getTime() - startTime.getTime()) < 32000)) { newCal = Calendar.getInstance(); endTime = newCal.getTime(); } if (m_discoverable) { recvdString = "No Device"; } else { Log.d("BluetoothPlugin", "Connected with Remote Device"); BluetoothSocket bluetoothSocket = bluetoothListenSocket; InputStream inputStream = bluetoothSocket.getInputStream(); int i = 0; int k = 0; boolean j = true; boolean measurementComplete = false; // boolean measurementOngoing = false; boolean measurementStart = false; float decweight = 0; int[] buf = new int[100]; while (!measurementComplete) { buf[i] = inputStream.read(); if ((i > 5) && (buf[i] == 0x02) && (buf[i - 6] == 0x93) && (buf[i - 1] == 0x00) && !measurementStart) { measurementStart = true; } if (measurementStart && (buf[i - 1] == 0x04) && (buf[i - 7] == 0x93) && (buf[i - 2] == 0x0)) { measurementComplete = true; measurementStart = false; // measurementOngoing = false; decweight = (buf[i - 10] << 8) + buf[i - 9]; } i++; Log.d("BluetoothPlugin", "i=" + i); } // String recvdString= new String(buf,0,i,"ISO-8859-1");;//new String(buf,0,i,"ISO-8859-1");//.toString();//"KBytes" + byteCnt; float weight = decweight / 100; //weight += decweight/100; recvdString = "" + weight; bluetoothSocket.close(); Log.d("BluetoothPlugin", "Disconnected with Remote Device"); } pluginResult = new PluginResult(PluginResult.Status.OK, recvdString); } catch (Exception e) { Log.e("BluetoothPlugin", e.toString() + " / " + e.getMessage()); pluginResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); } } else if (ACTION_WRITE.equals(action)) { try { int socketId = args.getInt(0); byte[] value = { 0x11, 0x0d, 0x44, 0x4d, 0x50 }; // byte[] value = {(byte)0x11,(byte)0x0D, (byte)0x0A, (byte)0x44, (byte)0x4D, (byte)0x46}; String string = new String(value); char sendCmd = 'g'; byte sendCmdByte = (byte) sendCmd;//.getBytes("UTF-16LE"); byte[] data = args.getString(1).getBytes("UTF-8"); if (data[0] == sendCmdByte) { data = value; Log.d("BluetoothPlugin", "Sending Onetouch Ultra2 Commands..."); } else if (data[0] == 'e') { data = args.getString(1).getBytes("UTF-8"); //Log.d( "BluetoothPlugin", "Sending +tronic Commands..." + args.getString(1)); } else { data = args.getString(1).getBytes("UTF-16LE"); //Log.d( "BluetoothPlugin", "Sending +tronic Commands..." + args.getString(1)); } //Log.d( "BluetoothPlugin", "Write Data..." + string ); BluetoothSocket bluetoothSocket = m_bluetoothSockets.get(socketId); OutputStream outputStream = bluetoothSocket.getOutputStream(); outputStream.write(data); outputStream.flush(); //outputStream.close(); //Log.d( "BluetoothPlugin", "Buffer: " + String.valueOf(buffer) ); pluginResult = new PluginResult(PluginResult.Status.OK, "Success"); } catch (Exception e) { Log.e("BluetoothPlugin", e.toString() + " / " + e.getMessage()); pluginResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); } } else if (ACTION_DISCONNECT.equals(action)) { try { int socketId = args.getInt(0); // Fetch socket & close it BluetoothSocket bluetoothSocket = m_bluetoothSockets.get(socketId); bluetoothSocket.close(); // Remove socket from internal list m_bluetoothSockets.remove(socketId); // Everything went fine... pluginResult = new PluginResult(PluginResult.Status.OK, "OK"); } catch (Exception e) { Log.e("BluetoothPlugin", e.toString() + " / " + e.getMessage()); pluginResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); } } else { pluginResult = new PluginResult(PluginResult.Status.INVALID_ACTION, "Action '" + action + "' not supported"); } } return pluginResult; }
From source file:com.nest5.businessClient.Initialactivity.java
@Override public void onDeviceSelected(String address) { // TODO Auto-generated method stub Toast.makeText(this, "address--->" + address, Toast.LENGTH_SHORT).show(); // Get the BLuetoothDevice object BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); try {/* w ww . jav a 2 s. com*/ device.createRfcommSocketToServiceRecord(uuid); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // Attempt to connect to the device mChatService.connect(device); //mSerialService.connect(device); }
From source file:cn.edu.zju.bme319.cordova.ExtraInfo.java
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { Activity activity = this.cordova.getActivity(); context = (Context) this.context; /*from w ww. j a va2s. c o m*/ // Register for broadcasts when a device is discovered IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); context.registerReceiver(mReceiver, filter); // Register for broadcasts when discovery starts filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED); context.registerReceiver(mReceiver, filter); // Register for broadcasts when discovery has finished filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); context.registerReceiver(mReceiver, filter); // Register for broadcasts when connectivity state changes filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); context.registerReceiver(mReceiver, filter); Looper.prepare(); found_devices = new ArrayList<BluetoothDevice>(); if (btadapter == null) { btadapter = BluetoothAdapter.getDefaultAdapter(); } if (action.equals("getExtra")) { callbackContext.success("123"); return true; } else if (ACTION_DISCOVER_DEVICES.equals(action)) { try { Log.d("BluetoothPlugin", "We're in "+ACTION_DISCOVER_DEVICES); found_devices.clear(); discovering=true; if (btadapter.isDiscovering()) { btadapter.cancelDiscovery(); } Log.i("BluetoothPlugin","Discovering devices..."); btadapter.startDiscovery(); while (discovering){} String devicesFound=null; int count=0; devicesFound="["; for (BluetoothDevice device : found_devices) { Log.i("BluetoothPlugin",device.getName() + " "+device.getAddress()+" "+device.getBondState()); if ((device.getName()!=null) && (device.getBluetoothClass()!=null)){ devicesFound = devicesFound + " { \"name\" : \"" + device.getName() + "\" ," + "\"address\" : \"" + device.getAddress() + "\" ," + "\"class\" : \"" + device.getBluetoothClass().getDeviceClass() + "\" }"; if (count<found_devices.size()-1) devicesFound = devicesFound + ","; }else Log.i("BluetoothPlugin",device.getName() + " Problems retrieving attributes. Device not added "); count++; } devicesFound= devicesFound + "] "; Log.d("BluetoothPlugin - "+ACTION_DISCOVER_DEVICES, "Returning: "+ devicesFound); callbackContext.success(devicesFound); //result = new PluginResult(Status.OK, devicesFound); } catch (Exception Ex) { Log.d("BluetoothPlugin - "+ACTION_DISCOVER_DEVICES, "Got Exception "+ Ex.getMessage()); callbackContext.error("discoveryError"); //result = new PluginResult(Status.ERROR); } // try { // // Log.d("BluetoothPlugin", "We're in "+ACTION_DISCOVER_DEVICES); // // // Create a BroadcastReceiver for ACTION_FOUND //// final BroadcastReceiver mReceiver = new BroadcastReceiver() { //// public void onReceive(Context context, Intent intent) { //// String action = intent.getAction(); //// // When discovery finds a device //// if (BluetoothDevice.ACTION_FOUND.equals(action)) { //// // Get the BluetoothDevice object from the Intent //// BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); //// // Add the name and address to an array adapter to show in a ListView //// mArrayAdapter.add(device.getName() + "\n" + device.getAddress()); //// } //// } //// }; //// // Register the BroadcastReceiver //// IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); //// registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy //// //// // ?? //// if (btadapter.isDiscovering()) { //// btadapter.cancelDiscovery(); //// Log.d("BluetoothPlugin", "We're in "+"12"); //// } //// //? //// Log.d("BluetoothPlugin", "We're in "+"1234"); //// btadapter.startDiscovery(); //// Log.d("BluetoothPlugin", "We're in "+"123456"); //// //// found_devices.clear(); //// //discovering=true; //// //// //if (btadapter.isDiscovering()) { //// // btadapter.cancelDiscovery(); //// //} //// //// SendCommand(0); //// //// Log.i("BluetoothPlugin","Discovering devices..."); //// //btadapter.startDiscovery(); //// //// while (discovering){} //// //// String devicesFound=null; //// int count=0; //// devicesFound="["; //// for (BluetoothDevice device : found_devices) { //// Log.i("BluetoothPlugin",device.getName() + " "+device.getAddress()+" "+device.getBondState()); //// if ((device.getName()!=null) && (device.getBluetoothClass()!=null)){ //// devicesFound = devicesFound + " { \"name\" : \"" + device.getName() + "\" ," + //// "\"address\" : \"" + device.getAddress() + "\" ," + //// "\"class\" : \"" + device.getBluetoothClass().getDeviceClass() + "\" }"; //// if (count<found_devices.size()-1) devicesFound = devicesFound + ","; //// }else Log.i("BluetoothPlugin",device.getName() + " Problems retrieving attributes. Device not added "); //// count++; //// } //// //// devicesFound= devicesFound + "] "; //// //// Log.d("BluetoothPlugin - "+ACTION_DISCOVER_DEVICES, "Returning: "+ devicesFound); //// callbackContext.success(devicesFound); // //result = new PluginResult(Status.OK, devicesFound); // return true; // } catch (Exception Ex) { // Log.d("BluetoothPlugin - "+ACTION_DISCOVER_DEVICES, "Got Exception "+ Ex.getMessage()); // //result = new PluginResult(Status.ERROR); // callbackContext.error("discoverError"); // return false; // } } else if (ACTION_IS_BT_ENABLED.equals(action)) { try { Log.d("BluetoothPlugin", "We're in "+ACTION_IS_BT_ENABLED); boolean isEnabled = btadapter.isEnabled(); Log.d("BluetoothPlugin - "+ACTION_IS_BT_ENABLED, "Returning "+ "is Bluetooth Enabled? "+isEnabled); callbackContext.success(""+isEnabled); //result = new PluginResult(Status.OK, isEnabled); return true; } catch (Exception Ex) { Log.d("BluetoothPlugin - "+ACTION_IS_BT_ENABLED, "Got Exception "+ Ex.getMessage()); callbackContext.error("isBTEnabledError"); //result = new PluginResult(Status.ERROR); return false; } } else if (ACTION_ENABLE_BT.equals(action)) { try { Log.d("BluetoothPlugin", "We're in "+ACTION_ENABLE_BT); boolean enabled = false; Log.d("BluetoothPlugin", "Enabling Bluetooth..."); if (btadapter.isEnabled()) { enabled = true; } else { enabled = btadapter.enable(); } Log.d("BluetoothPlugin - "+ACTION_ENABLE_BT, "Returning "+ "Result: "+enabled); callbackContext.success("" + enabled); //result = new PluginResult(Status.OK, enabled); return true; } catch (Exception Ex) { Log.d("BluetoothPlugin - "+ACTION_ENABLE_BT, "Got Exception "+ Ex.getMessage()); callbackContext.error("EnableBTError"); //result = new PluginResult(Status.ERROR); return false; } } else if (ACTION_DISABLE_BT.equals(action)) { try { Log.d("BluetoothPlugin", "We're in "+ACTION_DISABLE_BT); boolean disabled = false; Log.d("BluetoothPlugin", "Disabling Bluetooth..."); if (btadapter.isEnabled()) { disabled = btadapter.disable(); } else { disabled = true; } Log.d("BluetoothPlugin - "+ACTION_DISABLE_BT, "Returning "+ "Result: "+disabled); callbackContext.success("" + disabled); //result = new PluginResult(Status.OK, disabled); return true; } catch (Exception Ex) { Log.d("BluetoothPlugin - "+ACTION_DISABLE_BT, "Got Exception "+ Ex.getMessage()); callbackContext.error("DisableBTError"); //result = new PluginResult(Status.ERROR); return false; } } else if (ACTION_PAIR_BT.equals(action)) { try { Log.d("BluetoothPlugin", "We're in "+ACTION_PAIR_BT); String addressDevice = args.getString(0); if (btadapter.isDiscovering()) { btadapter.cancelDiscovery(); } BluetoothDevice device = btadapter.getRemoteDevice(addressDevice); boolean paired = false; Log.d("BluetoothPlugin","Pairing with Bluetooth device with name " + device.getName()+" and address "+device.getAddress()); try { Method m = device.getClass().getMethod("createBond"); paired = (Boolean) m.invoke(device); } catch (Exception e) { e.printStackTrace(); } Log.d("BluetoothPlugin - "+ACTION_PAIR_BT, "Returning "+ "Result: "+paired); callbackContext.success("" + paired); //result = new PluginResult(Status.OK, paired); return true; } catch (Exception Ex) { Log.d("BluetoothPlugin - "+ACTION_PAIR_BT, "Got Exception "+ Ex.getMessage()); callbackContext.error("pairBTError"); //result = new PluginResult(Status.ERROR); return false; } } else if (ACTION_UNPAIR_BT.equals(action)) { try { Log.d("BluetoothPlugin", "We're in "+ACTION_UNPAIR_BT); String addressDevice = args.getString(0); if (btadapter.isDiscovering()) { btadapter.cancelDiscovery(); } BluetoothDevice device = btadapter.getRemoteDevice(addressDevice); boolean unpaired = false; Log.d("BluetoothPlugin","Unpairing Bluetooth device with " + device.getName()+" and address "+device.getAddress()); try { Method m = device.getClass().getMethod("removeBond"); unpaired = (Boolean) m.invoke(device); } catch (Exception e) { e.printStackTrace(); } Log.d("BluetoothPlugin - "+ACTION_UNPAIR_BT, "Returning "+ "Result: "+unpaired); callbackContext.success("" + unpaired); //result = new PluginResult(Status.OK, unpaired); return true; } catch (Exception Ex) { Log.d("BluetoothPlugin - "+ACTION_UNPAIR_BT, "Got Exception "+ Ex.getMessage()); callbackContext.error("unpairBTError"); //result = new PluginResult(Status.ERROR); return false; } } else if (ACTION_LIST_BOUND_DEVICES.equals(action)) { try { Log.d("BluetoothPlugin", "We're in "+ACTION_LIST_BOUND_DEVICES); Log.d("BluetoothPlugin","Getting paired devices..."); //? Set<BluetoothDevice> pairedDevices = btadapter.getBondedDevices(); int count =0; String resultBoundDevices="[ "; if (pairedDevices.size() > 0) { for (BluetoothDevice device : pairedDevices) { Log.i("BluetoothPlugin",device.getName() + " "+device.getAddress()+" "+device.getBondState()); if ((device.getName()!=null) && (device.getBluetoothClass()!=null)){ resultBoundDevices = resultBoundDevices + " { \"name\" : \"" + device.getName() + "\" ," + "\"address\" : \"" + device.getAddress() + "\" ," + "\"class\" : \"" + device.getBluetoothClass().getDeviceClass() + "\" }"; if (count<pairedDevices.size()-1) resultBoundDevices = resultBoundDevices + ","; } else Log.i("BluetoothPlugin",device.getName() + " Problems retrieving attributes. Device not added "); count++; } } resultBoundDevices= resultBoundDevices + "] "; Log.d("BluetoothPlugin - "+ACTION_LIST_BOUND_DEVICES, "Returning "+ resultBoundDevices); callbackContext.success("" + resultBoundDevices); //result = new PluginResult(Status.OK, resultBoundDevices); return true; } catch (Exception Ex) { Log.d("BluetoothPlugin - "+ACTION_LIST_BOUND_DEVICES, "Got Exception "+ Ex.getMessage()); callbackContext.error("resultBoundDevicesError"); //result = new PluginResult(Status.ERROR); return false; } } else if (ACTION_STOP_DISCOVERING_BT.equals(action)) { try { Log.d("BluetoothPlugin", "We're in "+ACTION_STOP_DISCOVERING_BT); boolean stopped = true; Log.d("BluetoothPlugin", "Stop Discovering Bluetooth Devices..."); if (btadapter.isDiscovering()) { Log.i("BluetoothPlugin","Stop discovery..."); stopped = btadapter.cancelDiscovery(); discovering=false; } Log.d("BluetoothPlugin - "+ACTION_STOP_DISCOVERING_BT, "Returning "+ "Result: "+stopped); callbackContext.success("" + stopped); //result = new PluginResult(Status.OK, stopped); return true; } catch (Exception Ex) { Log.d("BluetoothPlugin - "+ACTION_STOP_DISCOVERING_BT, "Got Exception "+ Ex.getMessage()); callbackContext.error("stoppedError"); //result = new PluginResult(Status.ERROR); return false; } } else if (ACTION_IS_BOUND_BT.equals(action)) { try { Log.d("BluetoothPlugin", "We're in "+ACTION_IS_BOUND_BT); String addressDevice = args.getString(0); BluetoothDevice device = btadapter.getRemoteDevice(addressDevice); Log.i("BluetoothPlugin","BT Device in state "+device.getBondState()); boolean state = false; if (device!=null && device.getBondState()==12) state = true; else state = false; Log.d("BluetoothPlugin","Is Bound with " + device.getName()+" - address "+device.getAddress()); Log.d("BluetoothPlugin - "+ACTION_IS_BOUND_BT, "Returning "+ "Result: "+state); callbackContext.success("" + state); //result = new PluginResult(Status.OK, state); return true; } catch (Exception Ex) { Log.d("BluetoothPlugin - "+ACTION_IS_BOUND_BT, "Got Exception "+ Ex.getMessage()); callbackContext.error("boundBTError"); //result = new PluginResult(Status.ERROR); return false; } } else if(ACTION_BT_CONNECT.equals(action)){ try { Log.d("BluetoothPlugin", "We're in "+ACTION_BT_CONNECT); deviceAddress = "8C:DE:52:99:26:23"; Log.d("BluetoothPlugin", "We're in "+deviceAddress); BluetoothDevice device = btadapter.getRemoteDevice(deviceAddress); //m = device.getClass().getMethod("createRfcommSocket", new Class[] { int.class }); //bluetoothSocket = (BluetoothSocket) m.invoke(device, Integer.valueOf(1)); //SendCommand(0); // ??socket try { bluetoothSocket = device.createRfcommSocketToServiceRecord(UUID .fromString(MY_UUID)); } catch (IOException e) { //Toast.makeText(this, "?", Toast.LENGTH_SHORT).show(); } bluetoothSocket.connect(); sendCommandFlag = 0; SendCommand(sendCommandFlag); if(bluetoothSocket.isConnected()) { this.isConnection = true; String str = ""; // try { inputStream = bluetoothSocket.getInputStream(); // ??? str = ""+1; } catch (IOException e) { //Toast.makeText(this, "??", Toast.LENGTH_SHORT).show(); //return; str=""+2; } if (bThread == false) { ReadThread.start(); bThread = true; str = ""+3; } else { bRun = true; str = ""+4; } //result = new PluginResult(Status.OK, str); //result.setKeepCallback(true); // callbackContext.sendPluginResult(result); callbackContext.success("" + str); } else { //result = new PluginResult(Status.OK, "failure"); callbackContext.error("Could not connect to "); } return true; } catch (Exception Ex) { // TODO: handle exception Log.d("BluetoothPlugin - "+ACTION_BT_CONNECT, "Got Exception "+ Ex.getMessage()); //result = new PluginResult(Status.ERROR); callbackContext.error("Could not connect to "); return false; } }else if(ACTION_BT_GETDATA.equals(action)){ try { Log.d("BluetoothPlugin", "We're in "+ACTION_BT_GETDATA); sendCommandFlag = 1; SendCommand(sendCommandFlag); // if (bluetoothSocket != null) { // if(bluetoothSocket.isConnected()){ // SendCommand(1); // } // } // //result = new PluginResult(Status.OK, spoValue); Log.v("Get1 ", returnBTData); while(returnBTData == "") { Log.v("Get2 ", returnBTData); } Log.v("Get3 ", returnBTData); callbackContext.success("" + returnBTData); //ReadThread.cancel(); bluetoothSocket.close(); bluetoothSocket = null; return true; } catch (Exception Ex) { // TODO: handle exception Log.d("BluetoothPlugin - "+ACTION_BT_GETDATA, "Got Exception "+ Ex.getMessage()); callbackContext.error("" + "getDataError"); //result = new PluginResult(Status.ERROR); return false; } } else { // result = new PluginResult(Status.INVALID_ACTION); // Log.d("BluetoothPlugin", "Invalid action : "+action+" passed"); // return result; callbackContext.error("" + "actionError"); } return false; }