823677ca562bd642127a75d641f4969003550168
[profile/ivi/saythis.git] / js / wsapi.js
1 /*
2  * Copyright (c) 2012, Intel Corporation.
3  *
4  * This program is licensed under the terms and conditions of the 
5  * Apache License, version 2.0.  The full text of the Apache License is at
6  * http://www.apache.org/licenses/LICENSE-2.0
7  *
8  */
9
10 var wsAPI = (function(){
11     var ws = null;
12     var callbackQueue = {};
13     var reqId = 0;
14     var ready = false;
15     connect();
16
17     function connect(url)
18     {
19         url = typeof url !== 'undefined' ? url : 'ws://localhost:9999';
20         ws = new WebSocket(url);
21         ws.onopen = function() {
22             ready = true;
23             send({
24                 'type': 'connect',
25             });
26         };
27
28         ws.onmessage = function (e) {
29             console.log('Received data: ', e.data);
30             jsonMsg = JSON.parse(e.data);
31             if (jsonMsg.api_namespace !== 'tizen.ivi.texttospeech') return;
32 /*
33             if (jsonMsg.type === 'api_error')
34                 console.log(jsonMsg.api_error_msg);
35 */
36             if (jsonMsg.type === 'method_reply' && jsonMsg.method_name === 'speak') {
37                 callback = callbackQueue[jsonMsg.request_id]
38                 if (!callback || !typeof(callback) === 'function') {
39                     return;
40                 }
41                 
42                 callback(jsonMsg.results);
43                 delete callbackQueue[jsonMsg.request_id];
44             }
45         };
46
47         ws.onclose = function(e) {
48             ready = false;
49             console.log(e);
50         };
51     }
52
53     function send(msg) {
54         if (!ready) {
55             console.log('Websocket connection not ready, cannot send message');
56             return;
57         } 
58         jsonMsg = JSON.stringify(msg);
59         ws.send(jsonMsg);
60         console.log('sent message: ' + jsonMsg);
61     }
62
63     function invokeMethod(json, callback) {
64         reqId++;
65         if (callback)
66             callbackQueue[reqId.toString()] = callback;
67         json['request_id'] = reqId.toString();
68         send(json);
69         console.log('invoke method');
70     }
71
72     return {
73         isReady: function() {
74             return ready;
75         },
76         connect: connect,
77         speak: function (text, callback) {
78             if (!text)
79                 return;
80             if (callback && typeof(callback) !== 'function')
81                 return;
82
83             json = {
84                 'api_namespace': 'tizen.ivi.texttospeech',
85                 'type': 'method',
86                 'method_name': 'speak',
87                 'method_args': {
88                     'text': text
89                 }
90             };
91             invokeMethod(json, callback);
92         }
93     }
94 })()