diff options
author | Gowtham Anandha Babu <gowtham.ab@samsung.com> | 2016-12-26 12:19:12 +0530 |
---|---|---|
committer | Gowtham Anandha Babu <gowtham.ab@samsung.com> | 2016-12-26 12:28:18 +0530 |
commit | 7f1e8988b4982664f4356e44f090377a6c339b7d (patch) | |
tree | ab7a992877cd15f1eb63cf29a200b20c61d9b692 /Tizen.Network.Nfc | |
parent | ba8fc7f83fd5419feef2c57750d0ad14dd4652c4 (diff) | |
download | nfc-7f1e8988b4982664f4356e44f090377a6c339b7d.tar.gz nfc-7f1e8988b4982664f4356e44f090377a6c339b7d.tar.bz2 nfc-7f1e8988b4982664f4356e44f090377a6c339b7d.zip |
[C# Nfc]: Rename Tizen.Nfc to Tizen.Network.Nfcsubmit/tizen/20170102.053259submit/tizen/20161228.005300accepted/tizen/tv/20170102.060847accepted/tizen/mobile/20170102.060826
Change-Id: I5d167c57aa46ac20f98ea6c56f0fbc4c09ad7415
Signed-off-by: Gowtham Anandha Babu <gowtham.ab@samsung.com>
Diffstat (limited to 'Tizen.Network.Nfc')
26 files changed, 3834 insertions, 0 deletions
diff --git a/Tizen.Network.Nfc/Interop/Interop.Glib.cs b/Tizen.Network.Nfc/Interop/Interop.Glib.cs new file mode 100644 index 0000000..576a6e2 --- /dev/null +++ b/Tizen.Network.Nfc/Interop/Interop.Glib.cs @@ -0,0 +1,30 @@ +/* + * 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 Glib + { + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + internal delegate bool GSourceFunc(IntPtr userData); + + [DllImport(Libraries.Glib, EntryPoint = "g_idle_add", CallingConvention = CallingConvention.Cdecl)] + internal static extern uint IdleAdd(GSourceFunc d, IntPtr data); + } +} diff --git a/Tizen.Network.Nfc/Interop/Interop.Libc.cs b/Tizen.Network.Nfc/Interop/Interop.Libc.cs new file mode 100644 index 0000000..825599e --- /dev/null +++ b/Tizen.Network.Nfc/Interop/Interop.Libc.cs @@ -0,0 +1,27 @@ +/* + * 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 Libc + { + [DllImport(Libraries.Libc, EntryPoint = "free", CallingConvention = CallingConvention.Cdecl)] + internal static extern int Free(IntPtr ptr); + } +} diff --git a/Tizen.Network.Nfc/Interop/Interop.Libraries.cs b/Tizen.Network.Nfc/Interop/Interop.Libraries.cs new file mode 100644 index 0000000..8984d71 --- /dev/null +++ b/Tizen.Network.Nfc/Interop/Interop.Libraries.cs @@ -0,0 +1,25 @@ +/* + * 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 Nfc = "libcapi-network-nfc.so.0"; + public const string Glib = "libglib-2.0.so.0"; + public const string Libc = "libc.so.6"; + } +} diff --git a/Tizen.Network.Nfc/Interop/Interop.Nfc.cs b/Tizen.Network.Nfc/Interop/Interop.Nfc.cs new file mode 100644 index 0000000..d6ad84a --- /dev/null +++ b/Tizen.Network.Nfc/Interop/Interop.Nfc.cs @@ -0,0 +1,281 @@ +/* + * 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 Nfc + { + //Callback for async method + //nfc_activation_completed_cb + //nfc_tag_write_completed_cb + //nfc_tag_format_completed_cb + //nfc_mifare_authenticate_with_keyA_completed_cb + //nfc_mifare_authenticate_with_keyB_completed_cb + //nfc_mifare_write_block_completed_cb + //nfc_mifare_write_page_completed_cb + //nfc_mifare_increment_completed_cb + //nfc_mifare_decrement_completed_cb + //nfc_mifare_transfer_completed_cb + //nfc_mifare_restore_completed_cb + //nfc_p2p_send_completed_cb + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + internal delegate void VoidCallback(int result, IntPtr userData); + //nfc_tag_information_cb + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + internal delegate bool TagInformationCallback(IntPtr key, IntPtr value, int valueSize, IntPtr userData); + //nfc_tag_transceive_completed_cb + //nfc_mifare_read_block_completed_cb + //nfc_mifare_read_page_completed_cb + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + internal delegate void TagTransceiveCompletedCallback(int result, IntPtr value, int bufferSize, IntPtr userData); + //nfc_tag_read_completed_cb + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + internal delegate bool TagReadCompletedCallback(int result, IntPtr message, IntPtr userData); + //nfc_snep_event_cb + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + internal delegate void SnepEventCallback(IntPtr handle, int snepEvent, int result, IntPtr message, IntPtr userData); + //nfc_se_registered_aid_cb + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + internal delegate void SecureElementRegisteredAidCallback(int seType, IntPtr aid, bool readOnly, IntPtr userData); + + + //Callback for event + //nfc_activation_changed_cb + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + internal delegate void ActivationChangedCallback(bool activated, IntPtr userData); + //nfc_tag_discovered_cb + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + internal delegate void TagDiscoveredCallback(int type, IntPtr tag, IntPtr userData); + //nfc_p2p_target_discovered_cb + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + internal delegate void P2pTargetDiscoveredCallback(int type, IntPtr p2pTaget, IntPtr userData); + //nfc_ndef_discovered_cb + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + internal delegate void NdefMessageDiscoveredCallback(IntPtr message, IntPtr userData); + //nfc_se_event_cb + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + internal delegate void SecureElementEventCallback(int eventType, IntPtr userData); + //nfc_se_transaction_event_cb + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + internal delegate void SecureElementTransactionEventCallback(int type, IntPtr aid, int aidSize, IntPtr param, int paramSize, IntPtr userData); + //nfc_p2p_data_received_cb + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + internal delegate void P2pDataReceivedCallback(IntPtr target, IntPtr message, IntPtr userData); + //nfc_hce_event_cb + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + internal delegate void HostCardEmulationEventCallback(IntPtr handle, int eventType, IntPtr apdu, uint apduLen, IntPtr userData); + + //capi-network-nfc-0.2.5-6.1.armv7l + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_initialize")] + internal static extern int Initialize(); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_deinitialize")] + internal static extern int Deinitialize(); + + ////Nfc Manager + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_is_supported")] + internal static extern bool IsSupported(); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_set_activation")] + internal static extern int SetActivation(bool activation, VoidCallback callback, IntPtr userData); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_is_activated")] + internal static extern bool IsActivated(); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_set_activation_changed_cb")] + internal static extern int SetActivationChangedCallback(ActivationChangedCallback callback, IntPtr userData); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_unset_activation_changed_cb")] + internal static extern void UnsetActivationChangedCallback(); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_set_tag_discovered_cb")] + internal static extern int SetTagDiscoveredCallback(TagDiscoveredCallback callback, IntPtr userData); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_unset_tag_discovered_cb")] + internal static extern void UnsetTagDiscoveredCallback(); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_set_ndef_discovered_cb")] + internal static extern int SetNdefDiscoveredCallback(NdefMessageDiscoveredCallback callback, IntPtr userData); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_unset_ndef_discovered_cb")] + internal static extern void UnsetNdefDiscoveredCallback(); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_set_p2p_target_discovered_cb")] + internal static extern int SetP2pTargetDiscoveredCallback(P2pTargetDiscoveredCallback callback, IntPtr userData); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_unset_p2p_target_discovered_cb")] + internal static extern void UnsetP2pTargetDiscoveredCallback(); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_set_se_event_cb")] + internal static extern int SetSecureElementEventCallback(SecureElementEventCallback callback, IntPtr userData); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_unset_se_event_cb")] + internal static extern void UnsetSecureElementEventCallback(); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_set_se_transaction_event_cb")] + internal static extern int SetSecureElementTransactionEventCallback(int setype, SecureElementTransactionEventCallback callback, IntPtr userData); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_unset_se_transaction_event_cb")] + internal static extern int UnsetSecureElementTransactionEventCallback(int setype); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_set_hce_event_cb")] + internal static extern int SetHostCardEmulationEventCallback(HostCardEmulationEventCallback callback, IntPtr userData); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_unset_hce_event_cb")] + internal static extern void UnsetHostCardEmulationEventCallback(); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_enable_transaction_fg_dispatch")] + internal static extern int EnableTransactionForegroundDispatch(); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_disable_transaction_fg_dispatch")] + internal static extern int DisableTransactionForegroundDispatch(); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_get_cached_message")] + internal static extern int GetCachedMessage(out IntPtr ndefMessage); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_set_tag_filter")] + internal static extern void SetTagFilter(int filter); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_get_tag_filter")] + internal static extern int GetTagFilter(); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_get_connected_tag")] + internal static extern int GetConnectedTag(out IntPtr tag); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_get_connected_target")] + internal static extern int GetConnectedTarget(out IntPtr target); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_set_system_handler_enable")] + internal static extern int SetSystemHandlerEnable(bool enable); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_is_system_handler_enabled")] + internal static extern bool IsSystemHandlerEnabled(); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_set_se_type")] + internal static extern int SetSecureElementType(int type); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_manager_get_se_type")] + internal static extern int GetSecureElementType(out int type); + + ////NDEF - NFC Data Exchange Format, TNF - Type Name Format + internal static class NdefRecord + { + [DllImport(Libraries.Nfc, EntryPoint = "nfc_ndef_record_create")] + internal static extern int Create(out IntPtr record, int tnf, byte[] type, int typeSize, byte[] id, int idSize, byte[] payload, uint payloadSize); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_ndef_record_create_text")] + internal static extern int CreateText(out IntPtr record, string text, string languageCode, int encode); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_ndef_record_create_uri")] + internal static extern int CreateUri(out IntPtr record, string uri); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_ndef_record_create_mime")] + internal static extern int CreateMime(out IntPtr record, string mimeType, byte[] data, uint dataSize); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_ndef_record_destroy")] + internal static extern int Destroy(IntPtr record); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_ndef_record_set_id")] + internal static extern int SetId(IntPtr record, byte[] id, int idSize); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_ndef_record_get_id")] + internal static extern int GetId(IntPtr record, out IntPtr id, out int size); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_ndef_record_get_payload")] + internal static extern int GetPayload(IntPtr record, out IntPtr payload, out uint size); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_ndef_record_get_type")] + internal static extern int GetType(IntPtr record, out IntPtr type, out int size); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_ndef_record_get_tnf")] + internal static extern int GetTnf(IntPtr record, out int tnf); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_ndef_record_get_text")] + internal static extern int GetText(IntPtr record, out string text); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_ndef_record_get_langcode")] + internal static extern int GetLanguageCode(IntPtr record, out string languageCode); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_ndef_record_get_encode_type")] + internal static extern int GetEncodeType(IntPtr record, out int encode); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_ndef_record_get_uri")] + internal static extern int GetUri(IntPtr record, out string uri); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_ndef_record_get_mime_type")] + internal static extern int GetMimeType(IntPtr record, out string mimeType); + } + + internal static class NdefMessage + { + [DllImport(Libraries.Nfc, EntryPoint = "nfc_ndef_message_create")] + internal static extern int Create(out IntPtr ndefMessage); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_ndef_message_create_from_rawdata")] + internal static extern int CreateRawData(out IntPtr ndefMessage, byte[] rawData, uint rawDataSize); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_ndef_message_destroy")] + internal static extern int Destroy(IntPtr ndefMessage); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_ndef_message_get_record_count")] + internal static extern int GetRecordCount(IntPtr ndefMessage, out int count); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_ndef_message_get_rawdata")] + internal static extern int GetRawData(IntPtr ndefMessage, out IntPtr rawData, out uint rawDataSize); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_ndef_message_append_record")] + internal static extern int AppendRecord(IntPtr ndefMessage, IntPtr record); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_ndef_message_insert_record")] + internal static extern int InsertRecord(IntPtr ndefMessage, int index, IntPtr record); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_ndef_message_remove_record")] + internal static extern int RemoveRecord(IntPtr ndefMessage, int index); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_ndef_message_get_record")] + internal static extern int GetRecord(IntPtr ndefMessage, int index, out IntPtr record); + } + + internal static class Tag + { + [DllImport(Libraries.Nfc, EntryPoint = "nfc_tag_get_type")] + internal static extern int GetType(IntPtr tag, out int type); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_tag_is_support_ndef")] + internal static extern int IsSupportNdef(IntPtr tag, out bool isSupported); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_tag_get_maximum_ndef_size")] + internal static extern int GetMaximumNdefSize(IntPtr tag, out uint maximunNdefBytesSize); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_tag_get_ndef_size")] + internal static extern int GetNdefSize(IntPtr tag, out uint ndefBytesSize); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_tag_foreach_information")] + internal static extern int ForeachInformation(IntPtr tag, TagInformationCallback callback, IntPtr userData); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_tag_transceive")] + internal static extern int Transceive(IntPtr tag, byte[] buffer, int bufferSize, TagTransceiveCompletedCallback callback, IntPtr userData); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_tag_read_ndef")] + internal static extern int ReadNdef(IntPtr tag, TagReadCompletedCallback callback, IntPtr userData); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_tag_write_ndef")] + internal static extern int WriteNdef(IntPtr tag, IntPtr ndefMessage, VoidCallback callback, IntPtr userData); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_tag_format_ndef")] + internal static extern int FormatNdef(IntPtr tag, byte[] key, int kyeSize, VoidCallback callback, IntPtr userData); + + ////Mifare + } + + ////SNEP - Simple NDEF Exchange Protocol + internal static class P2p + { + [DllImport(Libraries.Nfc, EntryPoint = "nfc_p2p_set_data_received_cb")] + internal static extern int SetDataReceivedCallback(IntPtr target, P2pDataReceivedCallback callback, IntPtr userData); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_p2p_unset_data_received_cb")] + internal static extern int UnsetDataReceivedCallback(IntPtr target); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_p2p_send")] + internal static extern int Send(IntPtr target, IntPtr ndefMessage, VoidCallback callback, IntPtr userData); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_snep_start_server")] + internal static extern int SnepStartServer(IntPtr target, string san, int sap, SnepEventCallback callback, IntPtr userData); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_snep_start_client")] + internal static extern int SnepStartClient(IntPtr target, string san, int sap, SnepEventCallback callback, IntPtr userData); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_snep_send_client_request")] + internal static extern int SnepSendClientRequest(IntPtr snepHandle, int type, IntPtr ndefMessage, SnepEventCallback callback, IntPtr userData); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_snep_stop_service")] + internal static extern int SnepStopService(IntPtr target, IntPtr snepHandle); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_snep_register_server")] + internal static extern int SnepRegisterServer(string san, int sap, SnepEventCallback callback, IntPtr userData); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_snep_unregister_server")] + internal static extern int SnepUnregisterServer(string sam, int sap); + } + + ////SE - Secure Element, HCE - Host Card Emulation, APDU - Application Protocol Data Unit, AID - Application Identifier + internal static class CardEmulation + { + [DllImport(Libraries.Nfc, EntryPoint = "nfc_se_enable_card_emulation")] + internal static extern int EnableCardEmulation(); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_se_disable_card_emulation")] + internal static extern int DisableCardEmulatiion(); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_se_get_card_emulation_mode")] + internal static extern int GetCardEmulationMode(out int type); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_hce_send_apdu_response")] + internal static extern int HceSendApduRespondse(IntPtr seHandle, byte[] response, uint responseLength); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_se_set_default_route")] + internal static extern int SetDefaultRoute(int poweredOnStatus, int poweredOffStatus, int lowBatteryStatus); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_se_is_activated_handler_for_aid")] + internal static extern int IsActivatedHandlerForAid(int seType, string aid, out bool isActivatedHandler); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_se_is_activated_handler_for_category")] + internal static extern int IsActivatedHandlerForCategory(int seType, int category, out bool isActivatedHandler); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_se_register_aid")] + internal static extern int RegisterAid(int seType, int category, string aid); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_se_unregister_aid")] + internal static extern int UnregisterAid(int seType, int category, string aid); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_se_foreach_registered_aids")] + internal static extern int ForeachRegisterdAids(int seType, int category, SecureElementRegisteredAidCallback callback, IntPtr userData); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_se_set_preferred_handler")] + internal static extern int SetPreferredHandler(); + [DllImport(Libraries.Nfc, EntryPoint = "nfc_se_unset_preferred_handler")] + internal static extern int UnsetPreferredHandler(); + } + } +} diff --git a/Tizen.Network.Nfc/Properties/AssemblyInfo.cs b/Tizen.Network.Nfc/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..0524a42 --- /dev/null +++ b/Tizen.Network.Nfc/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Tizen.Network.Nfc")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Tizen.Network.Nfc")] +[assembly: AssemblyCopyright("Copyright \u00A9 2016")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("99a90243-7db1-4704-a078-3529c2da4e81")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Tizen.Network.Nfc/Tizen.Network.Nfc.Net45.csproj b/Tizen.Network.Nfc/Tizen.Network.Nfc.Net45.csproj new file mode 100644 index 0000000..066cdc5 --- /dev/null +++ b/Tizen.Network.Nfc/Tizen.Network.Nfc.Net45.csproj @@ -0,0 +1,85 @@ +<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ <ProjectGuid>{BF719F11-CDEA-4D04-A85B-4521A69E3614}</ProjectGuid>
+ <OutputType>Library</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>Tizen.Network.Nfc</RootNamespace>
+ <AssemblyName>Tizen.Network.Nfc</AssemblyName>
+ <FileAlignment>512</FileAlignment>
+ <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ <DebugSymbols>true</DebugSymbols>
+ <DebugType>full</DebugType>
+ <Optimize>false</Optimize>
+ <OutputPath>bin\Debug\Net45\</OutputPath>
+ <DefineConstants>DEBUG;TRACE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ <Prefer32Bit>false</Prefer32Bit>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ <DebugType>pdbonly</DebugType>
+ <Optimize>true</Optimize>
+ <OutputPath>bin\Release\Net45\</OutputPath>
+ <DefineConstants>TRACE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ <Prefer32Bit>false</Prefer32Bit>
+ </PropertyGroup>
+ <PropertyGroup>
+ <SignAssembly>true</SignAssembly>
+ </PropertyGroup>
+ <PropertyGroup>
+ <AssemblyOriginatorKeyFile>Tizen.Network.Nfc.snk</AssemblyOriginatorKeyFile>
+ </PropertyGroup>
+ <ItemGroup>
+ <Reference Include="System" />
+ <Reference Include="System.Core" />
+ <Reference Include="System.Xml.Linq" />
+ <Reference Include="System.Data.DataSetExtensions" />
+ <Reference Include="Microsoft.CSharp" />
+ <Reference Include="System.Data" />
+ <Reference Include="System.Net.Http" />
+ <Reference Include="System.Xml" />
+ </ItemGroup>
+ <ItemGroup>
+ <Compile Include="Interop\Interop.Glib.cs" />
+ <Compile Include="Interop\Interop.Libc.cs" />
+ <Compile Include="Interop\Interop.Libraries.cs" />
+ <Compile Include="Interop\Interop.Nfc.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcCallbackData.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcCardEmulationAdapter.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcEnumerations.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcErrorFactory.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcEventArgs.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcSecureElement.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcManager.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcManagerEvent.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcManagerImpl.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcNdefMessage.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcNdefRecord.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcP2p.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcP2pAdapter.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcTag.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcTagAdapter.cs" />
+
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="Tizen.Network.Nfc.nuspec" />
+ <None Include="Tizen.Network.Nfc.Net45.project.json" />
+ <None Include="Tizen.Network.Nfc.snk" />
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
+ Other similar extension points exist, see Microsoft.Common.targets.
+ <Target Name="BeforeBuild">
+ </Target>
+ <Target Name="AfterBuild">
+ </Target>
+ -->
+</Project>
\ No newline at end of file diff --git a/Tizen.Network.Nfc/Tizen.Network.Nfc.Net45.project.json b/Tizen.Network.Nfc/Tizen.Network.Nfc.Net45.project.json new file mode 100644 index 0000000..1ec1af2 --- /dev/null +++ b/Tizen.Network.Nfc/Tizen.Network.Nfc.Net45.project.json @@ -0,0 +1,11 @@ +{ + "dependencies": { + "Tizen": "1.0.2" + }, + "frameworks": { + "net45": {} + }, + "runtimes": { + "win": {} + } +} diff --git a/Tizen.Network.Nfc/Tizen.Network.Nfc.csproj b/Tizen.Network.Nfc/Tizen.Network.Nfc.csproj new file mode 100644 index 0000000..054a0fb --- /dev/null +++ b/Tizen.Network.Nfc/Tizen.Network.Nfc.csproj @@ -0,0 +1,94 @@ +<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ <ProjectGuid>{3EE5842E-7004-43BC-825B-29FFDEC18D4E}</ProjectGuid>
+ <OutputType>Library</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>Tizen.Network.Nfc</RootNamespace>
+ <AssemblyName>Tizen.Network.Nfc</AssemblyName>
+ <FileAlignment>512</FileAlignment>
+ </PropertyGroup>
+ <PropertyGroup>
+ <TargetFrameworkIdentifier>.NETStandard</TargetFrameworkIdentifier>
+ <TargetFrameworkVersion>v1.3</TargetFrameworkVersion>
+ <NuGetTargetMoniker>.NETStandard,Version=v1.3</NuGetTargetMoniker>
+ <AddAdditionalExplicitAssemblyReferences>false</AddAdditionalExplicitAssemblyReferences>
+ <NoStdLib>true</NoStdLib>
+ <NoWarn>$(NoWarn);1701;1702</NoWarn>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ <DebugSymbols>true</DebugSymbols>
+ <DebugType>full</DebugType>
+ <Optimize>false</Optimize>
+ <OutputPath>bin\Debug\</OutputPath>
+ <DefineConstants>DEBUG;TRACE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ <Prefer32Bit>false</Prefer32Bit>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ <DebugType>pdbonly</DebugType>
+ <Optimize>true</Optimize>
+ <OutputPath>bin\Release\</OutputPath>
+ <DefineConstants>TRACE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ <Prefer32Bit>false</Prefer32Bit>
+ </PropertyGroup>
+ <PropertyGroup>
+ <SignAssembly>true</SignAssembly>
+ </PropertyGroup>
+ <PropertyGroup>
+ <AssemblyOriginatorKeyFile>Tizen.Network.Nfc.snk</AssemblyOriginatorKeyFile>
+ </PropertyGroup>
+ <ItemGroup>
+ <Compile Include="Interop\Interop.Glib.cs" />
+ <Compile Include="Interop\Interop.Libc.cs" />
+ <Compile Include="Interop\Interop.Libraries.cs" />
+ <Compile Include="Interop\Interop.Nfc.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcCallbackData.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcCardEmulationAdapter.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcEnumerations.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcErrorFactory.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcEventArgs.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcSecureElement.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcManager.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcManagerEvent.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcManagerImpl.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcNdefMessage.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcNdefRecord.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcP2p.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcP2pAdapter.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcTag.cs" />
+ <Compile Include="Tizen.Network.Nfc\NfcTagAdapter.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="Tizen.Network.Nfc.nuspec" />
+ <None Include="Tizen.Network.Nfc.project.json" />
+ <None Include="Tizen.Network.Nfc.snk" />
+ </ItemGroup>
+ <Import Project="$(MSBuildExtensionsPath)\Tizen\Tizen.CSharp.GBS.targets" Condition="Exists('$(MSBuildExtensionsPath)\Tizen\Tizen.CSharp.GBS.targets')" />
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
+ Other similar extension points exist, see Microsoft.Common.targets.
+ <Target Name="BeforeBuild">
+ </Target>
+ <Target Name="AfterBuild">
+ </Target>
+ -->
+ <PropertyGroup>
+ <!-- https://github.com/dotnet/corefxlab/tree/master/samples/NetCoreSample and
+ https://docs.microsoft.com/en-us/dotnet/articles/core/tutorials/target-dotnetcore-with-msbuild
+ -->
+ <!-- We don't use any of MSBuild's resolution logic for resolving the framework, so just set these two
+ properties to any folder that exists to skip the GetReferenceAssemblyPaths task (not target) and
+ to prevent it from outputting a warning (MSB3644).
+ -->
+ <_TargetFrameworkDirectories>$(MSBuildThisFileDirectory)</_TargetFrameworkDirectories>
+ <_FullFrameworkReferenceAssemblyPaths>$(MSBuildThisFileDirectory)</_FullFrameworkReferenceAssemblyPaths>
+ <AutoUnifyAssemblyReferences>true</AutoUnifyAssemblyReferences>
+ </PropertyGroup>
+</Project>
\ No newline at end of file diff --git a/Tizen.Network.Nfc/Tizen.Network.Nfc.nuspec b/Tizen.Network.Nfc/Tizen.Network.Nfc.nuspec new file mode 100644 index 0000000..8d48005 --- /dev/null +++ b/Tizen.Network.Nfc/Tizen.Network.Nfc.nuspec @@ -0,0 +1,21 @@ +<?xml version="1.0"?> +<package> + <metadata> + <id>Tizen.Network.Nfc</id> + <version>$version$</version> + <authors>Samsung Electronics</authors> + <requireLicenseAcceptance>false</requireLicenseAcceptance> + <licenseUrl>https://www.apache.org/licenses/LICENSE-2.0</licenseUrl> + <projectUrl>https://www.tizen.org/</projectUrl> + <iconUrl>https://developer.tizen.org/sites/default/files/images/tizen-pinwheel-on-light-rgb_64_64.png</iconUrl> + <copyright>© Samsung Electronics Co., Ltd All Rights Reserved</copyright> + <description>Provides the Nfc API for Tizen.Net</description> + <dependencies> + <dependency id="Tizen" version="1.0.2" /> + </dependencies> + </metadata> + <files> + <file src="bin/$Configuration$/Tizen.Network.Nfc.dll" target="lib/netstandard1.3" /> + <file src="bin/$Configuration$/Net45/Tizen.Network.Nfc.dll" target="lib/net45" /> + </files> +</package> diff --git a/Tizen.Network.Nfc/Tizen.Network.Nfc.project.json b/Tizen.Network.Nfc/Tizen.Network.Nfc.project.json new file mode 100644 index 0000000..a4c6be0 --- /dev/null +++ b/Tizen.Network.Nfc/Tizen.Network.Nfc.project.json @@ -0,0 +1,9 @@ +{ + "dependencies": { + "NETStandard.Library": "1.6.0", + "Tizen": "1.0.2" + }, + "frameworks": { + "netstandard1.3": {} + } +}
\ No newline at end of file diff --git a/Tizen.Network.Nfc/Tizen.Network.Nfc.snk b/Tizen.Network.Nfc/Tizen.Network.Nfc.snk Binary files differnew file mode 100644 index 0000000..f3d151d --- /dev/null +++ b/Tizen.Network.Nfc/Tizen.Network.Nfc.snk diff --git a/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcCallbackData.cs b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcCallbackData.cs new file mode 100644 index 0000000..b76a52e --- /dev/null +++ b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcCallbackData.cs @@ -0,0 +1,55 @@ +/* + * 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.Nfc +{ + /// <summary> + /// Structure containing the information of Tag data. + /// </summary> + public class NfcTagInformation + { + /// <summary> + /// Key value. + /// </summary> + public string Key; + /// <summary> + /// Information value. + /// </summary> + public byte[] InformationValue; + } + + /// <summary> + /// Structure containing the information of Secure element Aid(Application Identifier). + /// </summary> + public class NfcRegisteredAidInformation + { + /// <summary> + /// Secure Element Type value. + /// </summary> + public NfcSecureElementType SeType; + /// <summary> + /// Aid value. + /// </summary> + public string Aid; + /// <summary> + /// Read-only value. + /// </summary> + public bool ReadOnly; + } +} diff --git a/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcCardEmulationAdapter.cs b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcCardEmulationAdapter.cs new file mode 100644 index 0000000..23d7f3a --- /dev/null +++ b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcCardEmulationAdapter.cs @@ -0,0 +1,508 @@ +/* + * 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; +using System.Collections.Generic; + +namespace Tizen.Network.Nfc +{ + /// <summary> + /// A class for NFC CardEmulation mode. It allows applications to handle Card Emulation informations. + /// </summary> + /// <privilege>http://tizen.org/privilege/nfc.cardemulation</privilege> + public class NfcCardEmulationAdapter : IDisposable + { + private bool disposed = false; + + private event EventHandler<SecureElementEventArgs> _secureElementEvent; + private event EventHandler<SecureElementTranscationEventArgs> _secureElementTransactionEvent; + private event EventHandler<HostCardEmulationEventArgs> _hostCardEmulationEvent; + + private Interop.Nfc.SecureElementEventCallback _secureElementEventCallback; + private Interop.Nfc.SecureElementTransactionEventCallback _secureElementTransactionEventCallback; + private Interop.Nfc.HostCardEmulationEventCallback _hostCardEmulationEventCallback; + + /// <summary> + /// Event that is called when receiving Secure Element (SIM/UICC(Universal Integrated Circuit Card)) event. + /// </summary> + public event EventHandler<SecureElementEventArgs> SecureElementEvent + { + add + { + if (_secureElementEvent == null) + { + RegisterSecureElementEvent(); + } + _secureElementEvent += value; + } + remove + { + _secureElementEvent -= value; + if (_secureElementEvent == null) + { + UnregisterSecureElementEvent(); + } + } + } + + /// <summary> + /// Event that is called when receiving Secure Element(SIM/UICC(Universal Integrated Circuit Card)) transaction event for 'Disable' type. + /// </summary> + public event EventHandler<SecureElementTranscationEventArgs> DisableSecureElementTransactionEvent + { + add + { + if (_secureElementTransactionEvent == null) + { + RegisterSecureElementTransactionEvent(NfcSecureElementType.Disable); + } + _secureElementTransactionEvent += value; + } + remove + { + _secureElementTransactionEvent -= value; + if (_secureElementTransactionEvent == null) + { + UnregisterSecureElementTransactionEvent(NfcSecureElementType.Disable); + } + } + } + + /// <summary> + /// Event that is called when receiving Secure Element(SIM/UICC(Universal Integrated Circuit Card)) transaction event for 'ESE(SmartMX)' type. + /// </summary> + public event EventHandler<SecureElementTranscationEventArgs> EseSecureElementTransactionEvent + { + add + { + if (_secureElementTransactionEvent == null) + { + RegisterSecureElementTransactionEvent(NfcSecureElementType.EmbeddedSE); + } + _secureElementTransactionEvent += value; + } + remove + { + _secureElementTransactionEvent -= value; + if (_secureElementTransactionEvent == null) + { + UnregisterSecureElementTransactionEvent(NfcSecureElementType.EmbeddedSE); + } + } + } + + /// <summary> + /// Event that is called when receiving Secure Element(SIM/UICC(Universal Integrated Circuit Card)) transaction event for 'UICC' type. + /// </summary> + public event EventHandler<SecureElementTranscationEventArgs> UiccSecureElementTransactionEvent + { + add + { + if (_secureElementTransactionEvent == null) + { + RegisterSecureElementTransactionEvent(NfcSecureElementType.Uicc); + } + _secureElementTransactionEvent += value; + } + remove + { + _secureElementTransactionEvent -= value; + if (_secureElementTransactionEvent == null) + { + UnregisterSecureElementTransactionEvent(NfcSecureElementType.Uicc); + } + } + } + + /// <summary> + /// Event that is called when receiving Secure Element(SIM/UICC(Universal Integrated Circuit Card)) transaction event for 'SDCard' type. + /// </summary> + public event EventHandler<SecureElementTranscationEventArgs> SdcardSecureElementTransactionEvent + { + add + { + if (_secureElementTransactionEvent == null) + { + RegisterSecureElementTransactionEvent(NfcSecureElementType.Sdcard); + } + _secureElementTransactionEvent += value; + } + remove + { + _secureElementTransactionEvent -= value; + if (_secureElementTransactionEvent == null) + { + UnregisterSecureElementTransactionEvent(NfcSecureElementType.Sdcard); + } + } + } + + /// <summary> + /// Event that is called when receiving Secure Element(SIM/UICC(Universal Integrated Circuit Card)) transaction event for 'HCE(Host based card emulation)' type. + /// </summary> + public event EventHandler<SecureElementTranscationEventArgs> HceSecureElementTransactionEvent + { + add + { + if (_secureElementTransactionEvent == null) + { + RegisterSecureElementTransactionEvent(NfcSecureElementType.Hce); + } + _secureElementTransactionEvent += value; + } + remove + { + _secureElementTransactionEvent -= value; + if (_secureElementTransactionEvent == null) + { + UnregisterSecureElementTransactionEvent(NfcSecureElementType.Hce); + } + } + } + + /// <summary> + /// Event that is called when when receiving HCE(Host Card Emulation) event. + /// </summary> + public event EventHandler<HostCardEmulationEventArgs> HostCardEmulationEvent + { + add + { + if (_hostCardEmulationEvent == null) + { + RegisterHostCardEmulationEvent(); + } + _hostCardEmulationEvent += value; + } + remove + { + _hostCardEmulationEvent -= value; + if (_hostCardEmulationEvent == null) + { + UnregisterHostCardEmulationEvent(); + } + } + } + + internal NfcCardEmulationAdapter() + { + } + + ~NfcCardEmulationAdapter() + { + Dispose(false); + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + private void Dispose(bool disposing) + { + if (disposed) + return; + + if (disposing) + { + // Free managed objects. + } + //Free unmanaged objects + disposed = true; + } + + /// <summary> + /// Enable card emulation mode. + /// </summary> + public void EnableCardEmulation() + { + int ret = Interop.Nfc.CardEmulation.EnableCardEmulation(); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to enable card emulation mode, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + } + + /// <summary> + /// Disable card emulation mode. + /// </summary> + public void DisableCardEmulation() + { + int ret = Interop.Nfc.CardEmulation.DisableCardEmulatiion(); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to disable card emulation mode, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + } + + /// <summary> + /// Get the current card emulation mode. + /// </summary> + /// <returns>Enumeration value of NfcSecureElementCardEmulationMode.</returns> + public NfcSecureElementCardEmulationMode GetCardEmulationMode() + { + int mode = 0; + int ret = Interop.Nfc.CardEmulation.GetCardEmulationMode(out mode); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to get card emulation mode, Error - " + (NfcError)ret); + } + + return (NfcSecureElementCardEmulationMode)mode; + } + + /// <summary> + /// Give the priority to the foreground application when dispatching transaction event. + /// </summary> + public void EnableTransactionForegroundDispatch() + { + int ret = Interop.Nfc.EnableTransactionForegroundDispatch(); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to enable foreground dispatch, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + } + + /// <summary> + /// Disable foreground dispatch for "EVT_TRANSACTION" to the givin application. + /// </summary> + public void DisableTransactionForegroundDispatch() + { + int ret = Interop.Nfc.DisableTransactionForegroundDispatch(); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to disable foreground dispatch, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + } + + /// <summary> + /// Set the default route for each device status. + /// </summary> + /// <param name="seTypeInPoweredOn">The type of default Secure Element when device is powered on.</param> + /// <param name="seTypeInPoweredOff">The type of default Secure Element when device is powered off.</param> + /// <param name="seTypeInLowBattery">The type of default Secure Element when battery is low.</param> + public void SetDefaultRoute(NfcSecureElementType seTypeInPoweredOn, NfcSecureElementType seTypeInPoweredOff, NfcSecureElementType seTypeInLowBattery) + { + int ret = Interop.Nfc.CardEmulation.SetDefaultRoute((int)seTypeInPoweredOn, (int)seTypeInPoweredOff, (int)seTypeInLowBattery); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to set default route, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + } + + /// <summary> + /// Gets the state whether an application to call this api is currently the activated handler for specific AID. + /// </summary> + /// <returns>'True' when application is currently the activated handler, otherwise 'False'.</returns> + /// <param name="seType">The type of Secure Element.</param> + /// <param name="aid">Application Id, specified in ISO/IEC 7816-4.</param> + public bool IsActivatedHandlerForAid(NfcSecureElementType seType, string aid) + { + bool isActivatedHandle = false; + int ret = Interop.Nfc.CardEmulation.IsActivatedHandlerForAid((int)seType, aid, out isActivatedHandle); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to check activated handle for aid, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + + return isActivatedHandle; + } + + /// <summary> + /// Gets the state whether an application to call this api is currently the activated handler for category. + /// </summary> + /// <returns>'True' when application is currently the activated handler, otherwise 'False'.</returns> + /// <param name="seType">The type of Secure Element.</param> + /// <param name="category">Enumeration value of category.</param> + public bool IsActivatedHandlerForCategory(NfcSecureElementType seType, NfcCardEmulationCategoryType category) + { + bool isActivatedHandle = false; + int ret = Interop.Nfc.CardEmulation.IsActivatedHandlerForCategory((int)seType, (int)category, out isActivatedHandle); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to check activated handle for category, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + + return isActivatedHandle; + } + + /// <summary> + /// Registers a AID for a specific category. + /// </summary> + /// <param name="seType">The type of Secure Element.</param> + /// <param name="category">Enumeration value of category.</param> + /// <param name="aid">Application Id, specified in ISO/IEC 7816-4.</param> + public void RegisterAid(NfcSecureElementType seType, NfcCardEmulationCategoryType category, string aid) + { + int ret = Interop.Nfc.CardEmulation.RegisterAid((int)seType, (int)category, aid); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to register aid, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + } + + /// <summary> + /// Unregisters a previously registered AID for the specified category. + /// </summary> + /// <param name="seType">The type of Secure Element.</param> + /// <param name="category">Enumeration value of category.</param> + /// <param name="aid">Application Id, specified in ISO/IEC 7816-4.</param> + public void UnregisterAid(NfcSecureElementType seType, NfcCardEmulationCategoryType category, string aid) + { + int ret = Interop.Nfc.CardEmulation.UnregisterAid((int)seType, (int)category, aid); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to unregister aid, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + } + + /// <summary> + /// Sets the application as a preferred handler. + /// </summary> + public void SetPreferredApplication() + { + int ret = Interop.Nfc.CardEmulation.SetPreferredHandler(); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to set preferred handler, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + } + + /// <summary> + /// Unsets the application as a preferred handler. + /// </summary> + public void UnsetPreferredApplication() + { + int ret = Interop.Nfc.CardEmulation.UnsetPreferredHandler(); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to unset preferred handler, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + } + + /// <summary> + /// Retrieves all registered AID. + /// </summary> + /// <returns>List of NfcRegisteredAidInformation objects.</returns> + /// <param name="seType">The type of Secure Element.</param> + /// <param name="category">Enumeration value of category.</param> + public IEnumerable<NfcRegisteredAidInformation> ForeachRegisteredAidInformations(NfcSecureElementType seType, NfcCardEmulationCategoryType category) + { + List<NfcRegisteredAidInformation> infoList = new List<NfcRegisteredAidInformation>(); + Interop.Nfc.SecureElementRegisteredAidCallback callback = (int type, IntPtr aid, bool readOnly, IntPtr userData) => + { + if (aid != IntPtr.Zero) + { + NfcRegisteredAidInformation aidInfo = new NfcRegisteredAidInformation(); + + aidInfo.SeType = (NfcSecureElementType)type; + aidInfo.Aid = Marshal.PtrToStringAnsi(aid); + aidInfo.ReadOnly = readOnly; + + infoList.Add(aidInfo); + } + }; + + int ret = Interop.Nfc.CardEmulation.ForeachRegisterdAids((int)seType, (int)category, callback, IntPtr.Zero); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to get all registerd aid informations, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + + return infoList; + } + + private void RegisterSecureElementEvent() + { + _secureElementEventCallback = (int eventType, IntPtr userData) => + { + NfcSecureElementEvent _eventType = (NfcSecureElementEvent)eventType; + SecureElementEventArgs e = new SecureElementEventArgs(_eventType); + _secureElementEvent.SafeInvoke(null, e); + }; + + int ret = Interop.Nfc.SetSecureElementEventCallback(_secureElementEventCallback, IntPtr.Zero); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to set secure element event callback, Error - " + (NfcError)ret); + } + } + + private void UnregisterSecureElementEvent() + { + Interop.Nfc.UnsetSecureElementEventCallback(); + } + + private void RegisterSecureElementTransactionEvent(NfcSecureElementType seType) + { + _secureElementTransactionEventCallback = (int type, IntPtr aid, int aidSize, IntPtr param, int paramSize, IntPtr userData) => + { + NfcSecureElementType _secureElementType = (NfcSecureElementType)type; + byte[] _aid = NfcConvertUtil.IntLengthIntPtrToByteArray(aid, aidSize); + byte[] _param = NfcConvertUtil.IntLengthIntPtrToByteArray(param, paramSize); + SecureElementTranscationEventArgs e = new SecureElementTranscationEventArgs(_secureElementType, _aid, _param); + _secureElementTransactionEvent.SafeInvoke(null, e); + }; + + int ret = Interop.Nfc.SetSecureElementTransactionEventCallback((int)seType, _secureElementTransactionEventCallback, IntPtr.Zero); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to set secure element transaction event callback, Error - " + (NfcError)ret); + } + } + + private void UnregisterSecureElementTransactionEvent(NfcSecureElementType seType) + { + Interop.Nfc.UnsetSecureElementTransactionEventCallback((int)seType); + } + + private void RegisterHostCardEmulationEvent() + { + _hostCardEmulationEventCallback = (IntPtr handle, int eventType, IntPtr apdu, uint apduLen, IntPtr userData) => + { + IntPtr _seHandle = handle; + NfcHceEvent _hcdEventType = (NfcHceEvent)eventType; + byte[] _apdu = NfcConvertUtil.UintLengthIntPtrToByteArray(apdu, apduLen); + HostCardEmulationEventArgs e = new HostCardEmulationEventArgs(_seHandle, _hcdEventType, _apdu); + _hostCardEmulationEvent.SafeInvoke(null, e); + }; + + int ret = Interop.Nfc.SetHostCardEmulationEventCallback(_hostCardEmulationEventCallback, IntPtr.Zero); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to set host card emulation event callback, Error - " + (NfcError)ret); + } + } + + private void UnregisterHostCardEmulationEvent() + { + Interop.Nfc.UnsetHostCardEmulationEventCallback(); + } + } +} diff --git a/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcEnumerations.cs b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcEnumerations.cs new file mode 100644 index 0000000..9a11123 --- /dev/null +++ b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcEnumerations.cs @@ -0,0 +1,362 @@ +/* + * 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.Nfc +{ + /// <summary> + /// Enumeration for Nfc record TNF (Type Name Format). + /// </summary> + public enum NfcRecordTypeNameFormat + { + /// <summary> + /// Empty + /// </summary> + Empty = 0, + /// <summary> + /// RTD(Record Type Definition) type format [NFC RTD] + /// </summary> + WellKnown = 1, + /// <summary> + /// MIME Media types in RFC 2046 [RFC 2046] + /// </summary> + MimeMedia = 2, + /// <summary> + /// Absolute URI as defined in RFC 3986 [RFC 3986] + /// </summary> + Uri = 3, + /// <summary> + /// NFC Forum external type [NFC RTD] + /// </summary> + ExternalRtd = 4, + /// <summary> + /// The payload type is unknown + /// </summary> + Unknown = 5, + /// <summary> + /// final chunk of a chunked NDEF Record + /// </summary> + UnChanged = 6 + } + + /// <summary> + /// Enumeration for Nfc Encode type. + /// </summary> + public enum NfcEncodeType + { + /// <summary> + /// UTF-8 + /// </summary> + Utf8 = 0, + /// <summary> + /// UTF-16 + /// </summary> + Utf16 = 1 + } + /// <summary> + /// Enumeration for Nfc Tag type. + /// </summary> + public enum NfcTagType + { + /// <summary> + /// Unknown target + /// </summary> + UnknownTarget = 0x00, + /// <summary> + /// Generic PICC + /// </summary> + GenericPicc, + /// <summary> + /// ISO14443 A PICC + /// </summary> + Iso14443APicc, + /// <summary> + /// ISO14443 4A PICC + /// </summary> + Iso144434APicc, + /// <summary> + /// ISO14443 4A PICC + /// </summary> + Iso144433APicc, + /// <summary> + /// Mifare Mini PICC + /// </summary> + MifareMiniPicc, + /// <summary> + /// Mifare 1k PICC + /// </summary> + Mifare1kPicc, + /// <summary> + /// Mifare 4k PICC + /// </summary> + Mifare4kPicc, + /// <summary> + /// Mifare Ultra PICC + /// </summary> + MifareUltraPicc, + /// <summary> + /// Mifare Desfire PICC + /// </summary> + MifareDesfirePicc, + /// <summary> + /// Iso14443 B PICC + /// </summary> + Iso14443BPicc, + /// <summary> + /// Iso14443 4B PICC + /// </summary> + Iso144434BPicc, + /// <summary> + /// ISO14443 B Prime PICC + /// </summary> + Iso14443BPrimePicc, + /// <summary> + /// Felica PICC + /// </summary> + FelicaPicc, + /// <summary> + /// Jewel PICC + /// </summary> + JewelPicc, + /// <summary> + /// ISO15693 PICC + /// </summary> + Iso15693Picc, + /// <summary> + /// Barcode 128 PICC + /// </summary> + Barcode128Picc, + /// <summary> + /// Barcode 256 PICC + /// </summary> + Barcode256Picc, + /// <summary> + /// NFCIP1 Target + /// </summary> + NfcIp1Target, + /// <summary> + /// NFCIP1 Initiator + /// </summary> + NfcIp1Initiator + } + /// <summary> + /// Enumeration for Nfc Tag Filter type. + /// </summary> + public enum NfcTagFilterType + { + /// <summary> + /// All disable + /// </summary> + AllDisable = 0x0000, + /// <summary> + /// ISO14443A enable + /// </summary> + Iso14443AEnable = 0x0001, + /// <summary> + /// ISO14443B enable + /// </summary> + Iso14443BEnable = 0x0002, + /// <summary> + /// ISO15693 enable + /// </summary> + Iso15693Enable = 0x0004, + /// <summary> + /// FELICA enable + /// </summary> + FelicaEnable = 0x0008, + /// <summary> + /// JEWEL enable + /// </summary> + JewelEnable = 0x0010, + /// <summary> + /// IP enable + /// </summary> + IpEnable = 0x0020, + /// <summary> + /// All enable + /// </summary> + AllEnable = ~0 + } + /// <summary> + /// Enumeration for Nfc discovered type. + /// </summary> + public enum NfcDiscoveredType + { + /// <summary> + /// Attached, discovered, activated event + /// </summary> + Attached, + /// <summary> + /// Detached, disappeared, deactivated event + /// </summary> + Detached + } + /// <summary> + /// Enumeration for Nfc Secure Element event. + /// </summary> + public enum NfcSecureElementEvent + { + /// <summary> + /// Start transaction + /// </summary> + StartTransaction, + /// <summary> + /// End transaction + /// </summary> + EndTransaction, + /// <summary> + /// Ready signal + /// </summary> + Connectivity, + /// <summary> + /// CLF(Contactless Front-end) detects a RF field + /// </summary> + FieldOn, + /// <summary> + /// CLF(Contactless Front-end) detects that the RF field is off + /// </summary> + FieldOff, + /// <summary> + /// External reader trys to access secure element + /// </summary> + Transaction, + /// <summary> + /// Changing the emulated secure element type + /// </summary> + TypeChanged, + /// <summary> + /// Changing the card emulation mode + /// </summary> + CardEmulationChanged + } + /// <summary> + /// Enumeration for Nfc Filter type. + /// </summary> + public enum NfcSecureElementType + { + /// <summary> + /// Disable card emulation + /// </summary> + Disable = 0x00, + /// <summary> + /// SmartMX type card emulation (Embedded Secure Element) + /// </summary> + EmbeddedSE = 0x01, + /// <summary> + /// UICC type card emulation (Universal IC Card) + /// </summary> + Uicc = 0x02, + /// <summary> + /// SDCARD card emulation + /// </summary> + Sdcard = 0x03, + /// <summary> + /// Host based card emulation + /// </summary> + Hce = 0x04 + } + /// <summary> + /// Enumeration for Nfc discovered type. + /// </summary> + public enum NfcSecureElementCardEmulationMode + { + /// <summary> + /// Card Emulation mode OFF + /// </summary> + Off = 0x00, + /// <summary> + /// Card Emulation mode ON + /// </summary> + On = 0x01 + } + /// <summary> + /// Enumeration for SNEP(Simple NDEF Exchange Protocol) event. + /// </summary> + public enum NfcSnepEvent + { + /// <summary> + /// server or client stopped + /// </summary> + Stop = 0x00, + /// <summary> + /// server started or client connected + /// </summary> + Start = 0x01, + /// <summary> + /// server received get request + /// </summary> + Get = 0x02, + /// <summary> + /// server received put request + /// </summary> + Put = 0x03, + /// <summary> + /// service registered + /// </summary> + Register = 0x04, + /// <summary> + /// service unregistered + /// </summary> + Unregister = 0x05 + } + /// <summary> + /// Enumeration for SNEP request type. + /// </summary> + public enum NfcSnepRequestType + { + /// <summary> + /// get request + /// </summary> + Get = 0x01, + /// <summary> + /// put request + /// </summary> + Put = 0x02 + } + /// <summary> + /// Enumeration for NFC Card Emulation Category type. + /// </summary> + public enum NfcCardEmulationCategoryType + { + /// <summary> + /// NFC payment services + /// </summary> + Payment = 0x01, + /// <summary> + /// all other card emulation services + /// </summary> + Other = 0x02 + } + /// <summary> + /// Enumeration for NFC Card Emulation HCE(Host Card Emulation) event type. + /// </summary> + public enum NfcHceEvent + { + /// <summary> + /// HCE deactivated + /// </summary> + Deactivated = 0x00, + /// <summary> + /// HCE activated + /// </summary> + Activated = 0x01, + /// <summary> + /// HCE APDU(Application Protocol Data Unit) Received + /// </summary> + ApduReceived = 0x02 + } +} diff --git a/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcErrorFactory.cs b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcErrorFactory.cs new file mode 100644 index 0000000..6e148c9 --- /dev/null +++ b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcErrorFactory.cs @@ -0,0 +1,85 @@ +/* + * 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 Tizen.Internals.Errors; + +namespace Tizen.Network.Nfc +{ + /// <summary> + /// Enumeration for Nfc Error. + /// </summary> + public enum NfcError + { + None = ErrorCode.None, + IoError = ErrorCode.IoError, + InvalidParameterError = ErrorCode.InvalidParameter, + OutOfMemoryError = ErrorCode.OutOfMemory, + TimedOutError = ErrorCode.TimedOut, + DeviceBusyError = ErrorCode.ResourceBusy, + NotSupportedError = ErrorCode.NotSupported, + PermissionDeniedError = ErrorCode.PermissionDenied, + OperationFailedError = -0x01C20000 | 0x01, + InvalidNdefMessageError = -0x01C20000 | 0x02, + InvalidRecordTypeError = -0x01C20000 | 0x03, + NoDeviceError = -0x01C20000 | 0x04, + NotActivatedError = -0x01C20000 | 0x05, + AlreadyActivatedError = -0x01C20000 | 0x06, + AlreadyDeactivatedError = -0x01C20000 | 0x07, + ReadOnlyNdefError = -0x01C20000 | 0x08, + NoSpaceOnNdefError = -0x01C20000 | 0x09, + NoNdefMessageError = -0x01C20000 | 0x0a, + NotNdefFormatError = -0x01C20000 | 0x0b, + SecurityRestrictedError = -0x01C20000 | 0x0c, + IllegalStateError = -0x01C20000 | 0x0d, + NotInitializedError = -0x01C20000 | 0x0e, + TagNotSupportedError = -0x01C20000 | 0x0f, + AidAlreadyRegisteredError = -0x01C20000 | 0x10 + } + + internal static class NfcErrorFactory + { + static internal void ThrowNfcException(int e) + { + ThrowException(e, false); + } + + static internal void ThrowNfcException(int e, int handle) + { + ThrowException(e, (handle < 0)); + } + + static private void ThrowException(int e, bool isHandleNull) + { + NfcError err = (NfcError)e; + + if (isHandleNull) + { + throw new InvalidOperationException("Invalid instance (object may have been disposed or released)"); + } + + if (err == NfcError.InvalidParameterError) + { + throw new ArgumentException(err.ToString()); + } + else + { + throw new InvalidOperationException(err.ToString()); + } + } + + } +} diff --git a/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcEventArgs.cs b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcEventArgs.cs new file mode 100644 index 0000000..015b0df --- /dev/null +++ b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcEventArgs.cs @@ -0,0 +1,297 @@ +/* + * 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.Nfc +{ + /// <summary> + /// An extended EventArgs class which contains changed Nfc activation state. + /// </summary> + public class ActivationChangedEventArgs : EventArgs + { + private bool _activated = false; + + internal ActivationChangedEventArgs(bool activated) + { + _activated = activated; + } + + /// <summary> + /// The Nfc activation state. + /// </summary> + public bool Activated + { + get + { + return _activated; + } + } + } + + /// <summary> + /// An extended EventArgs class which contains changed Nfc tag discovered. + /// </summary> + public class TagDiscoveredEventArgs : EventArgs + { + private NfcDiscoveredType _type = NfcDiscoveredType.Detached; + private NfcTag _tag; + + internal TagDiscoveredEventArgs(NfcDiscoveredType _type, IntPtr tagHandle) + { + _tag = new NfcTag(tagHandle); + } + + /// <summary> + /// The tag type. + /// </summary> + public NfcDiscoveredType Type + { + get + { + return _type; + } + } + + /// <summary> + /// Tag object + /// </summary> + public NfcTag Tag + { + get + { + return _tag; + } + } + } + + /// <summary> + /// An extended EventArgs class which contains changed Nfc p2p target discovered. + /// </summary> + public class P2pTargetDiscoveredEventArgs : EventArgs + { + private NfcDiscoveredType _type = NfcDiscoveredType.Detached; + private NfcP2p _p2pTarget; + + internal P2pTargetDiscoveredEventArgs(NfcDiscoveredType _type, IntPtr p2pTargetHandle) + { + _p2pTarget = new NfcP2p(p2pTargetHandle); + } + + /// <summary> + /// The p2p target type. + /// </summary> + public NfcDiscoveredType Type + { + get + { + return _type; + } + } + + /// <summary> + /// P2p object + /// </summary> + public NfcP2p P2pTaget + { + get + { + return _p2pTarget; + } + } + } + + /// <summary> + /// An extended EventArgs class which contains changed Nfc ndef discovered. + /// </summary> + public class NdefMessageDiscoveredEventArgs : EventArgs + { + private NfcNdefMessage _ndef; + + internal NdefMessageDiscoveredEventArgs(IntPtr messageHandle) + { + _ndef = new NfcNdefMessage(messageHandle); + } + + /// <summary> + /// Tag object + /// </summary> + public NfcNdefMessage NdefMessage + { + get + { + return _ndef; + } + } + } + + /// <summary> + /// An extended EventArgs class which contains changed Secure element event. + /// </summary> + public class SecureElementEventArgs : EventArgs + { + private NfcSecureElementEvent _eventType = NfcSecureElementEvent.StartTransaction; + + internal SecureElementEventArgs(NfcSecureElementEvent eventType) + { + _eventType = eventType; + } + + /// <summary> + /// The Nfc secure element event. + /// </summary> + public NfcSecureElementEvent EventType + { + get + { + return _eventType; + } + } + } + + /// <summary> + /// An extended EventArgs class which contains changed Secure element trasaction event. + /// </summary> + public class SecureElementTranscationEventArgs : EventArgs + { + private NfcSecureElementType _secureElementType = NfcSecureElementType.Disable; + byte[] _aid; + byte[] _param; + + internal SecureElementTranscationEventArgs(NfcSecureElementType secureElementType, byte[] aid, byte[] param) + { + _secureElementType = secureElementType; + _aid = aid; + _param = param; + } + + /// <summary> + /// The Nfc secure element type. + /// </summary> + public NfcSecureElementType SecureElementType + { + get + { + return _secureElementType; + } + } + /// <summary> + /// The Nfc secure element aid. + /// </summary> + public byte[] ApplicationID + { + get + { + return _aid; + } + } + /// <summary> + /// The Nfc secure element param. + /// </summary> + public byte[] Param + { + get + { + return _param; + } + } + } + + /// <summary> + /// An extended EventArgs class which contains changed HCE(Host Card Emulation) event. + /// </summary> + public class HostCardEmulationEventArgs : EventArgs + { + private NfcSecureElement _se; + private NfcHceEvent _hceEvent = NfcHceEvent.Deactivated; + private byte[] _apdu; + + internal HostCardEmulationEventArgs(IntPtr seHandle, NfcHceEvent hcdEvent, byte[] apdu) + { + _se = new NfcSecureElement(seHandle); + _hceEvent = hcdEvent; + _apdu = apdu; + } + + /// <summary> + /// The Nfc secure element. + /// </summary> + public NfcSecureElement SecureElement + { + get + { + return _se; + } + } + /// <summary> + /// The Nfc hce event. + /// </summary> + public NfcHceEvent HcdEvent + { + get + { + return _hceEvent; + } + } + /// <summary> + /// The Nfc apdu(Application Protocol Data Unit) + /// </summary> + public byte[] Apdu + { + get + { + return _apdu; + } + } + } + + /// <summary> + /// An extended EventArgs class which contains changed HCE(Host Card Emulation) event. + /// </summary> + public class P2pDataReceivedEventArgs : EventArgs + { + private NfcP2p _p2pTarget; + private NfcNdefMessage _ndefMessage; + + internal P2pDataReceivedEventArgs(IntPtr p2pHandle, IntPtr ndefHandle) + { + _p2pTarget = new NfcP2p(p2pHandle); + _ndefMessage = new NfcNdefMessage(ndefHandle); + } + + /// <summary> + /// The Nfc p2p target. + /// </summary> + public NfcP2p P2pTarget + { + get + { + return _p2pTarget; + } + } + /// <summary> + /// The Nfc ndef message. + /// </summary> + public NfcNdefMessage NdefMessage + { + get + { + return _ndefMessage; + } + } + } +} diff --git a/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcManager.cs b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcManager.cs new file mode 100644 index 0000000..57eca3d --- /dev/null +++ b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcManager.cs @@ -0,0 +1,170 @@ +/* + * 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.Threading.Tasks; + +namespace Tizen.Network.Nfc +{ + /// <summary> + /// A class for NFC management. It allows applications to use NFC service. + /// </summary> + /// <privilege>http://tizen.org/privilege/nfc</privilege> + static public class NfcManager + { + /// <summary> + /// Whether NFC is supported. + /// </summary> + static public bool IsSupported + { + get + { + return NfcManagerImpl.Instance.IsSupported; + } + } + + /// <summary> + /// NFC Activation state. + /// </summary> + static public bool IsActivated + { + get + { + return NfcManagerImpl.Instance.IsActivated; + } + } + + /// <summary> + /// The Tag Filter type. + /// </summary> + static public NfcTagFilterType TagFilterType + { + get + { + return NfcManagerImpl.Instance.TagFilterType; + } + set + { + NfcManagerImpl.Instance.TagFilterType = value; + } + } + + /// <summary> + /// The Secure Element type. + /// </summary> + static public NfcSecureElementType SecureElementType + { + get + { + return NfcManagerImpl.Instance.SecureElementType; + } + set + { + NfcManagerImpl.Instance.SecureElementType = value; + } + } + + /// <summary> + /// Enable or disable the system handling for tag and target discovered event. + /// </summary> + static public bool SystemHandlerEnabled + { + get + { + return NfcManagerImpl.Instance.SystemHandlerEnabled; + } + set + { + NfcManagerImpl.Instance.SystemHandlerEnabled = value; + } + } + + /// <summary> + /// The cached Ndef Message. + /// </summary> + static public NfcNdefMessage CachedNdefMessage + { + get + { + return NfcManagerImpl.Instance.CachedNdefMessage; + } + } + + /// <summary> + /// Gets Tag adapter object. + /// </summary> + static public NfcTagAdapter GetTagAdapter() + { + return NfcManagerImpl.Instance.TagAdapter; + } + + /// <summary> + /// Gets P2p adapter object. + /// </summary> + static public NfcP2pAdapter GetP2pAdapter() + { + return NfcManagerImpl.Instance.P2pAdapter; + } + + /// <summary> + /// Gets Card Emulation adepter object. + /// </summary> + static public NfcCardEmulationAdapter GetCardEmulationAdapter() + { + return NfcManagerImpl.Instance.CardEmulationAdapter; + } + + /// <summary> + /// Activates Nfc asynchronously. + /// </summary> + /// <returns>A task indicates whether the Activate method is done or not.</returns> + static public Task SetActivateAsync(bool activation) + { + return NfcManagerImpl.Instance.SetActivateAsync(activation); + } + + /// <summary> + /// The Activation changed event. + /// </summary> + static public event EventHandler<ActivationChangedEventArgs> ActivationChanged + { + add + { + NfcManagerImpl.Instance.ActivationChanged += value; + } + remove + { + NfcManagerImpl.Instance.ActivationChanged -= value; + } + } + + /// <summary> + /// The Ndef discovered event. + /// </summary> + static public event EventHandler<NdefMessageDiscoveredEventArgs> NdefMessageDiscovered + { + add + { + NfcManagerImpl.Instance.NdefMessageDiscovered += value; + } + remove + { + NfcManagerImpl.Instance.NdefMessageDiscovered -= value; + } + } + } +} diff --git a/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcManagerEvent.cs b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcManagerEvent.cs new file mode 100644 index 0000000..7150daa --- /dev/null +++ b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcManagerEvent.cs @@ -0,0 +1,139 @@ +/* + * 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.Threading.Tasks; + +namespace Tizen.Network.Nfc +{ + internal static class EventHandlerExtension + { + internal static void SafeInvoke(this EventHandler evt, object sender, EventArgs e) + { + var handler = evt; + if (handler != null) + { + handler(sender, e); + } + } + internal static void SafeInvoke<T>(this EventHandler<T> evt, object sender, T e) where T : EventArgs + { + var handler = evt; + if (handler != null) + { + handler(sender, e); + } + } + } + + internal partial class NfcManagerImpl + { + private event EventHandler<ActivationChangedEventArgs> _activationChanged; + private event EventHandler<NdefMessageDiscoveredEventArgs> _ndefMessageDiscovered; + + private Interop.Nfc.ActivationChangedCallback _activationChangedCallback; + private Interop.Nfc.NdefMessageDiscoveredCallback _ndefMessageDiscoveredCallback; + + internal event EventHandler<ActivationChangedEventArgs> ActivationChanged + { + add + { + if (_activationChanged == null) + { + RegisterActivationChangedEvent(); + } + _activationChanged += value; + } + remove + { + _activationChanged -= value; + if (_activationChanged == null) + { + UnregisterActivationChangedEvent(); + } + } + } + + internal event EventHandler<NdefMessageDiscoveredEventArgs> NdefMessageDiscovered + { + add + { + if (_ndefMessageDiscovered == null) + { + RegisterNdefMessageDiscoveredEvent(); + } + _ndefMessageDiscovered += value; + } + remove + { + _ndefMessageDiscovered -= value; + if (_ndefMessageDiscovered == null) + { + UnregisterNdefMessageDiscoveredEvent(); + } + } + } + + internal void RemoveAllRegisteredEvent() + { + //unregister all remaining events when this object is released. + if (_activationChanged != null) + { + UnregisterActivationChangedEvent(); + } + } + + private void RegisterActivationChangedEvent() + { + _activationChangedCallback = (bool activated, IntPtr userData) => + { + bool isActivated = activated; + ActivationChangedEventArgs e = new ActivationChangedEventArgs(isActivated); + _activationChanged.SafeInvoke(null, e); + }; + int ret = Interop.Nfc.SetActivationChangedCallback(_activationChangedCallback, IntPtr.Zero); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to set activation changed callback, Error - " + (NfcError)ret); + } + } + + private void UnregisterActivationChangedEvent() + { + Interop.Nfc.UnsetActivationChangedCallback(); + } + + private void RegisterNdefMessageDiscoveredEvent() + { + _ndefMessageDiscoveredCallback = (IntPtr ndefMessageHandle, IntPtr userData) => + { + NdefMessageDiscoveredEventArgs e = new NdefMessageDiscoveredEventArgs(ndefMessageHandle); + _ndefMessageDiscovered.SafeInvoke(null, e); + }; + + int ret = Interop.Nfc.SetNdefDiscoveredCallback(_ndefMessageDiscoveredCallback, IntPtr.Zero); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to set ndef message discovered callback, Error - " + (NfcError)ret); + } + } + + private void UnregisterNdefMessageDiscoveredEvent() + { + Interop.Nfc.UnsetNdefDiscoveredCallback(); + } + } +} diff --git a/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcManagerImpl.cs b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcManagerImpl.cs new file mode 100644 index 0000000..238c0b6 --- /dev/null +++ b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcManagerImpl.cs @@ -0,0 +1,271 @@ +/* + * 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; +using System.Threading.Tasks; + +namespace Tizen.Network.Nfc +{ + static internal class Globals + { + internal const string LogTag = "Tizen.Network.Nfc"; + } + + internal static class NfcConvertUtil + { + internal static byte[] IntLengthIntPtrToByteArray(IntPtr nativeValue, int length) + { + byte[] value = new byte[length]; + if (nativeValue != IntPtr.Zero) + { + Marshal.Copy(nativeValue, value, 0, length); + } + return value; + } + + internal static byte[] UintLengthIntPtrToByteArray(IntPtr nativeValue, uint length) + { + byte[] value = new byte[length]; + + if (nativeValue != IntPtr.Zero) + { + for (int i = 0; i < length; i++) + { + value[i] = Marshal.ReadByte(nativeValue); + nativeValue += sizeof(byte); + } + } + return value; + } + } + + internal partial class NfcManagerImpl : IDisposable + { + private static readonly NfcManagerImpl _instance = new NfcManagerImpl(); + private static readonly NfcTagAdapter _instanceTagAdapter = new NfcTagAdapter(); + private static readonly NfcP2pAdapter _instanceP2pAdapter = new NfcP2pAdapter(); + private static readonly NfcCardEmulationAdapter _instanceCardEmulationAdapter = new NfcCardEmulationAdapter(); + + private Dictionary<IntPtr, Interop.Nfc.VoidCallback> _callback_map = new Dictionary<IntPtr, Interop.Nfc.VoidCallback>(); + private int _requestId = 0; + private bool disposed = false; + + internal static NfcManagerImpl Instance + { + get + { + return _instance; + } + } + + internal NfcTagAdapter TagAdapter + { + get + { + return _instanceTagAdapter; + } + } + + internal NfcP2pAdapter P2pAdapter + { + get + { + return _instanceP2pAdapter; + } + } + + internal NfcCardEmulationAdapter CardEmulationAdapter + { + get + { + return _instanceCardEmulationAdapter; + } + } + + internal bool IsSupported + { + get + { + bool support = Interop.Nfc.IsSupported(); + + return support; + } + } + + internal bool IsActivated + { + get + { + bool active = Interop.Nfc.IsActivated(); + + return active; + } + } + + internal NfcNdefMessage CachedNdefMessage + { + get + { + IntPtr ndef = IntPtr.Zero; ; + int ret = Interop.Nfc.GetCachedMessage(out ndef); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to get cached ndef message, Error - " + (NfcError)ret); + } + + NfcNdefMessage ndefMessage = new NfcNdefMessage(ndef); + return ndefMessage; + } + } + + internal NfcTagFilterType TagFilterType + { + get + { + int type = Interop.Nfc.GetTagFilter(); + + return (NfcTagFilterType)type; + } + set + { + Interop.Nfc.SetTagFilter((int)value); + } + } + + internal NfcSecureElementType SecureElementType + { + get + { + int type; + int ret = Interop.Nfc.GetSecureElementType(out type); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to get secure element type, Error - " + (NfcError)ret); + } + return (NfcSecureElementType)type; + } + set + { + int ret = Interop.Nfc.SetSecureElementType((int)value); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to set secure element type, Error - " + (NfcError)ret); + } + } + } + + internal bool SystemHandlerEnabled + { + get + { + bool systemhandler = Interop.Nfc.IsSystemHandlerEnabled(); + + return systemhandler; + } + set + { + int ret = Interop.Nfc.SetSystemHandlerEnable(value); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to enable system handler, Error - " + (NfcError)ret); + } + } + } + + private NfcManagerImpl() + { + initialize(); + } + + ~NfcManagerImpl() + { + Dispose(false); + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + private void Dispose(bool disposing) + { + if (disposed) + return; + + if (disposing) + { + // Free managed objects. + } + //Free unmanaged objects + deinitialize(); + disposed = true; + } + + private void initialize() + { + int ret = Interop.Nfc.Initialize(); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to initialize Nfc, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + } + + private void deinitialize() + { + int ret = Interop.Nfc.Deinitialize(); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to deinitialize Nfc, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + } + + internal Task SetActivateAsync(bool activation) + { + TaskCompletionSource<bool> task = new TaskCompletionSource<bool>(); + IntPtr id = IntPtr.Zero; + lock (_callback_map) + { + id = (IntPtr)_requestId++; + _callback_map[id] = (error, key) => + { + Log.Debug(Globals.LogTag, "nfc activated"); + if (error != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Error occurs during Nfc activating, " + (NfcError)error); + task.SetException(new InvalidOperationException("Error occurs during Nfc activating, " + (NfcError)error)); + } + task.SetResult(true); + lock (_callback_map) + { + _callback_map.Remove(key); + } + }; + } + int ret = Interop.Nfc.SetActivation(activation, _callback_map[id], id); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to activate nfc, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + return task.Task; + } + } +} diff --git a/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcNdefMessage.cs b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcNdefMessage.cs new file mode 100644 index 0000000..76891d9 --- /dev/null +++ b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcNdefMessage.cs @@ -0,0 +1,236 @@ +/* + * 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; +using System.Collections.Generic; + +namespace Tizen.Network.Nfc +{ + /// <summary> + /// A class for Ndef Message information. It allows applications to use Ndef Message information. + /// </summary> + public class NfcNdefMessage : IDisposable + { + private bool disposed = false; + private IntPtr _messageHandle = IntPtr.Zero; + private List<NfcNdefRecord> _recordList = new List<NfcNdefRecord>(); + + /// <summary> + /// The number of record in NDEF message. + /// </summary> + public int RecordCount + { + get + { + int recordCount; + int ret = Interop.Nfc.NdefMessage.GetRecordCount(_messageHandle, out recordCount); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to get record count, Error - " + (NfcError)ret); + } + return recordCount; + } + } + + /// <summary> + /// The serial bytes array of NDEF message. + /// </summary> + public byte[] Rawdata + { + get + { + IntPtr rawData; + uint rawDataSize; + int ret = Interop.Nfc.NdefMessage.GetRawData(_messageHandle, out rawData, out rawDataSize); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to get rawdata, Error - " + (NfcError)ret); + return null; + } + + return NfcConvertUtil.UintLengthIntPtrToByteArray(rawData, rawDataSize); + } + } + + /// <summary> + /// Creates a object for the access point. + /// </summary> + public NfcNdefMessage() + { + int ret = Interop.Nfc.NdefMessage.Create(out _messageHandle); + + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to create Ndef message, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + } + + /// <summary> + /// Creates NDEF message handle from raw serial bytes. + /// </summary> + /// <param name="rawData">The NDEF message in form of bytes array.</param> + /// <param name="rawData">The size of bytes array.</param> + public NfcNdefMessage(byte[] rawData, uint rawDataSize) + { + int ret = Interop.Nfc.NdefMessage.CreateRawData(out _messageHandle, rawData, rawDataSize); + + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to create Ndef Rawdata message, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + } + + internal NfcNdefMessage(IntPtr messageHandle) + { + _messageHandle = messageHandle; + } + + ~NfcNdefMessage() + { + int ret = Interop.Nfc.NdefMessage.Destroy(_messageHandle); + + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to destroy ndef message, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + + Dispose(false); + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + private void Dispose(bool disposing) + { + if (disposed) + return; + + if (disposing) + { + // Free managed objects. + } + //Free unmanaged objects + disposed = true; + } + + /// <summary> + /// Appends a record into NDEF message. + /// </summary> + /// <returns>Whether appending the record succeeded.</returns> + /// <param name="record">The NfcNdefRecord object that will be appended into NDEF message.</param> + public bool AppendRecord(NfcNdefRecord record) + { + bool isSuccess = true; + + int ret = Interop.Nfc.NdefMessage.AppendRecord(_messageHandle, record.GetHandle()); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to append record, Error - " + (NfcError)ret); + isSuccess = false; + } + else + { + _recordList.Add(record); + } + + return isSuccess; + } + + /// <summary> + /// Inserts a record at index into NDEF message. + /// </summary> + /// <returns>Whether insterting the record succeeded.</returns> + /// <param name="index">The index of record ( starts from 0 ).</param> + /// <param name="record">The NfcNdefRecord object that will be appended into NDEF message.</param> + public bool InsertRecord(int index, NfcNdefRecord record) + { + bool isSuccess = true; + + int ret = Interop.Nfc.NdefMessage.InsertRecord(_messageHandle, index, record.GetHandle()); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to insert record, Error - " + (NfcError)ret); + isSuccess = false; + } + else + { + _recordList.Add(record); + } + + return isSuccess; + } + + /// <summary> + /// Inserts a record at index into NDEF message. + /// </summary> + /// <returns>Whether removing the record succeeded.</returns> + /// <param name="index">The index of record ( starts from 0 ).</param> + public bool RemoveRecord(int index) + { + bool isSuccess = true; + + int ret = Interop.Nfc.NdefMessage.RemoveRecord(_messageHandle, index); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to remove record, Error - " + (NfcError)ret); + isSuccess = false; + } + + return isSuccess; + } + + /// <summary> + /// Gets record by index. + /// </summary> + /// <returns>The NfcNdefRecord object.</returns> + /// <param name="index">The index of record ( starts from 0 ).</param> + public NfcNdefRecord GetRecord(int index) + { + IntPtr recordHandle; + NfcNdefRecord recordObject = null; + + int ret = Interop.Nfc.NdefMessage.GetRecord(_messageHandle, index, out recordHandle); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to remove record, Error - " + (NfcError)ret); + } + + foreach (NfcNdefRecord recordElement in _recordList) + { + if(recordElement.GetHandle() == recordHandle) + { + Log.Debug(Globals.LogTag, "Find record handle"); + recordObject = recordElement; + break; + } + } + + return recordObject; + } + + internal IntPtr GetHandle() + { + return _messageHandle; + } + } +} diff --git a/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcNdefRecord.cs b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcNdefRecord.cs new file mode 100644 index 0000000..10c2452 --- /dev/null +++ b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcNdefRecord.cs @@ -0,0 +1,306 @@ +/* + * 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; +using System.Collections.Generic; + +namespace Tizen.Network.Nfc +{ + /// <summary> + /// A class for Ndef Record information. It allows applications to use Ndef Record information. + /// </summary> + public class NfcNdefRecord : IDisposable + { + private bool disposed = false; + private IntPtr _recordHandle = IntPtr.Zero; + + /// <summary> + /// The record ID. + /// </summary> + public byte[] Id + { + get + { + IntPtr id; + int idLength; + int ret = Interop.Nfc.NdefRecord.GetId(_recordHandle, out id, out idLength); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to get id, Error - " + (NfcError)ret); + return null; + } + + return NfcConvertUtil.IntLengthIntPtrToByteArray(id, idLength); + } + set + { + int ret = Interop.Nfc.NdefRecord.SetId(_recordHandle, value, value.Length); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to set id, Error - " + (NfcError)ret); + } + } + } + + /// <summary> + /// The record payload. + /// </summary> + public byte[] Payload + { + get + { + IntPtr payload; + uint payloadLength; + int ret = Interop.Nfc.NdefRecord.GetPayload(_recordHandle, out payload, out payloadLength); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to get payload, Error - " + (NfcError)ret); + return null; + } + + return NfcConvertUtil.UintLengthIntPtrToByteArray(payload, payloadLength); + } + } + + /// <summary> + /// The record type. + /// </summary> + public byte[] Type + { + get + { + IntPtr type; + int typeSize; + int ret = Interop.Nfc.NdefRecord.GetType(_recordHandle, out type, out typeSize); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to get payload, Error - " + (NfcError)ret); + return null; + } + + return NfcConvertUtil.IntLengthIntPtrToByteArray(type, typeSize); + } + } + + /// <summary> + /// The record TNF(Type Name Format) value. + /// </summary> + public NfcRecordTypeNameFormat Tnf + { + get + { + int tnf; + int ret = Interop.Nfc.NdefRecord.GetTnf(_recordHandle, out tnf); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to get tnf, Error - " + (NfcError)ret); + } + return (NfcRecordTypeNameFormat)tnf; + } + } + + /// <summary> + /// The text of text type Ndef record. + /// </summary> + public string Text + { + get + { + string text; + int ret = Interop.Nfc.NdefRecord.GetText(_recordHandle, out text); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to get text, Error - " + (NfcError)ret); + } + return text; + } + } + + /// <summary> + /// The language code of text type Ndef record. + /// </summary> + public string LanguageCode + { + get + { + string languageCode; + int ret = Interop.Nfc.NdefRecord.GetLanguageCode(_recordHandle, out languageCode); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to get language code, Error - " + (NfcError)ret); + } + return languageCode; + } + } + + /// <summary> + /// The encoding type of text type Ndef record. + /// </summary> + public NfcEncodeType EncodeType + { + get + { + int encodeType; + int ret = Interop.Nfc.NdefRecord.GetEncodeType(_recordHandle, out encodeType); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to get encode type, Error - " + (NfcError)ret); + } + return (NfcEncodeType)encodeType; + } + } + + /// <summary> + /// The URI of uri type Ndef record. + /// </summary> + public string Uri + { + get + { + string uri; + int ret = Interop.Nfc.NdefRecord.GetUri(_recordHandle, out uri); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to get uri, Error - " + (NfcError)ret); + } + return uri; + } + } + + /// <summary> + /// The mime type of mime type Ndef record. + /// </summary> + public string MimeType + { + get + { + string mimeType; + int ret = Interop.Nfc.NdefRecord.GetMimeType(_recordHandle, out mimeType); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to get mime type, Error - " + (NfcError)ret); + } + return mimeType; + } + } + + /// <summary> + /// Creates a record with given parameter value. + /// </summary> + /// <param name="format">The type name format.</param> + /// <param name="type">The specified type name.</param> + /// <param name="id">The record ID.</param> + /// <param name="payload">The payload of this record.</param> + /// <param name="paloadLength">The byte size of payload.</param> + public NfcNdefRecord(NfcRecordTypeNameFormat format, byte[] type, byte[] id, byte[] payload, uint paloadLength) + { + int ret = Interop.Nfc.NdefRecord.Create(out _recordHandle, (int)format, type, type.Length, id, id.Length, payload, paloadLength); + + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to create Ndef record, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + } + + /// <summary> + /// Creates a record with text type payload. + /// </summary> + /// <param name="text">The encoded text.</param> + /// <param name="languageCode">The language code string value followed by IANA[RFC 3066] (ex: en-US, ko-KR).</param> + /// <param name="encode">The encoding type.</param> + public NfcNdefRecord(string text, string languageCode, NfcEncodeType encode) + { + int ret = Interop.Nfc.NdefRecord.CreateText(out _recordHandle, text, languageCode, (int)encode); + + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to create ndef Text record, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + } + + /// <summary> + /// Creates a record with text type payload. + /// </summary> + /// <param name="uri">The URI string that will be stored in the payload.</param> + public NfcNdefRecord(string uri) + { + int ret = Interop.Nfc.NdefRecord.CreateUri(out _recordHandle, uri); + + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to create ndef Uri record, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + } + + /// <summary> + /// Creates a record with text type payload. + /// </summary> + /// <param name="mimeType">The mime type [RFC 2046] (ex. text/plain, image/jpeg ) This value is stored in type field.</param> + /// <param name="data">The data in form of bytes array.</param> + /// <param name="dataSize">The size of data.</param> + public NfcNdefRecord(string mimeType, byte[] data, uint dataSize) + { + int ret = Interop.Nfc.NdefRecord.CreateMime(out _recordHandle, mimeType, data, dataSize); + + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to create ndef Mime record, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + } + + ~NfcNdefRecord() + { + int ret = Interop.Nfc.NdefRecord.Destroy(_recordHandle); + + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to destroy ndef record, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + + Dispose(false); + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + private void Dispose(bool disposing) + { + if (disposed) + return; + + if (disposing) + { + // Free managed objects. + } + //Free unmanaged objects + disposed = true; + } + + internal IntPtr GetHandle() + { + return _recordHandle; + } + } +} diff --git a/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcP2p.cs b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcP2p.cs new file mode 100644 index 0000000..fd85440 --- /dev/null +++ b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcP2p.cs @@ -0,0 +1,180 @@ +/* + * 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; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Tizen.Network.Nfc +{ + /// <summary> + /// A class for managing the p2p target information. + /// </summary> + public class NfcP2p : IDisposable + { + private IntPtr _p2pTargetHandle = IntPtr.Zero; + private bool disposed = false; + + private event EventHandler<P2pDataReceivedEventArgs> _p2pDataReceived; + + private Interop.Nfc.P2pDataReceivedCallback _p2pDataReceivedCallback; + + /// <summary> + /// The event for receiving data from NFC peer-to-peer target. + /// </summary> + public event EventHandler<P2pDataReceivedEventArgs> P2pDataReceived + { + add + { + if (_p2pDataReceived == null) + { + RegisterP2pDataReceivedEvent(); + } + _p2pDataReceived += value; + } + remove + { + _p2pDataReceived -= value; + if (_p2pDataReceived == null) + { + UnregisterP2pDataReceivedEvent(); + } + } + } + + internal NfcP2p(IntPtr handle) + { + _p2pTargetHandle = handle; + } + + ~NfcP2p() + { + Dispose(false); + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + private void Dispose(bool disposing) + { + if (disposed) + return; + + if (disposing) + { + // Free managed objects. + } + //Free unmanaged objects + disposed = true; + } + + internal IntPtr GetHandle() + { + return _p2pTargetHandle; + } + + /// <summary> + /// Sends data to NFC peer-to-peer target. + /// </summary> + /// <param name="ndefMessage">NfcNdefMessage object.</param> + public Task<NfcError> SendNdefMessageAsync(NfcNdefMessage ndefMessage) + { + var task = new TaskCompletionSource<NfcError>(); + + Interop.Nfc.VoidCallback callback = (int result, IntPtr userData) => + { + task.SetResult((NfcError)result); + return; + }; + + int ret = Interop.Nfc.P2p.Send(_p2pTargetHandle, ndefMessage.GetHandle(), callback, IntPtr.Zero); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to write ndef message, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + + return task.Task; + } + + private void RegisterP2pDataReceivedEvent() + { + _p2pDataReceivedCallback = (IntPtr p2pTargetHandle, IntPtr ndefMessageHandle, IntPtr userData) => + { + P2pDataReceivedEventArgs e = new P2pDataReceivedEventArgs(p2pTargetHandle, ndefMessageHandle); + _p2pDataReceived.SafeInvoke(null, e); + }; + + int ret = Interop.Nfc.P2p.SetDataReceivedCallback(_p2pTargetHandle, _p2pDataReceivedCallback, IntPtr.Zero); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to set p2p target discovered callback, Error - " + (NfcError)ret); + } + } + + private void UnregisterP2pDataReceivedEvent() + { + Interop.Nfc.P2p.UnsetDataReceivedCallback(_p2pTargetHandle); + } + } + + /// <summary> + /// A class for managing the snep(Simple NDEF Exchange Protocol) information. + /// </summary> + public class NfcSnep : IDisposable + { + private IntPtr _snepHandle = IntPtr.Zero; + private bool disposed = false; + + internal NfcSnep(IntPtr handle) + { + _snepHandle = handle; + } + + ~NfcSnep() + { + Dispose(false); + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + private void Dispose(bool disposing) + { + if (disposed) + return; + + if (disposing) + { + // Free managed objects. + } + //Free unmanaged objects + disposed = true; + } + + internal IntPtr GetHandle() + { + return _snepHandle; + } + } +} diff --git a/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcP2pAdapter.cs b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcP2pAdapter.cs new file mode 100644 index 0000000..25af7d4 --- /dev/null +++ b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcP2pAdapter.cs @@ -0,0 +1,127 @@ +/* + * 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; +using System.Collections.Generic; + +namespace Tizen.Network.Nfc +{ + /// <summary> + /// A class for NFC P2P(Peer to Peer) mode. It allows applications to handle P2P informations. + /// </summary> + /// <privilege>http://tizen.org/privilege/nfc</privilege> + public class NfcP2pAdapter : IDisposable + { + private NfcP2p _p2pTarget; + private bool disposed = false; + + private event EventHandler<P2pTargetDiscoveredEventArgs> _p2pTargetDiscovered; + + private Interop.Nfc.P2pTargetDiscoveredCallback _p2pTargetDiscoveredCallback; + + /// <summary> + /// The event for receiving NFC peer-to-peer target discovered notification. + /// </summary> + public event EventHandler<P2pTargetDiscoveredEventArgs> P2pTargetDiscovered + { + add + { + if (_p2pTargetDiscovered == null) + { + RegisterP2pTargetDiscoveredEvent(); + } + _p2pTargetDiscovered += value; + } + remove + { + _p2pTargetDiscovered -= value; + if (_p2pTargetDiscovered == null) + { + UnregisterP2pTargetDiscoveredEvent(); + } + } + } + + internal NfcP2pAdapter() + { + } + + ~NfcP2pAdapter() + { + Dispose(false); + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + private void Dispose(bool disposing) + { + if (disposed) + return; + + if (disposing) + { + // Free managed objects. + } + //Free unmanaged objects + disposed = true; + } + + /// <summary> + /// Gets current connected p2p target. + /// </summary> + /// <returns>NfcP2p object.</returns> + public NfcP2p GetConnectedTarget() + { + IntPtr targetHandle = IntPtr.Zero; + int ret = Interop.Nfc.GetConnectedTarget(out targetHandle); + + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to get connected p2p target, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + _p2pTarget = new NfcP2p(targetHandle); + + return _p2pTarget; + } + + private void RegisterP2pTargetDiscoveredEvent() + { + _p2pTargetDiscoveredCallback = (int type, IntPtr p2pTargetHandle, IntPtr userData) => + { + NfcDiscoveredType tagType = (NfcDiscoveredType)type; + P2pTargetDiscoveredEventArgs e = new P2pTargetDiscoveredEventArgs(tagType, p2pTargetHandle); + _p2pTargetDiscovered.SafeInvoke(null, e); + }; + + int ret = Interop.Nfc.SetP2pTargetDiscoveredCallback(_p2pTargetDiscoveredCallback, IntPtr.Zero); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to set p2p target discovered callback, Error - " + (NfcError)ret); + } + } + + private void UnregisterP2pTargetDiscoveredEvent() + { + Interop.Nfc.UnsetP2pTargetDiscoveredCallback(); + } + } +} diff --git a/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcSecureElement.cs b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcSecureElement.cs new file mode 100644 index 0000000..02c8986 --- /dev/null +++ b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcSecureElement.cs @@ -0,0 +1,80 @@ +/* + * 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; +using System.Collections.Generic; + +namespace Tizen.Network.Nfc +{ + /// <summary> + /// A class for managing the Secure Element information. + /// </summary> + public class NfcSecureElement : IDisposable + { + private IntPtr _secureElementHandle = IntPtr.Zero; + private bool disposed = false; + + internal NfcSecureElement(IntPtr handle) + { + _secureElementHandle = handle; + } + + ~NfcSecureElement() + { + Dispose(false); + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + private void Dispose(bool disposing) + { + if (disposed) + return; + + if (disposing) + { + // Free managed objects. + } + //Free unmanaged objects + disposed = true; + } + + /// <summary> + /// Send APDU(Application Protocol Data Unit) response to CLF(Contactless Front-end). + /// </summary> + /// <param name="response">The bytes array of response data.</param> + /// <param name="responseLength">The size of response bytes array.</param> + public void HceSendApduResponse(byte[] response, uint responseLength) + { + int ret = Interop.Nfc.CardEmulation.HceSendApduRespondse(_secureElementHandle, response, responseLength); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to hcd send apdu response, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + } + + internal IntPtr GetHandle() + { + return _secureElementHandle; + } + } +} diff --git a/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcTag.cs b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcTag.cs new file mode 100644 index 0000000..87ec4c2 --- /dev/null +++ b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcTag.cs @@ -0,0 +1,272 @@ +/* + * 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; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Tizen.Network.Nfc +{ + /// <summary> + /// A class for managing the Tag information. + /// </summary> + public class NfcTag : IDisposable + { + private bool disposed = false; + private IntPtr _tagHandle = IntPtr.Zero; + + /// <summary> + /// The type of NFC tag. + /// </summary> + public NfcTagType Type + { + get + { + int type; + int ret = Interop.Nfc.Tag.GetType(_tagHandle, out type); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to get tag type, Error - " + (NfcError)ret); + } + return (NfcTagType)type; + } + } + + /// <summary> + /// Whether the given NFC tag supports NDEF messages. + /// </summary> + public bool IsSupportNdef + { + get + { + bool isSupport; + int ret = Interop.Nfc.Tag.IsSupportNdef(_tagHandle, out isSupport); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to get support state, Error - " + (NfcError)ret); + } + return isSupport; + + } + } + + /// <summary> + /// The maximum NDEF message size that can be stored in NFC tag. + /// </summary> + public uint MaximumNdefSize + { + get + { + uint maxSize; + int ret = Interop.Nfc.Tag.GetMaximumNdefSize(_tagHandle, out maxSize); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to get max ndef size, Error - " + (NfcError)ret); + } + return maxSize; + } + } + + /// <summary> + /// The size of NDEF message that stored in the tag. + /// </summary> + public uint NdefSize + { + get + { + uint ndefSize; + int ret = Interop.Nfc.Tag.GetNdefSize(_tagHandle, out ndefSize); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to get ndef size, Error - " + (NfcError)ret); + } + return ndefSize; + } + } + + internal NfcTag(IntPtr handle) + { + _tagHandle = handle; + } + + ~NfcTag() + { + Dispose(false); + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + private void Dispose(bool disposing) + { + if (disposed) + return; + + if (disposing) + { + // Free managed objects. + } + //Free unmanaged objects + disposed = true; + } + + /// <summary> + /// Retrieves all tag information. + /// </summary> + /// <returns>List of NfcTagInformation objects.</returns> + public IEnumerable<NfcTagInformation> ForeachInformation() + { + List<NfcTagInformation> infoList = new List<NfcTagInformation>(); + Interop.Nfc.TagInformationCallback callback = (IntPtr key, IntPtr infoValue, int valueSize, IntPtr userData) => + { + if (key != IntPtr.Zero && infoValue != IntPtr.Zero) + { + NfcTagInformation tagInfo = new NfcTagInformation(); + + tagInfo.Key = Marshal.PtrToStringAnsi(key); + tagInfo.InformationValue = new byte[valueSize]; + Marshal.Copy(infoValue, tagInfo.InformationValue, 0, valueSize); + + infoList.Add(tagInfo); + + return true; + } + return false; + }; + + int ret = Interop.Nfc.Tag.ForeachInformation(_tagHandle, callback, IntPtr.Zero); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to get all Tag information, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + + return infoList; + } + + /// <summary> + /// Transceives the data of the raw format card. + /// </summary> + /// <param name="buffer">The binary data for parameter or additional commands.</param> + public Task<byte[]> TransceiveAsync(byte[] buffer) + { + var task = new TaskCompletionSource<byte[]>(); + + byte[] resultBuffer = null; + Interop.Nfc.TagTransceiveCompletedCallback callback = (int result, IntPtr resultData, int dataSize, IntPtr userData) => + { + if (result == (int)NfcError.None) + { + resultBuffer = new byte[dataSize]; + Marshal.Copy(resultData, resultBuffer, 0, dataSize); + task.SetResult(resultBuffer); + } + return; + }; + + int ret = Interop.Nfc.Tag.Transceive(_tagHandle, buffer, buffer.Length, callback, IntPtr.Zero); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to transceive data, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + + return task.Task; + } + + /// <summary> + /// Reads NDEF formatted data from NFC tag. + /// </summary> + public Task<NfcNdefMessage> ReadNdefMessageAsync() + { + var task = new TaskCompletionSource<NfcNdefMessage>(); + + NfcNdefMessage ndefMsg = null; + Interop.Nfc.TagReadCompletedCallback callback = (int result, IntPtr ndefMessage, IntPtr userData) => + { + if (result == (int)NfcError.None) + { + ndefMsg = new NfcNdefMessage(ndefMessage); + task.SetResult(ndefMsg); + + return true; + } + return false; + }; + + int ret = Interop.Nfc.Tag.ReadNdef(_tagHandle, callback, IntPtr.Zero); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to read ndef message, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + + return task.Task; + } + + /// <summary> + /// Writes NDEF formatted data. + /// </summary> + /// <param name="ndefMessage">The NfcNdefMessage object.</param> + public Task<NfcError> WriteNdefMessageAsync(NfcNdefMessage ndefMessage) + { + var task = new TaskCompletionSource<NfcError>(); + + Interop.Nfc.VoidCallback callback = (int result, IntPtr userData) => + { + task.SetResult((NfcError)result); + return; + }; + + int ret = Interop.Nfc.Tag.WriteNdef(_tagHandle, ndefMessage.GetHandle(), callback, IntPtr.Zero); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to write ndef message, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + + return task.Task; + } + + /// <summary> + /// Formats the detected tag that can store NDEF message. + /// </summary> + /// <param name="keyValue">The key value that may need to format the tag.</param> + public Task<NfcError> FormatNdefMessageAsync(byte[] keyValue) + { + var task = new TaskCompletionSource<NfcError>(); + + Interop.Nfc.VoidCallback callback = (int result, IntPtr userData) => + { + task.SetResult((NfcError)result); + return; + }; + + int ret = Interop.Nfc.Tag.FormatNdef(_tagHandle, keyValue, keyValue.Length, callback, IntPtr.Zero); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to format ndef message, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + + return task.Task; + } + } +} diff --git a/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcTagAdapter.cs b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcTagAdapter.cs new file mode 100644 index 0000000..815b75f --- /dev/null +++ b/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcTagAdapter.cs @@ -0,0 +1,127 @@ +/* + * 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; +using System.Collections.Generic; + +namespace Tizen.Network.Nfc +{ + /// <summary> + /// A class for NFC Tag mode. It allows applications to handle Tag informations. + /// </summary> + /// <privilege>http://tizen.org/privilege/nfc</privilege> + public class NfcTagAdapter : IDisposable + { + private NfcTag _tag; + private bool disposed = false; + + private event EventHandler<TagDiscoveredEventArgs> _tagDiscovered; + + private Interop.Nfc.TagDiscoveredCallback _tagDiscoveredCallback; + + /// <summary> + /// The event for receiving tag discovered notification. + /// </summary> + public event EventHandler<TagDiscoveredEventArgs> TagDiscovered + { + add + { + if (_tagDiscovered == null) + { + RegisterTagDiscoveredEvent(); + } + _tagDiscovered += value; + } + remove + { + _tagDiscovered -= value; + if (_tagDiscovered == null) + { + UnregisterTagDiscoveredEvent(); + } + } + } + + internal NfcTagAdapter() + { + } + + ~NfcTagAdapter() + { + Dispose(false); + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + private void Dispose(bool disposing) + { + if (disposed) + return; + + if (disposing) + { + // Free managed objects. + } + //Free unmanaged objects + disposed = true; + } + + /// <summary> + /// Gets current connected tag. + /// </summary> + /// <returns>NfcTag object.</returns> + public NfcTag GetConnectedTag() + { + IntPtr tagHandle = IntPtr.Zero; + int ret = Interop.Nfc.GetConnectedTag(out tagHandle); + + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to get connected tag, Error - " + (NfcError)ret); + NfcErrorFactory.ThrowNfcException(ret); + } + _tag = new NfcTag(tagHandle); + + return _tag; + } + + private void RegisterTagDiscoveredEvent() + { + _tagDiscoveredCallback = (int type, IntPtr tagHandle, IntPtr userData) => + { + NfcDiscoveredType tagType = (NfcDiscoveredType)type; + TagDiscoveredEventArgs e = new TagDiscoveredEventArgs(tagType, tagHandle); + _tagDiscovered.SafeInvoke(null, e); + }; + + int ret = Interop.Nfc.SetTagDiscoveredCallback(_tagDiscoveredCallback, IntPtr.Zero); + if (ret != (int)NfcError.None) + { + Log.Error(Globals.LogTag, "Failed to set tag discovered callback, Error - " + (NfcError)ret); + } + } + + private void UnregisterTagDiscoveredEvent() + { + Interop.Nfc.UnsetTagDiscoveredCallback(); + } + } +} |