cordova-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From bhigg...@apache.org
Subject [2/2] webworks commit: [CB-4344] Auto-detect started simulator
Date Mon, 12 Aug 2013 15:34:52 GMT
[CB-4344] Auto-detect started simulator

- check VMware dhcp.leases file for possible started simulator
- fix lint
- update device detection
- Fixed debugtoken-helper deploy method due to the missing target password in the properties
file


Project: http://git-wip-us.apache.org/repos/asf/cordova-blackberry/repo
Commit: http://git-wip-us.apache.org/repos/asf/cordova-blackberry/commit/b0941650
Tree: http://git-wip-us.apache.org/repos/asf/cordova-blackberry/tree/b0941650
Diff: http://git-wip-us.apache.org/repos/asf/cordova-blackberry/diff/b0941650

Branch: refs/heads/master
Commit: b094165016eea43e710c1ad01a5964a874cfe1d9
Parents: 9a766e0
Author: Eric Li <eli@blackberry.com>
Authored: Thu Aug 8 14:01:46 2013 -0400
Committer: Bryan Higgins <bhiggins@blackberry.com>
Committed: Mon Aug 12 11:33:55 2013 -0400

----------------------------------------------------------------------
 blackberry10/bin/lib/utils.js                   |  36 ++++-
 .../project/cordova/lib/debugtoken-helper.js    | 104 +++-----------
 .../bin/templates/project/cordova/lib/run       | 136 +++++++++----------
 .../project/cordova/lib/signing-helper.js       |   2 +-
 .../project/cordova/lib/target-utils.js         | 116 +++++++++++++---
 5 files changed, 217 insertions(+), 177 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cordova-blackberry/blob/b0941650/blackberry10/bin/lib/utils.js
----------------------------------------------------------------------
diff --git a/blackberry10/bin/lib/utils.js b/blackberry10/bin/lib/utils.js
index 4f4a500..04fd6f3 100644
--- a/blackberry10/bin/lib/utils.js
+++ b/blackberry10/bin/lib/utils.js
@@ -94,6 +94,40 @@ _self = {
         return filteredFiles;
     },
 
+    readdirSyncRecursive: function (baseDir) {
+        var files = [],
+            curFiles = [],
+            nextDirs,
+            isDir = function (f) {
+                return fs.statSync(f).isDirectory();
+            },
+            isFile = function (f) {
+                return !isDir(f);
+            },
+            prependBaseDir = function (fname) {
+                return path.join(baseDir, fname);
+            };
+
+        try {
+            curFiles = fs.readdirSync(baseDir);
+
+            if (curFiles && curFiles.length > 0) {
+                curFiles = curFiles.map(prependBaseDir);
+                nextDirs = curFiles.filter(isDir);
+                curFiles = curFiles.filter(isFile);
+
+                files = files.concat(curFiles);
+
+                while (nextDirs.length) {
+                    files = files.concat(_self.readdirSyncRecursive(nextDirs.shift()));
+                }
+            }
+        } catch (e) {
+        }
+
+        return files;
+    },
+
     isWindows: function () {
         return os.type().toLowerCase().indexOf("windows") >= 0;
     },
@@ -213,7 +247,7 @@ _self = {
         fs.writeFileSync(propertiesFile, contents, 'utf-8');
     },
 
-    genBarName: function() {
+    genBarName: function () {
         return DEFAULT_BAR_NAME;
     }
 

http://git-wip-us.apache.org/repos/asf/cordova-blackberry/blob/b0941650/blackberry10/bin/templates/project/cordova/lib/debugtoken-helper.js
----------------------------------------------------------------------
diff --git a/blackberry10/bin/templates/project/cordova/lib/debugtoken-helper.js b/blackberry10/bin/templates/project/cordova/lib/debugtoken-helper.js
index 206bd58..af42fce 100755
--- a/blackberry10/bin/templates/project/cordova/lib/debugtoken-helper.js
+++ b/blackberry10/bin/templates/project/cordova/lib/debugtoken-helper.js
@@ -26,7 +26,6 @@ var childProcess = require("child_process"),
     debugTokenDir = path.normalize(path.join(utils.getCordovaDir(), "blackberry10debugtoken.bar")),
     properties,
     targets,
-    deployCallback,
     self = {};
 
 function isDebugTokenValid(pin, data) {
@@ -44,11 +43,11 @@ function isDebugTokenValid(pin, data) {
 
     manifests = data.toString().replace(/[\r]/g, '').split('\n');
 
-    for (i=0, l=manifests.length; i<l; i++) {
+    for (i = 0, l = manifests.length; i < l; i++) {
         if (manifests[i].indexOf("Debug-Token-Expiry-Date: ") >= 0) {
             // Parse the expiry date
             line = manifests[i].substring("Debug-Token-Expiry-Date: ".length);
-            expiry = new Date(line.substring(0, line.indexOf("T")) + " " + line.substring(line.indexOf("T")
+ 1, line.length -1) + " UTC");
+            expiry = new Date(line.substring(0, line.indexOf("T")) + " " + line.substring(line.indexOf("T")
+ 1, line.length - 1) + " UTC");
         } else if (manifests[i].indexOf("Debug-Token-Device-Id: ") >= 0) {
             line = manifests[i].substring("Debug-Token-Device-Id: ".length);
             devices = line.split(",");
@@ -56,7 +55,7 @@ function isDebugTokenValid(pin, data) {
     }
 
     if (expiry && expiry > now) {
-        for (i=0, l=devices.length; i<l; i++) {
+        for (i = 0, l = devices.length; i < l; i++) {
             if (parseInt(devices[i]) === parseInt(pin, 16)) {
                 return true; // The debug token is valid if not expired and device pin is
included
             }
@@ -83,24 +82,26 @@ function generateCreateTokenOptions(pins, password) {
     return options;
 }
 
-function generateDeployTokenOptions(target) {
+function generateDeployTokenOptions(targetIp, targetPassword) {
     var options = [];
 
     options.push("-installDebugToken");
     options.push(debugTokenDir);
 
     options.push("-device");
-    options.push(properties.targets[target].ip);
+    options.push(targetIp);
 
-    options.push("-password");
-    options.push(properties.targets[target].password);
+    if (targetPassword) {
+        options.push("-password");
+        options.push(targetPassword);
+    }
 
     return options;
 }
 
 function execNativeScript(script, options, callback) {
-    var cp;
-        script = utils.inQuotes(path.join(process.env.CORDOVA_BBTOOLS, script));
+    var cp,
+        script = path.join(process.env.CORDOVA_BBTOOLS, script);
 
     if (pkgrUtils.isWindows()) {
         script += ".bat";
@@ -122,49 +123,6 @@ function execNativeScript(script, options, callback) {
     });
 }
 
-function checkTarget(target) {
-    if (!properties.targets[target]) {
-        logger.warn(localize.translate("WARN_TARGET_NOT_EXIST", target));
-        return false;
-    }
-
-    if (!properties.targets[target].ip) {
-        logger.warn(localize.translate("WARN_IP_NOT_DEFINED", target));
-        return false;
-    }
-
-    if (!properties.targets[target].password) {
-        logger.warn(localize.translate("WARN_PASSWORD_NOT_DEFINED", target));
-        return false;
-    }
-
-    return true;
-
-}
-
-// Deploy the debug token for each target in targets array recursively
-function deployTokenToTargetsRecursively() {
-    var target;
-
-    if (targets.length > 0) {
-        target = targets.pop();
-
-        logger.info(localize.translate("PROGRESS_DEPLOYING_DEBUG_TOKEN", target));
-        if (checkTarget(target)) {
-            execNativeScript("blackberry-deploy",
-                generateDeployTokenOptions(target),
-                deployTokenToTargetsRecursively
-            );
-        } else {
-            deployTokenToTargetsRecursively();
-        }
-    } else {
-        if (deployCallback && typeof deployCallback === "function") {
-            deployCallback();
-        }
-    }
-}
-
 self.createToken = function (projectProperties, target, keystorepass, callback) {
     var pins = [],
         key;
@@ -209,38 +167,12 @@ self.createToken = function (projectProperties, target, keystorepass,
callback)
     }
 };
 
-self.deployToken = function (projectProperties, target, callback) {
-    var key;
-
-    // Store the global variable "properties"
-    properties = projectProperties;
-
-    // Initialize the global variable "targets"
-    targets = [];
-
-    // Store callback so it will be invoked after debug token is deployed to all target(s)
-    deployCallback = callback;
-
-    // Gather targets information from properties
-    // Gather PINs information from properties
-    if (target === "all") {
-        for (key in properties.targets) {
-            if (properties.targets.hasOwnProperty(key) && properties.targets[key].pin)
{
-                targets.push(key);
-            }
-        }
-    } else {
-        if (!target) {
-            target = properties.defaultTarget;
-        }
-
-        if (properties.targets.hasOwnProperty(target) && properties.targets[target].pin)
{
-            targets.push(target);
-        }
-    }
-
-    // Deploy debug token recursively
-    deployTokenToTargetsRecursively();
+self.deployToken = function (target, targetIp, targetPassword, callback) {
+    logger.info(localize.translate("PROGRESS_DEPLOYING_DEBUG_TOKEN", target));
+    execNativeScript("blackberry-deploy",
+        generateDeployTokenOptions(targetIp, targetPassword),
+        callback
+    );
 };
 
 self.checkDebugToken = function (pin, callback) {
@@ -260,7 +192,7 @@ self.checkDebugToken = function (pin, callback) {
         script += ".bat";
     }
 
-    nativePackager = childProcess.exec(path.normalize(script +" -listManifest " + debugTokenDir),
{
+    nativePackager = childProcess.exec(path.normalize(script + " -listManifest " + debugTokenDir),
{
         "cwd": workingDir,
         "env": process.env
     }, function (error, stdout, stderr) {

http://git-wip-us.apache.org/repos/asf/cordova-blackberry/blob/b0941650/blackberry10/bin/templates/project/cordova/lib/run
----------------------------------------------------------------------
diff --git a/blackberry10/bin/templates/project/cordova/lib/run b/blackberry10/bin/templates/project/cordova/lib/run
index e604dd5..3ec1b45 100755
--- a/blackberry10/bin/templates/project/cordova/lib/run
+++ b/blackberry10/bin/templates/project/cordova/lib/run
@@ -42,8 +42,8 @@ var childProcess = require("child_process"),
     workingdir = path.normalize(__dirname + "/..");
 
 function generateOptions(uninstall) {
-    var options = [];
-    barPath = pkgrUtils.escapeStringForShell(path.normalize(__dirname + "/../../build/" +
targets.targets[target].type + "/" + utils.genBarName() + ".bar"));
+    var options = [],
+        barPath = pkgrUtils.escapeStringForShell(path.normalize(__dirname + "/../../build/"
+ targets.targets[target].type + "/" + utils.genBarName() + ".bar"));
 
     options.push("-device");
     options.push(ip);
@@ -73,14 +73,14 @@ function generateOptions(uninstall) {
 
 function execNativeDeploy(optionsArray, callback) {
     var script = utils.inQuotes(path.join(process.env.CORDOVA_BBTOOLS, "blackberry-deploy")),
-        nativeDeploy;
+        nativeDeploy,
         options = optionsArray.join(" ");
 
     if (pkgrUtils.isWindows()) {
         script += ".bat";
     }
 
-    nativeDeploy = childProcess.exec(path.normalize(script +" "+ options), {
+    nativeDeploy = childProcess.exec(path.normalize(script + " " + options), {
         "cwd": workingdir,
         "env": process.env
     });
@@ -96,56 +96,55 @@ function execNativeDeploy(optionsArray, callback) {
     });
 }
 
-function setTarget(callback) {
+function checkDeviceInfo(ip, deviceType, callback) {
     var props = utils.getProperties(),
         targetName;
 
+    targetUtils.getDeviceInfo(ip, program["devicepass"], function (device) {
+        if (device.name) {
+            targetName = device.name + "-" + device.pin;
+            props.targets[targetName] = {
+                ip: ip,
+                pin: device.pin,
+                type: deviceType
+            };
+            utils.writeToPropertiesFile(props);
+            target = targetName;
+            callback();
+        } else {
+            if (deviceType === "device") {
+                console.error("Unable to authenticate with device at " + ip);
+            } else {
+                console.error("Unable to authenticate with simulator at " + ip);
+            }
+
+            if (!program["devicepass"]) {
+                console.error("Please provide device password using --devicepass");
+            }
+
+            process.exit(1);
+        }
+    });
+}
 
+function setTarget(callback) {
     target = program.args[0] ? program.args[0] : targets.defaultTarget;
     if (program["device"]) {
-        targetUtils.getTargetList("device", true, function (targets) {
-            if (targets && targets.length > 0) {
-                target = targets[0].name;
-                callback();
+        targetUtils.findConnectedDevice(function (ip) {
+            if (!ip) {
+                console.error("No connected device found");
+                process.exit(1);
             } else {
-                targetUtils.findConnectedDevice(function (ip) {
-                    if (!ip) {
-                        console.error("No connected device found");
-                        process.exit(1);
-                    } else {
-                        targetUtils.getDeviceInfo(ip, program["password"], function (device)
{
-                            if (device.name) {
-                                targetName = device.name + "-" + device.pin;
-                                props.targets[targetName] = {
-                                    ip: ip,
-                                    pin: device.pin,
-                                    type: "device",
-                                    password: program["password"]
-                                };
-                                utils.writeToPropertiesFile(props);
-                                target = targetName;
-                                callback();
-                            } else {
-                                console.error("Unable to authenticate with device at " +
ip);
-                                if (!program["password"]) {
-                                    console.error("Please provide device password using --password");
-                                }
-                                process.exit(1);
-                            }
-                        });
-                    }
-                });
+                checkDeviceInfo(ip, "device", callback);
             }
         });
     } else if (program["emulator"]) {
-        targetUtils.getTargetList("simulator", true, function (targets) {
-            if (targets && targets.length > 0) {
-                target = targets[0].name;
-                callback();
-            } else {
-                console.error("No connected BB10 simulator found");
-                console.error("Simulators must first be configured using platforms/blackberry/cordova/target");
+        targetUtils.findConnectedSimulator(function (ip) {
+            if (!ip) {
+                console.error("No connected BlackBerry 10 simulator found");
                 process.exit(1);
+            } else {
+                checkDeviceInfo(ip, "simulator", callback);
             }
         });
     } else {
@@ -160,23 +159,36 @@ function checkTarget() {
         return false;
     }
     if (!targets.targets[target]) {
-        console.log("The target \""+target+"\" does not exist, to add that target please
run target add "+target+" <ip> [-t | --type <device | simulator>] [-p <password>]
[--pin <devicepin>]");
+        console.log("The target \"" + target + "\" does not exist, to add that target please
run target add " + target + " <ip> [-t | --type <device | simulator>] [-p <password>]
[--pin <devicepin>]");
         console.log(program.helpInformation());
         return false;
     }
     if (targets.targets[target].ip) {
-       ip = targets.targets[target].ip;
+        ip = targets.targets[target].ip;
     } else {
-        console.log("IP is not defined in target \""+target+"\"");
+        console.log("IP is not defined in target \"" + target + "\"");
         console.log(program.helpInformation());
         return false;
     }
     if (targets.targets[target].password) {
-       password = targets.targets[target].password;
+        password = targets.targets[target].password;
+    } else {
+        password = program["devicepass"];
     }
     return true;
 }
 
+function deploy() {
+    var options = generateOptions(false);
+    execNativeDeploy(options, function (code) {
+        if (code) {
+            process.exit(2);
+        } else {
+            process.exit(0);
+        }
+    });
+}
+
 function uninstall() {
     var script = utils.inQuotes(path.join(process.env.CORDOVA_BBTOOLS, "blackberry-deploy")),
         nativeDeploy;
@@ -185,18 +197,17 @@ function uninstall() {
         script += ".bat";
     }
 
-    nativeDeploy = childProcess.exec(script +" -listInstalledApps -device " +ip+ " -password
" +password, {
+    nativeDeploy = childProcess.exec(script + " -listInstalledApps -device " + ip + " -password
" + password, {
         "cwd": workingdir,
         "env": process.env
     }, function (error, stdout, stderr) {
         var parser = new xml2js.Parser();
-        fs.readFile(path.join(__dirname + "/../../www/", "config.xml"), function(err, data)
{
+        fs.readFile(path.join(__dirname + "/../../www/", "config.xml"), function (err, data)
{
             parser.parseString(data, function (err, result) {
-                if (stdout.indexOf(result['@'].id) != -1) {
+                if (stdout.indexOf(result['@'].id) !== -1) {
                     var options = generateOptions(true);
-                    execNativeDeploy(options,
-                        function(){
-                            deploy();
+                    execNativeDeploy(options, function () {
+                        deploy();
                     });
                 } else {
                     deploy();
@@ -206,17 +217,6 @@ function uninstall() {
     });
 }
 
-function deploy() {
-    options = generateOptions(false);
-    execNativeDeploy(options, function (code) {
-        if (code) {
-            process.exit(2);
-        } else {
-            process.exit(0);
-        }
-    });
-}
-
 function checkDebugtoken(previous, baton) {
     baton.take();
 
@@ -253,7 +253,7 @@ function createDebugToken(previous, baton) {
             baton.pass();
         });
     } else {
-            baton.pass();
+        baton.pass();
     }
 }
 
@@ -262,7 +262,7 @@ function deployDebugToken(previous, baton) {
 
     // If in debug build and debug token was created, deploy the debug token and wait until
the deployment is finished
     if (needDeployDebugToken) {
-        debugTokenHelper.deployToken(targets, target, function () {
+        debugTokenHelper.deployToken(target, ip, password, function () {
             baton.pass();
         });
     } else {
@@ -314,11 +314,11 @@ function postBuild() {
 
 function exec() {
     program
-        .usage('[--device] [--emulator] [--password] [--target=<id>] [-k | --keystorepass]
[--no-launch] [--no-uninstall] [--no-build]')
+        .usage('[--device] [--emulator] [--devicepass] [--target=<id>] [-k | --keystorepass]
[--no-launch] [--no-uninstall] [--no-build]')
         .option('-k, --keystorepass <password>', 'the password of signing key; needed
for creating debug token')
         .option('--device', 'run on connected device')
         .option('--emulator', 'run on BB10 simulator')
-        .option('--password <password>', 'device password')
+        .option('--devicepass <password>', 'device password')
         .option('--target', 'specifies the target to run the application')
         .option('--no-uninstall', 'does not uninstall application from device')
         .option('--no-launch', 'do not launch the application on device')

http://git-wip-us.apache.org/repos/asf/cordova-blackberry/blob/b0941650/blackberry10/bin/templates/project/cordova/lib/signing-helper.js
----------------------------------------------------------------------
diff --git a/blackberry10/bin/templates/project/cordova/lib/signing-helper.js b/blackberry10/bin/templates/project/cordova/lib/signing-helper.js
index 73b17df..2fce263 100644
--- a/blackberry10/bin/templates/project/cordova/lib/signing-helper.js
+++ b/blackberry10/bin/templates/project/cordova/lib/signing-helper.js
@@ -62,7 +62,7 @@ function getDefaultPath(file) {
 }
 
 function execSigner(session, target, callback) {
-    var script = utils.inQuotes(path.join(process.env.CORDOVA_BBTOOLS, "blackberry-signer")),
+    var script = path.join(process.env.CORDOVA_BBTOOLS, "blackberry-signer"),
         signer,
         params = session.getParams("blackberry-signer"),
         args = [];

http://git-wip-us.apache.org/repos/asf/cordova-blackberry/blob/b0941650/blackberry10/bin/templates/project/cordova/lib/target-utils.js
----------------------------------------------------------------------
diff --git a/blackberry10/bin/templates/project/cordova/lib/target-utils.js b/blackberry10/bin/templates/project/cordova/lib/target-utils.js
index 535a104..cd6829f 100644
--- a/blackberry10/bin/templates/project/cordova/lib/target-utils.js
+++ b/blackberry10/bin/templates/project/cordova/lib/target-utils.js
@@ -16,6 +16,7 @@
 
 var _self,
     os = require("os"),
+    fs = require('fs'),
     exec = require('child_process').exec,
     path = require('path'),
     bb10_utils = require('./utils'),
@@ -30,6 +31,11 @@ _self = {
                 targets[t].name = t;
                 targList.push(targets[t]);
             },
+            complete = function () {
+                if (count === Object.keys(targets).length) {
+                    callback(targList);
+                }
+            },
             checkConnection = function (name) {
                 _self.checkConnection(targets[name].ip, type, function (connected) {
                     count++;
@@ -39,11 +45,6 @@ _self = {
                     complete();
                 });
             },
-            complete = function () {
-                if (count === Object.keys(targets).length) {
-                    callback(targList);
-                }
-            },
             t;
 
         if (targets) {
@@ -64,29 +65,30 @@ _self = {
         complete();
     },
 
-    getDeviceInfo: function(ip, password, callback) {
+    getDeviceInfo: function (ip, password, callback) {
         var cmd = path.join(process.env.CORDOVA_BBTOOLS, 'blackberry-deploy') + ' -listDeviceInfo
' + ip;
         if (password) {
             cmd += ' -password ' + password;
         }
-        exec(cmd, function(error, stdout, stderr) {
+        exec(cmd, function (error, stdout, stderr) {
             var result = {},
-                name = /modelname::(.*?)\n/.exec(stdout),
-                pin = /devicepin::0x(.*?)\n/.exec(stdout);
+                name = /modelname::(.*?)(\r?)\n/.exec(stdout),
+                pin = /devicepin::0x(.*?)(\r?)\n/.exec(stdout);
             if (name && name.length > 0) {
                 result.name = name[1];
             }
             if (pin && pin.length > 0) {
                 result.pin = pin[1];
             }
+
             callback(result);
         });
     },
 
-    findConnectedDevice: function(callback) {
+    findConnectedDevice: function (callback) {
         var defaultIp = '169.254.0.1';
         _self.discoverUsb(function (result) {
-           if (result) {
+            if (result) {
                 _self.checkConnection(result, 'device', function (connection) {
                     if (connection)  {
                         callback(result);
@@ -106,7 +108,7 @@ _self = {
         });
     },
 
-    discoverUsb: function(callback) {
+    discoverUsb: function (callback) {
         var IPV4_TYPE = "IPv4",
             IP_SPLIT_REGEXP = /(169\.254\.\d{1,3}\.)(\d{1,3})/,
             networkInterfaces = os.networkInterfaces(),
@@ -116,11 +118,11 @@ _self = {
 
         for (ni in networkInterfaces) {
             if (networkInterfaces.hasOwnProperty(ni)) {
-                for (i=0; i< networkInterfaces[ni].length; i++) {
+                for (i = 0; i < networkInterfaces[ni].length; i++) {
                     if (networkInterfaces[ni][i].family === IPV4_TYPE) {
                         result = IP_SPLIT_REGEXP.exec(networkInterfaces[ni][i].address);
                         if (result && result[1] && result[2]) {
-                            callback(result[1] + (result[2] -1));
+                            callback(result[1] + (result[2] - 1));
                             return;
                         }
                     }
@@ -132,18 +134,90 @@ _self = {
         callback();
     },
 
-    checkConnection: function(ip, type, callback) {
-        var script = bb10_utils.inQuotes(path.join(process.env.CORDOVA_BBTOOLS, 'blackberry-deploy'));
-        exec(script + ' -test ' + ip, function(error, stdout, stderr) {
-            // error code 3 corresponds to a connected device, null corresponds to connected
sim
-            callback((type === 'simulator' && error === null) || (type == 'device'
&& error.code === 3));
+    findConnectedSimulator: function (callback) {
+        var pathVmDhcpLeases,
+            pathUserProfile,
+            pathAllUserProfile,
+            vmDhcpLeasesFiles,
+            DHCP_LEASES_REGEX = /VMware\\vmnetdhcp.leases$/,
+            targets = blackberryProperties.targets,
+            ipsToTest = [],
+            dhcpIPs = [],
+            t;
+
+        // Firstly, check targets in the properties file
+        if (targets) {
+            for (t in targets) {
+                if (targets.hasOwnProperty(t) && targets[t].type === "simulator"
&& targets[t].ip) {
+                    ipsToTest.push(targets[t].ip);
+                }
+            }
+        }
+
+        // Secondly, check VMware dhcp.leases file
+        if (bb10_utils.isWindows()) {
+            pathUserProfile = process.env['USERPROFILE'];
+            pathAllUserProfile = pathUserProfile.substr(0, pathUserProfile.lastIndexOf("\\")
+ 1) + "All Users";
+            vmDhcpLeasesFiles = bb10_utils.readdirSyncRecursive(pathAllUserProfile).filter(function
(file) {
+                return DHCP_LEASES_REGEX.test(file);
+            });
+            pathVmDhcpLeases = vmDhcpLeasesFiles[0];
+        } else {
+            pathVmDhcpLeases = "/private/var/db/vmware/vmnet-dhcpd-vmnet8.leases";
+        }
+
+        fs.readFile(pathVmDhcpLeases, 'utf8', function (err, data) {
+            if (!err) {
+                // Find all lines that start with "lease xxx.xxx.xxx.xxx "
+                dhcpIPs = data.match(/lease \d{1,3}.\d{1,3}.\d{1,3}.\d{1,3} /g);
+                dhcpIPs = dhcpIPs.map(function (result) {
+                    return result.substr(6, result.indexOf(' ', 7) - 6);
+                });
+            }
+
+            ipsToTest = ipsToTest.concat(dhcpIPs);
+            // Remove duplicated ip
+            ipsToTest = ipsToTest.filter(function (item, index, arr) {
+                return arr.indexOf(item) === index;
+            });
+
+            _self.checkConnectionRecursive(ipsToTest, 0, callback);
+        });
+    },
+
+    checkConnectionRecursive: function (ips, index, callback) {
+        var ip;
+
+        if (!ips || index === ips.length) {
+            callback();
+            return;
+        }
+
+        console.log("Searching for connected BlackBerry 10 Simulator (" + (index + 1) + "/"
+ ips.length + ")...");
+        ip = ips[index];
+        _self.checkConnection(ip, "simulator", function (connection) {
+            if (connection) {
+                callback(ip);
+            } else {
+                _self.checkConnectionRecursive(ips, index + 1, callback);
+            }
         });
     },
 
-    listTargets : function(type, pruneDisconnected) {
+    checkConnection: function (ip, type, callback) {
+        var script = path.join(process.env.CORDOVA_BBTOOLS, 'blackberry-deploy');
+        exec(script + ' -test ' + ip, function (error, stdout, stderr) {
+            // error code 3 corresponds to a connected device, null or "Error: null" in stderr
corresponds to connected simulator
+            callback((type === 'simulator' && (error === null || stderr.length ===
0 || stderr.indexOf('Error: null') >= 0 || stderr.indexOf('Error: Authentication failed')
>= 0)) || (type === 'device' && error.code === 3));
+        });
+    },
+
+    listTargets : function (type, pruneDisconnected) {
         _self.getTargetList(type, pruneDisconnected, function (targets) {
             for (var t in targets) {
-                console.log(targets[t].name + ' ip: ' + targets[t].ip);
+                if (targets.hasOwnProperty(t)) {
+                    console.log(targets[t].name + ' ip: ' + targets[t].ip);
+                }
             }
         });
     }


Mime
View raw message