Find Denon and marantz devices advertising their services by upnp.
@param {function} callback .
@constructor
1301
function MarantzDenonUPnPDiscovery(callback) {
    var that = this;
    var foundDevices = {};                                                      // only report a device once

    // create socket
    var socket = dgram.createSocket({type: 'udp4', reuseAddr: true});
    socket.unref();
    const search = new Buffer([
        'M-SEARCH * HTTP/1.1',
        'HOST: 239.255.255.250:1900',
        'ST: upnp:rootdevice',
        'MAN: "ssdp:discover"',
        'MX: 3',
        '',
        ''
    ].join('\r\n'));

    socket.on('error', function(err) {
        console.log(`server error:\n${err.stack}`);
        socket.close();
    });

    socket.on('message', function(message, rinfo) {
        var messageString = message.toString();
        console.log(messageString);
        if (messageString.match(/(d|D)enon/)) {
            location = messageString.match(/LOCATION: (.*?)(\d+\.\d+\.\d+\.\d+)(.*)/);
            if (location) {
                arp.getMAC(location[2], function(err, mac) {                    // lookup ip on the arp table to get the MacAddress
                    if (!err) {
                        if (foundDevices[mac]) {                                // only report foind devices once
                            return;
                        }
                        var device = {
                            friendlyName: '',
                            ip: location[2],
                            location: (location[1] + location[2] + location[3]).trim(),
                            mac: mac,
                            manufacturer: 'Unknown Manufacturer',
                            model: 'Unknown Model'
                        };
                        foundDevices[mac] = device;
                        that.getUPnPInfo(device, function() {
                            if (device.manufacturer == 'Unknown Manufacturer') { // still no info?
                                that.getDeviceInfo(device, function() {callback(null, device);}, 80);
                            } else {
                                callback(null, device);
                            }
                        });
                    }
                });
            }
        }
    });

    socket.on('listening', function() {
        socket.addMembership('239.255.255.250');
        socket.setMulticastTTL(4);
        const address = socket.address();
        console.log(`server listening ${address.address}:${address.port}`);
        socket.send(search, 0, search.length, 1900, '239.255.255.250');
        setTimeout(function() {socket.close();}, 5000);
    });

    socket.bind(0);
}
585009
function (callback) {
            var mapName;

            for (mapName in this.maps) {
                if (this.maps.hasOwnProperty(mapName)) {
                    callback.call(this, this.maps[mapName], mapName);
                }
            }
        }
487118
def get_filtered_devices(
        self, model_name, device_types="upnp:rootdevice", timeout=2
    ):
        

        # get list of all UPNP devices in the network
        upnp_devices = self.discover_upnp_devices(st=device_types)

        # go through all UPNP devices and filter wanted devices
        filtered_devices = collections.defaultdict(dict)
        for dev in upnp_devices.values():
            try:
                # download XML file with information about the device
                # from the device's location
                r = requests.get(dev.location, timeout=timeout)

                if r.status_code == requests.codes.ok:
                    # parse returned XML
                    root = ET.fromstring(r.text)

                    # add shortcut for XML namespace to access sub nodes
                    ns = {"upnp": "urn:schemas-upnp-org:device-1-0"}

                    # get device element
                    device = root.find("upnp:device", ns)

                    if model_name in device.find(
                        "upnp:modelName", ns
                    ).text:
                        # model name is wanted => add to list

                        # get unique UDN of the device that is used as key
                        udn = device.find("upnp:UDN", ns).text

                        # add url base
                        url_base = root.find("upnp:URLBase", ns)
                        if url_base is not None:
                            filtered_devices[udn][
                                "URLBase"
                            ] = url_base.text

                        # add interesting device attributes and
                        # use unique UDN as key
                        for attr in (
                            "deviceType", "friendlyName", "manufacturer",
                            "manufacturerURL", "modelDescription",
                            "modelName", "modelNumber"
                        ):
                            el = device.find("upnp:%s" % attr, ns)
                            if el is not None:
                                filtered_devices[udn][
                                    attr
                                ] = el.text.strip()

            except ET.ParseError:
                # just skip devices that are invalid xml
                pass
            except requests.exceptions.ConnectTimeout:
                # just skip devices that are not replying in time
                print("Timeout for '%s'. Skipping." % dev.location)

        return filtered_devices
430981
function(callback) {

      // Detect server errors
      var t = this, server = t.get('server');
      server.on('clientError', function(err){
        console.error('Client error detected on server', err);
        t.trigger('error', err);
      });
      server.on('close', function(err){
        server.hasEmittedClose = true;
        t.stop();
      });

      // Notify that we've started
      t.isListening = true;
      if (callback) {
        callback(null);
      }
      t.trigger('start');
    }
1119329
function (callback, trace) {
      return function (arg) {
        try {
          callback(arg);
        } catch (error) {
          if (this.listenerCount('error')) {
            this.emit('error', error, trace);
          } else {
            console.error(error, trace);
          }
        }
      }.bind(this);
    }
26895
function(callback) {
      var t = this;
      callback = callback || function(){};
      var onPong = function() {
        t.off('pong', onPong);
        callback();
      };
      t.on('pong', onPong);
      t.emit('connection:ping');
    }
549926
function(interval, callback) {
    if (lookupIntervalId) {
      return;
    }

    isRunning = true;

    if (!callback && _.isFunction(interval)) {
      callback = interval;
      interval = null;
    }

    interval = interval || 500;

    globalSerialDeviceLoader.trigger(function(err) {
      var triggering = false;
      lookupIntervalId = setInterval(function() {
        if (triggering) return;
        triggering = true;
        globalSerialDeviceLoader.trigger(function() {
          triggering = false;
        });
      }, interval);

      if (err && !err.name) {
        err = new Error(err);
      }
      if (callback) { callback(err); }
    });
  }
270831
function forOwn(object, callback) {
    for (var key in object) {
      if (hasOwnProperty.call(object, key)) {
        callback(object[key], key, object);
      }
    }
  }
331731
function find(query, options, callback) {
    if (typeof options === 'function') {
      callback = options
      options = {}
    }

    self.emit('find', query, options)
    if (callback !== undefined) {
      findByQuery(query, options, function(error, data) {
        if (error) return callback(error)
        self.emit('received', data)
        callback(null, data)
      })
    } else {
      return findByQuery(query, options)
    }
  }
842007
function(callback)
    {
        function mycallback(mimeType, content)
        {
            this._originalContent = content;
            callback(mimeType, content);
        }
        this._uiSourceCode.requestContent(mycallback.bind(this));
    }
97304
function discover (callback) {
  glob(path.join(this._source, '/**/*.*'), function (err, filepaths) {
    if (err) callback(err);
    callback(null, filepaths);
  });
}
116427
function(callback){
      ubeacon.getMeshDeviceId( function( deviceAddress ){
        console.log( '[ubeacon] Device address is: ' + deviceAddress + ' (0x' + deviceAddress.toString(16) + ')' );
        callback(null);
      });
    }
955403
function discover(target) {
	var both = false;
	if (!target) {
		target = 'googlecast';
		both = true;
	}
	return new Promise( function(resolve, reject) {
		var updateCounter=0;
		var discovered = [];
		try {
			if (getNetworkIp) {
				var browser = mdns.createBrowser(mdns.tcp(target));
				var exception;

				browser.on('error', function(error) {
					log('debug', 'discover()', 'mdns browser error: ' + error);
				})

				browser.on('ready', function(){
					browser.discover();
				});

				browser.on('update', function(service){
					//try {
						updateCounter++;
						log('debug', 'discover()', 'update received, service: ' + JSON.stringify(service));
						if (target=='googlecast' && service.type[0].name==target) {
							var currentDevice = {
								id: getId(service.txt[0]),
								name: getFriendlyName(service.txt),
									address: {
										host: service.addresses[0],
										port: service.port
								}
							}
					  		if (!duplicateDevice(discovered, currentDevice) && currentDevice.name!=null ) {
					  			log('debug', 'discover()', 'found device: '+ JSON.stringify(currentDevice));
					  			discovered.push(currentDevice);
					  			updateExistingCastDeviceAddress(currentDevice);

					  			if ( !deviceExists(currentDevice.id) ) {
					  				log('info', 'discover()', 'added device name: '+ currentDevice.name +', address: '+ JSON.stringify(currentDevice.address), currentDevice.id);
					  				devices.push( new CastDevice( currentDevice.id, currentDevice.address, currentDevice.name ) ); //TODO: addDevice
					  			}
					  		} else {
					  			log('debug', 'discover()', 'duplicate, googlezone device or empy name: ' + JSON.stringify(currentDevice));
					  		}
						}
						if (target=='googlezone' && service.type[0].name==target) {
							var currentGroupMembership = {
								id: getId(service.txt[0]).replace(/-/g, ''),
								groups: getGroupIds(service.txt)
							}
							log('debug', 'discover()', 'found googlezone: ' + JSON.stringify(currentGroupMembership) );
							discovered.push(currentGroupMembership);
						}
				 //  	} catch (e) {
					// 	log('error', 'discover()', 'exception while prcessing service: '+e);
					// }
				});
			}
		} catch (e) {
			reject('Exception caught: ' + e);
		}

		setTimeout(() => {
			try{
				browser.stop();
			} catch (e) {
				//reject('Exception caught: ' + e)
			}
			log('debug', 'discover()', 'updateCounter: ' + updateCounter);
			resolve(discovered);
	  	}, timeoutDiscovery);
	});
}
1029140
function () {
        "use strict";
    
        Object.defineProperty(this, 'isPhonegap', {
            'get': function () {
    
                return (!!window.cordova || !!window.PhoneGap || !!window.phonegap)
                    && /^file:\/{3}[^\/]/i.test(window.location.href)
                    && /ios|iphone|ipod|ipad|android/i.test(navigator.userAgent);
    
            }
        });
    
        var ready;
        Object.defineProperty(this, 'ready', {
            'get': function () {
                return ready;
            }
        });
    
        var callbacks = [];
    
        function onDeviceReady() {
    
            ready = true;
            for (var i in callbacks) {
                try {
                    callbacks[i]();
                }
                catch (exc) {
                    console.log(exc);
                }
            }
    
            callbacks = [];
    
        }
    
        document.addEventListener('deviceready', onDeviceReady);
    
        this.done = function (callback) {
    
            if (typeof callback !== 'function') {
                console.error('Invalid callback function.');
                return;
            }
    
            if (ready) {
                callback();
            }
            else {
                callbacks.push(callback);
            }
    
        };
    
    }
490273
function onDeviceFound(device)
	{
		// For debugging, print advertisement data.
		//console.log(JSON.stringify(device.advertisementData))

		// Alternative way to identify the device by advertised service UUID.
		/*
		if (device.advertisementData.kCBAdvDataServiceUUIDs.indexOf(
			'0000aa10-0000-1000-8000-00805f9b34fb') > -1)
		{
			showMessage('Found the TI SensorTag!')
		}
		*/

		if (device.advertisementData.kCBAdvDataLocalName == 'CC2650 SensorTag')
		{
			showMessage('Found the TI SensorTag!')

			// Stop scanning.
			evothings.ble.stopScan()

			// Connect.
			connectToDevice(device)
		}
	}
53457
function callbackOnce(err, arg) {
            var cb = callback;
            callback = null;
            if (cb) { cb(err, arg); }
        }
723331
function(callback) {
    var ports = [];
    var newPortToDevice = [];
    // get all devices
    var responses = 0;
    var devices = Espruino.Core.Serial.devices;
    if (!devices || devices.length==0) {
         portToDevice = newPortToDevice;
      return callback(ports, false);
    }
    var shouldCallAgain = false;
    devices.forEach(function (device) {
      //console.log("getPorts -->",device.name);
      device.getPorts(function(devicePorts, instantPorts) {
        //console.log("getPorts <--",device.name);
        if (instantPorts===false) shouldCallAgain = true;
        if (devicePorts) {
          devicePorts.forEach(function(port) {
            var ignored = false;
            if (Espruino.Config.SERIAL_IGNORE)
              Espruino.Config.SERIAL_IGNORE.split("|").forEach(function(wildcard) {
                var regexp = "^"+wildcard.replace(/\./g,"\\.").replace(/\*/g,".*")+"$";
                if (port.path.match(new RegExp(regexp)))
                  ignored = true;
              });

            if (!ignored) {
              if (port.usb && port.usb[0]==0x0483 && port.usb[1]==0x5740)
                port.description = "Espruino board";
              ports.push(port);
              newPortToDevice[port.path] = device;
            }
          });
        }
        responses++;
        if (responses == devices.length) {
          portToDevice = newPortToDevice;
          ports.sort(function(a,b) {
            if (a.unimportant && !b.unimportant) return 1;
            if (b.unimportant && !a.unimportant) return -1;
            return 0;
          });
          callback(ports, shouldCallAgain);
        }
      });
    });
  }