csapi-sensor: fix bug about the lifetime of delegate
[platform/core/csapi/tizenfx.git] / src / Tizen.Sensor / Tizen.Sensor / Plugins / GravitySensor.cs
1 /*
2  * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the License);
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an AS IS BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 using System;
18
19 namespace Tizen.Sensor
20 {
21     /// <summary>
22     /// GravitySensor Class. Used for registering callbacks for gravity sensor and getting gravity data
23     /// </summary>
24     public sealed class GravitySensor : Sensor
25     {
26         private const string GravitySensorKey = "http://tizen.org/feature/sensor.gravity";
27
28         private event EventHandler<SensorAccuracyChangedEventArgs> _accuracyChanged;
29         /// <summary>
30         /// Gets the X component of the gravity.
31         /// </summary>
32         public float X { get; private set; } = float.MinValue;
33
34         /// <summary>
35         /// Gets the Y component of the gravity.
36         /// </summary>
37         public float Y { get; private set; } = float.MinValue;
38
39         /// <summary>
40         /// Gets the Z component of the gravity.
41         /// </summary>
42         public float Z { get; private set; } = float.MinValue;
43
44         /// <summary>
45         /// Returns true or false based on whether gravity sensor is supported by device.
46         /// </summary>
47         public static bool IsSupported
48         {
49             get
50             {
51                 Log.Info(Globals.LogTag, "Checking if the GravitySensor is supported");
52                 return CheckIfSupported(SensorType.GravitySensor, GravitySensorKey);
53             }
54         }
55
56         /// <summary>
57         /// Returns the number of gravity sensors available on the device.
58         /// </summary>
59         public static int Count
60         {
61             get
62             {
63                 Log.Info(Globals.LogTag, "Getting the count of gravity sensors");
64                 return GetCount();
65             }
66         }
67
68         /// <summary>
69         /// Initializes a new instance of the <see cref="Tizen.Sensor.GravitySensor"/> class.
70         /// </summary>
71         /// <exception cref="ArgumentException">Thrown when an invalid argument is used</exception>
72         /// <exception cref="NotSupportedException">Thrown when the sensor is not supported</exception>
73         /// <exception cref="InvalidOperationException">Thrown when the operation is invalid for the current state</exception>
74         /// <param name='index'>
75         /// Index. Default value for this is 0. Index refers to a particular gravity sensor in case of multiple sensors
76         /// </param>
77         public GravitySensor (uint index = 0) : base(index)
78         {
79             Log.Info(Globals.LogTag, "Creating GravitySensor object");
80         }
81
82         internal override SensorType GetSensorType()
83         {
84             return SensorType.GravitySensor;
85         }
86
87         /// <summary>
88         /// Event Handler for storing the callback functions for event corresponding to change in gravity sensor data.
89         /// </summary>
90
91         public event EventHandler<GravitySensorDataUpdatedEventArgs> DataUpdated;
92
93         /// <summary>
94         /// Event handler for accuracy changed events.
95         /// </summary>
96         public event EventHandler<SensorAccuracyChangedEventArgs> AccuracyChanged
97         {
98             add
99             {
100                 if (_accuracyChanged == null)
101                 {
102                     AccuracyListenStart();
103                 }
104                 _accuracyChanged += value;
105             }
106             remove
107             {
108                 _accuracyChanged -= value;
109                 if (_accuracyChanged == null)
110                 {
111                     AccuracyListenStop();
112                 }
113             }
114         }
115
116         private static int GetCount()
117         {
118             IntPtr list;
119             int count;
120             int error = Interop.SensorManager.GetSensorList(SensorType.GravitySensor, out list, out count);
121             if (error != (int)SensorError.None)
122             {
123                 Log.Error(Globals.LogTag, "Error getting sensor list for gravity");
124                 count = 0;
125             }
126             else
127                 Interop.Libc.Free(list);
128             return count;
129         }
130
131         private static Interop.SensorListener.SensorEventCallback _callback;
132
133         internal override void EventListenStart()
134         {
135             _callback = (IntPtr sensorHandle, IntPtr eventPtr, IntPtr data) => {
136                 Interop.SensorEventStruct sensorData = Interop.IntPtrToEventStruct(eventPtr);
137
138                 TimeSpan = new TimeSpan((Int64)sensorData.timestamp);
139                 X = sensorData.values[0];
140                 Y = sensorData.values[1];
141                 Z = sensorData.values[2];
142
143                 DataUpdated?.Invoke(this, new GravitySensorDataUpdatedEventArgs(sensorData.values));
144             };
145
146             int error = Interop.SensorListener.SetEventCallback(ListenerHandle, Interval, _callback, IntPtr.Zero);
147             if (error != (int)SensorError.None)
148             {
149                 Log.Error(Globals.LogTag, "Error setting event callback for gravity sensor");
150                 throw SensorErrorFactory.CheckAndThrowException(error, "Unable to set event callback for gravity");
151             }
152         }
153
154         internal override void EventListenStop()
155         {
156             int error = Interop.SensorListener.UnsetEventCallback(ListenerHandle);
157             if (error != (int)SensorError.None)
158             {
159                 Log.Error(Globals.LogTag, "Error unsetting event callback for gravity sensor");
160                 throw SensorErrorFactory.CheckAndThrowException(error, "Unable to unset event callback for gravity");
161             }
162         }
163
164         private static Interop.SensorListener.SensorAccuracyCallback _accuracyCallback;
165
166         private void AccuracyListenStart()
167         {
168             _accuracyCallback = (IntPtr sensorHandle, UInt64 timestamp, SensorDataAccuracy accuracy, IntPtr data) => {
169                 TimeSpan = new TimeSpan((Int64)timestamp);
170                 _accuracyChanged?.Invoke(this, new SensorAccuracyChangedEventArgs(new TimeSpan((Int64)timestamp), accuracy));
171             };
172
173             int error = Interop.SensorListener.SetAccuracyCallback(ListenerHandle, _accuracyCallback, IntPtr.Zero);
174             if (error != (int)SensorError.None)
175             {
176                 Log.Error(Globals.LogTag, "Error setting accuracy event callback for gravity sensor");
177                 throw SensorErrorFactory.CheckAndThrowException(error, "Unable to set accuracy event callback for gravity");
178             }
179         }
180
181         private void AccuracyListenStop()
182         {
183             int error = Interop.SensorListener.UnsetAccuracyCallback(ListenerHandle);
184             if (error != (int)SensorError.None)
185             {
186                 Log.Error(Globals.LogTag, "Error unsetting accuracy event callback for gravity sensor");
187                 throw SensorErrorFactory.CheckAndThrowException(error, "Unable to unset accuracy event callback for gravity");
188             }
189         }
190     }
191 }