 URL = require 'url'
 auth = require './auth'
 
+
 udpConReq = (address, un, key, callback) ->
   [host, port] = address.split(':', 2)
 

      username = device.InternetGatewayDevice.ManagementServer.ConnectionRequestUsername?._value
      password = device.InternetGatewayDevice.ManagementServer.ConnectionRequestPassword?._value

    if not (username and password) and config.auth?.connectionRequest
      [username, password] = config.auth.connectionRequest(deviceId)

    if udpConnectionRequestAddress
      udpConReq(udpConnectionRequestAddress, username, password, (err) -> throw err if err)

    # for testing
    #connectionRequestUrl = connectionRequestUrl.replace(/^(http:\/\/)([0-9\.]+)(\:[0-9]+\/[a-zA-Z0-9]+\/?$)/, '$110.1.1.254$3')
    conReq(connectionRequestUrl, null, (statusCode, authHeader) ->
      if statusCode == 401
        if authHeader.method is 'Basic'
          authString = auth.basic(username, password)
        else if authHeader.method is 'Digest'
          uri = URL.parse(connectionRequestUrl)
          authString = auth.digest(username, password, uri.path, 'GET', null, authHeader)

        conReq(connectionRequestUrl, authString, (statusCode, authHeader) ->
          if statusCode == 0
            # Workaround for some devices unexpectedly closing the connection
            return conReq(connectionRequestUrl, authString, (statusCode) -> callback(statusToError(statusCode)))
          callback(statusToError(statusCode))
        )
      else if udpConnectionRequestAddress
        return callback()
      else
        callback(statusToError(statusCode))
    )
  )



  }

  db.devicesCollection.findOne({_id : deviceId}, proj, (err, device)->
    return callback(err) if err

    if device.Device? # TR-181 data model
      connectionRequestUrl = device.Device.ManagementServer.ConnectionRequestURL._value
