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