Expose spark core connection ready and disconnect event to API in spark-protocol DeviceServer.js


Hi, currently I am looking into the source code of spark-protocol. and in DeviceServer.js there is core connected and disconnected event. and now I want to expose these two events outside DeviceServer.js, so I can use DeviceServer in this way.

var DeviceServer = require("spark-protocol").DeviceServer;
var server = new DeviceServer({
  coreKeysDir: settings.coreKeysDir
global.server = server;
server.on('ready', function () {
   console.log('an ready  event has happened');
server.on('disconnect', function () {
   console.log('an disconnect event has happened');

Therefore I modified the code in this way by using the eventemiter.

var DeviceServer = function (options) {

    ////////////////   my change  //////////////
    var EventEmitter = require('events').EventEmitter;
    util.inherits(this, EventEmitter);

    this.options = options;
    this.options = options || {};
    settings.coreKeysDir = this.options.coreKeysDir = this.options.coreKeysDir || settings.coreKeysDir;
    this._allCoresByID = {};
    this._attribsByID = {};
    this._allIDs = {};

and inside the start function, I made the change like this

core.on('ready', function () {
    logger.log("Core online!");
    var coreid = this.getHexCoreID();
    that._allCoresByID[coreid] = core;
    that._attribsByID[coreid] = that._attribsByID[coreid] || {
        coreID: coreid,
        name: null,
        ip: this.getRemoteIPAddress(),
        product_id: this.spark_product_id,
        firmware_version: this.product_firmware_version
    ///// my change

core.on('disconnect', function (msg) {
    logger.log("Session ended for " + core._connection_key);
    delete _cores[key];
   ///////////////////////   my change

However, it doesn’t work with errors

I’ve edited your post to properly format the code. Please check out this post, so you know how to do this yourself in the future. Thanks in advance! ~Jordy