Example #1
0
http.createServer(function (req, res) {
    var bits = url_mod.parse(req.url, true);
    if (!bits.query || !bits.query.url) {
        res.sendHeader(500, {'Content-Type': 'text/plain'});
        res.write('Error - no URL specified');
        res.close();
        return;
    }
    var url = bits.query.url;
    sys.puts('Request for ' + url);
    function complete(status, content_type, body) {
        res.sendHeader(status, {'Content-Type': content_type||'text/plain'});
        res.write(body);
        res.close();
    }
    if (in_flight.listeners(url).length > 0) {
        in_flight.addListener(url, complete);
        sys.puts('... already in flight, adding to queue')
    } else {
        in_flight.addListener(url, complete);
        sys.puts('... kicking off backend HTTP fetch')
        function done(body, response) {
            var status = response.statusCode;
            var content_type = response['content-type'];
            sys.puts(
                'Fetched ' + url + ', alerting ' + in_flight.listeners(url).length + 
                ' waiting clients'
            );
            in_flight.emit(url, status, content_type, body);
            in_flight.listeners(url).length = 0;
        }
        rest.get(url).addListener('complete',done).addListener('error',done);
    }
}).listen(port);
Example #2
0
var registerExperiment = function (filename) {
  var experiment = require('./experiments/' + filename);

  if (experiment.onDoc)
    docEvents.addListener('doc', experiment.onDoc);

  if (experiment.onEndOfDocs)
    docEvents.addListener('end', experiment.onEndOfDocs);
};
Example #3
0
    'pagination': function(test) {
        var parsed, page;
        var q = "select title[0], itemId[0] \
            from ebay.finding.items where keywords= 'cooper' and FreeShippingOnly = 'true' and MinPrice = '100' \
            limit 10 offset ";

        var listener = function(payload) {
            parsed = new MutableURI(payload.uri);
        }
        var emitter = new EventEmitter();
        emitter.addListener(Engine.Events.STATEMENT_REQUEST, listener);

        engine.exec({
            emitter: emitter,
            script: q + "110",
            cb: function(err) {
                if(err) {
                    console.log(err.stack || err);
                    test.ok(false, 'Failed.');
                    test.done();
                }
                else {
                    // Check the paginationInput.pageNumber parameter.
                    page = parsed.getParam('paginationInput.pageNumber')
                    test.equals(page, 11);
                    test.done();
                }
            }
        });
    },
Example #4
0
            cb: function(err, list) {
                var count = 0;
                var listener = function() {
                    count++;
                }
                var emitter = new EventEmitter();
                emitter.addListener(Engine.Events.STATEMENT_REQUEST, listener);

                // We need to test that two HTTP requests are made for the following statement below.
                var q = "create table myitemdetails \
                         on select get from 'http://open.api.ebay.com/shopping?callname=GetMultipleItems&responseencoding={format}&appid={^apikey}&version=715&IncludeSelector={includeSelector}&ItemID={itemId}'\
                         with aliases json = 'JSON', xml = 'XML'\
                         using defaults format = 'JSON',\
                         apikey =  '{config.ebay.apikey}'\
                         resultset 'Item';\
                        select ViewItemURLForNaturalSearch from myitemdetails where itemId in ('" + list.body[0] + "', '" + list.body[1] + "') and includeSelector = 'ShippingCosts'";
                engine.exec({
                    script : q,
                    emitter: emitter,
                    cb: function(err, list) {
                        if(err) {
                            test.fail('got error: ' + err.stack || err);
                            test.done();
                        }
                        else {
                            test.equals(list.headers['content-type'], 'application/json', 'HTML expected');
                            test.ok(_.isArray(list.body), 'expected an array');
                            test.equals(2, list.body.length, 'expected 2 items');
                            test.equals(2, count, 'Expected two HTTP requests');
                            test.done();
                        }
                    }
                })
            }
Example #5
0
            cb: function(err, list) {
                var count = 0;
                var listener = function() {
                    count++;
                }
                var emitter = new EventEmitter();
                emitter.addListener(Engine.Events.STATEMENT_REQUEST, listener);

                // We need to test that two HTTP requests are made for the following statement below.
                var q = "select ViewItemURLForNaturalSearch from ebay.shopping.item where itemId in ('" + list.body[0] + "', '" + list.body[1] + "') and includeSelector = 'ShippingCosts'";
                engine.exec({
                    script : q,
                    emitter: emitter,
                    cb: function(err, list) {
                        if(err) {
                            test.fail('got error: ' + err.stack || err);
                            test.done();
                        }
                        else {
                            test.equals(list.headers['content-type'], 'application/json', 'HTML expected');
                            test.ok(_.isArray(list.body), 'expected an array');
                            test.equals(2, list.body.length, 'expected 2 items');
                            test.equals(1, count, 'Expected two HTTP requests');
                            test.done();
                        }
                    }
                })
            }
Example #6
0
function autoUpdate(connection,io) {
    var n = 0;
    var autoUpdate = new events.EventEmitter();
    
    //io.sockets.on('connection', function (socket) {
        
        autoUpdate.addListener('sec15', function() {
     
            setTimeout(function(){
                console.log("Запрос " + n);
                n += 1;
                autoUpdate.emit('sec15');
            }, 5000);
     
        });
        autoUpdate.emit('sec15');
     /*
        console.log('connection');
        autoUpdate.emit('sec15');
        
        socket.on('disconnect', function () {
            n = 0;
            autoUpdate.removeAllListeners('sec15')
            console.log("disconnect!");
        });
    });
    */
}
 _.forEach(eventHandlers, (handlerOrArray, eventName) => {
     if (_.isArray(handlerOrArray)) {
         _.forEach(handlerOrArray, handler => this.eventEmitter.addListener(eventName, handler));
     } else {
         this.eventEmitter.addListener(eventName, handlerOrArray);
     }
 });
Example #8
0
function testEventEmitter() {
  var emitter = new EventEmitter(), em;
  var numTimesEventHandlerWasCalled = 0;
  var myEventHandler = function() {
    numTimesEventHandlerWasCalled += 1;
  };
  em = emitter.addListener('myEvent', myEventHandler);
  assert.equal(em, emitter, 'emitter.addListener should return `this`');
  emitter.emit('myEvent');
  assert.equal(1, numTimesEventHandlerWasCalled, 'Handler should be called once');
  // Check that removeListener still works:
  emitter.removeListener('myEvent', myEventHandler);
  emitter.emit('myEvent');
  assert.equal(1, numTimesEventHandlerWasCalled, 'Handler should not be called after removing');

  // Check that .once works
  numTimesEventHandlerWasCalled = 0;
  em = emitter.once('myEvent', myEventHandler);
  assert.equal(em, emitter, 'emitter.once should return `this`');
  emitter.emit('myEvent');

  assert.equal(1, numTimesEventHandlerWasCalled, 'Handler should be called once');
  assert.equal(0, emitter.listeners('myEvent').length, 'Listener should not exist anymore');

  emitter.emit('myEvent');
  assert.equal(1, numTimesEventHandlerWasCalled, 'Handler should not be called after removing');

  // Check that removeListener works on a .once handler before it is called
  numTimesEventHandlerWasCalled = 0;
  emitter.once('myEvent', myEventHandler);
  emitter.removeListener('myEvent', myEventHandler);
  emitter.emit('myEvent');
  assert.equal(0, numTimesEventHandlerWasCalled, 'Handler should not be called');
}
	wss.on('connection', function connection(ws) {
		console.log('WebSocket start!');
		var uuid = UUID;

		var sendBullet = function(bullet){
			var sendJSON = [bullet];
			ws.send(JSON.stringify(sendJSON));//加入判断
		};
		var heartTimer = setInterval(function(){
			ws.send('');//发送心跳包防止WebSocket断开
		},1000*60*3);

		emitter.addListener('bullet come',sendBullet);//加入对字幕请求的监听器

		getTime(uuid,function(time){
			getBullet(time,function(results){
				if (results){
					ws.send(JSON.stringify(results));
				}
			});
		});

		ws.on('message', function incoming(message) {
			//保留,比如可以发送过来你的uuid来识别用户
		});

		ws.on('close', function close(){
			emitter.removeListener('bullet come',sendBullet);//取消监听器
			clearInterval(heartTimer);//取消心跳包
			saveTime(uuid);
		})
	});
Example #10
0
http.createServer(function(request, response) {
    var uri = url.parse(request.url).pathname;
    if(uri === "/stream") {
    
    	var listener = tweet_emitter.addListener("tweets", function(tweets) {
    		response.writeHead(200, { "Content-Type" : "text/plain" });
    		response.write(JSON.stringify(tweets));
    		response.end();
    		
    		clearTimeout(timeout);
    	});
    	
    	var timeout = setTimeout(function() {
    		response.writeHead(200, { "Content-Type" : "text/plain" });
    		response.write(JSON.stringify([]));
    		response.close();
    		
    		tweet_emitter.removeListener(listener);
    	}, 10000);
    	
    }
    else {
    	load_static_file(uri, response);
    }
}).listen(8080);
Example #11
0
 keys.forEach(function(k){
     var task = (tasks[k] instanceof Function)? [tasks[k]]: tasks[k];
     var taskCallback = function(err){
         if(err){
             callback(err);
             // stop subsequent errors hitting the callback multiple times
             callback = function(){};
         }
         else {
             completed.push(k);
             emitter.emit('taskComplete');
         }
     };
     var requires = task.slice(0, Math.abs(task.length-1)) || [];
     var ready = function(){
         return requires.reduce(function(a,x){
             return (a && completed.indexOf(x) != -1);
         }, true);
     };
     if(ready()) task[task.length-1](taskCallback);
     else {
         var listener = function(){
             if(ready()){
                 emitter.removeListener('taskComplete', listener);
                 task[task.length-1](taskCallback);
             }
         };
         emitter.addListener('taskComplete', listener);
     }
 });
Example #12
0
function eventStream(request, response) {
  var lastEventId = "";
  var parsedURL = url.parse(request.url, true);
  var test = Number(parsedURL.query.test);
  var cookies = {};

  (request.headers.cookie || "").split(";").forEach(function (cookie) {
    cookie = cookie.split("=");
    cookies[decodeURIComponent(cookie[0].trim())] = decodeURIComponent((cookie[1] || "").trim());
  });

  function sendMessages() {
    lastEventId = Math.max(lastEventId, firstId);
    while (lastEventId - firstId < history.length) {
      response.write("id: " + (lastEventId + 1) + "\n" + "data: " + (history[lastEventId - firstId]).replace(/[\r\n\x00]/g, "\ndata: ") + "\n\n");
      lastEventId += 1;
    }
    response.write(":\n");
  }

  response.on("close", function () {
    emitter.removeListener("message", sendMessages);
    response.end();
  });

  response.socket.setTimeout(0); // see http://contourline.wordpress.com/2011/03/30/preventing-server-timeout-in-node-js/

  var headers = {
    "Content-Type": "text/event-stream",
    "Cache-Control": "no-cache",
    "Access-Control-Allow-Origin": "*"
  };
  if (test === 9) {
    headers["Access-Control-Allow-Credentials"] = "true";
  }
  if (test === 16) {
    headers["Cache-Control"] = "max-age=3600";
    headers["Expires"] = new Date(Date.now() + 3600000).toUTCString();
    response.writeHead(200, headers);
    response.write("retry:1000\ndata:" + Math.random() + "\n\n");
    response.end();
    return;
  }

  response.writeHead(200, headers);
  lastEventId = Number(request.headers["last-event-id"]) || Number(parsedURL.query.lastEventId) || 0;

  response.write(":" + Array(2049).join(" ") + "\n"); // 2kB padding for IE
  response.write("retry: 1000\n");
  response.write("retryLimit: 60000\n");
  response.write("heartbeatTimeout: " + heartbeatTimeout + "\n");//!

  if (!isNaN(test)) {
    onTest(response, lastEventId, test, cookies);
  } else {
    emitter.addListener("message", sendMessages);
    emitter.setMaxListeners(0);
    sendMessages();
  }
}
Example #13
0
function createMultiPump (readables, writables) {
  var mpump = new events.EventEmitter();
  
  for (var i;i<readables.length;i+=1) {
    readables[i].pumps = [];
    if (i !== 0) {
      var readable = readables[i];
      readable.writers = 0;
      readable.pause();
      readable.buffers = []
      readable.bufferListener = function (chunk) { readable.buffers.push(chunk); }
    }
  }
  
  var startPump = function (writable) {
    if (writable.readableIndex >= readables.length) {
      mpump.emit("end", writable);
      return;
    }
    var readable = readables[writable.readableIndex]
    readable.resume();
    if (readable.writers) {
      readable.writers += 1;
      readable.buffers.forEach(function(chunk){writable.write(chunk)});
      if (readable.writers == writables.length) readable.removeListener("data", readable.bufferListener);
    }
    var pump = createPump(readable, writable);
    readable.pumps.push(pump);
    pump.removeDefaults();
    pump.paused = false;
    pump.addListener('pause', function () {
      pump.paused = true;
      var pcount = 0;
      readable.pumps.forEach(function(p) {if (p.paused) pcount += 1;});
      if (pcount == readable.pumps.length) readable.pause();
    })
    pump.addListener('resume', function () {
      pump.paused = false;
      pump.resumeListener()
    });
    pump.addListener('end', function () {
      writable.readableIndex += 1;
      readables.pumps.splice(readables.pumps.indexOf(pump), 1);
      startPump(writable);
    })
    mpump.emit("pump", pump);
  }
  
  writeables.forEach(function (writable) {
    var self = this;
    writable.readableIndex = 0;
    startPump(writable);
  })
  
  mpump.endListener = function (writable) { writable.end(); };
  mpump.addListener("end", mpump.endListener);
  
  return mpump;
}
 initialize: function() {
   var _this = this;
   this.listenTo(this.model, 'sync', this.render);
   ee.addListener('new-TAP_'+this.model.get('tapId'), function(){
     _this.model.fetch();
   });
   this.model.fetch();
 },
Example #15
0
var Ajax = (function() {
    var self = new events.EventEmitter(),
        privateSendData = function(data, response) {
            response.write(JSON.stringify(data));
            response.end();
        },
        privateSendOk = function(response) {
            response.write(querystring.stringify({
                response: 'ok'
            }));
            response.end();
        }

    self.addListener('sendOk', privateSendOk);
    self.addListener('sendData', privateSendData);

    return self;
}());
  observeLanguageTextEditors(
      fn: (textEditor: TextEditor) => void,
      cleanupFn: (textEditor: TextEditor) => void): Disposable {
    // The event was already handled before `fn` was added to the emitter, so
    // we need to call it on all the existing editors.
    atom.workspace.getTextEditors()
        .filter(textEditor => this._grammarScopes.has(textEditor.getGrammar().scopeName))
        // We wrap `fn` instead of passing it directly to `.forEach` so it only
        // gets called with one arg (i.e. it matches the Flow annotation).
        .forEach(textEditor => fn(textEditor));

    this._emitter.addListener(START_OBSERVING_TEXT_EDITOR_EVENT, fn);
    this._emitter.addListener(STOP_OBSERVING_TEXT_EDITOR_EVENT, cleanupFn);
    return new Disposable(() => {
      this._emitter.removeListener(START_OBSERVING_TEXT_EDITOR_EVENT, fn);
      this._emitter.removeListener(STOP_OBSERVING_TEXT_EDITOR_EVENT, cleanupFn);
    });
  }
Example #17
0
app.get('/velibs.json', function(req, res){
	var url_parts = url.parse(req.url, true);
	var query = url_parts.query;
	console.log(query['contract']);
	res.end(JSON.stringify(velibs));
	var listener = velib_emitter.addListener("velibs", function(velibs) {  
			call_number +=1 ;
      res.end(JSON.stringify(velibs));  
 });
});
Example #18
0
http.createServer(function (request, response) {
    var uri = url.parse(request.url).pathname;
    var raw = url.parse(request.url, true).query;

    if (uri === "/servers") {
        parseCsvFile('C:/SVN/monitoring_rest_queues/serverconfig.csv');
        var listener = json_emitter.addListener("servers", function (servers) {
            response.writeHead(200, { "Content-Type": "text/json" });
            response.write(servers);
            response.end();

            clearTimeout(timeout);
        });

        var timeout = setTimeout(function () {
            response.writeHead(200, { "Content-Type": "text/plain" });
            response.write(JSON.stringify([]));
            response.end();

            json_emitter.removeListener(listener);
        }, 10000);
    }
    if (uri === "/status") {
        var data = raw ? raw : {};
        data = raw.data ? JSON.parse(raw.data) : data;
        console.log(data.server);
        var options = {
            host: data.server,
            port: '18181',
            path: '/queue'
        };
        var req = http.get(options, function (res2) {
            //console.log("!!!!" + options.host + " " + options.port + " " + options.path + "!!!!");
            var serverqueuesjson = ''
            res2.on('data', function (chunk) {
                serverqueuesjson += chunk
            });

            res2.on('end', function () {
                //console.log("***" + serverqueuesjson);
                var data = JSON.parse(serverqueuesjson);
                response.writeHead(200, { "Content-Type": "text/json" });
                response.write(JSON.stringify(data));
                //console.log("!!!" + serverqueuesjson);
                response.end();
                //res2.end();
            });
        });

    }
    else {
        load_static_file(request, response);
    }

}).listen(8125);
Example #19
0
(function() {
    app = new EventEmitter();
    
    /* route */
    app.addListener('login', function() {
        
    });
    

    
    
})();
Example #20
0
	wss.on('connection', function connection(ws) {
		console.log('WebSocket start!');
		var sendBullet = function(bullet){
			console.log(bullet);
			ws.send(JSON.stringify(bullet));
		};

		var heartTimer = setInterval(function(){
			var empty = {
			  type: "text",
			  color : "",
			  fontsize : "",
			  content : "",
			  duration : "",
			  nickname : ""
			};
			ws.send(JSON.stringify(empty));//发送心跳包防止WebSocket断开
		},1000*60*5);

		emitter.addListener('bullet come',sendBullet);//加入对字幕请求的监听器

		getTime(uuid,function(time){
			getBullet(time,function(results){
				if (results){
					for (var i = 0; i < results.length; i++) {
						var bullet = checkBullet(results[i]);
						ws.send(JSON.stringify(bullet));
					};
				}
			});
		});

		ws.on('message', function incoming(message) {
			try{
				message = JSON.parse(message);
				var result = checkBullet(message);
				if (result){
					emitter.emit('bullet come',result);
					saveBullet(result);
				}
			}
			catch (e){
				console.log('Not legal bullet');
			}
		});

		ws.on('close', function close(){
			emitter.removeListener('bullet come',sendBullet);//取消监听器
			clearInterval(heartTimer);//取消心跳包
			saveTime(uuid);
		});
	});
http.createServer(function(_request, _response) {
  var _uri = url.parse(_request.url).pathname;
  if (_uri === "/nomospace") {
    tweetEmitter.addListener("tweets", function(tweets) {
      _response.writeHead(200, {"Content-Type": "text/plain"});
      _response.write(JSON.stringify(tweets));
      _response.end();
    });
  }
  else {
    _loadStatisFile(_uri, _response);
  }
}).listen(8080);
Example #22
0
(function () {
    var pulse_num = 0;
    var heartbeat = new events.EventEmitter();
    heartbeat.addListener('beat', function () {
        pulse_num += 1;
        setTimeout(function () {
            console.log(pulse_num);
            time = Lighter.work();
            heartbeat.emit('beat');
        }, time);
    });
    heartbeat.emit('beat');
})();
Example #23
0
 DNode.connect(6061, function (remote2) {
     moo.addListener('hi', function (x) {
         remote1.timesTen(x, function (res) {
             sys.puts(res);
             remote2.timesTwenty(res, function (res2) {
                 sys.puts(res2);
             });
         });
     });
     remote2.timesTwenty(5, function (n) {
         sys.puts(n); // 100
         remote1.timesTen(0.1, function (n) {
             sys.puts(n); // 1
         });
     });
 });
 completion = new Promise(function (resolve, reject) {
   function completionResolver (err, completed) {
     try {
       _.isFunction(listener) && listener(err, completed);
     } catch (e) {
       console.error("User supplied listener exception", e);
     }
     if (err) {
       err.notCompleted = notifier.filesNotDone;
       err.completed = completed;
       reject(err);
     } else {
       resolve(completed);
     }
   }
   emitter.addListener("complete", completionResolver);
 });
Example #25
0
http.createServer(function(request, response) {
    // response.header("Access-Control-Allow-Origin", "*");
    // response.header("Access-Control-Allow-Headers", "X-Requested-With");
    // next();
    var uri = url.parse(request.url).pathname;
    if (uri === "/stream") {
        console.log("petición a stream ...");
        var listener = tweet_emitter.addListener("tweets", function(tweets) {
        response.writeHead(200, {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS',
            'Access-Control-Allow-Headers': 'Content-Type',
            'content-type': 'text/plain'
        });
            console.log(JSON.stringify(tweets));
            response.write(JSON.stringify(tweets));
            response.end();
            clearTimeout(timeout);
        });

        var timeout = setTimeout(function() {
            response.writeHead(200, {
                "Content-Type": "text/plain"
            });
            response.write(JSON.stringify([]));
            response.end();

            tweet_emitter.removeListener(listener, function() {
                console.log('removing listening to tweets ...');
            });
        }, 10000);

    } else if (uri === "/otro") {
        console.log("petición a otro ...");
        response.writeHead(200, {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS',
            'Access-Control-Allow-Headers': 'Content-Type',
            'content-type': 'text/plain'
        });
        response.write("otra cosa");
        response.end();
    } else {
        load_static_file(uri, response);
    }
}).listen(port);
Example #26
0
async function spawn(name, args, option) {
    const { process: proc, canceller, } = spawnCancelableChild(name, args, option);

    const killSelf = function() {
        canceller();
    };
    master.addListener(EVENT_GRACEFUL_KILL, killSelf);

    const onExit = function () {
        master.removeListener(EVENT_GRACEFUL_KILL, killSelf);
        master.emit(EVENT_GRACEFUL_KILL);
    };

    const status = await proc;
    onExit();
    return assertReturnCode(status);
}
Example #27
0
exports.auto = function(tasks, callback){
    callback = callback || function(){};
    var keys = Object.keys(tasks);
    if(!keys.length) return callback(null);

    var completed = [];
    var emitter = new events.EventEmitter();
    emitter.addListener('taskComplete', function(){
        if(completed.length == keys.length){
            callback(null);
        }
    });

    keys.forEach(function(k){
        var task = (tasks[k] instanceof Function)? [tasks[k]]: tasks[k];
        var taskCallback = function(err){
            if(err){
                callback(err);
                // stop subsequent errors hitting the callback multiple times
                callback = function(){};
            }
            else {
                completed.push(k);
                emitter.emit('taskComplete');
            }
        };
        var requires = task.slice(0, Math.abs(task.length-1)) || [];
        var ready = function(){
            return requires.reduce(function(a,x){
                return (a && completed.indexOf(x) != -1);
            }, true);
        };
        if(ready()) task[task.length-1](taskCallback);
        else {
            var listener = function(){
                if(ready()){
                    emitter.removeListener('taskComplete', listener);
                    task[task.length-1](taskCallback);
                }
            };
            emitter.addListener('taskComplete', listener);
        }
    });
};
Example #28
0
    function(callback) {
  
  var ret = new events.EventEmitter();
  ret.writeable = true;
  var buffers = [];
  ret.write = function(buffer, encoding) {
    if (typeof buffer === 'string' || (encoding && encoding !== 'binary')) {
      throw new Error('Strings or non-binary encoding are not supported here - use buffers');
    }
    buffers.push(buffer);
    return true;
  };
  
  var ended = false;
  ret.end = function(buffer) {
    if (ended) {
      return; // make sure callback is called only once
    }
    ended = true;
    if (buffer) {
      ret.write(buffer);
    }
    var n = buffers.length;
    var size = 0;
    for (var i = 0; i < n; ++i) {
      size += buffers[i].length;
    }
    var buf = new Buffer(size);
    var pos = 0;
    for (i = 0; i < n; ++i) {
      buffers[i].copy(buf, pos);
      pos += buffers[i].length;
    }
    buffers = null; // release unneeded data
    callback(null, buf);
    return true;
  };
  ret.destroy = ret.destroySoon = function() { ret.writeable = false; };
  ret.addListener('pipe', function(stream) {
    stream.on('data', ret.write);
    stream.on('end', ret.end);
  });
  return ret;
};
Example #29
0
 function PxX(pipe, addr, opts) {           // base for PTX/PRX
     stream.Duplex.call(this,{highWaterMark:64});
     this.opts = opts;
     this._pipe = pipe;
     this._addr = addr;
     this._size = opts.size;
     this._wantsRead = false;
     this._sendOpts = {};
     
     var s = {},
         n = pipe;           // TODO: what if ack'ed TX already in progress and n=0?
     if (addr.length > 1) s['AW'] = addr.length - 2;
     if (opts._primRX) {
         s['PRIM_RX'] = true;
         if (pipe === 0) rxP0 = this;
         if (opts.autoAck) nrf._prevSender = null;         // make sure TX doesn't skip setup
     }
     if (opts._enableRX) {
         s['RX_ADDR_P'+n] = addr;
         s['ERX_P'+n] = true;
     } else {
         s['ERX_P'+n] = false;
     }
     if (opts.size === 'auto') {
         s['ENAA_P'+n] = true;   // must be set for DPL (…not sure why)
         s['DPL_P'+n] = true;
     } else {
         s['RX_PW_P'+n] = this._size;
         s['ENAA_P'+n] = opts.autoAck;
         s['DPL_P'+n] = false;
     }
     nrf.setStates(s, function (e) {
         if (opts._primRX) nrf.setCE(true,'stby2a');
         if (e) this.emit('error', e);
         else this.emit('ready');        // TODO: eliminate need to wait for this (setup on first _rx/_tx?)
     }.bind(this));
     
     var irqHandler = this._rx.bind(this);
     nrf.addListener('interrupt', irqHandler);
     this.once('close', function () {
         nrf.removeListener('interrupt', irqHandler);
     });
 }
Example #30
0
 app.get('/videoStream',function(req,response){   
     response.writeHead(200,{
         'Content-Type': 'multipart/x-mixed-replace;boundary="' + boundary + '"',
         'Connection': 'keep-alive',
         'Expires': 'Fri, 01 Jan 1990 00:00:00 GMT',
         'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate',
         'Pragma': 'no-cache'
     });
     response.write('--'+boundary+'\n');
     
     events.addListener('imagen_recibida',function(){
         fs.readFile(__dirname + '/image.jpeg',function(err,data){
              if(err) return send404(response);
              response.write('Content-Type: image/jpeg\n Content-Length: '+data.length+'\n\n');
              response.write(data);
            	response.write('\n--'+boundary+'\n');
            });
     });
 });