summaryrefslogtreecommitdiff
path: root/plugins/websocket/test/vehicle.js
blob: 706fb698e7d1335d3fe2780581f536d417290604 (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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
/*
 * Copyright (c) 2012, Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 */

/*****************************************************************************
* Class name: Vehicle
* Description:
*    A javascript implementation of the IVI vehicle API that communicates
*    to the automotive message broker through a websocket
* Optional constructor arguments:
*    sCB: success callback, called when socket is connected, argument is
*         success message string
*    eCB: error callback, called on socket close or error, argument is error
*         message string
*    url: the URL to use for the websocket, in the form "ws://host:port/script"
*    protocol: the protocol to use for the websocket, default is "http-only"
*
* [Public Member functions]
*  Function name: getSupportedEventTypes(type, writeable, successCB, errorCB)
*    Description:
*        Retrieves a list of vehicle events for the requested type
*    Required arguments:
*        type: target event or group to query (use empty string for all events)
*        writeable: if true, return only writeable events, otherwise get all
*        successCB: success callback, gets called with a string list of names
*              for all the events and event groups that are children of the
*              target. e.g. "vehicle_info" returns all events/groups with the
*              vehicle_info prefix. If the target is an event group, it's
*              omitted from the returned list
*        errorCB: error callback, called with error message string
*
*  Function name: get(eventlist, successCB, errorCB)
*    Description:
*        Retrieves a list of event/value pairs for a target list of event names
*    Required arguments:
*        eventlist[]: list of events to read (use empty string for all events)
*        successCB: success callback, gets called with the event/value pair list
*                   for all requested events. The list is the in the
*                   form of data[n].name/data[n].value
*        errorCB: error callback, called with error message string
*
*  Function name: getHistory(event, startTime, endTime, successCB, errorCB)
*    Description:
*        Retrieves a list of event/value pairs for a target list of event names
*    Required arguments:
*        event: event to read
*        startTime: start date/time
*        endTime: end date/time
*        successCB: success callback, gets called with the event/value pair list
*                   for all requested events. The list is the in the
*                   form of data[n].name/data[n].value
*        errorCB: error callback, called with error message string
*
*
*  Function name: set(eventlist, valuelist, successCB, errorCB)
*    Description:
*        Sets a gourp of event's values (triggers error on read-only events)
*    Required arguments:
*        eventlist: target events to set
*        valuelist: target event values
*        successCB: success callback, gets called with the eventlist
*                   that was successfully set
*        errorCB: error callback, called with error message string
*
*  Function name: subscribe(eventlist, successCB, errorCB)
*    Description:
*        Subscribe to a list of events so you can listen to value changes, they
*        can be monitored with document.addEventListener(eventname, callback, false);
*        The Event object passed to the callback has two parameters, e.name and
*        e.value. Events are sent to the handler individually.
*    Required arguments:
*        eventlist: target events to listen to
*        successCB: success callback, gets called with the eventlist
*                   that was successfully subscribed
*        errorCB: error callback, called with the eventlist that failed to subscribe
*
*  Function name: unsubscribe(eventlist, successCB, errorCB)
*    Description:
*        Unsubscribe to a list of events to let the server know you're not listening,
*        they should stop being sent from the server if no other clients are using them,
*        but will at least stop being triggered in your app.
*    Required arguments:
*        eventlist: target events to stop listening to
*        successCB: success callback, gets called with the eventlist
*                   that was successfully unsubscribed
*        errorCB: error callback, called with the eventlist that failed to unsubscribe
*
******************************************************************************/
/*
(function () {
*/
function Vehicle(sCB, eCB, url, protocol)
{
    /* store a copy of Vehicle this for reference in callbacks */
    var self = this;

    this.iSuccessCB = sCB;
    this.iErrorCB = eCB;

    /* variables for call management, supports up to 100 simultaneously */
    this.methodIdx = 0;
    this.methodCalls = [];
    for(var i = 0; i < 100; i++)
    {
        this.methodCalls[i] = null;
    }

    /* number of connection retries to attempt if the socket closes */
    this.retries = 5;
    this.connected = false;

    /* timeout for method calls in milliseconds */
    this.timeouttime = 5000;

    /* default values for WebSocket */
    this.socketUrl = "ws://localhost:23000/vehicle";
    this.socketProtocol = "http-only";

    /* override the websocket address if parameters are given */
    if(url !== undefined) this.socketUrl = url;
    if(protocol !== undefined) this.socketProtocol = protocol;

    this.VehicleMethodCall = function(id, name, successCB, errorCB)
    {
        var me = this;
        this.successCB = successCB;
        this.errorCB = errorCB;
        this.transactionid = id;
        this.name = name;
        this.done = false;
        this.start = function()
        {
            me.timeout = setTimeout(function(){
                if(me.errorCB !== undefined)
                {
                    me.errorCB("\""+me.name+"\" method timed out after "+self.timeouttime+"ms");
                }
                me.finish();
            }, self.timeouttime);
        }
        this.finish = function()
        {
            if(me.timeout !== undefined)
            {
                clearTimeout(me.timeout);
            }
            me.done = true;
        }
    }

    function init() {
        if ("WebSocket" in window)
        {
            if(self.socketProtocol.length > 0)
            {
                self.socket = new WebSocket(self.socketUrl, self.socketProtocol);
            }
            else
            {
                self.socket = new WebSocket(self.socketUrl);
            }
            self.socket.onopen = function()
            {
                self.connected = true;
                self.iSuccessCB((self.retries < 5)?"(RECONNECTED)":"");
                self.retries = 5;
            };
            self.socket.onclose = function()
            {
                self.connected = false;
                self.iErrorCB("socket closed "+((self.retries > 0)?"retrying in 5 seconds ...":""));
                if(self.retries > 0)
                {
                    setTimeout(function(){
                        self.retries--;
                        init();
                    }, 5000);
                }
            };
            self.socket.onerror = function(e)
            {
                self.iErrorCB(e.data);
            };
            self.socket.onmessage = function (e)
            {
                self.receive(e.data);
            };
        }
        else
        {
            console.log("This browser doesn't appear to support websockets!");
        }
    }
    init();
}

Vehicle.prototype.generateTransactionId = function()
{
    var i, val = [];
    for(i = 0; i < 8; i++)
    {
       var num = Math.floor((Math.random()+1)*65536);
       val[i] = num.toString(16).substring(1);
    }
    var uuid = val[0]+val[1]+"-"+
               val[2]+"-"+val[3]+"-"+val[4]+"-"+
               val[5]+val[6]+val[7];
    return uuid;
}

Vehicle.prototype.send = function(obj, successCB, errorCB)
{
    if(!this.connected)
    {
        if(errorCB !== undefined)
        {
            errorCB("\""+obj.name+"\" method failed because socket is closed");
        }
        return;
    }
    var i = this.methodIdx;
    this.methodIdx = (this.methodIdx + 1)%100;
    this.methodCalls[i] = new this.VehicleMethodCall(obj.transactionid,
        obj.name, successCB, errorCB);
    this.socket.send(JSON.stringify(obj));
    this.methodCalls[i].start();
}


Vehicle.prototype.getSupportedEventTypes = function(type, writeable, successCB, errorCB)
{
    var obj = {
        "type" : "method",
        "name" : "getSupported",
        "writeable" : writeable,
        "transactionid" : this.generateTransactionId(),
        "data" : type
    };
    this.send(obj, successCB, errorCB);
}

Vehicle.prototype.get = function(name, zone, successCB, errorCB)
{
    property = {"property" : name, "zone" : zone};

    var obj = {
        "type" : "method",
        "name": "get",
        "transactionid" : this.generateTransactionId(),
        "data" : property
    };
    this.send(obj, successCB, errorCB);
}

Vehicle.prototype.getHistory = function(event, startTime, endTime, successCB, errorCB)
{
    var obj = {
        "type" : "method",
        "name": "getHistory",
        "transactionid" : this.generateTransactionId(),
        "data" : [event, (startTime.getTime()/1000).toString(), (endTime.getTime()/1000).toString()]
    };

    this.send(obj, successCB, errorCB);

}

Vehicle.prototype.set = function(name, value, zone, successCB, errorCB)
{
    var obj = {
        "type" : "method",
        "name": "set",
        "transactionid" : this.generateTransactionId(),
        "data" : { "property" : name, "value" : value, "zone" : zone }
    };

    this.send(obj, successCB, errorCB);
}

Vehicle.prototype.subscribe = function(name, zone, successCB, errorCB)
{
    var obj = {
        "type" : "method",
        "name": "subscribe",
        "transactionid" : this.generateTransactionId(),
        "property" : name
    };

    this.send(obj, successCB, errorCB);
}

Vehicle.prototype.unsubscribe = function(name, zone, successCB, errorCB)
{
    var obj = {
        "type" : "method",
        "name": "unsubscribe",
        "transactionid" : this.generateTransactionId(),
        "property" : name
    };

    this.send(obj, successCB, errorCB);
}

Vehicle.prototype.sendEvent = function(name, value)
{
    var evt = document.createEvent("Event");
    evt.initEvent(name, true, true);
    evt.name = name;
    evt.value = value;
    document.dispatchEvent(evt);
    console.log(evt);
}

Vehicle.prototype.receive = function(msg)
{
    var self = this;
    var event;
    try {
        event = JSON.parse(msg);
    }
    catch(e) {
        self.iErrorCB("GARBAGE MESSAGE: "+msg);
        return;
    }

    if((event === undefined)||(event.type === undefined)||
       (event.name === undefined))
    {
        self.iErrorCB("BADLY FORMED MESSAGE: "+msg);
        return;
    }
    else
    {
        if(event.type === "methodReply")
        {
            var calls = this.methodCalls;
            for(var i = 0; i < calls.length; i++)
            {
                var call = calls[i];
                if(call && (!call.done) && (call.transactionid === event.transactionid))
                {
                    call.finish();
                    if(event.error !== undefined)
                    {
                        call.errorCB(event.error);
                    }
                    else if(call.successCB !== undefined)
                    {
                        call.successCB(event);
                    }
                    return;
                }
            }
        }
        else if(event.type === "valuechanged")
        {
            self.sendEvent(event.name, event.data);
        }
    }
}