UNPKG

1.88 kBPlain TextView Raw
1'use strict';
2import NativeReanimatedModule from './NativeReanimated';
3import type {
4 SensorConfig,
5 SharedValue,
6 Value3D,
7 ValueRotation,
8 ShareableRef,
9} from './commonTypes';
10import { SensorType } from './commonTypes';
11import { makeMutable } from './mutables';
12
13function initSensorData(
14 sensorType: SensorType
15): SharedValue<Value3D | ValueRotation> {
16 if (sensorType === SensorType.ROTATION) {
17 return makeMutable<Value3D | ValueRotation>({
18 qw: 0,
19 qx: 0,
20 qy: 0,
21 qz: 0,
22 yaw: 0,
23 pitch: 0,
24 roll: 0,
25 interfaceOrientation: 0,
26 });
27 } else {
28 return makeMutable<Value3D | ValueRotation>({
29 x: 0,
30 y: 0,
31 z: 0,
32 interfaceOrientation: 0,
33 });
34 }
35}
36
37export default class Sensor {
38 public listenersNumber = 0;
39 private sensorId: number | null = null;
40 private sensorType: SensorType;
41 private data: SharedValue<Value3D | ValueRotation>;
42 private config: SensorConfig;
43
44 constructor(sensorType: SensorType, config: SensorConfig) {
45 this.sensorType = sensorType;
46 this.config = config;
47 this.data = initSensorData(sensorType);
48 }
49
50 register(
51 eventHandler: ShareableRef<(data: Value3D | ValueRotation) => void>
52 ) {
53 const config = this.config;
54 const sensorType = this.sensorType;
55 this.sensorId = NativeReanimatedModule.registerSensor(
56 sensorType,
57 config.interval === 'auto' ? -1 : config.interval,
58 config.iosReferenceFrame,
59 eventHandler
60 );
61 return this.sensorId !== -1;
62 }
63
64 isRunning() {
65 return this.sensorId !== -1 && this.sensorId !== null;
66 }
67
68 isAvailable() {
69 return this.sensorId !== -1;
70 }
71
72 getSharedValue() {
73 return this.data;
74 }
75
76 unregister() {
77 if (this.sensorId !== null && this.sensorId !== -1) {
78 NativeReanimatedModule.unregisterSensor(this.sensorId);
79 }
80 this.sensorId = null;
81 }
82}