Skip to content

Commit

Permalink
Add more helper libs
Browse files Browse the repository at this point in the history
Add node-uuid module
Change logger code to generate more clean Homey Logger lines
  • Loading branch information
Inversion-NL committed Jan 24, 2017
1 parent ce8d397 commit 77d9b46
Show file tree
Hide file tree
Showing 19 changed files with 1,856 additions and 454 deletions.
724 changes: 296 additions & 428 deletions app.js

Large diffs are not rendered by default.

163 changes: 137 additions & 26 deletions lib/util.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,141 @@
exports.createAddressSpeech = function (place, city, name) {
var result = '';
if (name) result += __('speech.theLocationOf') + name + __('speech.is');

if (place && city) {
return result + place + __('speech.placeCityConjunction') + city
} else if (city) {
return result + city
} else if (place) {
return result + place
const Log = require('homey-log').Log;

const severity = {
debug: 1,
info: 2,
warning: 3,
error: 4,
critical: 5
};
exports.severity = severity;

/**
* Helper function to check if the variable is not undefined and null
* @param string Variable to check
* @returns {boolean} true when not undefined or null
*/
exports.value_exist = function (string) {
//noinspection RedundantIfStatementJS
if (typeof string != 'undefined' && string != null) return true;
else return false;
};

/**
* Logs the message to console.
* When the severity is error or above the message will also be logged to Athom online logging (Sentry atm).
* @param {string} message Message to log
* @param {int} level Message priority level
*/
exports.wuLog = function (message, level) {
if (!this.value_exist(level)) level = severity.debug;

if (level >= severity.error) Log.captureMessage(message);
this.debugLog(message);
};

/**
* Helper function to generate unique ID
* @returns {string} Returns unique ID
*/
exports.generateUniqueId = function () {
var uuid = require('node-uuid');
return uuid.v4();
};

/**
* Helper function to have Homey read the full word instead of the abbreviation
* @param text Abbreviation
* @returns {string} Returns long word
*/
exports.parseAbbreviations = function (text) {
// map with replace function parameters

if (Homey.manager('i18n').getLanguage() == 'nl') {
//noinspection SpellCheckingInspection,JSDuplicatedDeclaration
var replaceMap = [
['km/u', ' kilometer per uur'],
[' Z ', ' zuiden '],
[' ZW ', ' zuidwesten '],
[' WZW ', ' westzuidwesten '],
[' W ', ' westen '],
[' NW ', ' noordwesten '],
[' N ', ' noorden '],
[' NO ', ' noordoosten '],
[' O ', ' oosten '],
[' ZO ', ' zuidoosten '],
[/(.*?\d+)(C)\b/gi, function(match, g1) { return g1 + ' graden celcius'} ]
]
} else {
//noinspection JSDuplicatedDeclaration
var replaceMap = [
['mph', ' miles per hour'],
[' S ', ' south '],
[' SW ', ' south west '],
[' WSW ', ' west south west '],
[' W ', ' west '],
[' NW ', ' north west '],
[' N ', ' north '],
[' NE ', ' north east '],
[' E ', ' east '],
[' ZO ', ' south east '],
[/(.*?\d+)(C)\b/gi, function(match, g1) { return g1 + ' degrees celcius'} ]
]
}
return result + __('speech.positionUnknown')
};

exports.debugLog = function (message, data) {
var settings = Homey.manager('settings').get('teslaAccount');
var debugLog = Homey.manager('settings').get('teslaLog') || [];
if (settings && !settings.debug) return;
var logLine = {datetime: new Date(), message: message};
if (data) logLine.data = data;

// Push new event, remove items over 100 and save new array
debugLog.push(logLine);
if (debugLog.length > 100) debugLog.splice(0, 1);
Homey.log(this.epochToTimeFormatter(), message, data || '');
Homey.manager('settings').set('teslaLog', debugLog);
Homey.manager('api').realtime('teslaLog', logLine);

var result = text;
Object.keys(replaceMap).forEach(function (key) {
result = result.replace(replaceMap[key][0], replaceMap[key][1])
});

return result;
};

/**
* Helper function to convert epoch time to a date variable
* @param epoch Epoch time (in milli seconds)
* @returns {Date} Returns the date
*/
exports.epochToString = function (epoch) {
var date = new Date(0);
date.setUTCSeconds(epoch);
return date;
};

/**
* Helper function to calculates the difference between two values
* @param a Value 1
* @param b Value 2
* @returns {number} Returns the difference, 0 if something went wrong
*/
exports.diff = function (a,b) {
try {
return Math.abs(a-b);
} catch(err) {
util.wuLog('Error while calculating the difference between ' + JSON.stringify(a) + ' and ' + JSON.stringify(b), severity.debug);
return 0;
}
};

/**
* Helper function to check if a value is a integer
* @param value Value to check
* @returns {boolean} Returns true if integer
*/
exports.isInt = function (value) {
return !isNaN(value) &&
parseInt(Number(value)) == value &&
!isNaN(parseInt(value, 10));
};

/**
* Logs to Homey's log and exporting it to the app Homey Logger (if installed)
* @param message Message to log
*/
exports.debugLog = function (message) {
// Do not log empty lines to the Homey Logger app
if (message != '') Homey.manager('api').realtime('WU Log', message);

Homey.log('[' + this.epochToTimeFormatter() + ']', message)
};

exports.epochToTimeFormatter = function (epoch) {
Expand Down
27 changes: 27 additions & 0 deletions lib/weather.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
var util = require('./util.js');

const severity = util.severity;

/**
* Helper function to parse float from a string
* @param data
* @returns {*} Returns 0 if unable to parse, otherwise the parsed floating value
*/
exports.parseWeatherFloat = function (data){
var temp = parseFloat(data);
if (isNaN(temp)) return 0;
else return temp;
};

/**
* Helper function to test weather data
* @param data Data to test
* @returns {object} returns the weather object or a empty string the data was null or undefined
*/
exports.testWeatherData = function (data) {
if (!util.value_exist(data)) {
util.wuLog('Test weather data: Value was undefined or null, returning empty string', severity.debug);
return "";
}
else return data;
};
4 changes: 4 additions & 0 deletions node_modules/node-uuid/.npmignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 21 additions & 0 deletions node_modules/node-uuid/LICENSE.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 77d9b46

Please sign in to comment.