i6-historian
Version:
Historian plugins for i6
111 lines (92 loc) • 2.81 kB
JavaScript
var fs = require('fs');
var path = require('path');
module.exports = collector;
function collector(params){
this.description = params.description;
this.name = params.name;
this.interval = params.interval;
this.compress = params.compress;
this.autoStart = params.autostart;
this.delayStart = params.delay || 1000;
this.tags = params.tags;
this.globalModel = 'Collector' + params.name;
this.model = 'collector' + params.name.toLowerCase();
this._collecting = false;
generateCollector(this.globalModel);
if(this.autoStart){
setTimeout(method.start.bind(this), this.delayStart);
}
}
var method = collector.prototype;
method.start = function(){
sails.log.info('[i6-historian][' + this.name +'] Starting...');
this._collect();
};
method.stop = function(){
clearTimeout(this.timer);
};
method._collect = function(){
var collection = {}
this.tags.forEach(tag=>{
collection[tag] = i6.tags[tag].value;
});
sails.models[this.model].create(collection).exec((err,rows)=>{
this.timer = setTimeout(method._collect.bind(this), this.interval);
});
}
method._collectWithStatus = function(){
var collection = {}
this.tags.forEach(tag=>{
collection[tag] = {
value : i6.tags[tag].value,
status : i6.tags[tag].status
}
});
sails.models[this.model].create(collection).exec((err,rows)=>{
this.timer = setTimeout(method._collect.bind(this), this.interval);
});
}
/**
* Get collection
* @param {date} startTime
* @param {date} endTime
* @param {number} limit
* @param {array} req
* @param {string} sort
*/
method.get = function(cb, startTime, endTime,limit, req,sort){
var criteria = {};
var select = req;
criteria.time = {
'>=' : startTime,
'<=' : endTime
}
if(typeof(req)!=='undefined'){
criteria.select = select;
if (criteria.select.indexOf('time') == -1)
{
criteria.select.push('time');
}
}
if(typeof(limit)=='number'){
if(limit>0) criteria.limit = limit;
}
if(typeof(sort)=='string'){
criteria.sort = sort=='DESC'? 'createdAt DESC' : 'createdAt ASC';
}
sails.models[this.model].find(criteria).exec((err,records)=>{
if(err) sails.log.error('[i6-historian][' + this.name + '] Something wrong when getting collection');
cb(records);
});
}
/**
* Generate collector
* Just create some model for sails
* @param {string} name name of collector
*/
function generateCollector(name){
var _model = process.cwd() + '/api/models/' + name + '.js';
if (!fs.existsSync(_model)) {
fs.createReadStream(__dirname + '/collector-model.js').pipe(fs.createWriteStream(_model));
}
}