UNPKG

1.75 kBPlain TextView Raw
1'use strict';
2import type {
3 SensorType,
4 SensorConfig,
5 Value3D,
6 ValueRotation,
7 ShareableRef,
8 SharedValue,
9} from './commonTypes';
10import Sensor from './Sensor';
11
12export class SensorContainer {
13 private nativeSensors: Map<number, Sensor> = new Map();
14
15 getSensorId(sensorType: SensorType, config: SensorConfig) {
16 return (
17 sensorType * 100 +
18 config.iosReferenceFrame * 10 +
19 Number(config.adjustToInterfaceOrientation)
20 );
21 }
22
23 initializeSensor(
24 sensorType: SensorType,
25 config: SensorConfig
26 ): SharedValue<Value3D | ValueRotation> {
27 const sensorId = this.getSensorId(sensorType, config);
28
29 if (!this.nativeSensors.has(sensorId)) {
30 const newSensor = new Sensor(sensorType, config);
31 this.nativeSensors.set(sensorId, newSensor);
32 }
33
34 const sensor = this.nativeSensors.get(sensorId);
35 return sensor!.getSharedValue();
36 }
37
38 registerSensor(
39 sensorType: SensorType,
40 config: SensorConfig,
41 handler: ShareableRef<(data: Value3D | ValueRotation) => void>
42 ): number {
43 const sensorId = this.getSensorId(sensorType, config);
44
45 if (!this.nativeSensors.has(sensorId)) {
46 return -1;
47 }
48
49 const sensor = this.nativeSensors.get(sensorId);
50 if (
51 sensor &&
52 sensor.isAvailable() &&
53 (sensor.isRunning() || sensor.register(handler))
54 ) {
55 sensor.listenersNumber++;
56 return sensorId;
57 }
58 return -1;
59 }
60
61 unregisterSensor(sensorId: number) {
62 if (this.nativeSensors.has(sensorId)) {
63 const sensor = this.nativeSensors.get(sensorId);
64 if (sensor && sensor.isRunning()) {
65 sensor.listenersNumber--;
66 if (sensor.listenersNumber === 0) {
67 sensor.unregister();
68 }
69 }
70 }
71 }
72}