Coder Social home page Coder Social logo

reactivesensors's Introduction

ReactiveSensors

Android Arsenal Android CI

Android library monitoring hardware sensors with RxJava.

Current Branch Branch Artifact Id Maven Central
RxJava1.x reactivesensors Maven Central
RxJava2.x reactivesensors-rx2 Maven Central
☑️ RxJava3.x reactivesensors-rx3 Maven Central

Contents

Usage

Code sample below demonstrates how to observe Gyroscope sensor.

Please note that we are filtering events occurring when sensor readings change with ReactiveSensorEvent::sensorChanged method. There's also event describing change of sensor's accuracy, which can be filtered with ReactiveSensorEvent::accuracyChanged method. When we don't apply any filter, we will be notified both about sensor readings and accuracy changes.

new ReactiveSensors(context).observeSensor(Sensor.TYPE_GYROSCOPE)
    .subscribeOn(Schedulers.computation())
    .filter(ReactiveSensorEvent::sensorChanged)
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Consumer<ReactiveSensorEvent>() {
      @Override public void call(ReactiveSensorEvent event) {

        float x = event.sensorValues()[0];
        float y = event.sensorValues()[1];
        float z = event.sensorValues()[2];

        String message = String.format("x = %f, y = %f, z = %f", x, y, z);

        Log.d("gyroscope readings", message);
      }
    });
}

We can observe any hardware sensor in the same way. You can check list of all sensors in official Android documentation. To get list of all sensors available on the current device, you can use getSensors() method available in ReactiveSensors class.

Setting sampling period

Default sampling period for Flowable below is set to SensorManager.SENSOR_DELAY_NORMAL.

Flowable<ReactiveSensorEvent> observeSensor(int sensorType)

We can configure sampling period according to our needs with the following flowable:

Flowable<ReactiveSensorEvent> observeSensor(final int sensorType, final int samplingPeriodInUs)

We can use predefined values available in SensorManager class from Android SDK:

  • int SENSOR_DELAY_FASTEST - get sensor data as fast as possible
  • int SENSOR_DELAY_GAME - rate suitable for games
  • int SENSOR_DELAY_NORMAL - rate (default) suitable for screen orientation changes
  • int SENSOR_DELAY_UI - rate suitable for the user interface

We can also define our own integer value in microseconds, but it's recommended to use predefined values.

We can customize RxJava Backpressure Strategy for our flowable with method:

Flowable<ReactiveSensorEvent> observeSensor(final int sensorType, final int samplingPeriodInUs,
                                            final BackpressureStrategy strategy)

Default Backpressure Strategy is BUFFER.

Example

Exemplary application, which gets readings of various sensors is located in app directory of this repository. You can easily change SENSOR_TYPE variable to read values from a different sensor in a given samples.

Good practices

Checking whether sensor exists

We should check whether device has concrete sensor before we start observing it.

We can do it in the following way:

if (reactiveSensors.hasSensor(SENSOR_TYPE)) {
  // observe sensor
} else {
  // show error message
}

Letting it crash

We can let our subscription crash and handle situation when device does not have given sensor e.g. in the Consumer<Throwable>() implementation (if we want to return Disposable) or in the onError(throwable) method implementation of the Subscriber. Other types of errors can be handled there as well.

new ReactiveSensors(context).observeSensor(Sensor.TYPE_GYROSCOPE)
    .subscribeOn(Schedulers.computation())
    .filter(ReactiveSensorEvent::sensorChanged)
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Consumer<ReactiveSensorEvent>() {
      @Override public void accept(ReactiveSensorEvent reactiveSensorEvent) throws Exception {
        // handle reactiveSensorEvent
      }
    }, new Consumer<Throwable>() {
      @Override public void accept(Throwable throwable) throws Exception {
        if (throwable instanceof SensorNotFoundException) {
          textViewForMessage.setText("Sorry, your device doesn't have required sensor.");
        }
      }
    });

Subscribing and disposing flowables

When we are using Disposables in Activity, we should subscribe them in onResume() method and dispose them in onPause() method.

Filtering stream

When we want to receive only sensor updates, we should use ReactiveSensorEvent::sensorChanged method in filter(...) method from RxJava.

When we want to receive only accuracy updates, we should use ReactiveSensorEvent::accuracyChanged method in filter(...) method from RxJava.

If we don't apply any filter, we will receive both accuracy and sensor readings updates.

Writing tests

ReactiveSensors class implements SensorsProxy interface. It allows you to create stubs or mocks for testing behavior of the sensors in your application without need of mocking SensorManager class from Android SDK accessing hardware components. Once you instantiate SensorsProxy, then you'll be allowed to mock or stub it pretty easily. Moreover, you can mock ReactiveSensorEvent, which wraps code from Android API, expose appropriate methods and does not force you to use native code accessing hardware sensors in tests, so you can foucus just on the application logic.

Other practices

See also Best Practices for Accessing and Using Sensors.

Download

latest version: Maven Central

replace x.y.z with the latest version

You can depend on the library through Maven:

<dependency>
    <groupId>com.github.pwittchen</groupId>
    <artifactId>reactivesensors-rx3</artifactId>
    <version>x.y.z</version>
</dependency>

or through Gradle:

dependencies {
  compile 'com.github.pwittchen:reactivesensors-rx3:x.y.z'
}

Tests

Tests are available in library/src/androidTest/java/ directory and can be executed on emulator or Android device from Android Studio or CLI with the following command:

./gradlew connectedCheck

Code style

Code style used in the project is called SquareAndroid from Java Code Styles repository by Square available at: https://github.com/square/java-code-styles. Currently, library doesn't have checkstyle verification attached. It can be done in the future.

Static code analysis

Static code analysis runs Checkstyle, FindBugs, PMD and Lint. It can be executed with command:

./gradlew check

Reports from analysis are generated in library/build/reports/ directory.

Releasing

See RELEASING.md file.

References

License

Copyright 2015 Piotr Wittchen

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.

reactivesensors's People

Contributors

catalinghita8 avatar dependabot-preview[bot] avatar pwittchen avatar shawnduan avatar

Stargazers

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

Watchers

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

reactivesensors's Issues

release 0.3.3 (rx2, rx3)

Release notes:

  • added SensorsProxy interface implemented by ReactiveSensors class to improve library integration and testability in external projects, which depend on it

Crash on subscribe

I just copy pasted the sample code on the Github page into my project :

    new ReactiveSensors(context).observeSensor(Sensor.TYPE_GYROSCOPE)
        .subscribeOn(Schedulers.computation())
        .filter(ReactiveSensorFilter.filterSensorChanged())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Action1<ReactiveSensorEvent>() {
          @Override public void call(ReactiveSensorEvent reactiveSensorEvent) {
            SensorEvent event = reactiveSensorEvent.getSensorEvent();

            float x = event.values[0];
            float y = event.values[1];
            float z = event.values[2];

            String message = String.format("x = %f, y = %f, z = %f", x, y, z);

            Log.d("gyroscope readings", message);
          }
        });

But I get this error :

FATAL EXCEPTION: main
Process: com.qbes.totobusdriver, PID: 4543
java.lang.IllegalStateException: Exception thrown on Scheduler.Worker thread. Add onError handling.
at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:60)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6117)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: rx.exceptions.OnErrorNotImplementedException
at rx.Observable$27.onError(Observable.java:7923)
at rx.observers.SafeSubscriber._onError(SafeSubscriber.java:159)
at rx.observers.SafeSubscriber.onError(SafeSubscriber.java:120)
at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.pollQueue(OperatorObserveOn.java:191)
at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber$2.call(OperatorObserveOn.java:162)
at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:6117) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194) 
Caused by: rx.exceptions.MissingBackpressureException
at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.onNext(OperatorObserveOn.java:130)
at rx.internal.operators.OperatorFilter$1.onNext(OperatorFilter.java:54)
at rx.internal.operators.OperatorSubscribeOn$1$1$1.onNext(OperatorSubscribeOn.java:76)
at com.github.pwittchen.reactivesensors.library.ReactiveSensors$1$1.onSensorChanged(ReactiveSensors.java:110)
at android.hardware.SystemSensorManager$SensorEventQueue.dispatchSensorEvent(SystemSensorManager.java:503)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:143)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:6117) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194) 

Release 0.2.0

Initial release notes:

  • returning error through Rx to make the error handling easier - issue #29
  • creating sensor observable with the ability to specify handler - PR #26
  • updated project dependencies
  • migrated library to RxJava2.x on RxJava2.x branch
  • kept backward compatibility with RxJava1.x on RxJava1.x branch
  • removed master branch

Things to do:

  • Branch RxJava1.x
    • update JavaDoc on gh-pages
    • bump library version
    • upload archives to Maven Central
    • close and release artifact on Maven Central
    • update CHANGELOG.md after Maven Sync
    • bump library version in README.md
    • create new GitHub release
  • Branch RxJava2.x
    • update artifact name
    • update JavaDoc on gh-pages
    • bump library version
    • upload archives to Maven Central
    • close and release artifact on Maven Central
    • update CHANGELOG.md after Maven Sync
    • bump library version in README.md
    • create new GitHub release

Observing multiple sensors together

In this popular Android docs example of computing device orientation using accelerometer and magnetometer, sensor manager registers to listen to multiple sensors, which seems to be currently not possible in the API of ReactiveSensors. Can you point me if this is possible? I see that code of ReactiveSensor.observeSensor cannot handle it currently. Is there any plans to add the same? Or would you be interested in a PR for this?

Release 0.1.0

Initial release notes:

  • removed filterSensorChanged() method from ReactiveSensorEvent class
  • removed filterAccuracyChanged() method from ReactiveSensorEvent class
  • created ReactiveSensorFilter class
  • added filterSensorChanged() method to ReactiveSensorFilter class
  • added filterAccuracyChanged() method to ReactiveSensorFilter class
  • added sample app in Kotlin
  • added code examples with more sensors in sample apps
  • improved sample apps
  • added Static Code Analysis (CheckStyle, PMD, FindBugs, Android Lint)
  • updated documentation in README.md file

Things to do:

  • bump library version
  • upload archives to Maven Central
  • close and release artifact on Maven Central
  • update JavaDoc on gh-pages
  • update CHANGELOG.md after Maven Sync
  • bump library version in README.md
  • create new GitHub release

Fatal exception when the device does not have the sensor

Hi,

If the device does not have the sensor you are throwing a fatal exception outside the Rx scope. Isn't it better if you put the error to the Rx error stream ? So the client that subscribe can handle the error properly inside the onError callback and all the on Error operator.

I can PR

Regards,
Lucas

Automate deployment to Maven Central

Currently I'm performing deployments manually from my computer.

It should be possible to execute the following gradle commands on GH Actions CI:

  • uploadArchives
  • closeAndReleaseRepository

I've already added secrets to this repo via GH secret configuration.

Things to be done:

  • build project
  • add private gpg key to the project during the build (GPG_PRIVATE_KEY secret)
  • configure signing.keyId gradle param with GPG_KEY_ID secret
  • configure signing.password gradle param with GPG_PASSWORD secret
  • configure signing.secretKeyRingFile (it's defined locally on my machine) or a specific certificate (2nd point) - maybe this can be skipped, left empty or replaced with something else -> to be verified and tested
  • configure NEXUS_USERNAME gradle param with NEXUS_USERNAME secret
  • configure NEXUS_PASSWORD gradle param with NEXUS_PASSWORD secret
  • run uploadArchives gradle command
  • run closeAndReleaseRepository gradle command (this should be tested once command above will work because during tests we can upload and then remove artifacts without releasing them and when command above will fail, this one will fail too)

Notes:

  • Probably CI signing configuration will be a bit different than the local one. I think, the best idea would be to load private GPG Key into memory with GH action and then use in memory GPG Key with Key Id and Key Password and add appropriate gradle singing configuration according to the documentation. Then We can skip signing.secretKeyRingFile which is in the local setup.

References:

Release library v. 0.0.1

Tasks:

  • Upload library to Maven Central Repository. ✅ done
  • Update download section in README.md after Maven Sync. ✅ done
  • Create GitHub release of v. 0.0.1. ✅ done

Improve library testability/integration

Add ReactiveSensorsProxy or SensorsProxy interface, which will be implemented by ReactiveSensors class. Thanks to that, library will be more "pluggable" in other projects like apps and libs, what will allow to make code decomposition and testing easier. Moreover, after this improvement, we can think of simple sensors event stream simulation/mocking.

Release 0.3.0-rx2

Release notes:

  • added multiple sensors observing feature
  • updated getters of ReactiveSensorEvent (removed get prefix)
  • updated project dependencies
  • removed handler param from the library API

Release 0.1.2

Initial release notes:

  • bumped RxJava dependency to v. 1.1.8
  • bumped RxAndroid dependency to v. 1.2.1
  • bumped Google Truth test dependency to v. 0.28
  • bumped Compile SDK version to v. 23
  • bumped Kotlin to v. 1.0.0
  • updated sample apps

Things to do:

  • bump library version
  • upload archives to Maven Central
  • close and release artifact on Maven Central
  • update CHANGELOG.md after Maven Sync
  • bump library version in README.md
  • create new GitHub release

Handler param should be removed from methods

You should remove handler param from public methods. You have to create handler on your own based on thread execution (Schedulers in subscribeOn method) and then pass it to SensorManager. Right now, I can pass a handler (related to custom HandlerThread) and call subscribeOn (eg. Schedulers.computation()). So replace passing a handler with supporting Schedulers in correct way.

ReactiveSensors not working with Sensor.TYPE_STEP_COUNTER

ReactiveSensors returns does not return ReactiveSensor Event when calling callback.
.subscribe(new Consumer<ReactiveSensorEvent>() { @Override public void accept(ReactiveSensorEvent **reactiveSensorEvent**) throws Exception { SensorEvent event = reactiveSensorEvent.getSensorEvent(); sendSensorBroadcast(event); } }
reactiveSensorEvent == null!!
Any thoughts regarding that topic?
Beside great lib of yours, love it a lot.

release 0.4.0 [rx2, rx3]

Release notes:

  • added new methods to ReactiveSensorEvent class: int sensorId(), String sensorName(), float[] sensorValues()

Note:

  • for rx-3 I released 0.4.1 due to some issues with sonatype. I wasn't sure if the artifact for 0.4.0 was released or not

Release 0.3.2 (rx2, rx3)

Release notes:

  • fixing Flowable - moving sensors registration before Flowable.create(...) method (without that several RxJava operators could not be applied on the stream)
  • making ReactiveSensorEvent non-final
  • making SensorEventListener package-private
  • changing FlowableEmitter in SensorEventListener to Emitter
  • removing getEmitter() method from SensorEventListenerWrapper

Release 0.1.1

Initial release notes:

  • bumped RxJava dependency to v. 1.1.0
  • bumped RxAndroid dependency to v. 1.1.0
  • bumped Google Truth test dependency to v. 0.27
  • bumped Gradle Build Tools to v. 1.3.1

Things to do:

  • bump library version
  • upload archives to Maven Central
  • close and release artifact on Maven Central
  • update CHANGELOG.md after Maven Sync
  • bump library version in README.md
  • create new GitHub release

Recommend Projects

  • React photo React

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

  • Vue.js photo Vue.js

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

  • Typescript photo Typescript

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

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

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

  • web

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

  • server

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

  • Machine learning

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

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

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

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.