<commit_before>/**********************************************************************
 node-opmlparser - OPML parser for node.
 http://github.com/danmactough/node-opmlparser
 Copyright (c) 2011 Dan MacTough
  http://yabfog.com

**********************************************************************/
/*jshint sub:true, laxcomma:true */
/**
 * Module dependencies.
 */
var sax = require('sax')
  , addressparser = require('addressparser')
  , indexOfObject = require('array-indexofobject')
  , resanitize = require('resanitize')
  , URL = require('url')
  , util = require('util')
  , TransformStream = require('stream').Transform
  , utils = require('./utils')
  ;

if (TransformStream === undefined) {
  TransformStream = require('readable-stream').Transform;
}

/**
 * OpmlParser constructor. Most apps will only use one instance.
 *
 * @api public
 */
function OpmlParser (options) {
  if (!(this instanceof OpmlParser)) return new OpmlParser(options);
  TransformStream.call(this);
  this._readableState.objectMode = true;
  this._readableState.highWaterMark = 16; // max. # of output nodes buffered

  this.init();
  this.parseOpts(options);
  // See https://github.com/isaacs/sax-js for more info
  this.stream = sax.createStream(this.options.strict /* strict mode - no by default */, {lowercase: true, xmlns: false });
  this.stream.on('error', this.handleSaxError.bind(this));
  this.stream.on('processinginstruction', this.handleProcessingInstruction.bind(this));
  this.stream.on('opentag', this.handleOpenTag.bind(this));
  this.stream.on('closetag',this.handleCloseTag.bind(this));
  this.stream.on('text', this.handleText.bind(this));
  this.stream.on('cdata', this.handleText.bind(this));
  this.stream.on('end', this.handleEnd.bind(this));
}
util.inherits(OpmlParser, TransformStream);

/*
 * Initializes the SAX stream
 *
 * Initializes the class-variables
 */
OpmlParser.prototype.init = function (){
  this.meta = {
    '#ns': []
  , '@': []
  , '#xml': {}
  };
  this._emitted_meta = false;
  this.stack = [];
  this.xmlbase = [];
  this.errors = [];
};

/*
 * Parse options
 */
OpmlParser.prototype.parseOpts = function (options) {
  this.options = options || {};
  if (!('strict' in this.options)) this.options.strict = false;
  if (!('normalize' in this.options)) this.options.normalize = true;
  if (!('addmeta' in this.options)) this.options.addmeta = true;
  if (!('resume_saxerror' in this.options)) this.options.resume_saxerror = true;
  if ('MAX_BUFFER_LENGTH' in this.options) {
    sax.MAX_BUFFER_LENGTH = this.options.MAX_BUFFER_LENGTH; // set to Infinity to have unlimited buffers
  } else {
    sax.MAX_BUFFER_LENGTH = 16 * 1024 * 1024; // 16M versus the 64K default
  }
  if (this.options.opmlurl) this.xmlbase.unshift({ '#name': 'xml', '#': this.options.opmlurl});
};

OpmlParser.prototype.handleEnd = function () {
  // We made it to the end without throwing, but let's make sure we were actually
  // parsing a feed
  if (this.meta && !this.meta['#type']) {
    var e = new Error('Not an outline');
    return this.handleError(e);
  }
  this.push(null);
};

OpmlParser.prototype.handleSaxError = function (e) {
  this.emit('error', e);
  if (this.options.resume_saxerror) {
    this.resumeSaxError();
  }
};

OpmlParser.prototype.resumeSaxError = function () {
  if (this.stream._parser) {
    this.stream._parser.error = null;
    this.stream._parser.resume();
  }
};

OpmlParser.prototype.handleError = function (e) {
  this.emit('error', e);
};

OpmlParser.prototype.handleProcessingInstruction = function (node) {
  if (node.name !== 'xml') return;
  this.meta['#xml'] = node.body.trim().split(' ').reduce(function (map, attr) {
    var parts = attr.split('=');
    map[parts[0]] = parts[1] && parts[1].length > 2 && parts[1].match(/^.(.*?).$/)[1];
    return map;
  }, {});
};

OpmlParser.prototype.handleOpenTag = function (node) {
  var n = {};
  n['#name'] = node.name; // Avoid namespace collissions later...
  n['#prefix'] = node.prefix; // The current ns prefix
  n['#local'] = node.local; // The current element name, sans prefix
  n['#uri'] = node.uri; // The current ns uri
  n['@'] = {};
  n['#'] = '';

  if (Object.keys(node.attributes).length) {
    n['@'] = this.handleAttributes(node.attributes, n['#name']);
  }

  if (this.stack.length === 0 &&
     (n['#name'] === 'opml' || (n['#local'] === 'opml' && utils.nslookup([n['#uri']], 'opml')))) {
    this.meta['#ns'] = [];
    this.meta['@'] = [];
    Object.keys(n['@']).forEach(function(name) {
      var o = {};
      o[name] = n['@'][name];
      if (name.indexOf('xmlns') === 0) {
        this.meta['#ns'].push(o);
      } else if (name != 'version') {
        this.meta['@'].push(o);
      }
    }, this);
    this.meta['#version'] = n['@']['version'] || '1.1';
  }
  this.stack.unshift(n);
};

OpmlParser.prototype.handleCloseTag = function (el) {
  var node = { '#name' : el
             , '#prefix' : ''
             , '#local' : '' }
    , stdEl
    , item
    , baseurl
    ;
  var n = this.stack.shift();
  el = el.split(':');

  if (el.length > 1 && el[0] === n['#prefix']) {
    if (utils.nslookup(n['#uri'], 'opml')) {
      node['#prefix'] = el[0];
      node['#local'] = el.slice(1).join(':');
      node['#type'] = 'opml';
    } else {
      node['#prefix'] = utils.nsprefix(n['#uri']) || n['#prefix'];
      node['#local'] = el.slice(1).join(':');
    }
  } else {
    node['#local'] = node['#name'];
    node['#type'] = utils.nsprefix(n['#uri']) || n['#prefix'];
  }
  delete n['#name'];
  delete n['#local'];
  delete n['#prefix'];
  delete n['#uri'];

  if (this.xmlbase && this.xmlbase.length) {
    baseurl = this.xmlbase[0]['#'];
  }

  if (this.xmlbase.length && (el == this.xmlbase[0]['#name'])) {
    void this.xmlbase.shift();
  }

  if ('#' in n) {
    if (n['#'].match(/^\s*$/)) {
      // Delete text nodes with nothing by whitespace
      delete n['#'];
    } else {
      n['#'] = n['#'].trim();
      if (Object.keys(n).length === 1 && node['#name'] != 'outline') {
        n = n['#'];
      }
    }
  }

  if (node['#name'] === 'outline') { // We have an outline node
    if (!this.meta.title) { // We haven't yet parsed all the metadata
      utils.merge(this.meta, this.handleMeta(this.stack[1].head), true);
      if (!this._emitted_meta) {
        this.emit('meta', this.meta);
        this._emitted_meta = true;
      }
    }
    if (!baseurl && this.xmlbase && this.xmlbase.length) { // handleMeta was able to infer a baseurl without xml:base or options.feedurl
      n = utils.reresolve(n, this.xmlbase[0]['#']);
    }
    // These three lines reassign attributes to properties of the outline object and
    // preserve child outlines
    var children = n.outline;
    n = n['@'];
    if ('category' in n) n['categories'] = this.getCategories(n);
    if (children) n.outline = children;

    if ('xmlurl' in n) { // a feed is found
      n.folder = this.getFolderName(this.stack[0]);
      if (this.options.addmeta) {
        n.meta = this.meta;
      }
      this.emit('feed', n);
    }
    this.push(n);
  } else if ((node['#name'] === 'head' ||
            (node['#local'] === 'head' && (node['#prefix'] === '' || node['#type'] === 'opml'))) &&
            !this.meta.title) { // We haven't yet parsed all the metadata
    utils.merge(this.meta, this.handleMeta(n), true);
    if (!this._emitted_meta) {
      this.emit('meta', this.meta);
      this._emitted_meta = true;
    }
  }

  if (this.stack.length > 0) {
    if (node['#prefix'] && node['#local'] && !node['#type']) {
      stdEl = node['#prefix'] + ':' + node['#local'];
    } else if (node['#name'] && node['#type'] && node['#type'] !== this.meta['#type']) {
      stdEl = node['#name'];
    } else {
      stdEl = node['#local'] || node['#name'];
    }
    if (!this.stack[0].hasOwnProperty(stdEl)) {
      this.stack[0][stdEl] = n;
    } else if (this.stack[0][stdEl] instanceof Array) {
      this.stack[0][stdEl].push(n);
    } else {
      this.stack[0][stdEl] = [this.stack[0][stdEl], n];
    }
  }
};

OpmlParser.prototype.handleText = function (text) {
  if (this.stack.length) {
    if (this.stack[0] && '#' in this.stack[0]) {
      this.stack[0]['#'] += text;
    } else {
      this.stack[0]['#'] = text;
    }
  }
};

OpmlParser.prototype.handleAttributes = function (attrs, el) {
  Object.keys(attrs).forEach(function(name){
    if (this.xmlbase.length && (name == 'href' || name == 'src')) {
      // Apply xml:base to these elements as they appear
      // rather than leaving it to the ultimate parser
      attrs[name] = utils.resolve(this.xmlbase[0]['#'], attrs[name]);
    } else if (name == 'xml:base') {
      if (this.xmlbase.length) {
        attrs[name] = utils.resolve(this.xmlbase[0]['#'], attrs[name]);
      }
      this.xmlbase.unshift({ '#name': el, '#': attrs[name]});
    }
    attrs[name] = attrs[name] ? attrs[name].trim() : '';
  }, this);
  return attrs;
};

OpmlParser.prototype.handleMeta = function (node) {
  if (!node) return {};

  var meta = {};
  // Set all the meta keys to null
  ['title', 'datecreated', 'datemodified', 'ownername', 'owneremail', 'owneremail', 'docs', 'expansionstate', 'vertscrollstate', 'windowtop', 'windowleft', 'windowbottom', 'windowright'].forEach(function (property){
    meta[property] = null;
  });

  Object.keys(node).forEach(function(name){
    var el = node[name];
    switch(name){
    case('title'):
      meta.title = utils.get(el);
      break;
    case('datecreated'):
    case('datemodified'):
      meta[name] = utils.get(el) ? new Date(el['#']) : null;
      break;
    case('ownername'):
    case('ownerid'):
    case('docs'):
    case('expansionstate'):
    case('vertscrollstate'):
    case('windowtop'):
    case('windowleft'):
    case('windowbottom'):
    case('windowright'):
      meta[name] = utils.get(el);
      break;
    }
    // Fill with all native other namespaced properties
    if (name.indexOf('#') !== 0 && ~name.indexOf(':')) meta[name] = el;
  });
  return meta;
};

OpmlParser.prototype.getFolderName = function (node) {
  if (!node) return '';

  if (utils.get(node, '#name') == 'outline' && utils.get(node, '@') && utils.get(node['@'], 'text'))
    return utils.get(node['@'], 'text');
  else
    return '';
};

OpmlParser.prototype.getCategories = function (node) {
  if (!node || !('category' in node)) return [];
  else return utils.unique(utils.get(node, 'category').split(',').map(function (cat){ return cat.trim(); }));
};

// Naive Stream API
OpmlParser.prototype._transform = function (data, encoding, done) {
  this.stream.write(data);
  done();
};

OpmlParser.prototype._flush = function (done) {
  this.stream.end();
  done();
};

exports = module.exports = OpmlParser;<commit_msg>Remove unneeded dependencies.<commit_after>/**********************************************************************
 node-opmlparser - OPML parser for node.
 http://github.com/danmactough/node-opmlparser
 Copyright (c) 2011 Dan MacTough
  http://yabfog.com

**********************************************************************/
/*jshint sub:true, laxcomma:true */
/**
 * Module dependencies.
 */
var sax = require('sax')
  , util = require('util')
  , TransformStream = require('stream').Transform
  , utils = require('./utils')
  ;

if (TransformStream === undefined) {
  TransformStream = require('readable-stream').Transform;
}

/**
 * OpmlParser constructor. Most apps will only use one instance.
 *
 * @api public
 */
function OpmlParser (options) {
  if (!(this instanceof OpmlParser)) return new OpmlParser(options);
  TransformStream.call(this);
  this._readableState.objectMode = true;
  this._readableState.highWaterMark = 16; // max. # of output nodes buffered

  this.init();
  this.parseOpts(options);
  // See https://github.com/isaacs/sax-js for more info
  this.stream = sax.createStream(this.options.strict /* strict mode - no by default */, {lowercase: true, xmlns: false });
  this.stream.on('error', this.handleSaxError.bind(this));
  this.stream.on('processinginstruction', this.handleProcessingInstruction.bind(this));
  this.stream.on('opentag', this.handleOpenTag.bind(this));
  this.stream.on('closetag',this.handleCloseTag.bind(this));
  this.stream.on('text', this.handleText.bind(this));
  this.stream.on('cdata', this.handleText.bind(this));
  this.stream.on('end', this.handleEnd.bind(this));
}
util.inherits(OpmlParser, TransformStream);

/*
 * Initializes the SAX stream
 *
 * Initializes the class-variables
 */
OpmlParser.prototype.init = function (){
  this.meta = {
    '#ns': []
  , '@': []
  , '#xml': {}
  };
  this._emitted_meta = false;
  this.stack = [];
  this.xmlbase = [];
  this.errors = [];
};

/*
 * Parse options
 */
OpmlParser.prototype.parseOpts = function (options) {
  this.options = options || {};
  if (!('strict' in this.options)) this.options.strict = false;
  if (!('normalize' in this.options)) this.options.normalize = true;
  if (!('addmeta' in this.options)) this.options.addmeta = true;
  if (!('resume_saxerror' in this.options)) this.options.resume_saxerror = true;
  if ('MAX_BUFFER_LENGTH' in this.options) {
    sax.MAX_BUFFER_LENGTH = this.options.MAX_BUFFER_LENGTH; // set to Infinity to have unlimited buffers
  } else {
    sax.MAX_BUFFER_LENGTH = 16 * 1024 * 1024; // 16M versus the 64K default
  }
  if (this.options.opmlurl) this.xmlbase.unshift({ '#name': 'xml', '#': this.options.opmlurl});
};

OpmlParser.prototype.handleEnd = function () {
  // We made it to the end without throwing, but let's make sure we were actually
  // parsing a feed
  if (this.meta && !this.meta['#type']) {
    var e = new Error('Not an outline');
    return this.handleError(e);
  }
  this.push(null);
};

OpmlParser.prototype.handleSaxError = function (e) {
  this.emit('error', e);
  if (this.options.resume_saxerror) {
    this.resumeSaxError();
  }
};

OpmlParser.prototype.resumeSaxError = function () {
  if (this.stream._parser) {
    this.stream._parser.error = null;
    this.stream._parser.resume();
  }
};

OpmlParser.prototype.handleError = function (e) {
  this.emit('error', e);
};

OpmlParser.prototype.handleProcessingInstruction = function (node) {
  if (node.name !== 'xml') return;
  this.meta['#xml'] = node.body.trim().split(' ').reduce(function (map, attr) {
    var parts = attr.split('=');
    map[parts[0]] = parts[1] && parts[1].length > 2 && parts[1].match(/^.(.*?).$/)[1];
    return map;
  }, {});
};

OpmlParser.prototype.handleOpenTag = function (node) {
  var n = {};
  n['#name'] = node.name; // Avoid namespace collissions later...
  n['#prefix'] = node.prefix; // The current ns prefix
  n['#local'] = node.local; // The current element name, sans prefix
  n['#uri'] = node.uri; // The current ns uri
  n['@'] = {};
  n['#'] = '';

  if (Object.keys(node.attributes).length) {
    n['@'] = this.handleAttributes(node.attributes, n['#name']);
  }

  if (this.stack.length === 0 &&
     (n['#name'] === 'opml' || (n['#local'] === 'opml' && utils.nslookup([n['#uri']], 'opml')))) {
    this.meta['#ns'] = [];
    this.meta['@'] = [];
    Object.keys(n['@']).forEach(function(name) {
      var o = {};
      o[name] = n['@'][name];
      if (name.indexOf('xmlns') === 0) {
        this.meta['#ns'].push(o);
      } else if (name != 'version') {
        this.meta['@'].push(o);
      }
    }, this);
    this.meta['#version'] = n['@']['version'] || '1.1';
  }
  this.stack.unshift(n);
};

OpmlParser.prototype.handleCloseTag = function (el) {
  var node = { '#name' : el
             , '#prefix' : ''
             , '#local' : '' }
    , stdEl
    , item
    , baseurl
    ;
  var n = this.stack.shift();
  el = el.split(':');

  if (el.length > 1 && el[0] === n['#prefix']) {
    if (utils.nslookup(n['#uri'], 'opml')) {
      node['#prefix'] = el[0];
      node['#local'] = el.slice(1).join(':');
      node['#type'] = 'opml';
    } else {
      node['#prefix'] = utils.nsprefix(n['#uri']) || n['#prefix'];
      node['#local'] = el.slice(1).join(':');
    }
  } else {
    node['#local'] = node['#name'];
    node['#type'] = utils.nsprefix(n['#uri']) || n['#prefix'];
  }
  delete n['#name'];
  delete n['#local'];
  delete n['#prefix'];
  delete n['#uri'];

  if (this.xmlbase && this.xmlbase.length) {
    baseurl = this.xmlbase[0]['#'];
  }

  if (this.xmlbase.length && (el == this.xmlbase[0]['#name'])) {
    void this.xmlbase.shift();
  }

  if ('#' in n) {
    if (n['#'].match(/^\s*$/)) {
      // Delete text nodes with nothing by whitespace
      delete n['#'];
    } else {
      n['#'] = n['#'].trim();
      if (Object.keys(n).length === 1 && node['#name'] != 'outline') {
        n = n['#'];
      }
    }
  }

  if (node['#name'] === 'outline') { // We have an outline node
    if (!this.meta.title) { // We haven't yet parsed all the metadata
      utils.merge(this.meta, this.handleMeta(this.stack[1].head), true);
      if (!this._emitted_meta) {
        this.emit('meta', this.meta);
        this._emitted_meta = true;
      }
    }
    if (!baseurl && this.xmlbase && this.xmlbase.length) { // handleMeta was able to infer a baseurl without xml:base or options.feedurl
      n = utils.reresolve(n, this.xmlbase[0]['#']);
    }
    // These three lines reassign attributes to properties of the outline object and
    // preserve child outlines
    var children = n.outline;
    n = n['@'];
    if ('category' in n) n['categories'] = this.getCategories(n);
    if (children) n.outline = children;

    if ('xmlurl' in n) { // a feed is found
      n.folder = this.getFolderName(this.stack[0]);
      if (this.options.addmeta) {
        n.meta = this.meta;
      }
      this.emit('feed', n);
    }
    this.push(n);
  } else if ((node['#name'] === 'head' ||
            (node['#local'] === 'head' && (node['#prefix'] === '' || node['#type'] === 'opml'))) &&
            !this.meta.title) { // We haven't yet parsed all the metadata
    utils.merge(this.meta, this.handleMeta(n), true);
    if (!this._emitted_meta) {
      this.emit('meta', this.meta);
      this._emitted_meta = true;
    }
  }

  if (this.stack.length > 0) {
    if (node['#prefix'] && node['#local'] && !node['#type']) {
      stdEl = node['#prefix'] + ':' + node['#local'];
    } else if (node['#name'] && node['#type'] && node['#type'] !== this.meta['#type']) {
      stdEl = node['#name'];
    } else {
      stdEl = node['#local'] || node['#name'];
    }
    if (!this.stack[0].hasOwnProperty(stdEl)) {
      this.stack[0][stdEl] = n;
    } else if (this.stack[0][stdEl] instanceof Array) {
      this.stack[0][stdEl].push(n);
    } else {
      this.stack[0][stdEl] = [this.stack[0][stdEl], n];
    }
  }
};

OpmlParser.prototype.handleText = function (text) {
  if (this.stack.length) {
    if (this.stack[0] && '#' in this.stack[0]) {
      this.stack[0]['#'] += text;
    } else {
      this.stack[0]['#'] = text;
    }
  }
};

OpmlParser.prototype.handleAttributes = function (attrs, el) {
  Object.keys(attrs).forEach(function(name){
    if (this.xmlbase.length && (name == 'href' || name == 'src')) {
      // Apply xml:base to these elements as they appear
      // rather than leaving it to the ultimate parser
      attrs[name] = utils.resolve(this.xmlbase[0]['#'], attrs[name]);
    } else if (name == 'xml:base') {
      if (this.xmlbase.length) {
        attrs[name] = utils.resolve(this.xmlbase[0]['#'], attrs[name]);
      }
      this.xmlbase.unshift({ '#name': el, '#': attrs[name]});
    }
    attrs[name] = attrs[name] ? attrs[name].trim() : '';
  }, this);
  return attrs;
};

OpmlParser.prototype.handleMeta = function (node) {
  if (!node) return {};

  var meta = {};
  // Set all the meta keys to null
  ['title', 'datecreated', 'datemodified', 'ownername', 'owneremail', 'owneremail', 'docs', 'expansionstate', 'vertscrollstate', 'windowtop', 'windowleft', 'windowbottom', 'windowright'].forEach(function (property){
    meta[property] = null;
  });

  Object.keys(node).forEach(function(name){
    var el = node[name];
    switch(name){
    case('title'):
      meta.title = utils.get(el);
      break;
    case('datecreated'):
    case('datemodified'):
      meta[name] = utils.get(el) ? new Date(el['#']) : null;
      break;
    case('ownername'):
    case('ownerid'):
    case('docs'):
    case('expansionstate'):
    case('vertscrollstate'):
    case('windowtop'):
    case('windowleft'):
    case('windowbottom'):
    case('windowright'):
      meta[name] = utils.get(el);
      break;
    }
    // Fill with all native other namespaced properties
    if (name.indexOf('#') !== 0 && ~name.indexOf(':')) meta[name] = el;
  });
  return meta;
};

OpmlParser.prototype.getFolderName = function (node) {
  if (!node) return '';

  if (utils.get(node, '#name') == 'outline' && utils.get(node, '@') && utils.get(node['@'], 'text'))
    return utils.get(node['@'], 'text');
  else
    return '';
};

OpmlParser.prototype.getCategories = function (node) {
  if (!node || !('category' in node)) return [];
  else return utils.unique(utils.get(node, 'category').split(',').map(function (cat){ return cat.trim(); }));
};

// Naive Stream API
OpmlParser.prototype._transform = function (data, encoding, done) {
  this.stream.write(data);
  done();
};

OpmlParser.prototype._flush = function (done) {
  this.stream.end();
  done();
};

exports = module.exports = OpmlParser;<|endoftext|>


<commit_before>/**
 *
 * sma-em adapter, Copyright CTJaeger 2017, MIT
 *
 */

/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
'use strict';

// you have to require the utils module and call adapter function
var utils = require(__dirname + '/lib/utils'); // Get common adapter utils
var dgram = require('dgram');

// you have to call the adapter function and pass a options object
// name has to be set and has to be equal to adapters folder name and main file name excluding extension
// adapter will be restarted automatically every time as the configuration changed, e.g system.adapter.sma-em.0
var adapter = utils.Adapter('sma-em');

// is called when adapter shuts down - callback has to be called under any circumstances!
adapter.on('unload', function (callback) {
    try {
        adapter.log.info('cleaned everything up...');
        callback();
    } catch (e) {
        callback();
    }
});

// is called when databases are connected and adapter received configuration.
// start here!
adapter.on('ready', main);

var connected = false;
var points = {
    'SMASerial': 	        {offset: 20,  length: 4, factor: 1, unit: ''},
    'pregard':	                {offset: 32,  length: 4, factor: 1 / 10, unit: 'Watt'},
    'pregardcounter':           {offset: 40,  length: 8, factor: 1 / 3600000, unit: 'kWh'},
    'psurplus':                 {offset: 52,  length: 4, factor: 1 / 10, unit: 'Watt'},
    'psurpluscounter':          {offset: 60,  length: 8, factor: 1 / 3600000, unit: 'kWh'}
};

function readData() {
    var client = dgram.createSocket('udp4');

    client.on('listening', function () {
        client.setBroadcast(true);
    });

    client.on('message', function (message, rinfo) {
        var ser = message.readUIntBE(points['SMASerial'].offset, points['SMASerial'].length) * points['SMASerial'].factor;
		 adapter.setObjectNotExists(ser, {
       		 type: 'channel',
     		 common: {
         	 name: ser,
        	 type: 'channel'
       		 },
        native: {}
    });

	if (!connected) {
            connected = true;
            adapter.setState('info.connection', true, true);
        }

        for (var point in points) {
            if (points.hasOwnProperty(point)) {
                var val = message.readUIntBE(points[point].offset, points[point].length) * points[point].factor;
                if (points[point].val === undefined || points[point].val !== val) {
                    points[point].val = val;
                    adapter.setObjectNotExists (adapter.namespace + '.' + ser + '.' + point, {
					type: 'state',
					role: 'value',
					common: {
						name: point,
						type: 'state',
						role: 'value'
						},
					native: {}
			});
			adapter.setState (ser + '.' + point, val,true);
                }
            }
        }
    });

    client.bind(adapter.config.BPO, function () {
        adapter.log.info('Listen via UDP on Port ' + adapter.config.BPO + ' for Multicast IP ' + adapter.config.BIP);
        adapter.log.info('Details L1 ' + adapter.config.L1 + ' Details L2 ' + adapter.config.L2 + ' Details L3 ' + adapter.config.L3);
        client.addMembership(adapter.config.BIP);
    });

    client.on('close', function () {
        adapter.log.info('UDP Socket closed ...');
        setTimeout(readData, 2000);
        if (connected) {
            connected = false;
            adapter.setState('info.connection', false, true);
        }
    });

    client.on('error', function (err) {
        adapter.log.error('UDP Socket error: ' + err);
        setTimeout(readData, 2000);
        if (connected) {
            connected = false;
            adapter.setState('info.connection', false, true);
        }
    });
}

function main() {
    if (adapter.config.ext && adapter.config.ext === true) {
    points['qregard'] =                  {offset: 72,  length: 4, factor: 1 / 10, unit: 'var'};
    points['qregardcounter'] =       	 {offset: 80,  length: 8, factor: 1 / 3600000, unit: 'varh'};
    points['qsurplus'] =                 {offset: 92,  length: 4, factor: 1 / 10, unit: 'var'};
    points['qsurpluscounter'] =          {offset: 100, length: 8, factor: 1 / 3600000, unit: 'varh'};
    points['sregard'] =                  {offset: 112, length: 4, factor: 1 / 10, unit: 'VA'};
    points['sregardcounter'] =           {offset: 120, length: 8, factor: 1 / 3600000, unit: 'VAh'};
    points['ssurplus'] =                 {offset: 132, length: 4, factor: 1 / 10, unit: 'VA'};
    points['ssurpluscounter'] =          {offset: 140, length: 8, factor: 1 / 3600000, unit: 'VAh'};
    points['cosphi'] =                   {offset: 152, length: 4, factor: 1/ 1000, unit: 'Φ'};
};

 if (adapter.config.L1 && adapter.config.L1 === true) {
    points['L1.p1regard'] =              {offset: 160, length: 4, factor: 1/ 10, unit: 'Watt'};
    points['L1.p1regardcounter'] =	 {offset: 168, length: 8, factor: 1/ 3600000, unit: 'kWh'};
    points['L1.p1surplus'] =             {offset: 180, length: 4, factor: 1/ 10, unit: 'Watt'};
    points['L1.p1surpluscounter'] =      {offset: 188, length: 8, factor: 1/ 3600000, unit: 'kWh'};
 if (adapter.config.ext && adapter.config.ext === true) {
    points['L1.q1regard'] =              {offset: 200, length: 4, factor: 1/ 10, unit: 'var'};
    points['L1.q1regardcounter'] =       {offset: 208, length: 8, factor: 1/ 3600000, unit: 'var'};
    points['L1.q1surplus'] =             {offset: 220, length: 4, factor: 1/ 10, unit: 'var'};
    points['L1.q1surpluscounter'] =      {offset: 228, length: 8, factor: 1/ 3600000, unit: 'var'};
    points['L1.s1regard'] =              {offset: 240, length: 4, factor: 1/ 10, unit: 'VA'};
    points['L1.s1regardcounter'] =       {offset: 248, length: 8, factor: 1/ 3600000, unit: 'VAh'};
    points['L1.s1surplus'] =             {offset: 260, length: 4, factor: 1/ 10, unit: 'VA'};
    points['L1.s1surpluscounter'] =      {offset: 268, length: 8, factor: 1/ 3600000, unit: 'VAh'};
    points['L1.cosphi1'] =               {offset: 296, length: 4, factor: 1/ 1000, unit: 'Φ'};
    points['L1.thd1'] =                  {offset: 280, length: 4, factor: 1/ 1000, unit: ''};
    points['L1.v1'] =			 {offset: 288, length: 4, factor: 1/ 1000, unit: 'V'};
 };
 };

 if (adapter.config.L2 && adapter.config.L2 === true) {
    points['L2.p2regard'] =          	{offset: 304, length: 4, factor: 1/ 10, unit: 'Watt'};
    points['L2.p2regardcounter'] =   	{offset: 312, length: 8, factor: 1/ 3600000, unit: 'kWh'};
    points['L2.p2surplus'] =         	{offset: 324, length: 4, factor: 1/ 10, unit: 'Watt'};
    points['L2.p2surpluscounter'] =  	{offset: 332, length: 8, factor: 1/ 3600000, unit: 'kWh'};
if (adapter.config.ext && adapter.config.ext === true) {
    points['L2.q2regard'] =          	{offset: 344, length: 4, factor: 1/ 10, unit: 'var'};
    points['L2.q2regardcounter'] =   	{offset: 352, length: 8, factor: 1/ 3600000, unit: 'varh'};
    points['L2.q2surplus'] =         	{offset: 364, length: 4, factor: 1/ 10, unit: 'var'};
    points['L2.q2surpluscounter'] =  	{offset: 372, length: 8, factor: 1/ 3600000, unit: 'varh'};
    points['L2.s2regard'] =          	{offset: 384, length: 4, factor: 1/ 10, unit: 'VA'};
    points['L2.s2regardcounter'] =   	{offset: 392, length: 8, factor: 1/ 3600000, unit: 'VAh'};
    points['L2.s2surplus'] =         	{offset: 404, length: 4, factor: 1/ 10, unit: 'VA'};
    points['L2.s2surpluscounter'] =  	{offset: 412, length: 8, factor: 1/ 3600000, unit: 'VAh'};
    points['L2.cosphi2'] =           	{offset: 440, length: 4, factor: 1/ 1000, unit: 'Φ'};
    points['L2.thd2'] =           	{offset: 424, length: 4, factor: 1/ 1000, unit: ''};
    points['L2.v2'] =           	{offset: 432, length: 4, factor: 1/ 1000, unit: 'V'};
 };
 };
 if (adapter.config.L3 && adapter.config.L3 === true) {
    points['L3.p3regard'] =              {offset: 448, length: 4, factor: 1/ 10, unit: 'Watt'};
    points['L3.p3regardcounter'] =       {offset: 456, length: 8, factor: 1/ 3600000, unit: 'kWh'};
    points['L3.p3surplus'] =             {offset: 468, length: 4, factor: 1/ 10, unit: 'Watt'};
    points['L3.p3surpluscounter'] =      {offset: 476, length: 8, factor: 1/ 3600000, unit: 'kWh'};
if (adapter.config.ext && adapter.config.ext === true) {
    points['L3.q3regard'] =              {offset: 488, length: 4, factor: 1/ 10, unit: 'var'};
    points['L3.q3regardcounter'] =       {offset: 496, length: 8, factor: 1/ 3600000, unit: 'varh'};
    points['L3.q3surplus'] =             {offset: 508, length: 4, factor: 1/ 10, unit: 'var'};
    points['L3.q3surpluscounter'] =      {offset: 516, length: 8, factor: 1/ 3600000, unit: 'varh'};
    points['L3.s3regard'] =              {offset: 528, length: 4, factor: 1/ 10, unit: 'VA'};
    points['L3.s3regardcounter'] =       {offset: 536, length: 8, factor: 1/ 3600000, unit: 'VAh'};
    points['L3.s3surplus'] =             {offset: 548, length: 4, factor: 1/ 10, unit: 'VA'};
    points['L3.s3surpluscounter'] =      {offset: 556, length: 8, factor: 1/ 3600000, unit: 'VAh'};
    points['L3.cosphi3'] =               {offset: 584, length: 4, factor: 1/ 1000, unit: 'Φ'};
    points['L3.thd3'] =           	 {offset: 568, length: 4, factor: 1/ 1000, unit: ''};
    points['L3.v3'] =           	 {offset: 576, length: 4, factor: 1/ 1000, unit: 'V'};
 };
 };
    adapter.setState('info.connection', false, true);
    readData();
}
<commit_msg>Update main.js<commit_after>/**
 *
 * sma-em adapter, Copyright CTJaeger 2017, MIT
 *
 */

/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
'use strict';

// you have to require the utils module and call adapter function
var utils = require(__dirname + '/lib/utils'); // Get common adapter utils
var dgram = require('dgram');

// you have to call the adapter function and pass a options object
// name has to be set and has to be equal to adapters folder name and main file name excluding extension
// adapter will be restarted automatically every time as the configuration changed, e.g system.adapter.sma-em.0
var adapter = utils.Adapter('sma-em');

// is called when adapter shuts down - callback has to be called under any circumstances!
adapter.on('unload', function (callback) {
    try {
        adapter.log.info('cleaned everything up...');
        callback();
    } catch (e) {
        callback();
    }
});

// is called when databases are connected and adapter received configuration.
// start here!
adapter.on('ready', main);

var connected = false;
var points = {
    'SMASerial': 	        {offset: 20,  length: 4, factor: 1, unit: ''},
    'pregard':	                {offset: 32,  length: 4, factor: 1 / 10, unit: 'Watt'},
    'pregardcounter':           {offset: 40,  length: 8, factor: 1 / 3600000, unit: 'kWh'},
    'psurplus':                 {offset: 52,  length: 4, factor: 1 / 10, unit: 'Watt'},
    'psurpluscounter':          {offset: 60,  length: 8, factor: 1 / 3600000, unit: 'kWh'}
};

function readData() {
    var client = dgram.createSocket('udp4');

    client.on('listening', function () {
        client.setBroadcast(true);
    });

    client.on('message', function (message, rinfo) {
        var ser = message.readUIntBE(points['SMASerial'].offset, points['SMASerial'].length) * points['SMASerial'].factor;
		 adapter.setObjectNotExists(ser, {
       		 type: 'channel',
     		 common: {
         	 name: ser,
        	 type: 'channel'
       		 },
        native: {}
    });

	if (!connected) {
            connected = true;
            adapter.setState('info.connection', true, true);
        }

        for (var point in points) {
            if (points.hasOwnProperty(point)) {
                var val = message.readUIntBE(points[point].offset, points[point].length) * points[point].factor;
                if (points[point].val === undefined || points[point].val !== val) {
                    points[point].val = val;
                    adapter.setObjectNotExists (adapter.namespace + '.' + ser + '.' + point, {
					type: 'state',
					role: 'value',
					common: {
						name: point,
						type: 'state',
						role: 'value'
						},
					native: {}
			});
			adapter.setState (ser + '.' + point, val,true);
                }
            }
        }
    });

    client.bind(adapter.config.BPO, function () {
        adapter.log.info('Listen via UDP on Port ' + adapter.config.BPO + ' for Multicast IP ' + adapter.config.BIP);
        adapter.log.info('Details L1 ' + adapter.config.L1 + ' Details L2 ' + adapter.config.L2 + ' Details L3 ' + adapter.config.L3);
        client.addMembership(adapter.config.BIP);
    });

    client.on('close', function () {
        adapter.log.info('UDP Socket closed ...');
        setTimeout(readData, 2000);
        if (connected) {
            connected = false;
            adapter.setState('info.connection', false, true);
        }
    });

    client.on('error', function (err) {
        adapter.log.error('UDP Socket error: ' + err);
        setTimeout(readData, 2000);
        if (connected) {
            connected = false;
            adapter.setState('info.connection', false, true);
        }
    });
}

function main() {
    if (adapter.config.ext && adapter.config.ext === true) {
    points['qregard'] =                  {offset: 72,  length: 4, factor: 1 / 10, unit: 'var'};
    points['qregardcounter'] =       	 {offset: 80,  length: 8, factor: 1 / 3600000, unit: 'varh'};
    points['qsurplus'] =                 {offset: 92,  length: 4, factor: 1 / 10, unit: 'var'};
    points['qsurpluscounter'] =          {offset: 100, length: 8, factor: 1 / 3600000, unit: 'varh'};
    points['sregard'] =                  {offset: 112, length: 4, factor: 1 / 10, unit: 'VA'};
    points['sregardcounter'] =           {offset: 120, length: 8, factor: 1 / 3600000, unit: 'VAh'};
    points['ssurplus'] =                 {offset: 132, length: 4, factor: 1 / 10, unit: 'VA'};
    points['ssurpluscounter'] =          {offset: 140, length: 8, factor: 1 / 3600000, unit: 'VAh'};
    points['cosphi'] =                   {offset: 152, length: 4, factor: 1/ 1000, unit: 'Φ'};
};

 if (adapter.config.L1 && adapter.config.L1 === true) {
    points['L1.p1regard'] =              {offset: 160, length: 4, factor: 1/ 10, unit: 'Watt'};
    points['L1.p1regardcounter'] =	 {offset: 168, length: 8, factor: 1/ 3600000, unit: 'kWh'};
    points['L1.p1surplus'] =             {offset: 180, length: 4, factor: 1/ 10, unit: 'Watt'};
    points['L1.p1surpluscounter'] =      {offset: 188, length: 8, factor: 1/ 3600000, unit: 'kWh'};
 if (adapter.config.ext && adapter.config.ext === true) {
    points['L1.q1regard'] =              {offset: 200, length: 4, factor: 1/ 10, unit: 'var'};
    points['L1.q1regardcounter'] =       {offset: 208, length: 8, factor: 1/ 3600000, unit: 'var'};
    points['L1.q1surplus'] =             {offset: 220, length: 4, factor: 1/ 10, unit: 'var'};
    points['L1.q1surpluscounter'] =      {offset: 228, length: 8, factor: 1/ 3600000, unit: 'var'};
    points['L1.s1regard'] =              {offset: 240, length: 4, factor: 1/ 10, unit: 'VA'};
    points['L1.s1regardcounter'] =       {offset: 248, length: 8, factor: 1/ 3600000, unit: 'VAh'};
    points['L1.s1surplus'] =             {offset: 260, length: 4, factor: 1/ 10, unit: 'VA'};
    points['L1.s1surpluscounter'] =      {offset: 268, length: 8, factor: 1/ 3600000, unit: 'VAh'};
    points['L1.cosphi1'] =               {offset: 296, length: 4, factor: 1/ 1000, unit: 'Φ'};
    points['L1.amperage'] =                  {offset: 280, length: 4, factor: 1/ 1000, unit: 'A'};
    points['L1.v1'] =			 {offset: 288, length: 4, factor: 1/ 1000, unit: 'V'};
 };
 };

 if (adapter.config.L2 && adapter.config.L2 === true) {
    points['L2.p2regard'] =          	{offset: 304, length: 4, factor: 1/ 10, unit: 'Watt'};
    points['L2.p2regardcounter'] =   	{offset: 312, length: 8, factor: 1/ 3600000, unit: 'kWh'};
    points['L2.p2surplus'] =         	{offset: 324, length: 4, factor: 1/ 10, unit: 'Watt'};
    points['L2.p2surpluscounter'] =  	{offset: 332, length: 8, factor: 1/ 3600000, unit: 'kWh'};
if (adapter.config.ext && adapter.config.ext === true) {
    points['L2.q2regard'] =          	{offset: 344, length: 4, factor: 1/ 10, unit: 'var'};
    points['L2.q2regardcounter'] =   	{offset: 352, length: 8, factor: 1/ 3600000, unit: 'varh'};
    points['L2.q2surplus'] =         	{offset: 364, length: 4, factor: 1/ 10, unit: 'var'};
    points['L2.q2surpluscounter'] =  	{offset: 372, length: 8, factor: 1/ 3600000, unit: 'varh'};
    points['L2.s2regard'] =          	{offset: 384, length: 4, factor: 1/ 10, unit: 'VA'};
    points['L2.s2regardcounter'] =   	{offset: 392, length: 8, factor: 1/ 3600000, unit: 'VAh'};
    points['L2.s2surplus'] =         	{offset: 404, length: 4, factor: 1/ 10, unit: 'VA'};
    points['L2.s2surpluscounter'] =  	{offset: 412, length: 8, factor: 1/ 3600000, unit: 'VAh'};
    points['L2.cosphi2'] =           	{offset: 440, length: 4, factor: 1/ 1000, unit: 'Φ'};
    points['L2.amperage'] =           	{offset: 424, length: 4, factor: 1/ 1000, unit: 'A'};
    points['L2.v2'] =           	{offset: 432, length: 4, factor: 1/ 1000, unit: 'V'};
 };
 };
 if (adapter.config.L3 && adapter.config.L3 === true) {
    points['L3.p3regard'] =              {offset: 448, length: 4, factor: 1/ 10, unit: 'Watt'};
    points['L3.p3regardcounter'] =       {offset: 456, length: 8, factor: 1/ 3600000, unit: 'kWh'};
    points['L3.p3surplus'] =             {offset: 468, length: 4, factor: 1/ 10, unit: 'Watt'};
    points['L3.p3surpluscounter'] =      {offset: 476, length: 8, factor: 1/ 3600000, unit: 'kWh'};
if (adapter.config.ext && adapter.config.ext === true) {
    points['L3.q3regard'] =              {offset: 488, length: 4, factor: 1/ 10, unit: 'var'};
    points['L3.q3regardcounter'] =       {offset: 496, length: 8, factor: 1/ 3600000, unit: 'varh'};
    points['L3.q3surplus'] =             {offset: 508, length: 4, factor: 1/ 10, unit: 'var'};
    points['L3.q3surpluscounter'] =      {offset: 516, length: 8, factor: 1/ 3600000, unit: 'varh'};
    points['L3.s3regard'] =              {offset: 528, length: 4, factor: 1/ 10, unit: 'VA'};
    points['L3.s3regardcounter'] =       {offset: 536, length: 8, factor: 1/ 3600000, unit: 'VAh'};
    points['L3.s3surplus'] =             {offset: 548, length: 4, factor: 1/ 10, unit: 'VA'};
    points['L3.s3surpluscounter'] =      {offset: 556, length: 8, factor: 1/ 3600000, unit: 'VAh'};
    points['L3.cosphi3'] =               {offset: 584, length: 4, factor: 1/ 1000, unit: 'Φ'};
    points['L3.amperage'] =           	 {offset: 568, length: 4, factor: 1/ 1000, unit: 'A'};
    points['L3.v3'] =           	 {offset: 576, length: 4, factor: 1/ 1000, unit: 'V'};
 };
 };
    adapter.setState('info.connection', false, true);
    readData();
}
<|endoftext|>


<commit_before>const {app, BrowserWindow, ipcMain, Tray, nativeImage} = require('electron')
const path = require('path')

const assetsDir = path.join(__dirname, 'assets')

let tray = undefined
let window = undefined

// This method is called once Electron is ready to run our code
// It is effectively the main method of our Electron app
app.on('ready', () => {
  // Setup the menubar with an icon
  let icon = nativeImage.createFromDataURL(base64Icon)
  tray = new Tray(icon)

  // Remove dock icon on launch
  // app.dock.hide()

  // Add a click handler so that when the user clicks on the menubar icon, it shows
  // our popup window
  tray.on('click', function(event) {
    toggleWindow()

    // Show devtools when command clicked
    if (window.isVisible() && process.defaultApp && event.metaKey) {
      window.openDevTools({mode: 'detach'})
    }
  })

  // Make the popup window for the menubar
  window = new BrowserWindow({
    width: 250,
    height: 130,
    show: false,
    frame: false,
    resizable: false,
  })

  // Tell the popup window to load our index.html file
  window.loadURL(`file://${path.join(__dirname, 'index.html')}`)

  // Only close the window on blur if dev tools isn't opened
  window.on('blur', () => {
    if(!window.webContents.isDevToolsOpened()) {
      window.hide()
    }
  })
})

const toggleWindow = () => {
  if (window.isVisible()) {
    window.hide()
  } else {
    showWindow()
  }
}

const showWindow = () => {
  const trayPos = tray.getBounds()
  const windowPos = window.getBounds()
  let x, y = 0
  if (process.platform == 'darwin') {
    x = Math.round(trayPos.x + (trayPos.width / 2) - (windowPos.width / 2))
    y = Math.round(trayPos.y + trayPos.height)
  } else {
    x = Math.round(trayPos.x + (trayPos.width / 2) - (windowPos.width / 2))
    y = Math.round(trayPos.y + trayPos.height * 10)
  }

  window.setPosition(x, y, false)
  window.show()
  window.focus()
}

ipcMain.on('show-window', () => {
  showWindow()
})

app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// Tray Icon as Base64 so tutorial has less overhead
let base64Icon = `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAMAAAC6V+0/AAAAM1BMVEUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACjBUbJAAAAEHRSTlMAECAwQFBgcICPn6+/z9/vIxqCigAAAIpJREFUeAG1jdGuBCEIQ8cRkREQ//9rL+Umk33fLA+1Hmh6/Wo6L5HRKOdlGibynONmHvzPzBs2vvBSdLA7wGi3y2YaqZOpWK0EY1dQkJuw507ZiFJgQwUh/toPWNIKcv2rGY4tZVS7SpY9gM5VvPPpITNQRrhBYB8XPUeJiF2KYYbI7GpmytfX8weDLwSRi4YEvQAAAABJRU5ErkJggg==`
<commit_msg>Add new logo base64<commit_after>const {app, BrowserWindow, ipcMain, Tray, nativeImage} = require('electron')
const path = require('path')

const assetsDir = path.join(__dirname, 'assets')

let tray = undefined
let window = undefined

// This method is called once Electron is ready to run our code
// It is effectively the main method of our Electron app
app.on('ready', () => {
  // Setup the menubar with an icon
  let icon = nativeImage.createFromDataURL(base64Icon)
  tray = new Tray(icon)

  // Remove dock icon on launch
  // app.dock.hide()

  // Add a click handler so that when the user clicks on the menubar icon, it shows
  // our popup window
  tray.on('click', function(event) {
    toggleWindow()

    // Show devtools when command clicked
    if (window.isVisible() && process.defaultApp && event.metaKey) {
      window.openDevTools({mode: 'detach'})
    }
  })

  // Make the popup window for the menubar
  window = new BrowserWindow({
    width: 250,
    height: 130,
    show: false,
    frame: false,
    resizable: false,
  })

  // Tell the popup window to load our index.html file
  window.loadURL(`file://${path.join(__dirname, 'index.html')}`)

  // Only close the window on blur if dev tools isn't opened
  window.on('blur', () => {
    if(!window.webContents.isDevToolsOpened()) {
      window.hide()
    }
  })
})

const toggleWindow = () => {
  if (window.isVisible()) {
    window.hide()
  } else {
    showWindow()
  }
}

const showWindow = () => {
  const trayPos = tray.getBounds()
  const windowPos = window.getBounds()
  let x, y = 0
  if (process.platform == 'darwin') {
    x = Math.round(trayPos.x + (trayPos.width / 2) - (windowPos.width / 2))
    y = Math.round(trayPos.y + trayPos.height)
  } else {
    x = Math.round(trayPos.x + (trayPos.width / 2) - (windowPos.width / 2))
    y = Math.round(trayPos.y + trayPos.height * 10)
  }

  window.setPosition(x, y, false)
  window.show()
  window.focus()
}

ipcMain.on('show-window', () => {
  showWindow()
})

app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// Tray Icon as Base64 so tutorial has less overhead
let base64Icon = `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA3hpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMDE0IDc5LjE1Njc5NywgMjAxNC8wOC8yMC0wOTo1MzowMiAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDpjYTZmNTI2OC0yZWUzLTQzNDEtYTk4Yy01ZmJhMGQ0NmE4ZmQiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6NUZDRDU3NUVCMEMxMTFFNkFENDlBMUM3Mjc5QTQwRTUiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6NUZDRDU3NURCMEMxMTFFNkFENDlBMUM3Mjc5QTQwRTUiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTQgKE1hY2ludG9zaCkiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDo2MzE0NGNiZC1jNTE3LTRlZTEtOGUzZS05NTY2NGJhN2E2NmEiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6Y2E2ZjUyNjgtMmVlMy00MzQxLWE5OGMtNWZiYTBkNDZhOGZkIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+n9NOUQAAATFJREFUeNpi/P//PwM1AQsyx8TEQRKLmudnzhwg2kAmNL4eEN9EwiA+L9Ai8lwIBPOBuB2IDwGxHZSvToqXmbCIbQfio1CaZIDNwAtoNMUGgsBWIDagloGVQGwLxJ7UMDARiDWhbAkonyTACEvY0KTBCxV/CsRaQPwRiD+DBIhNi+gu/EyAT5KBINe5A3ELlF8K5TOQklOwJezJQHwdiF/AEjYwOD4jBQc28BlmKa6EfQItYYMMs0LLljBshWwZCzbrgLblQyNqNZDihwp7QV3fDuUbQJMWSI00XgOhhk2EJhv0pGMDtNAblJOAarih6ZYBn4GeUIWwMKyBirdAxbZDLTSAFiB4IyUR6gWYraFIyWcb1IJctOIsFJeBIE3HkMMDLS0ew1OUfcbIKdQCAAEGAGLsU/kwaSpnAAAAAElFTkSuQmCC`
<|endoftext|>


<commit_before>(function(window) {
    function isPromise(o) {
        return o instanceof Promise
    }

    var web3 = {
        _callbacks: {},
        _events: {},
        providers: {},
        toHex: function(str) {
            var hex = "";
            for(var i = 0; i < str.length; i++) {
                var n = str.charCodeAt(i).toString(16);
                hex += n.length < 2 ? '0' + n : n;
            }

            return hex;
        },

        toAscii: function(hex) {
            // Find termination
            var str = "";
            var i = 0, l = hex.length;
            for(; i < l; i+=2) {
                var code = hex.charCodeAt(i)
                if(code == 0) {
                    break;
                }

                str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
            }

            return str;
        },

        fromAscii: function(str, pad) {
            if(pad === undefined) {
                pad = 32
            }

            var hex = this.toHex(str);

            while(hex.length < pad*2)
                hex += "00";

            return hex
        },

        eth: {
            prototype: Object(),

            block: function(numberOrHash) {
                return new Promise(function(resolve, reject) {
                    /*
                    var func;
                    if(typeof numberOrHash == "string") {
                        func =  "getBlockByHash";
                    } else {
                        func =  "getBlockByNumber";
                    }
                    */

                    web3.provider.send({call: /*func*/"block", args: [numberOrHash]}, function(block) {
                        if(block)
                            resolve(block);
                        else
                            reject("not found");

                    });
                });
            },

            transaction: function(numberOrHash, nth) {
                return new Promise(function(resolve, reject) {
                    reject("`transaction` not yet implemented")
                });
            },

            uncle: function(numberOrHash, nth) {
                return new Promise(function(resolve, reject) {
                    reject("`uncle` not yet implemented")
                });
            },

            transact: function(params) {
                if(params === undefined) {
                    params = {};
                }

                if(params.endowment !== undefined)
                    params.value = params.endowment;
                if(params.code !== undefined)
                    params.data = params.code;

                var promises = []
                if(isPromise(params.to)) {
                    promises.push(params.to.then(function(_to) { params.to = _to; }));
                }
                if(isPromise(params.from)) {
                    promises.push(params.from.then(function(_from) { params.from = _from; }));
                }

                if(typeof params.data !== "object" || isPromise(params.data)) {
                    params.data = [params.data]
                }

                var data = params.data;
                for(var i = 0; i < params.data.length; i++) {
                    if(isPromise(params.data[i])) {
                        var promise = params.data[i];
                        var _i = i;
                        promises.push(promise.then(function(_arg) { params.data[_i] = _arg; }));
                    }
                }

                // Make sure everything is string
                var fields = ["value", "gas", "gasPrice"];
                for(var i = 0; i < fields.length; i++) {
                    if(params[fields[i]] === undefined) {
                        params[fields[i]] = "";
                    }
                    params[fields[i]] = params[fields[i]].toString();
                }

                // Load promises then call the last "transact".
                return Promise.all(promises).then(function() {
                    return new Promise(function(resolve, reject) {
                        params.data = params.data.join("");
                        web3.provider.send({call: "transact", args: ["0x"+params]}, function(data) {
                            if(data[1])
                                reject(data[0]);
                            else
                                resolve(data[0]);
                        });
                    });
                })
            },

            compile: function(code) {
                return new Promise(function(resolve, reject) {
                    web3.provider.send({call: "compile", args: [code]}, function(data) {
                        if(data[1])
                            reject(data[0]);
                        else
                            resolve(data[0]);
                    });
                });
            },

            balanceAt: function(address) {
                var promises = [];

                if(isPromise(address)) {
                    promises.push(address.then(function(_address) { address = _address; }));
                }

                return Promise.all(promises).then(function() {
                    return new Promise(function(resolve, reject) {
                        web3.provider.send({call: "balanceAt", args: [address]}, function(balance) {
                            resolve(balance);
                        });
                    });
                });
            },

            countAt: function(address) {
                var promises = [];

                if(isPromise(address)) {
                    promises.push(address.then(function(_address) { address = _address; }));
                }

                return Promise.all(promises).then(function() {
                    return new Promise(function(resolve, reject) {
                        web3.provider.send({call: "countAt", args: [address]}, function(count) {
                            resolve(count);
                        });
                    });
                });
            },

            codeAt: function(address) {
                var promises = [];

                if(isPromise(address)) {
                    promises.push(address.then(function(_address) { address = _address; }));
                }

                return Promise.all(promises).then(function() {
                    return new Promise(function(resolve, reject) {
                        web3.provider.send({call: "codeAt", args: [address]}, function(code) {
                            resolve(code);
                        });
                    });
                });
            },

            storageAt: function(address, storageAddress) {
                var promises = [];

                if(isPromise(address)) {
                    promises.push(address.then(function(_address) { address = _address; }));
                }

                if(isPromise(storageAddress)) {
                    promises.push(storageAddress.then(function(_sa) { storageAddress = _sa; }));
                }

                return Promise.all(promises).then(function() {
                    return new Promise(function(resolve, reject) {
                        web3.provider.send({call: "stateAt", args: [address, storageAddress]}, function(entry) {
                            resolve(entry);
                        });
                    });
                });
            },

            stateAt: function(address, storageAddress) {
                return this.storageAt(address, storageAddress);
            },

            call: function(params) {
                if(params === undefined) {
                    params = {};
                }

                if(params.endowment !== undefined)
                    params.value = params.endowment;
                if(params.code !== undefined)
                    params.data = params.code;

                var promises = []
                if(isPromise(params.to)) {
                    promises.push(params.to.then(function(_to) { params.to = _to; }));
                }
                if(isPromise(params.from)) {
                    promises.push(params.from.then(function(_from) { params.from = _from; }));
                }

                if(isPromise(params.data)) {
                    promises.push(params.data.then(function(_code) { params.data = _code; }));
                } else {
                    if(typeof params.data === "object") {
                        data = "";
                        for(var i = 0; i < params.data.length; i++) {
                            data += params.data[i]
                        }
                    } else {
                        data = params.data;
                    }
                }

                // Make sure everything is string
                var fields = ["value", "gas", "gasPrice"];
                for(var i = 0; i < fields.length; i++) {
                    if(params[fields[i]] === undefined) {
                        params[fields[i]] = "";
                    }
                    params[fields[i]] = params[fields[i]].toString();
                }

                // Load promises then call the last "transact".
                return Promise.all(promises).then(function() {
                    return new Promise(function(resolve, reject) {
                        web3.provider.send({call: "call", args: params}, function(data) {
                            if(data[1])
                                reject(data[0]);
                            else
                                resolve(data[0]);
                        });
                    });
                })
            },

            watch: function(params) {
                return new Filter(params);
            },
        },

        on: function(event, cb) {
            if(web3._events[event] === undefined) {
                web3._events[event] = [];
            }

            web3._events[event].push(cb);

            return this
        },

        off: function(event, cb) {
            if(web3._events[event] !== undefined) {
                var callbacks = web3._events[event];
                for(var i = 0; i < callbacks.length; i++) {
                    if(callbacks[i] === cb) {
                        delete callbacks[i];
                    }
                }
            }

            return this
        },

        trigger: function(event, data) {
            var callbacks = web3._events[event];
            if(callbacks !== undefined) {
                for(var i = 0; i < callbacks.length; i++) {
                    // Figure out whether the returned data was an array
                    // array means multiple return arguments (multiple params)
                    if(data instanceof Array) {
                        callbacks[i].apply(this, data);
                    } else {
                        callbacks[i].call(this, data);
                    }
                }
            }
        },
    };

    var eth = web3.eth;
    // Eth object properties
    Object.defineProperty(eth, "key", {
        get: function() {
            return new Promise(function(resolve, reject) {
                eth.provider.send({call: "getKey"}, function(k) {
                    resolve(k);
                });
            });
        },
    });

    Object.defineProperty(eth, "gasPrice", {
        get: function() {
            return "10000000000000"
        }
    });

    Object.defineProperty(eth, "coinbase", {
        get: function() {
            return new Promise(function(resolve, reject) {
                web3.provider.send({call: "getCoinBase"}, function(coinbase) {
                    resolve(coinbase);
                });
            });
        },
    });

    Object.defineProperty(eth, "listening", {
        get: function() {
            return new Promise(function(resolve, reject) {
                web3.provider.send({call: "getIsListening"}, function(listening) {
                    resolve(listening);
                });
            });
        },
    });

    Object.defineProperty(eth, "mining", {
        get: function() {
            return new Promise(function(resolve, reject) {
                web3.provider.send({call: "getIsMining"}, function(mining) {
                    resolve(mining);
                });
            });
        },
    });

    Object.defineProperty(eth, "peerCount", {
        get: function() {
            return new Promise(function(resolve, reject) {
                web3.provider.send({call: "getPeerCount"}, function(peerCount) {
                    resolve(peerCount);
                });
            });
        },
    });

    var ProviderManager = function() {
        this.queued = [];
        this.ready = false;
        this.provider = undefined;
        this.id = 1;
    };
    ProviderManager.prototype.send = function(data, cb) {
        data._id = this.id;
        if(cb) {
            web3._callbacks[data._id] = cb;
        }

        if(data.args === undefined) {
            data.args = [];
        }

        this.id++;

        if(this.provider !== undefined) {
            this.provider.send(data);
        } else {
            this.queued.push(data);
        }
    };

    ProviderManager.prototype.set = function(provider) {
        if(this.provider !== undefined && this.provider.unload !== undefined) {
            this.provider.unload();
        }

        this.provider = provider;
        this.ready = true;
    };

    ProviderManager.prototype.sendQueued = function() {
        for(var i = 0; this.queued.length; i++) {
            // Resend
            this.send(this.queued[i]);
        }
    };

    ProviderManager.prototype.installed = function() {
        return this.provider !== undefined;
    };
    web3.provider = new ProviderManager();

    web3.setProvider = function(provider) {
        provider.onmessage = messageHandler;

        web3.provider.set(provider);

        web3.provider.sendQueued();
    };

    var filters = [];
    var Filter = function(options) {
        filters.push(this);

        this.callbacks = [];
        this.options = options;

        var call;
        if(options === "chain") {
            call = "newFilterString"
        } else if(typeof options === "object") {
            call = "newFilter"
        }

        var self = this; // Cheaper than binding
        this.promise = new Promise(function(resolve, reject) {
            web3.provider.send({call: call, args: [options]}, function(id) {
                self.id = id;

                resolve(id);
            });
        });
    };

    Filter.prototype.changed = function(callback) {
        var self = this;
        this.promise.then(function(id) {
            self.callbacks.push(callback);
        });
    };

    Filter.prototype.trigger = function(messages, id) {
        if(id == this.id) {
            for(var i = 0; i < this.callbacks.length; i++) {
                this.callbacks[i].call(this, messages);
            }
        }
    };

    Filter.prototype.uninstall = function() {
        this.promise.then(function(id) {
            web3.provider.send({call: "uninstallFilter", args:[id]});
        });
    };

    Filter.prototype.messages = function() {
        var self=this;
        return Promise.all([this.promise]).then(function() {
            var id = self.id
            return new Promise(function(resolve, reject) {
                web3.provider.send({call: "getMessages", args: [id]}, function(messages) {
                    resolve(messages);
                });
            });
        });
    };

    // Register to the messages callback. "messages" will be emitted when new messages
    // from the client have been created.
    web3.on("messages", function(messages, id) {
        for(var i = 0; i < filters.length; i++) {
            filters[i].trigger(messages, id);
        }
    });

    function messageHandler(ev) {
        var data = JSON.parse(ev)

        if(data._event !== undefined) {
            web3.trigger(data._event, data.data);
        } else {
            if(data._id) {
                var cb = web3._callbacks[data._id];
                if(cb) {
                    cb.call(this, data.data)

                    // Remove the "trigger" callback
                    delete web3._callbacks[ev._id];
                }
            }
        }
    }

    /*
    // Install default provider
    if(!web3.provider.installed()) {
        var sock = new web3.WebSocket("ws://localhost:40404/eth");

        web3.setProvider(sock);
    }
    */

    window.web3 = web3;
})(this);
<commit_msg>Updated properties<commit_after>(function(window) {
    function isPromise(o) {
        return o instanceof Promise
    }

    var web3 = {
        _callbacks: {},
        _events: {},
        providers: {},
        toHex: function(str) {
            var hex = "";
            for(var i = 0; i < str.length; i++) {
                var n = str.charCodeAt(i).toString(16);
                hex += n.length < 2 ? '0' + n : n;
            }

            return hex;
        },

        toAscii: function(hex) {
            // Find termination
            var str = "";
            var i = 0, l = hex.length;
            for(; i < l; i+=2) {
                var code = hex.charCodeAt(i)
                if(code == 0) {
                    break;
                }

                str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
            }

            return str;
        },

        fromAscii: function(str, pad) {
            if(pad === undefined) {
                pad = 32
            }

            var hex = this.toHex(str);

            while(hex.length < pad*2)
                hex += "00";

            return hex
        },

        eth: {
            prototype: Object(),

            block: function(numberOrHash) {
                return new Promise(function(resolve, reject) {
                    /*
                    var func;
                    if(typeof numberOrHash == "string") {
                        func =  "getBlockByHash";
                    } else {
                        func =  "getBlockByNumber";
                    }
                    */

                    web3.provider.send({call: /*func*/"block", args: [numberOrHash]}, function(block) {
                        if(block)
                            resolve(block);
                        else
                            reject("not found");

                    });
                });
            },

            transaction: function(numberOrHash, nth) {
                return new Promise(function(resolve, reject) {
                    reject("`transaction` not yet implemented")
                });
            },

            uncle: function(numberOrHash, nth) {
                return new Promise(function(resolve, reject) {
                    reject("`uncle` not yet implemented")
                });
            },

            transact: function(params) {
                if(params === undefined) {
                    params = {};
                }

                if(params.endowment !== undefined)
                    params.value = params.endowment;
                if(params.code !== undefined)
                    params.data = params.code;

                var promises = []
                if(isPromise(params.to)) {
                    promises.push(params.to.then(function(_to) { params.to = _to; }));
                }
                if(isPromise(params.from)) {
                    promises.push(params.from.then(function(_from) { params.from = _from; }));
                }

                if(typeof params.data !== "object" || isPromise(params.data)) {
                    params.data = [params.data]
                }

                var data = params.data;
                for(var i = 0; i < params.data.length; i++) {
                    if(isPromise(params.data[i])) {
                        var promise = params.data[i];
                        var _i = i;
                        promises.push(promise.then(function(_arg) { params.data[_i] = _arg; }));
                    }
                }

                // Make sure everything is string
                var fields = ["value", "gas", "gasPrice"];
                for(var i = 0; i < fields.length; i++) {
                    if(params[fields[i]] === undefined) {
                        params[fields[i]] = "";
                    }
                    params[fields[i]] = params[fields[i]].toString();
                }

                // Load promises then call the last "transact".
                return Promise.all(promises).then(function() {
                    return new Promise(function(resolve, reject) {
                        params.data = params.data.join("");
                        web3.provider.send({call: "transact", args: ["0x"+params]}, function(data) {
                            if(data[1])
                                reject(data[0]);
                            else
                                resolve(data[0]);
                        });
                    });
                })
            },

            compile: function(code) {
                return new Promise(function(resolve, reject) {
                    web3.provider.send({call: "compile", args: [code]}, function(data) {
                        if(data[1])
                            reject(data[0]);
                        else
                            resolve(data[0]);
                    });
                });
            },

            balanceAt: function(address) {
                var promises = [];

                if(isPromise(address)) {
                    promises.push(address.then(function(_address) { address = _address; }));
                }

                return Promise.all(promises).then(function() {
                    return new Promise(function(resolve, reject) {
                        web3.provider.send({call: "balanceAt", args: [address]}, function(balance) {
                            resolve(balance);
                        });
                    });
                });
            },

            countAt: function(address) {
                var promises = [];

                if(isPromise(address)) {
                    promises.push(address.then(function(_address) { address = _address; }));
                }

                return Promise.all(promises).then(function() {
                    return new Promise(function(resolve, reject) {
                        web3.provider.send({call: "countAt", args: [address]}, function(count) {
                            resolve(count);
                        });
                    });
                });
            },

            codeAt: function(address) {
                var promises = [];

                if(isPromise(address)) {
                    promises.push(address.then(function(_address) { address = _address; }));
                }

                return Promise.all(promises).then(function() {
                    return new Promise(function(resolve, reject) {
                        web3.provider.send({call: "codeAt", args: [address]}, function(code) {
                            resolve(code);
                        });
                    });
                });
            },

            storageAt: function(address, storageAddress) {
                var promises = [];

                if(isPromise(address)) {
                    promises.push(address.then(function(_address) { address = _address; }));
                }

                if(isPromise(storageAddress)) {
                    promises.push(storageAddress.then(function(_sa) { storageAddress = _sa; }));
                }

                return Promise.all(promises).then(function() {
                    return new Promise(function(resolve, reject) {
                        web3.provider.send({call: "stateAt", args: [address, storageAddress]}, function(entry) {
                            resolve(entry);
                        });
                    });
                });
            },

            stateAt: function(address, storageAddress) {
                return this.storageAt(address, storageAddress);
            },

            call: function(params) {
                if(params === undefined) {
                    params = {};
                }

                if(params.endowment !== undefined)
                    params.value = params.endowment;
                if(params.code !== undefined)
                    params.data = params.code;

                var promises = []
                if(isPromise(params.to)) {
                    promises.push(params.to.then(function(_to) { params.to = _to; }));
                }
                if(isPromise(params.from)) {
                    promises.push(params.from.then(function(_from) { params.from = _from; }));
                }

                if(isPromise(params.data)) {
                    promises.push(params.data.then(function(_code) { params.data = _code; }));
                } else {
                    if(typeof params.data === "object") {
                        data = "";
                        for(var i = 0; i < params.data.length; i++) {
                            data += params.data[i]
                        }
                    } else {
                        data = params.data;
                    }
                }

                // Make sure everything is string
                var fields = ["value", "gas", "gasPrice"];
                for(var i = 0; i < fields.length; i++) {
                    if(params[fields[i]] === undefined) {
                        params[fields[i]] = "";
                    }
                    params[fields[i]] = params[fields[i]].toString();
                }

                // Load promises then call the last "transact".
                return Promise.all(promises).then(function() {
                    return new Promise(function(resolve, reject) {
                        web3.provider.send({call: "call", args: params}, function(data) {
                            if(data[1])
                                reject(data[0]);
                            else
                                resolve(data[0]);
                        });
                    });
                })
            },

            watch: function(params) {
                return new Filter(params);
            },
        },

        on: function(event, cb) {
            if(web3._events[event] === undefined) {
                web3._events[event] = [];
            }

            web3._events[event].push(cb);

            return this
        },

        off: function(event, cb) {
            if(web3._events[event] !== undefined) {
                var callbacks = web3._events[event];
                for(var i = 0; i < callbacks.length; i++) {
                    if(callbacks[i] === cb) {
                        delete callbacks[i];
                    }
                }
            }

            return this
        },

        trigger: function(event, data) {
            var callbacks = web3._events[event];
            if(callbacks !== undefined) {
                for(var i = 0; i < callbacks.length; i++) {
                    // Figure out whether the returned data was an array
                    // array means multiple return arguments (multiple params)
                    if(data instanceof Array) {
                        callbacks[i].apply(this, data);
                    } else {
                        callbacks[i].call(this, data);
                    }
                }
            }
        },
    };

    var eth = web3.eth;
    // Eth object properties
    Object.defineProperty(eth, "gasPrice", {
        get: function() {
            return "10000000000000"
        }
    });

    Object.defineProperty(eth, "coinbase", {
        get: function() {
            return new Promise(function(resolve, reject) {
                web3.provider.send({call: "coinbase"}, function(coinbase) {
                    resolve(coinbase);
                });
            });
        },
    });

    Object.defineProperty(eth, "listening", {
        get: function() {
            return new Promise(function(resolve, reject) {
                web3.provider.send({call: "listening"}, function(listening) {
                    resolve(listening);
                });
            });
        },
    });

    Object.defineProperty(eth, "mining", {
        get: function() {
            return new Promise(function(resolve, reject) {
                web3.provider.send({call: "mining"}, function(mining) {
                    resolve(mining);
                });
            });
        },
    });

    Object.defineProperty(eth, "peerCount", {
        get: function() {
            return new Promise(function(resolve, reject) {
                web3.provider.send({call: "peerCount"}, function(peerCount) {
                    resolve(peerCount);
                });
            });
        },
    });

    var ProviderManager = function() {
        this.queued = [];
        this.ready = false;
        this.provider = undefined;
        this.id = 1;
    };
    ProviderManager.prototype.send = function(data, cb) {
        data._id = this.id;
        if(cb) {
            web3._callbacks[data._id] = cb;
        }

        if(data.args === undefined) {
            data.args = [];
        }

        this.id++;

        if(this.provider !== undefined) {
            this.provider.send(data);
        } else {
            this.queued.push(data);
        }
    };

    ProviderManager.prototype.set = function(provider) {
        if(this.provider !== undefined && this.provider.unload !== undefined) {
            this.provider.unload();
        }

        this.provider = provider;
        this.ready = true;
    };

    ProviderManager.prototype.sendQueued = function() {
        for(var i = 0; this.queued.length; i++) {
            // Resend
            this.send(this.queued[i]);
        }
    };

    ProviderManager.prototype.installed = function() {
        return this.provider !== undefined;
    };
    web3.provider = new ProviderManager();

    web3.setProvider = function(provider) {
        provider.onmessage = messageHandler;

        web3.provider.set(provider);

        web3.provider.sendQueued();
    };

    var filters = [];
    var Filter = function(options) {
        filters.push(this);

        this.callbacks = [];
        this.options = options;

        var call;
        if(options === "chain") {
            call = "newFilterString"
        } else if(typeof options === "object") {
            call = "newFilter"
        }

        var self = this; // Cheaper than binding
        this.promise = new Promise(function(resolve, reject) {
            web3.provider.send({call: call, args: [options]}, function(id) {
                self.id = id;

                resolve(id);
            });
        });
    };

    Filter.prototype.changed = function(callback) {
        var self = this;
        this.promise.then(function(id) {
            self.callbacks.push(callback);
        });
    };

    Filter.prototype.trigger = function(messages, id) {
        if(id == this.id) {
            for(var i = 0; i < this.callbacks.length; i++) {
                this.callbacks[i].call(this, messages);
            }
        }
    };

    Filter.prototype.uninstall = function() {
        this.promise.then(function(id) {
            web3.provider.send({call: "uninstallFilter", args:[id]});
        });
    };

    Filter.prototype.messages = function() {
        var self=this;
        return Promise.all([this.promise]).then(function() {
            var id = self.id
            return new Promise(function(resolve, reject) {
                web3.provider.send({call: "getMessages", args: [id]}, function(messages) {
                    resolve(messages);
                });
            });
        });
    };

    // Register to the messages callback. "messages" will be emitted when new messages
    // from the client have been created.
    web3.on("messages", function(messages, id) {
        for(var i = 0; i < filters.length; i++) {
            filters[i].trigger(messages, id);
        }
    });

    function messageHandler(ev) {
        var data = JSON.parse(ev)

        if(data._event !== undefined) {
            web3.trigger(data._event, data.data);
        } else {
            if(data._id) {
                var cb = web3._callbacks[data._id];
                if(cb) {
                    cb.call(this, data.data)

                    // Remove the "trigger" callback
                    delete web3._callbacks[ev._id];
                }
            }
        }
    }

    /*
    // Install default provider
    if(!web3.provider.installed()) {
        var sock = new web3.WebSocket("ws://localhost:40404/eth");

        web3.setProvider(sock);
    }
    */

    window.web3 = web3;
})(this);
<|endoftext|>


<commit_before>var canvas; //Will be linked to the canvas in our index.html page
var stage; //Is the equivalent of stage in AS3; we'll add "children" to it

// Graphics
//[Background]

var bg; //The background graphic

//[Title View]

var main; //The Main Background
var startB; //The Start button in the main menu
var creditsB; //The credits button in the main menu

//[Credits]

var credits; //The Credits screen

//[Game View]

var player; //The player paddle graphic
var ball; //The ball graphic
var cpu; //The CPU paddle
var win; //The winning popup
var lose; //The losing popup

//[Score]

var playerScore; //The main player score
var cpuScore; //The CPU score
var cpuSpeed=6; //The speed of the CPU paddle; the faster it is the harder the game is

// Variables

var xSpeed = 5;
var ySpeed = 5;

var tkr = new Object;

//preloader
var preloader;
var manifest;
var totalLoaded = 0;

var TitleView = new Container();

function Main()
{
    /* Link Canvas */

    canvas = document.getElementById('PongStage');
    stage = new Stage(canvas);

    stage.mouseEventsEnabled = true;

    manifest = [
                {src:"bg.png", id:"bg"},
                {src:"main.png", id:"main"},
                {src:"startB.png", id:"startB"},
                {src:"creditsB.png", id:"creditsB"},
                {src:"credits.png", id:"credits"},
                {src:"paddle.png", id:"cpu"},
                {src:"paddle.png", id:"player"},
                {src:"ball.png", id:"ball"},
                {src:"win.png", id:"win"},
                {src:"lose.png", id:"lose"},
                {src:"playerScore.mp3|playerScore.ogg", id:"playerScore"},
                {src:"enemyScore.mp3|enemyScore.ogg", id:"enemyScore"},
                {src:"hit.mp3|hit.ogg", id:"hit"},
                {src:"wall.mp3|wall.ogg", id:"wall"}
            ];

    preloader = new PreloadJS();
    preloader.installPlugin(SoundJS);
    preloader.onProgress = handleProgress;
    preloader.onComplete = handleComplete;
    preloader.onFileLoad = handleFileLoad;
    preloader.loadManifest(manifest);

    /* Ticker */

    Ticker.setFPS(30);
    Ticker.addListener(stage);
}

function handleProgress(event)
{
    //use event.loaded to get the percentage of the loading
}

function handleComplete(event) {
         //triggered when all loading is complete
}

function handleFileLoad(event) {
         //triggered when an individual file completes loading

         switch(event.type)
         {
            case PreloadJS.IMAGE:
            //image loaded
             var img = new Image();
              img.src = event.src;
              img.onload = handleLoadComplete;
              window[event.id] = new Bitmap(img);
            break;

            case PreloadJS.SOUND:
            //sound loaded
            handleLoadComplete();
            break;
         }
}

function handleLoadComplete(event)
{

   totalLoaded++;

   if(manifest.length==totalLoaded)
   {
       addTitleView();
   }
}

function addTitleView()
{
    //console.log("Add Title View");
    startB.x = 240 - 31.5;
    startB.y = 160;
    startB.name = 'startB';

    creditsB.x = 241 - 42;
    creditsB.y = 200;

    TitleView.addChild(main, startB, creditsB);
    stage.addChild(bg, TitleView);
    stage.update();

    // Button Listeners

    startB.onPress = tweenTitleView;
    creditsB.onPress = showCredits;

}
function showCredits()
{
    // Show Credits

    credits.x = 480;

    stage.addChild(credits);
    stage.update();
    Tween.get(credits).to({x:0}, 300);
    credits.onPress = hideCredits;
}

// Hide Credits

function hideCredits(e)
{
    Tween.get(credits).to({x:480}, 300).call(rmvCredits);
}

// Remove Credits

function rmvCredits()
{
    stage.removeChild(credits);
}

// Tween Title View

function tweenTitleView()
{
    // Start Game

 Tween.get(TitleView).to({y:-320}, 300).call(addGameView);
}
<commit_msg>pls work deleted more stuff that doesnt like meh pls work<commit_after>var canvas; //Will be linked to the canvas in our index.html page
var stage; //Is the equivalent of stage in AS3; we'll add "children" to it

// Graphics
//[Background]

var bg; //The background graphic

//[Title View]

var main; //The Main Background
var startB; //The Start button in the main menu
var creditsB; //The credits button in the main menu

//[Credits]

var credits; //The Credits screen

//[Game View]

var player; //The player paddle graphic
var ball; //The ball graphic
var cpu; //The CPU paddle
var win; //The winning popup
var lose; //The losing popup

//[Score]

var playerScore; //The main player score
var cpuScore; //The CPU score
var cpuSpeed=6; //The speed of the CPU paddle; the faster it is the harder the game is

// Variables

var xSpeed = 5;
var ySpeed = 5;

var tkr = new Object;

//preloader
var preloader;
var manifest;
var totalLoaded = 0;

var TitleView = new Container();

function Main()
{
    /* Link Canvas */

    canvas = document.getElementById('PongStage');
    stage = new Stage(canvas);

    stage.mouseEventsEnabled = true;

    preloader = new PreloadJS();
    preloader.onProgress = handleProgress;
    preloader.onComplete = handleComplete;
    preloader.onFileLoad = handleFileLoad;
    preloader.loadManifest(manifest);

    /* Ticker */

    Ticker.setFPS(30);
    Ticker.addListener(stage);
}

function handleProgress(event)
{
    //use event.loaded to get the percentage of the loading
}

function handleComplete(event) {
         //triggered when all loading is complete
}

function handleFileLoad(event) {
         //triggered when an individual file completes loading

         switch(event.type)
         {
            case PreloadJS.IMAGE:
            //image loaded
             var img = new Image();
              img.src = event.src;
              img.onload = handleLoadComplete;
              window[event.id] = new Bitmap(img);
            break;

            case PreloadJS.SOUND:
            //sound loaded
            handleLoadComplete();
            break;
         }
}

function handleLoadComplete(event)
{

   totalLoaded++;

   if(manifest.length==totalLoaded)
   {
       addTitleView();
   }
}

function addTitleView()
{
    //console.log("Add Title View");
    startB.x = 240 - 31.5;
    startB.y = 160;
    startB.name = 'startB';

    creditsB.x = 241 - 42;
    creditsB.y = 200;

    TitleView.addChild(main, startB, creditsB);
    stage.addChild(bg, TitleView);
    stage.update();

    // Button Listeners

    startB.onPress = tweenTitleView;
    creditsB.onPress = showCredits;

}
function showCredits()
{
    // Show Credits

    credits.x = 480;

    stage.addChild(credits);
    stage.update();
    Tween.get(credits).to({x:0}, 300);
    credits.onPress = hideCredits;
}

// Hide Credits

function hideCredits(e)
{
    Tween.get(credits).to({x:480}, 300).call(rmvCredits);
}

// Remove Credits

function rmvCredits()
{
    stage.removeChild(credits);
}

// Tween Title View

function tweenTitleView()
{
    // Start Game

 Tween.get(TitleView).to({y:-320}, 300).call(addGameView);
}
<|endoftext|>