2 * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 using System.Collections.Generic;
20 using System.Collections.ObjectModel;
21 using System.Runtime.InteropServices;
23 namespace Tizen.Network.IoTConnectivity
26 /// Abstract class respresenting a resource.
27 /// All resources need to inherit from this class.
29 public abstract class Resource : IDisposable
31 private IntPtr _resourceHandle = IntPtr.Zero;
32 private bool _disposed = false;
33 private ObservableCollection<Resource> _children = new ObservableCollection<Resource>();
34 private IntPtr _observerHandle = IntPtr.Zero;
40 /// @a uri format would be relative URI path like '/a/light'
41 /// and its length must be less than 128.
44 /// http://tizen.org/privilege/internet
46 /// <param name="uri">The URI path of the resource</param>
47 /// <param name="types">Resource types</param>
48 /// <param name="interfaces">Resource interfaces</param>
49 /// <param name="policy">The policies of the resoruce</param>
51 /// IoTConnectivityServerManager.Initialize() should be called to initialize
53 /// <seealso cref="ResourceTypes"/>
54 /// <seealso cref="ResourceInterfaces"/>
55 /// <seealso cref="ResourcePolicy"/>
56 /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported</exception>
57 /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory</exception>
59 /// // Create a class which inherits from Resource
60 /// public class DoorResource : Resource
62 /// public DoorResource(string uri, ResourceTypes types, ResourceInterfaces interfaces, ResourcePolicy policy)
63 /// : base(uri, types, interfaces, policy) {
65 /// protected override Response OnDelete(Request request) {
68 /// protected override Response OnGet(Request request) {
71 /// // Override other abstract methods of Resource class
74 /// // Use it like below
75 /// ResourceInterfaces ifaces = new ResourceInterfaces(new List<string>(){ ResourceInterfaces.DefaultInterface });
76 /// ResourceTypes types = new ResourceTypes(new List<string>(){ "oic.iot.door.new" });
77 /// Resource resource = new DoorResource("/door/uri1", types, ifaces, ResourcePolicy.Discoverable | ResourcePolicy.Observable);
79 protected Resource(string uri, ResourceTypes types, ResourceInterfaces interfaces, ResourcePolicy policy)
83 Interfaces = interfaces;
86 _children.CollectionChanged += ChildrenCollectionChanged;
88 int ret = Interop.IoTConnectivity.Server.Observers.Create(out _observerHandle);
89 if (ret != (int)IoTConnectivityError.None)
91 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to create obsever handle");
92 throw IoTConnectivityErrorFactory.GetException(ret);
97 /// Destructor of the Resource class.
105 /// Type details of the resource
107 public ResourceTypes Types { get; internal set; }
110 /// Interface details of the resource
112 public ResourceInterfaces Interfaces { get; internal set; }
115 /// The policies of the resource
117 public ResourcePolicy Policy { get; internal set; }
120 /// URI path of the resource
122 public string UriPath { get; internal set; }
125 /// List of Child resources
127 public ICollection<Resource> Children
135 internal IntPtr ResourceHandle
139 return _resourceHandle;
143 _resourceHandle = value;
148 /// Notify the specified representation and qos.
151 /// http://tizen.org/privilege/internet
153 /// <param name="representation">Representation.</param>
154 /// <param name="qos">The quality of service for message transfer.</param>
156 /// IoTConnectivityServerManager.Initialize() should be called to initialize
158 /// <seealso cref="Representation"/>
159 /// <seealso cref="QualityOfService"/>
160 /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported</exception>
161 /// <exception cref="UnauthorizedAccessException">Thrown when app does not have privilege to access</exception>
162 /// <exception cref="InvalidOperationException">Thrown when the operation is invalid</exception>
164 /// ResourceInterfaces ifaces = new ResourceInterfaces(new List<string>(){ ResourceInterfaces.DefaultInterface });
165 /// ResourceTypes types = new ResourceTypes(new List<string>(){ "oic.iot.door.new.notify" });
166 /// Resource resource = new DoorResource("/door/uri/new/notify", types, ifaces, ResourcePolicy.Discoverable | ResourcePolicy.Observable);
167 /// IoTConnectivityServerManager.RegisterResource(resource);
169 /// Representation repr = new Representation();
170 /// repr.UriPath = "/door/uri/new/notify";
171 /// repr.Type = new ResourceTypes(new List<string>(){ "oic.iot.door.new.notify" });
172 /// repr.Attributes = new Attributes() {
175 /// resource.Notify(repr, QualityOfService.High);
177 public void Notify(Representation representation, QualityOfService qos)
179 int ret = (int)IoTConnectivityError.None;
180 ret = Interop.IoTConnectivity.Server.Resource.Notify(_resourceHandle, representation._representationHandle, _observerHandle, (int)qos);
181 if (ret != (int)IoTConnectivityError.None)
183 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to send notification");
184 throw IoTConnectivityErrorFactory.GetException(ret);
189 /// This is Called when the client performs get operation on this resource.
191 /// <param name="request">A request from client</param>
192 /// <returns>A response having the representation and the result</returns>
193 protected abstract Response OnGet(Request request);
196 /// This is Called when the client performs put operation on this resource.
198 /// <param name="request">A request from client</param>
199 /// <returns>A response</returns>
200 protected abstract Response OnPut(Request request);
203 /// This is Called when the client performs post operation on this resource.
205 /// <param name="request">A request from client</param>
206 /// <returns>A response having the representation and the result</returns>
207 protected abstract Response OnPost(Request request);
210 /// This is Called when the client performs delete operation on this resource.
212 /// <param name="request">A request from client</param>
213 /// <returns>A response</returns>
214 protected abstract Response OnDelete(Request request);
217 /// Called on the observing event.
219 /// <param name="request">A request from client</param>
220 /// <param name="type">Observer type</param>
221 /// <param name="observeId">Observe identifier.</param>
222 /// <returns>Returns true if it wants to be observed, else false.</returns>
223 protected abstract bool OnObserving(Request request, ObserveType type, int observeId);
226 /// Releases any unmanaged resources used by this object.
228 public void Dispose()
231 GC.SuppressFinalize(this);
235 /// Releases any unmanaged resources used by this object. Can also dispose any other disposable objects.
237 /// <param name="disposing">If true, disposes any disposable objects. If false, does not dispose disposable objects.</param>
238 protected virtual void Dispose(bool disposing)
246 Interfaces?.Dispose();
249 if (_resourceHandle != IntPtr.Zero)
250 Interop.IoTConnectivity.Server.Resource.Destroy(_resourceHandle);
251 if (_observerHandle != IntPtr.Zero)
252 Interop.IoTConnectivity.Server.Observers.Destroy(_observerHandle);
256 // This method is used as callback for Resource
257 internal void OnRequest(IntPtr resourceHandle, IntPtr requestHandle, IntPtr userData)
259 Request request = GetRequest(requestHandle);
260 Response response = null;
264 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get Request");
271 int ret = Interop.IoTConnectivity.Server.Request.GetObserveType(requestHandle, out observeType);
272 if (ret != (int)IoTConnectivityError.None)
274 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to Get observe type");
277 if ((ObserveType)observeType != ObserveType.NoType)
280 ret = Interop.IoTConnectivity.Server.Request.GetObserveId(requestHandle, out observeId);
281 if (ret != (int)IoTConnectivityError.None)
283 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to Get observe id");
286 switch ((ObserveType)observeType)
288 case ObserveType.Register:
290 if (OnObserving(request, ObserveType.Register, observeId))
292 ret = Interop.IoTConnectivity.Server.Observers.Add(_observerHandle, observeId);
293 if (ret != (int)IoTConnectivityError.None)
295 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add observer id");
302 // If OnObserving for ObserveType.Register returns false, do not operate for Get operation after Observe operation.
306 case ObserveType.Deregister:
308 if (OnObserving(request, ObserveType.Deregister, observeId))
310 ret = Interop.IoTConnectivity.Server.Observers.Remove(_observerHandle, observeId);
311 if (ret != (int)IoTConnectivityError.None)
313 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to remove observer id");
320 // If OnObserving for ObserveType.Deregister returns false, do not operate for Get operation after Observe operation.
327 ret = Interop.IoTConnectivity.Server.Request.GetRequestType(requestHandle, out requestType);
328 if (ret != (int)IoTConnectivityError.None)
330 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to Get request type");
333 switch ((Interop.IoTConnectivity.Server.RequestType)requestType)
335 case Interop.IoTConnectivity.Server.RequestType.Put:
337 response = OnPut(request);
340 case Interop.IoTConnectivity.Server.RequestType.Get:
342 response = OnGet(request);
345 case Interop.IoTConnectivity.Server.RequestType.Post:
347 response = OnPost(request);
350 case Interop.IoTConnectivity.Server.RequestType.Delete:
352 response = OnDelete(request);
358 if (response == null)
360 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to send Response");
364 if (!response.Send(requestHandle))
366 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to send Response");
377 private Request GetRequest(IntPtr requestHandle)
379 IntPtr hostAddressPtr;
380 int ret = Interop.IoTConnectivity.Server.Request.GetHostAddress(requestHandle, out hostAddressPtr);
381 if (ret != (int)IoTConnectivityError.None)
383 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to Get host address");
387 IntPtr optionsHandle = IntPtr.Zero;
388 ret = Interop.IoTConnectivity.Server.Request.GetOptions(requestHandle, out optionsHandle);
389 if (ret != (int)IoTConnectivityError.None)
391 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to Get options");
395 IntPtr queryHandle = IntPtr.Zero;
396 ret = Interop.IoTConnectivity.Server.Request.GetQuery(requestHandle, out queryHandle);
397 if (ret != (int)IoTConnectivityError.None)
399 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to Get Query");
403 IntPtr representationHandle = IntPtr.Zero;
404 ret = Interop.IoTConnectivity.Server.Request.GetRepresentation(requestHandle, out representationHandle);
405 if (ret != (int)IoTConnectivityError.None)
407 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to Get representation");
411 ResourceOptions opts = null;
412 ResourceQuery query = null;
413 Representation representation = null;
416 opts = (optionsHandle == IntPtr.Zero) ? null : new ResourceOptions(optionsHandle);
418 catch (Exception exp)
420 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to new ResourceOptions: " + exp.Message);
426 query = (queryHandle == IntPtr.Zero) ? null : new ResourceQuery(queryHandle);
428 catch (Exception exp)
430 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to new ResourceQuery: " + exp.Message);
437 representation = (representationHandle == IntPtr.Zero) ? null : new Representation(representationHandle);
439 catch (Exception exp)
441 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to new Representation: " + exp.Message);
449 HostAddress = (hostAddressPtr != IntPtr.Zero) ? Marshal.PtrToStringAnsi(hostAddressPtr) : string.Empty,
452 Representation = representation
456 private void ChildrenCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs eventArgs)
458 if (eventArgs.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
460 foreach (Resource r in eventArgs.NewItems)
462 int ret = Interop.IoTConnectivity.Server.Resource.BindChildResource(_resourceHandle, r._resourceHandle);
463 if (ret != (int)IoTConnectivityError.None)
465 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to bind resource ");
466 throw IoTConnectivityErrorFactory.GetException(ret);
470 else if (eventArgs.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
472 foreach (Resource r in eventArgs.NewItems)
474 int ret = Interop.IoTConnectivity.Server.Resource.UnbindChildResource(_resourceHandle, r._resourceHandle);
475 if (ret != (int)IoTConnectivityError.None)
477 Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to unbind resource");
478 throw IoTConnectivityErrorFactory.GetException(ret);