2. Java

2.1. Java

This tutorial will take you through your first Java App.

2.1.1. Prerequisites

If you are new to Android development, download Android Studio and enable debugging over USB on your Android device. You should be familiar with the Java language and know how to deploy apps before starting the Android Java tutorials.

2.1.2. Template App

For those who want to build a simple MetaWear app or are new to Android development, we have provided a template for creating MetaWear apps which we will be using in this guide. Download the Android template and import the project into Android Studio. All the code on this page will be added to the starter module.

Advanced developers building more complex apps can refer to the Android Documentation for explicit installation instructions of the MetaWear library.

2.1.3. Modules

MetaWear modules are sensors or peripherals that are on the board. Modules are represented by the Module interface and you retrieve references to them with the getModule function. The function may return null if the module is unsupported however all MetaWear boards have an accelerometer so we can safely assume the return value is non-null in this example.

In the onServiceConnected function, retrieve a reference to the Accelerometer module and configure the sensor.

private Accelerometer accelerometer;

@Override
public void onServiceConnected(ComponentName name, IBinder service) {
    metawear = ((BtleService.LocalBinder) service).getMetaWearBoard(settings.getBtDevice());

    accelerometer= metawear.getModule(Accelerometer.class);
    accelerometer.configure()
           .odr(25f)       // Set sampling frequency to 25Hz, or closest valid ODR
           .commit();
}

2.1.3.1. UI Elements

Next, add a start and stop button to the fragment layout defined in the fragment_device_setup.xml file.

<Button android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:text="Start" android:id="@+id/acc_start"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentEnd="true" />

<Button android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:text="Stop" android:id="@+id/acc_stop"
    android:layout_below="@+id/acc_start"
    android:layout_alignParentStart="true"
    android:layout_alignParentEnd="true" />

2.1.3.2. Data Stream

Switching back to the DeviceSetupActivityFragment class, override the onViewCreated function to add listeners for the start and stop buttons. The start button will setup a data route, subscribe to the data stream, and start the sensor. The stop button will stop the sensor and remove the data route.

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    view.findViewById(R.id.acc_start).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            accelerometer.acceleration().addRouteAsync(new RouteBuilder() {
                @Override
                public void configure(RouteElement source) {
                    source.stream(new Subscriber() {
                        @Override
                        public void apply(Data data, Object... env) {
                            Log.i("MainActivity", data.value(Acceleration.class).toString());
                        }
                    });
                }
            }).continueWith(new Continuation<Route, Void>() {
                @Override
                    public Void then(Task<Route> task) throws Exception {
                        accelerometer.acceleration().start();
                        accelerometer.start();
                        return null;
                    }
            });
        }
    });
    view.findViewById(R.id.acc_stop).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            accelerometer.stop();
            accelerometer.acceleration().stop();
            metawear.tearDown();
        }
    });
}

2.1.3.3. Test the App

Load the app onto your Android device and connect to your board. Press the start button to see the acceleration data in Logcat.

2.1.4. Freefall App

The free fall tutorial showcases advanced features of the MetaWear by using the on-board data processing to convert raw accelerometer data into a free fall metric. We will be building the app from scratch following the instructions outlined in the Android SDK documentation.

Source code for this tutorial is available on GitHub.

2.1.4.1. Project Setup

We kick off the free fall tutorial by showing you how to setup your project to use the MetaWear Android SDK.

2.1.4.2. Bluetooth LE Connection

Part B shows you how to connect to your MetaWear using the Android SDK.

2.1.4.3. Accelerometer Data Stream

Part C sets up a data stream of accelerometer sending live data from the sensor to your mobile device.

2.1.4.4. Data Processor

Part D utilizes the firmware data processor to manipulate the raw acceleration data on-board. By using the on-board data procesor, you can perform simple computations on the data without having to transmit the raw data.

2.1.4.5. On-Board Logging

In the last segment of this tutorial, we use the logger to record when the free fall events happened, and download the data at a later time.

For a deeper dive into the Android SDK, checkout the documentation page for links to additional information about the MetaWear SDKs.

2.1.4.6. Event Handling

Say you want your MetaWear to react to different events, for example, turn on the LED when the switch is pressed and turn off the LED by tapping the board. This is easily accomplished in a data route using the stream component however, it requires that the board remains connected to your Android device at all times. Using the react component, we can instead program the board to respond to these events offline thus removing the need for an external app to handle the events for us.

2.1.4.7. Route Setup

Before we go around adding react components in our data route, first, lets create the route that uses the Android device to manage events.

metawear.getModule(Switch.class).state().addRouteAsync(new RouteBuilder() {
    @Override
    public void configure(RouteComponent source) {
        source.stream(new Subscriber() {
            @Override
            public void apply(Data data, Object... env) {
                if (data.value(Boolean.class)) {
                    led.editPattern(Led.Color.BLUE, Led.PatternPreset.SOLID).commit();
                    led.play();
                }
            }
        });
    }
}).onSuccessTask(new Continuation<Route, Task<Route>>() {
    @Override
    public Task<Route> then(Task<Route> task) throws Exception {
        return accBosch.tap().addRouteAsync(new RouteBuilder() {
            @Override
            public void configure(RouteComponent source) {
                source.stream(new Subscriber() {
                    @Override
                    public void apply(Data data, Object... env) {
                        led.stop(true);
                    }
                });
            }
        });
    }
});

From here, replace the stream components with react components. For brevity, only the route functions are in the code snippets with the first route corresponding to the switch data.

// Switch reaction route
source.react(new RouteComponent.Action() {
    @Override
    public void execute(DataToken token) {
        led.editPattern(Led.Color.BLUE, Led.PatternPreset.SOLID).commit();
        led.play();
    }
});

// Tap reaction route
source.react(new RouteComponent.Action() {
    @Override
    public void execute(DataToken token) {
        led.stop(true);
    }
});

As you may have noticed, the if statement from the streaming route is not present in the reaction route. This is because only MetaWear commands can be used inside a reaction, that is, no Java language constructs like loops and no functions that reside outside of the MetaWear SDK. The commands wrapped by the execute method are run whenever there is new data or activity from its input source, meaning our reaction based route actually turns on the LED whenever the button state changes i.e. when both a press and release are detected.

To remedy this small bug, we will insert a data processing component in between the switch source and reaction so that only button presses are reacted upon. In this case, we use the comparator filter to check for switch values not equal to 0 (1 = pressed, 0 = released).

Our data route now looks as follows:

metawear.getModule(Switch.class).state().addRouteAsync(new RouteBuilder() {
    @Override
    public void configure(RouteComponent source) {
        source.filter(Comparison.NEQ, 0).react(new RouteComponent.Action() {
            @Override
            public void execute(DataToken token) {
                led.editPattern(Led.Color.BLUE, Led.PatternPreset.SOLID).commit();
                led.play();
            }
        });
    }
}).onSuccessTask(new Continuation<Route, Task<Route>>() {
    @Override
    public Task<Route> then(Task<Route> task) throws Exception {
        return accBosch.tap().addRouteAsync(new RouteBuilder() {
            @Override
            public void configure(RouteComponent source) {
                source.react(new RouteComponent.Action() {
                    @Override
                    public void execute(DataToken token) {
                        led.stop(true);
                    }
                });
            }
        });
    }
});

2.1.4.8. Cleanup

The MetaWear firmware only has limited resources available for reaction commands and data processing. Before you disconnect from the board or reload the app, remember to remove the routes that were created by calling Route interface’s remove function on the Route objects returned by addRouteAsync.