Coder Social home page Coder Social logo

react-native-sensor-manager's Introduction

react-native-sensor-manager

Wrapper for react-native. Accelerometer, Gyroscope, Magnetometer, Orientation, Step Counter, Thermometer, LightSensor, and Proximity Sensor are supported for now.

Add it to your project

$ npm i react-native-sensor-manager --save

Option: With rnpm

rnpm link

Option: Manually (try it if an runtime error occurs after nrpm link)

Make alterations to the following files:

  • android/settings.gradle
...
include ':react-native-sensor-manager'
project(':react-native-sensor-manager').projectDir = new File(settingsDir, '../node_modules/react-native-sensor-manager/android')
  • android/app/build.gradle
...
dependencies {
    ...
    compile project(':react-native-sensor-manager')
}
  • register module (in MainApplication.java)

    • For react-native below 0.19.0 (use cat ./node_modules/react-native/package.json | grep version)
import com.sensormanager.SensorManagerPackage; // <------ add package

public class MainActivity extends Activity implements DefaultHardwareBackBtnHandler {

  ......

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mReactRootView = new ReactRootView(this);

    mReactInstanceManager = ReactInstanceManager.builder()
      .setApplication(getApplication())
      .setBundleAssetName("index.android.bundle")
      .setJSMainModuleName("index.android")
      .addPackage(new MainReactPackage())
      .addPackage(new SensorManagerPackage())      // <------- add package
      .setUseDeveloperSupport(BuildConfig.DEBUG)
      .setInitialLifecycleState(LifecycleState.RESUMED)
      .build();

    mReactRootView.startReactApplication(mReactInstanceManager, "ExampleRN", null);

    setContentView(mReactRootView);
  }

  ......

}
  • For react-native 0.19.0 and higher
import com.sensormanager.SensorManagerPackage; // <------ add package

public class MainApplication extends Application implements ReactApplication {
   // ...
    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
        new MainReactPackage(), // <---- add comma
        new SensorManagerPackage() // <---------- add package
      );
    }

Api

Setup

import React, {
  DeviceEventEmitter // will emit events that you can listen to
} from 'react-native';

import { SensorManager } from 'NativeModules';

Accelerometer

SensorManager.startAccelerometer(100); // To start the accelerometer with a minimum delay of 100ms between events.
DeviceEventEmitter.addListener('Accelerometer', function (data) {
  /**
  * data.x
  * data.y
  * data.z
  **/
});
SensorManager.stopAccelerometer();

Gyroscope

DeviceEventEmitter.addListener('Gyroscope', function (data) {
  /**
  * data.x
  * data.y
  * data.z
  **/
});
SensorManager.startGyroscope(100);
SensorManager.stopGyroscope();

Magnetometer

SensorManager.startMagnetometer(100);
DeviceEventEmitter.addListener('Magnetometer', function (data) {
  /**
  * data.x
  * data.y
  * data.z
  **/
});
SensorManager.stopMagnetometer();

Orientation

SensorManager.startOrientation(100);
DeviceEventEmitter.addListener('Orientation', function (data) {
  /**
  * data.azimuth
  * data.pitch
  * data.roll
  **/
});
SensorManager.stopOrientation();

Step Counter

SensorManager.startStepCounter(1000);
DeviceEventEmitter.addListener('StepCounter', function (data) {
  /**
  * data.steps
  **/
});
SensorManager.stopStepCounter();

Thermometer

SensorManager.startThermometer(1000);
DeviceEventEmitter.addListener('Thermometer', function (data) {
  /**
  * data.temp
  **/
});
SensorManager.stopThermometer();

LightSensor

SensorManager.startLightSensor(100);
DeviceEventEmitter.addListener('LightSensor', function (data) {
  /**
  * data.light
  **/
});
SensorManager.stopLightSensor();

Proximity Sensor

SensorManager.startProximity(100);
DeviceEventEmitter.addListener('Proximity', function (data) {
  /**
  * data.isNear: [Boolean] A flag representing whether something is near the screen.
  * data.value: [Number] The raw value returned by the sensor (usually distance in cm).
  * data.maxRange: [Number] The maximum range of the sensor.
  **/
});
SensorManager.stopProximity();

react-native-sensor-manager's People

Contributors

dzcpy avatar ghengeveld avatar kprimice avatar leforestier avatar mcrowe avatar ohtangza avatar pocket-titan avatar velcio avatar zxcpoiu 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

react-native-sensor-manager's Issues

is there anyway to run two functions at the same time ?

I'm trying to send the values of the acceleration and orientation to the backend
but the orientation values are way faster than the Accelerometer
how can I send the values of the two sensors at the same time ? at the same speed ?

mSensorManager undefined

var mSensorManager = require('NativeModules').SensorManager;
NativeModules does not have a SensorManager key.

When I console.log the keys of NativeModules, I get the following values:
["FrescoModule", "DeviceEventManager", "AndroidConstants", "IntentAndroid", "AsyncSQLiteDBStorage", "DebugComponentOwnershipModule", "ImageLoader", "DialogManagerAndroid", "ToastAndroid", "AnimationsDebugModule", "Vibration", "LocationObserver", "NetInfo", "AndroidPermissions", "ImageStoreManager", "AppState", "JSCHeapCapture", "WebSocketModule", "StatusBarManager", "TimePickerAndroid", "Clipboard", "DatePickerAndroid", "Timing", "Networking", "CameraRollManager", "ExceptionsManager", "ImageEditingManager", "SourceCode", "UIManager"]

Gyroscope event not triggered

The listener 'Gyroscope' is never triggered, I have no errors at all, but nothing never happens. I suppose my code is Ok since all other sensors are working well. Tried on a Samsung and a Sony device. Any idea ?

import React, {DeviceEventEmitter} from 'react-native';

var mSensorManager = require('NativeModules').SensorManager;
mSensorManager.startGyroscope(100);
DeviceEventEmitter.addListener('Gyroscope', function(data) {
  // Got never here
});

NFC card read

at first thanks for your great job.

I wanted to ask if you have any plan to add NFC as well. you have covered all sensors but the NFC.

Or can you help me adding the nfc card tag reading feature to your module?

Thanks in advance!

Orientation listener callback gets called multiple times despite stopping right after the first update

componentDidMount() {
	SensorManager.startOrientation(5000); // Minimum delay does not work :(
	DeviceEventEmitter.addListener("Orientation", orientation => {
		SensorManager.stopOrientation();
		alert(JSON.stringify(orientation));
	});
}

This causes my component to popup an alert over 15 times before actually stopping. Is there anything I could do to only render once? Any help would be much appreciated! Thank you in advanced!

Magnetometer error

i am facing this error:
TypeError: undefined is not an object evaluation
mSensorManager.startMagnetometer
here is mt code :
var mSensorManager = require('NativeModules').SensorManager;

componentDidMount() {
mSensorManager.startMagnetometer(100);
DeviceEventEmitter.addListener('azimuthChanged', this.azimuthChanged.bind(this));

   this.interval = setInterval(() => {
  this.setState({
    azimuth: this.currentAzimuth
  });
}, 100);

}

Please Add OrientationRecord.java to determine azimuth pitch and roll events.

I do apologize but I have written this class to detect orientation change events using the accelerometer and the magnetometer. It uses Java's SensorManager.getRotationMatrix() and getOrientation() methods to determine the orientation of the device. This will help avoid complex geometry calculations for determining the orientation. It's untested but if you could merge it that'd be highly appreciated. I'd even donate for the trouble. Thanks heaps.

package com.sensormanager;

import android.os.Bundle;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;
import android.support.annotation.Nullable;

import java.io.*;
import java.util.Date;
import java.util.Timer;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.bridge.ReactApplicationContext;

public class OrientationRecord implements SensorEventListener {

  private SensorManager mSensorManager;
  private Sensor mAccelerometer;
  private Sensor mMagnetometer;
  private long lastUpdate = 0;
  private int i = 0, n = 0;
    private int delay;
    private int isRegistered = 0;

    private ReactContext mReactContext;
    private Arguments mArguments;


    public AccelerometerRecord(ReactApplicationContext reactContext) {
        mSensorManager = (SensorManager)reactContext.getSystemService(reactContext.SENSOR_SERVICE);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mMagnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
            mReactContext = reactContext;
    }

    public int start(int delay) {
        this.delay = delay;
        if (mAccelerometer != null && isRegistered == 0) {
            mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_FASTEST);
      mSensorManager.registerListener(this, mMagnetometer, SensorManager.SENSOR_DELAY_FASTEST);
            isRegistered = 1;
            return (1);
        }
        return (0);
    }

    public void stop() {
        if (isRegistered == 1) {
            mSensorManager.unregisterListener(this);
        isRegistered = 0;
      }
    }

    private void sendEvent(String eventName, @Nullable WritableMap params)
    {
        try {
            mReactContext 
                .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) 
                .emit(eventName, params);
        } catch (RuntimeException e) {
            Log.e("ERROR", "java.lang.RuntimeException: Trying to invoke JS before CatalystInstance has been set!");
        }
    }

  float[] mGravity;
  float[] mGeomagnetic;

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
      Sensor mySensor = sensorEvent.sensor;
          WritableMap map = mArguments.createMap();

      if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER)
        mGravity = sensorEvent.values;
      if (mySensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
        mGeomagnetic = sensorEvent.values;
      if (mGravity != null && mGeomagnetic != null) {
        float R[] = new float[9];
        float I[] = new float[9];
        boolean success = mSensorManager.getRotationMatrix(R, I, mGravity, mGeomagnetic);
        if (success) {
          long curTime = System.currentTimeMillis();
          float orientation[] = new float[3];
          mSensorManager.getOrientation(R, orientation);

          map.putDouble("azimuth", orientation[0]);
          map.putDouble("pitch", orientation[1]);
          map.putDouble("roll", orientation[2]);
          sendEvent("Orientation", map);
          lastUpdate = curTime;
        }
      }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }
}

Ability to as animation driver with useNativeDriver

Thanks for this awesome module.

I was using it to drive an animation but it is hurting performance. Is there anyway to use it as we use Animation event drivers - https://medium.com/xebia/linking-animations-to-scroll-position-in-react-native-5c55995f5a6e

This connects to scroll of a scroll view:

    const xOffset = new Animated.Value(0);

    const onScroll = Animated.event([{ nativeEvent: { contentOffset: { x: xOffset } } }], { useNativeDriver: true });

    <ScrollView scrollEventThrottle={16} onScroll={onScroll}>
        // ...
    </ScrollView>

M sensor manager not loading

Apparently, I've followed your installation steps using rnpm and after pasting sensor manager + accelerometer code to my blank new project an error was caused because require('NativeModules').SensorManager; did not load anything. Any reason why?

'undefined is not an object(evaluating mSensorManager.startAccelerometer)'

Issue with import android.support.annotation.Nullable;

I was trying to integrate react-native-sensors-manager in my application and getting below error when I try to build.

I think the issue is with the below package which we're using.

import android.support.annotation.Nullable;

image

needs check before invoke start() or stop()

After playing around, I think we need to add some check before invoke start() / stop(), also before create new instance of sensors. or it will either crash or register multiple instances.

below is what I came up for now:

  1. check whether instance being created in SensorManagerModule.java
diff --git a/android/src/main/java/com/sensormanager/SensorManagerModule.java b/android/src/main/java/com/sensormanager/SensorManagerModule.java
index 8fb0504..2e66e2a 100644
--- a/android/src/main/java/com/sensormanager/SensorManagerModule.java
+++ b/android/src/main/java/com/sensormanager/SensorManagerModule.java
@@ -17,7 +17,7 @@ public class SensorManagerModule extends ReactContextBaseJavaModule {
    private StepCounterRecord       mStepCounterRecord;
    private ThermometerRecord       mThermometerRecord;
    private MotionValueRecord       mMotionValueRecord;
-   private ProximityRecord         mProximityRecord;
+   private ProximityRecord         mProximityRecord = null;

    private ReactApplicationContext mReactContext;

@@ -99,13 +99,17 @@ public class SensorManagerModule extends ReactContextBaseJavaModule {

     @ReactMethod
     public int startProximity(int delay) {
-       mProximityRecord = new ProximityRecord(mReactContext);
+        if (mProximityRecord == null) {
+           mProximityRecord = new ProximityRecord(mReactContext);
+        }
        return (mProximityRecord.start(delay));
     }

     @ReactMethod
     public void stopProximity() {
-       mProximityRecord.stop();
+       if (mProximityRecord != null) {
+           mProximityRecord.stop();
+       }
     }

    /*
  1. track and check whether sensor is registered before invoke in start()/stop()
diff --git a/android/src/main/java/com/sensormanager/ProximityRecord.java b/android/src/main/java/com/sensormanager/ProximityRecord.java
index 40569da..3c5d0eb 100644
--- a/android/src/main/java/com/sensormanager/ProximityRecord.java
+++ b/android/src/main/java/com/sensormanager/ProximityRecord.java
@@ -25,26 +25,39 @@ public class ProximityRecord implements SensorEventListener {
     private long lastUpdate = 0;
     private int i = 0;
     private int delay;
+    private int isRegistered = 0;

     private ReactContext mReactContext;
     private Arguments mArguments;

     public ProximityRecord(ReactApplicationContext reactContext) {
         mSensorManager = (SensorManager)reactContext.getSystemService(reactContext.SENSOR_SERVICE);
+        mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
         mReactContext = reactContext;
     }

+    public boolean isSupported() {
+        return (mProximity != null);
+    }
+
    public int start(int delay) {
         this.delay = delay;
-        if ((mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY)) != null) {
+        if (isRegistered == 1) {
+            return (1);
+        }
+        if (isSupported()) {
             mSensorManager.registerListener(this, mProximity, SensorManager.SENSOR_DELAY_FASTEST);
+            isRegistered = 1;
             return (1);
         }
         return (0);
     }

     public void stop() {
-        mSensorManager.unregisterListener(this);
+        if (isRegistered == 1) {
+            mSensorManager.unregisterListener(this);
+            isRegistered = 0;
+        }
     }

     private void sendEvent(String eventName, @Nullable WritableMap params) {

what do you think?

How to reset step counter?

I am pretty new to react native (and android/java) and was playing around with your package, but stopping/starting StepCounterRecord does not seem to affect the count in the slightest.

Is there a way to do this in the code? If not I may try looking deeper into the java code.

NativeModules.SensorManger is undefined

I followed the steps, ran react-native run-android, but when I call NativeModules.SensorManager, it's undefined.

Ideas?

import { DeviceEventEmitter, NativeModules } from 'react-native';

const mSensorManager = NativeModules.SensorManager;

mSensorManager.startLightSensor(100);
DeviceEventEmitter.addListener('LightSensor', ({ light }) => {
  console.log(light);
});

define which camera to take LightSensor input

I am assuming the light sensor value is being derived from the camera.

I've noticed that the light sensor derives values from the front camera of the phone.

Is it possible to define whether to use the front or back camera of the phone? or is it just the case the light sensor is situated there? The latter would also make sense as that's what the device would be using to calibrate the screen brightness

NativeModules Error

Error: Unable to resolve module NativeModules from ......../app: NativeModules could not be found within the project.

I am using

"react": "16.9.0",
 "react-native": "0.61.5",

rnpm doesn't link properly

Hi!

rnpm was able to update

  • android/settings.gradle
  • android/app/build.gradle

But it mis-updated MainActivity instead of Application and that only import com.sensormanager.SensorManagerPackage;' line was added in MainActivity`!

I had to resort to manually updating the Application file!

How to decide the direction count that how much time device is rotated left, right, up or down ?

How to detect the direction when I move it (left, right, up and down)?

I installed react-native sensor npm install react-native-sensors --save.

**import { accelerometer } from "react-native-sensors";

const subscription = accelerometer.subscribe(({ x, y, z, timestamp }) =>
console.log({ x, y, z, timestamp })
);**
I tested with the above code it works smoothly.

But, how can I detect the directions?

How can I detect the direction when I move it (left, right, up and down)?

How to use LightSensor?

I get undefined is not a function (evaluating 'mSensorManager.startLightSensor(100);') this error message.

add method `start` for each sensor

Since not all sensors supported on any android versions, can we add a method start() which we register listener explicitly instead register directly in constructor.

We can detect Sensor Availability in the constructor and show some warnings if sensor is not supported in this device.

I can help if you agree

Some errors

sensormanager/LightSensorRecord.java:39: error: cannot find symbol if ((mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT)) != nul) { ^ symbol: variable nul location: class LightSensorRecord 1 error
==>missing l for null
sensormanager/SensorManagerModule.java:137: error: missing return statement } ^ 1 error
==>
public int stopLightSensor() { if(mLightSensorRecord != null) mLightSensorRecord.stop(); }this should be void

'Orientation' API missing.

In the documentation, it stated that you could use SensorManager.startOrientation(100) , but it produced 'not a function' error. To make sure, I logged SensorManager, and it was not really there.
Though, it was present in the source code atleast.

Broken on RN 0.33.0

Here is the stack trace:

:react-native-sensor-manager:compileReleaseJavaWithJavac
/Users/julienvincent/code/yumo/mobile/node_modules/react-native-sensor-manager/android/src/main/java/com/sensormanager/OrientationRecord.java:21: error: class OrientationValueRecord is public, should be declared in a file named OrientationValueRecord.java
public class OrientationValueRecord implements SensorEventListener { private SensorManager mSensorManager;
       ^
/Users/julienvincent/code/yumo/mobile/node_modules/react-native-sensor-manager/android/src/main/java/com/sensormanager/OrientationRecord.java:88: error: cannot find symbol
                mSensorManager.getOrientationValue(R, orientation);
                              ^
  symbol:   method getOrientationValue(float[],float[])
  location: variable mSensorManager of type SensorManager
2 errors
:react-native-sensor-manager:compileReleaseJavaWithJavac FAILED

Delay Not Working

Try to change orientation delay value from 100 to 1000000 and there is no difference

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.