1 | var util = require('util');
|
2 | var EventEmitter = require('events').EventEmitter;
|
3 | var ObjectStream = require('zetta-streams').ObjectStream;
|
4 | var buildDeviceActions = require('./api_formats/siren/device.siren').buildActions;
|
5 | var deviceFormatter = require('./api_formats/siren/device.siren');
|
6 |
|
7 | var EventSocket = module.exports = function(ws, query) {
|
8 | EventEmitter.call(this);
|
9 | this.ws = ws;
|
10 |
|
11 | if (!Array.isArray(query)) {
|
12 | query = [query];
|
13 | }
|
14 | this.query = query;
|
15 | this.init();
|
16 | };
|
17 | util.inherits(EventSocket, EventEmitter);
|
18 |
|
19 | EventSocket.prototype.send = function(topic, data) {
|
20 | if (!Buffer.isBuffer(data) && typeof data === 'object') {
|
21 | if (data['transitions']) {
|
22 |
|
23 | data.actions = buildDeviceActions(data.properties.id, this.ws._env, this.ws._loader, data.transitions);
|
24 | delete data.transitions;
|
25 | } else if (data['query']){
|
26 | data = deviceFormatter({ loader: this.ws._loader, env: this.ws._env, model: data.device });
|
27 | }
|
28 |
|
29 |
|
30 | if (Object.keys(data).length === 1 && typeof data.peer === 'object') {
|
31 | data = ObjectStream.format(topic, data.peer.properties());
|
32 | }
|
33 |
|
34 | try {
|
35 | data = JSON.stringify(data);
|
36 | } catch (err) {
|
37 | console.error('ws JSON.stringify ', err);
|
38 | return;
|
39 | }
|
40 | }
|
41 |
|
42 | var args = Array.prototype.slice.call(arguments);
|
43 | args.splice(0, 1);
|
44 |
|
45 |
|
46 | if (args.length < 1 && typeof args[args.length - 1] !== 'function') {
|
47 | args.push(function(err) { });
|
48 | }
|
49 |
|
50 | this.ws.send.apply(this.ws, args);
|
51 | };
|
52 |
|
53 | EventSocket.prototype.onData = function(data) {
|
54 | var args = ['data'].concat(Array.prototype.slice.call(arguments));
|
55 |
|
56 | this.emit.apply(this, args);
|
57 | };
|
58 |
|
59 | EventSocket.prototype.onClose = function() {
|
60 | this.emit('close');
|
61 | };
|
62 |
|
63 | EventSocket.prototype.init = function() {
|
64 | var self = this;
|
65 | this.ws.on('message', this.onData.bind(this));
|
66 | this.ws.on('close', this.onClose.bind(this));
|
67 | this.ws.on('error',function(err){
|
68 | console.error('ws error:', err);
|
69 | self.onClose();
|
70 | });
|
71 | };
|