--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+ internal static partial class IoTConnectivity
+ {
+ internal static partial class Client
+ {
+ internal static partial class DeviceInformation
+ {
+ internal delegate bool DeviceInformationCallback(IntPtr deviceInfoHandle, int result, IntPtr userData);
+
+ internal enum Property
+ {
+ Name = 0,
+ SpecVersion,
+ Id,
+ DataModelVersion,
+ }
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_find_device_info")]
+ internal static extern int Find(string hostAddress, int connectivityType, IntPtr query, DeviceInformationCallback cb, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_device_info_get_property")]
+ internal static extern int GetProperty(IntPtr deviceInfoHandle, int property, out IntPtr value);
+ }
+
+ internal static partial class PlatformInformation
+ {
+ internal delegate bool PlatformInformationCallback(IntPtr platformInfoHandle, int result, IntPtr userData);
+
+ internal enum Propery
+ {
+ Id = 0,
+ MfgName,
+ MfgUrl,
+ ModelNumber,
+ DateOfMfg,
+ PlatformVer,
+ OsVer,
+ HardwareVer,
+ FirmwareVer,
+ SupportUrl,
+ SystemTime
+ }
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_find_platform_info")]
+ internal static extern int Find(string hostAddress, int connectivityType, IntPtr query, PlatformInformationCallback cb, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_platform_info_get_property")]
+ internal static extern int GetProperty(IntPtr platformInfoHandle, int property, out IntPtr value);
+ }
+
+ internal static partial class RemoteResource
+ {
+ [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
+ internal delegate void ResponseCallback(IntPtr resource, int err, int requestType, IntPtr response, IntPtr userData);
+
+ [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
+ internal delegate void ObserveCallback(IntPtr resource, int err, int sequenceNumber, IntPtr response, IntPtr userData);
+
+ [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
+ internal delegate void CachedRepresentationChangedCallback(IntPtr resource, IntPtr representation, IntPtr userData);
+
+ [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
+ internal delegate void StateChangedCallback(IntPtr resource, int state, IntPtr userData);
+
+ internal enum ConnectivityType
+ {
+ None = -1,
+ All,
+ Ip,
+ Ipv4,
+ Ipv6
+ }
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_remote_resource_create")]
+ internal static extern int Create(string hostAddress, int connectivityType, string uriPath, int properties, IntPtr resourceTypes, IntPtr resourceInterfaces, out IntPtr remoteResource);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_remote_resource_destroy")]
+ internal static extern void Destroy(IntPtr resource);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_remote_resource_clone")]
+ internal static extern int Clone(IntPtr src, out IntPtr dest);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_remote_resource_observe_register")]
+ internal static extern int RegisterObserve(IntPtr resource, int observePolicy, IntPtr query, ObserveCallback cb, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_remote_resource_observe_deregister")]
+ internal static extern int DeregisterObserve(IntPtr resource);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_remote_resource_get")]
+ internal static extern int Get(IntPtr resource, IntPtr query, ResponseCallback cb, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_remote_resource_put")]
+ internal static extern int Put(IntPtr resource, IntPtr repr, IntPtr query, ResponseCallback cb, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_remote_resource_post")]
+ internal static extern int Post(IntPtr resource, IntPtr repr, IntPtr query, ResponseCallback cb, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_remote_resource_delete")]
+ internal static extern int Delete(IntPtr resource, ResponseCallback cb, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_remote_resource_start_caching")]
+ internal static extern int StartCaching(IntPtr resource, CachedRepresentationChangedCallback cb, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_remote_resource_stop_caching")]
+ internal static extern int StopCaching(IntPtr resource);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_remote_resource_start_monitoring")]
+ internal static extern int StartMonitoring(IntPtr resource, StateChangedCallback cb, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_remote_resource_stop_monitoring")]
+ internal static extern int StopMonitoring(IntPtr resource);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_remote_resource_get_uri_path")]
+ internal static extern int GetUriPath(IntPtr resource, out IntPtr uriPath);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_remote_resource_get_connectivity_type")]
+ internal static extern int GetConnectivityType(IntPtr resource, out int connectivityType);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_remote_resource_get_host_address")]
+ internal static extern int GetHostAddress(IntPtr resource, out IntPtr hostAddress);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_remote_resource_get_device_id")]
+ internal static extern int GetDeviceId(IntPtr resource, out IntPtr deviceId);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_remote_resource_get_types")]
+ internal static extern int GetTypes(IntPtr resource, out IntPtr types);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_remote_resource_get_interfaces")]
+ internal static extern int GetInterfaces(IntPtr resource, out IntPtr ifaces);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_remote_resource_get_policies")]
+ internal static extern int GetPolicies(IntPtr resource, out int properties);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_remote_resource_get_options")]
+ internal static extern int GetOptions(IntPtr resource, out IntPtr options);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_remote_resource_set_options")]
+ internal static extern int SetOptions(IntPtr resource, IntPtr options);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_remote_resource_get_cached_representation")]
+ internal static extern int GetCachedRepresentation(IntPtr resource, out IntPtr representation);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_remote_resource_get_checking_interval")]
+ internal static extern int GetTimeInterval(IntPtr resource, out int timeInterval);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_remote_resource_set_checking_interval")]
+ internal static extern int SetTimeInterval(IntPtr resource, int timeInterval);
+ }
+
+ internal static partial class IoTCon
+ {
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_initialize")]
+ internal static extern int Initialize(string filePath);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_deinitialize")]
+ internal static extern void Deinitialize();
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_get_timeout")]
+ internal static extern int GetTimeout(out int timeoutSeconds);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_set_timeout")]
+ internal static extern int SetTimeout(int timeoutSeconds);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_polling_get_interval")]
+ internal static extern int GetPollingInterval(out int interval);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_polling_set_interval")]
+ internal static extern int SetPollingInterval(int interval);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_polling_invoke")]
+ internal static extern int InvokePolling();
+ }
+
+ internal static partial class ResourceFinder
+ {
+ [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
+ internal delegate bool FoundResourceCallback(IntPtr remoteResourceHandle, int result, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_find_resource")]
+ internal static extern int AddResourceFoundCb(string hostAddress, int connectivityType, IntPtr query, FoundResourceCallback cb, IntPtr userData);
+ }
+
+ internal static partial class Presence
+ {
+ [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
+ internal delegate void PresenceCallback(IntPtr presenceResponseHandle, int err, IntPtr response, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_add_presence_cb")]
+ internal static extern int AddPresenceCb(string hostAddress, int connectivityType, string resourceType, PresenceCallback cb, IntPtr userData, out IntPtr presenceHandle);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_remove_presence_cb")]
+ internal static extern int RemovePresenceCb(IntPtr presenceHandle);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_presence_get_host_address")]
+ internal static extern int GetHostAddress(IntPtr presence, out IntPtr hostAddress);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_presence_get_connectivity_type")]
+ internal static extern int GetConnectivityType(IntPtr presence, out int connectivityType);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_presence_get_resource_type")]
+ internal static extern int GetResourceType(IntPtr presence, out IntPtr resourceType);
+ }
+
+ internal static partial class PresenceResponse
+ {
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_presence_response_get_result")]
+ internal static extern int GetResult(IntPtr response, out int result);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_presence_response_get_trigger")]
+ internal static extern int GetTrigger(IntPtr response, out int trigger);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_presence_response_get_host_address")]
+ internal static extern int GetHostAddress(IntPtr response, out IntPtr hostAddress);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_presence_response_get_connectivity_type")]
+ internal static extern int GetConnectivityType(IntPtr response, out int connectivityType);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_presence_response_get_resource_type")]
+ internal static extern int GetResourceType(IntPtr response, out IntPtr resourceType);
+ }
+ }
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+ internal static partial class IoTConnectivity
+ {
+ internal static partial class Common
+ {
+ internal enum DataType
+ {
+ None = 0,
+ Int,
+ Bool,
+ Double,
+ String,
+ ByteStr,
+ Null,
+ List,
+ Attributes
+ }
+
+ internal static partial class ResourceTypes
+ {
+ [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
+ internal delegate bool ForeachCallback(string type, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_resource_types_create")]
+ internal static extern int Create(out IntPtr types);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_resource_types_destroy")]
+ internal static extern void Destroy(IntPtr types);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_resource_types_add")]
+ internal static extern int Add(IntPtr types, string type);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_resource_types_remove")]
+ internal static extern int Remove(IntPtr types, string type);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_resource_types_foreach")]
+ internal static extern int Foreach(IntPtr types, ForeachCallback cb, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_resource_types_clone")]
+ internal static extern int Clone(IntPtr src, out IntPtr dest);
+ }
+
+ internal static partial class ResourceInterfaces
+ {
+ [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
+ internal delegate bool ForeachCallback(string iface, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_resource_interfaces_create")]
+ internal static extern int Create(out IntPtr ifaces);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_resource_interfaces_destroy")]
+ internal static extern void Destroy(IntPtr ifaces);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_resource_interfaces_add")]
+ internal static extern int Add(IntPtr ifaces, string iface);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_resource_interfaces_remove")]
+ internal static extern int Remove(IntPtr ifaces, string iface);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_resource_interfaces_foreach")]
+ internal static extern int Foreach(IntPtr ifaces, ForeachCallback cb, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_resource_interfaces_clone")]
+ internal static extern int Clone(IntPtr src, out IntPtr dest);
+ }
+
+ internal static partial class Attributes
+ {
+ internal delegate bool AttributesCallback(IntPtr attributes, string key, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_attributes_create")]
+ internal static extern int Create(out IntPtr attributes);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_attributes_destroy")]
+ internal static extern void Destroy(IntPtr attributes);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_attributes_clone")]
+ internal static extern int Clone(IntPtr attributes, out IntPtr attributes_clone);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_attributes_add_int")]
+ internal static extern int AddInt(IntPtr attributes, string key, int val);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_attributes_add_bool")]
+ internal static extern int AddBool(IntPtr attributes, string key, bool val);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_attributes_add_double")]
+ internal static extern int AddDouble(IntPtr attributes, string key, double val);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_attributes_add_str")]
+ internal static extern int AddStr(IntPtr attributes, string key, string val);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_attributes_add_byte_str")]
+ internal static extern int AddByteStr(IntPtr attributes, string key, byte[] val, int len);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_attributes_add_list")]
+ internal static extern int AddList(IntPtr attributes, string key, IntPtr list);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_attributes_add_attributes")]
+ internal static extern int AddAttributes(IntPtr dest, string key, IntPtr src);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_attributes_add_null")]
+ internal static extern int AddNull(IntPtr attributes, string key);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_attributes_get_int")]
+ internal static extern int GetInt(IntPtr attributes, string key, out int val);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_attributes_get_bool")]
+ internal static extern int GetBool(IntPtr attributes, string key, out bool val);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_attributes_get_double")]
+ internal static extern int GetDouble(IntPtr attributes, string key, out double val);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_attributes_get_str")]
+ internal static extern int GetStr(IntPtr attributes, string key, out IntPtr val);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_attributes_get_byte_str")]
+ internal static extern int GetByteStr(IntPtr attributes, string key, out IntPtr value, out int size);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_attributes_get_list")]
+ internal static extern int GetList(IntPtr attributes, string key, out IntPtr list);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_attributes_get_attributes")]
+ internal static extern int GetAttributes(IntPtr src, string key, out IntPtr dest);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_attributes_is_null")]
+ internal static extern int IsNull(IntPtr attributes, string key, out bool isNull);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_attributes_remove")]
+ internal static extern int Remove(IntPtr attributes, string key);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_attributes_get_type")]
+ internal static extern int GetType(IntPtr attributes, string key, out DataType type);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_attributes_foreach")]
+ internal static extern int Foreach(IntPtr attributes, AttributesCallback cb, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_attributes_get_keys_count")]
+ internal static extern int GetKeysCount(IntPtr attributes, out int count);
+ }
+
+ internal static partial class Query
+ {
+ internal delegate bool QueryCallback(string key, string value, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_query_create")]
+ internal static extern int Create(out IntPtr query);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_query_destroy")]
+ internal static extern void Destroy(IntPtr query);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_query_get_resource_type")]
+ internal static extern int GetResourceType(IntPtr query, out IntPtr resourceType);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_query_get_interface")]
+ internal static extern int GetInterface(IntPtr query, out IntPtr resourceInterface);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_query_set_resource_type")]
+ internal static extern int SetResourceType(IntPtr query, string resourceType);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_query_set_interface")]
+ internal static extern int SetInterface(IntPtr query, string resourceInterface);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_query_add")]
+ internal static extern int Add(IntPtr query, string key, string value);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_query_remove")]
+ internal static extern int Remove(IntPtr query, string key);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_query_lookup")]
+ internal static extern int Lookup(IntPtr query, string key, out IntPtr data);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_query_foreach")]
+ internal static extern int Foreach(IntPtr query, QueryCallback cb, IntPtr userData);
+ }
+
+ internal static partial class Representation
+ {
+ internal delegate bool RepresentationChildrenCallback(IntPtr child, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_representation_create")]
+ internal static extern int Create(out IntPtr repr);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_representation_destroy")]
+ internal static extern void Destroy(IntPtr repr);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_representation_clone")]
+ internal static extern int Clone(IntPtr src, out IntPtr dest);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_representation_set_uri_path")]
+ internal static extern int SetUriPath(IntPtr repr, string uriPath);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_representation_get_uri_path")]
+ internal static extern int GetUriPath(IntPtr repr, out IntPtr uriPath);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_representation_set_resource_types")]
+ internal static extern int SetResourceTypes(IntPtr repr, IntPtr types);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_representation_get_resource_types")]
+ internal static extern int GetResourceTypes(IntPtr repr, out IntPtr types);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_representation_set_resource_interfaces")]
+ internal static extern int SetResourceInterfaces(IntPtr repr, IntPtr ifaces);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_representation_get_resource_interfaces")]
+ internal static extern int GetResourceInterfaces(IntPtr repr, out IntPtr ifaces);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_representation_set_attributes")]
+ internal static extern int SetAttributes(IntPtr repr, IntPtr attribs);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_representation_get_attributes")]
+ internal static extern int GetAttributes(IntPtr repr, out IntPtr attribs);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_representation_add_child")]
+ internal static extern int AddChild(IntPtr parent, IntPtr child);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_representation_remove_child")]
+ internal static extern int RemoveChild(IntPtr parent, IntPtr child);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_representation_foreach_children")]
+ internal static extern int ForeachChildren(IntPtr parent, RepresentationChildrenCallback cb, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_representation_get_children_count")]
+ internal static extern int GetChildrenCount(IntPtr parent, out int count);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_representation_get_nth_child")]
+ internal static extern int GetNthChild(IntPtr parent, int pos, out IntPtr child);
+ }
+
+ internal static partial class Options
+ {
+ internal delegate bool OptionsCallback(ushort id, string data, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_options_create")]
+ internal static extern int Create(out IntPtr options);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_options_destroy")]
+ internal static extern void Destroy(IntPtr options);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_options_add")]
+ internal static extern int Add(IntPtr options, ushort id, string data);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_options_remove")]
+ internal static extern int Remove(IntPtr options, ushort id);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_options_lookup")]
+ internal static extern int Lookup(IntPtr options, ushort id, out IntPtr data);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_options_foreach")]
+ internal static extern int ForEach(IntPtr options, OptionsCallback cb, IntPtr userData);
+ }
+
+ internal static partial class List
+ {
+ internal delegate bool IntCallback(int pos, int value, IntPtr userData);
+
+ internal delegate bool BoolCallback(int pos, bool value, IntPtr userData);
+
+ internal delegate bool DoubleCallback(int pos, double value, IntPtr userData);
+
+ internal delegate bool ByteStrCallback(int pos, byte[] value, int len, IntPtr userData);
+
+ internal delegate bool StrCallback(int pos, string value, IntPtr userData);
+
+ internal delegate bool ListCallback(int pos, IntPtr value, IntPtr userData);
+
+ internal delegate bool AttribsCallback(int pos, IntPtr value, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_list_create")]
+ internal static extern int Create(DataType type, out IntPtr list);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_list_destroy")]
+ internal static extern void Destroy(IntPtr list);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_list_add_int")]
+ internal static extern int AddInt(IntPtr list, int val, int pos);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_list_add_bool")]
+ internal static extern int AddBool(IntPtr list, bool val, int pos);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_list_add_double")]
+ internal static extern int AddDouble(IntPtr list, double val, int pos);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_list_add_str")]
+ internal static extern int AddStr(IntPtr list, string val, int pos);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_list_add_byte_str")]
+ internal static extern int AddByteStr(IntPtr list, byte[] val, int len, int pos);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_list_add_list")]
+ internal static extern int AddList(IntPtr list, IntPtr val, int pos);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_list_add_attributes")]
+ internal static extern int AddAttributes(IntPtr list, IntPtr val, int pos);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_list_get_nth_int")]
+ internal static extern int GetNthInt(IntPtr list, int pos, out int val);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_list_get_nth_bool")]
+ internal static extern int GetNthBool(IntPtr list, int pos, out bool val);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_list_get_nth_double")]
+ internal static extern int GetNthDouble(IntPtr list, int pos, out double val);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_list_get_nth_str")]
+ internal static extern int GetNthStr(IntPtr list, int pos, out IntPtr val);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_list_get_nth_byte_str")]
+ internal static extern int GetNthByteStr(IntPtr list, int pos, out IntPtr val, out int len);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_list_get_nth_list")]
+ internal static extern int GetNthList(IntPtr src, int pos, out IntPtr dest);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_list_get_nth_attributes")]
+ internal static extern int GetNthAttributes(IntPtr list, int pos, out IntPtr attribs);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_list_remove_nth")]
+ internal static extern int RemoveNth(IntPtr list, int pos);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_list_get_type")]
+ internal static extern int GetType(IntPtr list, out int type);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_list_get_length")]
+ internal static extern int GetLength(IntPtr list, out int length);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_list_foreach_int")]
+ internal static extern int ForeachInt(IntPtr list, IntCallback cb, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_list_foreach_bool")]
+ internal static extern int ForeachBool(IntPtr list, BoolCallback cb, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_list_foreach_double")]
+ internal static extern int ForeachDouble(IntPtr list, DoubleCallback cb, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_list_foreach_byte_str")]
+ internal static extern int ForeachByteStr(IntPtr list, ByteStrCallback cb, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_list_foreach_str")]
+ internal static extern int ForeachStr(IntPtr list, StrCallback cb, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_list_foreach_list")]
+ internal static extern int ForeachList(IntPtr list, ListCallback cb, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_list_foreach_attributes")]
+ internal static extern int ForeachAttributes(IntPtr list, AttribsCallback cb, IntPtr userData);
+ }
+ }
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+ internal static partial class IoTConnectivity
+ {
+ internal static partial class Server
+ {
+ internal enum RequestType
+ {
+ Unknown = 0,
+ Get = 1,
+ Put = 2,
+ Post = 3,
+ Delete = 4,
+ }
+
+ internal static partial class IoTCon
+ {
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_start_presence")]
+ internal static extern int StartPresence(uint time);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_stop_presence")]
+ internal static extern int StopPresence();
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_set_device_name")]
+ internal static extern int SetDeviceName(string deviceName);
+ }
+
+ internal static partial class Resource
+ {
+ [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
+ internal delegate void RequestHandlerCallback(IntPtr resource, IntPtr request, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_resource_create")]
+ internal static extern int Create(string uriPath, IntPtr resTypes, IntPtr ifaces, int properties, RequestHandlerCallback cb, IntPtr userData, out IntPtr resourceHandle);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_resource_destroy")]
+ internal static extern int Destroy(IntPtr resourceHandle);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_resource_bind_interface")]
+ internal static extern int BindInterface(IntPtr resource, string iface);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_resource_bind_type")]
+ internal static extern int BindType(IntPtr resourceHandle, string resourceType);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_resource_set_request_handler")]
+ internal static extern int SetRequestHandler(IntPtr resource, RequestHandlerCallback cb, IntPtr userData);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_resource_bind_child_resource")]
+ internal static extern int BindChildResource(IntPtr parent, IntPtr child);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_resource_unbind_child_resource")]
+ internal static extern int UnbindChildResource(IntPtr parent, IntPtr child);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_resource_notify")]
+ internal static extern int Notify(IntPtr resource, IntPtr repr, IntPtr observers, int qos);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_resource_get_number_of_children")]
+ internal static extern int GetNumberOfChildren(IntPtr resource, out int number);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_resource_get_nth_child")]
+ internal static extern int GetNthChild(IntPtr parent, int index, out IntPtr child);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_resource_get_uri_path")]
+ internal static extern int GetUriPath(IntPtr resource, out IntPtr uriPath);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_resource_get_types")]
+ internal static extern int GetTypes(IntPtr resource, out IntPtr types);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_resource_get_interfaces")]
+ internal static extern int GetInterfaces(IntPtr resource, out IntPtr ifaces);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_resource_get_properties")]
+ internal static extern int GetProperties(IntPtr resource, out int properties);
+ }
+
+ internal static partial class Request
+ {
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_request_get_host_address")]
+ internal static extern int GetHostAddress(IntPtr request, out IntPtr hostAddress);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_request_get_connectivity_type")]
+ internal static extern int GetConnectivityType(IntPtr request, out int connectivityType);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_request_get_representation")]
+ internal static extern int GetRepresentation(IntPtr request, out IntPtr repr);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_request_get_request_type")]
+ internal static extern int GetRequestType(IntPtr request, out int type);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_request_get_options")]
+ internal static extern int GetOptions(IntPtr request, out IntPtr options);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_request_get_query")]
+ internal static extern int GetQuery(IntPtr request, out IntPtr query);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_request_get_observe_type")]
+ internal static extern int GetObserveType(IntPtr request, out int observeType);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_request_get_observe_id")]
+ internal static extern int GetObserveId(IntPtr request, out int observeId);
+ }
+
+ internal static partial class Response
+ {
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_response_create")]
+ internal static extern int Create(IntPtr request, out IntPtr response);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_response_destroy")]
+ internal static extern void Destroy(IntPtr resp);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_response_get_options")]
+ internal static extern int GetOptions(IntPtr resp, out IntPtr options);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_response_get_representation")]
+ internal static extern int GetRepresentation(IntPtr resp, out IntPtr repr);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_response_get_result")]
+ internal static extern int GetResult(IntPtr resp, out int result);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_response_set_result")]
+ internal static extern int SetResult(IntPtr resp, int result);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_response_set_representation")]
+ internal static extern int SetRepresentation(IntPtr resp, IntPtr repr);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_response_set_options")]
+ internal static extern int SetOptions(IntPtr resp, IntPtr options);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_response_send")]
+ internal static extern int Send(IntPtr resp);
+ }
+
+ internal static partial class Observers
+ {
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_observers_create")]
+ internal static extern int Create(out IntPtr observers);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_observers_destroy")]
+ internal static extern void Destroy(IntPtr observers);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_observers_add")]
+ internal static extern int Add(IntPtr observers, int observeId);
+
+ [DllImport(Libraries.IoTCon, EntryPoint = "iotcon_observers_remove")]
+ internal static extern int Remove(IntPtr observers, int observeId);
+ }
+ }
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+internal static partial class Interop
+{
+ internal static partial class Libraries
+ {
+ public const string IoTCon = "libiotcon.so.0";
+ public const string Glib = "libglib-2.0.so.0";
+ public const string Libc = "libc.so.6";
+ }
+}
--- /dev/null
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <Version>1.0.7</Version>
+ <Authors>Samsung Electronics</Authors>
+ <Copyright>© Samsung Electronics Co., Ltd All Rights Reserved</Copyright>
+ <Description>Tizen IoTConnectivity API for Tizen .NET</Description>
+ <PackageProjectUrl>https://www.tizen.org/</PackageProjectUrl>
+ <PackageLicenseUrl>https://www.apache.org/licenses/LICENSE-2.0</PackageLicenseUrl>
+ <PackageIconUrl>https://developer.tizen.org/sites/default/files/images/tizen-pinwheel-on-light-rgb_64_64.png</PackageIconUrl>
+ </PropertyGroup>
+
+ <PropertyGroup>
+ <TargetFramework>netstandard1.3</TargetFramework>
+ <AllowUnsafeBlocks>True</AllowUnsafeBlocks>
+ <SignAssembly>True</SignAssembly>
+ <AssemblyOriginatorKeyFile>Tizen.Network.IoTConnectivity.snk</AssemblyOriginatorKeyFile>
+ <PublicSign Condition="'$(OS)' != 'Windows_NT'">true</PublicSign>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Tizen" Version="1.0.5" />
+ </ItemGroup>
+
+</Project>
+
--- /dev/null
+/// Copyright 2016 by Samsung Electronics, Inc.,
+///
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// This class represents current attributes of a resource.
+ /// It provides API to manage attributes.
+ /// This class is accessed by using a constructor to create a new instance of this object.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public class Attributes : IDictionary<string, object>, IDisposable
+ {
+ internal IntPtr _resourceAttributesHandle = IntPtr.Zero;
+ private readonly IDictionary<string, object> _attributes = new Dictionary<string, object>();
+ private bool _disposed = false;
+
+ /// <summary>
+ /// The Attributes constructor.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory.</exception>
+ /// <code>
+ /// Tizen.Network.IoTConnectivity.Attributes attributes = new Tizen.Network.IoTConnectivity.Attributes();
+ /// </code>
+ public Attributes()
+ {
+ int ret = Interop.IoTConnectivity.Common.Attributes.Create(out _resourceAttributesHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to create attributes handle");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+
+ internal Attributes(IntPtr attributesHandleToClone)
+ {
+ int ret = Interop.IoTConnectivity.Common.Attributes.Clone(attributesHandleToClone, out _resourceAttributesHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to create attributes handle");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+
+ SetAttributes(_resourceAttributesHandle);
+ }
+
+ /// <summary>
+ /// Destructor of the Attributes class.
+ /// </summary>
+ ~Attributes()
+ {
+ Dispose(false);
+ }
+
+ /// <summary>
+ /// Gets the number of keys.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The number of keys.</value>
+ /// <code>
+ /// Tizen.Network.IoTConnectivity.Attributes attributes = new Tizen.Network.IoTConnectivity.Attributes() {
+ /// attributes.Add("brightness", 50);
+ /// var count = attributes.Count;
+ /// Console.WriteLine("There are {0} keys in the attribute object", count);
+ /// </code>
+ public int Count
+ {
+ get
+ {
+ return _attributes.Count;
+ }
+ }
+
+ /// <summary>
+ /// Represents whether an attribute is readonly.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>Whether an attribute is readonly.</value>
+ /// <code>
+ /// Tizen.Network.IoTConnectivity.Attributes attributes = new Tizen.Network.IoTConnectivity.Attributes() {
+ /// { "state", "ON" },
+ /// { "dim", 10 }
+ /// };
+ /// if (attributes.IsReadOnly)
+ /// Console.WriteLine("Read only attribute");
+ /// </code>
+ public bool IsReadOnly
+ {
+ get
+ {
+ return _attributes.IsReadOnly;
+ }
+ }
+
+ /// <summary>
+ /// Contains all the attribute keys.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>All the attribute keys.</value>
+ /// <code>
+ /// Tizen.Network.IoTConnectivity.Attributes attributes = new Tizen.Network.IoTConnectivity.Attributes() {
+ /// { "state", "ON" },
+ /// { "dim", 10 }
+ /// };
+ /// var keys = attributes.Keys;
+ /// Console.WriteLine("Attribute contains keys {0} and {1}", keys.ElementAt(0), keys.ElementAt(1));
+ /// </code>
+ public ICollection<string> Keys
+ {
+ get
+ {
+ return _attributes.Keys;
+ }
+ }
+
+ /// <summary>
+ /// Contains all the attribute values.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>All the attribute values.</value>
+ /// <code>
+ /// Tizen.Network.IoTConnectivity.Attributes attributes = new Tizen.Network.IoTConnectivity.Attributes() {
+ /// { "state", "ON" },
+ /// { "dim", 10 }
+ /// };
+ /// var values = attributes.Values;
+ /// Console.WriteLine("Attribute contains values {0} and {1}", values.ElementAt(0), values.ElementAt(1));
+ /// </code>
+ public ICollection<object> Values
+ {
+ get
+ {
+ return _attributes.Values;
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the attribute with the specified key.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The attribute with the specified key.</value>
+ /// <param name="key">The key of the attribute to get or set.</param>
+ /// <returns>The element with the specified key.</returns>
+ /// <code>
+ /// Tizen.Network.IoTConnectivity.Attributes attributes = new Tizen.Network.IoTConnectivity.Attributes();
+ /// attributes["state"] = "ON";
+ /// Console.WriteLine("Attribute value for key 'state' : {0}", attributes["state"]);
+ /// </code>
+ public object this[string key]
+ {
+ get
+ {
+ if (_attributes.ContainsKey(key))
+ return _attributes[key];
+ else
+ return null;
+ }
+
+ set
+ {
+ Add(key, value);
+ }
+ }
+
+ /// <summary>
+ /// Adds the attribute key and a value as a key value pair.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="item">The key value pair to add.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <code>
+ /// Tizen.Network.IoTConnectivity.Attributes attributes = new Tizen.Network.IoTConnectivity.Attributes();
+ /// attributes.Add(new KeyValuePair<string, object> ("state", "ON"));
+ /// </code>
+ public void Add(KeyValuePair<string, object> item)
+ {
+ Add(item.Key, item.Value);
+ }
+
+ /// <summary>
+ /// Adds an attribute.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="key">The key representing the attribute.</param>
+ /// <param name="value">The value representing the attribute.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <code>
+ /// Tizen.Network.IoTConnectivity.Attributes attributes = new Tizen.Network.IoTConnectivity.Attributes();
+ /// attributes.Add("brightness", 50);
+ /// </code>
+ public void Add(string key, object value)
+ {
+ int ret = 0;
+ if (value is int)
+ {
+ ret = Interop.IoTConnectivity.Common.Attributes.AddInt(_resourceAttributesHandle, key, (int)value);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add int");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ else if (value is Attributes)
+ {
+ Attributes attribs = (Attributes)value;
+ ret = Interop.IoTConnectivity.Common.Attributes.AddAttributes(_resourceAttributesHandle, key, attribs._resourceAttributesHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add attributes");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ else if (value is string)
+ {
+ ret = Interop.IoTConnectivity.Common.Attributes.AddStr(_resourceAttributesHandle, key, (string)value);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add string");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ else if (value is double)
+ {
+ ret = Interop.IoTConnectivity.Common.Attributes.AddDouble(_resourceAttributesHandle, key, (double)value);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add double");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ else if (value is bool)
+ {
+ ret = Interop.IoTConnectivity.Common.Attributes.AddBool(_resourceAttributesHandle, key, (bool)value);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add bool");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ else if (value is byte[])
+ {
+ byte[] val = value as byte[];
+ if (val == null)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get byte[] val");
+ throw new ArgumentException("Invalid Parameter");
+ }
+ ret = Interop.IoTConnectivity.Common.Attributes.AddByteStr(_resourceAttributesHandle, key, val, val.Length);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add bool");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ else if (value is IEnumerable)
+ {
+ IntPtr listHandle = List.GetListHandle(value);
+ ret = Interop.IoTConnectivity.Common.Attributes.AddList(_resourceAttributesHandle, key, listHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add list");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ else
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to Add");
+ throw IoTConnectivityErrorFactory.GetException((int)IoTConnectivityError.InvalidParameter);
+ }
+ _attributes.Add(key, value);
+ }
+
+ /// <summary>
+ /// Clears attributes collection.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the operation is invalid</exception>
+ /// <code>
+ /// Tizen.Network.IoTConnectivity.Attributes attributes = new Tizen.Network.IoTConnectivity.Attributes();
+ /// attributes.Add("brightness", 50);
+ /// attributes.Clear();
+ /// </code>
+ public void Clear()
+ {
+ foreach (string key in _attributes.Keys)
+ {
+ int ret = Interop.IoTConnectivity.Common.Attributes.Remove(_resourceAttributesHandle, key);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to clear attributes");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ _attributes.Clear();
+ }
+
+ /// <summary>
+ /// Checks whether the given key value pair exists in attributes collection.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="item">The status key value pair.</param>
+ /// <returns>true if exists. Otherwise, false.</returns>
+ /// <code>
+ /// Tizen.Network.IoTConnectivity.Attributes attributes = new Tizen.Network.IoTConnectivity.Attributes() {
+ /// { "state", "ON" },
+ /// { "dim", 10 }
+ /// };
+ /// if (attributes.Contains(new KeyValuePair<string, object> ("dim", 10))
+ /// Console.WriteLine("Attribute conatins pair ('dim', 10)");
+ /// </code>
+ public bool Contains(KeyValuePair<string, object> item)
+ {
+ return _attributes.Contains(item);
+ }
+
+ /// <summary>
+ /// Checks whether the given key exists in attributes collection.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="key">The status key to look for.</param>
+ /// <returns>true if exists. Otherwise, false.</returns>
+ /// <code>
+ /// Tizen.Network.IoTConnectivity.Attributes attributes = new Tizen.Network.IoTConnectivity.Attributes() {
+ /// { "state", "ON" },
+ /// { "dim", 10 }
+ /// };
+ /// if (attributes.ContainsKey("dim"))
+ /// Console.WriteLine("Attribute conatins key : dim");
+ /// </code>
+ public bool ContainsKey(string key)
+ {
+ return _attributes.ContainsKey(key);
+ }
+
+ /// <summary>
+ /// Copies the elements of the attributes to an array, starting at a particular index.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="array">The destination array.</param>
+ /// <param name="arrayIndex">The zero-based index in an array at which copying begins.</param>
+ /// <code>
+ /// Tizen.Network.IoTConnectivity.Attributes attributes = new Tizen.Network.IoTConnectivity.Attributes() {
+ /// { "state", "ON" },
+ /// { "dim", 10 }
+ /// };
+ /// KeyValuePair<string, object>[] dest = new KeyValuePair<string, object>[attributes.Count];
+ /// int index = 0;
+ /// attributes.CopyTo(dest, index);
+ /// Console.WriteLine("Dest conatins ({0}, {1})", dest[0].Key, dest[0].Value);
+ /// </code>
+ public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
+ {
+ _attributes.CopyTo(array, arrayIndex);
+ }
+
+ /// <summary>
+ /// Returns an enumerator that iterates through the collection.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <returns> An enumerator that can be used to iterate through the collection.</returns>
+ /// <code>
+ /// Tizen.Network.IoTConnectivity.Attributes attributes = new Tizen.Network.IoTConnectivity.Attributes() {
+ /// { "state", "ON" },
+ /// { "dim", 10 }
+ /// };
+ /// foreach (KeyValuePair<string, object> pair in attributes)
+ /// {
+ /// Console.WriteLine("key : {0}, value : {1}", pair.Key, pair.Value);
+ /// }
+ /// </code>
+ public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
+ {
+ return _attributes.GetEnumerator();
+ }
+
+ /// <summary>
+ /// Removes an attribute from collection.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="item">The attributes element to remove.</param>
+ /// <returns>true if operation is successful, otherwise, false.</returns>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported</exception>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the operation is invalid</exception>
+ /// <code>
+ /// Tizen.Network.IoTConnectivity.Attributes attributes = new Tizen.Network.IoTConnectivity.Attributes() {
+ /// { "state", "ON" },
+ /// { "dim", 10 }
+ /// };
+ /// if (attributes.Remove(new KeyValuePair<string, object>("dim", 10)))
+ /// Console.WriteLine("Remove was successful");
+ /// </code>
+ public bool Remove(KeyValuePair<string, object> item)
+ {
+ return Remove(item.Key);
+ }
+
+ /// <summary>
+ /// Removes an attribute from collection using a key.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="key">The attributes element to remove.</param>
+ /// <returns>true if operation is successful, otherwise, false.</returns>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported</exception>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the operation is invalid</exception>
+ /// <code>
+ /// Tizen.Network.IoTConnectivity.Attributes attributes = new Tizen.Network.IoTConnectivity.Attributes() {
+ /// { "state", "ON" },
+ /// { "dim", 10 }
+ /// };
+ /// if (attributes.Remove("state"))
+ /// Console.WriteLine("Remove was successful");
+ /// </code>
+ public bool Remove(string key)
+ {
+ int ret = Interop.IoTConnectivity.Common.Attributes.Remove(_resourceAttributesHandle, key);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to remove attributes");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+
+ bool isRemoved = _attributes.Remove(key);
+
+ return isRemoved;
+ }
+
+ /// <summary>
+ /// Gets the value associated with the specified key.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="key">The key whose value to get.</param>
+ /// <param name="value"> The value associated with the specified key.</param>
+ /// <returns> true if the attributes collection contains an element with the specified key, otherwise, false.</returns>
+ /// <code>
+ /// Tizen.Network.IoTConnectivity.Attributes attributes = new Tizen.Network.IoTConnectivity.Attributes() {
+ /// { "state", "ON" }
+ /// };
+ /// object value;
+ /// var isPresent = attributes.TryGetValue("state", out value);
+ /// if (isPresent)
+ /// Console.WriteLine("value : {0}", value);
+ /// </code>
+ public bool TryGetValue(string key, out object value)
+ {
+ return _attributes.TryGetValue(key, out value);
+ }
+
+ /// <summary>
+ /// Returns an enumerator that iterates through the collection.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ IEnumerator IEnumerable.GetEnumerator()
+ {
+ return _attributes.GetEnumerator();
+ }
+
+ /// <summary>
+ /// Releases any unmanaged resources used by this object.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ /// <summary>
+ /// Releases any unmanaged resources used by this object. Can also dispose any other disposable objects.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="disposing">If true, disposes any disposable objects. If false, does not dispose disposable objects.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ protected virtual void Dispose(bool disposing)
+ {
+ if (_disposed)
+ return;
+
+ if (disposing)
+ {
+ // Free managed objects
+ }
+
+ Interop.IoTConnectivity.Common.Attributes.Destroy(_resourceAttributesHandle);
+ _disposed = true;
+ }
+
+ private void SetAttributes(IntPtr attributesHandle)
+ {
+ Interop.IoTConnectivity.Common.Attributes.AttributesCallback cb = (IntPtr attributes, string key, IntPtr userData) =>
+ {
+ Interop.IoTConnectivity.Common.DataType dataType;
+ int ret = Interop.IoTConnectivity.Common.Attributes.GetType(attributes, key, out dataType);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get type");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+
+ switch ((Interop.IoTConnectivity.Common.DataType)dataType)
+ {
+ case Interop.IoTConnectivity.Common.DataType.Int:
+ {
+ int value;
+ ret = Interop.IoTConnectivity.Common.Attributes.GetInt(attributes, key, out value);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get attributes");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ _attributes.Add(key, value);
+ break;
+ }
+ case Interop.IoTConnectivity.Common.DataType.Bool:
+ {
+ bool value;
+ ret = Interop.IoTConnectivity.Common.Attributes.GetBool(attributes, key, out value);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get attributes");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ _attributes.Add(key, value);
+ break;
+ }
+ case Interop.IoTConnectivity.Common.DataType.Double:
+ {
+ double value;
+ ret = Interop.IoTConnectivity.Common.Attributes.GetDouble(attributes, key, out value);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get attributes");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ _attributes.Add(key, value);
+ break;
+ }
+ case Interop.IoTConnectivity.Common.DataType.String:
+ {
+ IntPtr value;
+ string Str;
+ ret = Interop.IoTConnectivity.Common.Attributes.GetStr(attributes, key, out value);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get attributes");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ Str = (value != IntPtr.Zero) ? Marshal.PtrToStringAnsi(value) : string.Empty;
+ _attributes.Add(key, Str);
+ break;
+ }
+ case Interop.IoTConnectivity.Common.DataType.ByteStr:
+ {
+ IntPtr byteStrPtr;
+ int byteStrSize;
+ ret = Interop.IoTConnectivity.Common.Attributes.GetByteStr(attributes, key, out byteStrPtr, out byteStrSize);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get attributes");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ byte[] byteStr = new byte[byteStrSize];
+ Marshal.Copy(byteStrPtr, byteStr, 0, byteStrSize);
+ _attributes.Add(key, byteStr);
+ break;
+ }
+ case Interop.IoTConnectivity.Common.DataType.Null:
+ {
+ _attributes.Add(key, null);
+ break;
+ }
+ case Interop.IoTConnectivity.Common.DataType.List:
+ {
+ IntPtr listHandle;
+ ret = Interop.IoTConnectivity.Common.Attributes.GetList(attributes, key, out listHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get attributes");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ _attributes.Add(key, List.GetList(listHandle));
+ break;
+ }
+ case Interop.IoTConnectivity.Common.DataType.Attributes:
+ {
+ IntPtr attribsHandle;
+ ret = Interop.IoTConnectivity.Common.Attributes.GetAttributes(attributes, key, out attribsHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get attributes");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ _attributes.Add(key, new Attributes(attribsHandle));
+ break;
+ }
+ default:
+ break;
+ }
+
+ return true;
+ };
+
+ int res = Interop.IoTConnectivity.Common.Attributes.Foreach(attributesHandle, cb, IntPtr.Zero);
+ if (res != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to remove attributes");
+ throw IoTConnectivityErrorFactory.GetException(res);
+ }
+ }
+ }
+
+ internal static class List
+ {
+ internal static IntPtr GetListHandle(object list)
+ {
+ IntPtr listHandle = IntPtr.Zero;
+ int ret;
+ int pos = 0;
+
+ if (list is IEnumerable<IEnumerable>)
+ {
+ ret = Interop.IoTConnectivity.Common.List.Create(Interop.IoTConnectivity.Common.DataType.List, out listHandle);
+ pos = 0;
+ foreach (IEnumerable val in (IEnumerable<IEnumerable>)list)
+ {
+ IntPtr childList = GetListHandle(val);
+ ret = Interop.IoTConnectivity.Common.List.AddList(listHandle, childList, pos++);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add attributes");
+ Interop.IoTConnectivity.Common.List.Destroy(childList);
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ }
+ else if (list is IEnumerable<int>)
+ {
+ ret = Interop.IoTConnectivity.Common.List.Create(Interop.IoTConnectivity.Common.DataType.Int, out listHandle);
+ pos = 0;
+ foreach (int val in (IEnumerable<int>)list)
+ {
+ ret = Interop.IoTConnectivity.Common.List.AddInt(listHandle, val, pos++);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add attributes");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ }
+ else if (list is IEnumerable<string>)
+ {
+ ret = Interop.IoTConnectivity.Common.List.Create(Interop.IoTConnectivity.Common.DataType.String, out listHandle);
+ pos = 0;
+ foreach (string val in (IEnumerable<string>)list)
+ {
+ ret = Interop.IoTConnectivity.Common.List.AddStr(listHandle, val, pos++);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add str");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ }
+ else if (list is IEnumerable<double>)
+ {
+ ret = Interop.IoTConnectivity.Common.List.Create(Interop.IoTConnectivity.Common.DataType.Double, out listHandle);
+ pos = 0;
+ foreach (double val in (IEnumerable<double>)list)
+ {
+ ret = Interop.IoTConnectivity.Common.List.AddDouble(listHandle, val, pos++);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add double");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ }
+ else if (list is IEnumerable<bool>)
+ {
+ ret = Interop.IoTConnectivity.Common.List.Create(Interop.IoTConnectivity.Common.DataType.Bool, out listHandle);
+ pos = 0;
+ foreach (bool val in (IEnumerable<bool>)list)
+ {
+ ret = Interop.IoTConnectivity.Common.List.AddBool(listHandle, val, pos++);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add bool");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ }
+ else if (list is IEnumerable<Attributes>)
+ {
+ ret = Interop.IoTConnectivity.Common.List.Create(Interop.IoTConnectivity.Common.DataType.Attributes, out listHandle);
+ pos = 0;
+ foreach (Attributes val in (IEnumerable<Attributes>)list)
+ {
+ ret = Interop.IoTConnectivity.Common.List.AddAttributes(listHandle, val._resourceAttributesHandle, pos++);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add attributes");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ }
+ else if (list is IEnumerable<byte[]>)
+ {
+ ret = Interop.IoTConnectivity.Common.List.Create(Interop.IoTConnectivity.Common.DataType.ByteStr, out listHandle);
+ pos = 0;
+ foreach (byte[] val in (IEnumerable<byte[]>)list)
+ {
+ ret = Interop.IoTConnectivity.Common.List.AddByteStr(listHandle, val, val.Length, pos++);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add byte[]");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ }
+ else
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to GetListHandle");
+ throw IoTConnectivityErrorFactory.GetException((int)IoTConnectivityError.InvalidParameter);
+ }
+ return listHandle;
+ }
+
+ internal static object GetList(IntPtr listHandle)
+ {
+ IList list = null;
+ int type;
+ int ret = Interop.IoTConnectivity.Common.List.GetType(listHandle, out type);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get type");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ switch ((Interop.IoTConnectivity.Common.DataType)type)
+ {
+ case Interop.IoTConnectivity.Common.DataType.Int:
+ {
+ list = new List<int>();
+ Interop.IoTConnectivity.Common.List.IntCallback cb = (int pos, int value, IntPtr userData) =>
+ {
+ list.Add(value);
+ return true;
+ };
+ ret = Interop.IoTConnectivity.Common.List.ForeachInt(listHandle, cb, IntPtr.Zero);
+ break;
+ }
+ case Interop.IoTConnectivity.Common.DataType.Bool:
+ {
+ list = new List<bool>();
+ Interop.IoTConnectivity.Common.List.BoolCallback cb = (int pos, bool value, IntPtr userData) =>
+ {
+ list.Add(value);
+ return true;
+ };
+ ret = Interop.IoTConnectivity.Common.List.ForeachBool(listHandle, cb, IntPtr.Zero);
+ break;
+ }
+ case Interop.IoTConnectivity.Common.DataType.Double:
+ {
+ list = new List<double>();
+ Interop.IoTConnectivity.Common.List.DoubleCallback cb = (int pos, double value, IntPtr userData) =>
+ {
+ list.Add(value);
+ return true;
+ };
+ ret = Interop.IoTConnectivity.Common.List.ForeachDouble(listHandle, cb, IntPtr.Zero);
+ break;
+ }
+ case Interop.IoTConnectivity.Common.DataType.String:
+ {
+ list = new List<string>();
+ Interop.IoTConnectivity.Common.List.StrCallback cb = (int pos, string value, IntPtr userData) =>
+ {
+ list.Add(value);
+ return true;
+ };
+ ret = Interop.IoTConnectivity.Common.List.ForeachStr(listHandle, cb, IntPtr.Zero);
+ break;
+ }
+ case Interop.IoTConnectivity.Common.DataType.Attributes:
+ {
+ list = new List<Attributes>();
+ Interop.IoTConnectivity.Common.List.AttribsCallback cb = (int pos, IntPtr value, IntPtr userData) =>
+ {
+ list.Add(new Attributes(value));
+ return true;
+ };
+ ret = Interop.IoTConnectivity.Common.List.ForeachAttributes(listHandle, cb, IntPtr.Zero);
+ break;
+ }
+ case Interop.IoTConnectivity.Common.DataType.ByteStr:
+ {
+ list = new List<byte[]>();
+ Interop.IoTConnectivity.Common.List.ByteStrCallback cb = (int pos, byte[] value, int len, IntPtr userData) =>
+ {
+ list.Add(value);
+ return true;
+ };
+ ret = Interop.IoTConnectivity.Common.List.ForeachByteStr(listHandle, cb, IntPtr.Zero);
+ break;
+ }
+ case Interop.IoTConnectivity.Common.DataType.List:
+ {
+ list = new List<List<object>>();
+ Interop.IoTConnectivity.Common.List.ListCallback cb = (int pos, IntPtr value, IntPtr userData) =>
+ {
+ object childList = GetList(value);
+ if (childList != null)
+ list.Add(childList);
+ return true;
+ };
+ ret = Interop.IoTConnectivity.Common.List.ForeachList(listHandle, cb, IntPtr.Zero);
+ break;
+ }
+ default:
+ break;
+ }
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get attributes");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ return list;
+ }
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+using System;
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// This class represents event arguments of the CacheUpdated event.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public class CacheUpdatedEventArgs : EventArgs
+ {
+ internal CacheUpdatedEventArgs() { }
+
+ /// <summary>
+ /// Indicates the updated representation of the resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The updated representation of the resource.</value>
+ public Representation Representation { get; internal set; }
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// This class represents event arguments of the DeviceInformationFound event.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public class DeviceInformationFoundEventArgs
+ {
+ internal DeviceInformationFoundEventArgs() { }
+
+ /// <summary>
+ /// The request ID.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The request ID.</value>
+ public int RequestId { get; internal set; }
+
+ /// <summary>
+ /// Indicates to continuously receive the event for finding device information.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>Continuously receive the event for finding device information.</value>
+ public bool EventContinue { get; set; }
+
+ /// <summary>
+ /// Indicates the human friendly name for device.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>Human friendly name for device.</value>
+ public string Name { get; internal set; }
+
+ /// <summary>
+ /// Indicates the spec version of the core specification.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>Spec version of the core specification.</value>
+ public string SpecVersion { get; internal set; }
+
+ /// <summary>
+ /// Indicates an unique identifier for the OIC device.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>Unique identifier for OIC device.</value>
+ public string DeviceId { get; internal set; }
+
+ /// <summary>
+ /// Indicates version of the specs this device data model is implemented to.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>Version of the specs this device data model is implemented to.</value>
+ public string DataModelVersion { get; internal set; }
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// Enumeration for resource found errors.
+ /// </summary>
+ internal enum FindingError
+ {
+ /// <summary>
+ /// I/O error.
+ /// </summary>
+ Io = 1,
+ /// <summary>
+ /// Out of memory.
+ /// </summary>
+ OutOfMemory,
+ /// <summary>
+ /// Permission denied.
+ /// </summary>
+ PermissionDenied,
+ /// <summary>
+ /// Not supported.
+ /// </summary>
+ NotSupported,
+ /// <summary>
+ /// Invalid parameter.
+ /// </summary>
+ InvalidParameter,
+ /// <summary>
+ /// No data available.
+ /// </summary>
+ NoData,
+ /// <summary>
+ /// Time out.
+ /// </summary>
+ TimeOut,
+ /// <summary>
+ /// IoTivity errors.
+ /// </summary>
+ Iotivity,
+ /// <summary>
+ /// Representation errors.
+ /// </summary>
+ Representation,
+ /// <summary>
+ /// Invalid type.
+ /// </summary>
+ InvalidType,
+ /// <summary>
+ /// Already.
+ /// </summary>
+ Already,
+ /// <summary>
+ /// System errors.
+ /// </summary>
+ System
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+using System;
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// This class represents event arguments of the FindingErrorOccurred event.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public class FindingErrorOccurredEventArgs : EventArgs
+ {
+ internal FindingErrorOccurredEventArgs() { }
+
+ /// <summary>
+ /// The request ID of the operation, which caused this error.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The request ID of the operation, which caused this error.</value>
+ public int RequestId { get; internal set; }
+
+ /// <summary>
+ /// Contains error details.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>Error details.</value>
+ public Exception Error { get; internal set; }
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System;
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// IoT connectivity client manager consists of client side APIs.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public static class IoTConnectivityClientManager
+ {
+ /// <summary>
+ /// The IP Address for multicast.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public const string MulticastAddress = null;
+
+ private static int s_presenceListenerId = 1;
+ private static Dictionary<IntPtr, Interop.IoTConnectivity.Client.Presence.PresenceCallback> s_presenceCallbacksMap = new Dictionary<IntPtr, Interop.IoTConnectivity.Client.Presence.PresenceCallback>();
+ private static Dictionary<IntPtr, IntPtr> s_presenceHandlesMap = new Dictionary<IntPtr, IntPtr>();
+
+ private static int s_requestId = 1;
+ private static Dictionary<IntPtr, Interop.IoTConnectivity.Client.ResourceFinder.FoundResourceCallback> s_resourceFoundCallbacksMap = new Dictionary<IntPtr, Interop.IoTConnectivity.Client.ResourceFinder.FoundResourceCallback>();
+ private static Dictionary<IntPtr, Interop.IoTConnectivity.Client.DeviceInformation.DeviceInformationCallback> s_deviceInformationCallbacksMap = new Dictionary<IntPtr, Interop.IoTConnectivity.Client.DeviceInformation.DeviceInformationCallback>();
+ private static Dictionary<IntPtr, Interop.IoTConnectivity.Client.PlatformInformation.PlatformInformationCallback> s_platformInformationCallbacksMap = new Dictionary<IntPtr, Interop.IoTConnectivity.Client.PlatformInformation.PlatformInformationCallback>();
+
+ /// <summary>
+ /// PresenceReceived event. This event occurs when server starts sending presence of a resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public static event EventHandler<PresenceReceivedEventArgs> PresenceReceived;
+
+ /// <summary>
+ /// ResourceFound event. This event occurs when a resource is found from the remote server
+ /// after sending request using API StartFindingResource().
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public static event EventHandler<ResourceFoundEventArgs> ResourceFound;
+
+ /// <summary>
+ /// PlatformInformationFound event. This event occurs when platform information is found
+ /// after sending request using API StartFindingPlatformInformation().
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public static event EventHandler<PlatformInformationFoundEventArgs> PlatformInformationFound;
+
+ /// <summary>
+ /// DeviceInformationFound event. This event occurs when device information is found
+ /// after sending request using API StartFindingDeviceInformation().
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public static event EventHandler<DeviceInformationFoundEventArgs> DeviceInformationFound;
+
+ /// <summary>
+ /// FindingError event. This event occurs when an error is found.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public static event EventHandler<FindingErrorOccurredEventArgs> FindingErrorOccurred;
+
+ /// <summary>
+ /// Timeout in seconds.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>
+ /// Value to be set must be in range from 1 to 3600. Default timeout interval value is 30.\n
+ /// Sets/gets the timeout of StartFindingResource(), StartFindingDeviceInformation(), StartFindingPlatformInformation(),
+ /// RemoteResource.GetAsync(), RemoteResource.PutAsync(), RemoteResource.PostAsync() and RemoteResource.DeleteAsync() APIs.\n
+ /// Setter can throw exception.
+ /// </value>
+ /// <pre>
+ /// Initialize() should be called to initialize.
+ /// </pre>
+ /// <code>
+ /// IoTConnectivityClientManager.Initialize();
+ /// IoTConnectivityClientManager.TimeOut = 120;
+ /// </code>
+ public static int TimeOut
+ {
+ get
+ {
+ int timeout;
+ int ret = Interop.IoTConnectivity.Client.IoTCon.GetTimeout(out timeout);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Warn(IoTConnectivityErrorFactory.LogTag, "Failed to get timeout");
+ return 0;
+ }
+ return timeout;
+ }
+ set
+ {
+ int ret = Interop.IoTConnectivity.Client.IoTCon.SetTimeout(value);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to set timeout");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ }
+
+ /// <summary>
+ /// Polling interval of IoTConnectivity.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>
+ /// Sets/Gets the polling inerval(milliseconds) of IoTCon. Default value is 100 milliseconds.
+ /// Value to be set must be in range from 1 to 999. The closer to 0, the faster it operates.
+ /// Setter is invoked immediately for changing the interval.
+ /// If you want the faster operation, we recommend you set 10 milliseconds for polling interval.
+ /// Setter can throw exception.
+ /// </value>
+ /// <pre>
+ /// Initialize() should be called to initialize.
+ /// </pre>
+ /// <code>
+ /// IoTConnectivityClientManager.Initialize();
+ /// IoTConnectivityClientManager.PollingInterval = 100;
+ /// </code>
+ public static int PollingInterval
+ {
+ get
+ {
+ int interval;
+ int ret = Interop.IoTConnectivity.Client.IoTCon.GetPollingInterval(out interval);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Warn(IoTConnectivityErrorFactory.LogTag, "Failed to get polling interval");
+ return 0;
+ }
+ return interval;
+ }
+ set
+ {
+ int ret = Interop.IoTConnectivity.Client.IoTCon.SetPollingInterval(value);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to set polling interval");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ }
+
+ /// <summary>
+ /// Initializes IoTCon.
+ /// Call this function to start IoTCon.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <remarks>
+ /// @a filePath point to a file for handling secure virtual resources.
+ /// The file that is CBOR(Concise Binary Object Representation)-format must already exist
+ /// in @a filePath. We recommend to use application-local file for @a filePath.
+ /// </remarks>
+ /// <privilege>
+ /// http://tizen.org/privilege/network.get \n
+ /// http://tizen.org/privilege/internet
+ /// </privilege>
+ /// <privlevel>public</privlevel>
+ /// <param name="filePath">The file path to point to storage for handling secure virtual resources.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <post>
+ /// You must call Deinitialize() if IoTCon API is no longer needed.
+ /// </post>
+ /// <seealso cref="Deinitialize()"/>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
+ /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have privilege to access.</exception>
+ /// <code>
+ /// string filePath = "../../res/iotcon-test-svr-db-client.dat";
+ /// IoTConnectivityClientManager.Initialize(filePath);
+ /// </code>
+ public static void Initialize(string filePath)
+ {
+ int ret = Interop.IoTConnectivity.Client.IoTCon.Initialize(filePath);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to initialize");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+
+ /// <summary>
+ /// Deinitializes IoTCon.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <remarks>
+ /// This API must be called if IoTCon API is no longer needed.
+ /// </remarks>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <pre>
+ /// Initialize() should be called to initialize.
+ /// </pre>
+ /// <seealso cref="Initialize()"/>
+ /// <seealso cref="SecureInitialize()"/>
+ /// <code>
+ /// IoTConnectivityClientManager.Deinitialize();
+ /// </code>
+ public static void Deinitialize()
+ {
+ s_presenceListenerId = 1;
+ s_presenceCallbacksMap.Clear();
+ s_presenceHandlesMap.Clear();
+
+ s_requestId = 1;
+ s_resourceFoundCallbacksMap.Clear();
+ s_deviceInformationCallbacksMap.Clear();
+ s_platformInformationCallbacksMap.Clear();
+
+ PresenceReceived = delegate{};
+ ResourceFound = delegate{};
+ PlatformInformationFound = delegate{};
+ DeviceInformationFound = delegate{};
+ FindingErrorOccurred = delegate{};
+
+ Interop.IoTConnectivity.Client.IoTCon.Deinitialize();
+ }
+
+ /// <summary>
+ /// Invokes a next message from a queue for receiving messages from others, immediately.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <remarks>
+ /// This API invokes a next message from a queue for receiving messages from others, immediately.
+ /// After calling the API, it continues the polling with existing interval.
+ /// </remarks>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <pre>
+ /// Initialize() should be called to initialize.
+ /// </pre>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <code>
+ /// IoTConnectivityClientManager.InvokePolling();
+ /// </code>
+ public static void InvokePolling()
+ {
+ int ret = Interop.IoTConnectivity.Client.IoTCon.InvokePolling();
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to invoke polling");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+
+ /// <summary>
+ /// Starts receiving presence events.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <remarks>
+ /// Sends request to receive presence to an interested server's resource with resourceType.
+ /// If succeeded, <see cref="PresenceReceived"/> event handler will be triggered when the server sends presence.
+ /// A server sends presence events when adds / removes / alters a resource or start / stop presence.\n
+ /// @a hostAddress could be <see cref="MulticastAddress"/> for IPv4 multicast.
+ /// The length of @ resourceType should be less than or equal to 61. The @ resourceType must start with a lowercase alphabetic character, followed by a sequence
+ /// of lowercase alphabetic, numeric, ".", or "-" characters, and contains no white space.
+ /// </remarks>
+ /// <privilege>
+ /// http://tizen.org/privilege/internet
+ /// </privilege>
+ /// <privlevel>public</privlevel>
+ /// <param name="hostAddress">The address or addressable name of the server.</param>
+ /// <param name="resourceType">A resource type that a client is interested in.</param>
+ /// <returns>PresenceId - An identifier for this request.</returns>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <pre>Initialize() should be called to initialize.</pre>
+ /// <post>
+ /// When the resource receive presence, <see cref="PresenceReceived"/> event handler will be invoked.\n
+ /// You must destroy presence by calling StopReceivingPresence() if presence event is no longer needed.
+ /// </post>
+ /// <seealso cref="IoTConnectivityServerManager.StartSendingPresence()"/>
+ /// <seealso cref="IoTConnectivityServerManager.StopSendingPresence()"/>
+ /// <seealso cref="StopReceivingPresence()"/>
+ /// <seealso cref="PresenceReceived"/>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
+ /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have privilege to access.</exception>
+ /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory.</exception>
+ /// <code>
+ /// EventHandler<PresenceReceivedEventArgs> handler = (sender, e) => {
+ /// Console.Log("PresenceReceived, presence id :" + e.PresenceId);
+ /// }
+ /// EventHandler<FindingErrorOccurredEventArgs> errorHandler = (sender, e) => {
+ /// Console.Log("Found error :" + e.Error.Message);
+ /// }
+ /// IoTConnectivityClientManager.PresenceReceived += handler;
+ /// IoTConnectivityClientManager.FindingErrorOccurred += errorHandler;
+ /// // Do not forget to remove these event handlers when they are not required any more.
+ /// int id = IoTConnectivityClientManager.StartReceivingPresence(IoTConnectivityClientManager.MulticastAddress, "oic.iot.door");
+ /// </code>
+ public static int StartReceivingPresence(string hostAddress, string resourceType)
+ {
+ Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType connectivityType = Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType.Ip;
+
+ if (resourceType != null && !ResourceTypes.IsValid(resourceType))
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Invalid type");
+ throw new ArgumentException("Invalid type");
+ }
+
+ IntPtr id = IntPtr.Zero;
+ lock (s_presenceCallbacksMap)
+ {
+ id = (IntPtr)s_presenceListenerId++;
+ }
+ s_presenceCallbacksMap[id] = (IntPtr presence, int result, IntPtr presenceResponseHandle, IntPtr userData) =>
+ {
+ int presenceId = (int)userData;
+ if (result == (int)IoTConnectivityError.None)
+ {
+ if (presenceResponseHandle != IntPtr.Zero)
+ {
+ PresenceReceivedEventArgs e = GetPresenceReceivedEventArgs(presenceId, presenceResponseHandle);
+ if (e == null)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Can't get PresenceReceivedEventArgs");
+ return;
+ }
+ PresenceReceived?.Invoke(null, e);
+ }
+ else
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Handle is null");
+ return;
+ }
+ }
+ else
+ {
+ FindingErrorOccurredEventArgs e = GetFindingErrorOccurredEventArgs(presenceId, result);
+ FindingErrorOccurred?.Invoke(null, e);
+ }
+ };
+
+ IntPtr presenceHandle;
+ int errorCode = Interop.IoTConnectivity.Client.Presence.AddPresenceCb(hostAddress, (int)connectivityType, resourceType, s_presenceCallbacksMap[id], id, out presenceHandle);
+ if (errorCode != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to register presence event handler");
+ lock (s_presenceCallbacksMap)
+ {
+ s_presenceCallbacksMap.Remove(id);
+ }
+ throw IoTConnectivityErrorFactory.GetException(errorCode);
+ }
+
+ lock (s_presenceHandlesMap)
+ {
+ s_presenceHandlesMap[id] = presenceHandle;
+ }
+ return (int)id;
+ }
+
+ /// <summary>
+ /// Stops receiving presence events.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <remarks>
+ /// Sends request to not to receive server's presence any more.
+ /// </remarks>
+ /// <privilege>
+ /// http://tizen.org/privilege/internet
+ /// </privilege>
+ /// <privlevel>public</privlevel>
+ /// <param name="presenceId">The start presence request identifier.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <pre>
+ /// Initialize() should be called to initialize.
+ /// </pre>
+ /// <seealso cref="IoTConnectivityServerManager.StartSendingPresence()"/>
+ /// <seealso cref="IoTConnectivityServerManager.StopSendingPresence()"/>
+ /// <seealso cref="StartReceivingPresence()"/>
+ /// <seealso cref="PresenceReceived"/>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
+ /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have privilege to access.</exception>
+ /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory.</exception>
+ /// <code>
+ /// EventHandler<PresenceReceivedEventArgs> handler = (sender, e) => {
+ /// Console.Log("PresenceReceived, presence id :" + e.PresenceId);
+ /// }
+ /// EventHandler<FindingErrorOccurredEventArgs> errorHandler = (sender, e) => {
+ /// Console.Log("Found error :" + e.Error.Message);
+ /// }
+ /// IoTConnectivityClientManager.PresenceReceived += handler;
+ /// IoTConnectivityClientManager.FindingErrorOccurred += errorHandler;
+ /// int id = IoTConnectivityClientManager.StartReceivingPresence(IoTConnectivityClientManager.MulticastAddress, "oic.iot.door");
+ /// await Task.Delay(5000); // Do other things here
+ /// // Call StopReceivingPresence() when receiving presence is not required any more
+ /// IoTConnectivityClientManager.PresenceReceived -= handler;
+ /// IoTConnectivityClientManager.FindingErrorOccurred -= errorHandler;
+ /// IoTConnectivityClientManager.StopReceivingPresence(id);
+ /// </code>
+ public static void StopReceivingPresence(int presenceId)
+ {
+ if (!s_presenceHandlesMap.ContainsKey((IntPtr)presenceId))
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "this presenceId does not exist");
+ throw new ArgumentException("this presenceId does not exist");
+ }
+
+ if (s_presenceHandlesMap.ContainsKey((IntPtr)presenceId))
+ {
+ IntPtr presenceHandle = s_presenceHandlesMap[(IntPtr)presenceId];
+ int ret = Interop.IoTConnectivity.Client.Presence.RemovePresenceCb(presenceHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to deregister presence event handler");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+
+ lock (s_presenceHandlesMap)
+ {
+ s_presenceHandlesMap.Remove((IntPtr)presenceId);
+ }
+ }
+
+ if (s_presenceCallbacksMap.ContainsKey((IntPtr)presenceId))
+ {
+ lock (s_presenceCallbacksMap)
+ {
+ s_presenceCallbacksMap.Remove((IntPtr)presenceId);
+ }
+ }
+ }
+
+ /// <summary>
+ /// Starts finding resources.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <remarks>
+ /// Sends request to find a resource of @a hostAddress server with @a resourceType.
+ /// If succeeded, <see cref="ResourceFound"/> event handler will be triggered with information of the resource.\n
+ /// @a hostAddress could be <see cref="MulticastAddress"/> for the IPv4 multicast.
+ /// The length of @a resourceType should be less than or equal to 61. The @ resourceType must start with a lowercase alphabetic character, followed by a sequence
+ /// of lowercase alphabetic, numeric, ".", or "-" characters, and contains no white space.
+ /// </remarks>
+ /// <privilege>
+ /// http://tizen.org/privilege/internet
+ /// </privilege>
+ /// <privlevel>public</privlevel>
+ /// <param name="hostAddress">The address or addressable name of the server. The address includes a protocol like coaps://.</param>
+ /// <param name="query">The query specified as a filter for founding resources.</param>
+ /// <returns>RequestId - An identifier for this request.</returns>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <pre>Initialize() should be called to initialize.</pre>
+ /// <post>
+ /// When the resource is found, <see cref="ResourceFound"/> event handler will be invoked.
+ /// </post>
+ /// <seealso cref="ResourceFound"/>
+ /// <seealso cref="ResourceFoundEventArgs"/>
+ /// <seealso cref="TimeOut"/>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
+ /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have privilege to access.</exception>
+ /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory.</exception>
+ /// <code>
+ /// EventHandler<ResourceFoundEventArgs> handler = (sender, e) => {
+ /// Console.Log("Found resource at host address :" + e.Resource.HostAddress + ", uri :" + e.Resource.UriPath);
+ /// }
+ /// EventHandler<FindingErrorOccurredEventArgs> errorHandler = (sender, e) => {
+ /// Console.Log("Found error :" + e.Error.Message);
+ /// }
+ /// IoTConnectivityClientManager.ResourceFound += handler;
+ /// IoTConnectivityClientManager.FindingErrorOccurred += errorHandler;
+ /// ResourceQuery query = new ResourceQuery();
+ /// query.Type = "oic.iot.door";
+ /// // Do not forget to remove these event handlers when they are not required any more.
+ /// int id = IoTConnectivityClientManager.StartFindingResource(null, query);
+ /// </code>
+ public static int StartFindingResource(string hostAddress, ResourceQuery query = null)
+ {
+ Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType connectivityType = Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType.Ip;
+
+ IntPtr id = IntPtr.Zero;
+ lock (s_resourceFoundCallbacksMap)
+ {
+ id = (IntPtr)s_requestId++;
+ }
+ s_resourceFoundCallbacksMap[id] = (IntPtr remoteResourceHandle, int result, IntPtr userData) =>
+ {
+ if (ResourceFound == null)
+ return false;
+
+ int requestId = (int)userData;
+ if (result == (int)IoTConnectivityError.None)
+ {
+ if (remoteResourceHandle != IntPtr.Zero)
+ {
+ RemoteResource resource = null;
+ try
+ {
+ resource = new RemoteResource(remoteResourceHandle);
+ }
+ catch (Exception exp)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Can't clone RemoteResource's handle: " + exp.Message);
+ return true;
+ }
+ ResourceFoundEventArgs e = new ResourceFoundEventArgs()
+ {
+ RequestId = requestId,
+ Resource = resource
+ };
+ ResourceFound?.Invoke(null, e);
+ Log.Info(IoTConnectivityErrorFactory.LogTag, "e.EventContinue : " + e.EventContinue);
+ return e.EventContinue;
+ }
+ else
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Handle is null");
+ }
+ }
+ else
+ {
+ FindingErrorOccurredEventArgs e = GetFindingErrorOccurredEventArgs(requestId, result);
+ FindingErrorOccurred?.Invoke(null, e);
+
+ lock (s_resourceFoundCallbacksMap)
+ {
+ s_resourceFoundCallbacksMap.Remove(id);
+ }
+ }
+ return true;
+ };
+ IntPtr queryHandle = (query == null) ? IntPtr.Zero : query._resourceQueryHandle;
+ int errorCode = Interop.IoTConnectivity.Client.ResourceFinder.AddResourceFoundCb(hostAddress, (int)connectivityType, queryHandle, s_resourceFoundCallbacksMap[id], id);
+ if (errorCode != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to register resource found event handler");
+ lock (s_resourceFoundCallbacksMap)
+ {
+ s_resourceFoundCallbacksMap.Remove(id);
+ }
+ throw IoTConnectivityErrorFactory.GetException(errorCode);
+ }
+ return (int)id;
+ }
+
+ /// <summary>
+ /// Starts finding the device information of remote server.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <remarks>
+ /// Requests server for device information.
+ /// If succeeded, <see cref="DeviceInformationFound"/> event handler will be triggered with information of the device.\n
+ /// @a hostAddress could be <see cref="MulticastAddress"/> for the IPv4 multicast.
+ /// </remarks>
+ /// <privilege>
+ /// http://tizen.org/privilege/internet
+ /// </privilege>
+ /// <privlevel>public</privlevel>
+ /// <param name="hostAddress">The host address of the remote server.</param>
+ /// <param name="query">The query specified as a filter for founding resources.</param>
+ /// <returns>RequestId - An identifier for this request.</returns>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <pre>Initialize() should be called to initialize.</pre>
+ /// <post>
+ /// <see cref="DeviceInformationFound" /> event handler will be invoked.
+ /// </post>
+ /// <seealso cref="IoTConnectivityServerManager.SetDeviceName()"/>
+ /// <seealso cref="DeviceInformationFound"/>
+ /// <seealso cref="DeviceInformationFoundEventArgs"/>
+ /// <seealso cref="TimeOut"/>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
+ /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have privilege to access.</exception>
+ /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory.</exception>
+ /// <code>
+ /// EventHandler<DeviceInformationFoundEventArgs> handler = (sender, e) => {
+ /// Console.Log("Device information found, id : " + e.RequestId + ", name : " + e.Name);
+ /// }
+ /// EventHandler<FindingErrorOccurredEventArgs> errorHandler = (sender, e) => {
+ /// Console.Log("Found error :" + e.Error.Message);
+ /// }
+ /// IoTConnectivityClientManager.DeviceInformationFound += handler;
+ /// IoTConnectivityClientManager.FindingErrorOccurred += errorHandler;
+ /// // Do not forget to remove these event handlers when they are not required any more.
+ /// int id = IoTConnectivityClientManager.StartFindingDeviceInformation(IoTConnectivityClientManager.MulticastAddress);
+ /// </code>
+ public static int StartFindingDeviceInformation(string hostAddress, ResourceQuery query = null)
+ {
+ Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType connectivityType = Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType.Ip;
+
+ IntPtr id = IntPtr.Zero;
+ lock (s_deviceInformationCallbacksMap)
+ {
+ id = (IntPtr)s_requestId++;
+ }
+ s_deviceInformationCallbacksMap[id] = (IntPtr deviceInfoHandle, int result, IntPtr userData) =>
+ {
+ if (DeviceInformationFound == null)
+ return false;
+
+ int requestId = (int)userData;
+ if (result == (int)IoTConnectivityError.None)
+ {
+ if (deviceInfoHandle != IntPtr.Zero)
+ {
+ DeviceInformationFoundEventArgs e = GetDeviceInformationFoundEventArgs(requestId, deviceInfoHandle);
+ if (e == null)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Can't get DeviceInformationFoundEventArgs");
+ return true;
+ }
+ DeviceInformationFound?.Invoke(null, e);
+ Log.Info(IoTConnectivityErrorFactory.LogTag, "e.EventContinue : " + e.EventContinue);
+ return e.EventContinue;
+ }
+ else
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Handle is null");
+ }
+ }
+ else
+ {
+ FindingErrorOccurredEventArgs e = GetFindingErrorOccurredEventArgs(requestId, result);
+ FindingErrorOccurred?.Invoke(null, e);
+
+ lock (s_deviceInformationCallbacksMap)
+ {
+ s_deviceInformationCallbacksMap.Remove(id);
+ }
+ }
+ return true;
+ };
+
+ IntPtr queryHandle = (query == null) ? IntPtr.Zero : query._resourceQueryHandle;
+ int errorCode = Interop.IoTConnectivity.Client.DeviceInformation.Find(hostAddress, (int)connectivityType, queryHandle, s_deviceInformationCallbacksMap[id], id);
+ if (errorCode != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get device information");
+ lock (s_deviceInformationCallbacksMap)
+ {
+ s_deviceInformationCallbacksMap.Remove(id);
+ }
+ throw IoTConnectivityErrorFactory.GetException(errorCode);
+ }
+
+ return (int)id;
+ }
+
+ /// <summary>
+ /// Starts finding the platform information of remote server.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <remarks>
+ /// Requests server for platform information.
+ /// If succeeded, <see cref="PlatformInformationFound" /> event handler will be triggered with information of the platform.\n
+ /// @a hostAddress could be <see cref="MulticastAddress"/> for IPv4 multicast.
+ /// </remarks>
+ /// <privilege>
+ /// http://tizen.org/privilege/internet
+ /// </privilege>
+ /// <privlevel>public</privlevel>
+ /// <param name="hostAddress">The host address of remote server.</param>
+ /// <param name="query">The query specified as a filter for founding resources.</param>
+ /// <returns>RequestId - An identifier for this request.</returns>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <pre>Initialize() should be called to initialize.</pre>
+ /// <post>
+ /// <see cref="PlatformInformationFound" /> event handler will be invoked.
+ /// </post>
+ /// <seealso cref="PlatformInformationFound"/>
+ /// <seealso cref="PlatformInformationFoundEventArgs"/>
+ /// <seealso cref="TimeOut"/>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
+ /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have privilege to access.</exception>
+ /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory.</exception>
+ /// <code>
+ /// EventHandler<PlatformInformationFoundEventArgs> handler = (sender, e) => {
+ /// Console.Log("PlatformInformationFound :" + e.RequestId);
+ /// }
+ /// EventHandler<FindingErrorOccurredEventArgs> errorHandler = (sender, e) => {
+ /// Console.Log("Found error :" + e.Error.Message);
+ /// }
+ /// IoTConnectivityClientManager.PlatformInformationFound += handler;
+ /// IoTConnectivityClientManager.FindingErrorOccurred += errorHandler;
+ /// // Do not forget to remove these event handlers when they are not required any more.
+ /// int id = IoTConnectivityClientManager.StartFindingPlatformInformation(IoTConnectivityClientManager.MulticastAddress);
+ /// </code>
+ public static int StartFindingPlatformInformation(string hostAddress, ResourceQuery query = null)
+ {
+ Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType connectivityType = Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType.Ip;
+
+ IntPtr id = IntPtr.Zero;
+ lock (s_platformInformationCallbacksMap)
+ {
+ id = (IntPtr)s_requestId++;
+ }
+ s_platformInformationCallbacksMap[id] = (IntPtr platformInfoHandle, int result, IntPtr userData) =>
+ {
+ if (PlatformInformationFound == null)
+ return false;
+
+ int requestId = (int)userData;
+ if (result == (int)IoTConnectivityError.None)
+ {
+ if (platformInfoHandle != IntPtr.Zero)
+ {
+ PlatformInformationFoundEventArgs e = GetPlatformInformationFoundEventArgs(requestId, platformInfoHandle);
+ if (e == null)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Can't get PlatformInformationFoundEventArgs");
+ return true;
+ }
+ PlatformInformationFound?.Invoke(null, e);
+ Log.Info(IoTConnectivityErrorFactory.LogTag, "e.EventContinue : " + e.EventContinue);
+ return e.EventContinue;
+ }
+ else
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Handle is null");
+ }
+ }
+ else
+ {
+ FindingErrorOccurredEventArgs e = GetFindingErrorOccurredEventArgs(requestId, result);
+ FindingErrorOccurred?.Invoke(null, e);
+
+ lock (s_platformInformationCallbacksMap)
+ {
+ s_platformInformationCallbacksMap.Remove(id);
+ }
+ }
+ return true;
+ };
+
+ IntPtr queryHandle = (query == null) ? IntPtr.Zero : query._resourceQueryHandle;
+ int errorCode = Interop.IoTConnectivity.Client.PlatformInformation.Find(hostAddress, (int)connectivityType, queryHandle, s_platformInformationCallbacksMap[id], id);
+ if (errorCode != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get platform information");
+ lock (s_platformInformationCallbacksMap)
+ {
+ s_platformInformationCallbacksMap.Remove(id);
+ }
+ throw IoTConnectivityErrorFactory.GetException(errorCode);
+ }
+
+ return (int)id;
+ }
+
+ // Private methods
+ private static PresenceReceivedEventArgs GetPresenceReceivedEventArgs(int presenceId, IntPtr presenceResponseHandle)
+ {
+ int trigger;
+ IntPtr host, type;
+
+ int ret = Interop.IoTConnectivity.Client.PresenceResponse.GetHostAddress(presenceResponseHandle, out host);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get host address");
+ return null;
+ }
+
+ ret = Interop.IoTConnectivity.Client.PresenceResponse.GetResourceType(presenceResponseHandle, out type);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get resource type");
+ return null;
+ }
+
+ ret = Interop.IoTConnectivity.Client.PresenceResponse.GetTrigger(presenceResponseHandle, out trigger);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get event type");
+ return null;
+ }
+
+ PresenceReceivedEventArgs e = new PresenceReceivedEventArgs()
+ {
+ PresenceId = presenceId,
+ HostAddress = (host != IntPtr.Zero) ? Marshal.PtrToStringAnsi(host) : string.Empty,
+ Type = (type != IntPtr.Zero) ? Marshal.PtrToStringAnsi(type) : string.Empty,
+ EventType = (PresenceEventType)trigger
+ };
+
+ return e;
+ }
+
+ private static DeviceInformationFoundEventArgs GetDeviceInformationFoundEventArgs(int requestId, IntPtr deviceInfoHandle)
+ {
+ IntPtr name, specVersion, deviceId, dataModelVersion;
+
+ int ret = Interop.IoTConnectivity.Client.DeviceInformation.GetProperty(deviceInfoHandle, (int)Interop.IoTConnectivity.Client.DeviceInformation.Property.Name, out name);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get name");
+ return null;
+ }
+
+ ret = Interop.IoTConnectivity.Client.DeviceInformation.GetProperty(deviceInfoHandle, (int)Interop.IoTConnectivity.Client.DeviceInformation.Property.SpecVersion, out specVersion);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get spec version");
+ return null;
+ }
+
+ ret = Interop.IoTConnectivity.Client.DeviceInformation.GetProperty(deviceInfoHandle, (int)Interop.IoTConnectivity.Client.DeviceInformation.Property.Id, out deviceId);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get device id");
+ return null;
+ }
+
+ ret = Interop.IoTConnectivity.Client.DeviceInformation.GetProperty(deviceInfoHandle, (int)Interop.IoTConnectivity.Client.DeviceInformation.Property.DataModelVersion, out dataModelVersion);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get data model version");
+ return null;
+ }
+
+ DeviceInformationFoundEventArgs e = new DeviceInformationFoundEventArgs()
+ {
+ RequestId = requestId,
+ EventContinue = true,
+ Name = (name != IntPtr.Zero) ? Marshal.PtrToStringAnsi(name) : string.Empty,
+ SpecVersion = (specVersion != IntPtr.Zero) ? Marshal.PtrToStringAnsi(specVersion) : string.Empty,
+ DeviceId = (deviceId != IntPtr.Zero) ? Marshal.PtrToStringAnsi(deviceId) : string.Empty,
+ DataModelVersion = (dataModelVersion != IntPtr.Zero) ? Marshal.PtrToStringAnsi(dataModelVersion) : string.Empty
+ };
+
+ return e;
+ }
+
+ private static PlatformInformationFoundEventArgs GetPlatformInformationFoundEventArgs(int requestId, IntPtr platformInfoHandle)
+ {
+ IntPtr platformId, manufacturerName, manufacturerUrl, modelNumber, dateOfManufacture, platformVersion, osVersion, hardwareVersion, firmwareVersion, supportUrl, systemTime;
+
+ int ret = Interop.IoTConnectivity.Client.PlatformInformation.GetProperty(platformInfoHandle, (int)Interop.IoTConnectivity.Client.PlatformInformation.Propery.Id, out platformId);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get platform id");
+ return null;
+ }
+
+ ret = Interop.IoTConnectivity.Client.PlatformInformation.GetProperty(platformInfoHandle, (int)Interop.IoTConnectivity.Client.PlatformInformation.Propery.MfgName, out manufacturerName);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get manufacturer name");
+ return null;
+ }
+
+ ret = Interop.IoTConnectivity.Client.PlatformInformation.GetProperty(platformInfoHandle, (int)Interop.IoTConnectivity.Client.PlatformInformation.Propery.MfgUrl, out manufacturerUrl);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get manufacturer url");
+ return null;
+ }
+
+ ret = Interop.IoTConnectivity.Client.PlatformInformation.GetProperty(platformInfoHandle, (int)Interop.IoTConnectivity.Client.PlatformInformation.Propery.ModelNumber, out modelNumber);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get model number");
+ return null;
+ }
+
+ ret = Interop.IoTConnectivity.Client.PlatformInformation.GetProperty(platformInfoHandle, (int)Interop.IoTConnectivity.Client.PlatformInformation.Propery.DateOfMfg, out dateOfManufacture);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get date of manufacture");
+ return null;
+ }
+
+ ret = Interop.IoTConnectivity.Client.PlatformInformation.GetProperty(platformInfoHandle, (int)Interop.IoTConnectivity.Client.PlatformInformation.Propery.PlatformVer, out platformVersion);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get platform version");
+ return null;
+ }
+
+ ret = Interop.IoTConnectivity.Client.PlatformInformation.GetProperty(platformInfoHandle, (int)Interop.IoTConnectivity.Client.PlatformInformation.Propery.OsVer, out osVersion);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to os version");
+ return null;
+ }
+
+ ret = Interop.IoTConnectivity.Client.PlatformInformation.GetProperty(platformInfoHandle, (int)Interop.IoTConnectivity.Client.PlatformInformation.Propery.HardwareVer, out hardwareVersion);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to hardware version");
+ return null;
+ }
+
+ ret = Interop.IoTConnectivity.Client.PlatformInformation.GetProperty(platformInfoHandle, (int)Interop.IoTConnectivity.Client.PlatformInformation.Propery.FirmwareVer, out firmwareVersion);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get firmware version");
+ return null;
+ }
+
+ ret = Interop.IoTConnectivity.Client.PlatformInformation.GetProperty(platformInfoHandle, (int)Interop.IoTConnectivity.Client.PlatformInformation.Propery.SupportUrl, out supportUrl);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get support url");
+ return null;
+ }
+
+ ret = Interop.IoTConnectivity.Client.PlatformInformation.GetProperty(platformInfoHandle, (int)Interop.IoTConnectivity.Client.PlatformInformation.Propery.SystemTime, out systemTime);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get system time");
+ return null;
+ }
+
+ PlatformInformationFoundEventArgs e = new PlatformInformationFoundEventArgs()
+ {
+ RequestId = requestId,
+ PlatformId = (platformId != IntPtr.Zero) ? Marshal.PtrToStringAnsi(platformId) : string.Empty,
+ ManufacturerName = (manufacturerName != IntPtr.Zero) ? Marshal.PtrToStringAnsi(manufacturerName) : string.Empty,
+ ManufacturerURL = (manufacturerUrl != IntPtr.Zero) ? Marshal.PtrToStringAnsi(manufacturerUrl) : string.Empty,
+ DateOfManufacture = (dateOfManufacture != IntPtr.Zero) ? Marshal.PtrToStringAnsi(dateOfManufacture) : string.Empty,
+ ModelNumber = (modelNumber != IntPtr.Zero) ? Marshal.PtrToStringAnsi(modelNumber) : string.Empty,
+ PlatformVersion = (platformVersion != IntPtr.Zero) ? Marshal.PtrToStringAnsi(platformVersion) : string.Empty,
+ OsVersion = (osVersion != IntPtr.Zero) ? Marshal.PtrToStringAnsi(osVersion) : string.Empty,
+ HardwareVersion = (hardwareVersion != IntPtr.Zero) ? Marshal.PtrToStringAnsi(hardwareVersion) : string.Empty,
+ FirmwareVersion = (firmwareVersion != IntPtr.Zero) ? Marshal.PtrToStringAnsi(firmwareVersion) : string.Empty,
+ SupportUrl = (supportUrl != IntPtr.Zero) ? Marshal.PtrToStringAnsi(supportUrl) : string.Empty,
+ SystemTime = (systemTime != IntPtr.Zero) ? Marshal.PtrToStringAnsi(systemTime) : string.Empty
+ };
+
+ Log.Info(IoTConnectivityErrorFactory.LogTag, "e.RequestId is " + e.RequestId);
+ Log.Info(IoTConnectivityErrorFactory.LogTag, "e.PlatformId is " + e.PlatformId);
+ Log.Info(IoTConnectivityErrorFactory.LogTag, "e.ManufacturerName is " + e.ManufacturerName);
+ Log.Info(IoTConnectivityErrorFactory.LogTag, "e.ManufacturerURL is " + e.ManufacturerURL);
+ Log.Info(IoTConnectivityErrorFactory.LogTag, "e.DateOfManufacture is " + e.DateOfManufacture);
+ Log.Info(IoTConnectivityErrorFactory.LogTag, "e.ModelNumber is " + e.ModelNumber);
+ Log.Info(IoTConnectivityErrorFactory.LogTag, "e.PlatformVersion is " + e.PlatformVersion);
+ Log.Info(IoTConnectivityErrorFactory.LogTag, "e.OsVersion is " + e.OsVersion);
+ Log.Info(IoTConnectivityErrorFactory.LogTag, "e.HardwareVersion is " + e.HardwareVersion);
+ Log.Info(IoTConnectivityErrorFactory.LogTag, "e.FirmwareVersion is " + e.FirmwareVersion);
+ Log.Info(IoTConnectivityErrorFactory.LogTag, "e.SupportUrl is " + e.SupportUrl);
+ Log.Info(IoTConnectivityErrorFactory.LogTag, "e.SystemTime is " + e.SystemTime);
+
+ return e;
+ }
+
+ private static FindingErrorOccurredEventArgs GetFindingErrorOccurredEventArgs(int requestId, int err)
+ {
+ FindingErrorOccurredEventArgs e = new FindingErrorOccurredEventArgs()
+ {
+ RequestId = requestId,
+ Error = IoTConnectivityErrorFactory.GetException(err)
+ };
+ return e;
+ }
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+using System;
+using System.IO;
+using Tizen.Internals.Errors;
+
+namespace Tizen.Network.IoTConnectivity
+{
+ internal enum IoTConnectivityError
+ {
+ None = ErrorCode.None,
+ InvalidParameter = ErrorCode.InvalidParameter,
+ OutOfMemory = ErrorCode.OutOfMemory,
+ Io = ErrorCode.IoError,
+ PermissionDenied = ErrorCode.PermissionDenied,
+ NotSupported = ErrorCode.NotSupported,
+ NoData = ErrorCode.NoData,
+ TimedOut = ErrorCode.TimedOut,
+ Iotivity = -0x01C80000 | 0x01,
+ Representation = -0x01C80000 | 0x02,
+ InvalidType = -0x01C80000 | 0x03,
+ Already = -0x01C80000 | 0x04,
+ System = -0x01C80000 | 0x06,
+ }
+
+ internal static class IoTConnectivityErrorFactory
+ {
+ internal const string LogTag = "Tizen.Network.IoTConnectivity";
+
+ internal static void ThrowException(int err)
+ {
+ throw GetException(err);
+ }
+
+ internal static Exception GetException(int err)
+ {
+ IoTConnectivityError error = (IoTConnectivityError)err;
+ if (error == IoTConnectivityError.OutOfMemory)
+ {
+ return new OutOfMemoryException("Out of memory");
+ }
+ else if (error == IoTConnectivityError.InvalidParameter)
+ {
+ return new ArgumentException("Invalid parameter");
+ }
+ else if (error == IoTConnectivityError.Io)
+ {
+ return new IOException("I/O Error");
+ }
+ else if (error == IoTConnectivityError.NoData)
+ {
+ return new InvalidOperationException("No data found");
+ }
+ else if (error == IoTConnectivityError.TimedOut)
+ {
+ return new TimeoutException("timed out");
+ }
+ else if (error == IoTConnectivityError.PermissionDenied)
+ {
+ return new UnauthorizedAccessException("Permission denied");
+ }
+ else if (error == IoTConnectivityError.NotSupported)
+ {
+ return new NotSupportedException("Not supported");
+ }
+ else if (error == IoTConnectivityError.Representation)
+ {
+ return new InvalidOperationException("Representation error");
+ }
+ else if (error == IoTConnectivityError.InvalidType)
+ {
+ return new ArgumentException("Invalid type");
+ }
+ else if (error == IoTConnectivityError.Already)
+ {
+ return new InvalidOperationException("Duplicate");
+ }
+ else if (error == IoTConnectivityError.System)
+ {
+ return new InvalidOperationException("System error");
+ }
+ else
+ {
+ return new InvalidOperationException("Invalid operation");
+ }
+ }
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System;
+using System.Collections.Generic;
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// IoT connectivity server manager consists of server side APIs.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public static class IoTConnectivityServerManager
+ {
+ private static int s_requestId = 1;
+ private static Dictionary<IntPtr, Interop.IoTConnectivity.Server.Resource.RequestHandlerCallback> s_RequestHandlerCallbackMap = new Dictionary<IntPtr, Interop.IoTConnectivity.Server.Resource.RequestHandlerCallback>();
+
+ /// <summary>
+ /// Initializes IoTCon. Calls this API to start IoTCon.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <remarks>
+ /// @a filePath point to a file for handling secure virtual resources.
+ /// The file that is CBOR(Concise Binary Object Representation)-format must already exist
+ /// in @a filePath. We recommend to use application-local file for @a filePath.
+ /// </remarks>
+ /// <privilege>
+ /// http://tizen.org/privilege/network.get \n
+ /// http://tizen.org/privilege/internet
+ /// </privilege>
+ /// <privlevel>public</privlevel>
+ /// <param name="filePath">The file path to point to storage for handling secure virtual resources.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <post>
+ /// You must call Deinitialize() if IoTCon API is no longer needed.
+ /// </post>
+ /// <seealso cref="Deinitialize()"/>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
+ /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have privilege to access</exception>
+ /// <code>
+ /// string filePath = "../../res/iotcon-test-svr-db-server.dat";
+ /// IoTConnectivityServerManager.Initialize(filePath);
+ /// </code>
+ public static void Initialize(string filePath)
+ {
+ int ret = Interop.IoTConnectivity.Client.IoTCon.Initialize(filePath);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to initialize");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+
+ /// <summary>
+ /// Deinitializes IoTCon.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <remarks>
+ /// This API must be called if IoTCon API is no longer needed.
+ /// </remarks>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <pre>
+ /// Initialize() should be called to initialize.
+ /// </pre>
+ /// <seealso cref="Initialize()"/>
+ /// <code>
+ /// IoTConnectivityServerManager.Deinitialize();
+ /// </code>
+ public static void Deinitialize()
+ {
+ _resources.Clear();
+ s_requestId = 1;
+ s_RequestHandlerCallbackMap.Clear();
+
+ Interop.IoTConnectivity.Client.IoTCon.Deinitialize();
+ }
+
+ /// <summary>
+ /// Registers a resource in IoTCon server.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <privilege>
+ /// http://tizen.org/privilege/internet
+ /// </privilege>
+ /// <privlevel>public</privlevel>
+ /// <param name="resource">The resource to register.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <pre>
+ /// Initialize() should be called to initialize.
+ /// </pre>
+ /// <seealso cref="Resource"/>
+ /// <seealso cref="LiteResource"/>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
+ /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory.</exception>
+ /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have privilege to access.</exception>
+ /// <code>
+ /// ResourceTypes types = new ResourceTypes(new List<string>(){ "org.tizen.light" });
+ /// Attributes attributes = new Attributes { { "state", "ON" }};
+ /// Resource res = new LiteResource("/room/1", types, ResourcePolicy.Discoverable, attributes);
+ /// try {
+ /// IoTConnectivityServerManager.RegisterResource(res);
+ /// } catch(Exception ex) {
+ /// Console.Log("Exception caught : " + ex.Message);
+ /// }
+ /// </code>
+ public static void RegisterResource(Resource resource)
+ {
+ Log.Info(IoTConnectivityErrorFactory.LogTag, "...");
+
+ IntPtr id = IntPtr.Zero;
+ lock (s_RequestHandlerCallbackMap)
+ {
+ id = (IntPtr)s_requestId++;
+ }
+
+ s_RequestHandlerCallbackMap[id] = (IntPtr r_resource, IntPtr request, IntPtr userData) =>
+ {
+ int requestId = (int)userData;
+
+ Log.Info(IoTConnectivityErrorFactory.LogTag, "Received s_RequestHandlerCallbackMap : " + requestId);
+
+ if (request == IntPtr.Zero)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "request is IntPtr.Zero");
+ return;
+ }
+ resource.OnRequest(r_resource, request, userData);
+ };
+
+ IntPtr handle = IntPtr.Zero;
+ int errorCode = Interop.IoTConnectivity.Server.Resource.Create(resource.UriPath, resource.Types._resourceTypeHandle, resource.Interfaces.ResourceInterfacesHandle, (int)resource.Policy, s_RequestHandlerCallbackMap[id], id, out handle);
+ if (errorCode != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed create resource");
+ lock (s_RequestHandlerCallbackMap)
+ {
+ s_RequestHandlerCallbackMap.Remove(id);
+ }
+ throw IoTConnectivityErrorFactory.GetException(errorCode);
+ }
+ else
+ {
+ resource.ResourceHandle = handle;
+ }
+ _resources.Add(resource);
+ }
+
+ /// <summary>
+ /// Unregisters a resource in IoTCon server.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <privilege>
+ /// http://tizen.org/privilege/internet
+ /// </privilege>
+ /// <privlevel>public</privlevel>
+ /// <param name="resource">The resource to unregister.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <pre>
+ /// Initialize() should be called to initialize.
+ /// </pre>
+ /// <seealso cref="Resource"/>
+ /// <seealso cref="LiteResource"/>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have privilege to access.</exception>
+ /// <code>
+ /// ResourceTypes types = new ResourceTypes(new List<string>(){ "org.tizen.light" });
+ /// Attributes attributes = new Attributes { { "state", "ON" }};
+ /// Resource res = new LiteResource("/room/1", types, ResourcePolicy.Discoverable, attributes);
+ /// IoTConnectivityServerManager.RegisterResource(res);
+ /// try {
+ /// IoTConnectivityServerManager.UnregisterResource(res);
+ /// } catch(Exception ex) {
+ /// Console.Log("Exception caught : " + ex.Message);
+ /// }
+ /// </code>
+ public static void UnregisterResource(Resource resource)
+ {
+ if (resource != null)
+ {
+ if (resource.ResourceHandle != IntPtr.Zero)
+ {
+ Interop.IoTConnectivity.Server.Resource.Destroy(resource.ResourceHandle);
+ resource.ResourceHandle = IntPtr.Zero;
+ }
+
+ _resources.Remove(resource);
+ }
+ }
+
+ /// <summary>
+ /// Starts presence of a server.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <remarks>
+ /// Use this API to send server's announcements to clients.
+ /// Server can call this API when online for the first time or come back from offline to online.\n
+ /// If @a time is 0, server will set default value as 60 seconds.\n
+ /// If @a time is very big, server will set maximum value as (60 * 60 * 24) seconds, (24 hours).
+ /// </remarks>
+ /// <privilege>
+ /// http://tizen.org/privilege/internet
+ /// </privilege>
+ /// <privlevel>public</privlevel>
+ /// <param name="time">The interval of announcing presence in seconds.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <pre>
+ /// Initialize() should be called to initialize.
+ /// </pre>
+ /// <seealso cref="IoTConnectivityClientManager.StartReceivingPresence()"/>
+ /// <seealso cref="IoTConnectivityClientManager.StopReceivingPresence()"/>
+ /// <seealso cref="IoTConnectivityClientManager.PresenceReceived"/>
+ /// <seealso cref="StopSendingPresence()"/>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
+ /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have privilege to access.</exception>
+ /// <code>
+ /// try {
+ /// IoTConnectivityServerManager.StartSendingPresence(120);
+ /// } catch(Exception ex) {
+ /// Console.Log("Exception caught : " + ex.Message);
+ /// }
+ /// </code>
+ public static void StartSendingPresence(uint time)
+ {
+ int ret = Interop.IoTConnectivity.Server.IoTCon.StartPresence(time);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to start presence");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+
+ /// <summary>
+ /// Stops presence of a server.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <remarks>
+ /// Use this API to stop sending server's announcements to clients.
+ /// Server can call this API when terminating, entering to offline or out of network.
+ /// </remarks>
+ /// <privilege>
+ /// http://tizen.org/privilege/internet
+ /// </privilege>
+ /// <privlevel>public</privlevel>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <pre>
+ /// Initialize() should be called to initialize.
+ /// </pre>
+ /// <seealso cref="IoTConnectivityClientManager.StartReceivingPresence()"/>
+ /// <seealso cref="IoTConnectivityClientManager.StopReceivingPresence()"/>
+ /// <seealso cref="IoTConnectivityClientManager.PresenceReceived"/>
+ /// <seealso cref="StartSendingPresence()"/>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
+ /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have privilege to access.</exception>
+ /// <code>
+ /// IoTConnectivityServerManager.StopSendingPresence();
+ /// </code>
+ public static void StopSendingPresence()
+ {
+ int ret = Interop.IoTConnectivity.Server.IoTCon.StopPresence();
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed cancel presence");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+
+ /// <summary>
+ /// Sets the device name.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <remarks>
+ /// This API sets the name of the local device (the device calling the API).\n
+ /// If the device name is set, clients can get the name using <see cref="IoTConnectivityClientManager.StartFindingDeviceInformation()"/>.
+ /// </remarks>
+ /// <param name="deviceName">The device name.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <seealso cref="IoTConnectivityClientManager.DeviceInformationFound"/>
+ /// <seealso cref="IoTConnectivityClientManager.StartFindingDeviceInformation()"/>
+ /// <seealso cref="DeviceInformationFoundEventArgs"/>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
+ /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have privilege to access.</exception>
+ /// <code>
+ /// IoTConnectivityServerManager.SetDeviceName("my-tizen");
+ /// </code>
+ public static void SetDeviceName(string deviceName)
+ {
+ int ret = Interop.IoTConnectivity.Server.IoTCon.SetDeviceName(deviceName);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed set device name");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ private static List<Resource> _resources = new List<Resource>();
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// This class represents a lite resource.
+ /// It provides APIs to encapsulate resources.
+ /// This class is accessed by using a constructor to create a new instance of this object.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public class LiteResource : Resource
+ {
+ /// <summary>
+ /// The LiteResource constructor.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <remarks>
+ /// Creates a lite resource, which can then be registered in server using <see cref="IoTConnectivityServerManager.RegisterResource()"/>.\n
+ /// When client requests some operations, it sends a response to client automatically.\n
+ /// @a uri length must be less than 128.
+ /// </remarks>
+ /// <privilege>
+ /// http://tizen.org/privilege/internet
+ /// </privilege>
+ /// <privlevel>public</privlevel>
+ /// <param name="uri">The uri path of the lite resource.</param>
+ /// <param name="types">The type of the resource.</param>
+ /// <param name="policy">Policy of the resource.</param>
+ /// <param name="attribs">Optional attributes of the resource.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <pre>
+ /// IoTConnectivityServerManager.Initialize() should be called to initialize.
+ /// </pre>
+ /// <seealso cref="ResourceTypes"/>
+ /// <seealso cref="ResourcePolicy"/>
+ /// <seealso cref="Attributes"/>
+ /// <code>
+ /// List<string> list = new List<string>() { "org.tizen.light" };
+ /// Attributes attributes = new Attributes() {
+ /// { "state", "ON" }
+ /// };
+ /// LiteResource res = new LiteResource("/light/1", new ResourceTypes(list), ResourcePolicy.Discoverable, attributes);
+ /// </code>
+ public LiteResource(string uri, ResourceTypes types, ResourcePolicy policy, Attributes attribs = null)
+ : base(uri, types, new ResourceInterfaces(new string[] { ResourceInterfaces.DefaultInterface }), policy)
+ {
+ Attributes = attribs;
+ }
+
+ /// <summary>
+ /// Gets or sets the attributes of the lite resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The attributes of the lite resource.</value>
+ /// <code>
+ /// List<string> list = new List<string>() { "org.tizen.light" };
+ /// LiteResource res = new LiteResource("/light/1", new ResourceTypes(list), ResourcePolicy.Discoverable);
+ /// Attributes attributes = new Attributes() {
+ /// { "state", "ON" }
+ /// };
+ /// res.Attributes = newAttributes;
+ /// foreach (KeyValuePair<string, object> pair in res.Attributes)
+ /// {
+ /// Console.WriteLine("key : {0}, value : {1}", pair.Key, pair.Value);
+ /// }
+ /// </code>
+ public Attributes Attributes { get; set; }
+
+ /// <summary>
+ /// Decides whether to accept or reject a post request.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <remarks>
+ /// Child classes of this class can override this method to accept or reject post request.
+ /// </remarks>
+ /// <param name="attribs">The new attributes of the lite resource.</param>
+ /// <returns>true to accept post request, false to reject it.</returns>
+ /// <code>
+ /// public class MyLightResource : LiteResource
+ /// {
+ /// protected override bool OnPost(Attributes attributes)
+ /// {
+ /// object newAttributes;
+ /// attributes.TryGetValue("LIGHT_ATTRIBUTE", out newAttributes);
+ /// if((int)newAttributes == 1)
+ /// return true;
+ /// return false;
+ /// }
+ /// }
+ /// </code>
+ protected virtual bool OnPost(Attributes attribs)
+ {
+ return true;
+ }
+
+ // The code block untill @endcond should not appear in doxygen spec.
+ /// @cond
+ protected sealed override Response OnGet(Request request)
+ {
+ Representation representation = new Representation()
+ {
+ UriPath = UriPath,
+ Interface = Interfaces,
+ Type = Types,
+ Attributes = Attributes
+ };
+
+ Response response = new Response()
+ {
+ Representation = representation,
+ Result = ResponseCode.Ok
+ };
+
+ return response;
+ }
+
+ protected sealed override Response OnPut(Request request)
+ {
+ Response response = new Response();
+ response.Result = ResponseCode.Forbidden;
+ return response;
+ }
+
+ protected sealed override Response OnPost(Request request)
+ {
+ if (OnPost(request.Representation.Attributes))
+ {
+ Attributes = request.Representation.Attributes;
+ Representation representation = new Representation() {
+ UriPath = UriPath,
+ Interface = Interfaces,
+ Type = Types,
+ Attributes = Attributes
+ };
+
+ Response response = new Response() {
+ Representation = representation,
+ Result = ResponseCode.Ok
+ };
+
+ Notify(representation, QualityOfService.High);
+ return response;
+ }
+
+ return new Response()
+ {
+ Result = ResponseCode.Error
+ };
+ }
+
+ protected sealed override Response OnDelete(Request request)
+ {
+ Response response = new Response();
+ response.Result = ResponseCode.Forbidden;
+ return response;
+ }
+
+ protected sealed override bool OnObserving(Request request, ObserveType observeType, int observeId)
+ {
+ return true;
+ }
+ /// @endcond
+ }
+}
--- /dev/null
+/**
+<summary>
+The Tizen.Network.IoTConnectivity namespace provides classes to manage
+Resource, RemoteResource, Request, Response and so on which are based on IoTivity project.
+</summary>
+<remarks>
+The Tizen.Network.IoTConnectivity namespace provides classes to manage
+Resource, RemoteResource, Request, Response and so on which are based on IoTivity project.
+</remarks>
+*/
+namespace Tizen.Network.IoTConnectivity {}
+
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// Enumeration for the policy of observation.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public enum ObservePolicy
+ {
+ /// <summary>
+ /// Indicates the observation request for the most up-to-date notifications only.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ IgnoreOutOfOrder = 0,
+ /// <summary>
+ /// Indicates the observation request for all notifications including state notifications.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ AcceptOutOfOrder
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// Enumeration for the type of observation.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public enum ObserveType
+ {
+ /// <summary>
+ /// No observe action.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ NoType = 0,
+
+ /// <summary>
+ /// Indicates an action of the registering observation.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ Register = 1,
+
+ /// <summary>
+ /// Indicates an action of unregistering observation.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ Deregister = 2,
+ }
+}
+
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+using System;
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// This class represents event arguments of the ObserverNotified event.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public class ObserverNotifiedEventArgs : EventArgs
+ {
+ internal ObserverNotifiedEventArgs() { }
+
+ /// <summary>
+ /// Result of the observe response.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>Result of the observe response.</value>
+ public ResponseCode Result { get; internal set; }
+
+ /// <summary>
+ /// Representation of the resource being observed.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>Representation of the resource being observed.</value>
+ public Representation Representation { get; internal set; }
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// This class represents event arguments of the PlatformInformationFound event.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public class PlatformInformationFoundEventArgs
+ {
+ internal PlatformInformationFoundEventArgs() { }
+
+ /// <summary>
+ /// Indicates the request ID.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The request ID.</value>
+ public int RequestId { get; internal set; }
+
+ /// <summary>
+ /// Indicates to continuously receive the event for finding the platform information.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>Continuously receive the event for finding the platform information.</value>
+ public bool EventContinue { get; set; }
+
+ /// <summary>
+ /// Indicates the platform identifier.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The platform identifier.</value>
+ public string PlatformId { get; internal set; }
+
+ /// <summary>
+ /// Indicates the name of the manufacturer.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The name of the manufacturer.</value>
+ public string ManufacturerName { get; internal set; }
+
+ /// <summary>
+ /// Indicates the URL of the manufacturer.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The URL of the manufacturer.</value>
+ public string ManufacturerURL { get; internal set; }
+
+ /// <summary>
+ /// Indicates the model number as designated by the manufacturer.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The model number as designated by the manufacturer.</value>
+ public string ModelNumber { get; internal set; }
+
+ /// <summary>
+ /// Indicates the manufacturing date of the device.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The manufacturing date of the device.</value>
+ public string DateOfManufacture { get; internal set; }
+
+ /// <summary>
+ /// Indicates the version of the platfrom defined by the manufacturer.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The version of platfrom defined by manufacturer.</value>
+ public string PlatformVersion { get; internal set; }
+
+ /// <summary>
+ /// Indicates the version of the platfrom resident OS.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The version of the platfrom resident OS.</value>
+ public string OsVersion { get; internal set; }
+
+ /// <summary>
+ /// Indicates the version of the platform Hardware.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The version of the platform Hardware.</value>
+ public string HardwareVersion { get; internal set; }
+
+ /// <summary>
+ /// Indicates the version of the device firmware.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The version of the device firmware.</value>
+ public string FirmwareVersion { get; internal set; }
+
+ /// <summary>
+ /// Indicates the URL that points to support information from the manufacturer.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The URL that points to support information from the manufacturer.</value>
+ public string SupportUrl { get; internal set; }
+
+ /// <summary>
+ /// Indicates the reference time of the device.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The reference time of the device.</value>
+ public string SystemTime { get; internal set; }
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// Enumeration for operation of presence response.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public enum PresenceEventType
+ {
+ /// <summary>
+ /// Indicates the resource creation operation of the server.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ ResourceCreated = 0,
+ /// <summary>
+ /// Indicates the resource updation operation of the server.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ ResourceUpdated,
+ /// <summary>
+ /// Indicates the resource destruction operation of the server.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ ResourceDestroyed
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+using System;
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// This class represents event arguments of the PresenceReceived event.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public class PresenceReceivedEventArgs : EventArgs
+ {
+ internal PresenceReceivedEventArgs() { }
+
+ /// <summary>
+ /// Indicates the request ID of the presence event.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The request ID of the presence event.</value>
+ public int PresenceId { get; internal set; }
+
+ /// <summary>
+ /// Indicates the event type.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The event type.</value>
+ public PresenceEventType EventType { get; internal set; }
+
+ /// <summary>
+ /// Indicates the host address of resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The host address of resource.</value>
+ public string HostAddress { get; internal set; }
+
+ /// <summary>
+ /// Indicates the type of the resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The type of the resource.</value>
+ public string Type { get; internal set; }
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// Enumeration for states of remote resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public enum QualityOfService
+ {
+ /// <summary>
+ /// Indicates the low quality of service.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ Low = 0,
+ /// <summary>
+ /// Indicates the high quality of service.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ High
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+using System;
+using System.Collections.Generic;
+using System.Net;
+using System.Runtime.InteropServices;
+using System.Threading.Tasks;
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// This class represents a remote resource.
+ /// It provides APIs to manage remote resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public class RemoteResource : IDisposable
+ {
+ internal const int TimeOutMax = 3600;
+ internal IntPtr _remoteResourceHandle = IntPtr.Zero;
+
+ private bool _disposed = false;
+ private bool _cacheEnabled = false;
+ private ResourceOptions _options;
+
+ private int _responseCallbackId = 1;
+ private static Dictionary<IntPtr, Interop.IoTConnectivity.Client.RemoteResource.ResponseCallback> _responseCallbacksMap = new Dictionary<IntPtr, Interop.IoTConnectivity.Client.RemoteResource.ResponseCallback>();
+
+ private Interop.IoTConnectivity.Client.RemoteResource.CachedRepresentationChangedCallback _cacheUpdatedCallback;
+ private Interop.IoTConnectivity.Client.RemoteResource.StateChangedCallback _stateChangedCallback;
+ private Interop.IoTConnectivity.Client.RemoteResource.ObserveCallback _observeCallback;
+
+ private EventHandler<StateChangedEventArgs> _stateChangedEventHandler;
+
+ /// <summary>
+ /// Creates a remote resource instance.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <remarks>
+ /// To use this API, you should provide all the details required to correctly contact and
+ /// observe the object.\n
+ /// If not, you should discover the resource object manually.\n
+ /// The @a policy can contain multiple policies like ResourcePolicy.Discoverable | ResourcePolicy.Observable.
+ /// </remarks>
+ /// <param name="hostAddress">The host address of the resource.</param>
+ /// <param name="uriPath">The URI path of the resource.</param>
+ /// <param name="policy">The policies of the resource.</param>
+ /// <param name="resourceTypes">The resource types of the resource.</param>
+ /// <param name="resourceInterfaces">The resource interfaces of the resource.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory.</exception>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
+ public RemoteResource(string hostAddress, string uriPath, ResourcePolicy policy, ResourceTypes resourceTypes, ResourceInterfaces resourceInterfaces)
+ {
+ if (hostAddress == null || uriPath == null || resourceTypes == null || resourceInterfaces == null)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Invalid parameters");
+ throw new ArgumentException("Invalid parameter");
+ }
+
+ HostAddress = hostAddress;
+ UriPath = uriPath;
+ Policy = policy;
+ Types = new List<string>(resourceTypes);
+ Interfaces = new List<string>(resourceInterfaces);
+ DeviceId = null;
+
+ CreateRemoteResource(resourceTypes._resourceTypeHandle, resourceInterfaces.ResourceInterfacesHandle);
+ }
+
+ internal RemoteResource(IntPtr handleToClone)
+ {
+ int ret = Interop.IoTConnectivity.Client.RemoteResource.Clone(handleToClone, out _remoteResourceHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Faled to clone");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ SetRemoteResource();
+ }
+
+ /// <summary>
+ /// Destructor of the RemoteResource class.
+ /// </summary>
+ ~RemoteResource()
+ {
+ Dispose(false);
+ }
+
+ /// <summary>
+ /// The event is invoked with cached resource attributes.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public event EventHandler<CacheUpdatedEventArgs> CacheUpdated;
+
+ /// <summary>
+ /// Observe an event on the resource sent by the server.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public event EventHandler<ObserverNotifiedEventArgs> ObserverNotified;
+
+ /// <summary>
+ /// The event is called when remote resource's state are changed.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public event EventHandler<StateChangedEventArgs> StateChanged
+ {
+ add
+ {
+ if (_stateChangedEventHandler == null)
+ {
+ RegisterStateChangedEvent();
+ }
+ _stateChangedEventHandler += value;
+ }
+ remove
+ {
+ _stateChangedEventHandler -= value;
+ if (_stateChangedEventHandler == null)
+ {
+ UnregisterStateChangedEvent();
+ }
+ }
+ }
+
+ /// <summary>
+ /// The host address of the resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The host address of the resource.</value>
+ public string HostAddress { get; private set; }
+
+ /// <summary>
+ /// The URI path of the resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The URI path of the resource.</value>
+ public string UriPath { get; private set; }
+
+ /// <summary>
+ /// The resource types of the remote resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The resource types of the remote resource.</value>
+ public IEnumerable<string> Types { get; private set; }
+
+ /// <summary>
+ /// The interfaces of the resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The interfaces of the resource.</value>
+ public IEnumerable<string> Interfaces { get; private set; }
+
+ /// <summary>
+ /// The policy of the resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The policy of the resource.</value>
+ public ResourcePolicy Policy { get; private set; }
+
+ /// <summary>
+ /// The header options of the resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The header options of the resource.</value>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
+ public ResourceOptions Options
+ {
+ get
+ {
+ return _options;
+ }
+ set
+ {
+ _options = value;
+ if (value != null)
+ {
+ int ret = Interop.IoTConnectivity.Client.RemoteResource.SetOptions(_remoteResourceHandle, value._resourceOptionsHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to set options");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// Indicates the CacheEnabled status of the remote resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>
+ /// Client can start caching only when this is set true. Set it to false to stop caching the resource attributes.
+ /// </value>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
+ /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have privilege to access.</exception>
+ /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory.</exception>
+ public bool CacheEnabled
+ {
+ get
+ {
+ return _cacheEnabled;
+ }
+ set
+ {
+ if (_cacheEnabled != value)
+ {
+ _cacheEnabled = value;
+ HandleCachePolicyChanged();
+ }
+ }
+ }
+
+ /// <summary>
+ /// Time interval of monitoring and caching API.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>
+ /// Default time interval is 10 seconds.
+ /// Seconds for time interval (must be in range from 1 to 3600).
+ /// </value>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
+ public int TimeInterval
+ {
+ get
+ {
+ int interval;
+ int ret = Interop.IoTConnectivity.Client.RemoteResource.GetTimeInterval(_remoteResourceHandle, out interval);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Warn(IoTConnectivityErrorFactory.LogTag, "Failed to get time interval");
+ return 0;
+ }
+ return interval;
+ }
+ set
+ {
+ int ret = (int)IoTConnectivityError.InvalidParameter;
+ if (value <= TimeOutMax && value > 0)
+ {
+ ret = Interop.IoTConnectivity.Client.RemoteResource.SetTimeInterval(_remoteResourceHandle, value);
+ }
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to set time interval");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ }
+
+ /// <summary>
+ /// The device ID of the resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The device ID of the resource.</value>
+ public string DeviceId { get; private set; }
+
+ /// <summary>
+ /// Gets cached representation from the remote resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <returns>cached representation from the remote resource.</returns>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ public Representation CachedRepresentation()
+ {
+ IntPtr handle;
+ int ret = Interop.IoTConnectivity.Client.RemoteResource.GetCachedRepresentation(_remoteResourceHandle, out handle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Warn(IoTConnectivityErrorFactory.LogTag, "Failed to get CachedRepresentation");
+ return null;
+ }
+
+ Representation representation = new Representation(handle);
+ return representation;
+ }
+
+ /// <summary>
+ /// Starts observing on the resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <remarks>
+ /// When server sends notification message, <see cref="ObserverNotified"/> will be called.
+ /// </remarks>
+ /// <privilege>
+ /// http://tizen.org/privilege/internet
+ /// </privilege>
+ /// <privlevel>public</privlevel>
+ /// <param name="policy">The type to specify how client wants to observe.</param>
+ /// <param name="query">The query to send to server.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
+ /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have privilege to access.</exception>
+ /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory.</exception>
+ public void StartObserving(ObservePolicy policy, ResourceQuery query = null)
+ {
+ _observeCallback = (IntPtr resource, int err, int sequenceNumber, IntPtr response, IntPtr userData) =>
+ {
+ int result;
+ IntPtr representationHandle;
+ int ret = Interop.IoTConnectivity.Server.Response.GetResult(response, out result);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get result");
+ return;
+ }
+
+ ret = Interop.IoTConnectivity.Server.Response.GetRepresentation(response, out representationHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get representation");
+ return;
+ }
+
+ Representation repr = null;
+ try
+ {
+ repr = new Representation(representationHandle);
+ }
+ catch (Exception exp)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to new representation: " + exp.Message);
+ return;
+ }
+
+ ObserverNotifiedEventArgs e = new ObserverNotifiedEventArgs()
+ {
+ Representation = repr,
+ Result = (ResponseCode)result
+ };
+ ObserverNotified?.Invoke(this, e);
+ };
+
+ IntPtr queryHandle = IntPtr.Zero;
+ if (query != null)
+ {
+ queryHandle = query._resourceQueryHandle;
+ }
+
+ int errCode = Interop.IoTConnectivity.Client.RemoteResource.RegisterObserve(_remoteResourceHandle, (int)policy, queryHandle, _observeCallback, IntPtr.Zero);
+ if (errCode != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to register observe callbacks");
+ throw IoTConnectivityErrorFactory.GetException(errCode);
+ }
+ }
+
+ /// <summary>
+ /// Stops observing on the resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <privilege>
+ /// http://tizen.org/privilege/internet
+ /// </privilege>
+ /// <privlevel>public</privlevel>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
+ /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have privilege to access.</exception>
+ public void StopObserving()
+ {
+ int ret = Interop.IoTConnectivity.Client.RemoteResource.DeregisterObserve(_remoteResourceHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to deregister observe callbacks");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+
+ /// <summary>
+ /// Gets the attributes of a resource asynchronously.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <privilege>
+ /// http://tizen.org/privilege/internet
+ /// </privilege>
+ /// <privlevel>public</privlevel>
+ /// <param name="query">The ResourceQuery to send to server.</param>
+ /// <returns>Remote response with result and representation.</returns>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ public async Task<RemoteResponse> GetAsync(ResourceQuery query = null)
+ {
+ TaskCompletionSource<RemoteResponse> tcsRemoteResponse = new TaskCompletionSource<RemoteResponse>();
+
+ IntPtr id = IntPtr.Zero;
+ lock (_responseCallbacksMap)
+ {
+ id = (IntPtr)_responseCallbackId++;
+ }
+ _responseCallbacksMap[id] = (IntPtr resource, int err, int requestType, IntPtr responseHandle, IntPtr userData) =>
+ {
+ IntPtr responseCallbackId = userData;
+ lock(_responseCallbacksMap)
+ {
+ _responseCallbacksMap.Remove(responseCallbackId);
+ }
+
+ if (responseHandle != IntPtr.Zero)
+ {
+ try
+ {
+ tcsRemoteResponse.TrySetResult(GetRemoteResponse(responseHandle));
+ }
+ catch(Exception exp)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get RemoteResponse: ", exp.Message);
+ tcsRemoteResponse.TrySetException(exp);
+ }
+ }
+ else
+ {
+ tcsRemoteResponse.TrySetException(IoTConnectivityErrorFactory.GetException((int)IoTConnectivityError.System));
+ }
+ };
+
+ IntPtr queryHandle = (query == null) ? IntPtr.Zero : query._resourceQueryHandle;
+ int errCode = Interop.IoTConnectivity.Client.RemoteResource.Get(_remoteResourceHandle, queryHandle, _responseCallbacksMap[id], id);
+ if (errCode != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get resource attributes");
+ tcsRemoteResponse.TrySetException(IoTConnectivityErrorFactory.GetException(errCode));
+ }
+ return await tcsRemoteResponse.Task;
+ }
+
+ /// <summary>
+ /// Puts the representation of a resource asynchronously.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <privilege>
+ /// http://tizen.org/privilege/internet
+ /// </privilege>
+ /// <privlevel>public</privlevel>
+ /// <param name="representation">Resource representation to put.</param>
+ /// <param name="query">The ResourceQuery to send to server.</param>
+ /// <returns>Remote response with result and representation.</returns>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ public async Task<RemoteResponse> PutAsync(Representation representation, ResourceQuery query = null)
+ {
+ TaskCompletionSource<RemoteResponse> tcsRemoteResponse = new TaskCompletionSource<RemoteResponse>();
+
+ IntPtr id = IntPtr.Zero;
+ lock (_responseCallbacksMap)
+ {
+ id = (IntPtr)_responseCallbackId++;
+ }
+ _responseCallbacksMap[id] = (IntPtr resource, int err, int requestType, IntPtr responseHandle, IntPtr userData) =>
+ {
+ IntPtr responseCallbackId = userData;
+ lock (_responseCallbacksMap)
+ {
+ _responseCallbacksMap.Remove(responseCallbackId);
+ }
+ if (err == (int)(IoTConnectivityError.Iotivity))
+ {
+ RemoteResponse response = new RemoteResponse();
+ response.Result = ResponseCode.Forbidden;
+ response.Representation = null;
+ tcsRemoteResponse.TrySetResult(response);
+ }
+ else if (responseHandle != IntPtr.Zero)
+ {
+ try
+ {
+ tcsRemoteResponse.TrySetResult(GetRemoteResponse(responseHandle));
+ }
+ catch (Exception exp)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get RemoteResponse: ", exp.Message);
+ tcsRemoteResponse.TrySetException(exp);
+ }
+ }
+ else
+ {
+ tcsRemoteResponse.TrySetException(IoTConnectivityErrorFactory.GetException((int)IoTConnectivityError.System));
+ }
+ };
+ IntPtr queryHandle = (query == null) ? IntPtr.Zero : query._resourceQueryHandle;
+ int errCode = Interop.IoTConnectivity.Client.RemoteResource.Put(_remoteResourceHandle, representation._representationHandle, queryHandle, _responseCallbacksMap[id], id);
+ if (errCode != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to put resource representation");
+ tcsRemoteResponse.TrySetException(IoTConnectivityErrorFactory.GetException(errCode));
+ }
+ return await tcsRemoteResponse.Task;
+ }
+
+ /// <summary>
+ /// Posts request on a resource asynchronously.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <privilege>
+ /// http://tizen.org/privilege/internet
+ /// </privilege>
+ /// <privlevel>public</privlevel>
+ /// <param name="representation">Resource representation of request.</param>
+ /// <param name="query">The ResourceQuery to send to server.</param>
+ /// <returns>Remote response with result and representation.</returns>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ public async Task<RemoteResponse> PostAsync(Representation representation, ResourceQuery query = null)
+ {
+ TaskCompletionSource<RemoteResponse> tcsRemoteResponse = new TaskCompletionSource<RemoteResponse>();
+
+ IntPtr id = IntPtr.Zero;
+ lock (_responseCallbacksMap)
+ {
+ id = (IntPtr)_responseCallbackId++;
+ }
+ _responseCallbacksMap[id] = (IntPtr resource, int err, int requestType, IntPtr responseHandle, IntPtr userData) =>
+ {
+ IntPtr responseCallbackId = userData;
+ lock (_responseCallbacksMap)
+ {
+ _responseCallbacksMap.Remove(responseCallbackId);
+ }
+ if (responseHandle != IntPtr.Zero)
+ {
+ try
+ {
+ tcsRemoteResponse.TrySetResult(GetRemoteResponse(responseHandle));
+ }
+ catch (Exception exp)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get RemoteResponse: ", exp.Message);
+ tcsRemoteResponse.TrySetException(exp);
+ }
+ }
+ else
+ {
+ tcsRemoteResponse.TrySetException(IoTConnectivityErrorFactory.GetException((int)IoTConnectivityError.System));
+ }
+ };
+ IntPtr queryHandle = (query == null) ? IntPtr.Zero : query._resourceQueryHandle;
+ int errCode = Interop.IoTConnectivity.Client.RemoteResource.Post(_remoteResourceHandle, representation._representationHandle, queryHandle, _responseCallbacksMap[id], id);
+ if (errCode != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to post request");
+ tcsRemoteResponse.TrySetException(IoTConnectivityErrorFactory.GetException(errCode));
+ }
+ return await tcsRemoteResponse.Task;
+ }
+
+ /// <summary>
+ /// Deletes the resource asynchronously.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <privilege>
+ /// http://tizen.org/privilege/internet
+ /// </privilege>
+ /// <privlevel>public</privlevel>
+ /// <returns>Remote response with result and representation.</returns>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ public async Task<RemoteResponse> DeleteAsync()
+ {
+ TaskCompletionSource<RemoteResponse> tcsRemoteResponse = new TaskCompletionSource<RemoteResponse>();
+
+ IntPtr id = IntPtr.Zero;
+ lock (_responseCallbacksMap)
+ {
+ id = (IntPtr)_responseCallbackId++;
+ }
+ _responseCallbacksMap[id] = (IntPtr resource, int err, int requestType, IntPtr responseHandle, IntPtr userData) =>
+ {
+ IntPtr responseCallbackId = userData;
+ lock (_responseCallbacksMap)
+ {
+ _responseCallbacksMap.Remove(responseCallbackId);
+ }
+ if (err == (int)(IoTConnectivityError.Iotivity))
+ {
+ RemoteResponse response = new RemoteResponse();
+ response.Result = ResponseCode.Forbidden;
+ response.Representation = null;
+ tcsRemoteResponse.TrySetResult(response);
+ }
+ else if (responseHandle != IntPtr.Zero)
+ {
+ try
+ {
+ tcsRemoteResponse.TrySetResult(GetRemoteResponse(responseHandle));
+ }
+ catch (Exception exp)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get RemoteResponse: ", exp.Message);
+ tcsRemoteResponse.TrySetException(exp);
+ }
+ }
+ else
+ {
+ tcsRemoteResponse.TrySetException(IoTConnectivityErrorFactory.GetException((int)IoTConnectivityError.System));
+ }
+ };
+
+ int errCode = Interop.IoTConnectivity.Client.RemoteResource.Delete(_remoteResourceHandle, _responseCallbacksMap[id], id);
+ if (errCode != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to delete");
+ tcsRemoteResponse.TrySetException(IoTConnectivityErrorFactory.GetException(errCode));
+ }
+ return await tcsRemoteResponse.Task;
+ }
+
+ /// <summary>
+ /// Releases any unmanaged resources used by this object.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ internal static Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType GetConnectivityType(string hostAddress)
+ {
+ Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType type = Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType.None;
+
+ Log.Info(IoTConnectivityErrorFactory.LogTag, hostAddress);
+
+ if (hostAddress == IoTConnectivityClientManager.MulticastAddress)
+ {
+ type = Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType.Ipv4;
+ }
+ else
+ {
+ IPAddress address;
+ string hostName = hostAddress;
+ if (hostAddress.Contains(":"))
+ {
+ string[] hostParts = hostAddress.Split(':');
+ if (hostParts.Length == 2)
+ {
+ hostName = hostParts[0];
+ }
+ }
+ if (hostAddress.Contains("%"))
+ {
+ string[] hostParts = hostAddress.Split('%');
+ if (hostParts.Length == 2)
+ {
+ hostName = hostParts[0];
+ }
+ }
+ if (hostName.Contains("["))
+ {
+ string[] hostParts = hostName.Split('[');
+ if (hostParts.Length == 2)
+ {
+ hostName = hostParts[1];
+ }
+ }
+ Log.Info(IoTConnectivityErrorFactory.LogTag, hostName);
+ if (IPAddress.TryParse(hostName, out address))
+ {
+ switch (address.AddressFamily)
+ {
+ case System.Net.Sockets.AddressFamily.InterNetwork:
+ type = Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType.Ipv4;
+ break;
+ case System.Net.Sockets.AddressFamily.InterNetworkV6:
+ type = Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType.Ipv6;
+ break;
+ default:
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to parse for Ipv4 or Ipv6");
+ break;
+ }
+ }
+ else
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to parse hostname " + hostName);
+ }
+ }
+ return type;
+ }
+
+ /// <summary>
+ /// Releases any unmanaged resources used by this object. Can also dispose any other disposable objects.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="disposing">If true, disposes any disposable objects. If false, does not dispose disposable objects.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ protected virtual void Dispose(bool disposing)
+ {
+ if (_disposed)
+ return;
+
+ if (disposing)
+ {
+ // Free managed objects
+ }
+
+ Interop.IoTConnectivity.Client.RemoteResource.Destroy(_remoteResourceHandle);
+ _disposed = true;
+ }
+
+ private void HandleCachePolicyChanged()
+ {
+ if (_cacheEnabled)
+ {
+ _cacheUpdatedCallback = (IntPtr resource, IntPtr representation, IntPtr userData) =>
+ {
+ if (CacheEnabled)
+ {
+ Representation repr = null;
+ try
+ {
+ repr = new Representation(representation);
+ }
+ catch (Exception exp)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to new Representation: " + exp.Message);
+ return;
+ }
+
+ CacheUpdatedEventArgs e = new CacheUpdatedEventArgs()
+ {
+ Representation = repr
+ };
+ CacheUpdated?.Invoke(this, e);
+ }
+ };
+
+ int ret = Interop.IoTConnectivity.Client.RemoteResource.StartCaching(_remoteResourceHandle, _cacheUpdatedCallback, IntPtr.Zero);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add cache updated event handler");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ else
+ {
+ int ret = Interop.IoTConnectivity.Client.RemoteResource.StopCaching(_remoteResourceHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to remove cache updated event handler");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ }
+
+ private void RegisterStateChangedEvent()
+ {
+ _stateChangedCallback = (IntPtr resource, int state, IntPtr userData) =>
+ {
+ StateChangedEventArgs e = new StateChangedEventArgs()
+ {
+ State = (ResourceState)state
+ };
+ _stateChangedEventHandler?.Invoke(null, e);
+ };
+
+ int ret = Interop.IoTConnectivity.Client.RemoteResource.StartMonitoring(_remoteResourceHandle, _stateChangedCallback, IntPtr.Zero);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add state changed event handler");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+
+ private void UnregisterStateChangedEvent()
+ {
+ int ret = Interop.IoTConnectivity.Client.RemoteResource.StopMonitoring(_remoteResourceHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to remove state changed event handler");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+
+ private void CreateRemoteResource(IntPtr resourceTypeHandle, IntPtr resourceInterfaceHandle)
+ {
+ Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType connectivityType = GetConnectivityType(HostAddress);
+ if (connectivityType == Interop.IoTConnectivity.Client.RemoteResource.ConnectivityType.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Unable to parse host address");
+ throw new ArgumentException("Unable to parse host address");
+ }
+ int ret = Interop.IoTConnectivity.Client.RemoteResource.Create(HostAddress, (int)connectivityType, UriPath, (int)Policy, resourceTypeHandle, resourceInterfaceHandle, out _remoteResourceHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get remote resource");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+
+ private void SetRemoteResource()
+ {
+ IntPtr hostAddressPtr, uriPathPtr;
+ int ret = Interop.IoTConnectivity.Client.RemoteResource.GetHostAddress(_remoteResourceHandle, out hostAddressPtr);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Faled to get host address");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+
+ ret = Interop.IoTConnectivity.Client.RemoteResource.GetUriPath(_remoteResourceHandle, out uriPathPtr);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Faled to get uri path");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+
+ int policy = (int)ResourcePolicy.NoProperty;
+ ret = Interop.IoTConnectivity.Client.RemoteResource.GetPolicies(_remoteResourceHandle, out policy);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Faled to get uri path");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+
+ IntPtr typesHandle, interfacesHandle;
+ ret = Interop.IoTConnectivity.Client.RemoteResource.GetTypes(_remoteResourceHandle, out typesHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get resource types");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+
+ ret = Interop.IoTConnectivity.Client.RemoteResource.GetInterfaces(_remoteResourceHandle, out interfacesHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get resource interfaces");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+
+ IntPtr deviceIdPtr;
+ ret = Interop.IoTConnectivity.Client.RemoteResource.GetDeviceId(_remoteResourceHandle, out deviceIdPtr);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get device id");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ DeviceId = (deviceIdPtr != IntPtr.Zero) ? Marshal.PtrToStringAnsi(deviceIdPtr) : string.Empty;
+ HostAddress = (hostAddressPtr != IntPtr.Zero) ? Marshal.PtrToStringAnsi(hostAddressPtr) : string.Empty;
+ UriPath = (uriPathPtr != IntPtr.Zero) ? Marshal.PtrToStringAnsi(uriPathPtr) : string.Empty;
+ Types = new ResourceTypes(typesHandle);
+ Interfaces = new ResourceInterfaces(interfacesHandle);
+ Policy = (ResourcePolicy)policy;
+ }
+
+ private RemoteResponse GetRemoteResponse(IntPtr response)
+ {
+ int result;
+ IntPtr representationHandle, optionsHandle;
+ int ret = Interop.IoTConnectivity.Server.Response.GetResult(response, out result);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get result");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+
+ ret = Interop.IoTConnectivity.Server.Response.GetRepresentation(response, out representationHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get representation");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+
+ ret = Interop.IoTConnectivity.Server.Response.GetOptions(response, out optionsHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get options");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ return new RemoteResponse()
+ {
+ Result = (ResponseCode)result,
+ Representation = new Representation(representationHandle),
+ Options = (optionsHandle == IntPtr.Zero)? null : new ResourceOptions(optionsHandle)
+ };
+ }
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// This class represents a remote response.
+ /// It represents the response of all CRUD operations.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public class RemoteResponse
+ {
+ internal RemoteResponse() { }
+
+ /// <summary>
+ /// Indicates the result of the response.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The result of the response.</value>
+ public ResponseCode Result { get; internal set; }
+
+ /// <summary>
+ /// Indicates representation of the response.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>Representation of the response.</value>
+ public Representation Representation { get; internal set; }
+
+ /// <summary>
+ /// Indicates header options of the response.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>Header options of the response.</value>
+ public ResourceOptions Options { get; internal set; }
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Runtime.InteropServices;
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// This class provides APIs to manage representation.
+ /// A representation is a payload of a request or a response.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public class Representation : IDisposable
+ {
+ internal IntPtr _representationHandle = IntPtr.Zero;
+
+ private bool _disposed = false;
+ private ObservableCollection<Representation> _children = new ObservableCollection<Representation>();
+
+ /// <summary>
+ /// The Representation constructor.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory.</exception>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
+ /// <code>
+ /// Representation repr = new Representation();
+ /// </code>
+ public Representation()
+ {
+ int ret = Interop.IoTConnectivity.Common.Representation.Create(out _representationHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to create representation");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+
+ _children.CollectionChanged += ChildrenCollectionChanged;
+ }
+
+ // Constructor for cloning native representation object
+ internal Representation(IntPtr handleToClone)
+ {
+ int ret = (int)IoTConnectivityError.InvalidParameter;
+ if (handleToClone != IntPtr.Zero)
+ {
+ ret = Interop.IoTConnectivity.Common.Representation.Clone(handleToClone, out _representationHandle);
+ }
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to create representation");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+
+ _children.CollectionChanged += ChildrenCollectionChanged;
+ }
+
+ /// <summary>
+ /// Destructor of the Representation class.
+ /// </summary>
+ ~Representation()
+ {
+ Dispose(false);
+ }
+
+ /// <summary>
+ /// The URI path of resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>
+ /// The URI path of resource.
+ /// Setter can throw exceptions.
+ /// </value>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
+ /// <code>
+ /// Representation repr = new Representation();
+ /// repr.UriPath = "/a/light";
+ /// Console.WriteLine("URI is {0}", repr.UriPath); //Getter
+ /// </code>
+ public string UriPath
+ {
+ get
+ {
+ IntPtr path;
+ int ret = Interop.IoTConnectivity.Common.Representation.GetUriPath(_representationHandle, out path);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to Get uri");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ return (path != IntPtr.Zero) ? Marshal.PtrToStringAnsi(path) : string.Empty;
+ }
+ set
+ {
+ int ret = (int)IoTConnectivityError.InvalidParameter;
+ if (value != null)
+ ret = Interop.IoTConnectivity.Common.Representation.SetUriPath(_representationHandle, value);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to set uri");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ }
+
+ /// <summary>
+ /// The type of resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The type of resource.</value>
+ /// <seealso cref="ResourceTypes"/>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
+ /// <code>
+ /// Representation repr = new Representation();
+ /// ResourceTypes types = new ResourceTypes (new List<string>(){ "org.tizen.light" });
+ /// repr.Type = types;
+ /// var type = repr.Type; // Getter
+ /// foreach (string item in type)
+ /// {
+ /// Console.WriteLine("Type is {0}", item);
+ /// }
+ /// </code>
+ public ResourceTypes Type
+ {
+ get
+ {
+ IntPtr typeHandle;
+ int ret = Interop.IoTConnectivity.Common.Representation.GetResourceTypes(_representationHandle, out typeHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get type");
+ return null;
+ }
+ return (typeHandle == IntPtr.Zero) ? null : new ResourceTypes(typeHandle);
+ }
+ set
+ {
+ int ret = (int)IoTConnectivityError.InvalidParameter;
+ if (value != null)
+ ret = Interop.IoTConnectivity.Common.Representation.SetResourceTypes(_representationHandle, value._resourceTypeHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to set type");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ }
+
+ /// <summary>
+ /// The interface of the resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The interface of the resource.</value>
+ /// <seealso cref="ResourceInterfaces"/>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
+ /// <code>
+ /// Representation repr = new Representation();
+ /// ResourceInterfaces ifaces = new ResourceInterfaces (new List<string>(){ ResourceInterfaces.DefaultInterface });
+ /// repr.Interface = ifaces;
+ /// var iface = repr.Interface; // Getter
+ /// foreach (string item in iface)
+ /// {
+ /// Console.WriteLine("Interface is {0}", iface);
+ /// }
+ /// </code>
+ public ResourceInterfaces Interface
+ {
+ get
+ {
+ IntPtr interfaceHandle;
+ int ret = Interop.IoTConnectivity.Common.Representation.GetResourceInterfaces(_representationHandle, out interfaceHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get interface");
+ return null;
+ }
+ return (interfaceHandle == IntPtr.Zero) ? null : new ResourceInterfaces(interfaceHandle);
+ }
+ set
+ {
+ int ret = (int)IoTConnectivityError.InvalidParameter;
+ if (value != null)
+ ret = Interop.IoTConnectivity.Common.Representation.SetResourceInterfaces(_representationHandle, value.ResourceInterfacesHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to set interface");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ }
+
+ /// <summary>
+ /// Current attributes of the resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>Current attributes of the resource.</value>
+ /// <seealso cref="Attributes"/>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
+ /// <code>
+ /// Representation repr = new Representation();
+ /// Attributes attributes = new Attributes() {
+ /// { "state", "ON" },
+ /// { "dim", 10 }
+ /// };
+ /// repr.Attributes = attributes;
+ /// var newAttributes = repr.Attributes; // Getter
+ /// string strval = newAttributes["state"] as string;
+ /// int intval = (int)newAttributes["dim"];
+ /// Console.WriteLine("attributes are {0} and {1}", strval, intval);
+ /// </code>
+ public Attributes Attributes
+ {
+ get
+ {
+ IntPtr attributeHandle;
+ int ret = Interop.IoTConnectivity.Common.Representation.GetAttributes(_representationHandle, out attributeHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get attributes");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ return (attributeHandle == IntPtr.Zero) ? null : new Attributes(attributeHandle);
+ }
+ set
+ {
+ int ret = (int)IoTConnectivityError.InvalidParameter;
+ if (value != null)
+ {
+ ret = Interop.IoTConnectivity.Common.Representation.SetAttributes(_representationHandle, value._resourceAttributesHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to set attributes");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// List of Child resource representation.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>List of Child resource representation.</value>
+ /// <code>
+ /// Representation repr = new Representation();
+ /// Representation child1 = new Representation();
+ /// ResourceTypes types1 = new ResourceTypes(new List<string>() { "org.tizen.light" });
+ /// child1.Type = types1;
+ /// ResourceInterfaces ifaces1 = new ResourceInterfaces(new List<string>() { ResourceInterfaces.DefaultInterface });
+ /// child1.Interface = ifaces1;
+ /// try
+ /// {
+ /// repr.Children.Add(child1);
+ /// Console.WriteLine("Number of children : {0}", repr.Children.Count);
+ /// Representation firstChild = repr.Children.ElementAt(0);
+ /// } catch(Exception ex)
+ /// {
+ /// Console.WriteLine("Exception caught : " + ex.Message);
+ /// }
+ /// </code>
+ public ICollection<Representation> Children
+ {
+ get
+ {
+ return _children;
+ }
+ }
+
+ /// <summary>
+ /// Releases any unmanaged resources used by this object.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ /// <summary>
+ /// Releases any unmanaged resources used by this object. Can also dispose any other disposable objects.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="disposing">If true, disposes any disposable objects. If false, does not dispose disposable objects.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ protected virtual void Dispose(bool disposing)
+ {
+ if (_disposed)
+ return;
+
+ if (disposing)
+ {
+ // Free managed objects
+ Type?.Dispose();
+ Interface?.Dispose();
+ Attributes?.Dispose();
+ foreach(var child in Children)
+ {
+ child.Dispose();
+ }
+ }
+
+ Interop.IoTConnectivity.Common.Representation.Destroy(_representationHandle);
+ _disposed = true;
+ }
+
+ private void ChildrenCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
+ {
+ if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
+ {
+ foreach (Representation r in e.NewItems)
+ {
+ int ret = Interop.IoTConnectivity.Common.Representation.AddChild(_representationHandle, r._representationHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add child");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ }
+ else if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
+ {
+ foreach (Representation r in e.NewItems)
+ {
+ int ret = Interop.IoTConnectivity.Common.Representation.RemoveChild(_representationHandle, r._representationHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to remove child");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ }
+ }
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+using System;
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// Class respresenting request to a resource.
+ /// It provides APIs to manage client's request.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public class Request : IDisposable
+ {
+ private bool _disposed = false;
+
+ internal Request()
+ {
+ }
+
+ /// <summary>
+ /// Destructor of the Request class.
+ /// </summary>
+ ~Request()
+ {
+ Dispose(false);
+ }
+
+ /// <summary>
+ /// The host address of the request.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The host address of the request.</value>
+ public string HostAddress { get; internal set; }
+
+ /// <summary>
+ /// The representation of the request.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The representation of the request.</value>
+ public Representation Representation { get; internal set; }
+
+ /// <summary>
+ /// The query of the request.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The query of the request.</value>
+ public ResourceQuery Query { get; internal set; }
+
+ /// <summary>
+ /// The options related to the request.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The options related to the request.</value>
+ public ResourceOptions Options { get; internal set; }
+
+ /// <summary>
+ /// Releases any unmanaged resources used by this object.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ /// <summary>
+ /// Releases any unmanaged resources used by this object. Can also dispose any other disposable objects.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="disposing">If true, disposes any disposable objects. If false, does not dispose disposable objects.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ protected virtual void Dispose(bool disposing)
+ {
+ if (_disposed)
+ return;
+
+ if (disposing)
+ {
+ Representation?.Dispose();
+ Query?.Dispose();
+ Options?.Dispose();
+ }
+
+ _disposed = true;
+ }
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Runtime.InteropServices;
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// Abstract class respresenting a resource.
+ /// All resources need to inherit from this class.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public abstract class Resource : IDisposable
+ {
+ private IntPtr _resourceHandle = IntPtr.Zero;
+ private bool _disposed = false;
+ private ObservableCollection<Resource> _children = new ObservableCollection<Resource>();
+ private IntPtr _observerHandle = IntPtr.Zero;
+
+ /// <summary>
+ /// The constructor.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <remarks>
+ /// @a uri format would be relative URI path like '/a/light'
+ /// and its length must be less than 128.
+ /// </remarks>
+ /// <privilege>
+ /// http://tizen.org/privilege/internet
+ /// </privilege>
+ /// <privlevel>public</privlevel>
+ /// <param name="uri">The URI path of the resource.</param>
+ /// <param name="types">Resource types.</param>
+ /// <param name="interfaces">Resource interfaces.</param>
+ /// <param name="policy">The policies of the resoruce.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <pre>
+ /// IoTConnectivityServerManager.Initialize() should be called to initialize.
+ /// </pre>
+ /// <seealso cref="ResourceTypes"/>
+ /// <seealso cref="ResourceInterfaces"/>
+ /// <seealso cref="ResourcePolicy"/>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory.</exception>
+ /// <code>
+ /// // Create a class which inherits from Resource
+ /// public class DoorResource : Resource
+ /// {
+ /// public DoorResource(string uri, ResourceTypes types, ResourceInterfaces interfaces, ResourcePolicy policy)
+ /// : base(uri, types, interfaces, policy) {
+ /// }
+ /// protected override Response OnDelete(Request request) {
+ /// // Do something
+ /// }
+ /// protected override Response OnGet(Request request) {
+ /// // Do something
+ /// }
+ /// // Override other abstract methods of Resource class
+ /// }
+ ///
+ /// // Use it like below
+ /// ResourceInterfaces ifaces = new ResourceInterfaces(new List<string>(){ ResourceInterfaces.DefaultInterface });
+ /// ResourceTypes types = new ResourceTypes(new List<string>(){ "oic.iot.door.new" });
+ /// Resource resource = new DoorResource("/door/uri1", types, ifaces, ResourcePolicy.Discoverable | ResourcePolicy.Observable);
+ /// </code>
+ protected Resource(string uri, ResourceTypes types, ResourceInterfaces interfaces, ResourcePolicy policy)
+ {
+ UriPath = uri;
+ Types = types;
+ Interfaces = interfaces;
+ Policy = policy;
+
+ _children.CollectionChanged += ChildrenCollectionChanged;
+
+ int ret = Interop.IoTConnectivity.Server.Observers.Create(out _observerHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to create obsever handle");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+
+ /// <summary>
+ /// Destructor of the Resource class.
+ /// </summary>
+ ~Resource()
+ {
+ Dispose(false);
+ }
+
+ /// <summary>
+ /// Type details of the resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>Type details of the resource.</value>
+ public ResourceTypes Types { get; internal set; }
+
+ /// <summary>
+ /// Interface details of the resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>Interface details of the resource.</value>
+ public ResourceInterfaces Interfaces { get; internal set; }
+
+ /// <summary>
+ /// The policies of the resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The policies of the resource.</value>
+ public ResourcePolicy Policy { get; internal set; }
+
+ /// <summary>
+ /// URI path of the resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>URI path of the resource.</value>
+ public string UriPath { get; internal set; }
+
+ /// <summary>
+ /// List of Child resources.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>List of Child resources.</value>
+ public ICollection<Resource> Children
+ {
+ get
+ {
+ return _children;
+ }
+ }
+
+ internal IntPtr ResourceHandle
+ {
+ get
+ {
+ return _resourceHandle;
+ }
+ set
+ {
+ _resourceHandle = value;
+ }
+ }
+
+ /// <summary>
+ /// Notify the specified representation and qos.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <privilege>
+ /// http://tizen.org/privilege/internet
+ /// </privilege>
+ /// <privlevel>public</privlevel>
+ /// <param name="representation">Representation.</param>
+ /// <param name="qos">The quality of service for message transfer.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <pre>
+ /// IoTConnectivityServerManager.Initialize() should be called to initialize.
+ /// </pre>
+ /// <seealso cref="Representation"/>
+ /// <seealso cref="QualityOfService"/>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="UnauthorizedAccessException">Thrown when an application does not have privilege to access.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
+ /// <code>
+ /// ResourceInterfaces ifaces = new ResourceInterfaces(new List<string>(){ ResourceInterfaces.DefaultInterface });
+ /// ResourceTypes types = new ResourceTypes(new List<string>(){ "oic.iot.door.new.notify" });
+ /// Resource resource = new DoorResource("/door/uri/new/notify", types, ifaces, ResourcePolicy.Discoverable | ResourcePolicy.Observable);
+ /// IoTConnectivityServerManager.RegisterResource(resource);
+ ///
+ /// Representation repr = new Representation();
+ /// repr.UriPath = "/door/uri/new/notify";
+ /// repr.Type = new ResourceTypes(new List<string>(){ "oic.iot.door.new.notify" });
+ /// repr.Attributes = new Attributes() {
+ /// _attribute, 1 }
+ /// };
+ /// resource.Notify(repr, QualityOfService.High);
+ /// </code>
+ public void Notify(Representation representation, QualityOfService qos)
+ {
+ int ret = (int)IoTConnectivityError.None;
+ ret = Interop.IoTConnectivity.Server.Resource.Notify(_resourceHandle, representation._representationHandle, _observerHandle, (int)qos);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to send notification");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+
+ /// <summary>
+ /// This is called when the client performs get operation on this resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="request">A request from client.</param>
+ /// <returns>A response having the representation and the result.</returns>
+ protected abstract Response OnGet(Request request);
+
+ /// <summary>
+ /// This is called when the client performs put operation on this resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="request">A request from client.</param>
+ /// <returns>A response.</returns>
+ protected abstract Response OnPut(Request request);
+
+ /// <summary>
+ /// This is called when the client performs post operation on this resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="request">A request from client.</param>
+ /// <returns>A response having the representation and the result.</returns>
+ protected abstract Response OnPost(Request request);
+
+ /// <summary>
+ /// This is called when the client performs delete operation on this resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="request">A request from client.</param>
+ /// <returns>A response.</returns>
+ protected abstract Response OnDelete(Request request);
+
+ /// <summary>
+ /// Called on the observing event.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="request">A request from client.</param>
+ /// <param name="type">Observer type.</param>
+ /// <param name="observeId">Observe identifier.</param>
+ /// <returns>Returns true if it wants to be observed, else false.</returns>
+ protected abstract bool OnObserving(Request request, ObserveType type, int observeId);
+
+ /// <summary>
+ /// Releases any unmanaged resources used by this object.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ /// <summary>
+ /// Releases any unmanaged resources used by this object. Can also dispose any other disposable objects.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="disposing">If true, disposes any disposable objects. If false, does not dispose disposable objects.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ protected virtual void Dispose(bool disposing)
+ {
+ if (_disposed)
+ return;
+
+ if (disposing)
+ {
+ Types?.Dispose();
+ Interfaces?.Dispose();
+ }
+
+ if (_resourceHandle != IntPtr.Zero)
+ Interop.IoTConnectivity.Server.Resource.Destroy(_resourceHandle);
+ if (_observerHandle != IntPtr.Zero)
+ Interop.IoTConnectivity.Server.Observers.Destroy(_observerHandle);
+ _disposed = true;
+ }
+
+ // This method is used as callback for Resource
+ internal void OnRequest(IntPtr resourceHandle, IntPtr requestHandle, IntPtr userData)
+ {
+ Request request = GetRequest(requestHandle);
+ Response response = null;
+
+ if (request == null)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get Request");
+ return;
+ }
+
+ try
+ {
+ int observeType;
+ int ret = Interop.IoTConnectivity.Server.Request.GetObserveType(requestHandle, out observeType);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to Get observe type");
+ return;
+ }
+ if ((ObserveType)observeType != ObserveType.NoType)
+ {
+ int observeId;
+ ret = Interop.IoTConnectivity.Server.Request.GetObserveId(requestHandle, out observeId);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to Get observe id");
+ return;
+ }
+ switch ((ObserveType)observeType)
+ {
+ case ObserveType.Register:
+ {
+ if (OnObserving(request, ObserveType.Register, observeId))
+ {
+ ret = Interop.IoTConnectivity.Server.Observers.Add(_observerHandle, observeId);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add observer id");
+ return;
+ }
+ break;
+ }
+ else
+ {
+ // If OnObserving for ObserveType.Register returns false, do not operate for Get operation after Observe operation.
+ return;
+ }
+ }
+ case ObserveType.Deregister:
+ {
+ if (OnObserving(request, ObserveType.Deregister, observeId))
+ {
+ ret = Interop.IoTConnectivity.Server.Observers.Remove(_observerHandle, observeId);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to remove observer id");
+ return;
+ }
+ break;
+ }
+ else
+ {
+ // If OnObserving for ObserveType.Deregister returns false, do not operate for Get operation after Observe operation.
+ return;
+ }
+ }
+ }
+ }
+ int requestType;
+ ret = Interop.IoTConnectivity.Server.Request.GetRequestType(requestHandle, out requestType);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to Get request type");
+ return;
+ }
+ switch ((Interop.IoTConnectivity.Server.RequestType)requestType)
+ {
+ case Interop.IoTConnectivity.Server.RequestType.Put:
+ {
+ response = OnPut(request);
+ break;
+ }
+ case Interop.IoTConnectivity.Server.RequestType.Get:
+ {
+ response = OnGet(request);
+ break;
+ }
+ case Interop.IoTConnectivity.Server.RequestType.Post:
+ {
+ response = OnPost(request);
+ break;
+ }
+ case Interop.IoTConnectivity.Server.RequestType.Delete:
+ {
+ response = OnDelete(request);
+ break;
+ }
+ default:
+ break;
+ }
+ if (response == null)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to send Response");
+ return;
+ }
+
+ if (!response.Send(requestHandle))
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to send Response");
+ return;
+ }
+ }
+ finally
+ {
+ request?.Dispose();
+ response?.Dispose();
+ }
+ }
+
+ private Request GetRequest(IntPtr requestHandle)
+ {
+ IntPtr hostAddressPtr;
+ int ret = Interop.IoTConnectivity.Server.Request.GetHostAddress(requestHandle, out hostAddressPtr);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to Get host address");
+ return null;
+ }
+
+ IntPtr optionsHandle = IntPtr.Zero;
+ ret = Interop.IoTConnectivity.Server.Request.GetOptions(requestHandle, out optionsHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to Get options");
+ return null;
+ }
+
+ IntPtr queryHandle = IntPtr.Zero;
+ ret = Interop.IoTConnectivity.Server.Request.GetQuery(requestHandle, out queryHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to Get Query");
+ return null;
+ }
+
+ IntPtr representationHandle = IntPtr.Zero;
+ ret = Interop.IoTConnectivity.Server.Request.GetRepresentation(requestHandle, out representationHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to Get representation");
+ return null;
+ }
+
+ ResourceOptions opts = null;
+ ResourceQuery query = null;
+ Representation representation = null;
+ try
+ {
+ opts = (optionsHandle == IntPtr.Zero) ? null : new ResourceOptions(optionsHandle);
+ }
+ catch (Exception exp)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to new ResourceOptions: " + exp.Message);
+ return null;
+ }
+
+ try
+ {
+ query = (queryHandle == IntPtr.Zero) ? null : new ResourceQuery(queryHandle);
+ }
+ catch (Exception exp)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to new ResourceQuery: " + exp.Message);
+ opts?.Dispose();
+ return null;
+ }
+
+ try
+ {
+ representation = (representationHandle == IntPtr.Zero) ? null : new Representation(representationHandle);
+ }
+ catch (Exception exp)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to new Representation: " + exp.Message);
+ opts?.Dispose();
+ query?.Dispose();
+ return null;
+ }
+
+ return new Request()
+ {
+ HostAddress = (hostAddressPtr != IntPtr.Zero) ? Marshal.PtrToStringAnsi(hostAddressPtr) : string.Empty,
+ Options = opts,
+ Query = query,
+ Representation = representation
+ };
+ }
+
+ private void ChildrenCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs eventArgs)
+ {
+ if (eventArgs.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
+ {
+ foreach (Resource r in eventArgs.NewItems)
+ {
+ int ret = Interop.IoTConnectivity.Server.Resource.BindChildResource(_resourceHandle, r._resourceHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to bind resource ");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ }
+ else if (eventArgs.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
+ {
+ foreach (Resource r in eventArgs.NewItems)
+ {
+ int ret = Interop.IoTConnectivity.Server.Resource.UnbindChildResource(_resourceHandle, r._resourceHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to unbind resource");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ }
+ }
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+using System;
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// This class represents event arguments of the ResourceFound event.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public class ResourceFoundEventArgs : EventArgs
+ {
+ internal ResourceFoundEventArgs() { }
+
+ /// <summary>
+ /// Indicates the request ID.
+ /// This is the same request ID returned by the <see cref="IoTConnectivityClientManager.StartFindingResource()"/> API.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The request ID.</value>
+ public int RequestId { get; internal set; }
+
+ /// <summary>
+ /// Indicates to continuously receive the event for finding resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>Continuously receive the event for finding resource.</value>
+ public bool EventContinue { get; set; }
+
+ /// <summary>
+ /// Remote resource, which is found after <see cref="IoTConnectivityClientManager.StartFindingResource()"/>.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>Remote resource which is found after <see cref="IoTConnectivityClientManager.StartFindingResource()"/>.</value>
+ /// <seealso cref="IoTConnectivityClientManager.ResourceFound"/>
+ /// <seealso cref="IoTConnectivityClientManager.StartFindingResource()"/>
+ public RemoteResource Resource { get; internal set; }
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Text.RegularExpressions;
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// This class contains resource interfaces and provides APIs to manage, add, or remove those interfaces.
+ /// A resource interface indicates a class or category of resources.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public class ResourceInterfaces : IEnumerable<string>, IDisposable
+ {
+ /// <summary>
+ /// Default Interface.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public const string DefaultInterface = "oic.if.baseline";
+
+ /// <summary>
+ /// List Links Interface, which is used to list the references to other resources contained in a resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public const string LinkInterface = "oic.if.ll";
+
+ /// <summary>
+ /// Batch Interface, which is used to manipulate (GET, PUT, POST, DELETE) on other resource contained in a resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public const string BatchInterface = "oic.if.b";
+
+ /// <summary>
+ /// Group Interface, which is used to manipulate (GET, PUT, POST) a group of remote resources.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public const string GroupInterface = "oic.mi.grp";
+
+ /// <summary>
+ /// Read-Only Interface, which is used to limit the methods that can be applied to a resource to GET only.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public const string ReadonlyInterface = "oic.if.r";
+
+ private readonly IntPtr _resourceInterfacesHandle = IntPtr.Zero;
+ private const int MaxLength = 61;
+ private readonly HashSet<string> _resourceInterfaces = new HashSet<string>();
+ private bool _disposed = false;
+
+ /// <summary>
+ /// Constructor of ResourceInterfaces.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <seealso cref="Add()"/>
+ /// <seealso cref="Remove()"/>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory.</exception>
+ /// <code>
+ /// ResourceInterfaces resourceInterfaces = new ResourceInterfaces();
+ /// </code>
+ public ResourceInterfaces()
+ {
+ int ret = Interop.IoTConnectivity.Common.ResourceInterfaces.Create(out _resourceInterfacesHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to create interface");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+
+ /// <summary>
+ /// Constructor of ResourceInterfaces using list of interfaces.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="ifaces">List of resource interfaces.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory.</exception>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
+ /// <code>
+ /// ResourceInterfaces resourceInterfaces = new ResourceInterfaces(new List<string>()
+ /// { ResourceInterfaces.LinkInterface, ResourceInterfaces.ReadonlyInterface });
+ /// </code>
+ public ResourceInterfaces(IEnumerable<string> ifaces)
+ {
+ int ret = Interop.IoTConnectivity.Common.ResourceInterfaces.Create(out _resourceInterfacesHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to create interface");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ foreach (string iface in ifaces)
+ {
+ Add(iface);
+ }
+ }
+
+ internal ResourceInterfaces(IntPtr ifacesHandleToClone)
+ {
+ int ret = Interop.IoTConnectivity.Common.ResourceInterfaces.Clone(ifacesHandleToClone, out _resourceInterfacesHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to create interface");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+
+ Interop.IoTConnectivity.Common.ResourceInterfaces.ForeachCallback cb = (string iface, IntPtr data) =>
+ {
+ _resourceInterfaces.Add(iface);
+ return true;
+ };
+
+ ret = Interop.IoTConnectivity.Common.ResourceInterfaces.Foreach(ifacesHandleToClone, cb, IntPtr.Zero);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to create type");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+
+ /// <summary>
+ /// Destructor of the ResourceInterfaces class.
+ /// </summary>
+ ~ResourceInterfaces()
+ {
+ Dispose(false);
+ }
+
+ internal IntPtr ResourceInterfacesHandle
+ {
+ get
+ {
+ return _resourceInterfacesHandle;
+ }
+ }
+
+ /// <summary>
+ /// Indicates count of interfaces in the list
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>Count of interfaces in the list.</value>
+ /// <code>
+ /// ResourceInterfaces resourceInterfaces = new ResourceInterfaces(new List<string>()
+ /// { ResourceInterfaces.LinkInterface, ResourceInterfaces.ReadonlyInterface });
+ /// Console.WriteLine("There are {0} interfaces", resourceInterfaces.Count);
+ /// </code>
+ public int Count
+ {
+ get
+ {
+ return _resourceInterfaces.Count;
+ }
+ }
+
+ /// <summary>
+ /// Adds a resource interface into the list.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <remarks>
+ /// @a item could be a value, such as <see cref="DefaultInterface"/>.
+ /// </remarks>
+ /// <param name="item">The string data to insert into the resource interfaces.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <seealso cref="Remove()"/>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
+ /// <code>
+ /// ResourceInterfaces resourceInterfaces = new ResourceInterfaces();
+ /// resourceInterfaces.Add(ResourceInterfaces.BatchInterface);
+ /// </code>
+ public void Add(string item)
+ {
+ if (IsValid(item))
+ {
+ int ret = Interop.IoTConnectivity.Common.ResourceInterfaces.Add(_resourceInterfacesHandle, item);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add interface");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ _resourceInterfaces.Add(item);
+ }
+ else
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Invalid interface");
+ throw IoTConnectivityErrorFactory.GetException((int)IoTConnectivityError.InvalidParameter);
+ }
+ }
+
+ /// <summary>
+ /// Removes a resource interface from the list.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="item">The string data to delete from the resource ifaces.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <seealso cref="Add()"/>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
+ /// <code>
+ /// ResourceInterfaces resourceInterfaces = new ResourceInterfaces(new List<string>(){ ResourceInterfaces.BatchInterface });
+ /// resourceInterfaces.Add(ResourceInterfaces.BatchInterface);
+ /// </code>
+ public void Remove(string item)
+ {
+ bool isRemoved = _resourceInterfaces.Remove(item);
+ if (isRemoved)
+ {
+ int ret = Interop.IoTConnectivity.Common.ResourceInterfaces.Remove(_resourceInterfacesHandle, item);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to remove interface");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ else
+ throw IoTConnectivityErrorFactory.GetException((int)IoTConnectivityError.InvalidParameter);
+ }
+
+ /// <summary>
+ /// Returns enumerator for the list of interfaces.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <returns>The enumerator.</returns>
+ /// <code>
+ /// ResourceInterfaces resourceInterfaces = new ResourceInterfaces(new List<string>()
+ /// { ResourceInterfaces.LinkInterface, ResourceInterfaces.ReadonlyInterface });
+ /// foreach(string item in resourceInterfaces)
+ /// {
+ /// Console.WriteLine("Interface : {0}", item);
+ /// }
+ /// </code>
+ public IEnumerator<string> GetEnumerator()
+ {
+ return _resourceInterfaces.GetEnumerator();
+ }
+
+ /// <summary>
+ /// Returns enumerator for the list of interfaces.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <returns>The enumerator.</returns>
+ /// <code>
+ /// ResourceInterfaces resourceInterfaces = new ResourceInterfaces(new List<string>()
+ /// { ResourceInterfaces.LinkInterface, ResourceInterfaces.ReadonlyInterface });
+ /// foreach(string item in resourceInterfaces)
+ /// {
+ /// Console.WriteLine("Interface : {0}", item);
+ /// }
+ /// </code>
+ IEnumerator IEnumerable.GetEnumerator()
+ {
+ return _resourceInterfaces.GetEnumerator();
+ }
+
+ /// <summary>
+ /// Releases any unmanaged resources used by this object.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ internal static bool IsValid(string type)
+ {
+ Regex r = new Regex("^[a-zA-Z0-9.-]+$");
+ return (type.Length <= MaxLength && type.Length > 0 && char.IsLower(type[0]) && r.IsMatch(type));
+ }
+
+ /// <summary>
+ /// Releases any unmanaged resources used by this object. Can also dispose any other disposable objects.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="disposing">If true, disposes any disposable objects. If false, does not dispose disposable objects.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ protected virtual void Dispose(bool disposing)
+ {
+ if (_disposed)
+ return;
+
+ if (disposing)
+ {
+ // Free managed objects
+ }
+
+ Interop.IoTConnectivity.Common.ResourceInterfaces.Destroy(_resourceInterfacesHandle);
+ _disposed = true;
+ }
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// This class represents resource options. It provides APIs to manage them.\n
+ /// The iotcon options API provides methods for managing vendor specific options of coap packet.\n
+ /// See more about coap packet in http://tools.ietf.org/html/rfc7252.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public class ResourceOptions : IDictionary<ushort, string>, IDisposable
+ {
+ internal const int MaxSize = 2;
+ internal const int IdMin = 2048;
+ internal const int IdMax = 3000;
+ internal const int DataMax = 15;
+
+ internal IntPtr _resourceOptionsHandle = IntPtr.Zero;
+ private readonly IDictionary<ushort, string> _options = new Dictionary<ushort, string>();
+ private bool _disposed = false;
+
+ /// <summary>
+ /// The resource options constructor.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <seealso cref="Add()"/>
+ /// <seealso cref="Remove()"/>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory.</exception>
+ /// <code>
+ /// ResourceOptions options = new ResourceOptions();
+ /// </code>
+ public ResourceOptions()
+ {
+ int ret = Interop.IoTConnectivity.Common.Options.Create(out _resourceOptionsHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to create options");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+
+ // internal constructor
+ internal ResourceOptions(IntPtr handleToClone)
+ {
+ int ret = Interop.IoTConnectivity.Common.Options.Create(out _resourceOptionsHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to create options");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+
+ Interop.IoTConnectivity.Common.Options.OptionsCallback forEachCallback = (ushort id, string value, IntPtr userData) =>
+ {
+ Add(id, value);
+ return true;
+ };
+
+ ret = Interop.IoTConnectivity.Common.Options.ForEach(handleToClone, forEachCallback, IntPtr.Zero);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to iterate options");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+
+ /// <summary>
+ /// Destructor of the ResourceOptions class.
+ /// </summary>
+ ~ResourceOptions()
+ {
+ Dispose(false);
+ }
+
+ /// <summary>
+ /// Contains all the Option keys.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>All the Option keys.</value>
+ /// <code>
+ /// ResourceOptions options = new ResourceOptions();
+ /// options.Add(2050, "sample-data");
+ /// options.Add(2055, "sample value");
+ /// var keys = options.Keys;
+ /// Console.WriteLine("Resource options contains keys {0} and {1}", keys.ElementAt(0), keys.ElementAt(1));
+ /// </code>
+ public ICollection<ushort> Keys
+ {
+ get
+ {
+ return _options.Keys;
+ }
+ }
+
+ /// <summary>
+ /// Contains all the Option values.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>All the Option values.</value>
+ /// <code>
+ /// ResourceOptions options = new ResourceOptions();
+ /// options.Add(2050, "sample-data");
+ /// options.Add(2055, "sample value");
+ /// var values = options.Values;
+ /// Console.WriteLine("Resource options contains values {0} and {1}", values.ElementAt(0), values.ElementAt(1));
+ /// </code>
+ public ICollection<string> Values
+ {
+ get
+ {
+ return _options.Values;
+ }
+ }
+
+ /// <summary>
+ /// Gets the number of options.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The number of options.</value>
+ /// <code>
+ /// ResourceOptions options = new ResourceOptions();
+ /// options.Add(2050, "sample-data");
+ /// options.Add(2055, "sample value");
+ /// var count = options.Count;
+ /// Console.WriteLine("There are {0} keys in the options object", count);
+ /// </code>
+ public int Count
+ {
+ get
+ {
+ return _options.Count;
+ }
+ }
+
+ /// <summary>
+ /// Represents whether the collection is readonly.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>Whether the collection is readonly.</value>
+ /// <code>
+ /// ResourceOptions options = new ResourceOptions();
+ /// if (options.IsReadOnly)
+ /// Console.WriteLine("Read only options");
+ /// </code>
+ public bool IsReadOnly
+ {
+ get
+ {
+ return _options.IsReadOnly;
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the option data.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The option data.</value>
+ /// <param name="key">The option ID to get or set.</param>
+ /// <returns>The option with the specified ID.</returns>
+ /// <code>
+ /// ResourceOptions options = new ResourceOptions();
+ /// options[2055] = "sample-data";
+ /// Console.WriteLine("Option has : {0}", options[2055]);
+ /// </code>
+ public string this[ushort key]
+ {
+ get
+ {
+ return _options[key];
+ }
+ set
+ {
+ Add(key, value);
+ }
+ }
+
+ /// <summary>
+ /// Checks whether the given key exists in Options collection.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="key">The key to look for.</param>
+ /// <returns>true if exists. Otherwise, false.</returns>
+ /// <code>
+ /// ResourceOptions options = new ResourceOptions();
+ /// options.Add(2050, "sample-data");
+ /// if (options.ContainsKey(2050))
+ /// Console.WriteLine("options conatins key : 2050");
+ /// </code>
+ public bool ContainsKey(ushort key)
+ {
+ return _options.ContainsKey(key);
+ }
+
+ /// <summary>
+ /// Adds a new ID and a correspoding data into the options.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <remarks>
+ /// ResourceOptions can have up to 2 options. \n
+ /// key is always situated between 2048 and 3000. \n
+ /// Length of option data is less than or equal to 15.
+ /// </remarks>
+ /// <param name="key">The ID of the option to insert.</param>
+ /// <param name="value">The string data to insert into the options.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <seealso cref="Remove()"/>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
+ /// <code>
+ /// ResourceOptions options = new ResourceOptions();
+ /// options.Add(2050, "sample-data");
+ /// </code>
+ public void Add(ushort key, string value)
+ {
+ int ret = (int)IoTConnectivityError.InvalidParameter;
+ if (IsValid(key, value))
+ {
+ ret = Interop.IoTConnectivity.Common.Options.Add(_resourceOptionsHandle, key, value);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add option");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ _options.Add(key, value);
+ }
+ else
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Invalid options");
+ throw IoTConnectivityErrorFactory.GetException((int)IoTConnectivityError.InvalidParameter);
+ }
+ }
+
+ /// <summary>
+ /// Removes the ID and its associated data from the options.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="key">The ID of the option to delete.</param>
+ /// <returns>True if operation is successful. Otherwise, false.</returns>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <seealso cref="Add()"/>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
+ /// <code>
+ /// ResourceOptions options = new ResourceOptions();
+ /// options.Add(2050, "12345");
+ /// var result = options.Remove(2050);
+ /// </code>
+ public bool Remove(ushort key)
+ {
+ int ret = Interop.IoTConnectivity.Common.Options.Remove(_resourceOptionsHandle, key);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to remove option");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+
+ bool isRemoved = _options.Remove(key);
+
+ return isRemoved;
+ }
+
+ /// <summary>
+ /// Gets the value associated with the specified key.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="key">The option ID.</param>
+ /// <param name="value">Value corresponding to option ID.</param>
+ /// <returns>True if the key exists, false otherwise.</returns>
+ /// <code>
+ /// ResourceOptions options = new ResourceOptions();
+ /// options.Add(2050, "12345");
+ /// string value;
+ /// var isPresent = options.TryGetValue(2050, out value);
+ /// if (isPresent)
+ /// Console.WriteLine("value : {0}", value);
+ /// </code>
+ public bool TryGetValue(ushort key, out string value)
+ {
+ return _options.TryGetValue(key, out value);
+ }
+
+ /// <summary>
+ /// Adds options key and value as a key value pair.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="item">The key value pair.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <seealso cref="Remove()"/>
+ /// <code>
+ /// ResourceOptions options = new ResourceOptions();
+ /// options.Add(new KeyValuePair<ushort, string>(2050, "12345"));
+ /// </code>
+ public void Add(KeyValuePair<ushort, string> item)
+ {
+ Add(item.Key, item.Value);
+ }
+
+ /// <summary>
+ /// Clears the Options collection.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <code>
+ /// ResourceOptions options = new ResourceOptions();
+ /// options.Add(2050, "12345");
+ /// options.Add(2055, "sample");
+ /// options.Clear();
+ /// </code>
+ public void Clear()
+ {
+ foreach (ushort key in Keys)
+ {
+ int ret = Interop.IoTConnectivity.Common.Options.Remove(_resourceOptionsHandle, key);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to remove option");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ };
+ }
+ _options.Clear();
+ }
+
+ /// <summary>
+ /// Checks if the given option pair exists.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="item">The key value pair.</param>
+ /// <returns>True if exists. Otherwise, false.</returns>
+ /// <code>
+ /// ResourceOptions options = new ResourceOptions();
+ /// options.Add(new KeyValuePair<ushort, string>(2050, "12345"));
+ /// var isPresent = options.Contains(new KeyValuePair<ushort, string>(2050, "12345"));
+ /// if (isPresent)
+ /// Console.WriteLine("Key value pair is present");
+ /// </code>
+ public bool Contains(KeyValuePair<ushort, string> item)
+ {
+ return _options.Contains(item);
+ }
+
+ /// <summary>
+ /// Copies the elements of the options collection to an array, starting at a particular index.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="array">The destination array.</param>
+ /// <param name="arrayIndex">Index parameter.</param>
+ /// <code>
+ /// ResourceOptions options = new ResourceOptions();
+ /// options.Add(new KeyValuePair<ushort, string>(2050, "12345"));
+ /// KeyValuePair<ushort, string>[] dest = new KeyValuePair<ushort, string>[options.Count];
+ /// options.CopyTo(dest, 0);
+ /// Console.WriteLine("Dest conatins ({0}, {1})", dest[0].Key, dest[0].Value);
+ /// </code>
+ public void CopyTo(KeyValuePair<ushort, string>[] array, int arrayIndex)
+ {
+ _options.CopyTo(array, arrayIndex);
+ }
+
+ /// <summary>
+ /// Removes the given key value pair from the options.
+ /// </summary>
+ /// <since_tizen>3</since_tizen>
+ /// <param name="item">The key value pair to remove</param>
+ /// <returns>True if operation is successful. Otherwise, false</returns>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <seealso cref="Add()"/>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter</exception>
+ /// <code>
+ /// ResourceOptions options = new ResourceOptions();
+ /// options.Add(new KeyValuePair<ushort, string>(2050, "12345"));
+ /// var result = options.Remove(new KeyValuePair<ushort, string>(2050, "12345"));
+ /// </code>
+ public bool Remove(KeyValuePair<ushort, string> item)
+ {
+ return Remove(item.Key);
+ }
+
+ /// <summary>
+ /// Get the enumerator to options collection.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <returns>Enumerator to option pairs.</returns>
+ /// <code>
+ /// ResourceOptions options = new ResourceOptions();
+ /// options.Add(new KeyValuePair<ushort, string>(2050, "sample1"));
+ /// options.Add(new KeyValuePair<ushort, string>(2055, "sample2"));
+ /// foreach (KeyValuePair<string, object> pair in options)
+ /// {
+ /// Console.WriteLine("key : {0}, value : {1}", pair.Key, pair.Value);
+ /// }
+ /// </code>
+ public IEnumerator<KeyValuePair<ushort, string>> GetEnumerator()
+ {
+ return _options.GetEnumerator();
+ }
+
+ /// <summary>
+ /// Releases any unmanaged resources used by this object.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ /// <summary>
+ /// Gets the enumerator to options collection.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <returns>Enumerator to option pairs.</returns>
+ /// <code>
+ /// ResourceOptions options = new ResourceOptions();
+ /// options.Add(new KeyValuePair<ushort, string>(2050, "sample1"));
+ /// options.Add(new KeyValuePair<ushort, string>(2055, "sample2"));
+ /// foreach (KeyValuePair<string, object> pair in options)
+ /// {
+ /// Console.WriteLine("key : {0}, value : {1}", pair.Key, pair.Value);
+ /// }
+ /// </code>
+ IEnumerator IEnumerable.GetEnumerator()
+ {
+ return _options.GetEnumerator();
+ }
+
+ /// <summary>
+ /// Releases any unmanaged resources used by this object. Can also dispose any other disposable objects.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="disposing">If true, disposes any disposable objects. If false, does not dispose disposable objects.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ protected virtual void Dispose(bool disposing)
+ {
+ if (_disposed)
+ return;
+
+ if (disposing)
+ {
+ // Free managed objects
+ }
+
+ Interop.IoTConnectivity.Common.Options.Destroy(_resourceOptionsHandle);
+ _disposed = true;
+ }
+
+ private bool IsValid(ushort key, string value)
+ {
+ return (key > IdMin && key < IdMax && value.Length <= DataMax && _options.Count() < MaxSize);
+ }
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+using System;
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// Enumeration for the policy, which can be held in a resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public enum ResourcePolicy
+ {
+ /// <summary>
+ /// Indicates resource uninitialized.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ NoProperty = 0,
+ /// <summary>
+ /// Indicates resource that is allowed to be discovered.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ Discoverable = (1 << 0),
+ /// <summary>
+ /// Indicates resource that is allowed to be observed.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ Observable = (1 << 1),
+ /// <summary>
+ /// Indicates resource initialized and activated.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ Active = (1 << 2),
+ /// <summary>
+ /// Indicates resource, which takes some delay to respond.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ Slow = (1 << 3),
+ /// <summary>
+ /// Indicates secure resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ Secure = (1 << 4),
+ /// <summary>
+ /// When this bit is set, the resource is allowed to be discovered only if discovery request contains an explicit querystring.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ ExplicitDiscoverable = (1 << 5),
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// This class provides APIs to manage the query of request.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public class ResourceQuery : IDictionary<string, string>, IDisposable
+ {
+ internal const int QueryMaxLenth = 64;
+ internal IntPtr _resourceQueryHandle = IntPtr.Zero;
+ private readonly IDictionary<string, string> _query = new Dictionary<string, string>();
+ private bool _disposed = false;
+
+ /// <summary>
+ /// The resource query constructor.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <seealso cref="Add()"/>
+ /// <seealso cref="Remove()"/>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory.</exception>
+ /// <code>
+ /// ResourceQuery query = new ResourceQuery();
+ /// </code>
+ public ResourceQuery()
+ {
+ int ret = Interop.IoTConnectivity.Common.Query.Create(out _resourceQueryHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to create query");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+
+ internal ResourceQuery(IntPtr resourceQueryHandleToClone)
+ {
+ int ret = Interop.IoTConnectivity.Common.Query.Create(out _resourceQueryHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to create query");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+
+ Interop.IoTConnectivity.Common.Query.QueryCallback forEachCallback = (string key, string value, IntPtr userData) =>
+ {
+ Add(key, value);
+ return true;
+ };
+
+ ret = Interop.IoTConnectivity.Common.Query.Foreach(resourceQueryHandleToClone, forEachCallback, IntPtr.Zero);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to iterate query");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+
+ /// <summary>
+ /// Destructor of the ResourceQuery class.
+ /// </summary>
+ ~ResourceQuery()
+ {
+ Dispose(false);
+ }
+
+ /// <summary>
+ /// Gets and sets the resource type of the query.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The resource type of the query.</value>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
+ /// <code>
+ /// ResourceQuery query = new ResourceQuery();
+ /// query.Type = "org.tizen.light";
+ /// Console.WriteLine("Type of query : {0}", query.Type);
+ /// </code>
+ public string Type
+ {
+ get
+ {
+ IntPtr type;
+ int ret = Interop.IoTConnectivity.Common.Query.GetResourceType(_resourceQueryHandle, out type);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get type");
+ return "";
+ }
+ return (type != IntPtr.Zero) ? Marshal.PtrToStringAnsi(type) : string.Empty;
+ }
+ set
+ {
+ int ret = (int)IoTConnectivityError.InvalidParameter;
+ if (ResourceTypes.IsValid(value))
+ ret = Interop.IoTConnectivity.Common.Query.SetResourceType(_resourceQueryHandle, value);
+
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to set type");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ }
+
+ /// <summary>
+ /// Gets and sets the resource interface of the query.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>
+ /// The resource interface of the query.
+ /// Setter value could be a value, such as <see cref="ResourceInterfaces.DefaultInterface"/>.
+ /// </value>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
+ /// <code>
+ /// ResourceQuery query = new ResourceQuery();
+ /// query.Interface = ResourceInterfaces.LinkInterface;
+ /// </code>
+ public string Interface
+ {
+ get
+ {
+ IntPtr iface;
+ int ret = Interop.IoTConnectivity.Common.Query.GetInterface(_resourceQueryHandle, out iface);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to get interface");
+ return "";
+ }
+ return (iface != IntPtr.Zero) ? Marshal.PtrToStringAnsi(iface) : string.Empty;
+ }
+ set
+ {
+ int ret = (int)IoTConnectivityError.InvalidParameter;
+ if (ResourceInterfaces.IsValid(value))
+ ret = Interop.IoTConnectivity.Common.Query.SetInterface(_resourceQueryHandle, value);
+
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to set interface");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ }
+
+ /// <summary>
+ /// Contains all the query keys.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>All the query keys.</value>
+ /// <code>
+ /// ResourceQuery query = new ResourceQuery();
+ /// query.Add("key", "value");
+ /// query.Add("newKey", "sample value");
+ /// var keys = query.Keys;
+ /// Console.WriteLine("Resource query contains keys {0} and {1}", keys.ElementAt(0), keys.ElementAt(1));
+ /// </code>
+ public ICollection<string> Keys
+ {
+ get
+ {
+ return _query.Keys;
+ }
+ }
+
+ /// <summary>
+ /// Contains all the query values.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>All the query values.</value>
+ /// <code>
+ /// ResourceQuery query = new ResourceQuery();
+ /// query.Add("key", "value");
+ /// query.Add("newKey", "sample value");
+ /// var values = query.Values;
+ /// Console.WriteLine("Resource query contains values {0} and {1}", values.ElementAt(0), values.ElementAt(1));
+ /// </code>
+ public ICollection<string> Values
+ {
+ get
+ {
+ return _query.Values;
+ }
+ }
+
+ /// <summary>
+ /// Gets the number of query elements.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The number of query elements.</value>
+ /// <code>
+ /// ResourceQuery query = new ResourceQuery();
+ /// query.Add("key", "value");
+ /// query.Add("newKey", "sample value");
+ /// var count = query.Count;
+ /// Console.WriteLine("There are {0} keys in the query object", count);
+ /// </code>
+ public int Count
+ {
+ get
+ {
+ return _query.Count;
+ }
+ }
+
+ /// <summary>
+ /// Represents whether the collection is readonly.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>Whether the collection is readonly.</value>
+ /// <code>
+ /// ResourceQuery query = new ResourceQuery();
+ /// if (query.IsReadOnly)
+ /// Console.WriteLine("Read only query");
+ /// </code>
+ public bool IsReadOnly
+ {
+ get
+ {
+ return _query.IsReadOnly;
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the query data.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The query data.</value>
+ /// <param name="key">The query key to get or set.</param>
+ /// <returns>The query with the specified key.</returns>
+ /// <code>
+ /// ResourceQuery query = new ResourceQuery();
+ /// query["key1"] = "sample-data";
+ /// Console.WriteLine("query has : {0}", query["key1"]);
+ /// </code>
+ public string this[string key]
+ {
+ get
+ {
+ return _query[key];
+ }
+
+ set
+ {
+ Add(key, value);
+ }
+ }
+
+ /// <summary>
+ /// Checks whether the given key exists in the query collection.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="key">The key to look for.</param>
+ /// <returns>true if exists. Otherwise, false.</returns>
+ /// <code>
+ /// ResourceQuery query = new ResourceQuery();
+ /// query.Add("key1", "value1");
+ /// if (query.ContainsKey("key1"))
+ /// Console.WriteLine("query conatins key : key1");
+ /// </code>
+ public bool ContainsKey(string key)
+ {
+ return _query.ContainsKey(key);
+ }
+
+ /// <summary>
+ /// Adds a new key and correspoding value into the query.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <remarks>
+ /// The full length of query should be less than or equal to 64.
+ /// </remarks>
+ /// <param name="key">The key of the query to insert.</param>
+ /// <param name="value">The string data to insert into the query.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <seealso cref="Remove()"/>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
+ /// <code>
+ /// ResourceQuery query = new ResourceQuery();
+ /// query.Add("key1", "value1");
+ /// </code>
+ public void Add(string key, string value)
+ {
+ if (CanAddQuery(key, value))
+ {
+ int ret = Interop.IoTConnectivity.Common.Query.Add(_resourceQueryHandle, key, value);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add query");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ _query.Add(key, value);
+ }
+ else
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Query cannot be added");
+ throw IoTConnectivityErrorFactory.GetException((int)IoTConnectivityError.InvalidParameter);
+ }
+ }
+
+ /// <summary>
+ /// Removes the key and its associated value from the query.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="key">The ID of the query to delete.</param>
+ /// <returns>True if operation is successful. Otherwise, false.</returns>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <seealso cref="Add()"/>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
+ /// <code>
+ /// ResourceQuery query = new ResourceQuery();
+ /// query.Add("key1", "value1");
+ /// var result = query.Remove("key1");
+ /// </code>
+ public bool Remove(string key)
+ {
+ int ret = Interop.IoTConnectivity.Common.Query.Remove(_resourceQueryHandle, key);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to remove query");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+
+ bool isRemoved = _query.Remove(key);
+
+ return isRemoved;
+ }
+
+ /// <summary>
+ /// Gets the value associated with the specified key.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="key">The query key.</param>
+ /// <param name="value">Value corresponding to query key.</param>
+ /// <returns>True if the key exists, false otherwise.</returns>
+ /// <code>
+ /// ResourceQuery query = new ResourceQuery();
+ /// query.Add("key1", "value1");
+ /// string value;
+ /// var isPresent = query.TryGetValue("key1", out value);
+ /// if (isPresent)
+ /// Console.WriteLine("value : {0}", value);
+ /// </code>
+ public bool TryGetValue(string key, out string value)
+ {
+ return _query.TryGetValue(key, out value);
+ }
+
+ /// <summary>
+ /// Adds a query key and a value as a key value pair.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="item">The key value pair.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <seealso cref="Remove()"/>
+ /// <code>
+ /// ResourceQuery query = new ResourceQuery();
+ /// query.Add(new KeyValuePair<string, string>("key1", "value1"));
+ /// </code>
+ public void Add(KeyValuePair<string, string> item)
+ {
+ Add(item.Key, item.Value);
+ }
+
+ /// <summary>
+ /// Clears the query collection.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
+ /// <code>
+ /// ResourceQuery query = new ResourceQuery();
+ /// query.Add("key1", "value1");
+ /// query.Add("key2", "value2");
+ /// query.Clear();
+ /// </code>
+ public void Clear()
+ {
+ foreach (string key in _query.Keys)
+ {
+ int ret = Interop.IoTConnectivity.Common.Query.Remove(_resourceQueryHandle, key);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to clear query");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+ _query.Clear();
+ }
+
+ /// <summary>
+ /// Checks if the given query pair exists.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="item">The key value pair.</param>
+ /// <returns>True if exists. Otherwise, false.</returns>
+ /// <code>
+ /// ResourceQuery query = new ResourceQuery();
+ /// query.Add(new KeyValuePair<string, string>("key1", "value1"));
+ /// var isPresent = query.Contains(new KeyValuePair<string, string>("key1", "value1"));
+ /// if (isPresent)
+ /// Console.WriteLine("Key value pair is present");
+ /// </code>
+ public bool Contains(KeyValuePair<string, string> item)
+ {
+ return _query.Contains(item);
+ }
+
+ /// <summary>
+ /// Copies the elements of the query collection to an array, starting at a particular index.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="array">The destination array.</param>
+ /// <param name="arrayIndex">Index parameter.</param>
+ /// <code>
+ /// ResourceQuery query = new ResourceQuery();
+ /// query.Add(new KeyValuePair<string, string>("key1", "value1"));
+ /// KeyValuePair<string, string>[] dest = new KeyValuePair<string, string>[query.Count];
+ /// query.CopyTo(dest, 0);
+ /// Console.WriteLine("Dest conatins ({0}, {1})", dest[0].Key, dest[0].Value);
+ /// </code>
+ public void CopyTo(KeyValuePair<string, string>[] array, int arrayIndex)
+ {
+ _query.CopyTo(array, arrayIndex);
+ }
+
+ /// <summary>
+ /// Removes the given key value pair from the query.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="item">The key value pair to remove.</param>
+ /// <returns>True if operation is successful. Otherwise, false.</returns>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <seealso cref="Add()"/>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
+ /// <code>
+ /// ResourceQuery query = new ResourceQuery();
+ /// query.Add(new KeyValuePair<string, string>("key1", "value1"));
+ /// var result = query.Remove(new KeyValuePair<string, string>("key1", "value1"));
+ /// </code>
+ public bool Remove(KeyValuePair<string, string> item)
+ {
+ return Remove(item.Key);
+ }
+
+ /// <summary>
+ /// Gets the enumerator to the query collection.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <returns>Enumerator to query pairs.</returns>
+ /// <code>
+ /// ResourceQuery query = new ResourceQuery();
+ /// query.Add(new KeyValuePair<string, string>("key1", "value1"));
+ /// query.Add(new KeyValuePair<string, string>("key2", "value2"));
+ /// foreach (KeyValuePair<string, string> pair in query)
+ /// {
+ /// Console.WriteLine("key : {0}, value : {1}", pair.Key, pair.Value);
+ /// }
+ /// </code>
+ public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
+ {
+ return _query.GetEnumerator();
+ }
+
+ /// <summary>
+ /// Gets the enumerator to the query collection.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <returns>The enumerator to the query pairs.</returns>
+ /// <code>
+ /// ResourceQuery query = new ResourceQuery();
+ /// query.Add(new KeyValuePair<string, string>("key1", "value1"));
+ /// query.Add(new KeyValuePair<string, string>("key2", "value2"));
+ /// foreach (KeyValuePair<string, string> pair in query)
+ /// {
+ /// Console.WriteLine("key : {0}, value : {1}", pair.Key, pair.Value);
+ /// }
+ /// </code>
+ IEnumerator IEnumerable.GetEnumerator()
+ {
+ return _query.GetEnumerator();
+ }
+
+ /// <summary>
+ /// Releases any unmanaged resources used by this object.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ /// <summary>
+ /// Releases any unmanaged resources used by this object. Can also dispose any other disposable objects.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="disposing">If true, disposes any disposable objects. If false, does not dispose disposable objects.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ protected virtual void Dispose(bool disposing)
+ {
+ if (_disposed)
+ return;
+
+ if (disposing)
+ {
+ // Free managed objects
+ }
+
+ Interop.IoTConnectivity.Common.Query.Destroy(_resourceQueryHandle);
+ _disposed = true;
+ }
+
+ private bool CanAddQuery(string newKey, string newValue)
+ {
+ int queryLenth = 0;
+ foreach (string key in Keys)
+ {
+ queryLenth += key.Length + 2;
+ }
+ foreach (string value in Values)
+ {
+ queryLenth += value.Length;
+ }
+
+ if ((newKey.Length + newValue.Length + queryLenth + 2) < QueryMaxLenth)
+ return true;
+
+ return false;
+ }
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// Enumeration for states of the remote resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public enum ResourceState
+ {
+ /// <summary>
+ /// Indicates remote resource is alive.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ Alive = 0,
+ /// <summary>
+ /// Indicates remote resource is lost.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ LostSignal
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Text.RegularExpressions;
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// This class contains resource types and provides APIs to manage, add, or remove those types.
+ /// A resource type indicates a class or a category of resources.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public class ResourceTypes : IEnumerable<string>, IDisposable
+ {
+ internal const int MaxLength = 61;
+ internal IntPtr _resourceTypeHandle = IntPtr.Zero;
+ private readonly HashSet<string> _resourceTypes = new HashSet<string>();
+ private bool _disposed = false;
+
+ /// <summary>
+ /// Constructor of ResourceTypes.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <seealso cref="Add()"/>
+ /// <seealso cref="Remove()"/>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory.</exception>
+ /// <code>
+ /// ResourceTypes types = new ResourceTypes();
+ /// </code>
+ public ResourceTypes()
+ {
+ int ret = Interop.IoTConnectivity.Common.ResourceTypes.Create(out _resourceTypeHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to create type");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+
+ /// <summary>
+ /// Constructor of ResourceTypes using list of types.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="types">List of resource types.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
+ /// <code>
+ /// ResourceTypes types = new ResourceTypes(new List<string>() { "org.tizen.light", "oic.if.room" });
+ /// </code>
+ public ResourceTypes(IEnumerable<string> types)
+ {
+ int ret = Interop.IoTConnectivity.Common.ResourceTypes.Create(out _resourceTypeHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to create type");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+
+ foreach (string type in types)
+ {
+ Add(type);
+ }
+ }
+
+ internal ResourceTypes(IntPtr typesHandleToClone)
+ {
+ int ret = Interop.IoTConnectivity.Common.ResourceTypes.Clone(typesHandleToClone, out _resourceTypeHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to create type");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+
+ Interop.IoTConnectivity.Common.ResourceTypes.ForeachCallback cb = (string type, IntPtr data) =>
+ {
+ _resourceTypes.Add(type);
+ return true;
+ };
+
+ ret = Interop.IoTConnectivity.Common.ResourceTypes.Foreach(typesHandleToClone, cb, IntPtr.Zero);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to create type");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ }
+
+ /// <summary>
+ /// Destructor of the ResourceTypes class.
+ /// </summary>
+ ~ResourceTypes()
+ {
+ Dispose(false);
+ }
+
+ /// <summary>
+ /// Indicates count of types in the list.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>Count of types in the list.</value>
+ /// <code>
+ /// ResourceTypes types = new ResourceTypes(new List<string>() { "org.tizen.light", "oic.if.room" });
+ /// Console.WriteLine("There are {0} items", types.Count);
+ /// </code>
+ public int Count
+ {
+ get
+ {
+ return _resourceTypes.Count;
+ }
+ }
+
+ /// <summary>
+ /// Adds a resource type into the list.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <remarks>
+ /// The length of @a item should be less than or equal to 61.\n
+ /// The @a item must start with a lowercase alphabetic character, followed by a sequence
+ /// of lowercase alphabetic, numeric, ".", or "-" characters, and contains no white space.\n
+ /// Duplicate strings are not allowed.
+ /// </remarks>
+ /// <param name="item">The string data to insert into the resource types.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <seealso cref="Remove()"/>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
+ /// <code>
+ /// ResourceTypes resourceTypes = new ResourceTypes();
+ /// resourceTypes.Add("org.tizen.light");
+ /// </code>
+ public void Add(string item)
+ {
+ if (IsValid(item))
+ {
+ int ret = Interop.IoTConnectivity.Common.ResourceTypes.Add(_resourceTypeHandle, item);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to add type");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+ _resourceTypes.Add(item);
+ }
+ else
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Invalid type");
+ throw IoTConnectivityErrorFactory.GetException((int)IoTConnectivityError.InvalidParameter);
+ }
+ }
+
+ /// <summary>
+ /// Removes a resource type from the list.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="item">The string data to delete from the resource types.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ /// <seealso cref="Add()"/>
+ /// <exception cref="NotSupportedException">Thrown when the iotcon is not supported.</exception>
+ /// <exception cref="ArgumentException">Thrown when there is an invalid parameter.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the operation is invalid.</exception>
+ /// <code>
+ /// ResourceTypes resourceTypes = new ResourceTypes(new List<string>() { "org.tizen.light", "oic.if.room" });
+ /// resourceTypes.Remove("oic.if.room");
+ /// </code>
+ public void Remove(string item)
+ {
+ int ret = Interop.IoTConnectivity.Common.ResourceTypes.Remove(_resourceTypeHandle, item);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to remove type");
+ throw IoTConnectivityErrorFactory.GetException(ret);
+ }
+
+ _resourceTypes.Remove(item);
+ }
+
+ /// <summary>
+ /// Returns an enumerator for the list of types.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <returns>The enumerator.</returns>
+ /// <code>
+ /// ResourceTypes resourceTypes = new ResourceTypes(new List<string>() { "org.tizen.light", "oic.if.room" });
+ /// foreach(string item in resourceTypes)
+ /// {
+ /// Console.WriteLine("Type : {0}", item);
+ /// }
+ /// </code>
+ public IEnumerator<string> GetEnumerator()
+ {
+ return _resourceTypes.GetEnumerator();
+ }
+
+ /// <summary>
+ /// Returns an enumerator for the list of types.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <returns>The enumerator.</returns>
+ /// <code>
+ /// ResourceTypes resourceTypes = new ResourceTypes(new List<string>() { "org.tizen.light", "oic.if.room" });
+ /// foreach(string item in resourceTypes)
+ /// {
+ /// Console.WriteLine("Type : {0}", item);
+ /// }
+ /// </code>
+ IEnumerator IEnumerable.GetEnumerator()
+ {
+ return _resourceTypes.GetEnumerator();
+ }
+
+ /// <summary>
+ /// Releases any unmanaged resources used by this object.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ internal static bool IsValid(string type)
+ {
+ Regex r = new Regex("^[a-zA-Z0-9.-]+$");
+ return (type.Length <= MaxLength && type.Length > 0 && char.IsLower(type[0]) && r.IsMatch(type));
+ }
+
+ /// <summary>
+ /// Releases any unmanaged resources used by this object. Can also dispose any other disposable objects.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="disposing">If true, disposes any disposable objects. If false, does not dispose disposable objects.</param>
+ /// <feature>http://tizen.org/feature/iot.ocf</feature>
+ protected virtual void Dispose(bool disposing)
+ {
+ if (_disposed)
+ return;
+
+ if (disposing)
+ {
+ // Free managed objects
+ }
+
+ Interop.IoTConnectivity.Common.ResourceTypes.Destroy(_resourceTypeHandle);
+ _disposed = true;
+ }
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+using System;
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// This class represents response from a resource.
+ /// It provides APIs to manage response.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public class Response : IDisposable
+ {
+ private bool _disposed = false;
+
+ /// <summary>
+ /// Constructor of Response.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <code>
+ /// Response response = new Response();
+ /// </code>
+ public Response() { }
+
+ /// <summary>
+ /// Destructor of the Response class.
+ /// </summary>
+ ~Response()
+ {
+ Dispose(false);
+ }
+
+ /// <summary>
+ /// Gets or sets the result from/into the response.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The result from/into the response.</value>
+ public ResponseCode Result { get; set; }
+
+ /// <summary>
+ /// Gets or sets the representation from/into the response.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The representation from/into the response.</value>
+ public Representation Representation { get; set; }
+
+ /// <summary>
+ /// Gets or sets the options from/into the response.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The options from/into the response.</value>
+ public ResourceOptions Options { get; set; }
+
+ /// <summary>
+ /// Releases any unmanaged resources used by this object.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ internal bool Send(IntPtr requestHandle)
+ {
+ IntPtr responseHandle = IntPtr.Zero;
+ int ret = Interop.IoTConnectivity.Server.Response.Create(requestHandle, out responseHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to send response");
+ return false;
+ }
+
+ ret = Interop.IoTConnectivity.Server.Response.SetResult(responseHandle, (int)Result);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to send response");
+ Interop.IoTConnectivity.Server.Response.Destroy(responseHandle);
+ return false;
+ }
+
+ if (Representation != null)
+ {
+ ret = Interop.IoTConnectivity.Server.Response.SetRepresentation(responseHandle, Representation._representationHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to send response");
+ Interop.IoTConnectivity.Server.Response.Destroy(responseHandle);
+ return false;
+ }
+ }
+
+ if (Options != null)
+ {
+ ret = Interop.IoTConnectivity.Server.Response.SetOptions(responseHandle, Options._resourceOptionsHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to send response");
+ Interop.IoTConnectivity.Server.Response.Destroy(responseHandle);
+ return false;
+ }
+ }
+
+ ret = Interop.IoTConnectivity.Server.Response.Send(responseHandle);
+ if (ret != (int)IoTConnectivityError.None)
+ {
+ Log.Error(IoTConnectivityErrorFactory.LogTag, "Failed to send response");
+ Interop.IoTConnectivity.Server.Response.Destroy(responseHandle);
+ return false;
+ }
+
+ Interop.IoTConnectivity.Server.Response.Destroy(responseHandle);
+ return true;
+ }
+
+ /// <summary>
+ /// Releases any unmanaged resources used by this object. Can also dispose any other disposable objects.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <param name="disposing">If true, disposes any disposable objects. If false, does not dispose disposable objects.</param>
+ protected virtual void Dispose(bool disposing)
+ {
+ if (_disposed)
+ return;
+
+ if (disposing)
+ {
+ }
+
+ _disposed = true;
+ }
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// Enumeration for the result of response.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public enum ResponseCode
+ {
+ /// <summary>
+ /// Indicates the result of response for success.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ Ok = 0,
+ /// <summary>
+ /// Indicates the result of response for some error.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ Error,
+ /// <summary>
+ /// Indicates the result of response for created resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ Created,
+ /// <summary>
+ /// Indicates the result of response for deleted resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ Deleted,
+ /// <summary>
+ /// Indicates the result of response for changed resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ Changed,
+ /// <summary>
+ /// Indicates the result of response for slow resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ Slow,
+ /// <summary>
+ /// Indicates the result of response for accessing unauthorized resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ Forbidden
+ }
+}
--- /dev/null
+ /*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+using System;
+
+namespace Tizen.Network.IoTConnectivity
+{
+ /// <summary>
+ /// This class represents event arguments of the StateChanged event.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ public class StateChangedEventArgs : EventArgs
+ {
+ internal StateChangedEventArgs() { }
+
+ /// <summary>
+ /// Indicates the new state of the resource.
+ /// </summary>
+ /// <since_tizen> 3 </since_tizen>
+ /// <value>The new state of the resource.</value>
+ public ResourceState State { get; internal set; }
+ }
+}