1 | import { throttle } from '../../utils';
|
2 | import { CallbackManager, MethodHandler } from '../../utils/handler';
|
3 | const callbackManager = new CallbackManager();
|
4 | let deviceMotionListener;
|
5 | const INTERVAL_MAP = {
|
6 | game: {
|
7 | interval: 20,
|
8 | frequency: 50
|
9 | },
|
10 | ui: {
|
11 | interval: 60,
|
12 | frequency: 16.67
|
13 | },
|
14 | normal: {
|
15 | interval: 200,
|
16 | frequency: 5
|
17 | }
|
18 | };
|
19 |
|
20 |
|
21 |
|
22 | export const stopDeviceMotionListening = ({ success, fail, complete } = {}) => {
|
23 | const handle = new MethodHandler({ name: 'stopDeviceMotionListening', success, fail, complete });
|
24 | try {
|
25 | window.removeEventListener('deviceorientation', deviceMotionListener, true);
|
26 | return handle.success();
|
27 | }
|
28 | catch (e) {
|
29 | return handle.fail({ errMsg: e.message });
|
30 | }
|
31 | };
|
32 |
|
33 |
|
34 |
|
35 | export const startDeviceMotionListening = ({ interval = 'normal', success, fail, complete } = {}) => {
|
36 | const handle = new MethodHandler({ name: 'startDeviceMotionListening', success, fail, complete });
|
37 | try {
|
38 | const intervalObj = INTERVAL_MAP[interval];
|
39 | if (window.DeviceOrientationEvent) {
|
40 | if (deviceMotionListener) {
|
41 | stopDeviceMotionListening();
|
42 | }
|
43 | deviceMotionListener = throttle((evt) => {
|
44 | callbackManager.trigger({
|
45 | alpha: evt.alpha,
|
46 | beta: evt.beta,
|
47 | gamma: evt.gamma
|
48 | });
|
49 | }, intervalObj.interval);
|
50 | window.addEventListener('deviceorientation', deviceMotionListener, true);
|
51 | }
|
52 | else {
|
53 | throw new Error('deviceMotion is not supported');
|
54 | }
|
55 | return handle.success();
|
56 | }
|
57 | catch (e) {
|
58 | return handle.fail({ errMsg: e.message });
|
59 | }
|
60 | };
|
61 |
|
62 |
|
63 |
|
64 | export const onDeviceMotionChange = callback => {
|
65 | callbackManager.add(callback);
|
66 | };
|
67 |
|
68 |
|
69 |
|
70 | export const offDeviceMotionChange = callback => {
|
71 | callbackManager.remove(callback);
|
72 | };
|