summaryrefslogtreecommitdiff
path: root/Tizen.Network.Nfc/Tizen.Network.Nfc/NfcTag.cs
blob: 76431719409667c9efd8810e78928655fb94a17c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
/*
 * 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>
    /// <since_tizen> 3 </since_tizen>
    public class NfcTag : IDisposable
    {
        private bool disposed = false;
        private IntPtr _tagHandle = IntPtr.Zero;

        /// <summary>
        /// The type of NFC tag.
        /// </summary>
        /// <since_tizen> 3 </since_tizen>
        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>
        /// <since_tizen> 3 </since_tizen>
        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>
        /// <since_tizen> 3 </since_tizen>
        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>
        /// <since_tizen> 3 </since_tizen>
        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>
        /// <since_tizen> 3 </since_tizen>
        /// <returns>List of NfcTagInformation objects.</returns>
        /// <exception cref="NotSupportedException">Thrown when Nfc is not supported.</exception>
        /// <exception cref="InvalidOperationException">Thrown when the method failed due to invalid operation.</exception>
        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(Marshal.PtrToStringAnsi(key), 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>
        /// <since_tizen> 3 </since_tizen>
        /// <param name="buffer">The binary data for parameter or additional commands.</param>
        /// <exception cref="NotSupportedException">Thrown when Nfc is not supported.</exception>
        /// <exception cref="ArgumentException">Thrown when method is failed due to an invalid parameter.</exception>
        /// <exception cref="InvalidOperationException">Thrown when the method failed due to invalid operation.</exception>
        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>
        /// <since_tizen> 3 </since_tizen>
        /// <exception cref="NotSupportedException">Thrown when Nfc is not supported.</exception>
        /// <exception cref="InvalidOperationException">Thrown when the method failed due to invalid operation.</exception>
        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>
        /// <since_tizen> 3 </since_tizen>
        /// <param name="ndefMessage">The NfcNdefMessage object.</param>
        /// <exception cref="NotSupportedException">Thrown when Nfc is not supported.</exception>
        /// <exception cref="ArgumentException">Thrown when method is failed due to an invalid parameter.</exception>
        /// <exception cref="InvalidOperationException">Thrown when the method failed due to invalid operation.</exception>
        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>
        /// <since_tizen> 3 </since_tizen>
        /// <param name="keyValue">The key value that may need to format the tag.</param>
        /// <exception cref="NotSupportedException">Thrown when Nfc is not supported.</exception>
        /// <exception cref="ArgumentException">Thrown when method is failed due to an invalid parameter.</exception>
        /// <exception cref="InvalidOperationException">Thrown when the method failed due to invalid operation.</exception>
        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;
        }
    }
}