diff --git a/.idea/compiler.xml b/.idea/compiler.xml
index fb7f4a8..659bf43 100644
--- a/.idea/compiler.xml
+++ b/.idea/compiler.xml
@@ -1,6 +1,6 @@
-
+
\ No newline at end of file
diff --git a/.idea/gradle.xml b/.idea/gradle.xml
index 526b4c2..fd51e56 100644
--- a/.idea/gradle.xml
+++ b/.idea/gradle.xml
@@ -7,6 +7,7 @@
+
diff --git a/.idea/vcs.xml b/.idea/vcs.xml
index 35eb1dd..94a25f7 100644
--- a/.idea/vcs.xml
+++ b/.idea/vcs.xml
@@ -1,6 +1,6 @@
-
+
\ No newline at end of file
diff --git a/app/build.gradle b/app/build.gradle
index c56f569..5469661 100644
--- a/app/build.gradle
+++ b/app/build.gradle
@@ -3,6 +3,13 @@ plugins {
}
android {
+ packagingOptions {
+ resources {
+ excludes += 'plugin.xml'
+ excludes += 'plugin.properties'
+ excludes += 'about_files/LICENSE*'
+ }
+ }
compileSdk 31
defaultConfig {
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 6df4fb5..f135637 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -2,6 +2,14 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/java/com/example/bottomnav/BluetoothLeService.java b/app/src/main/java/com/example/bottomnav/BluetoothLeService.java
new file mode 100644
index 0000000..2b5d74e
--- /dev/null
+++ b/app/src/main/java/com/example/bottomnav/BluetoothLeService.java
@@ -0,0 +1,418 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.example.bottomnav;
+
+
+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.content.Context;
+import android.content.Intent;
+import android.os.Binder;
+import android.os.IBinder;
+import android.util.Log;
+
+import com.example.bottomnav.bluetoothlegatt.SampleGattAttributes;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.UUID;
+
+/**
+ * Service for managing connection and data communication with a GATT server hosted on a
+ * given Bluetooth LE device.
+ */
+public class BluetoothLeService extends Service {
+ private final static String TAG = BluetoothLeService.class.getSimpleName();
+
+ private BluetoothManager mBluetoothManager;
+ private BluetoothAdapter mBluetoothAdapter;
+ private String mBluetoothDeviceAddress;
+ private BluetoothGatt mBluetoothGatt;
+ private int mConnectionState = STATE_DISCONNECTED;
+
+ private static final int STATE_DISCONNECTED = 0;
+ private static final int STATE_CONNECTING = 1;
+ private static final int STATE_CONNECTED = 2;
+
+ public final static String ACTION_GATT_CONNECTED =
+ "com.example.bluetooth.le.ACTION_GATT_CONNECTED";
+ public final static String ACTION_GATT_DISCONNECTED =
+ "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
+ public final static String ACTION_GATT_SERVICES_DISCOVERED =
+ "com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
+ public final static String ACTION_DATA_AVAILABLE =
+ "com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
+ public final static String EXTRA_DATA =
+ "com.example.bluetooth.le.EXTRA_DATA";
+ private BluetoothGattCharacteristic readCharacteristic, writeCharacteristic;
+ private static final UUID BLUETOOTH_LE_NRF_CHAR_RW2 = UUID.fromString("6e400002-b5a3-f393-e0a9-e50e24dcca9e"); // read on microbit, write on adafruit
+ private static final UUID BLUETOOTH_LE_NRF_CHAR_RW3 = UUID.fromString("6e400003-b5a3-f393-e0a9-e50e24dcca9e");
+ private static final UUID BLUETOOTH_LE_NRF_SERVICE = UUID.fromString("6e400001-b5a3-f393-e0a9-e50e24dcca9e");
+ public final static UUID UUID_HEART_RATE_MEASUREMENT =
+ UUID.fromString(SampleGattAttributes.HEART_RATE_MEASUREMENT);
+ private static final UUID BLUETOOTH_LE_CCCD = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
+
+ // 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) {
+ String intentAction;
+ if (newState == BluetoothProfile.STATE_CONNECTED) {
+ intentAction = ACTION_GATT_CONNECTED;
+ mConnectionState = STATE_CONNECTED;
+ broadcastUpdate(intentAction);
+
+ Log.i(TAG, "Connected to GATT server.");
+ // Attempts to discover services after successful connection.
+ Log.i(TAG, "Attempting to start service discovery:" +
+ mBluetoothGatt.discoverServices());
+
+ } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
+ intentAction = ACTION_GATT_DISCONNECTED;
+ mConnectionState = STATE_DISCONNECTED;
+ Log.i(TAG, "Disconnected from GATT server.");
+ broadcastUpdate(intentAction);
+ }
+ }
+
+
+ @Override
+ public void onServicesDiscovered(BluetoothGatt gatt, int status) {
+ if (status == BluetoothGatt.GATT_SUCCESS) {
+ broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
+ for (BluetoothGattService gattService : gatt.getServices()) {
+ if (gattService.getUuid().equals(BLUETOOTH_LE_NRF_SERVICE)) {
+ Log.w(TAG, "nrfservice: " + status);
+ if(connectCharacteristics(gattService)){
+ connectCharacteristics3(gatt);
+ };
+ }
+ }
+ } else {
+ Log.w(TAG, "onServicesDiscovered received: " + status);
+ }
+ }
+
+ @Override
+ public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
+ if (status == BluetoothGatt.GATT_SUCCESS) {
+ final byte[] dataInput = characteristic.getValue();
+ Log.i(TAG, "read:" + Arrays.toString(dataInput));
+ broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
+ }
+ else{
+ Log.i(TAG, "sadge");
+ }
+ }
+
+ @Override
+ public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
+ super.onDescriptorWrite(gatt, descriptor, status);
+ }
+
+ @Override
+ public void onCharacteristicChanged(BluetoothGatt gatt,
+ BluetoothGattCharacteristic characteristic) {
+ final byte[] dataInput = characteristic.getValue();
+ Log.i(TAG, "change"+ dataInput.toString() );
+ broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
+ }
+
+ boolean connectCharacteristics(BluetoothGattService gattService) {
+ Log.d(TAG, "service nrf uart");
+ BluetoothGattCharacteristic rw2 = gattService.getCharacteristic(BLUETOOTH_LE_NRF_CHAR_RW2);
+ BluetoothGattCharacteristic rw3 = gattService.getCharacteristic(BLUETOOTH_LE_NRF_CHAR_RW3);
+ if (rw2 != null && rw3 != null) {
+ int rw2prop = rw2.getProperties();
+ int rw3prop = rw3.getProperties();
+ boolean rw2write = (rw2prop & BluetoothGattCharacteristic.PROPERTY_WRITE) != 0;
+ boolean rw3write = (rw3prop & BluetoothGattCharacteristic.PROPERTY_WRITE) != 0;
+ Log.d(TAG, "characteristic properties " + rw2prop + "/" + rw3prop);
+ if (rw2write) {
+ writeCharacteristic = rw2;
+ readCharacteristic = rw3;
+ } else if (rw3write) {
+ writeCharacteristic = rw3;
+ readCharacteristic = rw2;
+ }
+ }
+ return true;
+ }
+ private void connectCharacteristics3(BluetoothGatt gatt) {
+ int writeProperties = writeCharacteristic.getProperties();
+ if((writeProperties & (BluetoothGattCharacteristic.PROPERTY_WRITE + // Microbit,HM10-clone have WRITE
+ BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE)) ==0) { // HM10,TI uart,Telit have only WRITE_NO_RESPONSE
+ return;
+ }
+ if(!gatt.setCharacteristicNotification(readCharacteristic,true)) {
+ return;
+ }
+ BluetoothGattDescriptor readDescriptor = readCharacteristic.getDescriptor(BLUETOOTH_LE_CCCD);
+ if(readDescriptor == null) {
+ return;
+ }
+ int readProperties = readCharacteristic.getProperties();
+ if((readProperties & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0) {
+ Log.d(TAG, "enable read indication");
+ readDescriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
+ }else if((readProperties & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) {
+ Log.d(TAG, "enable read notification");
+ readDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
+ } else {
+
+ return;
+ }
+ Log.d(TAG,"writing read characteristic descriptor");
+ if(!gatt.writeDescriptor(readDescriptor)) {
+
+ }
+ // continues asynchronously in onDescriptorWrite()
+ }
+
+ };
+
+
+ private void broadcastUpdate(final String action) {
+ final Intent intent = new Intent(action);
+ sendBroadcast(intent);
+ }
+
+ private void broadcastUpdate(final String action,
+ final BluetoothGattCharacteristic characteristic) {
+ final Intent intent = new Intent(action);
+
+ // This is special handling for the Heart Rate Measurement profile. Data parsing is
+ // carried out as per profile specifications:
+ // http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml
+ if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
+ int flag = characteristic.getProperties();
+ int format = -1;
+ if ((flag & 0x01) != 0) {
+ format = BluetoothGattCharacteristic.FORMAT_UINT16;
+ Log.d(TAG, "Heart rate format UINT16.");
+ } else {
+ format = BluetoothGattCharacteristic.FORMAT_UINT8;
+ Log.d(TAG, "Heart rate format UINT8.");
+ }
+ final int heartRate = characteristic.getIntValue(format, 1);
+ Log.d(TAG, String.format("Received heart rate: %d", heartRate));
+ intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));
+ } else {
+ // For all other profiles, writes the data formatted in HEX.
+ final byte[] data = characteristic.getValue();
+ if (data != null && data.length > 0) {
+ final StringBuilder stringBuilder = new StringBuilder(data.length);
+ for(byte byteChar : data)
+ stringBuilder.append(String.format("%02X ", byteChar));
+ intent.putExtra(EXTRA_DATA, new String(data) + "\n" + stringBuilder.toString());
+ }
+ }
+ sendBroadcast(intent);
+ }
+
+ public class LocalBinder extends Binder {
+ BluetoothLeService getService() {
+ return BluetoothLeService.this;
+ }
+ }
+
+ @Override
+ public IBinder onBind(Intent intent) {
+ return mBinder;
+ }
+
+ @Override
+ public boolean onUnbind(Intent intent) {
+ // After using a given device, you should make sure that BluetoothGatt.close() is called
+ // such that resources are cleaned up properly. In this particular example, close() is
+ // invoked when the UI is disconnected from the Service.
+ 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;
+ }
+
+ /**
+ * Connects to the GATT server hosted on the Bluetooth LE device.
+ *
+ * @param address The device address of the destination 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(final String address) {
+ if (mBluetoothAdapter == null || address == null) {
+ Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
+ return false;
+ }
+
+ // Previously connected device. Try to reconnect.
+ if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
+ && mBluetoothGatt != null) {
+ Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
+ if (mBluetoothGatt.connect()) {
+ mConnectionState = STATE_CONNECTING;
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
+ if (device == null) {
+ Log.w(TAG, "Device not found. Unable to connect.");
+ return false;
+ }
+ // We want to directly connect to the device, so we are setting the autoConnect
+ // parameter to false.
+ mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
+ Log.d(TAG, "Trying to create a new connection.");
+ mBluetoothDeviceAddress = address;
+ mConnectionState = STATE_CONNECTING;
+ return true;
+ }
+
+ /**
+ * 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;
+ }
+
+ /**
+ * Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported
+ * asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
+ * callback.
+ *
+ * @param characteristic The characteristic to read from.
+ */
+ public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
+ if (mBluetoothAdapter == null || mBluetoothGatt == null) {
+ Log.w(TAG, "BluetoothAdapter not initialized");
+ return;
+ }
+ mBluetoothGatt.readCharacteristic(characteristic);
+
+ }
+
+ /**
+ * Enables or disables notification on a give characteristic.
+ *
+ * @param characteristic Characteristic to act on.
+ * @param enabled If true, enable notification. False otherwise.
+ */
+
+ public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
+ boolean enabled) {
+ if (mBluetoothAdapter == null || mBluetoothGatt == null) {
+ Log.w(TAG, "BluetoothAdapter not initialized");
+ return;
+ }
+ for (BluetoothGattDescriptor descriptor:characteristic.getDescriptors()){
+ Log.e(TAG, "BluetoothGattDescriptor: "+ descriptor.getUuid().toString());
+ }
+
+
+ // This is specific to Heart Rate Measurement.
+ if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
+ BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
+ UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
+ descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
+ mBluetoothGatt.writeDescriptor(descriptor);
+
+ }
+ else{
+ mBluetoothGatt.setCharacteristicNotification(characteristic,true);
+ BluetoothGattDescriptor readDescriptor = characteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
+ mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
+ mBluetoothGatt.readDescriptor(readDescriptor );
+ readDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
+ readDescriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
+ if(!mBluetoothGatt.writeDescriptor(readDescriptor)) {
+ Log.i(TAG, "sadge");
+ }
+
+ }
+ }
+
+ /**
+ * Retrieves a list of supported GATT services on the connected device. This should be
+ * invoked only after {@code BluetoothGatt#discoverServices()} completes successfully.
+ *
+ * @return A {@code List} of supported services.
+ */
+ public List getSupportedGattServices() {
+ if (mBluetoothGatt == null) return null;
+
+ return mBluetoothGatt.getServices();
+ }
+}
diff --git a/app/src/main/java/com/example/bottomnav/CAN_Data.java b/app/src/main/java/com/example/bottomnav/CAN_Data.java
new file mode 100644
index 0000000..abb877f
--- /dev/null
+++ b/app/src/main/java/com/example/bottomnav/CAN_Data.java
@@ -0,0 +1,56 @@
+package com.example.bottomnav;
+
+
+import java.util.Arrays;
+
+class CAN_Data {
+ byte id;
+ byte[] data;
+
+ public CAN_Data(byte id, byte[] data) {
+ this.id = id;
+ this.data = data;
+ }
+
+ public static CAN_Data decode(String raw) {
+ byte id;
+ int len;
+
+ int index = -1;
+ if (raw.charAt(0) == 't' || raw.charAt(0) == 'r') {
+ id = Byte.parseByte(raw.substring(1, 4), 16);
+ index = 4;
+ }
+ else if (raw.charAt(0) == 'T' || raw.charAt(0) == 'R') {
+ id = Byte.parseByte(raw.substring(1, 9), 16);
+ index = 9;
+ }
+ else {
+ return null;
+ }
+
+ len = Integer.parseInt(raw.substring(index, index + 1), 16);
+ byte[] data = new byte[len];
+
+ for(int x = 0;x option = Optional.of(valueToString());;
+ if(option.isPresent()){
+ return option;
+ }
+ else{
+ return Optional.empty();
+ }
}
}
diff --git a/app/src/main/java/com/example/bottomnav/FloatDecoder.java b/app/src/main/java/com/example/bottomnav/FloatDecoder.java
index 97cdc7a..9ce725d 100644
--- a/app/src/main/java/com/example/bottomnav/FloatDecoder.java
+++ b/app/src/main/java/com/example/bottomnav/FloatDecoder.java
@@ -2,6 +2,7 @@
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
+import java.util.Optional;
public class FloatDecoder extends PrimitiveDecoder {
public FloatDecoder(VariableContents con) {
@@ -9,12 +10,21 @@ public FloatDecoder(VariableContents con) {
}
@Override
- public String decode(Integer canId, byte[] payload) {
+ public Optional decode(Integer canId, byte[] payload) {
ByteBuffer bb = ByteBuffer.wrap(payload);
byte[] packet = new byte[contents.packetSize];
+ if(payload.length < contents.packetSize){
+ return Optional.empty();
+ }
bb.get(packet, 0, contents.packetSize);
rawValue = (T) new Float(ByteBuffer.wrap(packet).order(ByteOrder.LITTLE_ENDIAN).getFloat());
value = "" + rawValue;
- return valueToString();
+ Optional option = Optional.of(valueToString());;
+ if(option.isPresent()){
+ return option;
+ }
+ else{
+ return Optional.empty();
+ }
}
}
diff --git a/app/src/main/java/com/example/bottomnav/IntegerDecoder.java b/app/src/main/java/com/example/bottomnav/IntegerDecoder.java
index 7684972..e8010b1 100644
--- a/app/src/main/java/com/example/bottomnav/IntegerDecoder.java
+++ b/app/src/main/java/com/example/bottomnav/IntegerDecoder.java
@@ -2,6 +2,7 @@
import java.math.BigInteger;
import java.nio.ByteBuffer;
+import java.util.Optional;
public class IntegerDecoder extends PrimitiveDecoder {
public IntegerDecoder(VariableContents contents) {
@@ -9,12 +10,20 @@ public IntegerDecoder(VariableContents contents) {
}
@Override
- public String decode(Integer canId, byte[] payload) {
+ public Optional decode(Integer canId, byte[] payload) {
ByteBuffer bb = ByteBuffer.wrap(payload);
byte[] packet = new byte[contents.packetSize];
bb.get(packet, 0, contents.packetSize);
rawValue = (T) new Integer(new BigInteger(packet).intValue());
+
+
value = "" + rawValue;
- return valueToString();
+ Optional option = Optional.of(valueToString());;
+ if(option.isPresent()){
+ return option;
+ }
+ else{
+ return Optional.empty();
+ }
}
}
diff --git a/app/src/main/java/com/example/bottomnav/MainActivity.java b/app/src/main/java/com/example/bottomnav/MainActivity.java
index 5a549f1..6334f92 100644
--- a/app/src/main/java/com/example/bottomnav/MainActivity.java
+++ b/app/src/main/java/com/example/bottomnav/MainActivity.java
@@ -1,17 +1,32 @@
package com.example.bottomnav;
+import android.Manifest;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.ServiceConnection;
import android.os.Bundle;
-import com.google.android.material.bottomnavigation.BottomNavigationView;
+import android.os.IBinder;
+import android.util.Log;
+import android.widget.ArrayAdapter;
+import android.widget.ExpandableListView;
+import android.widget.ListView;
+
import androidx.appcompat.app.AppCompatActivity;
+import androidx.core.app.ActivityCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
+
+import com.example.bottomnav.bluetoothlegatt.DeviceControlActivity;
+import com.example.bottomnav.databinding.ActivityMainBinding;
+import com.example.bottomnav.BluetoothLeService;
import com.example.bottomnav.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
-private ActivityMainBinding binding;
+ private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
@@ -23,11 +38,15 @@ protected void onCreate(Bundle savedInstanceState) {
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
- R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
+ R.id.navigation_home, R.id.navigation_table, R.id.navigation_notifications)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(binding.navView, navController);
+ ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.BLUETOOTH_CONNECT,Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001);
+
+
+
}
}
\ No newline at end of file
diff --git a/app/src/main/java/com/example/bottomnav/Parse.java b/app/src/main/java/com/example/bottomnav/Parse.java
index 5bdcd7b..0b8c8cf 100644
--- a/app/src/main/java/com/example/bottomnav/Parse.java
+++ b/app/src/main/java/com/example/bottomnav/Parse.java
@@ -91,7 +91,7 @@ private void storeStructDecoder(IASTDeclaration[] declarations, String name) thr
decoderRepo.put(name, decoder);
}
- public String decode(int canId, byte[] payload) {
+ public Optional decode(int canId, byte[] payload) {
String canName = canIdToName.get(canId);
Optional decoder = getDecoder(canName);
if (decoder.isPresent()) {
@@ -100,7 +100,7 @@ public String decode(int canId, byte[] payload) {
}
public Optional getDecoder(String name) {
- if (canNameToStruct.containsKey(name)) {
+ if (canNameToStruct.containsKey(name)&& decoderRepo.containsKey(canNameToStruct.get(name))) {
return decoderRepo.get(canNameToStruct.get(name));
} else if (decoderRepo.containsKey(name)) {
return decoderRepo.get(name);
diff --git a/app/src/main/java/com/example/bottomnav/PrimitiveDecoder.java b/app/src/main/java/com/example/bottomnav/PrimitiveDecoder.java
index 054ec22..42898ca 100644
--- a/app/src/main/java/com/example/bottomnav/PrimitiveDecoder.java
+++ b/app/src/main/java/com/example/bottomnav/PrimitiveDecoder.java
@@ -1,5 +1,7 @@
package com.example.bottomnav;
+import java.util.Optional;
+
public class PrimitiveDecoder implements DataDecoder {
protected VariableContents contents;
protected T rawValue;
@@ -11,7 +13,7 @@ public PrimitiveDecoder(VariableContents can) {
}
@Override
- public String decode(Integer canId, byte[] payload) {
+ public Optional decode(Integer canId, byte[] payload) {
return null;
}
diff --git a/app/src/main/java/com/example/bottomnav/StructDecoder.java b/app/src/main/java/com/example/bottomnav/StructDecoder.java
index 6d463a5..f924b34 100644
--- a/app/src/main/java/com/example/bottomnav/StructDecoder.java
+++ b/app/src/main/java/com/example/bottomnav/StructDecoder.java
@@ -32,7 +32,7 @@ public Object valueToRaw() {
}
@Override
- public String decode(Integer canId, byte[] payload) {
+ public Optional decode(Integer canId, byte[] payload) {
for (VariableContents variable : variables) {
Optional decoder = DataDecoder.createPrimitiveDecoder(variable);
if (decoder.isPresent()) {
@@ -41,7 +41,13 @@ public String decode(Integer canId, byte[] payload) {
payload = adjustPayload(payload, ((PrimitiveDecoder) decoder.get()).getPacketSize());
}
}
- return valueToString();
+ Optional option = Optional.of(valueToString());;
+ if(option.isPresent()){
+ return option;
+ }
+ else{
+ return Optional.empty();
+ }
}
// Splicing function for each variable
diff --git a/app/src/main/java/com/example/bottomnav/UnsignedIntegerDecoder.java b/app/src/main/java/com/example/bottomnav/UnsignedIntegerDecoder.java
index 9bc095f..8084671 100644
--- a/app/src/main/java/com/example/bottomnav/UnsignedIntegerDecoder.java
+++ b/app/src/main/java/com/example/bottomnav/UnsignedIntegerDecoder.java
@@ -2,6 +2,7 @@
import java.math.BigInteger;
import java.nio.ByteBuffer;
+import java.util.Optional;
public class UnsignedIntegerDecoder extends IntegerDecoder{
int sign;
@@ -12,13 +13,24 @@ public UnsignedIntegerDecoder(VariableContents contents, int givenSign) {
}
@Override
- public String decode(Integer canId, byte[] payload) {
+ public Optional decode(Integer canId, byte[] payload) {
ByteBuffer bb = ByteBuffer.wrap(payload);
byte[] packet = new byte[contents.packetSize];
+ if(payload.length < contents.packetSize){
+ return Optional.empty();
+ }
bb.get(packet, 0, contents.packetSize);
rawValue = (T) new Integer(new BigInteger(packet).intValue() & sign);
value = "" + rawValue;
- return valueToString();
+ Optional option = Optional.of(valueToString());;
+ if(option.isPresent()){
+ return option;
+ }
+ else{
+ return Optional.empty();
+ }
+
+
}
diff --git a/app/src/main/java/com/example/bottomnav/UnsignedLongDecoder.java b/app/src/main/java/com/example/bottomnav/UnsignedLongDecoder.java
index 6a7a787..7d06b0c 100644
--- a/app/src/main/java/com/example/bottomnav/UnsignedLongDecoder.java
+++ b/app/src/main/java/com/example/bottomnav/UnsignedLongDecoder.java
@@ -2,6 +2,7 @@
import java.math.BigInteger;
import java.nio.ByteBuffer;
+import java.util.Optional;
public class UnsignedLongDecoder extends IntegerDecoder {
Long sign;
@@ -12,12 +13,18 @@ public UnsignedLongDecoder(VariableContents contents) {
}
@Override
- public String decode(Integer canId, byte[] payload) {
+ public Optional decode(Integer canId, byte[] payload) {
ByteBuffer bb = ByteBuffer.wrap(payload);
byte[] packet = new byte[contents.packetSize];
bb.get(packet, 0, contents.packetSize);
rawValue = (T) new Long(new BigInteger(packet).longValue() & sign);
value = "" + rawValue;
- return valueToString();
+ Optional option = Optional.of(valueToString());;
+ if(option.isPresent()){
+ return option;
+ }
+ else{
+ return Optional.empty();
+ }
}
}
diff --git a/app/src/main/java/com/example/bottomnav/bluetoothlegatt/BluetoothLeService.java b/app/src/main/java/com/example/bottomnav/bluetoothlegatt/BluetoothLeService.java
new file mode 100644
index 0000000..3f49b6f
--- /dev/null
+++ b/app/src/main/java/com/example/bottomnav/bluetoothlegatt/BluetoothLeService.java
@@ -0,0 +1,415 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.example.bottomnav.bluetoothlegatt;
+
+
+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.content.Context;
+import android.content.Intent;
+import android.os.Binder;
+import android.os.IBinder;
+import android.util.Log;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.UUID;
+
+/**
+ * Service for managing connection and data communication with a GATT server hosted on a
+ * given Bluetooth LE device.
+ */
+public class BluetoothLeService extends Service {
+ private final static String TAG = BluetoothLeService.class.getSimpleName();
+
+ private BluetoothManager mBluetoothManager;
+ private BluetoothAdapter mBluetoothAdapter;
+ private String mBluetoothDeviceAddress;
+ private BluetoothGatt mBluetoothGatt;
+ private int mConnectionState = STATE_DISCONNECTED;
+
+ private static final int STATE_DISCONNECTED = 0;
+ private static final int STATE_CONNECTING = 1;
+ private static final int STATE_CONNECTED = 2;
+
+ public final static String ACTION_GATT_CONNECTED =
+ "com.example.bluetooth.le.ACTION_GATT_CONNECTED";
+ public final static String ACTION_GATT_DISCONNECTED =
+ "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
+ public final static String ACTION_GATT_SERVICES_DISCOVERED =
+ "com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
+ public final static String ACTION_DATA_AVAILABLE =
+ "com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
+ public final static String EXTRA_DATA =
+ "com.example.bluetooth.le.EXTRA_DATA";
+ private BluetoothGattCharacteristic readCharacteristic, writeCharacteristic;
+ private static final UUID BLUETOOTH_LE_NRF_CHAR_RW2 = UUID.fromString("6e400002-b5a3-f393-e0a9-e50e24dcca9e"); // read on microbit, write on adafruit
+ private static final UUID BLUETOOTH_LE_NRF_CHAR_RW3 = UUID.fromString("6e400003-b5a3-f393-e0a9-e50e24dcca9e");
+ private static final UUID BLUETOOTH_LE_NRF_SERVICE = UUID.fromString("6e400001-b5a3-f393-e0a9-e50e24dcca9e");
+ public final static UUID UUID_HEART_RATE_MEASUREMENT =
+ UUID.fromString(SampleGattAttributes.HEART_RATE_MEASUREMENT);
+ private static final UUID BLUETOOTH_LE_CCCD = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
+
+ // 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) {
+ String intentAction;
+ if (newState == BluetoothProfile.STATE_CONNECTED) {
+ intentAction = ACTION_GATT_CONNECTED;
+ mConnectionState = STATE_CONNECTED;
+ broadcastUpdate(intentAction);
+
+ Log.i(TAG, "Connected to GATT server.");
+ // Attempts to discover services after successful connection.
+ Log.i(TAG, "Attempting to start service discovery:" +
+ mBluetoothGatt.discoverServices());
+
+ } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
+ intentAction = ACTION_GATT_DISCONNECTED;
+ mConnectionState = STATE_DISCONNECTED;
+ Log.i(TAG, "Disconnected from GATT server.");
+ broadcastUpdate(intentAction);
+ }
+ }
+
+ @Override
+ public void onServicesDiscovered(BluetoothGatt gatt, int status) {
+ if (status == BluetoothGatt.GATT_SUCCESS) {
+ broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
+ for (BluetoothGattService gattService : gatt.getServices()) {
+ if (gattService.getUuid().equals(BLUETOOTH_LE_NRF_SERVICE)) {
+ Log.w(TAG, "nrfservice: " + status);
+ if(connectCharacteristics(gattService)){
+ connectCharacteristics3(gatt);
+ };
+ }
+ }
+ } else {
+ Log.w(TAG, "onServicesDiscovered received: " + status);
+ }
+ }
+
+ @Override
+ public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
+ if (status == BluetoothGatt.GATT_SUCCESS) {
+ final byte[] dataInput = characteristic.getValue();
+ Log.i(TAG, "read:" + Arrays.toString(dataInput));
+ broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
+ }
+ else{
+ Log.i(TAG, "sadge");
+ }
+ }
+
+ @Override
+ public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
+ super.onDescriptorWrite(gatt, descriptor, status);
+ }
+
+ @Override
+ public void onCharacteristicChanged(BluetoothGatt gatt,
+ BluetoothGattCharacteristic characteristic) {
+ final byte[] dataInput = characteristic.getValue();
+ Log.i(TAG, "change"+ dataInput.toString() );
+ broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
+ }
+
+ boolean connectCharacteristics(BluetoothGattService gattService) {
+ Log.d(TAG, "service nrf uart");
+ BluetoothGattCharacteristic rw2 = gattService.getCharacteristic(BLUETOOTH_LE_NRF_CHAR_RW2);
+ BluetoothGattCharacteristic rw3 = gattService.getCharacteristic(BLUETOOTH_LE_NRF_CHAR_RW3);
+ if (rw2 != null && rw3 != null) {
+ int rw2prop = rw2.getProperties();
+ int rw3prop = rw3.getProperties();
+ boolean rw2write = (rw2prop & BluetoothGattCharacteristic.PROPERTY_WRITE) != 0;
+ boolean rw3write = (rw3prop & BluetoothGattCharacteristic.PROPERTY_WRITE) != 0;
+ Log.d(TAG, "characteristic properties " + rw2prop + "/" + rw3prop);
+ if (rw2write) {
+ writeCharacteristic = rw2;
+ readCharacteristic = rw3;
+ } else if (rw3write) {
+ writeCharacteristic = rw3;
+ readCharacteristic = rw2;
+ }
+ }
+ return true;
+ }
+ private void connectCharacteristics3(BluetoothGatt gatt) {
+ int writeProperties = writeCharacteristic.getProperties();
+ if((writeProperties & (BluetoothGattCharacteristic.PROPERTY_WRITE + // Microbit,HM10-clone have WRITE
+ BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE)) ==0) { // HM10,TI uart,Telit have only WRITE_NO_RESPONSE
+ return;
+ }
+ if(!gatt.setCharacteristicNotification(readCharacteristic,true)) {
+ return;
+ }
+ BluetoothGattDescriptor readDescriptor = readCharacteristic.getDescriptor(BLUETOOTH_LE_CCCD);
+ if(readDescriptor == null) {
+ return;
+ }
+ int readProperties = readCharacteristic.getProperties();
+ if((readProperties & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0) {
+ Log.d(TAG, "enable read indication");
+ readDescriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
+ }else if((readProperties & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) {
+ Log.d(TAG, "enable read notification");
+ readDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
+ } else {
+
+ return;
+ }
+ Log.d(TAG,"writing read characteristic descriptor");
+ if(!gatt.writeDescriptor(readDescriptor)) {
+
+ }
+ // continues asynchronously in onDescriptorWrite()
+ }
+
+ };
+
+
+ private void broadcastUpdate(final String action) {
+ final Intent intent = new Intent(action);
+ sendBroadcast(intent);
+ }
+
+ private void broadcastUpdate(final String action,
+ final BluetoothGattCharacteristic characteristic) {
+ final Intent intent = new Intent(action);
+
+ // This is special handling for the Heart Rate Measurement profile. Data parsing is
+ // carried out as per profile specifications:
+ // http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml
+ if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
+ int flag = characteristic.getProperties();
+ int format = -1;
+ if ((flag & 0x01) != 0) {
+ format = BluetoothGattCharacteristic.FORMAT_UINT16;
+ Log.d(TAG, "Heart rate format UINT16.");
+ } else {
+ format = BluetoothGattCharacteristic.FORMAT_UINT8;
+ Log.d(TAG, "Heart rate format UINT8.");
+ }
+ final int heartRate = characteristic.getIntValue(format, 1);
+ Log.d(TAG, String.format("Received heart rate: %d", heartRate));
+ intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));
+ } else {
+ // For all other profiles, writes the data formatted in HEX.
+ final byte[] data = characteristic.getValue();
+ if (data != null && data.length > 0) {
+ final StringBuilder stringBuilder = new StringBuilder(data.length);
+ for(byte byteChar : data)
+ stringBuilder.append(String.format("%02X ", byteChar));
+ intent.putExtra(EXTRA_DATA, new String(data) + "\n" + stringBuilder.toString());
+ }
+ }
+ sendBroadcast(intent);
+ }
+
+ public class LocalBinder extends Binder {
+ BluetoothLeService getService() {
+ return BluetoothLeService.this;
+ }
+ }
+
+ @Override
+ public IBinder onBind(Intent intent) {
+ return mBinder;
+ }
+
+ @Override
+ public boolean onUnbind(Intent intent) {
+ // After using a given device, you should make sure that BluetoothGatt.close() is called
+ // such that resources are cleaned up properly. In this particular example, close() is
+ // invoked when the UI is disconnected from the Service.
+ 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;
+ }
+
+ /**
+ * Connects to the GATT server hosted on the Bluetooth LE device.
+ *
+ * @param address The device address of the destination 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(final String address) {
+ if (mBluetoothAdapter == null || address == null) {
+ Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
+ return false;
+ }
+
+ // Previously connected device. Try to reconnect.
+ if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
+ && mBluetoothGatt != null) {
+ Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
+ if (mBluetoothGatt.connect()) {
+ mConnectionState = STATE_CONNECTING;
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
+ if (device == null) {
+ Log.w(TAG, "Device not found. Unable to connect.");
+ return false;
+ }
+ // We want to directly connect to the device, so we are setting the autoConnect
+ // parameter to false.
+ mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
+ Log.d(TAG, "Trying to create a new connection.");
+ mBluetoothDeviceAddress = address;
+ mConnectionState = STATE_CONNECTING;
+ return true;
+ }
+
+ /**
+ * 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;
+ }
+
+ /**
+ * Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported
+ * asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
+ * callback.
+ *
+ * @param characteristic The characteristic to read from.
+ */
+ public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
+ if (mBluetoothAdapter == null || mBluetoothGatt == null) {
+ Log.w(TAG, "BluetoothAdapter not initialized");
+ return;
+ }
+ mBluetoothGatt.readCharacteristic(characteristic);
+
+ }
+
+ /**
+ * Enables or disables notification on a give characteristic.
+ *
+ * @param characteristic Characteristic to act on.
+ * @param enabled If true, enable notification. False otherwise.
+ */
+
+ public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
+ boolean enabled) {
+ if (mBluetoothAdapter == null || mBluetoothGatt == null) {
+ Log.w(TAG, "BluetoothAdapter not initialized");
+ return;
+ }
+ for (BluetoothGattDescriptor descriptor:characteristic.getDescriptors()){
+ Log.e(TAG, "BluetoothGattDescriptor: "+ descriptor.getUuid().toString());
+ }
+
+
+ // This is specific to Heart Rate Measurement.
+ if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
+ BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
+ UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
+ descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
+ mBluetoothGatt.writeDescriptor(descriptor);
+
+ }
+ else{
+ mBluetoothGatt.setCharacteristicNotification(characteristic,true);
+ BluetoothGattDescriptor readDescriptor = characteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
+ mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
+ mBluetoothGatt.readDescriptor(readDescriptor );
+ readDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
+ readDescriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
+ if(!mBluetoothGatt.writeDescriptor(readDescriptor)) {
+ Log.i(TAG, "sadge");
+ }
+
+ }
+ }
+
+ /**
+ * Retrieves a list of supported GATT services on the connected device. This should be
+ * invoked only after {@code BluetoothGatt#discoverServices()} completes successfully.
+ *
+ * @return A {@code List} of supported services.
+ */
+ public List getSupportedGattServices() {
+ if (mBluetoothGatt == null) return null;
+
+ return mBluetoothGatt.getServices();
+ }
+}
diff --git a/app/src/main/java/com/example/bottomnav/bluetoothlegatt/DeviceControlActivity.java b/app/src/main/java/com/example/bottomnav/bluetoothlegatt/DeviceControlActivity.java
new file mode 100644
index 0000000..f0bbea0
--- /dev/null
+++ b/app/src/main/java/com/example/bottomnav/bluetoothlegatt/DeviceControlActivity.java
@@ -0,0 +1,314 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.example.bottomnav.bluetoothlegatt;
+
+import com.example.bottomnav.R;
+import android.content.Intent;
+import android.os.Bundle;
+import android.view.View;
+import android.widget.EditText;
+import android.app.Activity;
+import android.bluetooth.BluetoothGattCharacteristic;
+import android.bluetooth.BluetoothGattService;
+import android.content.BroadcastReceiver;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.ServiceConnection;
+import android.os.Bundle;
+import android.os.IBinder;
+import android.util.Log;
+import android.view.Menu;
+import android.view.MenuItem;
+import android.view.View;
+import android.widget.ExpandableListView;
+import android.widget.SimpleExpandableListAdapter;
+import android.widget.TextView;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+/**
+ * For a given BLE device, this Activity provides the user interface to connect, display data,
+ * and display GATT services and characteristics supported by the device. The Activity
+ * communicates with {@code BluetoothLeService}, which in turn interacts with the
+ * Bluetooth LE API.
+ */
+public class DeviceControlActivity extends Activity {
+ private final static String TAG = DeviceControlActivity.class.getSimpleName();
+
+ public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
+ public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";
+
+ private TextView mConnectionState;
+ private TextView mDataField;
+ private String mDeviceName;
+ private String mDeviceAddress;
+ private ExpandableListView mGattServicesList;
+ private BluetoothLeService mBluetoothLeService;
+ private ArrayList> mGattCharacteristics =
+ new ArrayList>();
+ private boolean mConnected = false;
+ private BluetoothGattCharacteristic mNotifyCharacteristic;
+
+ private final String LIST_NAME = "NAME";
+ private final String LIST_UUID = "UUID";
+
+ // Code to manage Service lifecycle.
+ private final ServiceConnection mServiceConnection = new ServiceConnection() {
+
+ @Override
+ public void onServiceConnected(ComponentName componentName, IBinder service) {
+ mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
+ if (!mBluetoothLeService.initialize()) {
+ Log.e(TAG, "Unable to initialize Bluetooth");
+ finish();
+ }
+ // Automatically connects to the device upon successful start-up initialization.
+ mBluetoothLeService.connect(mDeviceAddress);
+ }
+
+ @Override
+ public void onServiceDisconnected(ComponentName componentName) {
+ mBluetoothLeService = null;
+ }
+ };
+
+ // Handles various events fired by the Service.
+ // ACTION_GATT_CONNECTED: connected to a GATT server.
+ // ACTION_GATT_DISCONNECTED: disconnected from a GATT server.
+ // ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services.
+ // ACTION_DATA_AVAILABLE: received data from the device. This can be a result of read
+ // or notification operations.
+ private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ final String action = intent.getAction();
+ if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
+ mConnected = true;
+ updateConnectionState(R.string.connected);
+ invalidateOptionsMenu();
+ } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
+ mConnected = false;
+ updateConnectionState(R.string.disconnected);
+ invalidateOptionsMenu();
+ clearUI();
+ } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
+ // Show all the supported services and characteristics on the user interface.
+ displayGattServices(mBluetoothLeService.getSupportedGattServices());
+ } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
+ displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
+ }
+ }
+ };
+
+ // If a given GATT characteristic is selected, check for supported features. This sample
+ // demonstrates 'Read' and 'Notify' features. See
+ // http://d.android.com/reference/android/bluetooth/BluetoothGatt.html for the complete
+ // list of supported characteristic features.
+ private final ExpandableListView.OnChildClickListener servicesListClickListner =
+ new ExpandableListView.OnChildClickListener() {
+ @Override
+ public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
+ int childPosition, long id) {
+ if (mGattCharacteristics != null) {
+ final BluetoothGattCharacteristic characteristic =
+ mGattCharacteristics.get(groupPosition).get(childPosition);
+ final int charaProp = characteristic.getProperties();
+ if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
+ // If there is an active notification on a characteristic, clear
+ // it first so it doesn't update the data field on the user interface.
+ if (mNotifyCharacteristic != null) {
+ mBluetoothLeService.setCharacteristicNotification(
+ mNotifyCharacteristic, false);
+ mNotifyCharacteristic = null;
+ }
+ mBluetoothLeService.readCharacteristic(characteristic);
+ }
+ if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
+ mNotifyCharacteristic = characteristic;
+ mBluetoothLeService.setCharacteristicNotification(
+ characteristic, true);
+ }
+ return true;
+ }
+ return false;
+ }
+ };
+
+ private void clearUI() {
+ mGattServicesList.setAdapter((SimpleExpandableListAdapter) null);
+ mDataField.setText(R.string.no_data);
+ }
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.gatt_services_characteristics);
+
+ final Intent intent = getIntent();
+ mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
+ mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);
+
+ // Sets up UI references.
+ ((TextView) findViewById(R.id.device_address)).setText(mDeviceAddress);
+ mGattServicesList = (ExpandableListView) findViewById(R.id.gatt_services_list);
+ mGattServicesList.setOnChildClickListener(servicesListClickListner);
+ mConnectionState = (TextView) findViewById(R.id.connection_state);
+ mDataField = (TextView) findViewById(R.id.data_value);
+
+ getActionBar().setTitle(mDeviceName);
+ getActionBar().setDisplayHomeAsUpEnabled(true);
+ Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
+ bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
+ if (mBluetoothLeService != null) {
+ final boolean result = mBluetoothLeService.connect(mDeviceAddress);
+ Log.d(TAG, "Connect request result=" + result);
+ }
+ }
+
+ @Override
+ protected void onPause() {
+ super.onPause();
+ unregisterReceiver(mGattUpdateReceiver);
+ }
+
+ @Override
+ protected void onDestroy() {
+ super.onDestroy();
+ unbindService(mServiceConnection);
+ mBluetoothLeService = null;
+ }
+
+ @Override
+ public boolean onCreateOptionsMenu(Menu menu) {
+ getMenuInflater().inflate(R.menu.gatt_services, menu);
+ if (mConnected) {
+ menu.findItem(R.id.menu_connect).setVisible(false);
+ menu.findItem(R.id.menu_disconnect).setVisible(true);
+ } else {
+ menu.findItem(R.id.menu_connect).setVisible(true);
+ menu.findItem(R.id.menu_disconnect).setVisible(false);
+ }
+ return true;
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ switch(item.getItemId()) {
+ case R.id.menu_connect:
+ mBluetoothLeService.connect(mDeviceAddress);
+ return true;
+ case R.id.menu_disconnect:
+ mBluetoothLeService.disconnect();
+ return true;
+ case android.R.id.home:
+ onBackPressed();
+ return true;
+ }
+ return super.onOptionsItemSelected(item);
+ }
+
+ private void updateConnectionState(final int resourceId) {
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mConnectionState.setText(resourceId);
+ }
+ });
+ }
+
+ private void displayData(String data) {
+ if (data != null) {
+ mDataField.setText(data);
+ }
+ }
+
+ // Demonstrates how to iterate through the supported GATT Services/Characteristics.
+ // In this sample, we populate the data structure that is bound to the ExpandableListView
+ // on the UI.
+ private void displayGattServices(List gattServices) {
+ if (gattServices == null) return;
+ String uuid = null;
+ String unknownServiceString = getResources().getString(R.string.unknown_service);
+ String unknownCharaString = getResources().getString(R.string.unknown_characteristic);
+ ArrayList> gattServiceData = new ArrayList>();
+ ArrayList>> gattCharacteristicData
+ = new ArrayList>>();
+ mGattCharacteristics = new ArrayList>();
+
+ // Loops through available GATT Services.
+ for (BluetoothGattService gattService : gattServices) {
+ HashMap currentServiceData = new HashMap();
+ uuid = gattService.getUuid().toString();
+ currentServiceData.put(
+ LIST_NAME, SampleGattAttributes.lookup(uuid, unknownServiceString));
+ currentServiceData.put(LIST_UUID, uuid);
+ gattServiceData.add(currentServiceData);
+
+ ArrayList> gattCharacteristicGroupData =
+ new ArrayList>();
+ List gattCharacteristics =
+ gattService.getCharacteristics();
+ ArrayList charas =
+ new ArrayList();
+
+ // Loops through available Characteristics.
+ for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
+ charas.add(gattCharacteristic);
+ HashMap currentCharaData = new HashMap();
+ uuid = gattCharacteristic.getUuid().toString();
+ currentCharaData.put(
+ LIST_NAME, SampleGattAttributes.lookup(uuid, unknownCharaString));
+ currentCharaData.put(LIST_UUID, uuid);
+ gattCharacteristicGroupData.add(currentCharaData);
+ }
+ mGattCharacteristics.add(charas);
+ gattCharacteristicData.add(gattCharacteristicGroupData);
+ }
+
+ SimpleExpandableListAdapter gattServiceAdapter = new SimpleExpandableListAdapter(
+ this,
+ gattServiceData,
+ android.R.layout.simple_expandable_list_item_2,
+ new String[] {LIST_NAME, LIST_UUID},
+ new int[] { android.R.id.text1, android.R.id.text2 },
+ gattCharacteristicData,
+ android.R.layout.simple_expandable_list_item_2,
+ new String[] {LIST_NAME, LIST_UUID},
+ new int[] { android.R.id.text1, android.R.id.text2 }
+ );
+ mGattServicesList.setAdapter(gattServiceAdapter);
+ }
+
+ private static IntentFilter makeGattUpdateIntentFilter() {
+ final IntentFilter intentFilter = new IntentFilter();
+ intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
+ intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
+ intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
+ intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
+ return intentFilter;
+ }
+}
diff --git a/app/src/main/java/com/example/bottomnav/bluetoothlegatt/DeviceScanActivity.java b/app/src/main/java/com/example/bottomnav/bluetoothlegatt/DeviceScanActivity.java
new file mode 100644
index 0000000..133308e
--- /dev/null
+++ b/app/src/main/java/com/example/bottomnav/bluetoothlegatt/DeviceScanActivity.java
@@ -0,0 +1,277 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.example.bottomnav.bluetoothlegatt;
+import com.example.bottomnav.MainActivity;
+import com.example.bottomnav.R;
+
+
+import android.Manifest;
+import android.app.Activity;
+import android.app.ListActivity;
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothDevice;
+import android.bluetooth.BluetoothManager;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.os.Bundle;
+import android.os.Handler;
+import androidx.core.app.ActivityCompat;
+import android.view.LayoutInflater;
+import android.view.Menu;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.BaseAdapter;
+import android.widget.ListView;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import java.util.ArrayList;
+
+/**
+ * Activity for scanning and displaying available Bluetooth LE devices.
+ */
+public class DeviceScanActivity extends ListActivity {
+ private LeDeviceListAdapter mLeDeviceListAdapter;
+ private BluetoothAdapter mBluetoothAdapter;
+ private boolean mScanning;
+ private Handler mHandler;
+
+ private static final int REQUEST_ENABLE_BT = 1;
+ // Stops scanning after 10 seconds.
+ private static final long SCAN_PERIOD = 10000;
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ //getActionBar().setTitle(R.string.title_devices);
+ mHandler = new Handler();
+
+ // 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();
+ }
+
+ // Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
+ // BluetoothAdapter through BluetoothManager.
+ //ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.BLUETOOTH_CONNECT,Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001);
+ final BluetoothManager bluetoothManager =
+ (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
+ mBluetoothAdapter = bluetoothManager.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();
+ finish();
+ return;
+ }
+ //ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001);
+
+
+ }
+
+ @Override
+ public boolean onCreateOptionsMenu(Menu menu) {
+ getMenuInflater().inflate(R.menu.main, menu);
+ if (!mScanning) {
+ menu.findItem(R.id.menu_stop).setVisible(false);
+ menu.findItem(R.id.menu_scan).setVisible(true);
+ menu.findItem(R.id.menu_refresh).setActionView(null);
+ } else {
+ menu.findItem(R.id.menu_stop).setVisible(true);
+ menu.findItem(R.id.menu_scan).setVisible(false);
+ menu.findItem(R.id.menu_refresh).setActionView(
+ R.layout.actionbar_indeterminate_progress);
+ }
+ return true;
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ switch (item.getItemId()) {
+ case R.id.menu_scan:
+ mLeDeviceListAdapter.clear();
+ scanLeDevice(true);
+ break;
+ case R.id.menu_stop:
+ scanLeDevice(false);
+ break;
+ }
+ return true;
+ }
+
+ @Override
+ protected void onResume() {
+ //ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001);
+ super.onResume();
+
+ // 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_BT);
+ }
+
+ // Initializes list view adapter.
+ mLeDeviceListAdapter = new LeDeviceListAdapter();
+ setListAdapter(mLeDeviceListAdapter);
+ scanLeDevice(true);
+ }
+
+ @Override
+ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+ // User chose not to enable Bluetooth.
+ if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
+ finish();
+ return;
+ }
+ super.onActivityResult(requestCode, resultCode, data);
+ }
+
+ @Override
+ protected void onPause() {
+ super.onPause();
+ scanLeDevice(false);
+ mLeDeviceListAdapter.clear();
+ }
+
+ @Override
+ protected void onListItemClick(ListView l, View v, int position, long id) {
+ final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
+ if (device == null) return;
+ final Intent intent = new Intent(this, MainActivity.class);
+ intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_NAME, device.getName());
+ intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());
+ if (mScanning) {
+ mBluetoothAdapter.stopLeScan(mLeScanCallback);
+ mScanning = false;
+ }
+ startActivity(intent);
+
+ }
+
+ private void scanLeDevice(final boolean enable) {
+ if (enable) {
+ // Stops scanning after a pre-defined scan period.
+ mHandler.postDelayed(new Runnable() {
+ @Override
+ public void run() {
+ mScanning = false;
+ mBluetoothAdapter.stopLeScan(mLeScanCallback);
+ invalidateOptionsMenu();
+ }
+ }, SCAN_PERIOD);
+
+ mScanning = true;
+ mBluetoothAdapter.startLeScan(mLeScanCallback);
+ } else {
+ mScanning = false;
+ mBluetoothAdapter.stopLeScan(mLeScanCallback);
+ }
+ invalidateOptionsMenu();
+ }
+
+ // Adapter for holding devices found through scanning.
+ private class LeDeviceListAdapter extends BaseAdapter {
+ private ArrayList mLeDevices;
+ private LayoutInflater mInflator;
+
+ public LeDeviceListAdapter() {
+ super();
+ mLeDevices = new ArrayList();
+ mInflator = DeviceScanActivity.this.getLayoutInflater();
+ }
+
+ public void addDevice(BluetoothDevice device) {
+ if(!mLeDevices.contains(device)) {
+ mLeDevices.add(device);
+ }
+ }
+
+ public BluetoothDevice getDevice(int position) {
+ return mLeDevices.get(position);
+ }
+
+ public void clear() {
+ mLeDevices.clear();
+ }
+
+ @Override
+ public int getCount() {
+ return mLeDevices.size();
+ }
+
+ @Override
+ public Object getItem(int i) {
+ return mLeDevices.get(i);
+ }
+
+ @Override
+ public long getItemId(int i) {
+ return i;
+ }
+
+ @Override
+ public View getView(int i, View view, ViewGroup viewGroup) {
+ ViewHolder viewHolder;
+ // General ListView optimization code.
+ if (view == null) {
+ view = mInflator.inflate(R.layout.listitem_device, null);
+ viewHolder = new ViewHolder();
+ viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address);
+ viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name);
+ view.setTag(viewHolder);
+ } else {
+ viewHolder = (ViewHolder) view.getTag();
+ }
+
+ BluetoothDevice device = mLeDevices.get(i);
+ final String deviceName = device.getName();
+ if (deviceName != null && deviceName.length() > 0)
+ viewHolder.deviceName.setText(deviceName);
+ else
+ viewHolder.deviceName.setText(R.string.unknown_device);
+ viewHolder.deviceAddress.setText(device.getAddress());
+
+ return view;
+ }
+ }
+
+ // Device scan callback.
+ private BluetoothAdapter.LeScanCallback mLeScanCallback =
+ new BluetoothAdapter.LeScanCallback() {
+
+ @Override
+ public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mLeDeviceListAdapter.addDevice(device);
+ mLeDeviceListAdapter.notifyDataSetChanged();
+ }
+ });
+ }
+ };
+
+ static class ViewHolder {
+ TextView deviceName;
+ TextView deviceAddress;
+ }
+}
diff --git a/app/src/main/java/com/example/bottomnav/bluetoothlegatt/SampleGattAttributes.java b/app/src/main/java/com/example/bottomnav/bluetoothlegatt/SampleGattAttributes.java
new file mode 100644
index 0000000..32860db
--- /dev/null
+++ b/app/src/main/java/com/example/bottomnav/bluetoothlegatt/SampleGattAttributes.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.example.bottomnav.bluetoothlegatt;
+
+import java.util.HashMap;
+
+/**
+ * This class includes a small subset of standard GATT attributes for demonstration purposes.
+ */
+public class SampleGattAttributes {
+ private static HashMap attributes = new HashMap();
+ public static String HEART_RATE_MEASUREMENT = "00002a37-0000-1000-8000-00805f9b34fb";
+ public static String CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb";
+
+ static {
+ // Sample Services.
+ attributes.put("0000180d-0000-1000-8000-00805f9b34fb", "Heart Rate Service");
+ attributes.put("0000180a-0000-1000-8000-00805f9b34fb", "Device Information Service");
+ // Sample Characteristics.
+ attributes.put(HEART_RATE_MEASUREMENT, "Heart Rate Measurement");
+ attributes.put("00002a29-0000-1000-8000-00805f9b34fb", "Manufacturer Name String");
+ }
+
+ public static String lookup(String uuid, String defaultName) {
+ String name = attributes.get(uuid);
+ return name == null ? defaultName : name;
+ }
+}
diff --git a/app/src/main/java/com/example/bottomnav/ui/DeviceScanActivity.java b/app/src/main/java/com/example/bottomnav/ui/DeviceScanActivity.java
new file mode 100644
index 0000000..4242780
--- /dev/null
+++ b/app/src/main/java/com/example/bottomnav/ui/DeviceScanActivity.java
@@ -0,0 +1,276 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.example.bottomnav.ui;
+
+import android.app.Activity;
+import android.app.ListActivity;
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothDevice;
+import android.bluetooth.BluetoothManager;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.os.Bundle;
+import android.os.Handler;
+import android.view.LayoutInflater;
+import android.view.Menu;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.BaseAdapter;
+import android.widget.ListView;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.example.bottomnav.MainActivity;
+import com.example.bottomnav.R;
+import com.example.bottomnav.bluetoothlegatt.DeviceControlActivity;
+
+import java.util.ArrayList;
+
+/**
+ * Activity for scanning and displaying available Bluetooth LE devices.
+ */
+public class DeviceScanActivity extends ListActivity {
+ private LeDeviceListAdapter mLeDeviceListAdapter;
+ private BluetoothAdapter mBluetoothAdapter;
+ private boolean mScanning;
+ private Handler mHandler;
+
+ private static final int REQUEST_ENABLE_BT = 1;
+ // Stops scanning after 10 seconds.
+ private static final long SCAN_PERIOD = 10000;
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ //getActionBar().setTitle(R.string.title_devices);
+ mHandler = new Handler();
+
+ // 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();
+ }
+
+ // Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
+ // BluetoothAdapter through BluetoothManager.
+ //ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.BLUETOOTH_CONNECT,Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001);
+ final BluetoothManager bluetoothManager =
+ (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
+ mBluetoothAdapter = bluetoothManager.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();
+ finish();
+ return;
+ }
+ //ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001);
+
+
+ }
+
+ @Override
+ public boolean onCreateOptionsMenu(Menu menu) {
+ getMenuInflater().inflate(R.menu.main, menu);
+ if (!mScanning) {
+ menu.findItem(R.id.menu_stop).setVisible(false);
+ menu.findItem(R.id.menu_scan).setVisible(true);
+ menu.findItem(R.id.menu_refresh).setActionView(null);
+ } else {
+ menu.findItem(R.id.menu_stop).setVisible(true);
+ menu.findItem(R.id.menu_scan).setVisible(false);
+ menu.findItem(R.id.menu_refresh).setActionView(
+ R.layout.actionbar_indeterminate_progress);
+ }
+ return true;
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ switch (item.getItemId()) {
+ case R.id.menu_scan:
+ mLeDeviceListAdapter.clear();
+ scanLeDevice(true);
+ break;
+ case R.id.menu_stop:
+ scanLeDevice(false);
+ break;
+ }
+ return true;
+ }
+
+ @Override
+ protected void onResume() {
+ //ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001);
+ super.onResume();
+
+ // 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_BT);
+ }
+
+ // Initializes list view adapter.
+ mLeDeviceListAdapter = new LeDeviceListAdapter();
+ setListAdapter(mLeDeviceListAdapter);
+ scanLeDevice(true);
+ }
+
+ @Override
+ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+ // User chose not to enable Bluetooth.
+ if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
+ finish();
+ return;
+ }
+ super.onActivityResult(requestCode, resultCode, data);
+ }
+
+ @Override
+ protected void onPause() {
+ super.onPause();
+ scanLeDevice(false);
+ mLeDeviceListAdapter.clear();
+ }
+
+ @Override
+ protected void onListItemClick(ListView l, View v, int position, long id) {
+ final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
+ if (device == null) return;
+ final Intent intent = new Intent(this, MainActivity.class);
+ intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_NAME, device.getName());
+ intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());
+ if (mScanning) {
+ mBluetoothAdapter.stopLeScan(mLeScanCallback);
+ mScanning = false;
+ }
+ startActivity(intent);
+
+ }
+
+ private void scanLeDevice(final boolean enable) {
+ if (enable) {
+ // Stops scanning after a pre-defined scan period.
+ mHandler.postDelayed(new Runnable() {
+ @Override
+ public void run() {
+ mScanning = false;
+ mBluetoothAdapter.stopLeScan(mLeScanCallback);
+ invalidateOptionsMenu();
+ }
+ }, SCAN_PERIOD);
+
+ mScanning = true;
+ mBluetoothAdapter.startLeScan(mLeScanCallback);
+ } else {
+ mScanning = false;
+ mBluetoothAdapter.stopLeScan(mLeScanCallback);
+ }
+ invalidateOptionsMenu();
+ }
+
+ // Adapter for holding devices found through scanning.
+ private class LeDeviceListAdapter extends BaseAdapter {
+ private ArrayList mLeDevices;
+ private LayoutInflater mInflator;
+
+ public LeDeviceListAdapter() {
+ super();
+ mLeDevices = new ArrayList();
+ mInflator = DeviceScanActivity.this.getLayoutInflater();
+ }
+
+ public void addDevice(BluetoothDevice device) {
+ if(!mLeDevices.contains(device) && device.getName().equals("Therm")) {
+ mLeDevices.add(device);
+ }
+ }
+
+ public BluetoothDevice getDevice(int position) {
+ return mLeDevices.get(position);
+ }
+
+ public void clear() {
+ mLeDevices.clear();
+ }
+
+ @Override
+ public int getCount() {
+ return mLeDevices.size();
+ }
+
+ @Override
+ public Object getItem(int i) {
+ return mLeDevices.get(i);
+ }
+
+ @Override
+ public long getItemId(int i) {
+ return i;
+ }
+
+ @Override
+ public View getView(int i, View view, ViewGroup viewGroup) {
+ ViewHolder viewHolder;
+ // General ListView optimization code.
+ if (view == null) {
+ view = mInflator.inflate(R.layout.listitem_device, null);
+ viewHolder = new ViewHolder();
+ viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address);
+ viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name);
+ view.setTag(viewHolder);
+ } else {
+ viewHolder = (ViewHolder) view.getTag();
+ }
+
+ BluetoothDevice device = mLeDevices.get(i);
+ final String deviceName = device.getName();
+ if (deviceName != null && deviceName.length() > 0)
+ viewHolder.deviceName.setText(deviceName);
+ else
+ viewHolder.deviceName.setText(R.string.unknown_device);
+ viewHolder.deviceAddress.setText(device.getAddress());
+
+ return view;
+ }
+ }
+
+ // Device scan callback.
+ private BluetoothAdapter.LeScanCallback mLeScanCallback =
+ new BluetoothAdapter.LeScanCallback() {
+
+ @Override
+ public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mLeDeviceListAdapter.addDevice(device);
+ mLeDeviceListAdapter.notifyDataSetChanged();
+ }
+ });
+ }
+ };
+
+ static class ViewHolder {
+ TextView deviceName;
+ TextView deviceAddress;
+ }
+}
diff --git a/app/src/main/java/com/example/bottomnav/ui/dashboard/DashboardFragment.java b/app/src/main/java/com/example/bottomnav/ui/dashboard/DashboardFragment.java
deleted file mode 100644
index ad80255..0000000
--- a/app/src/main/java/com/example/bottomnav/ui/dashboard/DashboardFragment.java
+++ /dev/null
@@ -1,42 +0,0 @@
-package com.example.bottomnav.ui.dashboard;
-
-import android.os.Bundle;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.TextView;
-import androidx.annotation.NonNull;
-import androidx.annotation.Nullable;
-import androidx.fragment.app.Fragment;
-import androidx.lifecycle.Observer;
-import androidx.lifecycle.ViewModelProvider;
-import com.example.bottomnav.R;
-import com.example.bottomnav.databinding.FragmentDashboardBinding;
-
-public class DashboardFragment extends Fragment {
-
- private DashboardViewModel dashboardViewModel;
- private FragmentDashboardBinding binding;
-
- public View onCreateView(@NonNull LayoutInflater inflater,
- ViewGroup container, Bundle savedInstanceState) {
- dashboardViewModel = new ViewModelProvider(this).get(DashboardViewModel.class);
-
- binding = FragmentDashboardBinding.inflate(inflater, container, false);
-
- final TextView textView = binding.textDashboard;
- dashboardViewModel.getText().observe(getViewLifecycleOwner(), new Observer() {
- @Override
- public void onChanged(@Nullable String s) {
- textView.setText(s);
- }
- });
- return binding.getRoot();
- }
-
- @Override
- public void onDestroyView() {
- super.onDestroyView();
- binding = null;
- }
-}
\ No newline at end of file
diff --git a/app/src/main/java/com/example/bottomnav/ui/home/HomeFragment.java b/app/src/main/java/com/example/bottomnav/ui/home/HomeFragment.java
index 1f51a89..07e7816 100644
--- a/app/src/main/java/com/example/bottomnav/ui/home/HomeFragment.java
+++ b/app/src/main/java/com/example/bottomnav/ui/home/HomeFragment.java
@@ -12,20 +12,39 @@
import androidx.lifecycle.ViewModelProvider;
import com.example.bottomnav.R;
import com.example.bottomnav.databinding.FragmentHomeBinding;
+import android.content.Intent;
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+import android.widget.TextView;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+import androidx.fragment.app.Fragment;
+import androidx.lifecycle.Observer;
+import androidx.lifecycle.ViewModelProvider;
+
+import com.example.bottomnav.MainActivity;
+import com.example.bottomnav.R;
+import com.example.bottomnav.databinding.FragmentSettingsBinding;
+import com.example.bottomnav.ui.DeviceScanActivity;
+import com.example.bottomnav.ui.settings.SettingsViewModel;
public class HomeFragment extends Fragment {
- private HomeViewModel homeViewModel;
- private FragmentHomeBinding binding;
+ private SettingsViewModel settingsViewModel;
+ private FragmentSettingsBinding binding;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
- homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class);
+ settingsViewModel = new ViewModelProvider(this).get(SettingsViewModel.class);
+ binding = FragmentSettingsBinding.inflate(inflater, container, false);
+ final TextView textView = binding.textSettings;
- binding = FragmentHomeBinding.inflate(inflater, container, false);
- final TextView textView = binding.textHome;
- homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer() {
+ settingsViewModel.getText().observe(getViewLifecycleOwner(), new Observer() {
@Override
public void onChanged(@Nullable String s) {
textView.setText(s);
@@ -34,6 +53,20 @@ public void onChanged(@Nullable String s) {
return binding.getRoot();
}
+ public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
+ super.onViewCreated(view, savedInstanceState);
+
+ Button button = view.findViewById(R.id.Scan);
+
+ View.OnClickListener onClickListener = v -> { // lambda function
+ final Intent intent = new Intent(this.getContext(), DeviceScanActivity.class);
+ startActivity(intent);
+ };
+
+ button.setOnClickListener(onClickListener);
+ }
+
+
@Override
public void onDestroyView() {
super.onDestroyView();
diff --git a/app/src/main/java/com/example/bottomnav/ui/notifications/BluetoothLeService.java b/app/src/main/java/com/example/bottomnav/ui/notifications/BluetoothLeService.java
new file mode 100644
index 0000000..8c0df57
--- /dev/null
+++ b/app/src/main/java/com/example/bottomnav/ui/notifications/BluetoothLeService.java
@@ -0,0 +1,418 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.example.bottomnav.ui.notifications;
+
+
+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.content.Context;
+import android.content.Intent;
+import android.os.Binder;
+import android.os.IBinder;
+import android.util.Log;
+
+import com.example.bottomnav.bluetoothlegatt.SampleGattAttributes;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.UUID;
+
+/**
+ * Service for managing connection and data communication with a GATT server hosted on a
+ * given Bluetooth LE device.
+ */
+public class BluetoothLeService extends Service {
+ private final static String TAG = BluetoothLeService.class.getSimpleName();
+
+ private BluetoothManager mBluetoothManager;
+ private BluetoothAdapter mBluetoothAdapter;
+ private String mBluetoothDeviceAddress;
+ private BluetoothGatt mBluetoothGatt;
+ private int mConnectionState = STATE_DISCONNECTED;
+
+ private static final int STATE_DISCONNECTED = 0;
+ private static final int STATE_CONNECTING = 1;
+ private static final int STATE_CONNECTED = 2;
+
+ public final static String ACTION_GATT_CONNECTED =
+ "com.example.bluetooth.le.ACTION_GATT_CONNECTED";
+ public final static String ACTION_GATT_DISCONNECTED =
+ "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
+ public final static String ACTION_GATT_SERVICES_DISCOVERED =
+ "com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
+ public final static String ACTION_DATA_AVAILABLE =
+ "com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
+ public final static String EXTRA_DATA =
+ "com.example.bluetooth.le.EXTRA_DATA";
+ private BluetoothGattCharacteristic readCharacteristic, writeCharacteristic;
+ private static final UUID BLUETOOTH_LE_NRF_CHAR_RW2 = UUID.fromString("6e400002-b5a3-f393-e0a9-e50e24dcca9e"); // read on microbit, write on adafruit
+ private static final UUID BLUETOOTH_LE_NRF_CHAR_RW3 = UUID.fromString("6e400003-b5a3-f393-e0a9-e50e24dcca9e");
+ private static final UUID BLUETOOTH_LE_NRF_SERVICE = UUID.fromString("6e400001-b5a3-f393-e0a9-e50e24dcca9e");
+ public final static UUID UUID_HEART_RATE_MEASUREMENT =
+ UUID.fromString(SampleGattAttributes.HEART_RATE_MEASUREMENT);
+ private static final UUID BLUETOOTH_LE_CCCD = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
+
+ // 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) {
+ String intentAction;
+ if (newState == BluetoothProfile.STATE_CONNECTED) {
+ intentAction = ACTION_GATT_CONNECTED;
+ mConnectionState = STATE_CONNECTED;
+ broadcastUpdate(intentAction);
+
+ Log.i(TAG, "Connected to GATT server.");
+ // Attempts to discover services after successful connection.
+ Log.i(TAG, "Attempting to start service discovery:" +
+ mBluetoothGatt.discoverServices());
+
+ } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
+ intentAction = ACTION_GATT_DISCONNECTED;
+ mConnectionState = STATE_DISCONNECTED;
+ Log.i(TAG, "Disconnected from GATT server.");
+ broadcastUpdate(intentAction);
+ }
+ }
+
+
+ @Override
+ public void onServicesDiscovered(BluetoothGatt gatt, int status) {
+ if (status == BluetoothGatt.GATT_SUCCESS) {
+ broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
+ for (BluetoothGattService gattService : gatt.getServices()) {
+ if (gattService.getUuid().equals(BLUETOOTH_LE_NRF_SERVICE)) {
+ Log.w(TAG, "nrfservice: " + status);
+ if(connectCharacteristics(gattService)){
+ connectCharacteristics3(gatt);
+ };
+ }
+ }
+ } else {
+ Log.w(TAG, "onServicesDiscovered received: " + status);
+ }
+ }
+
+ @Override
+ public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
+ if (status == BluetoothGatt.GATT_SUCCESS) {
+ final byte[] dataInput = characteristic.getValue();
+ Log.i(TAG, "read:" + Arrays.toString(dataInput));
+ broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
+ }
+ else{
+ Log.i(TAG, "sadge");
+ }
+ }
+
+ @Override
+ public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
+ super.onDescriptorWrite(gatt, descriptor, status);
+ }
+
+ @Override
+ public void onCharacteristicChanged(BluetoothGatt gatt,
+ BluetoothGattCharacteristic characteristic) {
+ final byte[] dataInput = characteristic.getValue();
+
+ broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
+ }
+
+ boolean connectCharacteristics(BluetoothGattService gattService) {
+ Log.d(TAG, "service nrf uart");
+ BluetoothGattCharacteristic rw2 = gattService.getCharacteristic(BLUETOOTH_LE_NRF_CHAR_RW2);
+ BluetoothGattCharacteristic rw3 = gattService.getCharacteristic(BLUETOOTH_LE_NRF_CHAR_RW3);
+ if (rw2 != null && rw3 != null) {
+ int rw2prop = rw2.getProperties();
+ int rw3prop = rw3.getProperties();
+ boolean rw2write = (rw2prop & BluetoothGattCharacteristic.PROPERTY_WRITE) != 0;
+ boolean rw3write = (rw3prop & BluetoothGattCharacteristic.PROPERTY_WRITE) != 0;
+ Log.d(TAG, "characteristic properties " + rw2prop + "/" + rw3prop);
+ if (rw2write) {
+ writeCharacteristic = rw2;
+ readCharacteristic = rw3;
+ } else if (rw3write) {
+ writeCharacteristic = rw3;
+ readCharacteristic = rw2;
+ }
+ }
+ return true;
+ }
+ private void connectCharacteristics3(BluetoothGatt gatt) {
+ int writeProperties = writeCharacteristic.getProperties();
+ if((writeProperties & (BluetoothGattCharacteristic.PROPERTY_WRITE + // Microbit,HM10-clone have WRITE
+ BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE)) ==0) { // HM10,TI uart,Telit have only WRITE_NO_RESPONSE
+ return;
+ }
+ if(!gatt.setCharacteristicNotification(readCharacteristic,true)) {
+ return;
+ }
+ BluetoothGattDescriptor readDescriptor = readCharacteristic.getDescriptor(BLUETOOTH_LE_CCCD);
+ if(readDescriptor == null) {
+ return;
+ }
+ int readProperties = readCharacteristic.getProperties();
+ if((readProperties & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0) {
+ Log.d(TAG, "enable read indication");
+ readDescriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
+ }else if((readProperties & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) {
+ Log.d(TAG, "enable read notification");
+ readDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
+ } else {
+
+ return;
+ }
+ Log.d(TAG,"writing read characteristic descriptor");
+ if(!gatt.writeDescriptor(readDescriptor)) {
+
+ }
+ // continues asynchronously in onDescriptorWrite()
+ }
+
+ };
+
+
+ private void broadcastUpdate(final String action) {
+ final Intent intent = new Intent(action);
+ sendBroadcast(intent);
+ }
+
+ private void broadcastUpdate(final String action,
+ final BluetoothGattCharacteristic characteristic) {
+ final Intent intent = new Intent(action);
+
+ // This is special handling for the Heart Rate Measurement profile. Data parsing is
+ // carried out as per profile specifications:
+ // http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml
+ if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
+ int flag = characteristic.getProperties();
+ int format = -1;
+ if ((flag & 0x01) != 0) {
+ format = BluetoothGattCharacteristic.FORMAT_UINT16;
+ Log.d(TAG, "Heart rate format UINT16.");
+ } else {
+ format = BluetoothGattCharacteristic.FORMAT_UINT8;
+ Log.d(TAG, "Heart rate format UINT8.");
+ }
+ final int heartRate = characteristic.getIntValue(format, 1);
+ Log.d(TAG, String.format("Received heart rate: %d", heartRate));
+ intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));
+ } else {
+ // For all other profiles, writes the data formatted in HEX.
+ final byte[] data = characteristic.getValue();
+ if (data != null && data.length > 0) {
+ final StringBuilder stringBuilder = new StringBuilder(data.length);
+ for(byte byteChar : data)
+ stringBuilder.append(String.format("%02X ", byteChar));
+ intent.putExtra(EXTRA_DATA, new String(data) + "\n" + stringBuilder.toString());
+ }
+ }
+ sendBroadcast(intent);
+ }
+
+ public class LocalBinder extends Binder {
+ BluetoothLeService getService() {
+ return BluetoothLeService.this;
+ }
+ }
+
+ @Override
+ public IBinder onBind(Intent intent) {
+ return mBinder;
+ }
+
+ @Override
+ public boolean onUnbind(Intent intent) {
+ // After using a given device, you should make sure that BluetoothGatt.close() is called
+ // such that resources are cleaned up properly. In this particular example, close() is
+ // invoked when the UI is disconnected from the Service.
+ 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;
+ }
+
+ /**
+ * Connects to the GATT server hosted on the Bluetooth LE device.
+ *
+ * @param address The device address of the destination 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(final String address) {
+ if (mBluetoothAdapter == null || address == null) {
+ Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
+ return false;
+ }
+
+ // Previously connected device. Try to reconnect.
+ if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
+ && mBluetoothGatt != null) {
+ Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
+ if (mBluetoothGatt.connect()) {
+ mConnectionState = STATE_CONNECTING;
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
+ if (device == null) {
+ Log.w(TAG, "Device not found. Unable to connect.");
+ return false;
+ }
+ // We want to directly connect to the device, so we are setting the autoConnect
+ // parameter to false.
+ mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
+ Log.d(TAG, "Trying to create a new connection.");
+ mBluetoothDeviceAddress = address;
+ mConnectionState = STATE_CONNECTING;
+ return true;
+ }
+
+ /**
+ * 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;
+ }
+
+ /**
+ * Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported
+ * asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
+ * callback.
+ *
+ * @param characteristic The characteristic to read from.
+ */
+ public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
+ if (mBluetoothAdapter == null || mBluetoothGatt == null) {
+ Log.w(TAG, "BluetoothAdapter not initialized");
+ return;
+ }
+ mBluetoothGatt.readCharacteristic(characteristic);
+
+ }
+
+ /**
+ * Enables or disables notification on a give characteristic.
+ *
+ * @param characteristic Characteristic to act on.
+ * @param enabled If true, enable notification. False otherwise.
+ */
+
+ public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
+ boolean enabled) {
+ if (mBluetoothAdapter == null || mBluetoothGatt == null) {
+ Log.w(TAG, "BluetoothAdapter not initialized");
+ return;
+ }
+ for (BluetoothGattDescriptor descriptor:characteristic.getDescriptors()){
+ Log.e(TAG, "BluetoothGattDescriptor: "+ descriptor.getUuid().toString());
+ }
+
+
+ // This is specific to Heart Rate Measurement.
+ if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
+ BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
+ UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
+ descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
+ mBluetoothGatt.writeDescriptor(descriptor);
+
+ }
+ else{
+ mBluetoothGatt.setCharacteristicNotification(characteristic,true);
+ BluetoothGattDescriptor readDescriptor = characteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
+ mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
+ mBluetoothGatt.readDescriptor(readDescriptor );
+ readDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
+ readDescriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
+ if(!mBluetoothGatt.writeDescriptor(readDescriptor)) {
+ Log.i(TAG, "sadge");
+ }
+
+ }
+ }
+
+ /**
+ * Retrieves a list of supported GATT services on the connected device. This should be
+ * invoked only after {@code BluetoothGatt#discoverServices()} completes successfully.
+ *
+ * @return A {@code List} of supported services.
+ */
+ public List getSupportedGattServices() {
+ if (mBluetoothGatt == null) return null;
+
+ return mBluetoothGatt.getServices();
+ }
+}
diff --git a/app/src/main/java/com/example/bottomnav/ui/notifications/CAN_Data.java b/app/src/main/java/com/example/bottomnav/ui/notifications/CAN_Data.java
new file mode 100644
index 0000000..fc5fd26
--- /dev/null
+++ b/app/src/main/java/com/example/bottomnav/ui/notifications/CAN_Data.java
@@ -0,0 +1,57 @@
+package com.example.bottomnav.ui.notifications;
+
+
+import java.util.Arrays;
+
+class CAN_Data {
+ byte id;
+ byte[] data;
+
+ public CAN_Data(byte id, byte[] data) {
+ this.id = id;
+ this.data = data;
+ }
+
+ public static CAN_Data decode(String raw) {
+ byte id;
+ int len;
+
+ int index = -1;
+ if (raw.charAt(0) == 't' || raw.charAt(0) == 'r') {
+ id = Byte.parseByte(raw.substring(1, 4), 16);
+ index = 4;
+ }
+ else if (raw.charAt(0) == 'T' || raw.charAt(0) == 'R') {
+ id = Byte.parseByte(raw.substring(1, 9), 16);
+ index = 9;
+ }
+ else {
+ return null;
+ }
+
+ len = Integer.parseInt(raw.substring(index, index + 1), 16);
+ byte[] data = new byte[len];
+
+ for(int x = 0;x id2){
+ return 1;
+ }
+ else if(id2==id){
+ return 0;
+ }
+ else{
+ return -1;
+ }
+ }
+}
diff --git a/app/src/main/java/com/example/bottomnav/ui/notifications/ListDisplay.java b/app/src/main/java/com/example/bottomnav/ui/notifications/ListDisplay.java
new file mode 100644
index 0000000..f569f46
--- /dev/null
+++ b/app/src/main/java/com/example/bottomnav/ui/notifications/ListDisplay.java
@@ -0,0 +1,77 @@
+package com.example.bottomnav.ui.notifications;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.widget.ArrayAdapter;
+import android.widget.ListView;
+
+import com.example.bottomnav.R;
+
+import java.util.ArrayList;
+
+public class ListDisplay extends Activity {
+ //Array of strings
+ String[] CAN_receiver = new String[]{"petals", "bms", "dashboard", "petals", "petals",
+ "dashboard", "bms", "dashboard", "lights", "petals", "bms"};
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+// setContentView(R.layout.activity_listview);
+//
+// // Creates an Adapter that adapts array CAN_receiver to display
+// ArrayAdapter adapter = new ArrayAdapter(this,
+// R.layout.activity_listview, CAN_receiver);
+//
+// // A listView is created and adapted
+// ListView listView = findViewById(R.id.mobile_list);
+// listView.setAdapter(adapter);
+ }
+
+
+
+
+
+
+
+
+
+ // A kinda HashSet of CANPackets that only store 1 value
+ ArrayList index = new ArrayList<>();
+ int x = 0;
+ ArrayList values = new ArrayList<>();
+
+ public void display() {
+ // Just a loop
+ while (x < 1000) {
+ //get new CANPackets
+ CANPacket packet = new CANPacket(0x02af2b17, 3.30);
+
+ // Find position to insert packet._value into by looking through INDEX
+ // If packet._id not already in INDEX, add it and then insert packet._value into VALUES
+ for (int i = 0; i < index.size(); i++) {
+ if (index.get(i) == packet._id) {
+ values.remove(i);
+ values.add(i, packet._value);
+ } else if (i == index.size() - 1) {
+ index.add(packet._id);
+ }
+ }
+
+ // Create new adapter and listView and display it
+ ArrayAdapter adp = new ArrayAdapter(this, R.layout.listview_layout, index);
+ ListView listView = findViewById(R.id.listy);
+ listView.setAdapter(adp);
+ }
+ }
+
+ class CANPacket {
+ CANPacket(int id, double value) {
+ _id = id;
+ _value = value;
+ }
+
+ int _id;
+ double _value;
+ }
+}
diff --git a/app/src/main/java/com/example/bottomnav/ui/notifications/NotificationsFragment.java b/app/src/main/java/com/example/bottomnav/ui/notifications/NotificationsFragment.java
index 0a3f420..c1040dc 100644
--- a/app/src/main/java/com/example/bottomnav/ui/notifications/NotificationsFragment.java
+++ b/app/src/main/java/com/example/bottomnav/ui/notifications/NotificationsFragment.java
@@ -1,9 +1,28 @@
package com.example.bottomnav.ui.notifications;
+import android.bluetooth.BluetoothGattCharacteristic;
+import android.bluetooth.BluetoothGattService;
+import android.content.BroadcastReceiver;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Context.*;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.ServiceConnection;
import android.os.Bundle;
+import android.os.IBinder;
+import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
+import android.view.contentcapture.DataRemovalRequest;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.EditText;
+import android.widget.ExpandableListView;
+import android.widget.GridView;
+import android.widget.ListView;
+import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
@@ -11,31 +30,222 @@
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import com.example.bottomnav.R;
+import com.example.bottomnav.*;
+import com.example.bottomnav.bluetoothlegatt.DeviceControlActivity;
+import com.example.bottomnav.bluetoothlegatt.SampleGattAttributes;
import com.example.bottomnav.databinding.FragmentNotificationsBinding;
+import com.example.bottomnav.ui.table.CAN_Data;
import org.w3c.dom.Text;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Dictionary;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
public class NotificationsFragment extends Fragment {
+ private final static String TAG = DeviceControlActivity.class.getSimpleName();
+ public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
+ public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";
+
+ private TextView mConnectionState;
+ private TextView mDataField;
+ private String mDeviceName;
+ private String mDeviceAddress;
+ private ExpandableListView mGattServicesList;
+ private BluetoothLeService mBluetoothLeService;
+ private ArrayList> mGattCharacteristics =
+ new ArrayList>();
+ private boolean mConnected = false;
+ private BluetoothGattCharacteristic mNotifyCharacteristic;
+
+ private final String LIST_NAME = "NAME";
+ private final String LIST_UUID = "UUID";
private NotificationsViewModel notificationsViewModel;
private FragmentNotificationsBinding binding;
+
+ //Array of strings
+ ArrayList CAN_receiver = new ArrayList<>();
+ ArrayAdapter adapter;
+ Parse parser = Parse.parseTextFile("decode.h");
+ private final ServiceConnection mServiceConnection = new ServiceConnection() {
+ @Override
+ public void onServiceConnected(ComponentName componentName, IBinder service) {
+ Log.e(TAG, "initialize Bluetooth");
+ mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
+ if (!mBluetoothLeService.initialize()) {
+ Log.e(TAG, "Unable to initialize Bluetooth");
+ getActivity().finish();
+ }
+ // Automatically connects to the device upon successful start-up initialization.
+
+ mBluetoothLeService.connect(mDeviceAddress);
+ }
+ @Override
+ public void onServiceDisconnected(ComponentName componentName) {
+ mBluetoothLeService = null;
+ }
+ };
+
+ private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
+ @Override
+
+ public void onReceive(Context context, Intent intent) {
+ final String action = intent.getAction();
+ if (com.example.bottomnav.bluetoothlegatt.BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
+ mConnected = true;
+ getActivity().getActionBar().setTitle(mDeviceName);
+ getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
+ //change ui
+ } else if (com.example.bottomnav.bluetoothlegatt.BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
+ mConnected = false;
+
+ //change ui
+ }
+ if (com.example.bottomnav.bluetoothlegatt.BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
+ displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
+ }
+ }
+ };
+
+
+
+ public NotificationsFragment() throws Exception {
+ Log.e(TAG, "exception sadge");
+ }
+
+
+ @Override
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
- notificationsViewModel = new ViewModelProvider(this).get(NotificationsViewModel.class);
+ adapter = new ArrayAdapter<>(getActivity(),
+ R.layout.listview_layout, CAN_receiver);
+ View view = inflater.inflate(R.layout.fragment_notifications, container, false);
+ return view;
+ }
+
+ private void displayData(String data) {
+ if (data != null) {
+ String name;
+ String val;
+ Optional newDataOpt = CAN_Data.decode(data);
+ if (!newDataOpt.isPresent()) {
+ Log.i(TAG, "error in decode");
+ return;
+ }
+ CAN_Data newData = newDataOpt.get();
+ Optional option = parser.getDecoder(newData.getId());
+ if (!option.isPresent()) {
+ put(CAN_receiver, newData);
+ sort(CAN_receiver);
+ adapter.notifyDataSetChanged();
+ } else {
+ Optional listData = parser.decode(newData.getId(), newData.getData());
+ if(listData.isPresent()) {
+ DataDecoder decoder = option.get();
+ Log.i(TAG, CAN_receiver.toString());
+
+ for (int x = 0; x < decoder.getSize(); x++) {
+ name = decoder.getVarNameAt(x);
+ val = decoder.getValueStringAt(x);
+ put(newData, CAN_receiver, name, val);
+ }
+ sort(CAN_receiver);
+ adapter.notifyDataSetChanged();
+ }
+ else{
+ Log.i(TAG, "DATA MISMATCH");
+ }
+ }
- binding = FragmentNotificationsBinding.inflate(inflater, container, false);
- final TextView textView = binding.textNotifications;
- notificationsViewModel.getText().observe(getViewLifecycleOwner(), new Observer() {
- @Override
- public void onChanged(@Nullable String s) {
- textView.setText(s);
+ }
+ }
+
+
+ public void sort(ArrayList list){
+ CAN_ID_COMP comp = new CAN_ID_COMP();
+ list.sort(comp);
+
+ }
+ public int getIDFromString(String id){
+ String[] split = id.split("]");
+ String split_id = split[0];
+ int CAN_id= Integer.parseInt(split_id.substring(1));
+ return CAN_id;
+ }
+ public void put(ArrayList list, CAN_Data data){
+ if(list != null){
+ boolean flag = false;
+ for(int x = 0; x list, String name,
+ String val){
+ if(list != null && input != null){
+ boolean flag = false;
+ for(int x = 0; x() {
@Override
public void onChanged(@Nullable String s) {
@@ -34,6 +39,19 @@ public void onChanged(@Nullable String s) {
});
return binding.getRoot();
}
+ public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
+ super.onViewCreated(view, savedInstanceState);
+
+ Button button = view.findViewById(R.id.Scan);
+
+ View.OnClickListener onClickListener = v -> { // lambda function
+ final Intent intent = new Intent(this.getContext(), DeviceScanActivity.class);
+ startActivity(intent);
+ };
+
+ button.setOnClickListener(onClickListener);
+ }
+
@Override
public void onDestroyView() {
diff --git a/app/src/main/java/com/example/bottomnav/ui/table/BluetoothLeService.java b/app/src/main/java/com/example/bottomnav/ui/table/BluetoothLeService.java
new file mode 100644
index 0000000..f184bb3
--- /dev/null
+++ b/app/src/main/java/com/example/bottomnav/ui/table/BluetoothLeService.java
@@ -0,0 +1,418 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.example.bottomnav.ui.table;
+
+
+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.content.Context;
+import android.content.Intent;
+import android.os.Binder;
+import android.os.IBinder;
+import android.util.Log;
+
+import com.example.bottomnav.bluetoothlegatt.SampleGattAttributes;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.UUID;
+
+/**
+ * Service for managing connection and data communication with a GATT server hosted on a
+ * given Bluetooth LE device.
+ */
+public class BluetoothLeService extends Service {
+ private final static String TAG = BluetoothLeService.class.getSimpleName();
+
+ private BluetoothManager mBluetoothManager;
+ private BluetoothAdapter mBluetoothAdapter;
+ private String mBluetoothDeviceAddress;
+ private BluetoothGatt mBluetoothGatt;
+ private int mConnectionState = STATE_DISCONNECTED;
+
+ private static final int STATE_DISCONNECTED = 0;
+ private static final int STATE_CONNECTING = 1;
+ private static final int STATE_CONNECTED = 2;
+
+ public final static String ACTION_GATT_CONNECTED =
+ "com.example.bluetooth.le.ACTION_GATT_CONNECTED";
+ public final static String ACTION_GATT_DISCONNECTED =
+ "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
+ public final static String ACTION_GATT_SERVICES_DISCOVERED =
+ "com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
+ public final static String ACTION_DATA_AVAILABLE =
+ "com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
+ public final static String EXTRA_DATA =
+ "com.example.bluetooth.le.EXTRA_DATA";
+ private BluetoothGattCharacteristic readCharacteristic, writeCharacteristic;
+ private static final UUID BLUETOOTH_LE_NRF_CHAR_RW2 = UUID.fromString("6e400002-b5a3-f393-e0a9-e50e24dcca9e"); // read on microbit, write on adafruit
+ private static final UUID BLUETOOTH_LE_NRF_CHAR_RW3 = UUID.fromString("6e400003-b5a3-f393-e0a9-e50e24dcca9e");
+ private static final UUID BLUETOOTH_LE_NRF_SERVICE = UUID.fromString("6e400001-b5a3-f393-e0a9-e50e24dcca9e");
+ public final static UUID UUID_HEART_RATE_MEASUREMENT =
+ UUID.fromString(SampleGattAttributes.HEART_RATE_MEASUREMENT);
+ private static final UUID BLUETOOTH_LE_CCCD = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
+
+ // 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) {
+ String intentAction;
+ if (newState == BluetoothProfile.STATE_CONNECTED) {
+ intentAction = ACTION_GATT_CONNECTED;
+ mConnectionState = STATE_CONNECTED;
+ broadcastUpdate(intentAction);
+
+ Log.i(TAG, "Connected to GATT server.");
+ // Attempts to discover services after successful connection.
+ Log.i(TAG, "Attempting to start service discovery:" +
+ mBluetoothGatt.discoverServices());
+
+ } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
+ intentAction = ACTION_GATT_DISCONNECTED;
+ mConnectionState = STATE_DISCONNECTED;
+ Log.i(TAG, "Disconnected from GATT server.");
+ broadcastUpdate(intentAction);
+ }
+ }
+
+
+ @Override
+ public void onServicesDiscovered(BluetoothGatt gatt, int status) {
+ if (status == BluetoothGatt.GATT_SUCCESS) {
+ broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
+ for (BluetoothGattService gattService : gatt.getServices()) {
+ if (gattService.getUuid().equals(BLUETOOTH_LE_NRF_SERVICE)) {
+ Log.w(TAG, "nrfservice: " + status);
+ if(connectCharacteristics(gattService)){
+ connectCharacteristics3(gatt);
+ };
+ }
+ }
+ } else {
+ Log.w(TAG, "onServicesDiscovered received: " + status);
+ }
+ }
+
+ @Override
+ public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
+ if (status == BluetoothGatt.GATT_SUCCESS) {
+ final byte[] dataInput = characteristic.getValue();
+ Log.i(TAG, "read:" + Arrays.toString(dataInput));
+ broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
+ }
+ else{
+ Log.i(TAG, "sadge");
+ }
+ }
+
+ @Override
+ public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
+ super.onDescriptorWrite(gatt, descriptor, status);
+ }
+
+ @Override
+ public void onCharacteristicChanged(BluetoothGatt gatt,
+ BluetoothGattCharacteristic characteristic) {
+ final byte[] dataInput = characteristic.getValue();
+ Log.i(TAG, "change"+ dataInput.toString() );
+ broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
+ }
+
+ boolean connectCharacteristics(BluetoothGattService gattService) {
+ Log.d(TAG, "service nrf uart");
+ BluetoothGattCharacteristic rw2 = gattService.getCharacteristic(BLUETOOTH_LE_NRF_CHAR_RW2);
+ BluetoothGattCharacteristic rw3 = gattService.getCharacteristic(BLUETOOTH_LE_NRF_CHAR_RW3);
+ if (rw2 != null && rw3 != null) {
+ int rw2prop = rw2.getProperties();
+ int rw3prop = rw3.getProperties();
+ boolean rw2write = (rw2prop & BluetoothGattCharacteristic.PROPERTY_WRITE) != 0;
+ boolean rw3write = (rw3prop & BluetoothGattCharacteristic.PROPERTY_WRITE) != 0;
+ Log.d(TAG, "characteristic properties " + rw2prop + "/" + rw3prop);
+ if (rw2write) {
+ writeCharacteristic = rw2;
+ readCharacteristic = rw3;
+ } else if (rw3write) {
+ writeCharacteristic = rw3;
+ readCharacteristic = rw2;
+ }
+ }
+ return true;
+ }
+ private void connectCharacteristics3(BluetoothGatt gatt) {
+ int writeProperties = writeCharacteristic.getProperties();
+ if((writeProperties & (BluetoothGattCharacteristic.PROPERTY_WRITE + // Microbit,HM10-clone have WRITE
+ BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE)) ==0) { // HM10,TI uart,Telit have only WRITE_NO_RESPONSE
+ return;
+ }
+ if(!gatt.setCharacteristicNotification(readCharacteristic,true)) {
+ return;
+ }
+ BluetoothGattDescriptor readDescriptor = readCharacteristic.getDescriptor(BLUETOOTH_LE_CCCD);
+ if(readDescriptor == null) {
+ return;
+ }
+ int readProperties = readCharacteristic.getProperties();
+ if((readProperties & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0) {
+ Log.d(TAG, "enable read indication");
+ readDescriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
+ }else if((readProperties & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) {
+ Log.d(TAG, "enable read notification");
+ readDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
+ } else {
+
+ return;
+ }
+ Log.d(TAG,"writing read characteristic descriptor");
+ if(!gatt.writeDescriptor(readDescriptor)) {
+
+ }
+ // continues asynchronously in onDescriptorWrite()
+ }
+
+ };
+
+
+ private void broadcastUpdate(final String action) {
+ final Intent intent = new Intent(action);
+ sendBroadcast(intent);
+ }
+
+ private void broadcastUpdate(final String action,
+ final BluetoothGattCharacteristic characteristic) {
+ final Intent intent = new Intent(action);
+
+ // This is special handling for the Heart Rate Measurement profile. Data parsing is
+ // carried out as per profile specifications:
+ // http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml
+ if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
+ int flag = characteristic.getProperties();
+ int format = -1;
+ if ((flag & 0x01) != 0) {
+ format = BluetoothGattCharacteristic.FORMAT_UINT16;
+ Log.d(TAG, "Heart rate format UINT16.");
+ } else {
+ format = BluetoothGattCharacteristic.FORMAT_UINT8;
+ Log.d(TAG, "Heart rate format UINT8.");
+ }
+ final int heartRate = characteristic.getIntValue(format, 1);
+ Log.d(TAG, String.format("Received heart rate: %d", heartRate));
+ intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));
+ } else {
+ // For all other profiles, writes the data formatted in HEX.
+ final byte[] data = characteristic.getValue();
+ if (data != null && data.length > 0) {
+ final StringBuilder stringBuilder = new StringBuilder(data.length);
+ for(byte byteChar : data)
+ stringBuilder.append(String.format("%02X ", byteChar));
+ intent.putExtra(EXTRA_DATA, new String(data) + "\n" + stringBuilder.toString());
+ }
+ }
+ sendBroadcast(intent);
+ }
+
+ public class LocalBinder extends Binder {
+ BluetoothLeService getService() {
+ return BluetoothLeService.this;
+ }
+ }
+
+ @Override
+ public IBinder onBind(Intent intent) {
+ return mBinder;
+ }
+
+ @Override
+ public boolean onUnbind(Intent intent) {
+ // After using a given device, you should make sure that BluetoothGatt.close() is called
+ // such that resources are cleaned up properly. In this particular example, close() is
+ // invoked when the UI is disconnected from the Service.
+ 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;
+ }
+
+ /**
+ * Connects to the GATT server hosted on the Bluetooth LE device.
+ *
+ * @param address The device address of the destination 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(final String address) {
+ if (mBluetoothAdapter == null || address == null) {
+ Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
+ return false;
+ }
+
+ // Previously connected device. Try to reconnect.
+ if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
+ && mBluetoothGatt != null) {
+ Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
+ if (mBluetoothGatt.connect()) {
+ mConnectionState = STATE_CONNECTING;
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
+ if (device == null) {
+ Log.w(TAG, "Device not found. Unable to connect.");
+ return false;
+ }
+ // We want to directly connect to the device, so we are setting the autoConnect
+ // parameter to false.
+ mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
+ Log.d(TAG, "Trying to create a new connection.");
+ mBluetoothDeviceAddress = address;
+ mConnectionState = STATE_CONNECTING;
+ return true;
+ }
+
+ /**
+ * 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;
+ }
+
+ /**
+ * Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported
+ * asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
+ * callback.
+ *
+ * @param characteristic The characteristic to read from.
+ */
+ public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
+ if (mBluetoothAdapter == null || mBluetoothGatt == null) {
+ Log.w(TAG, "BluetoothAdapter not initialized");
+ return;
+ }
+ mBluetoothGatt.readCharacteristic(characteristic);
+
+ }
+
+ /**
+ * Enables or disables notification on a give characteristic.
+ *
+ * @param characteristic Characteristic to act on.
+ * @param enabled If true, enable notification. False otherwise.
+ */
+
+ public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
+ boolean enabled) {
+ if (mBluetoothAdapter == null || mBluetoothGatt == null) {
+ Log.w(TAG, "BluetoothAdapter not initialized");
+ return;
+ }
+ for (BluetoothGattDescriptor descriptor:characteristic.getDescriptors()){
+ Log.e(TAG, "BluetoothGattDescriptor: "+ descriptor.getUuid().toString());
+ }
+
+
+ // This is specific to Heart Rate Measurement.
+ if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
+ BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
+ UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
+ descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
+ mBluetoothGatt.writeDescriptor(descriptor);
+
+ }
+ else{
+ mBluetoothGatt.setCharacteristicNotification(characteristic,true);
+ BluetoothGattDescriptor readDescriptor = characteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
+ mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
+ mBluetoothGatt.readDescriptor(readDescriptor );
+ readDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
+ readDescriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
+ if(!mBluetoothGatt.writeDescriptor(readDescriptor)) {
+ Log.i(TAG, "sadge");
+ }
+
+ }
+ }
+
+ /**
+ * Retrieves a list of supported GATT services on the connected device. This should be
+ * invoked only after {@code BluetoothGatt#discoverServices()} completes successfully.
+ *
+ * @return A {@code List} of supported services.
+ */
+ public List getSupportedGattServices() {
+ if (mBluetoothGatt == null) return null;
+
+ return mBluetoothGatt.getServices();
+ }
+}
diff --git a/app/src/main/java/com/example/bottomnav/ui/table/CAN_Data.java b/app/src/main/java/com/example/bottomnav/ui/table/CAN_Data.java
new file mode 100644
index 0000000..076d970
--- /dev/null
+++ b/app/src/main/java/com/example/bottomnav/ui/table/CAN_Data.java
@@ -0,0 +1,67 @@
+package com.example.bottomnav.ui.table;
+
+
+
+import java.security.cert.PKIXRevocationChecker;
+import java.util.Arrays;
+import java.util.Optional;
+
+public class CAN_Data {
+ int id;
+ byte[] data;
+ int id_size;
+ public CAN_Data(int id, byte[] data,int size) {
+ this.id = id;
+ this.data = data;
+ id_size = size;
+ }
+
+ public static Optional decode(String raw) {
+ try {
+ int id;
+ int len;
+
+ int index = -1;
+ if (raw.charAt(0) == 't' || raw.charAt(0) == 'r') {
+ id = Integer.parseInt(raw.substring(1, 4), 16);
+ index = 4;
+ } else if (raw.charAt(0) == 'T' || raw.charAt(0) == 'R') {
+ id = Integer.parseInt(raw.substring(1, 9), 16);
+ index = 9;
+ } else {
+ return null;
+ }
+
+ len = Integer.parseInt(raw.substring(index, index + 1), 16);
+ byte[] data = new byte[len];
+
+ for (int x = 0; x < len; x += 1) {
+
+ data[x] = (byte) Integer.parseInt(raw.substring(2 * x + index + 1, 2 * x + 2 + index + 1), 16);
+ }
+ return Optional.of(new CAN_Data(id, data, index - 1));
+ }catch(NumberFormatException e){
+ return Optional.empty();
+
+ }
+ }
+
+ public int getId(){
+ return id;
+ }
+
+ public byte[] getData() {
+ return data;
+ }
+
+ @Override
+ public String toString() {
+ return id +
+ ":"+ Arrays.toString(data) +
+ '}';
+ }
+
+ public int getId_size() {
+ return id_size;
+ }
+}
diff --git a/app/src/main/java/com/example/bottomnav/ui/table/TableFragment.java b/app/src/main/java/com/example/bottomnav/ui/table/TableFragment.java
new file mode 100644
index 0000000..f39d8bf
--- /dev/null
+++ b/app/src/main/java/com/example/bottomnav/ui/table/TableFragment.java
@@ -0,0 +1,185 @@
+package com.example.bottomnav.ui.table;
+
+import android.bluetooth.BluetoothGattCharacteristic;
+import android.bluetooth.BluetoothGattService;
+import android.content.BroadcastReceiver;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Context.*;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.ServiceConnection;
+import android.os.Bundle;
+import android.os.IBinder;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.contentcapture.DataRemovalRequest;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.EditText;
+import android.widget.ExpandableListView;
+import android.widget.GridView;
+import android.widget.ListView;
+import android.widget.SimpleExpandableListAdapter;
+import android.widget.TextView;
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+import androidx.fragment.app.Fragment;
+import androidx.lifecycle.Observer;
+import androidx.lifecycle.ViewModelProvider;
+import androidx.recyclerview.widget.GridLayoutManager;
+import androidx.recyclerview.widget.RecyclerView;
+
+import com.example.bottomnav.R;
+import com.example.bottomnav.*;
+import com.example.bottomnav.bluetoothlegatt.DeviceControlActivity;
+import com.example.bottomnav.bluetoothlegatt.SampleGattAttributes;
+import com.example.bottomnav.databinding.FragmentNotificationsBinding;
+import com.example.bottomnav.ui.table.CAN_Data;
+
+import org.w3c.dom.Text;
+
+import java.util.ArrayList;
+import java.util.Dictionary;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class TableFragment extends Fragment {
+ private final static String TAG = DeviceControlActivity.class.getSimpleName();
+ public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
+ public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";
+
+ private TextView mConnectionState;
+ private TextView mDataField;
+ private String mDeviceName;
+ private String mDeviceAddress;
+ private ExpandableListView mGattServicesList;
+ private BluetoothLeService mBluetoothLeService;
+ private ArrayList> mGattCharacteristics =
+ new ArrayList>();
+ private boolean mConnected = false;
+ private BluetoothGattCharacteristic mNotifyCharacteristic;
+
+ private final String LIST_NAME = "NAME";
+ private final String LIST_UUID = "UUID";
+
+ private TableViewModel notificationsViewModel;
+ private FragmentNotificationsBinding binding;
+
+
+ //Array of strings
+ ArrayList CAN_receiver = new ArrayList();
+ ArrayAdapter adapter;
+
+
+ private final ServiceConnection mServiceConnection = new ServiceConnection() {
+ @Override
+ public void onServiceConnected(ComponentName componentName, IBinder service) {
+ Log.e(TAG, "initialize Bluetooth");
+ mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
+ if (!mBluetoothLeService.initialize()) {
+ Log.e(TAG, "Unable to initialize Bluetooth");
+ getActivity().finish();
+ }
+ // Automatically connects to the device upon successful start-up initialization.
+
+ mBluetoothLeService.connect(mDeviceAddress);
+ }
+ @Override
+ public void onServiceDisconnected(ComponentName componentName) {
+ mBluetoothLeService = null;
+ }
+ };
+ private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
+ @Override
+
+ public void onReceive(Context context, Intent intent) {
+ final String action = intent.getAction();
+
+ if (com.example.bottomnav.bluetoothlegatt.BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
+ try {
+ displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ };
+
+
+
+
+
+
+ @Override
+ public View onCreateView(@NonNull LayoutInflater inflater,
+ ViewGroup container, Bundle savedInstanceState) {
+ View view = inflater.inflate(R.layout.fragment_table, container, false);
+ return view;
+ }
+
+ private void displayData(String data) throws Exception {
+ if (data != null) {
+ Parse parser = Parse.parseTextFile("decode.h");
+ String name;
+ String val;
+// CAN_Data newData = CAN_Data.decode(data);
+// String listData = parser.decode(newData.getId(), newData.getData());
+// DataDecoder decoder = parser.getDecoder(newData.getId()).get();
+//
+//
+// name = decoder.getVarNameAt(0);
+// val = decoder.getValueStringAt(0);
+// CAN_receiver.add(newData);
+//
+
+ adapter.notifyDataSetChanged();
+ }
+ }
+
+
+
+ private static IntentFilter makeGattUpdateIntentFilter() {
+ final IntentFilter intentFilter = new IntentFilter();
+ intentFilter.addAction(com.example.bottomnav.bluetoothlegatt.BluetoothLeService.ACTION_DATA_AVAILABLE);
+ return intentFilter;
+ }
+
+ @Override
+ public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
+ super.onViewCreated(view, savedInstanceState);
+ final Intent intent = this.getActivity().getIntent();
+ mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
+ mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);
+ Intent gattServiceIntent = new Intent(this.getActivity(), BluetoothLeService.class);
+ System.out.println(this.getActivity().bindService(gattServiceIntent, mServiceConnection, Context.BIND_AUTO_CREATE));
+
+ this.getActivity().registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
+ if (mBluetoothLeService != null) {
+ final boolean result = mBluetoothLeService.connect(mDeviceAddress);
+ Log.d(TAG, "Connect request result=" + result);
+ }
+ Log.e(TAG, "bind");
+
+ // Creates an Adapter that ad(apts array CAN_receiver to display
+
+ // Creates new button logic with counter as final one-element array
+ // A listView is created and adapted
+ RecyclerView gridView = view.findViewById(R.id.lister);
+ //Log.i(TAG, gridView);
+ gridView.setLayoutManager(new GridLayoutManager(this.getActivity(), 2));
+ CustomArrayAdapter customAdapter = new CustomArrayAdapter(this.getActivity(), R.layout.listview_layout, CAN_receiver);
+ gridView.setAdapter(customAdapter);
+
+ }
+
+
+ @Override
+ public void onDestroyView() {
+ super.onDestroyView();
+ binding = null;
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/example/bottomnav/ui/dashboard/DashboardViewModel.java b/app/src/main/java/com/example/bottomnav/ui/table/TableViewModel.java
similarity index 60%
rename from app/src/main/java/com/example/bottomnav/ui/dashboard/DashboardViewModel.java
rename to app/src/main/java/com/example/bottomnav/ui/table/TableViewModel.java
index cebf12d..8ac1832 100644
--- a/app/src/main/java/com/example/bottomnav/ui/dashboard/DashboardViewModel.java
+++ b/app/src/main/java/com/example/bottomnav/ui/table/TableViewModel.java
@@ -1,19 +1,21 @@
-package com.example.bottomnav.ui.dashboard;
+package com.example.bottomnav.ui.table;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
-public class DashboardViewModel extends ViewModel {
+public class TableViewModel extends ViewModel {
private MutableLiveData mText;
- public DashboardViewModel() {
+ public TableViewModel() {
mText = new MutableLiveData<>();
- mText.setValue("This is dashboard fragment");
+ mText.setValue("This is table fragment");
}
public LiveData getText() {
return mText;
}
+
+
}
\ No newline at end of file
diff --git a/app/src/main/res/decode.h b/app/src/main/res/decode.h
new file mode 100644
index 0000000..e33c04a
--- /dev/null
+++ b/app/src/main/res/decode.h
@@ -0,0 +1,20 @@
+const float PACKED_FLOAT = 0x310;
+
+// @canPayloadStruct CAN_PEDAL_POS = CanPedalPosStruct
+const uint16_t CAN_PEDAL_POS = 0x282;
+
+struct CanPedalPosStruct {
+ uint8_t accelPos;
+ uint8_t brakePos;
+ uint8_t reserved1Pos;
+ uint8_t reserved2Pos;
+};
+
+// @canPayloadStruct CAN_TRITIUM_VELOCITY = CanTritiumVelocityStruct
+const uint16_t CAN_TRITIUM_VELOCITY = 0x402;
+
+struct CanTritiumVelocityStruct {
+ float rpm;
+ float mps;
+};
+
diff --git a/app/src/main/res/layout/actionbar_indeterminate_progress.xml b/app/src/main/res/layout/actionbar_indeterminate_progress.xml
new file mode 100644
index 0000000..a950833
--- /dev/null
+++ b/app/src/main/res/layout/actionbar_indeterminate_progress.xml
@@ -0,0 +1,23 @@
+
+
+
+
diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml
index a57477b..5becd5f 100644
--- a/app/src/main/res/layout/activity_main.xml
+++ b/app/src/main/res/layout/activity_main.xml
@@ -1,4 +1,5 @@
+
-
\ No newline at end of file
+
diff --git a/app/src/main/res/layout/fragment_home.xml b/app/src/main/res/layout/fragment_home.xml
index 7ecfe18..8f18500 100644
--- a/app/src/main/res/layout/fragment_home.xml
+++ b/app/src/main/res/layout/fragment_home.xml
@@ -16,8 +16,25 @@
android:layout_marginEnd="8dp"
android:textAlignment="center"
android:textSize="20sp"
+ app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
+ app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
- app:layout_constraintBottom_toBottomOf="parent" />
+ app:layout_constraintVertical_bias="0.035"
+ tools:visibility="visible" />
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/fragment_notifications.xml b/app/src/main/res/layout/fragment_notifications.xml
index 01a3222..43bab1b 100644
--- a/app/src/main/res/layout/fragment_notifications.xml
+++ b/app/src/main/res/layout/fragment_notifications.xml
@@ -1,23 +1,30 @@
-
-
-
\ No newline at end of file
+ android:inputType="text"
+ android:hint="Enter a String" />
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/fragment_settings.xml b/app/src/main/res/layout/fragment_settings.xml
index a654e5a..3a2df77 100644
--- a/app/src/main/res/layout/fragment_settings.xml
+++ b/app/src/main/res/layout/fragment_settings.xml
@@ -20,4 +20,12 @@
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/fragment_dashboard.xml b/app/src/main/res/layout/fragment_table.xml
similarity index 57%
rename from app/src/main/res/layout/fragment_dashboard.xml
rename to app/src/main/res/layout/fragment_table.xml
index 0ef53b9..0d680b4 100644
--- a/app/src/main/res/layout/fragment_dashboard.xml
+++ b/app/src/main/res/layout/fragment_table.xml
@@ -1,14 +1,18 @@
-
+ tools:context=".ui.table.TableFragment">
+
+
-
\ No newline at end of file
+ app:layout_constraintTop_toTopOf="parent" />
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/gatt_services_characteristics.xml b/app/src/main/res/layout/gatt_services_characteristics.xml
new file mode 100644
index 0000000..2f31061
--- /dev/null
+++ b/app/src/main/res/layout/gatt_services_characteristics.xml
@@ -0,0 +1,71 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/listitem_device.xml b/app/src/main/res/layout/listitem_device.xml
new file mode 100644
index 0000000..eff44fc
--- /dev/null
+++ b/app/src/main/res/layout/listitem_device.xml
@@ -0,0 +1,28 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/listview_layout.xml b/app/src/main/res/layout/listview_layout.xml
new file mode 100644
index 0000000..7e243e2
--- /dev/null
+++ b/app/src/main/res/layout/listview_layout.xml
@@ -0,0 +1,26 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/menu/bottom_nav_menu.xml b/app/src/main/res/menu/bottom_nav_menu.xml
index 1c9eb4a..9daca1b 100644
--- a/app/src/main/res/menu/bottom_nav_menu.xml
+++ b/app/src/main/res/menu/bottom_nav_menu.xml
@@ -7,9 +7,9 @@
android:title="@string/title_home"/>
+ android:title="@string/title_table"/>
-
+
+
diff --git a/app/src/main/res/menu/main.xml b/app/src/main/res/menu/main.xml
new file mode 100644
index 0000000..39dd66a
--- /dev/null
+++ b/app/src/main/res/menu/main.xml
@@ -0,0 +1,29 @@
+
+
+
diff --git a/app/src/main/res/navigation/mobile_navigation.xml b/app/src/main/res/navigation/mobile_navigation.xml
index 037dc0a..51fcede 100644
--- a/app/src/main/res/navigation/mobile_navigation.xml
+++ b/app/src/main/res/navigation/mobile_navigation.xml
@@ -12,10 +12,10 @@
tools:layout="@layout/fragment_home" />
+ android:id="@+id/navigation_table"
+ android:name="com.example.bottomnav.ui.table.TableFragment"
+ android:label="@string/title_table"
+ tools:layout="@layout/fragment_table" />
Bottom Nav
Home
- Dashboard
+ Table
Notifications
Settings
+
+ BLE is not supported
+ Data:
+ Device address:
+ State:
+ No data
+ Connected
+ Disconnected
+ BLE Device Scan
+ Bluetooth not supported.
+
+ Unknown device
+ Unknown characteristic
+ Unknown service
+
+
+ Connect
+ Disconnect
+ Scan
+ Stop
+
+
+ CAN ID
+ Value
\ No newline at end of file
diff --git a/app/src/main/resources/decode.h b/app/src/main/resources/decode.h
new file mode 100644
index 0000000..fc325a3
--- /dev/null
+++ b/app/src/main/resources/decode.h
@@ -0,0 +1,273 @@
+/* CalSol - UC Berkeley Solar Vehicle Team
+ * can_id.h - Zephyr
+ * Purpose: Can ID Definitions
+ * Author(s): Steven Rhodes
+ * Date: Jun 7th 2014
+ */
+
+#ifndef __CAN_ID
+#define __CAN_ID
+
+#ifndef IMPULSE
+const uint32_t CAN_FREQUENCY = 500000;
+#else
+const uint32_t CAN_FREQUENCY = 1000000;
+#endif
+
+// Heartbeats
+const uint16_t CAN_HEART_BMS = 0x040;
+const uint16_t CAN_HEART_CUTOFF = 0x041;
+const uint16_t CAN_HEART_MCC_LEFT = 0x042;
+const uint16_t CAN_HEART_MCC_RIGHT = 0x043;
+const uint16_t CAN_HEART_DASHBOARD = 0x044;
+const uint16_t CAN_HEART_POWERHUB_BOTTOM = 0x045;
+const uint16_t CAN_HEART_POWERHUB_TOP = 0x046;
+const uint16_t CAN_HEART_TELEMETRY = 0x047;
+const uint16_t CAN_HEART_LPCTELEMETRY = 0x048;
+const uint16_t CAN_HEART_DATALOGGER = 0x049;
+#define CAN_HEART_MPPT(I) 0x060 + I
+const uint16_t CAN_HEART_DEMO_CODE = 0x050;
+const uint16_t CAN_HEART_ACTIVE_BALANCING = 0x051;
+const uint16_t CAN_HEART_LIGHTS_FRONT = 0x056;
+const uint16_t CAN_HEART_LIGHTS_REAR = 0x057;
+
+const uint16_t CAN_HEART_SOLARJET_L = 0x290;
+const uint16_t CAN_HEART_SOLARJET_R = 0x2A0;
+
+// BMS controls and messages
+ // TODO the uint32_t is actually a flag array
+const uint16_t CAN_BMS_CAR_SHUTDOWN = 0x30; // @canPayloadStruct CAN_BMS_CAR_SHUTDOWN = uint32_t
+const uint16_t CAN_BMS_CAR_WARNING = 0x31; // @canPayloadStruct CAN_BMS_CAR_WARNING = uint32_t
+const uint16_t CAN_BMS_SHUTDOWN_VOLTAGE = 0x32; // @canPayloadStruct CAN_BMS_SHUTDOWN_VOLTAGE = float
+const uint16_t CAN_BMS_SHUTDOWN_CURRENT = 0x32; // @canPayloadStruct CAN_BMS_SHUTDOWN_CURRENT = float
+const uint16_t CAN_BMS_SHUTDOWN_TEMP = 0x33; // @canPayloadStruct CAN_BMS_SHUTDOWN_TEMP = int16_t
+
+struct PackVoltage {
+ float voltage;
+};
+const uint16_t CAN_PACK_VOLTAGE = 0x123; // @canPayloadStruct CAN_PACK_VOLTAGE = PackVoltage
+
+struct PackCurrent {
+ float current;
+};
+const uint16_t CAN_PACK_CURRENT = 0x124; // @canPayloadStruct CAN_PACK_CURRENT = PackCurrent
+const uint16_t CAN_PACK_CHARGE = 0x122; // @canPayloadStruct CAN_PACK_CHARGE = int64_t
+
+struct CellVolts {
+ uint16_t cell[4];
+};
+struct CellVoltsDecoder { // TODO: the decoder doesn't understand array notation, so we have this unrolled one for now
+ uint16_t cell0;
+ uint16_t cell1;
+ uint16_t cell2;
+ uint16_t cell3;
+};
+#define CAN_CELL_VOLTAGE(I) (0x130 + (I))
+const uint16_t CAN_CELL_VOLTAGE_0 = 0x130; // @canPayloadStruct CAN_CELL_VOLTAGE_0 = CellVoltsDecoder
+const uint16_t CAN_CELL_VOLTAGE_4 = 0x131; // @canPayloadStruct CAN_CELL_VOLTAGE_4 = CellVoltsDecoder
+const uint16_t CAN_CELL_VOLTAGE_8 = 0x132; // @canPayloadStruct CAN_CELL_VOLTAGE_8 = CellVoltsDecoder
+const uint16_t CAN_CELL_VOLTAGE_12 = 0x133; // @canPayloadStruct CAN_CELL_VOLTAGE_12 = CellVoltsDecoder
+const uint16_t CAN_CELL_VOLTAGE_16 = 0x134; // @canPayloadStruct CAN_CELL_VOLTAGE_16 = CellVoltsDecoder
+const uint16_t CAN_CELL_VOLTAGE_20 = 0x135; // @canPayloadStruct CAN_CELL_VOLTAGE_20 = CellVoltsDecoder
+const uint16_t CAN_CELL_VOLTAGE_24 = 0x136; // @canPayloadStruct CAN_CELL_VOLTAGE_24 = CellVoltsDecoder
+
+struct Temp {
+ uint16_t temp;
+};
+const uint16_t CAN_PACK_TEMPERATURE_HIGH = 0x125; // @canPayloadStruct CAN_PACK_TEMPERATURE_HIGH = Temp
+const uint16_t CAN_PACK_TEMPERATURE_LOW = 0x126; // @canPayloadStruct CAN_PACK_TEMPERATURE_LOW = Temp
+const uint16_t CAN_PACK_TEMPERATURE_AVG = 0x127; // @canPayloadStruct CAN_PACK_TEMPERATURE_AVG = Temp
+
+const uint16_t CAN_BMS_TRIGGER_BALANCING = 0x128;
+ // TODO actually a flag array
+const uint16_t CAN_BMS_STATES = 0x129; // @canPayloadStruct CAN_BMS_STATES = uint32_t
+
+#define CAN_PACK_TEMPERATURE(I) (0x160 + (I))
+
+struct FanSpeedDecoder { // TODO: the decoder doesn't understand array notation, so we have this unrolled one for now
+ uint16_t fan0;
+ uint16_t fan1;
+ uint16_t fan2;
+ uint16_t fan3;
+};
+#define CAN_BMS_FAN_SPEED(I) (0x190 + (I))
+const uint16_t CAN_BMS_FAN_SPEED_0 = 0x190; // @canPayloadStruct CAN_BMS_FAN_SPEED_0 = FanSpeedDecoder
+const uint16_t CAN_BMS_FAN_SPEED_1 = 0x191; // @canPayloadStruct CAN_BMS_FAN_SPEED_1 = FanSpeedDecoder
+const uint16_t CAN_BMS_FAN_SPEED_2 = 0x192; // @canPayloadStruct CAN_BMS_FAN_SPEED_2 = FanSpeedDecoder
+
+// Cutoff board controls and messages
+const uint16_t CAN_CUTOFF_TRIGGER = 0x260;
+const uint16_t CAN_CUTOFF_AIN_VOLTAGES = 0x261;
+const uint16_t CAN_CUTOFF_SPI_VOLTAGES = 0x262;
+
+// Dashboard controls and messages
+struct pedalPos {
+ uint8_t accel;
+ uint8_t brake;
+ uint8_t mechBrake;
+};
+const uint16_t CAN_PEDAL_POS = 0x282; // @canPayloadStruct CAN_PEDAL_POS = pedalPos
+const uint16_t CAN_BRAKE_BUTTON = 0x283;
+
+
+struct RPM {
+ float rpm;
+};
+
+// MCC queries - left
+const uint16_t CAN_MCC_LEFT_RPM = 0x310; // @canPayloadStruct CAN_MCC_LEFT_RPM = float
+
+// MCC queries - right
+const uint16_t CAN_MCC_RIGHT_RPM = 0x311; // @canPayloadStruct CAN_MCC_RIGHT_RPM = float
+
+// MCC thermistors
+const uint16_t CAN_MCC_LEFT_TEMP = 0x320;
+const uint16_t CAN_MCC_RIGHT_TEMP = 0x321;
+
+const uint16_t CAN_MOTOR_OVERHEAT_L = 0x322;
+const uint16_t CAN_MOTOR_OVERHEAT_R = 0x323;
+
+// PowerHub controls and messages
+//const uint16_t CAN_POWERHUBBOTTOM_TURNON = 0x500;
+//const uint16_t CAN_POWERHUBBOTTOM_TURNOFF = 0x501;
+
+//const uint16_t CAN_POWERHUBTOP_TURNON = 0x504;
+//const uint16_t CAN_POWERHUBTOP_TURNOFF = 0x505;
+
+// PowerHub current sensors
+// #define CAN_POWERHUBBOTTOM_CURRENT(I) 0x520 + I
+
+// #define CAN_POWERHUBTOP_CURRENT(I) 0x529 + I
+
+
+// #define CAN_MPPT_PWR(I) 0x550 + I
+// #define CAN_MPPT_VC(I) 0x560 + I
+// #define CAN_MPPT_T(I) 0x570 + I
+// #define CAN_MPPT_DATA(I) 0x580 + I
+
+// MPPT controls and messages
+// http://goo.gl/KFx2nd
+const uint16_t CAN_FRONT_RIGHT_MPPT_STATUS = 0x600;
+const uint16_t CAN_FRONT_LEFT_MPPT_STATUS = 0x601;
+const uint16_t CAN_BACK_RIGHT_MPPT_STATUS = 0x602;
+const uint16_t CAN_BACK_LEFT_MPPT_STATUS = 0x603;
+const uint16_t CAN_FRONT_RIGHT_MPPT_ENABLE = 0x610;
+const uint16_t CAN_FRONT_LEFT_MPPT_ENABLE = 0x611;
+const uint16_t CAN_BACK_RIGHT_MPPT_ENABLE = 0x612;
+const uint16_t CAN_BACK_LEFT_MPPT_ENABLE = 0x613;
+
+const uint16_t CAN_DRIVE_CONTROL = 0x700;
+const uint16_t CAN_CONTACTOR_CONTROL = 0x701;
+const uint16_t CAN_HORN = 0x702;
+const uint16_t CAN_LIGHTS = 0x703;
+const uint16_t CAN_BRAKE_LIMIT = 0x704; // @canPayloadStruct CAN_BRAKE_LIMIT = uint8_t
+
+struct ActiveBalancingPwmDecoder { // TODO: the decoder doesn't understand array notation, so we have this unrolled one for now
+ uint16_t pwm0;
+ uint16_t pwm1;
+ uint16_t pwm2;
+ uint16_t pwm3;
+ uint16_t pwm4;
+ uint16_t pwm5;
+ uint16_t pwm6;
+ uint16_t pwm7;
+};
+#define CAN_ACTIVE_BALANCING_PWM(I) 0x710 + I
+const uint16_t CAN_ACTIVE_BALANCING_PWM_ARR = 0x700; // @canMessageArray length=8
+ // @canPayloadStruct CAN_ACTIVE_BALANCING_PWM_ARR = ActiveBalancingPwmDecoder
+ // TODO: proposed notation, doesn't actually work yet
+const uint16_t CAN_ACTIVE_BALANCING_PWM_0 = 0x710; // @canPayloadStruct CAN_ACTIVE_BALANCING_PWM_0 = ActiveBalancingPwmDecoder
+const uint16_t CAN_ACTIVE_BALANCING_PWM_1 = 0x711; // @canPayloadStruct CAN_ACTIVE_BALANCING_PWM_1 = ActiveBalancingPwmDecoder
+const uint16_t CAN_ACTIVE_BALANCING_PWM_2 = 0x712; // @canPayloadStruct CAN_ACTIVE_BALANCING_PWM_2 = ActiveBalancingPwmDecoder
+const uint16_t CAN_ACTIVE_BALANCING_PWM_3 = 0x713; // @canPayloadStruct CAN_ACTIVE_BALANCING_PWM_3 = ActiveBalancingPwmDecoder
+const uint16_t CAN_ACTIVE_BALANCING_PWM_4 = 0x714; // @canPayloadStruct CAN_ACTIVE_BALANCING_PWM_4 = ActiveBalancingPwmDecoder
+const uint16_t CAN_ACTIVE_BALANCING_PWM_5 = 0x715; // @canPayloadStruct CAN_ACTIVE_BALANCING_PWM_5 = ActiveBalancingPwmDecoder
+const uint16_t CAN_ACTIVE_BALANCING_PWM_6 = 0x716; // @canPayloadStruct CAN_ACTIVE_BALANCING_PWM_6 = ActiveBalancingPwmDecoder
+const uint16_t CAN_ACTIVE_BALANCING_PWM_7 = 0x717; // @canPayloadStruct CAN_ACTIVE_BALANCING_PWM_7 = ActiveBalancingPwmDecoder
+
+struct GPSCoords {
+ uint32_t lat;
+ uint32_t lon;
+};
+const uint16_t CAN_GPS = 0x750; // @canPayloadStruct CAN_GPS = GPSCoords
+struct GPSTime {
+ uint32_t centiSeconds;
+};
+const uint16_t CAN_GPS_TIME = 0x751; // @canPayloadStruct CAN_GPS_TIME = GPSTime
+struct GPSMeta {
+ uint8_t quality;
+ uint8_t numSats;
+ uint16_t deciHdop; // units of 1/10 hdop
+};
+const uint16_t CAN_GPS_META = 0x752; // @canPayloadStruct CAN_GPS_META = GPSMeta
+struct GPSAltitude {
+ uint32_t decimetersAltitude;
+};
+const uint16_t CAN_GPS_ALT = 0x753; // @canPayloadStruct CAN_GPS_ALT = GPSAltitude
+
+/** Mostly just tells the current RTC time. */
+// const uint16_t CAN_TELEMETRY_INFO = 0x800;
+// const uint16_t CAN_TELEMETRY_STAT = 0x801;
+// const uint16_t CAN_TELEMETRY_RTC = 0x802;
+// const uint16_t CAN_TELEMETRY_TEMP = 0x803;
+
+// Telemetry controls and messages
+
+// For inspiration, these are the IDs from Impulse
+
+//// Emergency signals
+//const uint16_t CAN_EMER_BPS = 0x021;
+//const uint16_t CAN_EMER_CUTOFF = 0x022;
+//const uint16_t CAN_EMER_DRIVER_IO = 0x023;
+//const uint16_t CAN_EMER_DRIVER_CTL = 0x024;
+//const uint16_t CAN_EMER_TELEMETRY = 0x025;
+//const uint16_t CAN_EMER_OTHER1 = 0x026;
+//const uint16_t CAN_EMER_OTHER2 = 0x027;
+//const uint16_t CAN_EMER_OTHER3 = 0x028;
+//
+//// Heartbeats
+//const uint16_t CAN_HEART_BPS = 0x041;
+//const uint16_t CAN_HEART_CUTOFF = 0x042;
+//const uint16_t CAN_HEART_DRIVER_IO = 0x043;
+//const uint16_t CAN_HEART_DRIVER_CTL = 0x044;
+//const uint16_t CAN_HEART_TELEMETRY = 0x045;
+//const uint16_t CAN_HEART_DATALOGGER = 0x046;
+//const uint16_t CAN_HEART_OTHER2 = 0x047;
+//const uint16_t CAN_HEART_OTHER3 = 0x048;
+//
+//// Cutoff signals
+//const uint16_t CAN_CUTOFF_VOLT = 0x523;
+//const uint16_t CAN_CUTOFF_CURR = 0x524;
+//const uint16_t CAN_CUTOFF_NORMAL_SHUTDOWN = 0x521;
+//
+//// BPS signals
+//#define CAN_BPS_BASE 0x100 // BPS signal base
+//#define CAN_BPS_MODULE_OFFSET 0x010 // Difference between modules
+//#define CAN_BPS_TEMP_OFFSET 0x00C // Offset in addition to module offset
+//#define CAN_BPS_DIE_TEMP_OFFSET 0x00C // Offset for LT die temperature
+//
+//// To Tritium signals
+//const uint16_t CAN_TRITIUM_DRIVE = 0x501;
+//const uint16_t CAN_TRITIUM_RESET = 0x503;
+//
+//// From Tritium signals
+//const uint16_t CAN_TRITIUM_ID = 0x400;
+//const uint16_t CAN_TRITIUM_STATUS = 0x401;
+//const uint16_t CAN_TRITIUM_BUS = 0x402;
+//const uint16_t CAN_TRITIUM_VELOCITY = 0x403;
+//const uint16_t CAN_TRITIUM_PHASE_CURR = 0x404;
+//const uint16_t CAN_TRITIUM_MOTOR_VOLT = 0x405;
+//const uint16_t CAN_TRITIUM_MOTOR_CURR = 0x406;
+//const uint16_t CAN_TRITIUM_MOTOR_BEMF = 0x407;
+//const uint16_t CAN_TRITIUM_15V_RAIL = 0x408;
+//const uint16_t CAN_TRITIUM_LV_RAIL = 0x409;
+//const uint16_t CAN_TRITIUM_FAN_SPEED = 0x40A;
+//const uint16_t CAN_TRITIUM_MOTOR_TEMP = 0x40B;
+//const uint16_t CAN_TRITIUM_AIR_TEMP = 0x40C;
+//const uint16_t CAN_TRITIUM_CAP_TEMP = 0x40D;
+//const uint16_t CAN_TRITIUM_ODOMETER = 0x40E;
+//
+//// Dashboard Signals
+//const uint16_t CAN_DASHBOARD_INPUTS = 0x481;
+
+#endif // __CAN_ID
diff --git a/app/src/test/java/com/example/bottomnav/ExampleUnitTest.java b/app/src/test/java/com/example/bottomnav/ExampleUnitTest.java
index 62f1867..c3d9876 100644
--- a/app/src/test/java/com/example/bottomnav/ExampleUnitTest.java
+++ b/app/src/test/java/com/example/bottomnav/ExampleUnitTest.java
@@ -14,4 +14,8 @@ public class ExampleUnitTest {
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
+ @Test
+ public void byteTest(){
+ System.out.println((byte)Integer.parseInt("80", 16));
+ }
}
\ No newline at end of file
diff --git a/app/src/test/java/com/example/bottomnav/ParseTest.java b/app/src/test/java/com/example/bottomnav/ParseTest.java
index 580dca3..3c9faa5 100644
--- a/app/src/test/java/com/example/bottomnav/ParseTest.java
+++ b/app/src/test/java/com/example/bottomnav/ParseTest.java
@@ -196,7 +196,22 @@ public void decodeIntegers() throws Exception {
assertEquals("MODE: -1", test.decode(0x407, thirtytwo));
}
+ @Test
+ public void doubleParse() throws Exception {
+ Parse test = Parse.parseTextFile("decode.h");
+ // Start
+ DataDecoder solution2 = test.getDecoder(0x310).get();
+
+ byte[] packedFloatPayload = {0x71, (byte) 0xFD, 0x47, 0x41};
+ String packedFloatMessage = "PACKED_FLOAT: 12.499375";
+ assertEquals(packedFloatMessage, test.decode(0x310, packedFloatPayload));
+ byte[] packet2 = {0x21, (byte) 0xFF, 0x37, 0x21};
+ test.decode(0x310, packet2);
+ System.out.println(solution2.getVarNameAt(0));
+ System.out.println(solution2.getValueStringAt(0));
+
+ }
@Test
public void decodingVariety() throws Exception {
Parse test = Parse.parseTextFile("decode.h");