Giter Site home page Giter Site logo

bleapp's People

Contributors

ahawse avatar greglandry avatar vdni222 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bleapp's Issues

Migrate to Swift 4 or Swift 5

Hey,

can you please migrate the Code to Swift 4 or Swift 5? I am not able to do it by myself, because you have to use Xcode 10.1 an that version does not run on Big Sur.

Ty

Creating BLE Android App

Hi I am a novice in regards to this but I am having issues getting the android app to search for Cypress BLE Device using the code provided as when I go to search for a device on the app it says when I am debugging that it is scanning but cant find the CY8CKIT-042-BLE. I thought it maybe the BLE device but have checked using another BLE scanner app and the device picks up. I have also tried to create a custom UUID on pssocreator as shown in the videos so that the app picks up the device but to no avail. I will enter my main activity and PSSocCapsense java info if anyone has any ideas would be greatly appreciated.

import android.annotation.TargetApi;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.os.ParcelUuid;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**

  • Service for managing the BLE data connection with the GATT database.

*/

@TargetApi(Build.VERSION_CODES.LOLLIPOP) // This is required to allow us to use the lollipop and later scan APIs

public class PSoCCapSenseLedService extends Service {

private final static String TAG = PSoCCapSenseLedService.class.getSimpleName();



// Bluetooth objects that we need to interact with

private static BluetoothManager mBluetoothManager;

private static BluetoothAdapter mBluetoothAdapter;

private static BluetoothLeScanner mLEScanner;

private static BluetoothDevice mLeDevice;

private static BluetoothGatt mBluetoothGatt;



// Bluetooth characteristics that we need to read/write

private static BluetoothGattCharacteristic mLedCharacterisitc;

private static BluetoothGattCharacteristic mCapsenseCharacteristic;

private static BluetoothGattDescriptor mCapSenseCccd;



// UUIDs for the service and characteristics that the custom CapSenseLED service uses

private final static String baseUUID =                   "00000000-0000-1000-8000-00805F9B34F";

private final static String capsenseLedServiceUUID =      baseUUID + "0";

public  final static String ledCharacteristicUUID =       baseUUID + "1";

public  final static String capsenseCharacteristicUUID =  baseUUID + "2";

private final static String CccdUUID =                   "00000000-0000-1000-8000-00805F9B34F";



// Variables to keep track of the LED switch state and CapSense Value

private static boolean mLedSwitchState = false;

private static String mCapSenseValue = "-1"; // This is the No Touch value (0xFFFF)



// Actions used during broadcasts to the main activity

public final static String ACTION_BLESCAN_CALLBACK =

        "uk.co.marchwoodsafety.comonitor.ACTION_BLESCAN_CALLBACK";

public final static String ACTION_CONNECTED =

        "uk.co.marchwoodsafety.comonitor.ACTION_CONNECTED";

public final static String ACTION_DISCONNECTED =

        "uk.co.marchwoodsafety.comonitor.ACTION_DISCONNECTED";

public final static String ACTION_SERVICES_DISCOVERED =

        "uk.co.marchwoodsafety.comonitor.ACTION_SERVICES_DISCOVERED";

public final static String ACTION_DATA_RECEIVED =

        "uk.co.marchwoodsafety.comonitor.ACTION_DATA_RECEIVED";
private String mPSoCCapSenseLedService;


public PSoCCapSenseLedService() {

}



/**

 * This is a binder for the PSoCCapSenseLedService

 */

public class LocalBinder extends Binder {

    PSoCCapSenseLedService getService() {

        return PSoCCapSenseLedService.this;

    }

}



@Override

public IBinder onBind(Intent intent) {

    return mBinder;

}



@Override

public boolean onUnbind(Intent intent) {

    // The BLE close method is called when we unbind the service to free up the resources.

    close();

    return super.onUnbind(intent);

}



private final IBinder mBinder = new LocalBinder();



/**

 * Initializes a reference to the local Bluetooth adapter.

 *

 * @return Return true if the initialization is successful.

 */

public boolean initialize() {

    // 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) {

            Log.e(TAG, "Unable to initialize BluetoothManager.");

            return false;

        }

    }



    mBluetoothAdapter = mBluetoothManager.getAdapter();

    if (mBluetoothAdapter == null) {

        Log.e(TAG, "Unable to obtain a BluetoothAdapter.");

        return false;

    }



    return true;

}



/**

 * Scans for BLE devices that support the service we are looking for

 */

public void scan() {

    /* Scan for devices and look for the one with the service that we want */

    UUID   capsenseLedService =       UUID.fromString(capsenseCharacteristicUUID);

    UUID[] capsenseLedServiceArray = {capsenseLedService};



    // Use old scan method for versions older than lollipop

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {

        //noinspection deprecation

        mBluetoothAdapter.startLeScan(capsenseLedServiceArray, mLeScanCallback);

    } else { // New BLE scanning introduced in LOLLIPOP

        ScanSettings settings;

        List<ScanFilter> filters;

        mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();

        settings = new ScanSettings.Builder()


                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)

                .build();

        filters = new ArrayList<>();

        // We will scan just for the CAR's UUID

        ParcelUuid PUuid = new ParcelUuid(capsenseLedService);

        ScanFilter filter = new ScanFilter.Builder().setServiceUuid(PUuid).build();

        filters.add(filter);

        mLEScanner.startScan(filters, settings, mScanCallback);

    }

}




/**

 * Connects to the GATT server hosted on the Bluetooth LE device.

 *

 * @return Return true if the connection is initiated successfully. The connection result

 * is reported asynchronously through the

 * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}

 * callback.

 */

public boolean connect() {

    if (mBluetoothAdapter == null) {

        Log.w(TAG, "BluetoothAdapter not initialized");

        return false;

    }





    // Previously connected device.  Try to reconnect.

    if (mBluetoothGatt != null) {

        Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");

        return mBluetoothGatt.connect();

    }



    // We want to directly connect to the device, so we are setting the autoConnect

    // parameter to false.

    mBluetoothGatt = mLeDevice.connectGatt(this, false, mGattCallback);

    Log.d(TAG, "Trying to create a new connection.");

    return true;

}



/**

 * Runs service discovery on the connected device.

 */

public void discoverServices() {

    if (mBluetoothAdapter == null || mBluetoothGatt == null) {

        Log.w(TAG, "BluetoothAdapter not initialized");

        return;

    }

    mBluetoothGatt.discoverServices();

}



/**

 * Disconnects an existing connection or cancel a pending connection. The disconnection result

 * is reported asynchronously through the

 * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}

 * callback.

 */

public void disconnect() {

    if (mBluetoothAdapter == null || mBluetoothGatt == null) {

        Log.w(TAG, "BluetoothAdapter not initialized");

        return;

    }

    mBluetoothGatt.disconnect();

}



/**

 * After using a given BLE device, the app must call this method to ensure resources are

 * released properly.

 */

public void close() {

    if (mBluetoothGatt == null) {

        return;

    }

    mBluetoothGatt.close();

    mBluetoothGatt = null;

}



/**

 * This method is used to read the state of the LED from the device

 */

public void readLedCharacteristic() {

    if (mBluetoothAdapter == null || mBluetoothGatt == null) {

        Log.w(TAG, "BluetoothAdapter not initialized");

        return;

    }

    mBluetoothGatt.readCharacteristic(mLedCharacterisitc);

}



/**

 * This method is used to turn the LED on or off

 *

 * @param value Turns the LED on (1) or off (0)

 */

public void writeLedCharacteristic(boolean value) {

    byte[] byteVal = new byte[1];

    if (value) {

        byteVal[0] = (byte) (1);

    } else {

        byteVal[0] = (byte) (0);

    }

    Log.i(TAG, "LED " + value);

    mLedSwitchState = value;

    mLedCharacterisitc.setValue(byteVal);

    mBluetoothGatt.writeCharacteristic(mLedCharacterisitc);

}



/**

 * This method enables or disables notifications for the CapSense slider

 *

 * @param value Turns notifications on (1) or off (0)

 */

public void writeCapSenseNotification(boolean value) {

    // Set notifications locally in the CCCD

    mBluetoothGatt.setCharacteristicNotification(mCapsenseCharacteristic, value);

    byte[] byteVal = new byte[1];

    if (value) {

        byteVal[0] = 1;

    } else {

        byteVal[0] = 0;

    }

    // Write Notification value to the device

    Log.i(TAG, "CapSense Notification " + value);

    mCapSenseCccd.setValue(byteVal);

    mBluetoothGatt.writeDescriptor(mCapSenseCccd);

}



/**

 * This method returns the state of the LED switch

 *

 * @return the value of the LED swtich state

 */

public boolean getLedSwitchState() {

    return mLedSwitchState;

}



/**

 * This method returns the value of th CapSense Slider

 *

 * @return the value of the CapSense Slider

 */

public String getCapSenseValue() {

    return mCapSenseValue;

}





/**

 * Implements the callback for when scanning for devices has found a device with

 * the service we are looking for.

 *

 * This is the callback for BLE scanning on versions prior to Lollipop

 */

private BluetoothAdapter.LeScanCallback mLeScanCallback =

        new BluetoothAdapter.LeScanCallback() {

            @Override

            public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {

                mLeDevice = device;

                //noinspection deprecation

                mBluetoothAdapter.stopLeScan(mLeScanCallback); // Stop scanning after the first device is found

                broadcastUpdate(ACTION_BLESCAN_CALLBACK); // Tell the main activity that a device has been found

            }

        };



/**

 * Implements the callback for when scanning for devices has faound a device with

 * the service we are looking for.

 *

 * This is the callback for BLE scanning for LOLLIPOP and later

 */

private final ScanCallback mScanCallback = new ScanCallback() {

    @Override

    public void onScanResult(int callbackType, ScanResult result) {

        mLeDevice = result.getDevice();

        mLEScanner.stopScan(mScanCallback); // Stop scanning after the first device is found

        broadcastUpdate(ACTION_BLESCAN_CALLBACK); // Tell the main activity that a device has been found

    }

};





/**

 * Implements callback methods for GATT events that the app cares about.  For example,

 * connection change and services discovered.

 */

private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {

    @Override

    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {

        if (newState == BluetoothProfile.STATE_CONNECTED) {

            broadcastUpdate(ACTION_CONNECTED);

            Log.i(TAG, "Connected to GATT server.");

        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {

            Log.i(TAG, "Disconnected from GATT server.");

            broadcastUpdate(ACTION_DISCONNECTED);

        }

    }



    /**

     * This is called when a service discovery has completed.

     *

     * It gets the characteristics we are interested in and then

     * broadcasts an update to the main activity.

     *

     * @param gatt The GATT database object

     * @param status Status of whether the write was successful.

     */

    @Override

    public void onServicesDiscovered(BluetoothGatt gatt, int status) {

        // Get just the service that we are looking for

        BluetoothGattService mService = gatt.getService(UUID.fromString(capsenseLedServiceUUID));

        /* Get characteristics from our desired service */

        mLedCharacterisitc = mService.getCharacteristic(UUID.fromString(ledCharacteristicUUID));

        mCapsenseCharacteristic = mService.getCharacteristic(UUID.fromString(capsenseCharacteristicUUID));

        /* Get the CapSense CCCD */

        mCapSenseCccd = mCapsenseCharacteristic.getDescriptor(UUID.fromString(CccdUUID));



        // Read the current state of the LED from the device

        readLedCharacteristic();



        // Broadcast that service/characteristic/descriptor discovery is done

        broadcastUpdate(ACTION_SERVICES_DISCOVERED);

    }



    /**

     * This is called when a read completes

     *

     * @param gatt the GATT database object

     * @param characteristic the GATT characteristic that was read

     * @param status the status of the transaction

     */

    @Override

    public void onCharacteristicRead(BluetoothGatt gatt,

                                     BluetoothGattCharacteristic characteristic,

                                     int status) {



        if (status == BluetoothGatt.GATT_SUCCESS) {

            // Verify that the read was the LED state

            String uuid = characteristic.getUuid().toString();

            // In this case, the only read the app does is the LED state.

            // If the application had additional characteristics to read we could

            // use a switch statement here to operate on each one separately.

            if(uuid.equals(ledCharacteristicUUID)) {

                final byte[] data = characteristic.getValue();

                // Set the LED switch state variable based on the characteristic value ttat was read

                mLedSwitchState = ((data[0] & 0xff) != 0x00);

            }

            // Notify the main activity that new data is available

            broadcastUpdate(ACTION_DATA_RECEIVED);

        }

    }



    /**

     * This is called when a characteristic with notify set changes.

     * It broadcasts an update to the main activity with the changed data.

     *

     * @param gatt The GATT database object

     * @param characteristic The characteristic that was changed

     */

    @Override

    public void onCharacteristicChanged(BluetoothGatt gatt,

                                        BluetoothGattCharacteristic characteristic) {



        String uuid = characteristic.getUuid().toString();



        // In this case, the only notification the apps gets is the CapSense value.

        // If the application had additional notifications we could

        // use a switch statement here to operate on each one separately.

        if(uuid.equals(capsenseCharacteristicUUID)) {

            mCapSenseValue = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_SINT16,0).toString();

        }



        // Notify the main activity that new data is available

        broadcastUpdate(ACTION_DATA_RECEIVED);

    }

}; // End of GATT event callback methods



/**

 * Sends a broadcast to the listener in the main activity.

Main Activity.Java

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;

import uk.co.marchwoodsaftey.comonitor.R;

public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";

// Variables to access objects from the layout such as buttons, switches, values

private TextView mCapsenseValue;
public Button start_button;
public Button search_button;
public Button connect_button;
public Button discover_button;
public Button disconnect_button;
public Switch led_switch;
public Switch cap_switch;



// Variables to manage BLE connection

private static boolean mConnectState;

private static boolean mServiceConnected;

private static PSoCCapSenseLedService mPSoCCapSenseLedService;


private static final int REQUEST_ENABLE_BLE = 1;


//This is required for Android 6.0 (Marshmallow)

private static final int PERMISSION_REQUEST_COARSE_LOCATION= 1;

// Keep track of whether CapSense Notifications are on or off

private static boolean CapSenseNotifyState = false;


/**
 * This manages the lifecycle of the BLE service.
 * <p>
 * When the service starts we get the service object and initialize the service.
 */

private final ServiceConnection mServiceConnection = new ServiceConnection() {


    /**

     * This is called when the PSoCCapSenseLedService is connected

     *

     * @param componentName the component name of the service that has been connected

     * @param service service being bound

     */

    @Override

    public void onServiceConnected(ComponentName componentName, IBinder service) {

        Log.i( TAG, "onServiceConnected" );

        mPSoCCapSenseLedService = ((PSoCCapSenseLedService.LocalBinder) service).getService();

        mServiceConnected = true;

        mPSoCCapSenseLedService.initialize();

    }


    /**

     * This is called when the PSoCCapSenseService is disconnected.

     *

     * @param componentName the component name of the service that has been connected

     */

    @Override

    public void onServiceDisconnected(ComponentName componentName) {

        Log.i( TAG, "onServiceDisconnected" );

        mPSoCCapSenseLedService = null;

    }

};


/**

 * This is called when the main activity is first created

 *

 * @param savedInstanceState is any state saved from prior creations of this activity

 */

@SuppressLint("WrongViewCast")
@TargetApi(Build.VERSION_CODES.M) // This is required for Android 6.0 (Marshmallow) to work

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


   



    // Set up a variable to point to the CapSense value on the display

    mCapsenseValue = (TextView) findViewById(R.id.capsense_value);



    // Set up variables for accessing buttons and slide switches

    start_button = (Button) findViewById(R.id.start_button);

    search_button = (Button) findViewById(R.id.search_button);

    connect_button = (Button) findViewById(R.id.connect_button);

    discover_button = (Button) findViewById(R.id.discoverSvc_button);

    disconnect_button = (Button) findViewById(R.id.disconnect_button);

    led_switch = (Switch) findViewById(R.id.led_switch);

    cap_switch = (Switch) findViewById(R.id.capsense_switch);



    // Initialize service and connection state variable

    mServiceConnected = false;

    mConnectState = false;





    //This section required for Android 6.0 (Marshmallow)

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

        // Android M Permission check

        if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            final AlertDialog.Builder builder = new AlertDialog.Builder(this);

            builder.setTitle("This app needs location access ");

            builder.setMessage("Please grant location access so this app can detect beacons.");

            builder.setPositiveButton(android.R.string.ok, null);

            builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override

                public void onDismiss(DialogInterface dialog) {

                    requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);

                }

            });

            builder.show();

        }

    } //End of section for Android 6.0 (Marshmallow)



    /* This will be called when the LED On/Off switch is touched */

    led_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            // Turn the LED on or OFF based on the state of the switch

            mPSoCCapSenseLedService.writeLedCharacteristic(isChecked);

        }

    });



    /* This will be called when the CapSense Notify On/Off switch is touched */

    cap_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            // Turn CapSense Notifications on/off based on the state of the switch

            mPSoCCapSenseLedService.writeCapSenseNotification(isChecked);

            CapSenseNotifyState = isChecked;  // Keep track of CapSense notification state

            if(isChecked) { // Notifications are now on so text has to say "No Touch"

                mCapsenseValue.setText(R.string.NoTouch);

            } else { // Notifications are now off so text has to say "Notify Off"

                mCapsenseValue.setText(R.string.NotifyOff);

            }

        }

    });

}



//This method required for Android 6.0 (Marshmallow)

@Override

public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {

    switch (requestCode) {

        case PERMISSION_REQUEST_COARSE_LOCATION: {

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {


                Log.d( TAG, "Coarse location permission granted");

            } else {

                final AlertDialog.Builder builder = new AlertDialog.Builder(this);

                builder.setTitle("Functionality limited");

                builder.setMessage("Since location access has not been granted, this app will not be able to discover beacons when in the background.");

                builder.setPositiveButton(android.R.string.ok, null);

                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {

                    @Override

                    public void onDismiss(DialogInterface dialog) {

                    }

                });

                builder.show();

            }
            return;
        }

    }

} //End of section for Android 6.0 (Marshmallow)



@Override

protected void onResume() {

    super.onResume();

    // Register the broadcast receiver. This specified the messages the main activity looks for from the PSoCCapSenseLedService

    final IntentFilter filter = new IntentFilter();

    filter.addAction(PSoCCapSenseLedService.ACTION_BLESCAN_CALLBACK);

    filter.addAction(PSoCCapSenseLedService.ACTION_CONNECTED);

    filter.addAction(PSoCCapSenseLedService.ACTION_DISCONNECTED);

    filter.addAction(PSoCCapSenseLedService.ACTION_SERVICES_DISCOVERED);

    filter.addAction(PSoCCapSenseLedService.ACTION_DATA_RECEIVED);

    registerReceiver(mBleUpdateReceiver, filter);

}



@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    // User chose not to enable Bluetooth.

    if (requestCode == REQUEST_ENABLE_BLE && resultCode == Activity.RESULT_CANCELED) {

        finish();

        return;

    }

    super.onActivityResult(requestCode, resultCode, data);

}



@Override

protected void onPause() {

    super.onPause();

    unregisterReceiver(mBleUpdateReceiver);

}



@Override

protected void onDestroy() {

    super.onDestroy();

    // Close and unbind the service when the activity goes away

    mPSoCCapSenseLedService.close();

    unbindService(mServiceConnection);

    mPSoCCapSenseLedService = null;

    mServiceConnected = false;

}



/**

 * This method handles the start bluetooth button

 *

 * @param view the view object

 */

public void startBluetooth(View view) {


    // Find BLE service and adapter

    final BluetoothManager bluetoothManager =

            (BluetoothManager) getSystemService( Context.BLUETOOTH_SERVICE );

    BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();







    // 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()) {

        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BLE);

    }



    // Start the BLE Service

    Log.d(TAG, "Starting BLE Service");

    Intent gattServiceIntent = new Intent(this, PSoCCapSenseLedService.class);

    bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);



    // Disable the start button and turn on the search  button

    start_button.setEnabled(false);

    search_button.setEnabled(true);

    Log.d(TAG, "Bluetooth is Enabled");

}




/**

 * This method handles the Search for Device button

 *

 * @param view the view object

 */

public void searchBluetooth(View view) {

    if(mServiceConnected) {

        mPSoCCapSenseLedService.scan();

    }



    /* After this we wait for the scan callback to detect that a device has been found */

    /* The callback broadcasts a message which is picked up by the mGattUpdateReceiver */

}



/**

 * This method handles the Connect to Device button

 *

 * @param view the view object

 */

public void connectBluetooth(View view) {

    mPSoCCapSenseLedService.connect();



    /* After this we wait for the gatt callback to report the device is connected */

    /* That event broadcasts a message which is picked up by the mGattUpdateReceiver */

}



/**

 * This method handles the Discover Services and Characteristics button

 *

 * @param view the view object

 */

public void discoverServices(View view) {

    /* This will discover both services and characteristics */

    mPSoCCapSenseLedService.discoverServices();



    /* After this we wait for the gatt callback to report the services and characteristics */

    /* That event broadcasts a message which is picked up by the mGattUpdateReceiver */

}



/**

 * This method handles the Disconnect button

 *

 * @param view the view object

 */

public void Disconnect(View view) {

    mPSoCCapSenseLedService.disconnect();



    /* After this we wait for the gatt callback to report the device is disconnected */

    /* That event broadcasts a message which is picked up by the mGattUpdateReceiver */

}





private final BroadcastReceiver mBleUpdateReceiver = new BroadcastReceiver() {

    public Object device;

    @Override

    public void onReceive(Context context, Intent intent) {

        final String action = intent.getAction();

        switch (action) {

            case PSoCCapSenseLedService.ACTION_BLESCAN_CALLBACK:

                // Disable the search button and enable the connect button

                search_button.setEnabled(false);

                connect_button.setEnabled(true);

                break;



            case PSoCCapSenseLedService.ACTION_CONNECTED:

                /* This if statement is needed because we sometimes get a GATT_CONNECTED */

                /* action when sending Capsense notifications */

                if (!mConnectState) {

                    // Dsable the connect button, enable the discover services and disconnect buttons

                    connect_button.setEnabled(false);

                    discover_button.setEnabled(true);

                    disconnect_button.setEnabled(true);

                    mConnectState = true;

                    Log.d(TAG, "Connected to Device");

                }

                break;

            case PSoCCapSenseLedService.ACTION_DISCONNECTED:

                // Disable the disconnect, discover svc, discover char button, and enable the search button

                disconnect_button.setEnabled(false);

                discover_button.setEnabled(false);

                search_button.setEnabled(true);

                // Turn off and disable the LED and CapSense switches

                led_switch.setChecked(false);

                led_switch.setEnabled(false);

                cap_switch.setChecked(false);

                cap_switch.setEnabled(false);

                mConnectState = false;

                Log.d(TAG, "Disconnected");

                break;

            case PSoCCapSenseLedService.ACTION_SERVICES_DISCOVERED:

                // Disable the discover services button

                discover_button.setEnabled(false);

                // Enable the LED and CapSense switches

                led_switch.setEnabled(true);

                cap_switch.setEnabled(true);

                Log.d(TAG, "Services Discovered");

                break;

            case PSoCCapSenseLedService.ACTION_DATA_RECEIVED:

                // This is called after a notify or a read completes

                // Check LED switch Setting

                if(mPSoCCapSenseLedService.getLedSwitchState()){

                    led_switch.setChecked(true);

                } else {

                    led_switch.setChecked(false);

                }

                // Get CapSense Slider Value

                String CapSensePos = mPSoCCapSenseLedService.getCapSenseValue();

                if (CapSensePos.equals("-1")) {  // No Touch returns 0xFFFF which is -1

                    if(!CapSenseNotifyState) { // Notifications are off

                        mCapsenseValue.setText( R.string.NotifyOff);

                    } else { // Notifications are on but there is no finger on the slider

                        mCapsenseValue.setText(R.string.NoTouch);

                    }

                } else { // Valid CapSense value is returned

                    mCapsenseValue.setText(CapSensePos);

                }


            default:

                break;







        }

    }

};

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.