UNPKG

2.19 kBJavaScriptView Raw
1var util = require('util');
2var EventEmitter = require('events').EventEmitter;
3var ObjectStream = require('zetta-streams').ObjectStream;
4var buildDeviceActions = require('./api_formats/siren/device.siren').buildActions;
5var deviceFormatter = require('./api_formats/siren/device.siren');
6
7var 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; // contains .topic, .name
15 this.init();
16};
17util.inherits(EventSocket, EventEmitter);
18
19EventSocket.prototype.send = function(topic, data) {
20 if (!Buffer.isBuffer(data) && typeof data === 'object') {
21 if (data['transitions']) {
22 // format transitions
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 // used for _peer/connect _peer/disconnect
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); // remove topic
44
45 // add callback to args list if it does not have one
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
53EventSocket.prototype.onData = function(data) {
54 var args = ['data'].concat(Array.prototype.slice.call(arguments));
55 // @todo handle remote devices publishing data on the websocket
56 this.emit.apply(this, args);
57};
58
59EventSocket.prototype.onClose = function() {
60 this.emit('close');
61};
62
63EventSocket.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};