Release 4.0.0-preview1-00213
[platform/core/csapi/tizenfx.git] / src / Tizen.Network.IoTConnectivity / Tizen.Network.IoTConnectivity / IoTConnectivityServerManager.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 using System.Collections.Generic;
19
20 namespace Tizen.Network.IoTConnectivity
21 {
22     /// <summary>
23     /// IoT connectivity server manager consists of server side APIs.
24     /// </summary>
25     /// <since_tizen> 3 </since_tizen>
26     public static class IoTConnectivityServerManager
27     {
28         private static int s_requestId = 1;
29         private static Dictionary<IntPtr, Interop.IoTConnectivity.Server.Resource.RequestHandlerCallback> s_RequestHandlerCallbackMap = new Dictionary<IntPtr, Interop.IoTConnectivity.Server.Resource.RequestHandlerCallback>();
30
31         /// <summary>
32         /// Initializes IoTCon. Calls this API to start IoTCon.
33         /// </summary>
34         /// <since_tizen> 3 </since_tizen>
35         /// <remarks>
36         /// @a filePath point to a file for handling secure virtual resources.
37         /// The file that is CBOR(Concise Binary Object Representation)-format must already exist
38         /// in @a filePath. We recommend to use application-local file for @a filePath.
39         /// </remarks>
40         /// <privilege>
41         /// http://tizen.org/privilege/network.get \n
42         /// http://tizen.org/privilege/internet
43         /// </privilege>
44         /// <privlevel>public</privlevel>
45         /// <param name="filePath">The file path to point to storage for handling secure virtual resources.</param>
46         /// <feature>http://tizen.org/feature/iot.ocf</feature>
47         /// <post>
48         /// You must call Deinitialize() if IoTCon API is no longer needed.
49         /// </post>
50         /// <seealso cref="Deinitialize()"/>
51         /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
52         /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
53         /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have privilege to access</exception>
54         /// <code>
55         /// string filePath = "../../res/iotcon-test-svr-db-server.dat";
56         /// IoTConnectivityServerManager.Initialize(filePath);
57         /// </code>
58         public static void Initialize(string filePath)
59         {
60             int ret = Interop.IoTConnectivity.Client.IoTCon.Initialize(filePath);
61             if (ret != (int)IoTConnectivityError.None)
62             {
63                 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to initialize");
64                 throw IoTConnectivityErrorFactory.GetException(ret);
65             }
66         }
67
68         /// <summary>
69         /// Deinitializes IoTCon.
70         /// </summary>
71         /// <since_tizen> 3 </since_tizen>
72         /// <remarks>
73         /// This API must be called if IoTCon API is no longer needed.
74         /// </remarks>
75         /// <feature>http://tizen.org/feature/iot.ocf</feature>
76         /// <pre>
77         /// Initialize() should be called to initialize.
78         /// </pre>
79         /// <seealso cref="Initialize(string)"/>
80         /// <code>
81         /// IoTConnectivityServerManager.Deinitialize();
82         /// </code>
83         public static void Deinitialize()
84         {
85             _resources.Clear();
86             s_requestId = 1;
87             s_RequestHandlerCallbackMap.Clear();
88
89             Interop.IoTConnectivity.Client.IoTCon.Deinitialize();
90         }
91
92         /// <summary>
93         /// Registers a resource in IoTCon server.
94         /// </summary>
95         /// <since_tizen> 3 </since_tizen>
96         /// <privilege>
97         /// http://tizen.org/privilege/internet
98         /// </privilege>
99         /// <privlevel>public</privlevel>
100         /// <param name="resource">The resource to register.</param>
101         /// <feature>http://tizen.org/feature/iot.ocf</feature>
102         /// <pre>
103         /// Initialize() should be called to initialize.
104         /// </pre>
105         /// <seealso cref="Resource"/>
106         /// <seealso cref="LiteResource"/>
107         /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
108         /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
109         /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
110         /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory.</exception>
111         /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have privilege to access.</exception>
112         /// <code>
113         /// ResourceTypes types = new ResourceTypes(new List<string>(){ "org.tizen.light" });
114         /// Attributes attributes = new Attributes { { "state", "ON" }};
115         /// Resource res = new LiteResource("/room/1", types, ResourcePolicy.Discoverable, attributes);
116         /// try {
117         ///     IoTConnectivityServerManager.RegisterResource(res);
118         /// } catch(Exception ex) {
119         ///     Console.Log("Exception caught : " + ex.Message);
120         /// }
121         /// </code>
122         public static void RegisterResource(Resource resource)
123         {
124             Log.Info(IoTConnectivityErrorFactory.LogTag, "...");
125
126             IntPtr id = IntPtr.Zero;
127             lock (s_RequestHandlerCallbackMap)
128             {
129                 id = (IntPtr)s_requestId++;
130             }
131
132             s_RequestHandlerCallbackMap[id] = (IntPtr r_resource, IntPtr request, IntPtr userData) =>
133             {
134                 int requestId = (int)userData;
135
136                 Log.Info(IoTConnectivityErrorFactory.LogTag, "Received s_RequestHandlerCallbackMap : " + requestId);
137
138                 if (request == IntPtr.Zero)
139                 {
140                     Log.Error(IoTConnectivityErrorFactory.LogTag, "request is IntPtr.Zero");
141                     return;
142                 }
143                 resource.OnRequest(r_resource, request, userData);
144             };
145
146             IntPtr handle = IntPtr.Zero;
147             int errorCode = Interop.IoTConnectivity.Server.Resource.Create(resource.UriPath, resource.Types._resourceTypeHandle, resource.Interfaces.ResourceInterfacesHandle, (int)resource.Policy, s_RequestHandlerCallbackMap[id], id, out handle);
148             if (errorCode != (int)IoTConnectivityError.None)
149             {
150                 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed create resource");
151                 lock (s_RequestHandlerCallbackMap)
152                 {
153                     s_RequestHandlerCallbackMap.Remove(id);
154                 }
155                 throw IoTConnectivityErrorFactory.GetException(errorCode);
156             }
157             else
158             {
159                 resource.ResourceHandle = handle;
160             }
161             _resources.Add(resource);
162         }
163
164         /// <summary>
165         /// Unregisters a resource in IoTCon server.
166         /// </summary>
167         /// <since_tizen> 3 </since_tizen>
168         /// <privilege>
169         /// http://tizen.org/privilege/internet
170         /// </privilege>
171         /// <privlevel>public</privlevel>
172         /// <param name="resource">The resource to unregister.</param>
173         /// <feature>http://tizen.org/feature/iot.ocf</feature>
174         /// <pre>
175         /// Initialize() should be called to initialize.
176         /// </pre>
177         /// <seealso cref="Resource"/>
178         /// <seealso cref="LiteResource"/>
179         /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
180         /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have privilege to access.</exception>
181         /// <code>
182         /// ResourceTypes types = new ResourceTypes(new List<string>(){ "org.tizen.light" });
183         /// Attributes attributes = new Attributes { { "state", "ON" }};
184         /// Resource res = new LiteResource("/room/1", types, ResourcePolicy.Discoverable, attributes);
185         /// IoTConnectivityServerManager.RegisterResource(res);
186         /// try {
187         ///     IoTConnectivityServerManager.UnregisterResource(res);
188         /// } catch(Exception ex) {
189         ///     Console.Log("Exception caught : " + ex.Message);
190         /// }
191         /// </code>
192         public static void UnregisterResource(Resource resource)
193         {
194             if (resource != null)
195             {
196                 if (resource.ResourceHandle != IntPtr.Zero)
197                 {
198                     Interop.IoTConnectivity.Server.Resource.Destroy(resource.ResourceHandle);
199                     resource.ResourceHandle = IntPtr.Zero;
200                 }
201
202                 _resources.Remove(resource);
203             }
204         }
205
206         /// <summary>
207         /// Starts presence of a server.
208         /// </summary>
209         /// <since_tizen> 3 </since_tizen>
210         /// <remarks>
211         /// Use this API to send server's announcements to clients.
212         /// Server can call this API when online for the first time or come back from offline to online.\n
213         /// If @a time is 0, server will set default value as 60 seconds.\n
214         /// If @a time is very big, server will set maximum value as (60 * 60 * 24) seconds, (24 hours).
215         /// </remarks>
216         /// <privilege>
217         /// http://tizen.org/privilege/internet
218         /// </privilege>
219         /// <privlevel>public</privlevel>
220         /// <param name="time">The interval of announcing presence in seconds.</param>
221         /// <feature>http://tizen.org/feature/iot.ocf</feature>
222         /// <pre>
223         /// Initialize() should be called to initialize.
224         /// </pre>
225         /// <seealso cref="IoTConnectivityClientManager.StartReceivingPresence(string, string)"/>
226         /// <seealso cref="IoTConnectivityClientManager.StopReceivingPresence(int)"/>
227         /// <seealso cref="IoTConnectivityClientManager.PresenceReceived"/>
228         /// <seealso cref="StopSendingPresence()"/>
229         /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
230         /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
231         /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have privilege to access.</exception>
232         /// <code>
233         /// try {
234         ///     IoTConnectivityServerManager.StartSendingPresence(120);
235         /// } catch(Exception ex) {
236         ///     Console.Log("Exception caught : " + ex.Message);
237         /// }
238         /// </code>
239         public static void StartSendingPresence(uint time)
240         {
241             int ret = Interop.IoTConnectivity.Server.IoTCon.StartPresence(time);
242             if (ret != (int)IoTConnectivityError.None)
243             {
244                 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to start presence");
245                 throw IoTConnectivityErrorFactory.GetException(ret);
246             }
247         }
248
249         /// <summary>
250         /// Stops presence of a server.
251         /// </summary>
252         /// <since_tizen> 3 </since_tizen>
253         /// <remarks>
254         /// Use this API to stop sending server's announcements to clients.
255         /// Server can call this API when terminating, entering to offline or out of network.
256         /// </remarks>
257         /// <privilege>
258         /// http://tizen.org/privilege/internet
259         /// </privilege>
260         /// <privlevel>public</privlevel>
261         /// <feature>http://tizen.org/feature/iot.ocf</feature>
262         /// <pre>
263         /// Initialize() should be called to initialize.
264         /// </pre>
265         /// <seealso cref="IoTConnectivityClientManager.StartReceivingPresence(string, string)"/>
266         /// <seealso cref="IoTConnectivityClientManager.StopReceivingPresence(int)"/>
267         /// <seealso cref="IoTConnectivityClientManager.PresenceReceived"/>
268         /// <seealso cref="StartSendingPresence(uint)"/>
269         /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
270         /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
271         /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have privilege to access.</exception>
272         /// <code>
273         /// IoTConnectivityServerManager.StopSendingPresence();
274         /// </code>
275         public static void StopSendingPresence()
276         {
277             int ret = Interop.IoTConnectivity.Server.IoTCon.StopPresence();
278             if (ret != (int)IoTConnectivityError.None)
279             {
280                 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed cancel presence");
281                 throw IoTConnectivityErrorFactory.GetException(ret);
282             }
283         }
284
285         /// <summary>
286         /// Sets the device name.
287         /// </summary>
288         /// <since_tizen> 3 </since_tizen>
289         /// <remarks>
290         /// This API sets the name of the local device (the device calling the API).\n
291         /// If the device name is set, clients can get the name using <see cref="IoTConnectivityClientManager.StartFindingDeviceInformation(string, ResourceQuery)"/>.
292         /// </remarks>
293         /// <param name="deviceName">The device name.</param>
294         /// <feature>http://tizen.org/feature/iot.ocf</feature>
295         /// <seealso cref="IoTConnectivityClientManager.DeviceInformationFound"/>
296         /// <seealso cref="IoTConnectivityClientManager.StartFindingDeviceInformation(string, ResourceQuery)"/>
297         /// <seealso cref="DeviceInformationFoundEventArgs"/>
298         /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
299         /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
300         /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have privilege to access.</exception>
301         /// <code>
302         /// IoTConnectivityServerManager.SetDeviceName("my-tizen");
303         /// </code>
304         public static void SetDeviceName(string deviceName)
305         {
306             int ret = Interop.IoTConnectivity.Server.IoTCon.SetDeviceName(deviceName);
307             if (ret != (int)IoTConnectivityError.None)
308             {
309                 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed set device name");
310                 throw IoTConnectivityErrorFactory.GetException(ret);
311             }
312         }
313         private static List<Resource> _resources = new List<Resource>();
314     }
315 }