Scan WiFi network
@return {Promise} Return list of access points
354795
function scanWiFi() {
    return new Promise((ac) => {
        // WiFi scan
        exec('nmcli dev wifi list', (err, stdout, stderr) => {
            // eslint-disable-next-line max-len
            if (err) log('Cannot scan Wifi APs (possibly because "nmcli dev wifi list" command requires sudo?)');
            let lines = stdout.split('\n');
            const aps = [];
            lines.shift();
            lines.forEach((line)=>{
                let li = line.indexOf('Infra');
                if (li==-1) li = line.indexOf('インフラ');
                if (li==-1) return;
                let sp = line.slice(0, li).trim();
                if (sp[0]=='*') sp = sp.slice(1).trim();
                if (sp == '--') return;
                aps.push(sp);
            });
            ac(aps);
        });
    });
}
394414
public static String getMacAddr(Context context) {
        String mac = "";
        try {
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifi = wifiManager.getConnectionInfo();
            mac = wifi.getMacAddress();
        } catch (Exception e) {
            mac = null;
            Log.e(TAG, "", e);
        }

        if (StringUtils.isNullOrEmpty(mac))
            mac = getLocalMacAddressFromBusybox();

        if (StringUtils.isNullOrEmpty(mac))
            mac = MAC_EMPTY;

        return mac;
    }
1284328
function addCachedScanResults(bundle) {
        debugLFDS('In Add Cached Scan Results');
        
        var defered = q.defer();
        var scannedData = bundle.scannedData;
        var cScannedData;
        if(self.cachedScanBundle) {
            if(self.cachedScanBundle.scannedData) {
                cScannedData = self.cachedScanBundle.scannedData;
            } else {
                cScannedData = {};
            }
        } else {
            cScannedData = {};
        }

        debugLFDS('Cached Connection Types:');
        printScannedDataConnectionTypes(cScannedData);
        debugPrintFlatScannedData(cScannedData, debugLFDS);
        debugMACT('!!! In addCachedScanResults');
        debugPrintFlatScannedData(cScannedData, debugMACT);
        // console.log('Current Devices', self.cachedCurrentDevices);
        // console.log('Current bundle', bundle.scannedData);
        

        var cKeys = Object.keys(cScannedData);
        cKeys.forEach(function(cKey) {
            if(scannedData[cKey]) {
                debugLFDS('We already have the key', cKey);
                // If the key exists we need to transfer data about the device
                // connection types.  The only reason why the key would exist
                // already is if the device is open due to no scans having been
                // performed.  

                // The situation that this branch needs to cover is if a currently
                // connected device is found to have valid Ethernet/WiFi connections.
                // Due to no scan having been performed, the types WILL show up
                // as "added by attribute".  If the cached scan had them showing
                // up as 'scan' then that information should be indicated as such.
                /* 
                 * Need to update the following keys:
                 * numConnectionTypes (int) ex: 1
                 * connectionTypeNames (String Array) ex: ['Ethernet']
                 * unverifiedConnectionTypes (Object array) [object]
                 * unverifiedConnectionTypeNames (String Array) ex: ['Ethernet']
                 * verifiedConnectionTypeNames: [],
                 * connectionTypes (object array) [object]
                 */

                 // On second thought, due to this case being run into due to
                 // the device's handle being open.  Lets ignore it.  The previous
                 // scan data may be invalid and we should only use the latest
                 // scan data.  If a user wants re-freshed data, then they should
                 // perform a new scan.
            } else {
                debugLFDS('We dont have the key', cKey);
                // If the key doesn't exist then copy over the data.
                scannedData[cKey] = cScannedData[cKey];
            }
        });

        bundle.scannedData = scannedData;
        // console.log('New bundle', bundle);
        // console.log('Scanned Data', scannedData);
        if(DEBUG_MARKING_ACTIVE_CONNECTION_TYPES) {
            var sDKeys = Object.keys(scannedData);
            var foundActiveConnection = false;
            var activeConnection = {
                'sn': 0,
                'ct': {},
            };

            sDKeys.forEach(function(key) {
                var dev = scannedData[key];
                dev.connectionTypes.forEach(function(ctInfo) {
                    if(ctInfo.isActive) {
                        foundActiveConnection = true;
                        activeConnection.sn = dev.serialNumber;
                        activeConnection.ct = ctInfo;
                    }
                });
                // console.log('Device:',dev.serialNumber,'CTs',dev.connectionTypes);
            });
            if(foundActiveConnection) {
                debugMACT('!!! We found an active CT', activeConnection);
            } else {
                debugMACT('!!! We did not find an active CT');
            }
        }
        defered.resolve(bundle);
        return defered.promise;
    }
1324560
function() {
                var network = typeof connection_id === 'undefined' ?
                    _kiwi.app.connections.active_connection :
                    _kiwi.app.connections.getByConnectionId(connection_id);

                return network ?
                    network :
                    undefined;
            }
119570
def getNeighbouringRouters(self):
        
        print '%s call getNeighbouringRouters' % self.port
        try:
            routerInfo = []
            routerList = []
            routerList = self.__sendCommand('router list')[0].split()
            print routerList

            if 'Done' in routerList:
                print 'no neighbouring routers'
                return None

            for index in routerList:
                router = []
                cmd = 'router %s' % index
                router = self.__sendCommand(cmd)

                for line in router:
                    if 'Done' in line:
                        break
                    #elif 'Rloc' in line:
                    #    rloc16 = line.split()[1]
                    elif 'Ext Addr' in line:
                        eui = line.split()[2]
                        routerInfo.append(int(eui, 16))
                    #elif 'LQI In' in line:
                    #    lqi_in = line.split()[1]
                    #elif 'LQI Out' in line:
                    #    lqi_out = line.split()[1]
                    else:
                        pass

            print routerInfo
            return routerInfo
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("getNeighbouringDevice() Error: " + str(e))
943708
def get_available_routers(self, dc=None):
        
        mask = "mask[locations]"
        # Step 1, get the package id
        package = self.ordering_manager.get_package_by_key(self.capacity_package, mask="id")

        # Step 2, get the regions this package is orderable in
        regions = self.client.call('Product_Package', 'getRegions', id=package['id'], mask=mask, iter=True)
        _filter = None
        routers = {}
        if dc is not None:
            _filter = {'datacenterName': {'operation': dc}}

        # Step 3, for each location in each region, get the pod details, which contains the router id
        pods = self.client.call('Network_Pod', 'getAllObjects', filter=_filter, iter=True)
        for region in regions:
            routers[region['keyname']] = []
            for location in region['locations']:
                location['location']['pods'] = list()
                for pod in pods:
                    if pod['datacenterName'] == location['location']['name']:
                        location['location']['pods'].append(pod)

        # Step 4, return the data.
        return regions
1096980
function() {
            var result = [];
            var hostname = spec.env.allPublicNodeIds.publicHostname ||
                    $._.__ca_getAppFullName__();
            var start = spec.env.allPublicNodeIds.publicRangeStart;
            var end = spec.env.allPublicNodeIds.publicRangeEnd;
            for (var i = start; i<= end; i++) {
                result.push(hostname + ':' + i);
            }
            return result;
        }
323307
function () {
                return {
                    href: location.href,
                    hash: location.hash,
                    host: location.host,
                    hostName: location.hostname,
                    port: location.port,
                    protocol: location.protocol
                };
            }
713583
function openAllAvailableDevices(bundle) {
        debugSS('in openAllAvailableDevices');
        var defered = q.defer();

        // Save the scan request list to a local variable w/ a shorter name.
        // If enabling extra T5 mock stanning...
        var scanMethods;
        if(LIVE_DEVICE_SCANNING_ENABLED) {
            scanMethods = OPEN_ALL_SCAN_REQUEST_LIST;
        } else {
            scanMethods = OPEN_ALL_SCAN_REQUEST_LIST;
            if(ENABLE_BETA_MOCK_T5_USB_SCAN) {
                scanMethods.push(EXTRA_T5_MOCK_SCAN);
            }
        }

        // Default... aka when the T5 has been added.
        // var scanMethods = OPEN_ALL_SCAN_REQUEST_LIST
        
        // Determine which scan options to enable given the input options.
        var scanOptions = bundle.options;
        var filteredScanMethods = scanMethods.filter(function(scanMethod) {
            var enableScan = false;
            var smct = scanMethod.connectionType;

            if(smct == driver_const.LJM_CT_USB) {
                if(scanOptions.scanUSB) {
                    enableScan = true;
                }
            }
            if(smct == driver_const.LJM_CT_ETHERNET_UDP) {
                if(scanOptions.scanEthernet) {
                    enableScan = true;
                }
            }
            if(smct == driver_const.LJM_CT_ETHERNET_TCP) {
                if(scanOptions.scanEthernetTCP) {
                    enableScan = true;
                }
            }
            if(smct == driver_const.LJM_CT_WIFI_UDP) {
                if(scanOptions.scanWiFi) {
                    enableScan = true;
                }
            }
            if(smct == driver_const.LJM_CT_WIFI_TCP) {
                if(scanOptions.scanWiFiTCP) {
                    enableScan = true;
                }
            }
            if(smct == driver_const.LJM_CT_UDP) {
                if(scanOptions.scanWiFi || scanOptions.scanEthernet) {
                    enableScan = true;
                }
            }
            if(smct == driver_const.LJM_CT_TCP) {
                if(scanOptions.scanWiFiTCP || scanOptions.scanEthernetTCP) {
                    enableScan = true;
                }
            }
            return enableScan;
        });

        // Save async vs sync option to a local variable w/ a shorter name.
        var performAsync = PERFORM_SCAN_REQUESTS_ASYNCHRONOUSLY;

        var startTime = new Date();
        function finishedScanning() {
            var stopTime = new Date();
            var duration = stopTime - startTime;
            duration = parseFloat((duration/1000).toFixed(3));

            // We are finished scanning...
            if(DEBUG_OPEN_ALL_SCAN) {
                console.log(
                    'Finished performing all openAll scans. Duration:',
                    duration
                );
            }
            defered.resolve(bundle);
        }

        if(performAsync) {
            async.each(
                filteredScanMethods,
                getPerformOpenAllScanMethod(bundle),
                finishedScanning
            );
        } else {
            async.eachSeries(
                filteredScanMethods,
                getPerformOpenAllScanMethod(bundle),
                finishedScanning
            );
        }
        return defered.promise;
    }
1190248
function (area, layer) {
	
	// check if layer exists
	if (l_layers.hasOwnProperty(layer) === false)
		return [];
	
	// get all current subscriptions at this layer
	var subs = l_layers[layer];
	
	// prepare list of connection of subscribers matching / covering the area
	var connections = [];
	
	// check each subscription to see if it overlaps with the given area
	for (var id in subs) {
		var subscription = subs[id];
		
		// check for overlaps (distance between the two centers is less than sum of radii)
		if (l_dist(subscription, para) <= (subscription.r + para.r))
			connections.push(subscription.conn);
	}
	
	return connections;
}
293493
function getBroadcastAddresses() {
    // enumerate interfaces
    var net = os.networkInterfaces();
    var broadcastAddresses = Object.keys(net)
        // flatten the array structure
        .map(function (k) { return net[k]; })
        .reduce(function (prev, cur) { return prev.concat.apply(prev, cur); }, [])
        // only use external IPv4 ones
        .filter(function (add) { return !add.internal && add.family === "IPv4"; })
        // extract address and subnet as number array
        .map(function (k) { return ({
        address: k.address.split(".").map(function (num) { return +num; }),
        netmask: k.netmask.split(".").map(function (num) { return +num; }),
    }); })
        // broadcast is address OR (not netmask)
        .map(function (add) {
        return add.address.map(function (val, i) { return (val | ~add.netmask[i]) & 0xff; });
    })
        // ignore unconnected ones
        .filter(function (add) { return add[0] !== 169; })
        // turn the address into a string again
        .map(function (a) { return a[0] + "." + a[1] + "." + a[2] + "." + a[3]; });
    return broadcastAddresses;
}
816632
function getDeviceConnectionTypesData(deviceInfo) {
            if(false) {
                console.log(
                    'in getDeviceConnectionTypesData',
                    deviceInfo.serialNumber,
                    deviceInfo.ct,
                    deviceInfo.port,
                    deviceInfo.isActive,
                    deviceInfo.isMockDevice
                );//, Object.keys(deviceInfo));
            }
            var connectionTypes = [];

            var foundUSB = false;
            var usbInfo = {};
            var foundEth = false;
            var ethInfo = {};
            var foundWiFi = false;
            var wifiInfo = {};

            var usbCT = driver_const.connectionTypes.usb;
            var ethCT = driver_const.connectionTypes.ethernet;
            var wifiCT = driver_const.connectionTypes.wifi;
            if(deviceInfo.ct === usbCT) {
                usbInfo = createDeviceConnectionObj(
                    deviceInfo.dt,
                    deviceInfo.ct,
                    deviceInfo.serialNumber.toString()
                );
                // Always indicate that a USB device's USB connection 
                // is verified.
                usbInfo.isVerified = true;
                usbInfo.verified = true;
                
                usbInfo.isScanned = true;
                usbInfo.insertionMethod = 'scan';
                usbInfo.isActive = deviceInfo.isActive;
                if(deviceInfo.isActive) {
                    usbInfo.insertionMethod = 'connected';
                    usbInfo.isVerified = true;
                    usbInfo.verified = true;
                }
                foundUSB = true;
            } else if(deviceInfo.ct === ethCT) {
                ethInfo = createDeviceConnectionObj(
                    deviceInfo.dt,
                    deviceInfo.ct,
                    // deviceInfo.ip
                    deviceInfo.ethernetIP
                );
                ethInfo.isScanned = true;
                ethInfo.insertionMethod = 'scan';
                ethInfo.isActive = deviceInfo.isActive;
                if(deviceInfo.isActive) {
                    ethInfo.insertionMethod = 'connected';
                    ethInfo.isVerified = true;
                    ethInfo.verified = true;
                }
                foundEth = true;
            } else if(deviceInfo.ct === wifiCT) {
                wifiInfo = createDeviceConnectionObj(
                    deviceInfo.dt,
                    deviceInfo.ct,
                    // deviceInfo.ip
                    deviceInfo.wifiIP
                );
                wifiInfo.isScanned = true;
                wifiInfo.insertionMethod = 'scan';
                wifiInfo.isActive = deviceInfo.isActive;
                if(deviceInfo.isActive) {
                    wifiInfo.insertionMethod = 'connected';
                    wifiInfo.isVerified = true;
                    wifiInfo.verified = true;
                }
                foundWiFi = true;
            } else {
                console.error('openall_d_s, Encountered Invalid Connection Type', deviceInfo.ct);
            }

            if(!foundEth) {
                if(deviceInfo.ETHERNET_IP) {
                    if(deviceInfo.ETHERNET_IP.isReal) {
                        ethInfo = createDeviceConnectionObj(
                            deviceInfo.dt,
                            ethCT,
                            deviceInfo.ethernetIP
                        );
                        foundEth = true;
                        ethInfo.insertionMethod = 'attribute';
                        ethInfo.foundByAttribute = true;
                    }
                }
            }
            if(!foundWiFi) {
                if(deviceInfo.WIFI_IP) {
                    if(deviceInfo.WIFI_IP.isReal) {
                        wifiInfo = createDeviceConnectionObj(
                            deviceInfo.dt,
                            wifiCT,
                            deviceInfo.wifiIP
                        );
                        foundWiFi = true;
                        wifiInfo.insertionMethod = 'attribute';
                        wifiInfo.foundByAttribute = true;
                    }
                }
            }

            if(foundUSB) {connectionTypes.push(usbInfo);}
            if(foundEth) {connectionTypes.push(ethInfo);}
            if(foundWiFi) {connectionTypes.push(wifiInfo);}

            // console.log('device connection types', deviceInfo.ct, deviceInfo.WIFI_IP, deviceInfo.ETHERNET_IP);

            return connectionTypes;
        }
1331600
def get_wifi_list(self, startno, callback=None):
        '''
        
        '''
        params = {'startNo': startno}
        return self.execute_command('getWifiList', params, callback=callback)
1232034
def interfaces(self):
        """"""

        self._ifaces = []
        wifi_ctrl = wifiutil.WifiUtil()

        for interface in wifi_ctrl.interfaces():
            iface = Interface(interface)
            self._ifaces.append(iface)
            self._logger.info("Get interface: %s", iface.name())

        if not self._ifaces:
            self._logger.error("Can't get wifi interface")

        return self._ifaces
889811
function ip() {
    let network = os.networkInterfaces(),
        keys = Object.keys(network),
        ips = [];

    for (let key of keys) {
        network[key].forEach(ip => {
            ip.family === 'IPv4' && !ip.internal && ips.push(ip.address);
        });
    }

    return ips.length ? ips[0] : '127.0.0.1';
}
478659
function scanNetworks(callback) {
  exec(scanner.cmdLine, function (err, stdout) {
    if (err) {
      callback(err, null);
      return;
    }
    scanner.parseOutput(stdout, callback);
  });
}
1094830
function getDevices(): Array<string> {
  try {
    const devicesResult = child_process.execSync('adb devices');
    return parseDevicesResult(devicesResult.toString());
  } catch (e) {
    return [];
  }


}