3bedee099d1f75a47cf1b297f17f65d1b896aa8a
[apps/web/sample/ContactsExchanger.git] / project / js / app.nfc.js
1 /*
2  *      Copyright 2013  Samsung Electronics Co., Ltd
3  *
4  *      Licensed under the Flora License, Version 1.1 (the "License");
5  *      you may not use this file except in compliance with the License.
6  *      You may obtain a copy of the License at
7  *
8  *              http://floralicense.org/license/
9  *
10  *      Unless required by applicable law or agreed to in writing, software
11  *      distributed under the License is distributed on an "AS IS" BASIS,
12  *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *      See the License for the specific language governing permissions and
14  *      limitations under the License.
15  */
16
17 /*jslint devel: true*/
18 /*global $, tizen, App, app */ 
19 (function () { // strict mode wrapper
20     'use strict';
21
22     /**
23      * Constructs NFCControl
24      * @constructor
25      * @param {App} app
26      */
27     App.NFCControl = function NFCControl(app) {
28         this.app = app;
29         this.init();
30     };
31
32     App.NFCControl.prototype = {
33         nfcTarget: null,
34         nfcStateMemory: false,
35
36         /**
37          * Initialize NFC application module
38          */
39         init: function nfc_init() {
40             this.card = new App.NFCCard(this);
41             this.peer = new App.NFCPeer(this);
42             this.endOfText = String.fromCharCode(3);
43         },
44         /**
45          * Disable tag/target detection and move to start page
46          *
47          * @param {string} monit message text to be displayed
48          */
49         timeExpired: function nfc_timeExpired(monit) {
50             clearTimeout(this.app.timeOutHandler);
51             if (tizen.nfc.getDefaultAdapter().powered) {
52                 this.unsetTargetDetect();
53                 this.unsetTagDetect();
54             }
55             this.app.ui.moveToStartPage(monit);
56         },
57
58         /**
59          * Get the end of text marker
60          *
61          * @returns {string}
62          */
63         getEndOfText: function nfc_getEndOfText() {
64             return this.endOfText;
65         },
66
67         /**
68          *
69          * @param {string|object} contact
70          * @returns {string}
71          */
72         prepareForNFC: function nfc_prepareForNFC(contact) {
73             return contact.vCard;
74         },
75
76         resolveData: function nfc_resolveData(value, endOfText) {
77             if (!value) {
78                 return '';
79             }
80             endOfText = endOfText || this.getEndOfText();
81             return value.replace(endOfText, '…');
82         },
83
84
85         resolveContact: function nfc_resolveContact(contactsString) {
86             var receivedContact = new tizen.Contact(contactsString, 'VCARD_30');
87
88             return {
89                 phone: receivedContact.phoneNumbers[0].number,
90                 phone_type: receivedContact.phoneNumbers[0].types[0],
91                 first: receivedContact.name.firstName,
92                 middle: receivedContact.name.middleName,
93                 last: receivedContact.name.lastName,
94                 vCard: receivedContact.convertToString('VCARD_30')
95             };
96         },
97
98         /**
99          *
100          * @param {type} record
101          * @returns {undefined}
102          */
103         fillRecordInfo: function nfc_fillRecordInfo(record) {
104             try {
105                 var contactsData = this.resolveContact(
106                     this.convertNDEF2phoneNumber(record.payload)
107                 );
108                 this.app.nfc.displayContact(contactsData);
109             } catch (error) {
110                 console.error(error);
111             }
112         },
113
114         /**
115          *
116          * @param {NDEFMessage} message
117          */
118         readMessage: function nfc_readMessage(message) {
119             try {
120                 this.fillRecordInfo(message.records[0]);
121             } catch (e) {
122                 console.error(e.message);
123             }
124         },
125
126         /**
127          *
128          * @param {string|object} contact
129          * @returns {NDEFMessage}
130          */
131         contact2NDEF: function nfc_contact2NDEF(contact) {
132             var t, a = [],
133                 len, i, newMessage = new tizen.NDEFMessage();
134             if (typeof contact === 'string') {
135                 t = contact;
136             } else {
137                 t = contact.convertToString('VCARD_30');
138             }
139             len = t.length;
140             for (i = 0; i < len; i += 1) {
141                 a[i] = t.charCodeAt(i);
142             }
143             newMessage.records[0] =
144                 new tizen.NDEFRecordMedia('text/x-vcard', a);
145             return newMessage;
146         },
147
148         /**
149          *
150          * @param {string} contact
151          * @returns {NDEFMessage}
152          */
153         phoneNumber2NDEF: function nfc_phoneNumber2NDEF(contact) {
154             var phoneNumberArray = [],
155                 i,
156                 length = contact.length,
157                 newMessage = new tizen.NDEFMessage();
158             for (i = 0; i < length; i += 1) {
159                 phoneNumberArray.push(contact.charCodeAt(i));
160             }
161             newMessage.records[0] =
162                 new tizen.NDEFRecordMedia('text/x-vcard', phoneNumberArray);
163             return newMessage;
164         },
165
166         /**
167          *
168          * @param {string} contact
169          * @returns {string}
170          */
171         convertNDEF2phoneNumber: function nfc_convertNDEF2phoneNumber(contact) {
172             var i, length = contact.length,
173                 phoneNumber = '';
174             for (i = 0; i < length; i += 1) {
175                 phoneNumber += String.fromCharCode(contact[i]);
176             }
177             return phoneNumber;
178         },
179
180         /**
181          * NFC setPowered success callback
182          * @returns {undefined}
183          */
184         onPowerOn: function nfc_onPowerOn() {
185             console.log('Power On succeeded.');
186             this.app.started = true;
187             this.app.ui.loadStartPage();
188         },
189
190         /**
191          * NFC setPowered error callback
192          * @param {Error} err
193          * @returns {undefined}
194          */
195         onPowerOnFails: function nfc_onPowerOnFails(err) {
196             console.error('Power On error: ' + err.message);
197             this.app.ui.showPopupWarning();
198         },
199
200         /**
201          * NFC setPowered success callback
202          * @returns {undefined}
203          */
204         onPowerOff: function nfc_onPowerOff() {
205             tizen.application.getCurrentApplication().exit();
206         },
207
208         /**
209          * NFC setPowered error callback
210          * @param {Error} err
211          * @returns {undefined}
212          */
213         onPowerOffFails: function nfc_onPowerOffFails(err) {
214             console.error('Power Off error', err);
215             tizen.application.getCurrentApplication().exit();
216         },
217
218         isPowered: function nfc_isPowered() {
219             return this.nfcAdapter.powered;
220         },
221
222         startNFC: function nfc_startNFC() {
223             try {
224                 this.nfcAdapter = tizen.nfc.getDefaultAdapter();
225                 if (this.nfcAdapter.powered) {
226                     this.nfcStateMemory = true;
227                     this.onPowerOn();
228                     return;
229                 }
230                 this.nfcStateMemory = false;
231                 console.log('Turning NFC adapter On...');
232                 this.nfcAdapter.setPowered(
233                     true,
234                     this.onPowerOn.bind(this),
235                     this.onPowerOnFails.bind(this)
236                 );
237             } catch (e) {
238                 console.error('startNFC problem', e);
239                 this.app.ui.showPopupWarning();
240             }
241         },
242
243         stopNFC: function nfc_stopNFC() {
244             try {
245                 if (this.nfcStateMemory) {
246                     this.onPowerOff();
247                 } else {
248                     this.nfcAdapter.setPowered(
249                         false,
250                         this.onPowerOff.bind(this),
251                         this.onPowerOffFails.bind(this)
252                     );
253                 }
254             } catch (err) {
255                 console.error('setPowered(false) problem', err);
256             }
257         },
258
259         unsetTargetDetect: function nfc_unsetTargetDetect() {
260             try {
261                 if (this.nfcTarget) {
262                     this.nfcTarget.unsetReceiveNDEFListener();
263                     this.nfcTarget = null;
264                 } else {
265                     //console.info('app.nfc.nfcTarget not set');
266                 }
267             } catch (error) {
268                 console.error('error: ' + error.message);
269             }
270             try {
271                 this.nfcAdapter.unsetPeerListener();
272             } catch (e) {
273                 console.error('error: ' + e.message);
274             }
275         },
276
277         unsetTagDetect: function nfc_unsetTagDetect() {
278             try {
279                 this.nfcAdapter.unsetTagListener();
280             } catch (error) {
281                 console.error('error: ' + error.message);
282             }
283         },
284
285         displayContact: function nfc_displayContact(obj) {
286             clearTimeout(this.app.timeOutHandler);
287             if (tizen.nfc.getDefaultAdapter().powered) {
288                 this.unsetTargetDetect();
289                 this.unsetTagDetect();
290             }
291             this.app.ui.moveToContactPage(obj);
292         },
293
294         sucDetach: function nfc_sucDetach() {}
295     };
296
297 }());