Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @author Marten Koedam
- * @copyright 2013, Dalines Software Library
- *
- * For more information see http://sanctorium.org
- */
- var createModel = require('./models.js');
- var settings = require('./settings.js');
- var EMPYREAL_SERVER = {
- host: settings.EMPYREAL_SERVER_HOST,
- port: settings.EMPYREAL_SERVER_PORT
- };
- /**
- * Client object to connect to the Empyreal Server with the correct protocol.
- *
- * Use the send method to trigger actions on the server and add callbacks to be executed with the return value.
- * This is asynchronous so the callbacks are stored per UID which is send back and forth with the server.
- *
- * For more information see the Empyreal documentation at http://empyreal.sanctorium.org
- */
- var EmpyrealClient = function (listener) {
- this._broadcastListener = listener;
- this._callbacks = {};
- this._errbacks = {}
- this._broadcasted = {}; // List with UIDs to not fire the same broadcast message twice... eep?
- this.id = this._generateUniqueID();
- };
- EmpyrealClient.prototype = {
- /**
- * Connects to the Empyreal server and adds a listener.
- */
- connect : function (cb) {
- cb = cb ? cb : function () {};
- var net = require('net');
- this.client = net.createConnection(EMPYREAL_SERVER, function () {});
- this.client.on('data', this.processResponse.bind(this), cb);
- },
- /**
- * An object which can handle the Broadcast calls.
- */
- setBroadcastListener : function ( listener ) {
- this._broadcastListener = listener;
- },
- /**
- * Generate a unique ID so we can add the callbacks for it.
- */
- _generateUniqueID : function () {
- return 'yxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
- var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
- return v.toString(16);
- });
- },
- /**
- * Default success callback, just log.
- */
- cbSuccess : function ( answer ) {
- console.log('Default cbSuccess: ', answer);
- },
- /**
- * Default error callback, just log.
- */
- cbError : function ( answer ) {
- console.error('Default cbError: ', answer);
- },
- /**
- * Send a command to the Empyreal server.
- */
- send : function ( cmd, args, callback, errback, scope ) {
- var uid = this._generateUniqueID();
- var line = this.writeLine( cmd, args, uid);
- callback = callback ? callback : this.cbSuccess;
- errback = errback ? errback : this.cbError;
- scope = scope ? scope : this;
- this._callbacks[uid] = {
- method: callback,
- scope: scope
- };
- this._errbacks[uid] = {
- method: errback,
- scope: scope
- };
- this.client.write(line);
- },
- /**
- * JSON Serialize the command to send.
- */
- writeLine : function ( cmd, args, uid ) {
- args = args ? args : [];
- uid = uid ? uid : null;
- return JSON.stringify({command: cmd, args: args, uid: uid})+"\r\n"; // TODO: models?
- },
- /**
- * This is the hook we added on the client for the onData callback.
- */
- processResponse : function ( data ) {
- this._receive( data );
- },
- /**
- * Per received line we process the response.
- */
- _process : function ( response ) {
- var status, answer, uid;
- try {
- var parsed = this.decodeJSON( response );
- } catch ( e ) {
- console.error(e);
- throw e;
- }
- var status = parsed.status;
- var answer = parsed.answer;
- var uid = parsed.uid;
- // We usually expect a status OK.
- if( status == 'OK' ) {
- if( uid ) {
- if( typeof this._callbacks[uid] == 'undefined' ) {
- // The callback must have been removed.
- return;
- }
- var cb = this._callbacks[uid];
- cb.method.call(cb.scope, answer);
- delete this._callbacks[uid];
- delete this._errbacks[uid];
- return;
- }
- this.cbSuccess(answer);
- return
- }
- // BROADCAST Received.
- if ( status == 'BROADCAST' ) {
- if(this._broadcastListener && (typeof this._broadcasted[uid] == 'undefined')) {
- this._broadcasted[uid] = true;
- this._broadcastListener.received( answer );
- return;
- }
- return;
- }
- // Not a status we wanted.
- if( uid ) {
- if( typeof this._errbacks[uid] == 'undefined' ) {
- // The callback must have been removed.
- return;
- }
- var cb = this._errbacks[uid];
- cb.method.call(cb.scope, answer);
- delete this._callbacks[uid];
- delete this._errbacks[uid];
- return;
- }
- throw Error(this+': RECEIVED status: '+status+'; args: '+answer+';');
- },
- /**
- * Receive a line from the server, delimiter is a new line.
- */
- _receive : function ( data ) {
- var response = /^(.*?)$/mg.exec(data.toString());
- for(var i = 0; i < response.length; i++) {
- this._process(response[i]);
- }
- // Test to see if this prevents us from receiving things twice.
- delete data;
- },
- /**
- * Decode the JSON string with the Empyreal model wrapper.
- */
- decodeJSON : function ( response ) {
- return JSON.parse(response, function (k, v) {
- return createModel(v);
- });
- },
- /**
- * Close the connection
- */
- close : function () {
- this.client.end();
- },
- toString : function () {
- return 'EmpyrealClient::'+this.id;
- }
- };
- var createClient = function () {
- return new EmpyrealClient();
- };
- module.exports.client = createClient;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement