List of usage examples for android.bluetooth BluetoothDevice getName
@RequiresPermission(Manifest.permission.BLUETOOTH)
public String getName()
From source file:org.thecongers.mcluster.MainActivity.java
private boolean iTPMSConnect() { btAdapter = BluetoothAdapter.getDefaultAdapter(); checkBTState();//from w ww. j a v a2s .c om if (btAdapter != null) { Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices(); // If there are paired devices if (pairedDevices.size() > 0) { // Loop through paired devices for (BluetoothDevice device : pairedDevices) { if (device.getName().contains("iTPMS")) { address = device.getAddress(); Log.d(TAG, "Paired iTPMS found: " + device.getName() + " " + device.getAddress()); } } if (address == null) { Toast.makeText(MainActivity.this, getResources().getString(R.string.toast_noPairedTPMS), Toast.LENGTH_LONG).show(); return false; } } if (address != null) { // Set up a pointer to the remote node using it's address. BluetoothDevice device = btAdapter.getRemoteDevice(address); iTPMSConnectThread = new iTPMSConnectThread(device); iTPMSConnectThread.start(); } else { Toast.makeText(MainActivity.this, getResources().getString(R.string.toast_noPairedTPMS), Toast.LENGTH_LONG).show(); return false; } return true; } Log.d(TAG, "Bluetooth not supported"); return false; }
From source file:com.authorwjf.bounce.BluetoothChatService.java
/** * Start the ConnectedThread to begin managing a Bluetooth connection * @param socket The BluetoothSocket on which the connection was made * @param device The BluetoothDevice that has been connected *//*from www .ja v a2 s .com*/ public synchronized void connected(BluetoothSocket socket, BluetoothDevice device, final String socketType) { // Cancel the thread that completed the connection if (mConnectThread != null) { mConnectThread.cancel(); mConnectThread = null; } // Cancel any thread currently running a connection if (mConnectedThread != null) { mConnectedThread.cancel(); mConnectedThread = null; } // Cancel the accept thread because we only want to connect to one device if (mSecureAcceptThread != null) { mSecureAcceptThread.cancel(); mSecureAcceptThread = null; } if (mInsecureAcceptThread != null) { mInsecureAcceptThread.cancel(); mInsecureAcceptThread = null; } // Start the thread to manage the connection and perform transmissions mConnectedThread = new ConnectedThread(socket, socketType); mConnectedThread.start(); // Send the name of the connected device back to the UI Activity Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_DEVICE_NAME); Bundle bundle = new Bundle(); bundle.putString(BluetoothChat.DEVICE_NAME, device.getName()); msg.setData(bundle); mHandler.sendMessage(msg); setState(STATE_CONNECTED); }
From source file:uk.ac.gcu.bluedroid.BluetoothChatService.java
/** * Start the ConnectedThread to begin managing a Bluetooth connection * /* w w w. ja v a 2 s . com*/ * @param socket * The BluetoothSocket on which the connection was made * @param device * The BluetoothDevice that has been connected */ public synchronized void connected(BluetoothSocket socket, BluetoothDevice device, final String socketType) { if (D) Log.d(TAG, "connected, Socket Type:" + socketType); // Cancel the thread that completed the connection if (mConnectThread != null) { mConnectThread.cancel(); mConnectThread = null; } // Cancel any thread currently running a connection if (mConnectedThread != null) { mConnectedThread.cancel(); mConnectedThread = null; } // Cancel the accept thread because we only want to connect to one // device if (mSecureAcceptThread != null) { mSecureAcceptThread.cancel(); mSecureAcceptThread = null; } if (mInsecureAcceptThread != null) { mInsecureAcceptThread.cancel(); mInsecureAcceptThread = null; } // Start the thread to manage the connection and perform transmissions mConnectedThread = new ConnectedThread(socket, socketType); mConnectedThread.start(); // Send the name of the connected device back to the UI Activity Message msg = mHandler.obtainMessage(MainActivity.MESSAGE_DEVICE_NAME); Bundle bundle = new Bundle(); bundle.putString(MainActivity.DEVICE_NAME, device.getName()); msg.setData(bundle); mHandler.sendMessage(msg); setState(STATE_CONNECTED); }
From source file:com.piusvelte.taplock.client.core.TapLockService.java
@Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent != null) { String action = intent.getAction(); if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) { int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF); if (state == BluetoothAdapter.STATE_ON) { if (mStartedBT) { if (mUIInterface != null) { try { mUIInterface.setMessage("Bluetooth enabled"); } catch (RemoteException e) { Log.e(TAG, e.getMessage()); }// www. j a va 2s . c om } if ((mQueueAddress != null) && (mQueueState != null)) requestWrite(mQueueAddress, mQueueState, mQueuePassphrase); else if (mRequestDiscovery && !mBtAdapter.isDiscovering()) mBtAdapter.startDiscovery(); else if (mUIInterface != null) { try { mUIInterface.setBluetoothEnabled(); } catch (RemoteException e) { Log.e(TAG, e.getMessage()); } } } } else if (state == BluetoothAdapter.STATE_TURNING_OFF) { if (mUIInterface != null) { try { mUIInterface.setMessage("Bluetooth disabled"); } catch (RemoteException e) { Log.e(TAG, e.getMessage()); } } stopThreads(); } } else if (BluetoothDevice.ACTION_FOUND.equals(action)) { // Get the BluetoothDevice object from the Intent BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (device.getBondState() == BluetoothDevice.BOND_BONDED) { // connect if configured String address = device.getAddress(); for (JSONObject deviceJObj : mDevices) { try { if (deviceJObj.getString(KEY_ADDRESS).equals(address)) { // if queued mDeviceFound = (mQueueAddress != null) && mQueueAddress.equals(address) && (mQueueState != null); break; } } catch (JSONException e) { Log.e(TAG, e.getMessage()); } } } else if (mRequestDiscovery && (mUIInterface != null)) { String unpairedDevice = TapLock .createDevice(device.getName(), device.getAddress(), DEFAULT_PASSPHRASE).toString(); try { mUIInterface.setUnpairedDevice(unpairedDevice); } catch (RemoteException e) { Log.e(TAG, e.getMessage()); } } } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { if (mDeviceFound) { requestWrite(mQueueAddress, mQueueState, mQueuePassphrase); mDeviceFound = false; } else if (mRequestDiscovery) { mRequestDiscovery = false; if (mUIInterface != null) { try { mUIInterface.setDiscoveryFinished(); } catch (RemoteException e) { Log.e(TAG, e.toString()); } } } } else if (ACTION_TOGGLE.equals(action) && intent.hasExtra(EXTRA_DEVICE_ADDRESS)) { String address = intent.getStringExtra(EXTRA_DEVICE_ADDRESS); requestWrite(address, ACTION_TOGGLE, null); } else if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) { // create widget if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) { int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); if (intent.hasExtra(EXTRA_DEVICE_NAME)) { // add a widget String deviceName = intent.getStringExtra(EXTRA_DEVICE_NAME); for (int i = 0, l = mDevices.size(); i < l; i++) { String name = null; try { name = mDevices.get(i).getString(KEY_NAME); } catch (JSONException e1) { e1.printStackTrace(); } if ((name != null) && name.equals(deviceName)) { JSONObject deviceJObj = mDevices.remove(i); JSONArray widgetsJArr; if (deviceJObj.has(KEY_WIDGETS)) { try { widgetsJArr = deviceJObj.getJSONArray(KEY_WIDGETS); } catch (JSONException e) { widgetsJArr = new JSONArray(); } } else widgetsJArr = new JSONArray(); widgetsJArr.put(appWidgetId); try { deviceJObj.put(KEY_WIDGETS, widgetsJArr); } catch (JSONException e) { e.printStackTrace(); } mDevices.add(i, deviceJObj); TapLock.storeDevices(this, getSharedPreferences(KEY_PREFS, MODE_PRIVATE), mDevices); break; } } } buildWidget(appWidgetId); } else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS)) { int[] appWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS); if (appWidgetIds != null) { for (int appWidgetId : appWidgetIds) buildWidget(appWidgetId); } } } else if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) { int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); Log.d(TAG, "delete appWidgetId: " + appWidgetId); for (int i = 0, l = mDevices.size(); i < l; i++) { JSONObject deviceJObj = mDevices.get(i); if (deviceJObj.has(KEY_WIDGETS)) { JSONArray widgetsJArr = null; try { widgetsJArr = deviceJObj.getJSONArray(KEY_WIDGETS); } catch (JSONException e) { e.printStackTrace(); } if (widgetsJArr != null) { boolean wasUpdated = false; JSONArray newWidgetsJArr = new JSONArray(); for (int widgetIdx = 0, wdigetsLen = widgetsJArr .length(); widgetIdx < wdigetsLen; widgetIdx++) { int widgetId; try { widgetId = widgetsJArr.getInt(widgetIdx); } catch (JSONException e) { widgetId = AppWidgetManager.INVALID_APPWIDGET_ID; e.printStackTrace(); } Log.d(TAG, "eval widgetId: " + widgetId); if ((widgetId != AppWidgetManager.INVALID_APPWIDGET_ID) && (widgetId == appWidgetId)) { Log.d(TAG, "skip: " + widgetId); wasUpdated = true; } else { Log.d(TAG, "include: " + widgetId); newWidgetsJArr.put(widgetId); } } if (wasUpdated) { try { deviceJObj.put(KEY_WIDGETS, newWidgetsJArr); mDevices.remove(i); mDevices.add(i, deviceJObj); TapLock.storeDevices(this, getSharedPreferences(KEY_PREFS, MODE_PRIVATE), mDevices); Log.d(TAG, "stored: " + deviceJObj.toString()); } catch (JSONException e) { e.printStackTrace(); } } } } else { JSONArray widgetsJArr = new JSONArray(); try { deviceJObj.put(KEY_WIDGETS, widgetsJArr); mDevices.remove(i); mDevices.add(i, deviceJObj); TapLock.storeDevices(this, getSharedPreferences(KEY_PREFS, MODE_PRIVATE), mDevices); } catch (JSONException e) { e.printStackTrace(); } } } } } return START_STICKY; }
From source file:com.nbplus.iotapp.bluetooth.BluetoothLeService.java
/** * Initializes a reference to the local Bluetooth adapter. * * @return Return true if the initialization is successful. */// w w w .j a v a 2 s . c om @SuppressLint("NewApi") public IoTResultCodes initialize() { // Use this check to determine whether BLE is supported on the device. Then you can // selectively disable BLE-related features. if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show(); //finish(); return IoTResultCodes.BLE_NOT_SUPPORTED; } // Initializes a Bluetooth adapter. For API level 18 and above, get a reference to // BluetoothAdapter through BluetoothManager. if (mBluetoothManager == null) { mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); if (mBluetoothManager == null) { Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show(); Log.e(TAG, "Unable to initialize BluetoothManager."); return IoTResultCodes.BLUETOOTH_NOT_SUPPORTED; } } mBluetoothAdapter = mBluetoothManager.getAdapter(); // Checks if Bluetooth is supported on the device. if (mBluetoothAdapter == null) { Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show(); Log.e(TAG, "Unable to obtain a BluetoothAdapter."); //finish(); return IoTResultCodes.BLUETOOTH_NOT_SUPPORTED; } // Ensures Bluetooth is enabled on the device. If Bluetooth is not currently enabled, // fire an intent to display a dialog asking the user to grant permission to enable it. if (!mBluetoothAdapter.isEnabled()) { return IoTResultCodes.BLUETOOTH_NOT_ENABLED; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mLeScanLollipopCallback = new ScanCallback() { @Override public void onScanResult(int callbackType, ScanResult result) { //super.onScanResult(callbackType, result); try { BluetoothDevice device = result.getDevice(); byte[] scanRecord = result.getScanRecord().getBytes(); final HashMap<Integer, AdRecord> adRecords = AdRecord.parseScanRecord(scanRecord); /** * UUID ? . */ ArrayList<String> scannedUuids = DataParser.getUuids(adRecords); if (scannedUuids == null || scannedUuids.size() == 0) { Log.e(TAG, ">>> xx device name " + device.getAddress() + " has no uuid advertisement"); return; } IoTDevice iotDevice = new IoTDevice(); iotDevice.setDeviceId(device.getAddress()); iotDevice.setDeviceName(device.getName()); iotDevice.setDeviceType(IoTDevice.DEVICE_TYPE_STRING_BT); iotDevice.setUuids(scannedUuids); iotDevice.setUuidLen(DataParser.getUuidLength(adRecords)); iotDevice.setAdRecordHashMap(adRecords); mTempScanedList.put(iotDevice.getDeviceId(), iotDevice); } catch (Exception e) { e.printStackTrace(); } } @Override public void onBatchScanResults(List<ScanResult> results) { //super.onBatchScanResults(results); Log.d(TAG, "mScanCallback.. onBatchScanResults"); } @Override public void onScanFailed(int errorCode) { //super.onScanFailed(errorCode); Log.d(TAG, "mScanCallback.. onScanFailed"); } }; } else { mLeScanKitkatCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) { Log.d(TAG, ">> mLeScanKitkatCallback.."); try { final HashMap<Integer, AdRecord> adRecords = AdRecord.parseScanRecord(scanRecord); /** * UUID ? . */ ArrayList<String> scannedUuids = DataParser.getUuids(adRecords); if (scannedUuids == null || scannedUuids.size() == 0) { Log.e(TAG, ">>> xx device name " + device.getAddress() + " has no uuid advertisement"); return; } IoTDevice iotDevice = new IoTDevice(); iotDevice.setDeviceId(device.getAddress()); iotDevice.setDeviceName(device.getName()); iotDevice.setDeviceType(IoTDevice.DEVICE_TYPE_STRING_BT); iotDevice.setUuids(scannedUuids); iotDevice.setUuidLen(DataParser.getUuidLength(adRecords)); iotDevice.setAdRecordHashMap(adRecords); mTempScanedList.put(iotDevice.getDeviceId(), iotDevice); } catch (Exception e) { e.printStackTrace(); } } }; } return IoTResultCodes.SUCCESS; }
From source file:com.github.akinaru.bleanalyzer.bluetooth.BluetoothCustomManager.java
private void dispatchRFdroid(BluetoothDevice device, int rssi, final byte[] scanRecord) { if (scanningList.containsKey(device.getAddress())) { if (adListener != null && measurement.getBtDevice() != null && measurement.getBtDevice().getDeviceAddress().equals(device.getAddress())) { long ts = new Date().getTime(); measurement.getHistoryList().add(ts); adListener.onADframeReceived(ts, measurement.getHistoryList()); }//w w w .ja v a 2s. c o m } else { Log.i(TAG, "found a RFdroid"); List<ADStructure> structures = ADPayloadParser.getInstance().parse(scanRecord); int advInterval = -1; for (ADStructure structure : structures) { if (structure instanceof ADManufacturerSpecific) { ADManufacturerSpecific data = (ADManufacturerSpecific) structure; if (data.getData().length == 9) { byte[] name = new byte[7]; System.arraycopy(data.getData(), 0, name, 0, 7); String nameStr = new String(name); if (nameStr.equals("RFdroid")) { advInterval = (data.getData()[7] << 8) + (data.getData()[8] & 0xFF); Log.i(TAG, "current scan interval : " + advInterval); } } } } if (advInterval != -1) { scanningList.put(device.getAddress(), device); if (!measurement.isSelectionningDevice()) measurement.setBtDevice(new BluetoothObject(device.getAddress(), device.getName(), (int) (advInterval * 0.625))); try { JSONObject object = new JSONObject(); object.put(JsonConstants.BT_ADDRESS, device.getAddress()); object.put(JsonConstants.BT_DEVICE_NAME, device.getName()); object.put(JsonConstants.BT_ADVERTISING_INTERVAL, (int) (advInterval * 0.625)); ArrayList<String> deviceInfo = new ArrayList<>(); deviceInfo.add(object.toString()); broadcastUpdateStringList(BluetoothEvents.BT_EVENT_DEVICE_DISCOVERED, deviceInfo); } catch (JSONException e) { e.printStackTrace(); } } } }
From source file:com.updetector.MainActivity.java
public void selectBluetoothDevice() { Set<BluetoothDevice> bluetoothDevices = mBluetoothAdapter.getBondedDevices(); final CharSequence[] listItems = new CharSequence[bluetoothDevices.size()]; int i = 0;//from ww w .j a v a2 s . c o m for (BluetoothDevice device : mBluetoothAdapter.getBondedDevices()) { String device_name = device.getName(); listItems[i++] = device_name; } AlertDialog select = new AlertDialog.Builder(this).setTitle(R.string.set_bluetooth_message) .setSingleChoiceItems(listItems, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.e(LOG_TAG, "id=" + whichButton); if (whichButton >= 0) selectedBloothDeviceName = listItems[whichButton].toString(); } }).setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.e(LOG_TAG, selectedBloothDeviceName); Toast.makeText(getApplicationContext(), getString(R.string.bluetooth_device_selected, selectedBloothDeviceName), Toast.LENGTH_SHORT).show(); final SharedPreferences mPrefs = getSharedPreferences(Constants.SHARED_PREFERENCES, Context.MODE_PRIVATE); Editor editor = mPrefs.edit(); editor.putString(Constants.BLUETOOTH_CAR_DEVICE_NAME, selectedBloothDeviceName); editor.commit(); } }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }).create(); select.show(); }
From source file:com.megster.cordova.BluetoothPlugin.java
/** * Execute a bluetooth function/*from w ww . j a va2 s. c om*/ */ @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:org.bcsphere.bluetooth.BCBluetooth.java
@Override public boolean execute(final String action, final JSONArray json, final CallbackContext callbackContext) throws JSONException { try {/*from www. j av a2 s .co m*/ if (bluetoothAPI != null) { if (isSetContext) { bluetoothAPI.setContext(myContext); isSetContext = false; } if (action.equals("getCharacteristics")) { bluetoothAPI.getCharacteristics(json, callbackContext); } else if (action.equals("getDescriptors")) { bluetoothAPI.getDescriptors(json, callbackContext); } else if (action.equals("removeServices")) { bluetoothAPI.removeServices(json, callbackContext); } if (action.equals("stopScan")) { bluetoothAPI.stopScan(json, callbackContext); } else if (action.equals("getConnectedDevices")) { bluetoothAPI.getConnectedDevices(json, callbackContext); } cordova.getThreadPool().execute(new Runnable() { @Override public void run() { try { if (action.equals("startScan")) { bluetoothAPI.startScan(json, callbackContext); } else if (action.equals("connect")) { bluetoothAPI.connect(json, callbackContext); } else if (action.equals("disconnect")) { bluetoothAPI.disconnect(json, callbackContext); } else if (action.equals("getServices")) { bluetoothAPI.getServices(json, callbackContext); } else if (action.equals("writeValue")) { bluetoothAPI.writeValue(json, callbackContext); } else if (action.equals("readValue")) { bluetoothAPI.readValue(json, callbackContext); } else if (action.equals("setNotification")) { bluetoothAPI.setNotification(json, callbackContext); } else if (action.equals("getDeviceAllData")) { bluetoothAPI.getDeviceAllData(json, callbackContext); } else if (action.equals("addServices")) { bluetoothAPI.addServices(json, callbackContext); } else if (action.equals("getRSSI")) { bluetoothAPI.getRSSI(json, callbackContext); } } catch (Exception e) { Tools.sendErrorMsg(callbackContext); } catch (Error e) { Tools.sendErrorMsg(callbackContext); } } }); } if (action.equals("addEventListener")) { String eventName = Tools.getData(json, Tools.EVENT_NAME); if (eventName.equals("newadvpacket")) { newadvpacketContext = callbackContext; } else if (eventName.equals("disconnect")) { disconnectContext = callbackContext; } if (bluetoothAPI != null) { bluetoothAPI.addEventListener(json, callbackContext); } return true; } if (action.equals("getEnvironment")) { JSONObject jo = new JSONObject(); if (this.webView.page != null) { jo.put("deviceAddress", this.webView.page.deviceAddress); jo.put("deviceType", this.webView.page.deviceType); jo.put("api", versionOfAPI); } else { jo.put("deviceAddress", "N/A"); jo.put("deviceType", "N/A"); jo.put("api", versionOfAPI); } callbackContext.success(jo); return true; } if (action.equals("openBluetooth")) { if (!bluetoothAdapter.isEnabled()) { bluetoothAdapter.enable(); } Tools.sendSuccessMsg(callbackContext); return true; } if (action.equals("getBluetoothState")) { Log.i(TAG, "getBluetoothState"); JSONObject obj = new JSONObject(); if (bluetoothAdapter.isEnabled()) { Tools.addProperty(obj, Tools.BLUETOOTH_STATE, Tools.IS_TRUE); callbackContext.success(obj); } else { Tools.addProperty(obj, Tools.BLUETOOTH_STATE, Tools.IS_FALSE); callbackContext.success(obj); } return true; } if (action.equals("startClassicalScan")) { Log.i(TAG, "startClassicalScan"); if (bluetoothAdapter.isEnabled()) { if (bluetoothAdapter.startDiscovery()) { callbackContext.success(); } else { callbackContext.error("start classical scan error!"); } } else { callbackContext.error("your bluetooth is not open!"); } } if (action.equals("stopClassicalScan")) { Log.i(TAG, "stopClassicalScan"); if (bluetoothAdapter.isEnabled()) { if (bluetoothAdapter.cancelDiscovery()) { callbackContext.success(); } else { callbackContext.error("stop classical scan error!"); } } else { callbackContext.error("your bluetooth is not open!"); } } if (action.equals("rfcommConnect")) { String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS); String securestr = Tools.getData(json, Tools.SECURE); String uuidstr = Tools.getData(json, Tools.UUID); boolean secure = false; if (securestr != null && securestr.equals("true")) { secure = true; } Log.i(TAG, "connect to " + deviceAddress); BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress); BluetoothSerialService classicalService = classicalServices.get(deviceAddress); if (device != null && classicalService == null) { classicalService = new BluetoothSerialService(); classicalService.disconnectCallback = disconnectContext; classicalServices.put(deviceAddress, classicalService); } if (device != null) { classicalService.connectCallback = callbackContext; classicalService.connect(device, uuidstr, secure); } else { callbackContext.error("Could not connect to " + deviceAddress); } } if (action.equals("rfcommDisconnect")) { String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS); BluetoothSerialService service = classicalServices.get(deviceAddress); if (service != null) { service.connectCallback = null; service.stop(); classicalServices.remove(deviceAddress); callbackContext.success(); } else { callbackContext.error("Could not disconnect to " + deviceAddress); } } if (action.equals("rfcommListen")) { String name = Tools.getData(json, Tools.NAME); String uuidstr = Tools.getData(json, Tools.UUID); String securestr = Tools.getData(json, Tools.SECURE); boolean secure = false; if (securestr.equals("true")) { secure = true; } BluetoothSerialService service = new BluetoothSerialService(); service.listen(name, uuidstr, secure, this); acceptServices.put(name + uuidstr, service); } if (action.equals("rfcommUnListen")) { String name = Tools.getData(json, Tools.NAME); String uuidstr = Tools.getData(json, Tools.UUID); BluetoothSerialService service = acceptServices.get(name + uuidstr); if (service != null) { service.stop(); } } if (action.equals("rfcommWrite")) { String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS); BluetoothSerialService service = classicalServices.get(deviceAddress); if (service != null) { String data = Tools.getData(json, Tools.WRITE_VALUE); service.write(Tools.decodeBase64(data)); callbackContext.success(); } else { callbackContext.error("there is no connection on device:" + deviceAddress); } } if (action.equals("rfcommRead")) { String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS); BluetoothSerialService service = classicalServices.get(deviceAddress); if (service != null) { byte[] data = new byte[2048]; byte[] predata = service.buffer.array(); for (int i = 0; i < service.bufferSize; i++) { data[i] = predata[i]; } JSONObject obj = new JSONObject(); //Tools.addProperty(obj, Tools.DEVICE_ADDRESS, deviceAddress); Tools.addProperty(obj, Tools.VALUE, Tools.encodeBase64(data)); Tools.addProperty(obj, Tools.DATE, Tools.getDateString()); callbackContext.success(obj); service.bufferSize = 0; service.buffer.clear(); } else { callbackContext.error("there is no connection on device:" + deviceAddress); } } if (action.equals("rfcommSubscribe")) { String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS); BluetoothSerialService service = classicalServices.get(deviceAddress); if (service != null) { service.dataAvailableCallback = callbackContext; } else { callbackContext.error("there is no connection on device:" + deviceAddress); } } if (action.equals("rfcommUnsubscribe")) { String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS); BluetoothSerialService service = classicalServices.get(deviceAddress); if (service != null) { service.dataAvailableCallback = null; } else { callbackContext.error("there is no connection on device:" + deviceAddress); } } if (action.equals("getPairedDevices")) { try { Log.i(TAG, "getPairedDevices"); JSONArray ary = new JSONArray(); Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices(); Iterator<BluetoothDevice> it = devices.iterator(); while (it.hasNext()) { BluetoothDevice device = (BluetoothDevice) it.next(); JSONObject obj = new JSONObject(); Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress()); Tools.addProperty(obj, Tools.DEVICE_NAME, device.getName()); ary.put(obj); } callbackContext.success(ary); } catch (Exception e) { Tools.sendErrorMsg(callbackContext); } catch (java.lang.Error e) { Tools.sendErrorMsg(callbackContext); } } else if (action.equals("createPair")) { Log.i(TAG, "createPair"); String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS); JSONObject obj = new JSONObject(); BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress); if (Tools.creatBond(device.getClass(), device)) { Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress()); callbackContext.success(obj); } else { Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress()); callbackContext.error(obj); } } else if (action.equals("removePair")) { Log.i(TAG, "removePair"); String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS); JSONObject obj = new JSONObject(); BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress); if (Tools.removeBond(device.getClass(), device)) { Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress()); callbackContext.success(obj); } else { Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress()); callbackContext.error(obj); } } } catch (Exception e) { Tools.sendErrorMsg(callbackContext); } catch (Error e) { Tools.sendErrorMsg(callbackContext); } return true; }