Skip to content

Commit

Permalink
Add tests and clean up
Browse files Browse the repository at this point in the history
  • Loading branch information
Connor Kennedy committed Jan 28, 2020
1 parent 019b9f6 commit 964e9f0
Show file tree
Hide file tree
Showing 4 changed files with 853 additions and 49 deletions.
78 changes: 32 additions & 46 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,98 +9,85 @@ const ICMPPingDefaults = {
ColorScalingInterval: 30, // Time gap in milliseconds between colors
GradientStops: 8, // Default granularity of gradient to be calculated
SuccessColor: '#00ff00', // Default color where an action has been successful
FailureColor: '#ff0000'//, // Default color when there has been a failure
FailureColor: '#ff0000' // Default color when there has been a failure
};

class ICMPPing extends q.DesktopApp {
constructor() {
super();
this.pollingInterval = 1000 * this.getPollingIntervalSeconds();
this.gradientArray = this.generateGradientArray();
logger.info("ICMP Ping applet initialized");
}

async run() {
return this.getPingAddress()
.then(address => this.ping(address))
.then(avgResponseTime => ICMPPing.buildSignal(this.config.pingAddress, this.getColor(avgResponseTime), avgResponseTime))
.catch(err => {
logger.error(`Error while pinging ${this.config.pingAddress}: ${err}`);
return ICMPPing.buildSignal(this.config.pingAddress, ICMPPingDefaults.FailureColor, null, err);
});
return await new Promise((resolve, reject) => {
this.ping(this.config.pingAddress)
.then(avgResponseTime => resolve(ICMPPing.buildSignal(this.config.pingAddress, this.getColor(avgResponseTime), avgResponseTime)))
.catch(err => {
logger.error(`Error while pinging ${this.config.pingAddress}: ${err}`);
return reject(ICMPPing.buildSignal(this.config.pingAddress, ICMPPingDefaults.FailureColor, null, err));
});
});
}

async applyConfig() {
return this.getPingAddress()
.then(address => this.ping(address, 1))
.then(data => logger.info('Configuration updated'))
.catch(err => {
logger.error(`Error while applying configuration: ${err}`);
return false;
});
}

async getPingAddress() {
return this.config.pingAddress ?
Promise.resolve(this.config.pingAddress) :
Promise.reject();
this.pollingInterval = 1000 * this.pollingIntervalSeconds;
this.gradientArray = this.generateGradientArray();
}

getPollingIntervalSeconds() {
get pollingIntervalSeconds(){
return JSON.parse(this.config.pollingIntervalSeconds || ICMPPingDefaults.PollingIntervalSeconds);
}

getPingCount(){
get pingCount(){
return JSON.parse(this.config.pingCount || ICMPPingDefaults.PingCount);
}

getMinPing(){
get minPing(){
return JSON.parse(this.config.minimumPing || ICMPPingDefaults.MinimumPing);
}

getColorScalingInterval(){
get colorScalingInterval(){
return JSON.parse(this.config.colorScalingInterval || ICMPPingDefaults.ColorScalingInterval);
}

getGradientStops(){
get gradientStops(){
return JSON.parse(this.config.gradientStops || ICMPPingDefaults.GradientStops);
}

getFastColor(){
get fastColor(){
return this.config.fastColor || ICMPPingDefaults.SuccessColor;
}

getSlowColor(){
get slowColor(){
return this.config.slowColor || ICMPPingDefaults.FailureColor;
}

isXClockwiseGradient(){
get isXClockwiseGradient(){
return !!this.config.counterClockwiseGradient;
}

get isWindows(){
return process.platform == 'win32';
}

getColor(avgResponseTime) {
const minPing = this.getMinPing();
const scalingInterval = this.getColorScalingInterval();
let arrIndx = Math.floor(Math.abs(((avgResponseTime - minPing) / scalingInterval) + 1))
const minPing = this.minPing;
const scalingInterval = this.colorScalintInterval;
let arrIndx = Math.floor(Math.abs(((avgResponseTime - minPing) / scalingInterval) + 1));
return this.gradientArray[arrIndx < this.gradientArray.length ? arrIndx : this.gradientArray.length - 1];
}

generateGradientArray(){
let gradient = tinygradient([ // Define a simple gradient between the two colors
{ color: this.getFastColor(), pos: 0 }, // Fast color first as we calculate
{ color: this.getSlowColor(), pos: 1 } // from fast->slow when selecting colors
{ color: this.fastColor, pos: 0 }, // Fast color first as we calculate
{ color: this.slowColor, pos: 1 } // from fast->slow when selecting colors
]);
// Calculate array of points on gradient for key colors and convert them to hex
return gradient.hsv(this.getGradientStops(), this.isXClockwiseGradient()).map((el) => el.toHexString());
}

isWindows(){
return process.platform == 'win32';
return gradient.hsv(this.gradientStops, this.isXClockwiseGradient).map((el) => el.toHexString());
}

async ping(address, count){
let pingCount = !!count ? count : this.getPingCount();
let pingCountArg = this.isWindows() ? '-n' : '-c';
let pingCount = !!count ? count : this.pingCount;
let pingCountArg = this.isWindows ? '-n' : '-c';
return new Promise((resolve, reject) => {
childprocess.exec(`ping ${address} ${pingCountArg} ${pingCount}`, (err, stdout, stderr) => {
if (err){
Expand All @@ -112,14 +99,13 @@ class ICMPPing extends q.DesktopApp {
let pingAverage = pingTimes.reduce((a, b) => JSON.parse(a) + JSON.parse(b), 0) / pingTimes.length;
if (!pingAverage)
return reject(`Unable to calculate ping due to invalid ping time data: ${times.replace(/(?:\r\n|\r|\n)/g, ' ')}`);
logger.info(`Average response time for ${address} is ${pingAverage.toFixed(2)}ms`)
return resolve(pingAverage);
});
});
}

static buildSignal(address, color, avgResponseTime, err) {
if ( !(typeof err === 'undefined') || (avgResponseTime == null)){
if (typeof err !== 'undefined' || avgResponseTime == null){
return q.Signal.error([`Error while pinging ${address}`]);
}
return new q.Signal({
Expand Down
Loading

0 comments on commit 964e9f0

Please sign in to comment.