From dd0e14693957b8223c6eca13fe83759f5b08c300 Mon Sep 17 00:00:00 2001 From: marcus Date: Sat, 18 Jun 2016 18:24:45 +0200 Subject: [PATCH] Generated files --- API.md | 15 +++++++++++++++ lib/index.js | 33 ++++++++++++++++++++++++++++++++- 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/API.md b/API.md index fb869c1..54e3709 100644 --- a/API.md +++ b/API.md @@ -162,5 +162,20 @@ Schedules a given function which will not be called as long as it * **Number** *delay* - delay in milliseconds * **Function** *fn* - function to be called +## generateDeviceId([framework], prefix, framework, [lastId]) + +Generates a new device id which is not yet in use by another device + +### Params: + +* *[framework]* - the pimatic framework object. +* **String** *prefix* - a prefix string to be used as part of device id. +* **Integer** *framework* - the pimatic framework object. +* **String** *[lastId]* - the lastId returned by generateDeviceId + +### Return: + +* **String** the id generated or undefined if id could not be generated + diff --git a/lib/index.js b/lib/index.js index e7c58c2..4d589cb 100644 --- a/lib/index.js +++ b/lib/index.js @@ -227,7 +227,7 @@ module.exports = function(env) { return array; } output = {}; - for (key = i = 0, ref = array.length; 0 <= ref ? i < ref : i > ref; key = 0 <= ref ? ++i : --i) { + for (key = i = 0, ref = array.length; i < ref; key = i += 1) { output[array[key]] = array[key]; } results = []; @@ -271,6 +271,37 @@ module.exports = function(env) { return fn.call(device); }, delay); return Promise.resolve(); + }, + + /* + Generates a new device id which is not yet in use by another device + @param {*} [framework] - the pimatic framework object. + @param {String} prefix - a prefix string to be used as part of device id. + @param {Integer} framework - the pimatic framework object. + @param {String} [lastId] - the lastId returned by generateDeviceId + @returns {String} the id generated or undefined if id could not be generated + */ + generateDeviceId: function(framework, prefix, lastId) { + var i, m, matched, ref, result, start, x; + if (lastId == null) { + lastId = ''; + } + start = 1; + if ((lastId != null) && lastId !== '') { + m = lastId.match(/.*-([0-9]+)$/); + if ((m != null) && m.length === 2) { + start = +m[1] + 1; + } + } + for (x = i = ref = start; i < 1000; x = i += 1) { + result = prefix + "-" + x; + matched = framework.deviceManager.devicesConfig.some(function(element, iterator) { + return element.id === result; + }); + if (!matched) { + return result; + } + } } }; }