Revision: 201007 RCL_3
authorDremov Kirill (Nokia-D-MSW/Tampere) <kirill.dremov@nokia.com>
Fri, 12 Mar 2010 15:43:23 +0200
branchRCL_3
changeset 10 0707dd69d236
parent 6 6a29d5ad0713
child 11 a42ed326b458
Revision: 201007 Kit: 201008
bluetoothengine/bteng/bttoggle/src/bttoggle.cpp
bluetoothengine/bteng/data/btengsdp.rss
bluetoothengine/bteng/data/bttoggle_reg.rss
bluetoothengine/bteng/group/bteng.mmp
bluetoothengine/bteng/group/btengconnman.mmp
bluetoothengine/bteng/group/btengdiscovery.mmp
bluetoothengine/bteng/group/btengsettings.mmp
bluetoothengine/bteng/inc/btengactive.h
bluetoothengine/bteng/inc/btengactive.inl
bluetoothengine/bteng/inc/btengpairman.h
bluetoothengine/bteng/inc/btengserver.h
bluetoothengine/bteng/inc/btengsrvsession.h
bluetoothengine/bteng/inc/btengsrvsettingsmgr.h
bluetoothengine/bteng/inc/btengsrvstate.h
bluetoothengine/bteng/rom/bteng.iby
bluetoothengine/bteng/src/btengpairman.cpp
bluetoothengine/bteng/src/btengserver.cpp
bluetoothengine/bteng/src/btengsrvkeywatcher.cpp
bluetoothengine/bteng/src/btengsrvpluginmgr.cpp
bluetoothengine/bteng/src/btengsrvsession.cpp
bluetoothengine/bteng/src/btengsrvsettingsmgr.cpp
bluetoothengine/bteng/src/btengsrvstate.cpp
bluetoothengine/btmac/inc/btmonocmdhandler/btmcoperator.h
bluetoothengine/btmac/inc/btmonocmdhandler/btmcphonestatus.h
bluetoothengine/btmac/inc/btmonocmdhandler/btmcprotocol.h
bluetoothengine/btmac/inc/btmonocmdhandler/btmcvolume.h
bluetoothengine/btmac/src/BTMonoCmdHandler/btmccallstatus.cpp
bluetoothengine/btmac/src/BTMonoCmdHandler/btmcoperator.cpp
bluetoothengine/btmac/src/BTMonoCmdHandler/btmcphonestatus.cpp
bluetoothengine/btmac/src/BTMonoCmdHandler/btmcprotocol.cpp
bluetoothengine/btmac/src/BTMonoCmdHandler/btmcvolume.cpp
bluetoothengine/btnotif/src/BTNInqNotifier.cpp
bluetoothengine/btui/Ecom/src/BTUIPairedDevicesView.cpp
tsrc/public/basic/obexservapitest/src/ObexServAPItestBlocks.cpp
tsrc/public/basic/obexservapitest/src/testlogger.cpp
--- a/bluetoothengine/bteng/bttoggle/src/bttoggle.cpp	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/bteng/bttoggle/src/bttoggle.cpp	Fri Mar 12 15:43:23 2010 +0200
@@ -358,8 +358,9 @@
 // ==========================================================
 //
 TInt CBTToggle::RunError(TInt aError)
-  {	  
-  TRACE_INFO((_L("[BTENG][BTTOGGLE]RunL error %d"), aError ))		
-  CActiveScheduler::Stop();
-  return KErrNone;
-  }
+    {	  
+    TRACE_INFO((_L("[BTENG][BTTOGGLE] RunError %d"), aError ))	
+    iActiveNotifier = ENoneQuery;
+    CActiveScheduler::Stop();
+    return KErrNone;
+    }
--- a/bluetoothengine/bteng/data/btengsdp.rss	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/bteng/data/btengsdp.rss	Fri Mar 12 15:43:23 2010 +0200
@@ -879,7 +879,7 @@
                             elements = 
                                 {
                                 ELEMENT_UUID { uuid = SERVICE_CLASS_ID_HEADSET; },
-                                ELEMENT_WORD { value = 0x0100; }
+                                ELEMENT_WORD { value = 0x0102; }
                                 };
                             }
                         };
--- a/bluetoothengine/bteng/data/bttoggle_reg.rss	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/bteng/data/bttoggle_reg.rss	Fri Mar 12 15:43:23 2010 +0200
@@ -24,7 +24,9 @@
 
 RESOURCE APP_REGISTRATION_INFO
     {
-    app_file = "bttoggle";	
+    app_file = "bttoggle";
+    hidden = KAppIsHidden;
+    launch = KAppLaunchInForeground;
     }
 
 
--- a/bluetoothengine/bteng/group/bteng.mmp	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/bteng/group/bteng.mmp	Fri Mar 12 15:43:23 2010 +0200
@@ -35,11 +35,11 @@
 SOURCE                  btengsrvbbconnectionmgr.cpp
 SOURCE                  btengsdpdbhandler.cpp
 SOURCE                  btengsrvkeywatcher.cpp
-SOURCE                  btengactive.cpp
 SOURCE                  btengpairman.cpp
 SOURCE                  btengpairbase.cpp
 SOURCE                  btengincpair.cpp 
 SOURCE                  btengotgpair.cpp
+SOURCE                  btengsrvsettingsmgr.cpp
 START RESOURCE          ../data/btengsdp.rss
 HEADER
 TARGETPATH              RESOURCE_FILES_DIR
@@ -64,6 +64,10 @@
 LIBRARY                 aknnotify.lib
 LIBRARY                 btfeatures.lib
 
+#ifndef SETLOCALNAME
+LIBRARY                 btengsettings.lib
+#endif
+
 LIBRARY                 btpowercontrol.lib
 #ifndef __WINS__
 LIBRARY                 dutmode.lib
--- a/bluetoothengine/bteng/group/btengconnman.mmp	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/bteng/group/btengconnman.mmp	Fri Mar 12 15:43:23 2010 +0200
@@ -31,7 +31,6 @@
 SOURCE                  btengconnhandler.cpp
 SOURCEPATH              ../src
 SOURCE                  btengclient.cpp
-SOURCE                  btengactive.cpp
 
 USERINCLUDE             ../inc
 USERINCLUDE             ../btengconnman/inc
--- a/bluetoothengine/bteng/group/btengdiscovery.mmp	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/bteng/group/btengdiscovery.mmp	Fri Mar 12 15:43:23 2010 +0200
@@ -32,7 +32,6 @@
 SOURCE                  btengsdpattrparser.cpp
 SOURCE                  btengdevicesearch.cpp
 SOURCEPATH              ../src
-SOURCE                  btengactive.cpp
 SOURCE                  btengsdpdbhandler.cpp
 
 USERINCLUDE             ../inc
--- a/bluetoothengine/bteng/group/btengsettings.mmp	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/bteng/group/btengsettings.mmp	Fri Mar 12 15:43:23 2010 +0200
@@ -30,7 +30,6 @@
 SOURCE                  btengsettings.cpp
 SOURCE                  btengsettingsnotify.cpp
 SOURCEPATH              ../src
-SOURCE                  btengactive.cpp
 SOURCE                  btengclient.cpp
 
 USERINCLUDE             ../inc
--- a/bluetoothengine/bteng/inc/btengactive.h	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/bteng/inc/btengactive.h	Fri Mar 12 15:43:23 2010 +0200
@@ -86,10 +86,12 @@
      * @since S60 v3.2
      * @param aObserver Pointer to callback interface that receives notification
      *                  that the request has been completed.
+     * @param aId Identifier for the CBTEngActive instance.
+     * @param aPriority The priority of the active object.
      * @return Pointer to the constructed CBTEngActive object.
      */
-    static CBTEngActive* NewL( MBTEngActiveObserver& aObserver, 
-                                TInt aId, TInt aPriority );
+    static CBTEngActive* NewL( MBTEngActiveObserver& aObserver, TInt aId,
+                                TInt aPriority = CActive::EPriorityStandard );
 
     /**
      * Destructor
--- a/bluetoothengine/bteng/inc/btengactive.inl	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/bteng/inc/btengactive.inl	Fri Mar 12 15:43:23 2010 +0200
@@ -16,6 +16,66 @@
 */
 
 
+// ======== MEMBER FUNCTIONS ========
+
+// ---------------------------------------------------------------------------
+// C++ default constructor
+// ---------------------------------------------------------------------------
+//
+inline CBTEngActive::CBTEngActive(  MBTEngActiveObserver& aObserver, TInt aId, 
+    TInt aPriority )
+:   CActive( aPriority ),
+    iRequestId( aId ),
+    iObserver( aObserver )
+    {
+    CActiveScheduler::Add( this );
+    }
+
+
+// ---------------------------------------------------------------------------
+// Symbian 2nd-phase constructor
+// ---------------------------------------------------------------------------
+//
+inline void CBTEngActive::ConstructL()
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// NewLC
+// ---------------------------------------------------------------------------
+//
+inline CBTEngActive* CBTEngActive::NewL( MBTEngActiveObserver& aObserver, 
+    TInt aId, TInt aPriority )
+    {
+    CBTEngActive* self = new( ELeave ) CBTEngActive( aObserver, aId, aPriority );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// Destructor
+// ---------------------------------------------------------------------------
+//
+inline CBTEngActive::~CBTEngActive()
+    {
+    Cancel();
+    }
+
+
+// ---------------------------------------------------------------------------
+// From class CActive.
+// Called by the active scheduler when the request has been cancelled.
+// ---------------------------------------------------------------------------
+//
+inline void CBTEngActive::DoCancel()
+    {
+    }
+
+
 
 // -----------------------------------------------------------------------------
 // Get the identifier of this instance.
@@ -65,3 +125,26 @@
     {
     return iStatus;
     }
+
+
+// ---------------------------------------------------------------------------
+// From class CActive.
+// Called by the active scheduler when the request has been completed.
+// ---------------------------------------------------------------------------
+//
+inline void CBTEngActive::RunL()
+    {
+    iObserver.RequestCompletedL( this, iRequestId, iStatus.Int() );
+    }
+
+
+// ---------------------------------------------------------------------------
+// From class CActive.
+// Called by the active scheduler when an error in RunL has occurred.
+// ---------------------------------------------------------------------------
+//
+inline TInt CBTEngActive::RunError( TInt aError )
+    {
+    iObserver.HandleError( this, iRequestId, aError );
+    return KErrNone;
+    }
--- a/bluetoothengine/bteng/inc/btengpairman.h	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/bteng/inc/btengpairman.h	Fri Mar 12 15:43:23 2010 +0200
@@ -61,12 +61,6 @@
     void ProcessCommandL( const RMessage2& aMessage );
     
     /**
-     * Cancels an outstanding command.
-     * @param aOpcode the identifier of the command to be cancelled.
-     */
-    void CancelCommand( TInt aOpCode );
-    
-    /**
      * Handle a change in BTRegistry remote device table.
      *
      * @since S60 v5.1
@@ -103,6 +97,14 @@
     void OutgoingPairCompleted( TInt aErr );
     
     /**
+     * Be informed that a session will be closed.
+     *
+     * @since Symbian^3
+     * @param aSession the session to be cloased.
+     */
+    void SessionClosed(CSession2* aSession );
+    
+    /**
      * Unpair a device via registry
      */
     void UnpairDevice( const TBTDevAddr& aAddr );
@@ -313,6 +315,11 @@
      * Own.
      */
     CBTEngPairBase* iPairer;
+    
+    /**
+     * Client-server message for power change requests.
+     */
+    RMessage2 iMessage;
     };
 
 #endif /*BTENGPAIRMANAGER_H_*/
--- a/bluetoothengine/bteng/inc/btengserver.h	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/bteng/inc/btengserver.h	Fri Mar 12 15:43:23 2010 +0200
@@ -20,13 +20,10 @@
 #define BTENGSERVER_H
 
 #include <bluetooth/btpowercontrol.h>
-#ifndef __WINS__
-#include <bluetooth/dutmode.h>
-#endif  //__WINS__  
 #include <bt_sock.h>
 #include <bttypes.h>
-#include <btfeaturescfg.h>
-#include "btengdomaincrkeys.h"
+#include <btserversdkcrkeys.h>
+
 #include "btengconstants.h"
 
 class CBTEngSrvState;
@@ -40,6 +37,7 @@
 class TEComResolverParams;
 class CImplementationInformation;
 class CDeltaTimer;
+class CBTEngSrvSettingsMgr;
 
 /**
  * Main function in which the server is running.
@@ -75,7 +73,8 @@
     EBTEngPanicArgumentIsNull,
     EBTEngPanicMemberVarIsNull,
     EBTEngPanicCorrupt,
-    EBTEngPanicCorruptSettings
+    EBTEngPanicCorruptSettings,
+    EBTEngPanicExpectSetPowerOpcode,
     };
 
 
@@ -90,43 +89,114 @@
 NONSHARABLE_CLASS( CBTEngServer ) : public CPolicyServer
     {
 
-    friend class CBTEngSrvSession;
-    friend class CBTEngSrvState;
     friend class CBTEngSrvPluginMgr;
-    friend class CBTEngSrvKeyWatcher;
     friend class CBTEngPairMan;
 
 public:
 
+    /**  Enumeration of bitmask for keeping track of different timers. */
+    enum TTimerQueued
+        {
+        ENone               = 0x00,
+        EScanModeTimer      = 0x01,
+        EIdleTimer          = 0x02,
+        EAutoPowerOffTimer  = 0x04,
+        ESspDebugModeTimer  = 0x08 
+        };
+
+    /**
+     * Two-phased constructor.
+     */
     static CBTEngServer* NewLC();
 
+    /**
+     * Destructor.
+     */
     virtual ~CBTEngServer();
 
     /**
-     * ?description
+     * Getter for power change state machine instance.
+     *
+     * @since Symbian^3
+     * @return Pointer to instance of state machine.
+     */
+    inline CBTEngSrvState* StateMachine() const
+            { return iServerState; }
+
+    /**
+     * Getter for settings manager instance.
+     *
+     * @since Symbian^3
+     * @return Pointer to instance of settings manager.
+     */
+    inline CBTEngSrvSettingsMgr* SettingsManager() const
+            { return iSettingsMgr; }
+
+    /**
+     * Getter for plug-in manager instance.
+     *
+     * @since Symbian^3
+     * @return Pointer to instance of plug-in manager.
+     */
+    inline CBTEngSrvPluginMgr* PluginManager() const
+            { return iPluginMgr; }
+
+    /**
+     * Getter for baseband connection manager instance.
+     *
+     * @since Symbian^3
+     * @return Pointer to instance of baseband connection manager.
+     */
+    inline CBTEngSrvBBConnMgr* BasebandConnectionManager() const
+            { return iBBConnMgr; }
+
+    /**
+     * Getter for pairing manager. Ownership is not transferred.
+     *
+     * @since Symbian^3
+     * @return Pointer to instance of baseband connection manager.
+     */
+    inline CBTEngPairMan* PairManager() const
+            { return iPairMan; }
+
+    /**
+     * Getter for socket server session.
+     * This handle can be used for creating subsessions.
+     *
+     * @since Symbian^3
+     * @return Reference to session with the socket server.
+     */
+    inline RSocketServ& SocketServer()
+            { return  iSocketServ; }
+
+    /**
+     * Getter for registry server session.
+     * This handle can be used for creating subsessions.
+     *
+     * @since Symbian^3
+     * @return Reference to session with the registry server.
+     */
+    inline RBTRegServ& RegistrServer()
+            { return iBTRegServ; }
+
+    /**
+     * Set Bluetooth on or off
      *
      * @since S60 v3.2
      * @param aState The new power state.
-     * @param aTemp Turn BT off after use (ETrue) or not (EFalse).
+     * @param aTemporary Turn BT off after use (ETrue) or not (EFalse).
      */
-    void SetPowerStateL( TBTPowerStateValue aState, TBool aTemporary );
+    void SetPowerStateL( TBTPowerState aState, TBool aTemporary );
 
     /**
-     * ?description
+     * Set Bluetooth on or off upon a client power management request.
+     * This function is only for power management request from clients of bteng server.
      *
-     * @since S60 v3.2
-     * @param ?arg1 ?description
+     * @since Symbian^3
+     * @param aMessage The message containing the detail of power management request.
      */
-    void SetVisibilityModeL( TBTVisibilityMode aMode, TInt aTime );
+    void SetPowerStateL( const RMessage2 aMessage );
     
-     /**
-     * ?description
-     *
-     * @since S60 v3.2
-     * @param ?arg1 ?description
-     */
-    void UpdateVisibilityModeL( TInt aStackScanMode );
-
     /**
      * ?description
      *
@@ -141,23 +211,7 @@
      * @since S60 v3.2
      * @param ?arg1 ?description
      */
-    void SetDutMode( TInt aDutMode );
-
-    /**
-     * ?description
-     *
-     * @since S60 v3.2
-     * @param ?arg1 ?description
-     */
-    void ScanModeTimerCompletedL();
-
-    /**
-     * ?description
-     *
-     * @since S60 v3.2
-     * @param ?arg1 ?description
-     */
-     void DisconnectAllCompleted();
+    void DisconnectAllCompleted();
 
     /**
      * ?description
@@ -172,86 +226,89 @@
      *
      * @since S60 v3.2
      */
-     void AddSession();
+    void AddSession();
 
     /**
      * Decrement the session count.
      *
-     * @since S60 v3.2
+     * @since Symbian^3
+     * @param aSession the session to be cloased.
      * @param aAutoOff Indicator if this session had requested BT temporary on.
      */
-     void RemoveSession( TBool aAutoOff );
-     
-     /**
-     * ?description
+    void RemoveSession(CSession2* aSession, TBool aAutoOff );
+
+    /**
+     * Queue a new timer.
+     *
+     * @since Symbian^3
+     * @param aTimer Identifier for the timer to be queued.
+     * @param aInterval The interval for timer callback.
+     */
+    void QueueTimer( CBTEngServer::TTimerQueued aTimer, TInt64 aInterval );
+
+    /**
+     * Remove a queued timer.
+     *
+     * @since Symbian^3
+     * @param aTimer Identifier for the timer to be removed.
+     */
+    void RemoveTimer( CBTEngServer::TTimerQueued aTimer );
+
+    /**
+     * Check if a specific timer is currently queued.
+     *
+     * @since Symbian^3
+     * @param aTimer Identifier for the timer to check.
+     */
+    inline TBool IsTimerQueued( CBTEngServer::TTimerQueued aTimer ) const
+            { return ( iTimerQueued & aTimer ); }
+
+    /**
+     * Returns the service (limited to services managed in bteng scope)
+     * level connection status of the specified device.
+     *
+     * @param aAddr the address of the device
+     * @return one of TBTEngConnectionStatus enums
+     */
+    TBTEngConnectionStatus IsDeviceConnected( const TBTDevAddr& aAddr );
+
+    /**
+     * Checks if power is off and no session are connected, and
+     * starts a shutdown timer if so.
      *
      * @since S60 v3.2
      * @param ?arg1 ?description
      */
-     void SetUiIndicatorsL();
-     
-     /**
+    void CheckIdle();
+
+    /**
      * ?description
      *
      * @since S60 v3.2
      * @param ?arg1 ?description
      */
-     void SetIndicatorStateL( const TInt aIndicator, const TInt aState );
-
-    /**
-     * Check whether BT should be turned off automatically.
-     *
-     * @since S60 v5.0
-     */
-     void CheckAutoPowerOffL();
+    void ManageDIServiceL( TBool aState );
 
     /**
-     * Utility to get HW power state.
-     *
-     * @since S60 v5.1
-     * @param aState On return, this will contain the current HW power state.
-     * @return KErrNone if successful, otherwise one of the system-wide error codes.
-     */
-    TInt GetHwPowerState( TBTPowerStateValue& aState );
-
-     /**
-     * queue a timer if Simple Pairing debug mode has been enabled.
+     * Callback function for completion of disconnecting all 
+     * Bluetoooth Baseband links.
      *
      * @since S60 v3.2
-     * @param aDebugMode State of Simple Pairing debug mode.
+     * @param aPtr Pointer to ourselves.
+     * @return Result
      */
-     void CheckSspDebugModeL( TBool aDebugMode );
-     
-     /**
-      * Gets the access to pairing manager. Ownership is not transferred.
-      * @return the pairing manager
-      */
-     CBTEngPairMan& PairManager();
-     
-     /**
-      * Be informed when registry remote device table is changed
-      */
-     void RemoteRegistryChangeDetected();
+    static TInt DisconnectAllCallBack( TAny* aPtr );
 
-     /**
-      * gets the reference of socket server session
-      */
-     RSocketServ& SocketServ();
-     
-     /**
-      * gets the reference of registry session.
-      */
-     RBTRegServ& BTRegServ();
-     
-     /**
-      * Returns the service (limited to services managed in bteng scope)
-      * level connection status of the specified device.
-      *
-      * @param aAddr the address of the device
-      * @return one of TBTEngConnectionStatus enums
-      */
-     TBTEngConnectionStatus IsDeviceConnected( const TBTDevAddr& aAddr );
-     
+    /**
+     * Callback function for turning BT off automatically after all
+     * connections are gone.
+     *
+     * @since S60 v5.0
+     * @param aPtr Pointer to ourselves.
+     * @return Result
+     */
+    static TInt AutoPowerOffCallBack( TAny* aPtr );
+
 // from base class CPolicyServer
 
     /**
@@ -264,10 +321,6 @@
     virtual CSession2* NewSessionL( const TVersion& aVersion, 
                                      const RMessage2& aMessage ) const;
 
-// from base class MBTPowerManagerObserver
-
-    BluetoothFeatures::TEnterpriseEnablementMode EnterpriseEnablementMode() const;
-    
 private:
 
     CBTEngServer();
@@ -275,81 +328,6 @@
     void ConstructL();
 
     /**
-     * Checks if power is off and no session are connected, and
-     * starts a shutdown timer if so.
-     *
-     * @since S60 v3.2
-     * @param ?arg1 ?description
-     */
-     void CheckIdle();
-
-    /**
-     * ?description
-     *
-     * @since S60 v3.2
-     * @param ?arg1 ?description
-     */
-    TInt SetPowerState( TBool aState );
-
-    /**
-     * ?description
-     *
-     * @since S60 v3.2
-     * @param ?arg1 ?description
-     */
-    TInt SetLocalNameL();
-    
-    TInt GetLocalNameFromRegistryL(TDes& aName);
-
-    /**
-     * ?description
-     *
-     * @since S60 v3.2
-     * @param ?arg1 ?description
-     */
-    void SetClassOfDeviceL();
-
-    /**
-     * ?description
-     *
-     * @since S60 v3.2
-     * @param ?arg1 ?description
-     */
-    void InitBTStackL();
-
-    /**
-     * ?description
-     *
-     * @since S60 v3.2
-     * @param ?arg1 ?description
-     */
-    void StopBTStackL();
-
-    /**
-     * ?description
-     *
-     * @since S60 v3.2
-     * @param ?arg1 ?description
-     */
-    void UpdateCenRepPowerKeyL( TBTPowerStateValue aValue );
-
-    /**
-     * ?description
-     *
-     * @since S60 v3.2
-     * @param ?arg1 ?description
-     */
-    void LoadBTPowerManagerL();
-
-    /**
-     * ?description
-     *
-     * @since S60 v3.2
-     * @param ?arg1 ?description
-     */
-    void ManageDIServiceL( TBool aState );
-    
-    /**
      * Reads the product-specific IDs for this phone from central repository.
      * These values are used in the BT Device Information profile.
      *
@@ -358,19 +336,6 @@
      * @param aProductId On return, holds the product ID for this phone.
      */
     void GetProductIdsL( TInt& aVendorId, TInt& aProductId );
-    
-	/**
-     * Checks if a client requests temporary power on/off, and keeps track 
-     * of the number of clients requesting that.
-     *
-     * @since S60 v5.0
-     * @param aCurrentState On return, will contain the current power state.
-     * @param aNewState The requested power state.
-     * @param aTemporary Indicates if this is about a tempororary state change.
-     */
-    void CheckTemporaryPowerStateL( TBTPowerStateValue& aCurrentState, 
-                                     TBTPowerStateValue aNewState, 
-                                     TBool aTemporary );
 
     /**
      * Callback function for expiry of CDeltaTimer timer of temporary 
@@ -383,16 +348,6 @@
     static TInt ScanModeTimerCallBack( TAny* aPtr );
     
     /**
-     * Callback function for completion of disconnecting all 
-     * Bluetoooth Baseband links.
-     *
-     * @since S60 v3.2
-     * @param aPtr Pointer to ourselves.
-     * @return Result
-     */
-    static TInt DisconnectAllCallBack( TAny* aPtr );
-    
-    /**
      * Callback function for expiriy CDeltaTimer timer of server idle timeout.
      *
      * @since S60 v3.2
@@ -410,17 +365,7 @@
      * @return Result
      */
     static TInt DebugModeTimerCallBack( TAny* aPtr );
-    
-    /**
-     * Callback function for turning BT off automatically after all
-     * connections are gone.
-     *
-     * @since S60 v5.0
-     * @param aPtr Pointer to ourselves.
-     * @return Result
-     */
-    static TInt AutoPowerOffCallBack( TAny* aPtr );
-	
+
 private: // data
 
     /**
@@ -436,28 +381,6 @@
     TUint32 iDiSdpRecHandle;
 
     /**
-     * Flag indicating if BT is going to be switched off automatically.
-     */
-    TBool iAutoSwitchOff;
-
-    /**
-     * Number of clients that are using BT temporarily.
-     * Note that this is equal or less than the active number of links.
-     */
-    TInt iAutoOffClients;
-
-    /**
-     * Flag indicating hidden mode has been set for temporary power on.
-     */
-    TBool iRestoreVisibility;
-
-    /**
-    * To decide wether DUT mode should be enabled in power mode
-    * change callback.
-    */   
-    TBool iEnableDutMode;
-
-    /**
      * Remember which timer has been queued. (CDeltaTimer does not 
      * provide this information).
      */
@@ -477,24 +400,13 @@
      * Callback for expiry of idle timer.
      */
     TDeltaTimerEntry iIdleCallBack;
+
     /**
      * Callback for expiry of Simple Pairing debug mode.
      */
     TDeltaTimerEntry iDebugModeCallBack;
 
     /**
-     * Handle to BT Power Manager library; this handle must exist 
-     * for the lifetime of the loaded library.
-     */
-    RLibrary iPowerMgrLib;
-#ifndef __WINS__
-    /**
-     *  Handle for DUT mode API
-     */
-    RBluetoothDutMode iDutMode;
-#endif  //__WINS__  
-
-    /**
      * Pairing manager.
      */
     CBTEngPairMan* iPairMan;
@@ -503,20 +415,25 @@
     * Socket Server instance for this and other classes to access Bluetooth socket APIs.
     */   
     RSocketServ iSocketServ;
-    
-    
+
     /**
     * Registry Server instance for bteng to access Bluetooth registry APIs.
     */      
     RBTRegServ iBTRegServ;
-     
+
     /**
-     * BT Power Manager.
+     * Our state machine for handling power on/off.
      * Own.
      */
     CBTEngSrvState* iServerState;
 
     /**
+     * Hardware and stack settings manager.
+     * Own.
+     */
+    CBTEngSrvSettingsMgr* iSettingsMgr;
+
+    /**
      * ECOM plugin manager.
      * Own.
      */
@@ -535,18 +452,6 @@
     CBTEngSrvKeyWatcher* iWatcher;
 
     /**
-     * BT Power Manager (HCIv2 version).
-     */
-    RBTPowerControl iPowerMgr;
-
-#ifdef __WINS__
-    /**
-     * Current BT power state (power manager is not used in emulator).
-     */
-    TBTPowerState iPowerState;
-#endif  //__WINS__
-
-    /**
      * SDP database handler.
      * Own.
      */
@@ -558,7 +463,6 @@
      */
     CDeltaTimer* iTimer;
 
-    BluetoothFeatures::TEnterpriseEnablementMode iEnterpriseEnablementMode;
     };
 
 
--- a/bluetoothengine/bteng/inc/btengsrvsession.h	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/bteng/inc/btengsrvsession.h	Fri Mar 12 15:43:23 2010 +0200
@@ -73,12 +73,6 @@
                                  TBTEngConnectionStatus aConnStatus, 
                                  RBTDevAddrArray* aArray, TInt aErr );
 
-    /**
-     * Completes client's pairing request.
-     * @param aResult the resultof pairing the client will receive.
-     */
-    TInt CompletePairRequest( TInt aResult );
-    
 private: // from base class CSession2
 
     /**
@@ -131,22 +125,22 @@
     void DispatchMessageL( const RMessage2& aMessage );
 
     /**
-     * Cancels outstanding pairing request.
+     * Cancels outstanding request.
      */
-    void CancelPairRequest();
-    
+    void CancelRequest();
+
+    /**
+     * Checks if power is on, and leaves with error KErrNotReady if not.
+     */
+    void CheckPowerOnL();
+
 private: // data
+
     /**
      * Client-server message containing the thread handle of the client.
      * For connection notifications.
      */
     RMessage2 iNotifyConnMessage;
-
-    /**
-     * For connection notifications.
-     * For outgoing pairing request.
-     */
-    RMessage2 iPairMessage;
     
     /**
      * Flag indicating if this client requested BT to be switched on temporarily.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/bluetoothengine/bteng/inc/btengsrvsettingsmgr.h	Fri Mar 12 15:43:23 2010 +0200
@@ -0,0 +1,312 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Class to manage Bluetooth hardware and stack settings.
+*
+*/
+
+#ifndef BTENGSRVSETTINGSMGR_H
+#define BTENGSRVSETTINGSMGR_H
+
+#include <bluetooth/btpowercontrol.h>
+#include <btfeaturescfg.h>
+#ifndef __WINS__
+#include <bluetooth/dutmode.h>
+#endif  //__WINS__  
+
+#include "btengprivatecrkeys.h"
+#include "btengconstants.h"
+#include "btengactive.h"
+
+class CBTEngServer;
+
+
+/**
+ *  ?one_line_short_description
+ *  ?more_complete_description
+ *
+ *  @code
+ *   ?good_class_usage_example(s)
+ *  @endcode
+ *
+ *  @lib ?library
+ *  @since S60 ?S60_version *** for example, S60 v3.0
+ */
+NONSHARABLE_CLASS( CBTEngSrvSettingsMgr ) : public CBase,
+                                            public MBTEngActiveObserver
+    {
+
+public:
+
+    /**
+     * Two-phased constructor.
+     * @param aServer Pointer to server instance.
+     */
+    static CBTEngSrvSettingsMgr* NewL( CBTEngServer* aServer );
+
+    /**
+     * Destructor.
+     */
+    virtual ~CBTEngSrvSettingsMgr();
+
+    /**
+     * Utility to get the Bluetooth hardware power state.
+     *
+     * @since Symbian^3
+     * @param aState On return, this will contain the current HW power state.
+     * @return KErrNone if successful, otherwise one of the system-wide error codes.
+     */
+    TInt GetHwPowerState( TBTPowerState& aState );
+
+    /**
+     * Set the Bluetooth hardware power state.
+     *
+     * @since Symbian^3
+     * @param aState The new power state.
+     */
+    TInt SetHwPowerState( TBTPowerState aState );
+
+    /**
+     * Set Bluetooth on or off. This function is for internal classes of bteng server
+     * for power management.
+     *
+     * @since Symbian^3
+     * @param aState The new power state.
+     * @param aTemporary Turn BT off after use (ETrue) or not (EFalse).
+     */
+    void SetPowerStateL( TBTPowerState aState, TBool aTemporary );
+    
+    /**
+     * Set Bluetooth on or off upon a client power management request.
+     * This function is only for power management request from clients of bteng server.
+     *
+     * @since Symbian^3
+     * @param aState The new power state.
+     * @param aTemporary Turn BT off after use (ETrue) or not (EFalse).
+     */
+    void SetPowerStateL( const RMessage2 aMessage );
+    
+    /**
+     * Initialize Bluetooth stack settings.
+     *
+     * @since S60 v3.2
+     * @param ?arg1 ?description
+     */
+    void InitBTStackL();
+
+    /**
+     * Reset settings and disconnect all links.
+     *
+     * @since Symbian^3
+     */
+    void StopBTStackL();
+
+    /**
+     * Update the central repository key for Bluetooth power state.
+     *
+     * @since Symbian^3
+     * @param aValue The new Bluetooth power state.
+     */
+    void UpdateCenRepPowerKeyL( TBTPowerState aValue );
+
+    /**
+    * ?description
+    *
+    * @since S60 v3.2
+    * @param ?arg1 ?description
+    */
+    void SetUiIndicatorsL();
+    
+    /**
+    * ?description
+    *
+    * @since S60 v3.2
+    * @param ?arg1 ?description
+    */
+    void SetIndicatorStateL( const TInt aIndicator, const TInt aState );
+
+    /**
+     * Update the Bluetooth visibility mode.
+     *
+     * @since Symbian^3
+     * @param ?arg1 ?description
+     */
+    void SetVisibilityModeL( TBTVisibilityMode aMode, TInt aTime );
+
+    /**
+     * Update the Bluetooth visibility mode.
+     *
+     * @since Symbian^3
+     * @param ?arg1 ?description
+     */
+    void UpdateVisibilityModeL( TInt aStackScanMode );
+
+    /**
+     * Set Device Under Test mode.
+     *
+     * @since Symbian^3
+     * @param aDutMode The mode to be set (DUT mode on or off).
+     */
+    void SetDutMode( TInt aDutMode );
+
+    /**
+     * Timed visible mode has expired. 
+     *
+     * @since Symbian^3
+     */
+    void ScanModeTimerCompletedL();
+
+    /**
+     * Check whether BT should be turned off automatically.
+     *
+     * @since Symbian^3
+     */
+    void CheckAutoPowerOffL();
+
+    /**
+     * Queue a timer if secure simple pairing debug mode has been enabled.
+     *
+     * @since Symbian^3
+     * @param aDebugMode State of Simple Pairing debug mode.
+     */
+    void CheckSspDebugModeL( TBool aDebugMode );
+
+    /**
+     * Be informed that a session will be closed.
+     *
+     * @since Symbian^3
+     * @param aSession the session to be cloased.
+     */
+    void SessionClosed(CSession2* aSession );
+    
+private:
+    
+// from base class MBTEngActiveObserver
+
+    /**
+     * From MBTEngActiveObserver.
+     * Callback to notify that an outstanding request has completed.
+     *
+     * @since Symbian^3
+     * @param aActive Pointer to the active object that completed.
+     * @param aId The ID that identifies the outstanding request.
+     * @param aStatus The status of the completed request.
+     */
+    virtual void RequestCompletedL( CBTEngActive* aActive, TInt aId, TInt aStatus );
+
+    /**
+     * From MBTEngActiveObserver.
+     * Callback to notify that an error has occurred in RunL.
+     *
+     * @since Symbian^3
+     * @param aActive Pointer to the active object that completed.
+     * @param aId The ID that identifies the outstanding request.
+     * @param aStatus The status of the completed request.
+     */
+    virtual void HandleError( CBTEngActive* aActive, TInt aId, TInt aError );
+
+private:
+
+    /**
+     * C++ default constructor.
+     */
+    CBTEngSrvSettingsMgr( CBTEngServer* aServer );
+
+    /**
+     * Symbian second-phase constructor.
+     */
+    void ConstructL();
+
+    /**
+     * Open a handle to the Bluetooth power manager, and 
+     * initialize the power to off.
+     *
+     * @since Symbian^3
+     */
+    void LoadBTPowerManagerL();
+
+    /**
+     * Checks if a client requests temporary power on/off, and keeps track 
+     * of the number of clients requesting that.
+     *
+     * @since Symbian^3
+     * @param aCurrentState On return, will contain the current power state.
+     * @param aNewState The requested power state.
+     * @param aTemporary Indicates if this is about a tempororary state change.
+     */
+    void CheckTemporaryPowerStateL( TBTPowerState& aCurrentState,
+                                     TBTPowerState aNewState, TBool aTemporary );
+
+    /**
+     * Set the Class of Device.
+     *
+     * @since Symbian^3
+     */
+    void SetClassOfDeviceL();
+
+private: // data
+
+#ifdef __WINS__
+    /**
+     * Current BT power state (power manager is not used in emulator).
+     */
+    TBTPowerState iPowerState;
+#endif  //__WINS__
+
+    /**
+     * Flag indicating if BT is allowed to be turned on.
+     */
+    BluetoothFeatures::TEnterpriseEnablementMode iEnterpriseEnablementMode;
+
+    /**
+     * Flag indicating if BT is going to be switched off automatically.
+     */
+    TBool iAutoSwitchOff;
+
+    /**
+     * Number of clients that are using BT temporarily.
+     * Note that this is equal or less than the active number of links.
+     */
+    TInt iAutoOffClients;
+
+    /**
+     * Flag indicating hidden mode has been set for temporary power on.
+     */
+    TBool iRestoreVisibility;
+
+    /**
+     * BT power control.
+     */
+    RBTPowerControl iPowerMgr;
+
+    /**
+     * Active object helper.
+     * Own.
+     */
+    CBTEngActive* iActive;
+
+    /**
+     * The server instance.
+     * Not own.
+     */
+    CBTEngServer* iServer;
+    
+    /**
+     * Client-server message for power change requests.
+     */
+    RMessage2 iMessage;
+    
+    };
+
+
+#endif // BTENGSRVSETTINGS_H
--- a/bluetoothengine/bteng/inc/btengsrvstate.h	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/bteng/inc/btengsrvstate.h	Fri Mar 12 15:43:23 2010 +0200
@@ -20,18 +20,13 @@
 #ifndef BTENGSRVSTATE_H
 #define BTENGSRVSTATE_H
 
-
-//#include <?include_file>
+#include <bluetooth/hci/hcitypes.h>
 
 #include "btengactive.h"
-#include "btserversdkcrkeys.h"
 
 class MBTEngActiveObserver;
 class CBTEngServer;
 
-/**  ?description */
-//const ?type ?constant_var = ?constant;
-
 
 /**
  *  Class CBTEngSrvState
@@ -93,32 +88,26 @@
     virtual ~CBTEngSrvState();
 
     /**
-     * ?description
+     * Getter for the current operation.
      *
      * @since S60 v3.2
-     * @param ?arg1 ?description
-     * @param ?arg2 ?description
-     * @return ?description
+     * @return The current operation.
      */
     CBTEngSrvState::TBTEngSrvOperation CurrentOperation();
 
     /**
-     * ?description
+     * Start the state machine. If the state machine was already running,
+     * it is simply restarted.
      *
      * @since S60 v3.2
      * @param ?arg1 ?description
-     * @param ?arg2 ?description
-     * @return ?description
      */
-    void StartStateMachineL( TBool aState );
+    void StartStateMachineL( TBTPowerState aState );
 
     /**
-     * ?description
+     * Schedule the next state operation.
      *
      * @since S60 v3.2
-     * @param ?arg1 ?description
-     * @param ?arg2 ?description
-     * @return ?description
      */
     void ChangeState();    
 
@@ -133,11 +122,20 @@
      * Symbian 2nd-phase constructor
      */
     void ConstructL();
-    
+
+    /**
+     * Callback function for asynchronous cycle.
+     */
     static TInt ChangeStateCb(TAny* aThis);
-    
+
+    /**
+     * Execute the next state operation.
+     */
     void RequestCompletedL();
-    
+
+    /**
+     * Handle an error that occurred during a state operation.
+     */
     void HandleError(TInt aError);
 
 private: // data
--- a/bluetoothengine/bteng/rom/bteng.iby	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/bteng/rom/bteng.iby	Fri Mar 12 15:43:23 2010 +0200
@@ -29,9 +29,8 @@
 file=ABI_DIR\BUILD_DIR\btengdiscovery.dll         SHARED_LIB_DIR\btengdiscovery.dll
 file=ABI_DIR\BUILD_DIR\btfeatures.dll             SHARED_LIB_DIR\btfeatures.dll
 file=ABI_DIR\BUILD_DIR\btengsettings.dll          SHARED_LIB_DIR\btengsettings.dll
-data=ZPRIVATE\10005950\backup_registration.xml	private\10005950\backup_registration.xml
-data=ZPRIVATE\10003A3F\APPS\bttoggle_reg.rsc 	Private\10003a3f\apps\bttoggle_reg.rsc
-
+data=ZPRIVATE\10005950\backup_registration.xml		private\10005950\backup_registration.xml
+data=ZPRIVATE\10003A3F\APPS\bttoggle_reg.rsc 			Private\10003a3f\apps\bttoggle_reg.rsc
 data=DATAZ_\RESOURCE_FILES_DIR\btengsdp.rsc       RESOURCE_FILES_DIR\btengsdp.rsc
 data=DATAZ_\RESOURCE_FILES_DIR\btrfs.txt       RESOURCE_FILES_DIR\btrfs.txt
 
--- a/bluetoothengine/bteng/src/btengpairman.cpp	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/bteng/src/btengpairman.cpp	Fri Mar 12 15:43:23 2010 +0200
@@ -134,6 +134,10 @@
         iPairingServ->Close();
         delete iPairingServ;
         }
+    if ( !iMessage.IsNull() )
+        {
+        iMessage.Complete( KErrCancel );
+        }
     TRACE_FUNC_EXIT
     }
 
@@ -156,14 +160,24 @@
             }
         case EBTEngPairDevice:
             {
+            if ( !iMessage.IsNull() )
+                {
+                User::Leave( KErrServerBusy );
+                }
             TBTDevAddrPckgBuf addrPkg;
             aMessage.ReadL( KBTEngAddrSlot, addrPkg );
             PairDeviceL( addrPkg(), aMessage.Int1() );
+            iMessage = RMessage2( aMessage );
             break;
             }
         case EBTEngCancelPairDevice:
             {
-            CancelCommand( opcode );
+            // Only the client who requested pairing can cancel it:
+            if ( !iMessage.IsNull() && aMessage.Session() == iMessage.Session() )
+                {
+                iPairer->CancelOutgoingPair();
+                iMessage.Complete( KErrCancel );
+                }
             break;
             }
         default:
@@ -177,27 +191,6 @@
     }
 
 // ---------------------------------------------------------------------------
-// Cancels outgoing pairing requests
-// ---------------------------------------------------------------------------
-//
-void CBTEngPairMan::CancelCommand( TInt aOpCode )
-    {
-    switch( aOpCode )
-        {
-        case EBTEngPairDevice:
-            {
-            TRACE_FUNC_ENTRY
-            if ( iPairer )
-                {
-                iPairer->CancelOutgoingPair();
-                }
-            TRACE_FUNC_EXIT
-            break;
-            }
-        }
-    }
-
-// ---------------------------------------------------------------------------
 // Handle a change in BTRegistry remote devices table.
 // ---------------------------------------------------------------------------
 //
@@ -228,7 +221,7 @@
 //
 RSocketServ& CBTEngPairMan::SocketServ()
     {
-    return iServer.SocketServ();
+    return iServer.SocketServer();
     }
 
 // ---------------------------------------------------------------------------
@@ -237,7 +230,7 @@
 //
 RBTRegServ& CBTEngPairMan::BTRegServ()
     {
-    return iServer.BTRegServ();
+    return iServer.RegistrServer();
     }
 
 // ---------------------------------------------------------------------------
@@ -265,13 +258,23 @@
         aErr = KErrNone;
         }
     // we must complete client's pairing request:
-    iServer.iSessionIter.SetToLast();
-    CBTEngSrvSession* session = (CBTEngSrvSession*) iServer.iSessionIter--;
-    TInt ret( KErrNotFound );
-    while( session && ret )
+    if ( !iMessage.IsNull()  )
         {
-        ret = session->CompletePairRequest( aErr );
-        session = (CBTEngSrvSession*) iServer.iSessionIter--;
+        iMessage.Complete( aErr );
+        }
+    TRACE_FUNC_EXIT
+    }
+
+// ---------------------------------------------------------------------------
+// A session will be ended, completes the pending request for this session.
+// ---------------------------------------------------------------------------
+//
+void CBTEngPairMan::SessionClosed( CSession2* aSession )
+    {
+    TRACE_FUNC_ARG( ( _L( " session %x"), aSession ) )
+    if ( !iMessage.IsNull() && iMessage.Session() == aSession )
+        {
+        iMessage.Complete( KErrCancel );
         }
     TRACE_FUNC_EXIT
     }
--- a/bluetoothengine/bteng/src/btengserver.cpp	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/bteng/src/btengserver.cpp	Fri Mar 12 15:43:23 2010 +0200
@@ -16,12 +16,6 @@
 */
 
 
-
-#ifdef SYMBIAN_ENABLE_SPLIT_HEADERS
-#include <bthci.h>
-#include <bt_subscribe_partner.h>
-#endif
-
 #include <e32base.h>
 #include <btmanclient.h>
 #include <es_sock.h>
@@ -29,20 +23,18 @@
 #include <utf.h>
 #include <ecom/ecom.h>
 #include <centralrepository.h>
-#include <featmgr.h>
-#include <AknSmallIndicator.h>
-#include <avkon.hrh>
+#include <btengdomaincrkeys.h>
 #include <bt_subscribe.h>
 #include "btengserver.h"
 #include "btengsrvstate.h"
 #include "btengsrvsession.h"
 #include "btengsrvpluginmgr.h"
 #include "btengsrvbbconnectionmgr.h"
+#include "btengsrvsettingsmgr.h"
 #include "btengsrvkeywatcher.h"
 #include "btengsdpdbhandler.h"
 #include "btengclientserver.h"
 #include "btengsecpolicy.h"
-#include "btengprivatecrkeys.h"
 #include "btengprivatepskeys.h"
 #include "btengplugin.h"
 #include "btengpairman.h"
@@ -50,43 +42,12 @@
 
 /**  Bluetooth Engine server thread name */
 _LIT( KBTEngThreadName, "BTEngine" );
-
-/**  Constant for converting minutes to microseconds */
-const TInt64 KMinutesInMicroSecs = MAKE_TINT64( 0, 60000000 );
-
-/**  Idle timeout for shutting down the server (when power is off, 
- *   and no clients are connected). The value is 3 seconds.
- */
+/**  Timeout (3 sec) for shutting down the server (when power is off and no clients connected). */
 const TInt KBTEngSrvIdleTimeout = 3000000;
-
-/**  Timeout for disabling Simple Pairing debug mode. The value is 30 minutes. */
-const TInt KBTEngSspDebugModeTimeout = 1800000000;
-
-/**  Timeout for determining that BT is not turned off automatically. 
- *   The value is 10.5 seconds.
- */
-const TInt KBTEngBtAutoOffTimeout = 10500000;
+/**  PubSub key read and write policies */
+_LIT_SECURITY_POLICY_C2( KBTEngPSKeyReadPolicy, ECapabilityLocalServices, ECapabilityReadDeviceData );
+_LIT_SECURITY_POLICY_C2( KBTEngPSKeyWritePolicy, ECapabilityLocalServices, ECapabilityWriteDeviceData );
 
-/**  Enumeration of bitmask for keeping track of different timers. */
-enum TTimerQueued
-    {
-    ENone               = 0x00,
-    EScanModeTimer      = 0x01,
-    EIdleTimer          = 0x02,
-    EAutoPowerOffTimer  = 0x04,
-    ESspDebugModeTimer  = 0x08 
-    };
-
-/**  PubSub key read and write policies */
-_LIT_SECURITY_POLICY_C2( KBTEngPSKeyReadPolicy, 
-                          ECapabilityLocalServices, ECapabilityReadDeviceData );
-_LIT_SECURITY_POLICY_C2( KBTEngPSKeyWritePolicy, 
-                          ECapabilityLocalServices, ECapabilityWriteDeviceData );
-
-// Default values for Major and Minor Device Class
-const TUint16 KCoDDefaultServiceClass = EMajorServiceTelephony | EMajorServiceObjectTransfer | EMajorServiceNetworking;
-const TUint8 KCoDDefaultMajorDeviceClass = EMajorDevicePhone;
-const TUint8 KCoDDefaultMinorDeviceClass = EMinorDevicePhoneSmartPhone;
 
 // ======== LOCAL FUNCTIONS ========
 
@@ -149,7 +110,6 @@
 CBTEngServer::CBTEngServer()
 :   CPolicyServer( EPriorityHigh, KBTEngServerPolicy )
     {
-    iEnableDutMode = EFalse;
     }
 
 
@@ -190,7 +150,6 @@
                                             RProperty::EInt,
                                             KBTEngPSKeyReadPolicy,
                                             KBTEngPSKeyWritePolicy) );
-    
     User::LeaveIfError( RProperty::Define( KPSUidBluetoothEnginePrivateCategory,
                                             KBTNotifierLocks,
                                             RProperty::EByteArray,
@@ -198,18 +157,19 @@
                                             KBTEngPSKeyWritePolicy) );    
     
     User::LeaveIfError( iSocketServ.Connect() );
-    LoadBTPowerManagerL();
+
         // The server is only started by its client, so leave the state 
         // machine in Init state. A request to turn power on will follow 
         // usually immediately.
     iServerState = CBTEngSrvState::NewL( this );
     iWatcher = CBTEngSrvKeyWatcher::NewL( this );
+    iSettingsMgr = CBTEngSrvSettingsMgr::NewL( this );
     iPluginMgr = CBTEngSrvPluginMgr::NewL( this );
     iBBConnMgr = CBTEngSrvBBConnMgr::NewL( iSocketServ );
-    
+
     User::LeaveIfError( iBTRegServ.Connect() );
     iPairMan = CBTEngPairMan::NewL( *this );
-    
+
     TCallBack idleCb( IdleTimerCallBack, this );
     iIdleCallBack.Set( idleCb );
     TCallBack sspCb( DebugModeTimerCallBack, this );
@@ -219,14 +179,6 @@
     TCallBack powerOffCb( AutoPowerOffCallBack, this );
     iPowerOffCallBack.Set( powerOffCb );
     iTimer = CDeltaTimer::NewL(CActive::EPriorityLow);
-    
-    iEnterpriseEnablementMode = BluetoothFeatures::EnterpriseEnablementL();
-	TRACE_INFO( ( _L( "iEnterpriseEnablementMode = %d" ), iEnterpriseEnablementMode) )
-    if ( iEnterpriseEnablementMode == BluetoothFeatures::EDisabled )
-        {
-        SetVisibilityModeL( EBTVisibilityModeNoScans, 0 );
-        }
-    
     TRACE_FUNC_EXIT
     }
 
@@ -256,7 +208,7 @@
         iTimerQueued = ENone;
         iTimer->Remove( iScanModeCallBack );
         iTimer->Remove( iPowerOffCallBack );
-        iTimer->Remove( iIdleCallBack);
+        iTimer->Remove( iIdleCallBack );
         iTimer->Remove( iDebugModeCallBack );
         }
     RProperty::Delete( KPSUidBluetoothTestingMode, KBTDutEnabled );
@@ -269,171 +221,34 @@
     delete iTimer;
     delete iSdpDbHandler;
     delete iWatcher;
+    delete iSettingsMgr;
     delete iPluginMgr;
     delete iBBConnMgr;
     delete iServerState;
     delete iPairMan;
-    iPowerMgr.Close();
     iSocketServ.Close();
     iBTRegServ.Close();
     }
 
-
 // ---------------------------------------------------------------------------
 // Turn BT on or off.
 // ---------------------------------------------------------------------------
 //
-void CBTEngServer::SetPowerStateL( TBTPowerStateValue aState, TBool aTemporary )
+void CBTEngServer::SetPowerStateL( TBTPowerState aState, TBool aTemporary )
     {
-    TRACE_FUNC_ARG( ( _L( "setting power state %d" ), (TInt) aState ) )
-    if ( aState == EBTPowerOn && iEnterpriseEnablementMode == BluetoothFeatures::EDisabled )
-        {
-        TRACE_INFO( ( _L( "\tno we're not... Bluetooth is enterprise-IT-disabled" ) ) )
-        User::Leave(KErrNotSupported);
-        }
-    
-    TBTPowerStateValue currentState = EBTPowerOff;
-    CheckTemporaryPowerStateL( currentState, aState, aTemporary );
-
-    if( ( currentState == aState || ( aTemporary && aState == EBTPowerOff ) ) && iServerState->CurrentOperation() == CBTEngSrvState::ESrvOpIdle )
-        {
-		// The requested power state is already active, ignore silently.
-		// We don't return an error here, as there is no error situation.
-        TRACE_INFO( ( _L( "SetPowerStateL: nothing to do" ) ) )
-        if(currentState == aState)
-            {
-            // Make sure that the CenRep key is in sync.
-            // During boot-up, the pwoer is set from the CenRep key, so we could 
-            // end up out-of-sync.
-            TRACE_INFO( ( _L( "SetPowerStateL: currentState == aState" ) ) )
-            UpdateCenRepPowerKeyL( aState );
-            } 
-        return;
-        }
-    if( aState )
-        {
-            // Hardware power on is the first step.
-        User::LeaveIfError( SetPowerState( aState ) );
-        }
-    else
-        {
-        //Prevent BT visibility in the situation when we turn OFF BT Engine 
-        //but FM Radio is still alive
-        SetVisibilityModeL( EBTVisibilityModeNoScans, 0 );
-            // Hardware power off is the last step.
-            // First disconnect all plug-ins.
-        iPluginMgr->DisconnectAllPlugins();
-        }
-        // We only signal that BT is on after everything has completed (through 
-        // the CenRep power state key), so that all services are initialized.
-        // We signal that BT is off immediately though, so that our clients will 
-        // not try to use BT during power down.
-    iServerState->StartStateMachineL( (TBool) aState );
+    TRACE_FUNC_ARG( ( _L( "setting power state %d (temporary=%d" ), (TInt) aState, aTemporary ) )
+    iSettingsMgr->SetPowerStateL( aState, aTemporary );
     TRACE_FUNC_EXIT
     }
 
-
 // ---------------------------------------------------------------------------
-// ?implementation_description
+// Turn BT on or off.
 // ---------------------------------------------------------------------------
 //
-void CBTEngServer::SetVisibilityModeL( TBTVisibilityMode aMode, TInt aTime )
+void CBTEngServer::SetPowerStateL(const RMessage2 aMessage )
     {
     TRACE_FUNC_ENTRY
-    
-    if ( aMode != EBTVisibilityModeNoScans && iEnterpriseEnablementMode == BluetoothFeatures::EDisabled )
-        {
-        TRACE_INFO( ( _L( "\tnot changing anything... Bluetooth is enterprise-IT-disabled" ) ) )
-        User::Leave(KErrNotSupported);
-        }
-
-    TInt err = KErrNone;
-    iTimerQueued &= ~EScanModeTimer;
-    iTimer->Remove( iScanModeCallBack );
-    if( aMode != EBTVisibilityModeNoScans )
-        {
-        CRepository* cenRep = CRepository::NewL( KCRUidBTEngPrivateSettings );
-        err = cenRep->Set( KBTDiscoverable, aMode );
-        delete cenRep;
-        }
-    if( !err && aMode == EBTVisibilityModeTemporary )
-        {
-            // We need TInt64 here, as the max. time in microseconds for the 
-            // max. value (1 hour) is larger than KMaxTInt32.
-        TInt64 timeMicroSec = MAKE_TINT64( 0, aTime );
-        timeMicroSec = timeMicroSec * KMinutesInMicroSecs;
-        TTimeIntervalMicroSeconds interval( timeMicroSec );
-            // Queue callback to set the visibility back to hidden.
-        err = iTimer->QueueLong( interval, iScanModeCallBack );
-        iTimerQueued |= EScanModeTimer;
-        aMode = EBTVisibilityModeGeneral;
-		}
-    else if( !err && iRestoreVisibility )
-        {
-            // The user overrides, do not restore visibility mode anymore.
-        iRestoreVisibility = EFalse;
-        }
-    if( !err )
-        {
-        err = RProperty::Set( KUidSystemCategory, 
-                               KPropertyKeyBluetoothSetScanningStatus, aMode );
-        }
-    TBool hiddenMode = ( aMode == EBTVisibilityModeHidden );
-    if( !err && aMode != EBTVisibilityModeNoScans )
-        {
-            // In hidden mode, we only accept connections from paired devices.
-        err = RProperty::Set( KUidSystemCategory, 
-                               KPropertyKeyBluetoothSetAcceptPairedOnlyMode, 
-                               hiddenMode );
-        }
-
-    User::LeaveIfError( err );  // To communicate the result to the client.
-    TRACE_FUNC_EXIT
-    }
-    
-// ---------------------------------------------------------------------------
-// The method is called when BT stack scanning mode P&S key is changed
-// ---------------------------------------------------------------------------
-//
-void CBTEngServer::UpdateVisibilityModeL( TInt aStackScanMode )
-    {
-    TRACE_FUNC_ENTRY
-    TRACE_INFO( ( _L( "[BTEng]\t aStackScanMode: %d" ), aStackScanMode ) )
-    TBTVisibilityMode currentMode;
-    
-    CRepository* cenRep = CRepository::NewLC( KCRUidBTEngPrivateSettings );
-    User::LeaveIfError( cenRep->Get( KBTDiscoverable, (TInt&) currentMode ) );
-    
-        // In case we are in temp visibility mode, we cannot always know whether the BT stack
-        // scan mode key was set by some external party or by us in SetVisibilityModeL above.
-        // Therefore we cannot stop the timer in case aMode is EBTVisibilityModeGeneral and 
-        // currentmode is EBTVisibilityModeTemporary
-    if( !( currentMode == EBTVisibilityModeTemporary && aStackScanMode == EBTVisibilityModeGeneral ) )
-        {
-            // Cancel the timer and queue it again if needed.
-        iTimerQueued &= ~EScanModeTimer;
-        iTimer->Remove( iScanModeCallBack );
-        if( currentMode != aStackScanMode )
-            {
-            if( aStackScanMode == EPageScanOnly || aStackScanMode == EInquiryAndPageScan )
-                {
-                User::LeaveIfError( cenRep->Set( KBTDiscoverable, aStackScanMode ) );
-                }
-            else if( aStackScanMode == EInquiryScanOnly )
-                {
-                    // We don't support ENoScansEnabled nor EInquiryScanOnly mode
-                    // -> Consider these as same as Hidden 
-                User::LeaveIfError( cenRep->Set( KBTDiscoverable, EBTVisibilityModeHidden ) );
-                }
-            else if( aStackScanMode == ENoScansEnabled )
-                {
-                //We don't change KBTDiscoverable here, because ENoScansEnabled
-                //indicates BT/SYSTEM shutdown is happening
-                }
-            }
-        }
-    SetUiIndicatorsL();
-    CleanupStack::PopAndDestroy( cenRep );
+    iSettingsMgr->SetPowerStateL( aMessage );
     TRACE_FUNC_EXIT
     }
 
@@ -454,90 +269,13 @@
 // ?implementation_description
 // ---------------------------------------------------------------------------
 //
-void CBTEngServer::SetDutMode( TInt aDutMode )
-    {
-    TRACE_FUNC_ARG( ( _L( "DUT mode %d" ), aDutMode ) )
-
-    if (aDutMode == EBTDutOff)
-        {
-        return;
-        }
-
-    TInt powerState = EBTPowerOff;
-    CRepository* cenrep = NULL;
-    
-    TRAPD(err, cenrep = CRepository::NewL(KCRUidBluetoothPowerState));
-    
-    if (!err && cenrep)
-        {
-        cenrep->Get(KBTPowerState, powerState);
-        delete cenrep;
-        cenrep = NULL;
-        }
-    else
-        {
-        return;
-        }
-
-    if (powerState == EBTPowerOn)
-        {
-
-#ifndef __WINS__
-
-        TInt err = iDutMode.Open();
-        TRACE_FUNC_ARG( ( _L( "Open DUT mode handle err %d" ), err) )
-        if(!err) 
-            {
-            iDutMode.ActivateDutMode();
-            iDutMode.Close();
-            }
-#endif  //__WINS__                        
-        }
-        iEnableDutMode = EFalse;    
-    }
-
-// ---------------------------------------------------------------------------
-// ?implementation_description
-// ---------------------------------------------------------------------------
-//
-void CBTEngServer::ScanModeTimerCompletedL()
-    {
-    TRACE_FUNC_ENTRY
-    // The timer has completed, so remove our reference as well.
-    iTimerQueued &= ~EScanModeTimer;
-    iTimer->Remove( iScanModeCallBack );
-    SetVisibilityModeL( EBTVisibilityModeHidden, 0 );
-    TBTPowerStateValue power = EBTPowerOff;
-    TInt err = GetHwPowerState( (TBTPowerStateValue&) power );
-    if( !err && power )
-        {
-        // Show a notification to the user
-        TBTGenericInfoNotiferParamsPckg pckg;
-        pckg().iMessageType = EBTVisibilityTimeout;
-        
-        RNotifier notifier;
-        TInt err = notifier.Connect();
-        if( !err )
-            {
-            err = notifier.StartNotifier( KBTGenericInfoNotifierUid, pckg );
-            notifier.Close();
-            }
-        }
-    TRACE_FUNC_RES( ( _L( "result: %d" ), err ) )
-    }
-
-
-// ---------------------------------------------------------------------------
-// ?implementation_description
-// ---------------------------------------------------------------------------
-//
 void CBTEngServer::DisconnectAllCompleted()
     {
         // Check if we are powering off. Otherwise we have just been 
         // requested to disconnect all, e.g. for system shutdown.
     if( iServerState->CurrentOperation() == CBTEngSrvState::EPowerOff )
         {
-        (void) SetPowerState( EFalse );
+        (void) iSettingsMgr->SetHwPowerState( EBTOff );
             // Put the state machine into idle state.
         iServerState->ChangeState();
         }
@@ -568,18 +306,20 @@
 
 
 // ---------------------------------------------------------------------------
-// A session has been ended, update the session count.
+// A session has been ended, update the session count and inform others.
 // ---------------------------------------------------------------------------
 //
-void CBTEngServer::RemoveSession( TBool aAutoOff )
+void CBTEngServer::RemoveSession( CSession2* aSession, TBool aAutoOff )
     {
 	TRACE_FUNC_ENTRY
 	TRACE_INFO( ( _L( "[CBTEngServer]\t aAutoOff %d"), aAutoOff ))
 	TRACE_INFO( ( _L( "[CBTEngServer]\t iSessionCount %d"), iSessionCount ))
     iSessionCount--;
+	iSettingsMgr->SessionClosed( aSession );
+	iPairMan->SessionClosed( aSession );
     if( aAutoOff )
         {
-        TRAP_IGNORE( SetPowerStateL( EBTPowerOff, ETrue ) );
+        TRAP_IGNORE( SetPowerStateL( EBTOff, ETrue ) );
         }
     else
         {
@@ -588,6 +328,64 @@
 	TRACE_FUNC_EXIT
     }
 
+// ---------------------------------------------------------------------------
+// Queue a new timer.
+// ---------------------------------------------------------------------------
+//
+void CBTEngServer::QueueTimer( CBTEngServer::TTimerQueued aTimer, TInt64 aInterval )
+    {
+    TRACE_FUNC_ARG( ( _L( "queueing timer %d" ), (TInt) aTimer ) )
+    iTimerQueued |= aTimer;
+    TTimeIntervalMicroSeconds interval( aInterval );
+    switch( aTimer )
+        {
+        case EScanModeTimer:
+            (void) iTimer->QueueLong( interval, iScanModeCallBack );
+            break;
+        case EIdleTimer:
+            iTimer->QueueLong( aInterval, iIdleCallBack );
+            break;
+        case EAutoPowerOffTimer:
+            iTimer->QueueLong( aInterval, iPowerOffCallBack );
+            break;
+        case ESspDebugModeTimer:
+            iTimer->QueueLong( aInterval, iDebugModeCallBack );
+            break;
+        default:
+            PanicServer( EBTEngPanicCorrupt );
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// Remove a queued timer.
+// ---------------------------------------------------------------------------
+//
+void CBTEngServer::RemoveTimer( CBTEngServer::TTimerQueued aTimer )
+    {
+    TRACE_FUNC_ARG( ( _L( "removing timer %d" ), (TInt) aTimer ) )
+    iTimerQueued &= ~aTimer;
+    // Timers can be removed without being queued, no need to check.
+    switch( aTimer )
+        {
+        case EScanModeTimer:
+            iTimer->Remove( iScanModeCallBack );
+            break;
+        case EIdleTimer:
+            iTimer->Remove( iIdleCallBack );
+            break;
+        case EAutoPowerOffTimer:
+            iTimer->Remove( iPowerOffCallBack );
+            break;
+        case ESspDebugModeTimer:
+            iTimer->Remove( iDebugModeCallBack );
+            break;
+        default:
+            PanicServer( EBTEngPanicCorrupt );
+        }
+    TRACE_FUNC_EXIT
+    }
+
 
 // ---------------------------------------------------------------------------
 // From class CPolicyServer.
@@ -628,10 +426,10 @@
     if( iSessionCount <= 0 )
         {
             // No more sessions, check the power state.
-        TBTPowerStateValue pwr = EBTPowerOff;
-        TInt err = GetHwPowerState( pwr );
-        TRACE_INFO( ( _L( "[BTEng]\t No sessions; power state: %d" ), pwr ) )
-        if( !err &&!pwr 
+        TBTPowerState power = EBTOff;
+        TInt err = iSettingsMgr->GetHwPowerState( power );
+        TRACE_INFO( ( _L( "[BTEng]\t No sessions; power state: %d" ), power ) )
+        if( !err && power == EBTOff
             && iServerState->CurrentOperation() == CBTEngSrvState::ESrvOpIdle )
             {
             TRACE_INFO( ( _L( "[BTEng]\t Power off; starting shutdown timer" ) ) )
@@ -648,259 +446,6 @@
 // ?implementation_description
 // ---------------------------------------------------------------------------
 //
-TInt CBTEngServer::SetPowerState( TBool aState )
-    {
-    TRACE_FUNC_ENTRY
-    TInt err = KErrNone;
-    // HCIv2 power state type is inverted from BTPM-defined type...
-    TBTPowerState powerState = (TBTPowerState) !aState;
-    TRequestStatus status;
-    
-#ifndef __WINS__
-    iPowerMgr.SetPower( powerState, NULL, status );
-    User::WaitForRequest( status );
-    err = status.Int();
-#else   //__WINS__
-    iPowerState = powerState;
-    err = KErrNone;
-#endif  //__WINS__
-
-   if( !err && aState )
-        {
-        TInt dutMode;
-        err = RProperty::Get( KPSUidBluetoothTestingMode, KBTDutEnabled, dutMode );
-        if( !err && dutMode == EBTDutOn )
-            {
-                // Set the DUT mode key to OFF since DUT mode is disabled at this point
-            err = RProperty::Set( KPSUidBluetoothTestingMode, KBTDutEnabled, EBTDutOff );
-            }
-            // Set the local name straight away, so that an error 
-            // in the loading of the BT stack will be detected here.
-            // Note that the HCIv2 power manager already loads the BT stack, 
-            // so we do not need to do that here.
-        TRAP(err,SetLocalNameL());
-        }
-    if( err )
-        {
-        // Power off if an error occurred during power on sequence.
-#ifndef __WINS__
-            // This cannot happen in emulator environment.
-        iPowerMgr.SetPower( EBTOff, NULL, status );
-        User::WaitForRequest( status );
-#endif  //__WINS__
-        } 
-    TRACE_FUNC_RES( ( _L( "result: %d" ), err ) )
-    return err;
-    }
-
-
-// ---------------------------------------------------------------------------
-// ?implementation_description
-// ---------------------------------------------------------------------------
-//
-TInt CBTEngServer::SetLocalNameL()
-    {
-    TRACE_FUNC_ENTRY
-    RHostResolver hostResolver;
-    TBuf<KMaxBluetoothNameLen> name;
-    name.Zero();
-    TBuf<KMaxBluetoothNameLen> tmpName;
-    
-    TInt err = RProperty::Get(KPropertyUidBluetoothCategory, 
-                                KPropertyKeyBluetoothGetDeviceName, name);
-    if(err == KErrNone)
-        {
-        err = RProperty::Get(KPropertyUidBluetoothCategory, 
-                               KPropertyKeyBluetoothSetDeviceName, tmpName);
-        if (tmpName.Compare(name))
-            {
-            // The name has not yet been updated. Use the new one.
-            name.Copy(tmpName);
-            }
-        }
-    // if name hasn't been set, check whats in the registry
-    if (err || !name.Length())
-        {
-        GetLocalNameFromRegistryL(name);
-        }
-
-    TRACE_INFO( ( _L( "[CBTEngServer]\t localDev.DeviceName(): '%S'" ), &name))
-    
-    CleanupClosePushL(hostResolver);
-    User::LeaveIfError(hostResolver.Open(iSocketServ, KBTAddrFamily, KBTLinkManager));
-    User::LeaveIfError(hostResolver.SetHostName(name));    
-    CleanupStack::PopAndDestroy(&hostResolver);
-
-    return KErrNone;
-    }
-
-
-// ---------------------------------------------------------------------------
-// Checks whats written in the registry in order to set host name 
-// ---------------------------------------------------------------------------
-//
-TInt CBTEngServer::GetLocalNameFromRegistryL(TDes& aName)
-    {
-    TRACE_FUNC_ENTRY
-    RBTRegServ btRegServ;
-    RBTLocalDevice btReg;
-    TBTLocalDevice localDev;
-    
-    CleanupClosePushL(btRegServ);
-    CleanupClosePushL(btReg);
-    
-    // In case of error, read local name from registry
-    aName.Zero();
-    User::LeaveIfError(btRegServ.Connect());
-    User::LeaveIfError(btReg.Open(btRegServ));
-    
-    // Read the BT local name from BT Registry.
-    User::LeaveIfError(btReg.Get(localDev));       
-
-    CleanupStack::PopAndDestroy(2,&btRegServ);
- 
-    // BT registry keeps the device name in UTF-8 format, convert to unicode.
-    // The error can be > 0 if there are unconverted characters.
-    TInt err = CnvUtfConverter::ConvertToUnicodeFromUtf8(aName, localDev.DeviceName());
-    if (err != KErrNone)
-        User::Leave(err);
-    return KErrNone; 
-    }
-
-
-// ---------------------------------------------------------------------------
-// ?implementation_description
-// ---------------------------------------------------------------------------
-//
-void CBTEngServer::SetClassOfDeviceL()
-    {
-    TRACE_FUNC_ENTRY
-    TUint16 serviceClass = KCoDDefaultServiceClass;
-        // Check from feature manager if stereo audio is enabled.
-    FeatureManager::InitializeLibL();
-    TBool supported = FeatureManager::FeatureSupported( KFeatureIdBtStereoAudio );
-    FeatureManager::UnInitializeLib();
-    if( supported )
-        {
-        // A2DP spec says we should set this bit as we are a SRC
-        serviceClass |= EMajorServiceCapturing;
-        }
-        // These values may nayway be overridden by HCI
-    TBTDeviceClass cod( serviceClass, KCoDDefaultMajorDeviceClass, 
-                         KCoDDefaultMinorDeviceClass );
-        // Ignore error, it is non-critical
-    (void) RProperty::Set( KPropertyUidBluetoothControlCategory, 
-                            KPropertyKeyBluetoothSetDeviceClass, cod.DeviceClass() );
-    TRACE_FUNC_EXIT
-    }
-
-
-// ---------------------------------------------------------------------------
-// ?implementation_description
-// ---------------------------------------------------------------------------
-//
-void CBTEngServer::InitBTStackL()
-    {
-    TRACE_FUNC_ENTRY
-    iBBConnMgr->Subscribe();
-    TBTVisibilityMode visibility = EBTVisibilityModeHidden;
-    CRepository* cenRep = CRepository::NewL( KCRUidBTEngPrivateSettings );
-    TInt err = cenRep->Get( KBTDiscoverable, (TInt&) visibility );
-    delete cenRep;
-    if (iRestoreVisibility == EFalse)
-        {
-        if( err || visibility == EBTVisibilityModeTemporary && !( iTimerQueued & EScanModeTimer ) )
-            {
-            visibility = EBTVisibilityModeHidden;
-            }
-        SetVisibilityModeL( visibility, 0 );
-        }
-    SetClassOfDeviceL();
-    TBool sspDebugMode = EFalse;
-    (void) RProperty::Get( KPropertyUidBluetoothCategory, 
-                            KPropertyKeyBluetoothGetSimplePairingDebugMode, 
-                            (TInt&) sspDebugMode );
-        // Only set debug mode to off if it is on, to prevent a loop notifications.
-    if( sspDebugMode )
-        {
-        sspDebugMode = EFalse;
-        // Add LeaveIfError if unsuccessful
-        (void) RProperty::Set(KPropertyUidBluetoothCategory, 
-                               KPropertyKeyBluetoothSetSimplePairingDebugMode,
-                               (TInt) sspDebugMode );
-        }
-    TRACE_FUNC_EXIT
-    }
-
-
-// ---------------------------------------------------------------------------
-// ?implementation_description
-// ---------------------------------------------------------------------------
-//
-void CBTEngServer::StopBTStackL()
-    {
-    TRACE_FUNC_ENTRY
-    TBTVisibilityMode visibility = EBTVisibilityModeHidden;
-    CRepository* cenRep = CRepository::NewL( KCRUidBTEngPrivateSettings );
-          // Ignore error here; if we can't read it, likely we can't set it either.
-    (void) cenRep->Get( KBTDiscoverable, (TInt&) visibility );
-    delete cenRep;
-    if( visibility == EBTVisibilityModeTemporary )
-        {
-        visibility = EBTVisibilityModeHidden;
-        SetVisibilityModeL( visibility, 0 );    // Also cancels scan mode timer.
-        }
-
-        // Stop listening to events
-    iBBConnMgr->Unsubscribe();
-        // Disconnect all links
-    TCallBack cb( DisconnectAllCallBack, this );
-    iBBConnMgr->DisconnectAllLinksL( cb );
-        // Results in a callback (which is called directly when there are no links).
-    TRACE_FUNC_EXIT
-    }
-
-
-// ---------------------------------------------------------------------------
-// Update the power state CenRep key.
-// ---------------------------------------------------------------------------
-//
-void CBTEngServer::UpdateCenRepPowerKeyL( TBTPowerStateValue aState )
-    {
-    TRACE_FUNC_ENTRY
-    CRepository* cenrep = CRepository::NewLC( KCRUidBluetoothPowerState );
-    User::LeaveIfError( cenrep->Set( KBTPowerState, (TInt) aState ) );
-    CleanupStack::PopAndDestroy( cenrep );
-    TRACE_FUNC_EXIT
-    }
-
-
-// ---------------------------------------------------------------------------
-// Loads the BT Power Manager; leaves if it cannot be loaded.
-// ---------------------------------------------------------------------------
-//
-void CBTEngServer::LoadBTPowerManagerL()
-    {
-    TRACE_FUNC_ENTRY
-    TRACE_INFO( ( _L( "[CBTEngServer]\t Using HCI API v2 power manager" ) ) )
-    User::LeaveIfError( iPowerMgr.Open() );
-#ifndef __WINS__
-    TRequestStatus status( KRequestPending );
-    iPowerMgr.SetPower( EBTOff, NULL, status );
-    User::WaitForRequest( status );
-    status = ( status.Int() == KErrAlreadyExists ? KErrNone : status.Int() ); 
-    User::LeaveIfError( status.Int() );
-#else   //__WINS__
-    iPowerState = EBTOff;
-#endif  //__WINS__
-    TRACE_FUNC_EXIT
-    }
-
-
-// ---------------------------------------------------------------------------
-// ?implementation_description
-// ---------------------------------------------------------------------------
-//
 void CBTEngServer::ManageDIServiceL( TBool aState )
     {
     TRACE_FUNC_ENTRY
@@ -959,353 +504,6 @@
     CleanupStack::PopAndDestroy( cenRep );  //cenRep
     }
 
-// ---------------------------------------------------------------------------
-// ?implementation_description
-// ---------------------------------------------------------------------------
-//
-void CBTEngServer::SetUiIndicatorsL()
-    {
-    TRACE_FUNC_ENTRY
-    TInt powerState = EBTPowerOff;
-    TBTVisibilityMode visibilityMode = EBTVisibilityModeHidden;
-    CRepository* cenrep = NULL;
-    TInt phys = 0;
-    TInt connecting = 0;
-    
-    cenrep = CRepository::NewLC( KCRUidBluetoothPowerState );
-    User::LeaveIfError( cenrep->Get( KBTPowerState, powerState ) );
-    CleanupStack::PopAndDestroy( cenrep );  
-    
-    if( powerState == EBTPowerOff )
-        {
-        SetIndicatorStateL( EAknIndicatorBluetoothModuleOn, EAknIndicatorStateOff );
-        SetIndicatorStateL( EAknIndicatorBluetooth, EAknIndicatorStateOff );
-        SetIndicatorStateL( EAknIndicatorBluetoothModuleOnVisible, EAknIndicatorStateOff );
-        SetIndicatorStateL( EAknIndicatorBluetoothVisible, EAknIndicatorStateOff );
-        }
-    else if( powerState == EBTPowerOn )
-        {
-        RProperty::Get( KPropertyUidBluetoothCategory, KPropertyKeyBluetoothPHYCount, phys );
-        RProperty::Get( KPropertyUidBluetoothCategory, KPropertyKeyBluetoothConnecting, connecting );
-        
-        cenrep = CRepository::NewLC( KCRUidBTEngPrivateSettings );
-        User::LeaveIfError( cenrep->Get( KBTDiscoverable, (TInt&) visibilityMode ) );
-        CleanupStack::PopAndDestroy( cenrep );
-        
-        if( visibilityMode == EBTVisibilityModeHidden )
-            {
-             if ( connecting ) // BT connecting and hidden
-                {
-                SetIndicatorStateL( EAknIndicatorBluetoothModuleOn, EAknIndicatorStateOff );
-                SetIndicatorStateL( EAknIndicatorBluetooth, EAknIndicatorStateAnimate );
-                }
-            else if ( phys > 0 ) // BT connection active and hidden     
-                {
-                SetIndicatorStateL( EAknIndicatorBluetoothModuleOn, EAknIndicatorStateOff );
-                SetIndicatorStateL( EAknIndicatorBluetooth, EAknIndicatorStateOn );
-                }
-            else  // BT connection not active and hidden
-                {
-                SetIndicatorStateL( EAknIndicatorBluetoothModuleOn, EAknIndicatorStateOn );
-                SetIndicatorStateL( EAknIndicatorBluetooth, EAknIndicatorStateOff );
-                }
-            SetIndicatorStateL( EAknIndicatorBluetoothModuleOnVisible, EAknIndicatorStateOff );
-            SetIndicatorStateL( EAknIndicatorBluetoothVisible, EAknIndicatorStateOff );
-            }           
-        else if( visibilityMode == EBTVisibilityModeGeneral || visibilityMode == EBTVisibilityModeTemporary )
-            {     
-            if ( connecting ) // BT connecting and visible
-                {
-                SetIndicatorStateL( EAknIndicatorBluetoothModuleOnVisible, EAknIndicatorStateOff );
-                SetIndicatorStateL( EAknIndicatorBluetoothVisible, EAknIndicatorStateAnimate );
-                }
-            else if ( phys > 0 ) // BT connection active and visible 
-                {
-                SetIndicatorStateL( EAknIndicatorBluetoothModuleOnVisible, EAknIndicatorStateOff );
-                SetIndicatorStateL( EAknIndicatorBluetoothVisible, EAknIndicatorStateOn );
-                }
-            else  // BT connection not active and visible
-                {
-                SetIndicatorStateL( EAknIndicatorBluetoothModuleOnVisible, EAknIndicatorStateOn );
-                SetIndicatorStateL( EAknIndicatorBluetoothVisible, EAknIndicatorStateOff );
-                }
-            SetIndicatorStateL( EAknIndicatorBluetoothModuleOn, EAknIndicatorStateOff );
-            SetIndicatorStateL( EAknIndicatorBluetooth, EAknIndicatorStateOff );
-            }
-        }
-    TRACE_FUNC_EXIT
-    }
-
-// ---------------------------------------------------------------------------
-// ?implementation_description
-// ---------------------------------------------------------------------------
-//
-void CBTEngServer::SetIndicatorStateL( const TInt aIndicator, const TInt aState )
-    {
-    CAknSmallIndicator* indicator = CAknSmallIndicator::NewLC( TUid::Uid( aIndicator ) );
-    indicator->SetIndicatorStateL( aState );
-    CleanupStack::PopAndDestroy( indicator ); //indicator
-    }
-
-// ---------------------------------------------------------------------------
-// Gets the current HW power state.
-// For now this is a separate method to isolate the different variations.
-// ---------------------------------------------------------------------------
-//
-TInt CBTEngServer::GetHwPowerState( TBTPowerStateValue& aState )
-    {
-    TRACE_FUNC_ENTRY
-    TInt err = KErrNone;
-    
-#ifndef __WINS__
-    err = iPowerMgr.GetPower( (TBTPowerState&) aState, NULL );
-#else   //__WINS__
-    aState = (TBTPowerStateValue) iPowerState;
-#endif  //__WINS__
-    
-        // HCIv2 power state type is inverted from BTPM-defined type...
-    aState = (TBTPowerStateValue) !aState;
-    TRACE_FUNC_ARG( ( _L( "Power state is %d, result %d" ), (TInt) aState, err ) )
-    return err;
-    }
-
-// ---------------------------------------------------------------------------
-// Check the power state and if BT gets turned off automatically.
-// ---------------------------------------------------------------------------
-//
-void CBTEngServer::CheckTemporaryPowerStateL( TBTPowerStateValue& aCurrentState, 
-    TBTPowerStateValue aNewState, TBool aTemporary )
-    {
-	TRACE_FUNC_ENTRY
-    User::LeaveIfError( GetHwPowerState( aCurrentState ) );
-    if( !aTemporary )
-        {
-            // Force the new power state, so clear all auto switch off flags.
-            // If power is off, this will anyway be ignored.
-        iAutoOffClients = 0;
-        iAutoSwitchOff = EFalse;
-        TCallBack cb;
-        iBBConnMgr->SetAutoSwitchOff( EFalse, cb );
-        if( iRestoreVisibility && aCurrentState == EBTPowerOn )
-            {
-                // Set visibility mode back to the value selected by the user.
-            SetVisibilityModeL( EBTVisibilityModeGeneral, 0 );
-            iRestoreVisibility = EFalse;
-            }
-        }
-    else
-        {
-        if( aCurrentState == aNewState )
-            {
-            if( iAutoSwitchOff && aNewState == EBTPowerOn )
-                {
-                iAutoOffClients++;
-                if( iTimerQueued & EAutoPowerOffTimer )
-                   {
-                   iTimer->Remove( iPowerOffCallBack );
-                   iTimerQueued &= ~EAutoPowerOffTimer;
-                   }
-                }
-            }
-        else if( iAutoSwitchOff || aNewState == EBTPowerOn )
-            {
-            aNewState == EBTPowerOff ? iAutoOffClients-- : iAutoOffClients++;
-            iAutoSwitchOff = ETrue;
-            if( aNewState == EBTPowerOff && iAutoOffClients <= 0 )
-                {
-                TCallBack powerOffCb( AutoPowerOffCallBack, this );
-                iBBConnMgr->SetAutoSwitchOff( ETrue, powerOffCb );
-                iTimer->Queue( KBTEngBtAutoOffTimeout, iPowerOffCallBack );
-                iTimerQueued |= EAutoPowerOffTimer;
-                }
-            else if( aNewState == EBTPowerOn )
-                {
-                CRepository* cenRep = CRepository::NewLC( KCRUidBTEngPrivateSettings );
-                TBTVisibilityMode visibility = EBTVisibilityModeGeneral;
-                TInt err = cenRep->Get( KBTDiscoverable, (TInt&) visibility );
-                CleanupStack::PopAndDestroy( cenRep );
-                if( !err && visibility == EBTVisibilityModeGeneral )
-                    {
-                    SetVisibilityModeL( EBTVisibilityModeHidden, 0 );
-                    iRestoreVisibility = ETrue;
-                    }
-                if( iTimerQueued & EAutoPowerOffTimer )
-                   {
-                   iTimer->Remove( iPowerOffCallBack );
-                   iTimerQueued &= ~EAutoPowerOffTimer;
-                   }
-                }
-            }
-        }
-    if( iAutoOffClients < 0 )
-        {
-        iAutoOffClients = 0;
-        }
-	TRACE_FUNC_EXIT	
-    }
-
-// ---------------------------------------------------------------------------
-// Check the power state and if BT gets turned off automatically.
-// This method is invoked either when the timer has expired, or
-// if there are no more connections while the timer was running.
-// ---------------------------------------------------------------------------
-//
-void CBTEngServer::CheckAutoPowerOffL()
-    {
-   	TRACE_FUNC_ENTRY
-	if ( iAutoOffClients > 0 )
-	{
-	TRACE_INFO( ( _L( "[CBTEngServer]\t iAutoOffClients %d"), iAutoOffClients ))
-	return;
-	}
-    TInt linkCount = 0;
-    TInt err = RProperty::Get( KPropertyUidBluetoothCategory, 
-                                KPropertyKeyBluetoothGetPHYCount, linkCount );
-    if( !err && !linkCount )
-        {
-        TRACE_INFO( ( _L( "[CBTEngServer]\t SetPowerStateL( EBTPowerOff, EFalse );")))
-        SetPowerStateL( EBTPowerOff, EFalse );
-        }
-    else
-        {
-        if( iRestoreVisibility )
-            {
-                // Set visibility mode back to the value selected by the user.
-            SetVisibilityModeL( EBTVisibilityModeGeneral, 0 );
-            iRestoreVisibility = EFalse;
-            }
-            // show note if non-audio connection exists
-        if ( !iPluginMgr->CheckAudioConnectionsL() )
-            {
-	        RNotifier notifier;
-	        TInt err = notifier.Connect();
-	        if( !err )
-	            {
-				TRequestStatus status;
-				TBTGenericInfoNotiferParamsPckg pckg;
-				pckg().iMessageType = EBTStayPowerOn;
-				TBuf8<sizeof(TInt)> result;
-	            //notifier.StartNotifier( KBTGenericInfoNotifierUid, pckg, result );
-				notifier.StartNotifierAndGetResponse( status, 
-                                                  KBTGenericInfoNotifierUid, 
-                                                  pckg, result );   // Reply buffer not used.
-				User::WaitForRequest( status );
-	            notifier.Close();
-		        }
-            }
-        iAutoOffClients = 0;
-        iAutoSwitchOff = EFalse;
-        TCallBack cb;
-        iBBConnMgr->SetAutoSwitchOff( EFalse, cb );
-        }
-	TRACE_FUNC_EXIT	
-    }
-
-// ---------------------------------------------------------------------------
-// ?implementation_description
-// ---------------------------------------------------------------------------
-//
-void CBTEngServer::CheckSspDebugModeL( TBool aDebugMode )
-    {
-    TRACE_FUNC_ARG( ( _L( "SSP debug mode state %d" ), (TInt) aDebugMode ) )
-    TBTPowerState pwr = EBTOff;
-    TBool currentMode = EFalse;
-    TInt err = RProperty::Get( KPropertyUidBluetoothCategory, 
-                                KPropertyKeyBluetoothGetSimplePairingDebugMode, 
-                                (TInt&) currentMode );
-#ifndef __WINS__
-    err = iPowerMgr.GetPower( pwr, NULL ); // Treat error as power off.
-#else   //__WINS__
-    pwr = iPowerState;
-#endif  //__WINS__
-    if( err || pwr == EBTOff )
-        {
-        iTimerQueued &= ~ESspDebugModeTimer;
-        iTimer->Remove( iDebugModeCallBack );
-            // Only set debug mode to off if it is on, to prevent a loop notifications.
-        if( currentMode )
-            {
-            (void) RProperty::Set( KPropertyUidBluetoothCategory, 
-                                    KPropertyKeyBluetoothSetSimplePairingDebugMode,
-                                    (TInt) aDebugMode );
-            }
-            // In case of an error in getting the power state, turn BT off. 
-            // If BT is already off, this call will be ignored.
-        SetPowerStateL( EBTPowerOff, EFalse );
-        }
-    else if( aDebugMode )
-        {
-            // Ignore if there already is a timer queued.
-        if( !( iTimerQueued & ESspDebugModeTimer ) )
-            {
-            iTimer->Queue( TTimeIntervalMicroSeconds32( KBTEngSspDebugModeTimeout ), 
-                            iDebugModeCallBack );
-            iTimerQueued &= ESspDebugModeTimer;
-            err =  RProperty::Set(KPropertyUidBluetoothCategory, 
-                                   KPropertyKeyBluetoothSetSimplePairingDebugMode, 
-                                   (TInt) aDebugMode );
-            }
-        }
-    else
-        {
-            // Power is on, and debug mode is set to off.
-        TInt linkCount = 0;
-        err = RProperty::Get( KPropertyUidBluetoothCategory, 
-                               KPropertyKeyBluetoothGetPHYCount, linkCount );
-        if( err || !linkCount )
-            {
-            (void) RProperty::Set(KPropertyUidBluetoothCategory, 
-                                   KPropertyKeyBluetoothSetSimplePairingDebugMode,
-                                   (TInt) aDebugMode );
-            SetPowerStateL( EBTPowerOff, EFalse );
-            }
-        else
-            {
-                // There are still existing connections, queue the 
-                // timer again for half the period.
-            iTimer->Queue( TTimeIntervalMicroSeconds32( KBTEngSspDebugModeTimeout / 2 ), 
-                            iDebugModeCallBack );
-            iTimerQueued &= ESspDebugModeTimer;
-            }
-        }
-    TRACE_FUNC_EXIT
-    }
-
-// ---------------------------------------------------------------------------
-// returns the reference of pairing manager
-// ---------------------------------------------------------------------------
-//
-CBTEngPairMan& CBTEngServer::PairManager()
-    {
-    return *iPairMan;
-    }
-
-// ---------------------------------------------------------------------------
-// Delegate the information to pairing manager
-// ---------------------------------------------------------------------------
-//
-void CBTEngServer::RemoteRegistryChangeDetected()
-    {
-    iPairMan->RemoteRegistryChangeDetected();
-    }
-
-// ---------------------------------------------------------------------------
-// Access the reference of RSockServ
-// ---------------------------------------------------------------------------
-//
-RSocketServ& CBTEngServer::SocketServ()
-    {
-    return iSocketServ;
-    }
-
-// ---------------------------------------------------------------------------
-// Access the reference of RBTRegSrv
-// ---------------------------------------------------------------------------
-//
-RBTRegServ& CBTEngServer::BTRegServ()
-    {
-    return iBTRegServ;
-    }
 
 // ---------------------------------------------------------------------------
 // Ask plugin manager the connection status of the specified device
@@ -1321,6 +519,7 @@
     return status;
     }
 
+
 // ---------------------------------------------------------------------------
 // Static callback for temporary visibility mode.
 // ---------------------------------------------------------------------------
@@ -1328,10 +527,14 @@
 TInt CBTEngServer::ScanModeTimerCallBack( TAny* aPtr )
     {
     __ASSERT_ALWAYS(aPtr, PanicServer(EBTEngPanicArgumentIsNull) );
-    TRAPD( err, ( (CBTEngServer*) aPtr )->ScanModeTimerCompletedL() );
+    // The timer has completed, so remove our reference as well.
+    CBTEngServer* server = (CBTEngServer*) aPtr;
+    server->RemoveTimer( EScanModeTimer );
+    TRAPD( err, server->SettingsManager()->ScanModeTimerCompletedL() );
     return err;
     }
 
+
 // ---------------------------------------------------------------------------
 // Static callback for disconnecting all Baseband connections.
 // ---------------------------------------------------------------------------
@@ -1355,6 +558,7 @@
     return KErrNone;
     }
 
+
 // ---------------------------------------------------------------------------
 // Static callback for idle timer timeout. Turn off BT to get it out of 
 // debug mode. If there are existing connections, queue the timer again.
@@ -1362,35 +566,29 @@
 //
 TInt CBTEngServer::DebugModeTimerCallBack( TAny* aPtr )
     {
+    __ASSERT_ALWAYS(aPtr, PanicServer(EBTEngPanicArgumentIsNull) );
     // Set our internal debug mode key to off. Ignore error, not critical here.
     (void) RProperty::Set( KPSUidBluetoothTestingMode, KBTSspDebugmode, EFalse );
-    
-    __ASSERT_ALWAYS(aPtr, PanicServer(EBTEngPanicArgumentIsNull) );
-    
-    TRAP_IGNORE( ( (CBTEngServer*) aPtr )->CheckSspDebugModeL( EFalse ) );
+    CBTEngServer* server = (CBTEngServer*) aPtr;
+    TRAP_IGNORE( server->SettingsManager()->CheckSspDebugModeL( EFalse ) );
     return KErrNone;
     }
 
+
 // ---------------------------------------------------------------------------
 // Static callback for auto power off.
 // ---------------------------------------------------------------------------
 //
 TInt CBTEngServer::AutoPowerOffCallBack( TAny* aPtr )
     {
-	TRACE_FUNC_ENTRY
-	
-	__ASSERT_ALWAYS(aPtr, PanicServer(EBTEngPanicArgumentIsNull) );
-	
+    __ASSERT_ALWAYS(aPtr, PanicServer(EBTEngPanicArgumentIsNull) );
+    // The timer has completed, so remove our reference as well.
     CBTEngServer* server = (CBTEngServer*) aPtr;
-    server->iTimerQueued &= ~EAutoPowerOffTimer;
-    TRAPD( err, server->CheckAutoPowerOffL() );
+    server->RemoveTimer( EAutoPowerOffTimer );
+    TRAPD( err, server->SettingsManager()->CheckAutoPowerOffL() );
     return err;
     }
 
-BluetoothFeatures::TEnterpriseEnablementMode CBTEngServer::EnterpriseEnablementMode() const
-    {
-    return iEnterpriseEnablementMode;
-    }
 
 // ======== GLOBAL FUNCTIONS ========
 
--- a/bluetoothengine/bteng/src/btengsrvkeywatcher.cpp	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/bteng/src/btengsrvkeywatcher.cpp	Fri Mar 12 15:43:23 2010 +0200
@@ -26,6 +26,8 @@
 #include "btengsrvkeywatcher.h"
 #include "btengserver.h"
 #include "btengsrvpluginmgr.h"
+#include "btengsrvsettingsmgr.h"
+#include "btengpairman.h"
 #include "btengprivatepskeys.h"
 #include "btengprivatecrkeys.h"
 #include "debug.h"
@@ -302,7 +304,7 @@
             aActive->GoActive();
             if( !aStatus && !iDutModeKey.Get( val ) )
                 {
-                iServer->SetDutMode( val );
+                iServer->SettingsManager()->SetDutMode( val );
                 }
             }
             break;
@@ -316,7 +318,7 @@
             remoteLockVal = ERemoteLocked;
             if( !aStatus && !iPhoneLockKey.Get( val ) && val == remoteLockVal )
                 {
-                iServer->SetPowerStateL( EBTPowerOff, EFalse );
+                iServer->SetPowerStateL( EBTOff, EFalse );
                 }
 #endif  //RD_REMOTELOCK
             }
@@ -329,7 +331,7 @@
             if( !aStatus && !iSystemStateKey.Get( val ) && 
                  val == ESwStateShuttingDown )
                 {
-                iServer->SetVisibilityModeL( EBTVisibilityModeNoScans , 0 );
+                iServer->SettingsManager()->SetVisibilityModeL( EBTVisibilityModeNoScans , 0 );
                 iServer->DisconnectAllL();   
                 }
             }
@@ -339,7 +341,7 @@
             TRACE_INFO( ( _L( "PHY count key changed" ) ) )
             iPHYCountKey.Subscribe( aActive->RequestStatus() );
             aActive->GoActive();
-            iServer->SetUiIndicatorsL();
+            iServer->SettingsManager()->SetUiIndicatorsL();
             }
             break;
         case KBTEngBtConnectionWatcher:
@@ -347,7 +349,7 @@
             TRACE_INFO( ( _L( "BT connection key changed" ) ) )
             iBtConnectionKey.Subscribe( aActive->RequestStatus() );
             aActive->GoActive();
-            iServer->SetUiIndicatorsL();
+            iServer->SettingsManager()->SetUiIndicatorsL();
             }
             break;        
         case KBTEngScanningWatcher:
@@ -357,7 +359,7 @@
             aActive->GoActive();
             if ( !iBtScanningKey.Get( val ) )
                 {
-                iServer->UpdateVisibilityModeL( val );
+                iServer->SettingsManager()->UpdateVisibilityModeL( val );
                 }
             }
             break;
@@ -369,7 +371,7 @@
             if( !aStatus && !iEmergencyCallKey.Get( val ) && val )
                 {
                 // An emergency call initiated -> Close SAP connection if it's active
-                iServer->iPluginMgr->DisconnectProfile( EBTProfileSAP );
+                iServer->PluginManager()->DisconnectProfile( EBTProfileSAP );
                 }
             }
             break;
@@ -380,7 +382,7 @@
             aActive->GoActive();
             if( !aStatus && !iSspDebugModeKey.Get( val ) )
                 {
-                iServer->CheckSspDebugModeL( (TBool) val );
+                iServer->SettingsManager()->CheckSspDebugModeL( (TBool) val );
                 }
             break;
             }
@@ -396,7 +398,7 @@
             if( !err && myChangedTable == KRegistryChangeRemoteTable )
             	{
             	TRACE_INFO( ( _L("BT Remote registry key changed") ) )
-            	iServer->RemoteRegistryChangeDetected();            	
+            	iServer->PairManager()->RemoteRegistryChangeDetected();
             	}
         	break;
         	}    
@@ -407,18 +409,18 @@
             aActive->GoActive();
             iSapKeyCenRep->Get( KBTSapEnabled, val );
             
-            TBTPowerStateValue powerState = EBTPowerOff;
-            User::LeaveIfError( iServer->GetHwPowerState( (TBTPowerStateValue&) powerState ) );
-            if( aStatus >= 0 && powerState )
+            TBTPowerState powerState = EBTOff;
+            User::LeaveIfError( iServer->SettingsManager()->GetHwPowerState( powerState ) );
+            if( aStatus >= 0 && powerState == EBTOn )
                 {
                 // Relevant only if BT is on
                 if( val == EBTSapEnabled )
                     {
-                    iServer->iPluginMgr->LoadBTSapPluginL();
+                    iServer->PluginManager()->LoadBTSapPluginL();
                     }
                 else
                     {
-                    iServer->iPluginMgr->UnloadBTSapPlugin();
+                    iServer->PluginManager()->UnloadBTSapPlugin();
                     }
                 }
             }
--- a/bluetoothengine/bteng/src/btengsrvpluginmgr.cpp	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/bteng/src/btengsrvpluginmgr.cpp	Fri Mar 12 15:43:23 2010 +0200
@@ -229,7 +229,7 @@
 	{
 	TRACE_FUNC_ENTRY
 	TBool want = EFalse;
-	switch ( iServer->EnterpriseEnablementMode() )
+	switch ( BluetoothFeatures::EnterpriseEnablementL() )
 		{
 	case BluetoothFeatures::EDisabled:
 		// In Disabled mode all plugins are filtered out.
@@ -322,7 +322,7 @@
     TRACE_FUNC_ENTRY
 
 	// SAP is supported in neither Data Profiles Disabled nor Disabled mode.
-    if ( iServer->EnterpriseEnablementMode() != BluetoothFeatures::EEnabled )
+    if ( BluetoothFeatures::EnterpriseEnablementL() != BluetoothFeatures::EEnabled )
         {
         TRACE_INFO( ( _L( "\tno we're not... Bluetooth is enterprise-IT-disabled" ) ) )
         User::Leave(KErrNotSupported);
--- a/bluetoothengine/bteng/src/btengsrvsession.cpp	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/bteng/src/btengsrvsession.cpp	Fri Mar 12 15:43:23 2010 +0200
@@ -22,6 +22,7 @@
 #include "btengserver.h"
 #include "btengsrvbbconnectionmgr.h"
 #include "btengpairman.h"
+#include "btengsrvsettingsmgr.h"
 #include "btengclientserver.h"
 #include "debug.h"
 
@@ -79,14 +80,11 @@
         {
         iNotifyConnMessage.Complete( KErrCancel );
         }
-    CancelPairRequest();
     if( Server() )
         {
-        Server()->RemoveSession( iAutoSwitchOff );
+        Server()->RemoveSession(this, iAutoSwitchOff );
         }
-    
     delete iConnectionEventQueue;
-    
     TRACE_FUNC_EXIT
     }
 
@@ -150,20 +148,6 @@
     }
 
 // ---------------------------------------------------------------------------
-// Comfirm the caller if pairing request is completed in this invoke. 
-// ---------------------------------------------------------------------------
-//
-TInt CBTEngSrvSession::CompletePairRequest( TInt aResult )
-    {
-    if ( !iPairMessage.IsNull())
-        {
-        iPairMessage.Complete( aResult );
-        return KErrNone;
-        }
-    return KErrNotFound;
-    }
-
-// ---------------------------------------------------------------------------
 // From class CSession2
 // Handles servicing of a client request that has been passed to the server.
 // ---------------------------------------------------------------------------
@@ -171,11 +155,11 @@
 void CBTEngSrvSession::ServiceL( const RMessage2& aMessage )
     {
     TRAPD( err, DispatchMessageL( aMessage ) );
-
     if( !aMessage.IsNull() &&
         ( err || 
           ( aMessage.Function() != EBTEngNotifyConnectionEvents && 
-            aMessage.Function() != EBTEngPairDevice ) ) )
+            aMessage.Function() != EBTEngPairDevice &&
+            aMessage.Function() != EBTEngSetPowerState ) ) )
         {
             // Return the error code to the client.
         aMessage.Complete( err );
@@ -206,15 +190,13 @@
         {
         case EBTEngSetPowerState:
             {
-            iAutoSwitchOff = (TBool) aMessage.Int1();
-            Server()->SetPowerStateL( (TBTPowerStateValue) aMessage.Int0(), 
-                                       iAutoSwitchOff );
+            Server()->SetPowerStateL( aMessage );
             }
             break;
         case EBTEngSetVisibilityMode:
             {
-            Server()->SetVisibilityModeL( (TBTVisibilityMode) aMessage.Int0(),
-                                           aMessage.Int1() );
+            Server()->SettingsManager()->SetVisibilityModeL(
+                        (TBTVisibilityMode) aMessage.Int0(),aMessage.Int1() );
             }
             break;
         case EBTEngNotifyConnectionEvents:
@@ -229,7 +211,6 @@
                 {
                 User::Leave(KErrInUse);
                 }
-            
             //save the client message
             iNotifyConnMessage = RMessage2(aMessage);
             
@@ -261,17 +242,9 @@
         case EBTEngIsDeviceConnected:
         case EBTEngGetConnectedAddresses:
             {
-            TBTPowerStateValue pwr = EBTPowerOff;
-            Server()->GetHwPowerState( pwr );
-            if( pwr )
-                {
-                    // Simply forward it to the plug-in manager
-                Server()->DispatchPluginMessageL( aMessage );
-                }
-            else
-                {
-                User::Leave( KErrNotReady );
-                }
+            CheckPowerOnL();
+            // Simply forward it to the plug-in manager
+            Server()->DispatchPluginMessageL( aMessage );
             }
             break;    
         case EBTEngIsDeviceConnectable:
@@ -282,38 +255,31 @@
         case EBTEngPrepareDiscovery:
             {
             aMessage.Complete( KErrNone );  // Client does not have to wait.
-            Server()->iBBConnMgr->ManageTopology( ETrue );
+            Server()->BasebandConnectionManager()->ManageTopology( ETrue );
             }
             break;
         case EBTEngSetPairingObserver:
+            {
+            CheckPowerOnL();
+            // Simply forward it to the pairing manager
+            Server()->PairManager()->ProcessCommandL( aMessage );
+            break;
+            }
         case EBTEngPairDevice:
             {
-            TBTPowerStateValue pwr = EBTPowerOff;
-            (void) Server()->GetHwPowerState( pwr );
-            if( pwr )
-                {
-                // Simply forward it to the pairing manager
-                Server()->PairManager().ProcessCommandL( aMessage );
-                if ( opcode == EBTEngPairDevice )
-                    {
-                    iPairMessage = RMessage2( aMessage );
-                    }
-                }
-            else
-                {
-                User::Leave( KErrNotReady );
-                }
+            CheckPowerOnL();
+            // Simply forward it to the pairing manager
+            Server()->PairManager()->ProcessCommandL( aMessage );
             break;
             }
         case EBTEngCancelPairDevice:
             {
-            CancelPairRequest();
+            Server()->PairManager()->ProcessCommandL( aMessage );
             break;
             }
         default:
             {
-            TRACE_INFO( ( _L( "[BTENG]\t DispatchMessageL: bad request (%d)" ), 
-                                aMessage.Function() ) )
+            TRACE_INFO( ( _L( "[BTENG]\t DispatchMessageL: bad request (%d)" ), aMessage.Function() ) )
             User::Leave( KErrArgument );
             }
             break;
@@ -322,14 +288,15 @@
     }
 
 // ---------------------------------------------------------------------------
-// Only the originator of pairing can cancel the pairing request.
+// Check if power is on, and leave if it is not.
 // ---------------------------------------------------------------------------
 //
-void CBTEngSrvSession::CancelPairRequest()
+void CBTEngSrvSession::CheckPowerOnL()
     {
-    if ( !iPairMessage.IsNull() )
+    TBTPowerState power = EBTOff;
+    (void) Server()->SettingsManager()->GetHwPowerState( power );
+    if ( power == EBTOff )
         {
-        Server()->PairManager().CancelCommand( iPairMessage.Function() );
-        iPairMessage.Complete( KErrCancel );
+        User::Leave( KErrNotReady );
         }
     }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/bluetoothengine/bteng/src/btengsrvsettingsmgr.cpp	Fri Mar 12 15:43:23 2010 +0200
@@ -0,0 +1,939 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: Class to manage Bluetooth hardware and stack settings.
+*
+*/
+
+#include "btengsrvsettingsmgr.h"
+#include <bthci.h>
+#include <bt_subscribe_partner.h>
+#include <btnotif.h>
+#include <btengdomainpskeys.h>
+#include <centralrepository.h>
+#include <featmgr.h>
+#include <AknSmallIndicator.h>
+#include <avkon.hrh>
+
+#include "btengserver.h"
+#include "btengsrvpluginmgr.h"
+#include "btengsrvbbconnectionmgr.h"
+#include "btengsrvstate.h"
+#include "debug.h"
+
+#ifndef SETLOCALNAME
+#include <btengsettings.h>
+#endif
+
+/** ID of active object helper */
+const TInt KBTEngSettingsActive = 30;
+/** Constant for converting minutes to microseconds */
+//const TInt64 KMinutesInMicroSecs = 60000000;
+const TInt64 KMinutesInMicroSecs = MAKE_TINT64( 0, 60000000 );
+/**  Timeout for disabling Simple Pairing debug mode. The value is 30 minutes. */
+//const TInt KBTEngSspDebugModeTimeout = 1800000000;
+const TInt64 KBTEngSspDebugModeTimeout = MAKE_TINT64( 0, 1800000000 );
+/**  Timeout for turning BT off automatically. The value is 10.5 seconds. */
+const TInt KBTEngBtAutoOffTimeout = 10500000;
+/**  Default values for Major Service Class */
+const TUint16 KCoDDefaultServiceClass = EMajorServiceTelephony | EMajorServiceObjectTransfer | EMajorServiceNetworking;
+/**  Default values for Major Device Class */
+const TUint8 KCoDDefaultMajorDeviceClass = EMajorDevicePhone;
+/**  Default values for Minor Device Class */
+const TUint8 KCoDDefaultMinorDeviceClass = EMinorDevicePhoneSmartPhone;
+
+
+// ======== MEMBER FUNCTIONS ========
+
+// ---------------------------------------------------------------------------
+// C++ default constructor
+// ---------------------------------------------------------------------------
+//
+CBTEngSrvSettingsMgr::CBTEngSrvSettingsMgr( CBTEngServer* aServer )
+:   iServer( aServer )
+    {
+    }
+
+
+// ---------------------------------------------------------------------------
+// Symbian second-phase constructor
+// ---------------------------------------------------------------------------
+//
+void CBTEngSrvSettingsMgr::ConstructL()
+    {
+    TRACE_FUNC_ENTRY
+    iActive = CBTEngActive::NewL( *this, KBTEngSettingsActive );
+    LoadBTPowerManagerL();
+    iEnterpriseEnablementMode = BluetoothFeatures::EnterpriseEnablementL();
+    TRACE_INFO( ( _L( "iEnterpriseEnablementMode = %d" ), iEnterpriseEnablementMode) )
+    if ( iEnterpriseEnablementMode == BluetoothFeatures::EDisabled )
+        {
+        SetVisibilityModeL( EBTVisibilityModeNoScans, 0 );
+        }
+    TRACE_FUNC_EXIT
+    }
+
+
+// ---------------------------------------------------------------------------
+// NewL
+// ---------------------------------------------------------------------------
+//
+CBTEngSrvSettingsMgr* CBTEngSrvSettingsMgr::NewL( CBTEngServer* aServer )
+    {
+    CBTEngSrvSettingsMgr* self = new( ELeave ) CBTEngSrvSettingsMgr( aServer );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// Destructor
+// ---------------------------------------------------------------------------
+//
+CBTEngSrvSettingsMgr::~CBTEngSrvSettingsMgr()
+    {
+    if( iActive && iActive->IsActive() )
+        {
+        // Cancel the outstanding request.
+        iPowerMgr.Cancel();
+        }
+    delete iActive;  
+    iPowerMgr.Close();
+    }
+
+
+// ---------------------------------------------------------------------------
+// Power Bluetooth hardware on or off.
+// ---------------------------------------------------------------------------
+//
+TInt CBTEngSrvSettingsMgr::SetHwPowerState( TBTPowerState aState )
+    {
+    TRACE_FUNC_ENTRY
+    TInt err = KErrNone;
+#ifndef __WINS__
+    if( iActive->IsActive() )
+        {
+        // Cancel the outstanding request.
+        iPowerMgr.Cancel();
+        iActive->Cancel();
+        }
+    iPowerMgr.SetPower( aState, NULL, iActive->RequestStatus() );
+    iActive->GoActive();
+#else   //__WINS__
+    iPowerState = aState;
+#endif  //__WINS__
+
+   if( !err && aState == EBTOn )
+        {
+        TInt dutMode = EBTDutOff;
+        err = RProperty::Get( KPSUidBluetoothTestingMode, KBTDutEnabled, dutMode );
+        if( !err && dutMode == EBTDutOn )
+            {
+            // Set the DUT mode key to OFF since DUT mode is disabled at this point
+            err = RProperty::Set( KPSUidBluetoothTestingMode, KBTDutEnabled, EBTDutOff );
+            }
+        }
+    if( err )
+        {
+        // Power off if an error occurred during power on sequence.
+#ifndef __WINS__
+            // This cannot happen in emulator environment.
+        iPowerMgr.Cancel();
+        iActive->Cancel();
+        iPowerMgr.SetPower( EBTOff, NULL, iActive->RequestStatus() );
+        User::WaitForRequest( iActive->RequestStatus() );
+        // Result will be communicated through the caller of this function (by leaving).
+#else   //__WINS__
+        iPowerState = EBTOff;
+#endif  //__WINS__
+        } 
+    TRACE_FUNC_RES( ( _L( "result: %d" ), err ) )
+    return err;
+    }
+
+
+// ---------------------------------------------------------------------------
+// Turn BT on or off.
+// ---------------------------------------------------------------------------
+//
+void CBTEngSrvSettingsMgr::SetPowerStateL( TBTPowerState aState, TBool aTemporary )
+    {
+    TRACE_FUNC_ARG( ( _L( "%d (temporary=%d" ), aState, aTemporary ) )
+    if ( aState == EBTOn && iEnterpriseEnablementMode == BluetoothFeatures::EDisabled )
+        {
+        TRACE_INFO( ( _L( "no we're not... Bluetooth is enterprise-IT-disabled" ) ) )
+        User::Leave(KErrNotSupported);
+        }
+    TBool idle = ( iServer->StateMachine()->CurrentOperation() == CBTEngSrvState::ESrvOpIdle );
+    TBTPowerState currentState = EBTOff;
+    CheckTemporaryPowerStateL( currentState, aState, aTemporary );
+
+    if ( ( currentState == aState || ( aTemporary && aState == EBTOff ) ) && idle )
+        {
+        // The requested power state is already active, ignore silently.
+        // We don't return an error here, as there is no error situation.
+        TRACE_INFO( ( _L( "SetPowerStateL: nothing to do" ) ) )
+        if ( currentState == aState )
+            {
+            // Make sure that the CenRep key is in sync.
+            // During boot-up, the pwoer is set from the CenRep key, so we could 
+            // end up out-of-sync.
+            TRACE_INFO( ( _L( "SetPowerStateL: currentState == aState" ) ) )
+            UpdateCenRepPowerKeyL( aState );
+            } 
+        return;
+        }
+    if ( aState == EBTOn )
+        {
+        // Hardware power on is the first step.
+        User::LeaveIfError( SetHwPowerState( aState ) );
+        }
+    else
+        {
+        //Prevent BT visibility in the situation when we turn OFF BT Engine 
+        //but FM Radio is still alive
+        SetVisibilityModeL( EBTVisibilityModeNoScans, 0 );
+        // Hardware power off is the last step.
+        // First disconnect all plug-ins.
+        iServer->PluginManager()->DisconnectAllPlugins();
+        }
+    // We only signal that BT is on after everything has completed (through 
+    // the CenRep power state key), so that all services are initialized.
+    // We signal that BT is off immediately though, so that our clients will 
+    // not try to use BT during power down.
+    iServer->StateMachine()->StartStateMachineL( aState );
+    TRACE_FUNC_EXIT
+    }
+
+// ---------------------------------------------------------------------------
+// Turn BT on or off.
+// ---------------------------------------------------------------------------
+//
+void CBTEngSrvSettingsMgr::SetPowerStateL(const RMessage2 aMessage )
+    {
+    TRACE_FUNC_ENTRY
+    __ASSERT_ALWAYS( aMessage.Function() == EBTEngSetPowerState, 
+            PanicServer( EBTEngPanicExpectSetPowerOpcode ) );
+    if ( !iMessage.IsNull() )
+        {
+        // A power management request from a client is outstanding.
+        User::Leave( KErrAlreadyExists );
+        }
+ 
+    TBTPowerStateValue arg = (TBTPowerStateValue) aMessage.Int0();
+    // TBTPowerState power state type is inverted from TBTPowerStateValue,
+    // which is used by the client to pass the parameter...
+    TBTPowerState reqedPowerState( EBTOff );
+    if ( arg == EBTPowerOn )
+        {
+        reqedPowerState = EBTOn;
+        }
+    TBool tempPowerOn = (TBool) aMessage.Int1();
+    
+    SetPowerStateL( reqedPowerState, tempPowerOn );
+    if ( iServer->StateMachine()->CurrentOperation() == CBTEngSrvState::ESrvOpIdle )
+        {
+        // The request is accepted but the state machine is not running. This means the
+        // requested power state is already active. Request is done.
+        aMessage.Complete( KErrNone );
+        }
+    else
+        {
+        iMessage = RMessage2( aMessage );
+        }
+    TRACE_FUNC_EXIT
+    }
+
+// ---------------------------------------------------------------------------
+// Initialize Bluetooth stack settings.
+// ---------------------------------------------------------------------------
+//
+void CBTEngSrvSettingsMgr::InitBTStackL()
+    {
+    TRACE_FUNC_ENTRY
+    iServer->BasebandConnectionManager()->Subscribe();
+    TBTVisibilityMode visibility = EBTVisibilityModeHidden;
+    CRepository* cenRep = CRepository::NewL( KCRUidBTEngPrivateSettings );
+    TInt err = cenRep->Get( KBTDiscoverable, (TInt&) visibility );
+    delete cenRep;
+    if (iRestoreVisibility == EFalse)
+        {
+        if( err || visibility == EBTVisibilityModeTemporary &&
+            !( iServer->IsTimerQueued( CBTEngServer::EScanModeTimer ) ) )
+            {
+            visibility = EBTVisibilityModeHidden;
+            }
+        SetVisibilityModeL( visibility, 0 );
+        }
+
+    TBool sspDebugMode = EFalse;
+    (void) RProperty::Get( KPropertyUidBluetoothCategory,
+                KPropertyKeyBluetoothGetSimplePairingDebugMode, (TInt&) sspDebugMode );
+        // Only set debug mode to off if it is on, to prevent a loop notifications.
+    if( sspDebugMode )
+        {
+        sspDebugMode = EFalse;
+        // Add LeaveIfError if unsuccessful
+        (void) RProperty::Set(KPropertyUidBluetoothCategory,
+                    KPropertyKeyBluetoothSetSimplePairingDebugMode, (TInt) sspDebugMode );
+        }
+    TRACE_FUNC_EXIT
+    }
+
+
+// ---------------------------------------------------------------------------
+// Reset settings and disconnect all links.
+// ---------------------------------------------------------------------------
+//
+void CBTEngSrvSettingsMgr::StopBTStackL()
+    {
+    TRACE_FUNC_ENTRY
+    TBTVisibilityMode visibility = EBTVisibilityModeHidden;
+    CRepository* cenRep = CRepository::NewL( KCRUidBTEngPrivateSettings );
+          // Ignore error here; if we can't read it, likely we can't set it either.
+    (void) cenRep->Get( KBTDiscoverable, (TInt&) visibility );
+    delete cenRep;
+    if( visibility == EBTVisibilityModeTemporary )
+        {
+        visibility = EBTVisibilityModeHidden;
+        SetVisibilityModeL( visibility, 0 );    // Also cancels scan mode timer.
+        }
+
+        // Stop listening to events
+    iServer->BasebandConnectionManager()->Unsubscribe();
+        // Disconnect all links
+    TCallBack cb( CBTEngServer::DisconnectAllCallBack, iServer );
+    iServer->BasebandConnectionManager()->DisconnectAllLinksL( cb );
+        // Results in a callback (which is called directly when there are no links).
+    TRACE_FUNC_EXIT
+    }
+
+
+// ---------------------------------------------------------------------------
+// Update the power state CenRep key.
+// ---------------------------------------------------------------------------
+//
+void CBTEngSrvSettingsMgr::UpdateCenRepPowerKeyL( TBTPowerState aState )
+    {
+    TRACE_FUNC_ENTRY
+    CRepository* cenrep = CRepository::NewLC( KCRUidBluetoothPowerState );
+    // TBTPowerState power state type is inverted from TBTPowerStateValue...
+    TBTPowerStateValue power = (TBTPowerStateValue) !aState;
+    User::LeaveIfError( cenrep->Set( KBTPowerState, (TInt) power ) );
+    CleanupStack::PopAndDestroy( cenrep );
+    TRACE_FUNC_EXIT
+    }
+
+
+// ---------------------------------------------------------------------------
+// ?implementation_description
+// ---------------------------------------------------------------------------
+//
+void CBTEngSrvSettingsMgr::SetVisibilityModeL( TBTVisibilityMode aMode, TInt aTime )
+    {
+    TRACE_FUNC_ARG( ( _L( "[aMode: %d" ), aMode ) )
+    if ( aMode != EBTVisibilityModeNoScans && iEnterpriseEnablementMode == BluetoothFeatures::EDisabled )
+        {
+        TRACE_INFO( ( _L( "\tnot changing anything... Bluetooth is enterprise-IT-disabled" ) ) )
+        User::Leave( KErrNotSupported );
+        }
+
+    TInt err = KErrNone;
+    iServer->RemoveTimer( CBTEngServer::EScanModeTimer );
+    if( aMode != EBTVisibilityModeNoScans )
+        {
+        CRepository* cenRep = CRepository::NewL( KCRUidBTEngPrivateSettings );
+        err = cenRep->Set( KBTDiscoverable, aMode );
+        delete cenRep;
+        }
+    if( !err && aMode == EBTVisibilityModeTemporary )
+        {
+            // We need TInt64 here, as the max. time in microseconds for the 
+            // max. value (1 hour) is larger than KMaxTInt32.
+        TInt64 timeMicroSec = MAKE_TINT64( 0, aTime );
+        timeMicroSec = timeMicroSec * KMinutesInMicroSecs;
+            // Queue callback to set the visibility back to hidden.
+        iServer->QueueTimer( CBTEngServer::EScanModeTimer, (TInt64) timeMicroSec );
+        aMode = EBTVisibilityModeGeneral;
+        }
+    else if( !err && iRestoreVisibility )
+        {
+            // The user overrides, do not restore visibility mode anymore.
+        iRestoreVisibility = EFalse;
+        }
+    if( !err )
+        {
+        err = RProperty::Set( KUidSystemCategory, 
+                               KPropertyKeyBluetoothSetScanningStatus, aMode );
+        }
+    TBool hiddenMode = ( aMode == EBTVisibilityModeHidden );
+    if( !err && aMode != EBTVisibilityModeNoScans )
+        {
+            // In hidden mode, we only accept connections from paired devices.
+        err = RProperty::Set( KUidSystemCategory, 
+                               KPropertyKeyBluetoothSetAcceptPairedOnlyMode, 
+                               hiddenMode );
+        }
+
+    User::LeaveIfError( err );  // To communicate the result to the client.
+    TRACE_FUNC_EXIT
+    }
+
+
+// ---------------------------------------------------------------------------
+// Timed visible mode has expired.
+// ---------------------------------------------------------------------------
+//
+void CBTEngSrvSettingsMgr::ScanModeTimerCompletedL()
+    {
+    TRACE_FUNC_ENTRY
+    SetVisibilityModeL( EBTVisibilityModeHidden, 0 );
+    TBTPowerState power = EBTOff;
+    TInt err = GetHwPowerState( power );
+    if( !err && power )
+        {
+        // Show a notification to the user
+        TBTGenericInfoNotiferParamsPckg pckg;
+        pckg().iMessageType = EBTVisibilityTimeout;
+        
+        RNotifier notifier;
+        TInt err = notifier.Connect();
+        if( !err )
+            {
+            err = notifier.StartNotifier( KBTGenericInfoNotifierUid, pckg );
+            notifier.Close();
+            }
+        }
+    TRACE_FUNC_RES( ( _L( "result: %d" ), err ) )
+    }
+
+
+// ---------------------------------------------------------------------------
+// Check the secure simple pairing debug mode and turn it off if needed.
+// ---------------------------------------------------------------------------
+//
+void CBTEngSrvSettingsMgr::CheckSspDebugModeL( TBool aDebugMode )
+    {
+    TRACE_FUNC_ARG( ( _L( "SSP debug mode state %d" ), (TInt) aDebugMode ) )
+    TBTPowerState pwr = EBTOff;
+    TBool currentMode = EFalse;
+    TInt err = RProperty::Get( KPropertyUidBluetoothCategory, 
+                                KPropertyKeyBluetoothGetSimplePairingDebugMode, 
+                                (TInt&) currentMode );
+#ifndef __WINS__
+    err = iPowerMgr.GetPower( pwr, NULL ); // Treat error as power off.
+#else   //__WINS__
+    pwr = iPowerState;
+#endif  //__WINS__
+    if( err || pwr == EBTOff )
+        {
+        iServer->RemoveTimer( CBTEngServer::ESspDebugModeTimer );
+            // Only set debug mode to off if it is on, to prevent a loop notifications.
+        if( currentMode )
+            {
+            (void) RProperty::Set( KPropertyUidBluetoothCategory, 
+                                    KPropertyKeyBluetoothSetSimplePairingDebugMode,
+                                    (TInt) aDebugMode );
+            }
+            // In case of an error in getting the power state, turn BT off. 
+            // If BT is already off, this call will be ignored.
+        SetPowerStateL( EBTOff, EFalse );
+        }
+    else if( aDebugMode )
+        {
+            // Ignore if there already is a timer queued.
+        if( !( iServer->IsTimerQueued( CBTEngServer::ESspDebugModeTimer ) ) )
+            {
+            iServer->QueueTimer( CBTEngServer::ESspDebugModeTimer, (TInt64) KBTEngSspDebugModeTimeout );
+            err =  RProperty::Set(KPropertyUidBluetoothCategory, 
+                                   KPropertyKeyBluetoothSetSimplePairingDebugMode, 
+                                   (TInt) aDebugMode );
+            }
+        }
+    else
+        {
+            // Power is on, and debug mode is set to off.
+        TInt linkCount = 0;
+        err = RProperty::Get( KPropertyUidBluetoothCategory, 
+                               KPropertyKeyBluetoothGetPHYCount, linkCount );
+        if( err || !linkCount )
+            {
+            (void) RProperty::Set(KPropertyUidBluetoothCategory, 
+                                   KPropertyKeyBluetoothSetSimplePairingDebugMode,
+                                   (TInt) aDebugMode );
+            SetPowerStateL( EBTOff, EFalse );
+            }
+        else
+            {
+            // There are still existing connections, queue the
+            // timer again for half the period.
+            TInt64 interval = KBTEngSspDebugModeTimeout / 2;
+            iServer->QueueTimer( CBTEngServer::ESspDebugModeTimer, interval );
+            }
+        }
+    TRACE_FUNC_EXIT
+    }
+
+// ---------------------------------------------------------------------------
+// A session will be ended, completes the pending request for this session.
+// ---------------------------------------------------------------------------
+//
+void CBTEngSrvSettingsMgr::SessionClosed( CSession2* aSession )
+    {
+    TRACE_FUNC_ARG( ( _L( " session %x"), aSession ) )
+    if ( !iMessage.IsNull() && iMessage.Session() == aSession )
+        {
+        iMessage.Complete( KErrCancel );
+        }
+    TRACE_FUNC_EXIT
+    }
+
+// ---------------------------------------------------------------------------
+// Check the power state and if BT gets turned off automatically.
+// This method is invoked either when the timer has expired, or
+// if there are no more connections while the timer was running.
+// ---------------------------------------------------------------------------
+//
+void CBTEngSrvSettingsMgr::CheckAutoPowerOffL()
+    {
+    TRACE_FUNC_ENTRY
+    if ( iAutoOffClients > 0 )
+        {
+        TRACE_INFO( ( _L( "[CBTEngServer]\t iAutoOffClients %d"), iAutoOffClients ) )
+        return;
+        }
+    TInt linkCount = 0;
+    TInt err = RProperty::Get( KPropertyUidBluetoothCategory, 
+                                KPropertyKeyBluetoothGetPHYCount, linkCount );
+    if( !err && !linkCount )
+        {
+        TRACE_INFO( ( _L( "[CBTEngServer]\t SetPowerStateL( EBTOff, EFalse );")))
+        SetPowerStateL( EBTOff, EFalse );
+        }
+    else
+        {
+        if( iRestoreVisibility )
+            {
+                // Set visibility mode back to the value selected by the user.
+            SetVisibilityModeL( EBTVisibilityModeGeneral, 0 );
+            iRestoreVisibility = EFalse;
+            }
+            // show note if non-audio connection exists
+        if ( !iServer->PluginManager()->CheckAudioConnectionsL() )
+            {
+            RNotifier notifier;
+            TInt err = notifier.Connect();
+            if( !err )
+                {
+                TRequestStatus status;
+                TBTGenericInfoNotiferParamsPckg pckg;
+                pckg().iMessageType = EBTStayPowerOn;
+                TBuf8<sizeof(TInt)> result;
+                //notifier.StartNotifier( KBTGenericInfoNotifierUid, pckg, result );
+                notifier.StartNotifierAndGetResponse( status, 
+                                                  KBTGenericInfoNotifierUid, 
+                                                  pckg, result );   // Reply buffer not used.
+                User::WaitForRequest( status );
+                notifier.Close();
+                }
+            }
+        iAutoOffClients = 0;
+        iAutoSwitchOff = EFalse;
+        TCallBack cb;
+        iServer->BasebandConnectionManager()->SetAutoSwitchOff( EFalse, cb );
+        }
+    TRACE_FUNC_EXIT 
+    }
+
+
+// ---------------------------------------------------------------------------
+// The method is called when BT stack scanning mode P&S key is changed
+// ---------------------------------------------------------------------------
+//
+void CBTEngSrvSettingsMgr::UpdateVisibilityModeL( TInt aStackScanMode )
+    {
+    TRACE_FUNC_ARG( ( _L( "[aStackScanMode: %d" ), aStackScanMode ) )
+    TBTVisibilityMode currentMode;
+
+    CRepository* cenRep = CRepository::NewLC( KCRUidBTEngPrivateSettings );
+    User::LeaveIfError( cenRep->Get( KBTDiscoverable, (TInt&) currentMode ) );
+
+        // In case we are in temp visibility mode, we cannot always know whether the BT stack
+        // scan mode key was set by some external party or by us in SetVisibilityModeL above.
+        // Therefore we cannot stop the timer in case aMode is EBTVisibilityModeGeneral and 
+        // currentmode is EBTVisibilityModeTemporary
+    if( !( currentMode == EBTVisibilityModeTemporary && aStackScanMode == EBTVisibilityModeGeneral ) )
+        {
+            // Cancel the timer and queue it again if needed.
+        iServer->RemoveTimer( CBTEngServer::EScanModeTimer );
+        if( currentMode != aStackScanMode )
+            {
+            if( aStackScanMode == EPageScanOnly || aStackScanMode == EInquiryAndPageScan )
+                {
+                User::LeaveIfError( cenRep->Set( KBTDiscoverable, aStackScanMode ) );
+                }
+            else if( aStackScanMode == EInquiryScanOnly )
+                {
+                    // We don't support ENoScansEnabled nor EInquiryScanOnly mode
+                    // -> Consider these as same as Hidden 
+                User::LeaveIfError( cenRep->Set( KBTDiscoverable, EBTVisibilityModeHidden ) );
+                }
+            else if( aStackScanMode == ENoScansEnabled )
+                {
+                //We don't change KBTDiscoverable here, because ENoScansEnabled
+                //indicates BT/SYSTEM shutdown is happening
+                }
+            }
+        }
+    SetUiIndicatorsL();
+    CleanupStack::PopAndDestroy( cenRep );
+    TRACE_FUNC_EXIT
+    }
+
+
+// ---------------------------------------------------------------------------
+// Set Device Under Test mode.
+// ---------------------------------------------------------------------------
+//
+void CBTEngSrvSettingsMgr::SetDutMode( TInt aDutMode )
+    {
+    TRACE_FUNC_ARG( ( _L( "DUT mode %d" ), aDutMode ) )
+
+    if (aDutMode == EBTDutOff)
+        {
+        return;
+        }
+
+    TInt powerState = EBTOff;
+    CRepository* cenrep = NULL;
+    
+    TRAPD(err, cenrep = CRepository::NewL(KCRUidBluetoothPowerState));
+    
+    if (!err && cenrep)
+        {
+        cenrep->Get(KBTPowerState, powerState);
+        delete cenrep;
+        cenrep = NULL;
+        }
+    else
+        {
+        return;
+        }
+
+    if (powerState == EBTOn)
+        {
+
+#ifndef __WINS__
+        RBluetoothDutMode dutMode;
+        TInt err = dutMode.Open();
+        TRACE_FUNC_ARG( ( _L( "Open DUT mode handle err %d" ), err) )
+        if(!err) 
+            {
+            dutMode.ActivateDutMode();
+            dutMode.Close();
+            }
+#endif  //__WINS__                        
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// From class MBTEngActiveObserver.
+// Callback to notify that an outstanding request has completed.
+// ---------------------------------------------------------------------------
+//
+void CBTEngSrvSettingsMgr::RequestCompletedL( CBTEngActive* aActive, TInt aId, TInt aStatus )
+    {
+    __ASSERT_ALWAYS( aId == KBTEngSettingsActive, PanicServer( EBTEngPanicCorrupt ) );
+    TRACE_FUNC_ENTRY
+    (void) aActive;
+    if ( aStatus != KErrNone && aStatus != KErrAlreadyExists && aStatus != KErrCancel )
+        {
+        // Something went wrong, so we turn BT off again.
+        SetPowerStateL( EBTOff, EFalse );
+        }
+    else
+        {
+        // Write CoD only when the hardware has fully powered up.
+        TBTPowerState currState ( EBTOff );
+        (void) GetHwPowerState( currState );
+        if ( currState == EBTOn )
+            {
+            SetClassOfDeviceL();
+#ifndef SETLOCALNAME 
+            // the macro SETLOCALNAME is used as a workaround to tackle the BT name 
+            // could not be saved to BT chip before chip initialization completed for the first time,
+            // which is one of the regression after improving the BT boot up time. 
+            // To be removed once the final solution is in place. 
+            CBTEngSettings* settings = CBTEngSettings::NewL();
+            TBTDeviceName localName;           
+            localName.Zero();
+            TInt err = settings->GetLocalName(localName);
+            if (err == KErrNone)
+                {
+                settings->SetLocalName(localName);
+                }
+            delete settings;
+#endif
+            }
+        }
+    if ( !iMessage.IsNull())
+        {
+        iMessage.Complete( aStatus );
+        }
+    TRACE_FUNC_EXIT
+    }
+
+
+// ---------------------------------------------------------------------------
+// From class MBTEngActiveObserver.
+// Callback to notify that an error has occurred in RunL.
+// ---------------------------------------------------------------------------
+//
+void CBTEngSrvSettingsMgr::HandleError( CBTEngActive* aActive, TInt aId, TInt aError )
+    {
+    (void) aActive;
+    (void) aId;
+    if ( !iMessage.IsNull())
+        {
+        iMessage.Complete( aError );
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// Loads the BT Power Manager; leaves if it cannot be loaded.
+// ---------------------------------------------------------------------------
+//
+void CBTEngSrvSettingsMgr::LoadBTPowerManagerL()
+    {
+    TRACE_FUNC_ENTRY
+    TRACE_INFO( ( _L( "[CBTEngSrvSettingsMgr]\t Using HCI API v2 power manager" ) ) )
+    User::LeaveIfError( iPowerMgr.Open() );
+#ifndef __WINS__
+    iPowerMgr.SetPower( EBTOff, NULL, iActive->RequestStatus() );
+    User::WaitForRequest( iActive->RequestStatus() );
+    TInt status = ( iActive->RequestStatus().Int() == KErrAlreadyExists ? KErrNone : iActive->RequestStatus().Int() ); 
+    User::LeaveIfError( status );
+#else   //__WINS__
+    iPowerState = EBTOff;
+#endif  //__WINS__
+    TRACE_FUNC_EXIT
+    }
+
+
+// ---------------------------------------------------------------------------
+// ?implementation_description
+// ---------------------------------------------------------------------------
+//
+void CBTEngSrvSettingsMgr::SetUiIndicatorsL()
+    {
+    TRACE_FUNC_ENTRY
+    TBTPowerStateValue powerState = EBTPowerOff;
+    TBTVisibilityMode visibilityMode = EBTVisibilityModeHidden;
+    CRepository* cenrep = NULL;
+    TInt phys = 0;
+    TInt connecting = 0;
+
+    cenrep = CRepository::NewLC( KCRUidBluetoothPowerState );
+    User::LeaveIfError( cenrep->Get( KBTPowerState, (TInt&) powerState ) );
+    CleanupStack::PopAndDestroy( cenrep );
+    
+    if( powerState == EBTPowerOff )
+        {
+        SetIndicatorStateL( EAknIndicatorBluetoothModuleOn, EAknIndicatorStateOff );
+        SetIndicatorStateL( EAknIndicatorBluetooth, EAknIndicatorStateOff );
+        SetIndicatorStateL( EAknIndicatorBluetoothModuleOnVisible, EAknIndicatorStateOff );
+        SetIndicatorStateL( EAknIndicatorBluetoothVisible, EAknIndicatorStateOff );
+        }
+    else
+        {
+        // Power is on.
+        RProperty::Get( KPropertyUidBluetoothCategory, KPropertyKeyBluetoothPHYCount, phys );
+        RProperty::Get( KPropertyUidBluetoothCategory, KPropertyKeyBluetoothConnecting, connecting );
+        
+        cenrep = CRepository::NewLC( KCRUidBTEngPrivateSettings );
+        User::LeaveIfError( cenrep->Get( KBTDiscoverable, (TInt&) visibilityMode ) );
+        CleanupStack::PopAndDestroy( cenrep );
+        
+        if( visibilityMode == EBTVisibilityModeHidden )
+            {
+             if ( connecting ) // BT connecting and hidden
+                {
+                SetIndicatorStateL( EAknIndicatorBluetoothModuleOn, EAknIndicatorStateOff );
+                SetIndicatorStateL( EAknIndicatorBluetooth, EAknIndicatorStateAnimate );
+                }
+            else if ( phys > 0 ) // BT connection active and hidden     
+                {
+                SetIndicatorStateL( EAknIndicatorBluetoothModuleOn, EAknIndicatorStateOff );
+                SetIndicatorStateL( EAknIndicatorBluetooth, EAknIndicatorStateOn );
+                }
+            else  // BT connection not active and hidden
+                {
+                SetIndicatorStateL( EAknIndicatorBluetoothModuleOn, EAknIndicatorStateOn );
+                SetIndicatorStateL( EAknIndicatorBluetooth, EAknIndicatorStateOff );
+                }
+            SetIndicatorStateL( EAknIndicatorBluetoothModuleOnVisible, EAknIndicatorStateOff );
+            SetIndicatorStateL( EAknIndicatorBluetoothVisible, EAknIndicatorStateOff );
+            }           
+        else if( visibilityMode == EBTVisibilityModeGeneral || visibilityMode == EBTVisibilityModeTemporary )
+            {     
+            if ( connecting ) // BT connecting and visible
+                {
+                SetIndicatorStateL( EAknIndicatorBluetoothModuleOnVisible, EAknIndicatorStateOff );
+                SetIndicatorStateL( EAknIndicatorBluetoothVisible, EAknIndicatorStateAnimate );
+                }
+            else if ( phys > 0 ) // BT connection active and visible 
+                {
+                SetIndicatorStateL( EAknIndicatorBluetoothModuleOnVisible, EAknIndicatorStateOff );
+                SetIndicatorStateL( EAknIndicatorBluetoothVisible, EAknIndicatorStateOn );
+                }
+            else  // BT connection not active and visible
+                {
+                SetIndicatorStateL( EAknIndicatorBluetoothModuleOnVisible, EAknIndicatorStateOn );
+                SetIndicatorStateL( EAknIndicatorBluetoothVisible, EAknIndicatorStateOff );
+                }
+            SetIndicatorStateL( EAknIndicatorBluetoothModuleOn, EAknIndicatorStateOff );
+            SetIndicatorStateL( EAknIndicatorBluetooth, EAknIndicatorStateOff );
+            }
+        }
+    TRACE_FUNC_EXIT
+    }
+
+
+// ---------------------------------------------------------------------------
+// ?implementation_description
+// ---------------------------------------------------------------------------
+//
+void CBTEngSrvSettingsMgr::SetIndicatorStateL( const TInt aIndicator, const TInt aState )
+    {
+    CAknSmallIndicator* indicator = CAknSmallIndicator::NewLC( TUid::Uid( aIndicator ) );
+    indicator->SetIndicatorStateL( aState );
+    CleanupStack::PopAndDestroy( indicator ); //indicator
+    }
+
+
+// ---------------------------------------------------------------------------
+// Gets the current HW power state.
+// For now this is a separate method to isolate the different variations.
+// ---------------------------------------------------------------------------
+//
+TInt CBTEngSrvSettingsMgr::GetHwPowerState( TBTPowerState& aState )
+    {
+    TRACE_FUNC_ENTRY
+    TInt err = KErrNone;
+    
+#ifndef __WINS__
+    err = iPowerMgr.GetPower( aState, NULL );
+#else   //__WINS__
+    aState = iPowerState;
+#endif  //__WINS__
+    TRACE_FUNC_ARG( ( _L( "Power state is %d, result %d" ), (TInt) aState, err ) )
+    return err;
+    }
+
+// ---------------------------------------------------------------------------
+// Check the power state and if BT gets turned off automatically.
+// ---------------------------------------------------------------------------
+//
+void CBTEngSrvSettingsMgr::CheckTemporaryPowerStateL( TBTPowerState& aCurrentState, 
+    TBTPowerState aNewState, TBool aTemporary )
+    {
+    TRACE_FUNC_ENTRY
+    User::LeaveIfError( GetHwPowerState( aCurrentState ) );
+    if( !aTemporary )
+        {
+            // Force the new power state, so clear all auto switch off flags.
+            // If power is off, this will anyway be ignored.
+        iAutoOffClients = 0;
+        iAutoSwitchOff = EFalse;
+        TCallBack cb;
+        iServer->BasebandConnectionManager()->SetAutoSwitchOff( EFalse, cb );
+        if( iRestoreVisibility && aCurrentState == EBTOn )
+            {
+                // Set visibility mode back to the value selected by the user.
+            SetVisibilityModeL( EBTVisibilityModeGeneral, 0 );
+            iRestoreVisibility = EFalse;
+            }
+        }
+    else
+        {
+        if( aCurrentState == aNewState )
+            {
+            if( iAutoSwitchOff && aNewState == EBTOn )
+                {
+                iAutoOffClients++;
+                iServer->RemoveTimer( CBTEngServer::EAutoPowerOffTimer );
+                }
+            }
+        else if( iAutoSwitchOff || aNewState == EBTOn )
+            {
+            aNewState == EBTOff ? iAutoOffClients-- : iAutoOffClients++;
+            iAutoSwitchOff = ETrue;
+            if( aNewState == EBTOff && iAutoOffClients <= 0 )
+                {
+                TCallBack powerOffCb( CBTEngServer::AutoPowerOffCallBack, iServer );
+                iServer->BasebandConnectionManager()->SetAutoSwitchOff( ETrue, powerOffCb );
+                TInt64 interval = KBTEngBtAutoOffTimeout;
+                iServer->QueueTimer( CBTEngServer::EAutoPowerOffTimer, interval );
+                }
+            else if( aNewState == EBTOn )
+                {
+                CRepository* cenRep = CRepository::NewLC( KCRUidBTEngPrivateSettings );
+                TBTVisibilityMode visibility = EBTVisibilityModeGeneral;
+                TInt err = cenRep->Get( KBTDiscoverable, (TInt&) visibility );
+                CleanupStack::PopAndDestroy( cenRep );
+                if( !err && visibility == EBTVisibilityModeGeneral )
+                    {
+                    SetVisibilityModeL( EBTVisibilityModeHidden, 0 );
+                    iRestoreVisibility = ETrue;
+                   }
+                iServer->RemoveTimer( CBTEngServer::EAutoPowerOffTimer );
+                }
+            }
+        }
+    if( iAutoOffClients < 0 )
+        {
+        iAutoOffClients = 0;
+        }
+    TRACE_FUNC_EXIT 
+    }
+
+
+// ---------------------------------------------------------------------------
+// Set the Class of Device.
+// ---------------------------------------------------------------------------
+//
+void CBTEngSrvSettingsMgr::SetClassOfDeviceL()
+    {
+    TRACE_FUNC_ENTRY
+    TUint16 serviceClass = KCoDDefaultServiceClass;
+        // Check from feature manager if stereo audio is enabled.
+    FeatureManager::InitializeLibL();
+    TBool supported = FeatureManager::FeatureSupported( KFeatureIdBtStereoAudio );
+    FeatureManager::UnInitializeLib();
+    if( supported )
+        {
+        // A2DP spec says we should set this bit as we are a SRC
+        serviceClass |= EMajorServiceCapturing;
+        }
+        // These values may nayway be overridden by HCI
+    TBTDeviceClass cod( serviceClass, KCoDDefaultMajorDeviceClass, 
+                         KCoDDefaultMinorDeviceClass );
+        // Ignore error, it is non-critical
+    (void) RProperty::Set( KPropertyUidBluetoothControlCategory, 
+                            KPropertyKeyBluetoothSetDeviceClass, cod.DeviceClass() );
+    TRACE_FUNC_EXIT
+    }
--- a/bluetoothengine/bteng/src/btengsrvstate.cpp	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/bteng/src/btengsrvstate.cpp	Fri Mar 12 15:43:23 2010 +0200
@@ -22,6 +22,7 @@
 #include "btengsrvstate.h"
 #include "btengserver.h"
 #include "btengsrvpluginmgr.h"
+#include "btengsrvsettingsmgr.h"
 #include "debug.h"
 
 
@@ -93,10 +94,10 @@
 // ?implementation_description
 // ---------------------------------------------------------------------------
 //
-void CBTEngSrvState::StartStateMachineL( TBool aState )
+void CBTEngSrvState::StartStateMachineL( TBTPowerState aState )
     {
     TRACE_FUNC_ENTRY
-    if( aState )
+    if( aState == EBTOn )
         {
         // Power on; starting state is initializing the stack
         iState = EInitBTStack;
@@ -107,8 +108,8 @@
         // Power off, starting state is to disconnect the plug-ins
         iState = EDisconnectPlugins;
         iOperation = EPowerOff;
-        iServer->UpdateCenRepPowerKeyL( EBTPowerOff );
-        iServer->SetUiIndicatorsL();
+        iServer->SettingsManager()->UpdateCenRepPowerKeyL( EBTOff );
+        iServer->SettingsManager()->SetUiIndicatorsL();
         }
     ChangeState();
     }
@@ -121,10 +122,7 @@
 void CBTEngSrvState::ChangeState()
     {
     TRACE_FUNC_ENTRY
-    if(!iAsyncCallback->IsActive())
-        {
-        iAsyncCallback->CallBack();
-        }
+    iAsyncCallback->CallBack();
     }
 
 // ---------------------------------------------------------------------------
@@ -153,7 +151,7 @@
         case EInitBTStack:
             {
             iState = ELoadDIService;
-            iServer->InitBTStackL();
+            iServer->SettingsManager()->InitBTStackL();
             }
             break;
         case ELoadDIService:
@@ -166,13 +164,13 @@
             {
             iState = ELoadNextPlugin;
             TEComResolverParams params;
-            iServer->iPluginMgr->LoadProfilePluginsL( params );
+            iServer->PluginManager()->LoadProfilePluginsL( params );
             }
             break;
         case ELoadNextPlugin:
             {
                 // Only change the state when all plug-ins are loaded
-            if( iServer->iPluginMgr->LoadPluginL() <= 0 )
+            if( iServer->PluginManager()->LoadPluginL() <= 0 )
                 {
                 iState = EIdle;
                 }
@@ -181,7 +179,7 @@
         case EStopBTStack:
             {
             iState = EWaitingForPowerOff;
-            iServer->StopBTStackL();
+            iServer->SettingsManager()->StopBTStackL();
             }
             break;
         case EUnloadDIService:
@@ -193,7 +191,7 @@
         case EUnloadPlugins:
             {
             iState = EUnloadDIService;
-            iServer->iPluginMgr->UnloadProfilePlugins();
+            iServer->PluginManager()->UnloadProfilePlugins();
             }
             break;
         case EDisconnectPlugins:
@@ -214,8 +212,8 @@
             {
             if( iOperation == EPowerOn )
                 {
-                iServer->UpdateCenRepPowerKeyL( EBTPowerOn );
-                iServer->SetUiIndicatorsL();
+                iServer->SettingsManager()->UpdateCenRepPowerKeyL( EBTOn );
+                iServer->SettingsManager()->SetUiIndicatorsL();
                 }
             iOperation = ESrvOpIdle;
             iServer->CheckIdle();
--- a/bluetoothengine/btmac/inc/btmonocmdhandler/btmcoperator.h	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/btmac/inc/btmonocmdhandler/btmcoperator.h	Fri Mar 12 15:43:23 2010 +0200
@@ -86,7 +86,6 @@
         CBtmcProtocol& iProtocol;
         RTelServer iServer;
         RMobilePhone iPhone;
-		RMobileONStore iStore;
         RMmCustomAPI iCustomApi;
         RMmCustomAPI::TOperatorNameInfo iInfo;
     };
--- a/bluetoothengine/btmac/inc/btmonocmdhandler/btmcphonestatus.h	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/btmac/inc/btmonocmdhandler/btmcphonestatus.h	Fri Mar 12 15:43:23 2010 +0200
@@ -82,8 +82,6 @@
         
         TInt GetRssiStrength();
         
-        TInt GetVolumeStatus();
-        
         TInt GetBatteryCharge();
         
         void SetRecognitionInitiator(TBTMonoVoiceRecognitionInitiator aInitiator);
--- a/bluetoothengine/btmac/inc/btmonocmdhandler/btmcprotocol.h	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/btmac/inc/btmonocmdhandler/btmcprotocol.h	Fri Mar 12 15:43:23 2010 +0200
@@ -164,7 +164,6 @@
         TBool iHandleCmdPending;
         CDesC8ArrayFlat* iOutgoPacketQueue; // owned
         TInt iCredit; // How many commands are allowed to acc
-        TBool iVolumeSyncFromAccessory;
         TBool iAccessoryInitiated; // who initiated the connection
         RMobilePhone::TMobilePhoneIdentityV1 iIdentity; // holds IMEI etc
         RMobilePhone::TMobilePhoneSubscriberId iId; // holds id
--- a/bluetoothengine/btmac/inc/btmonocmdhandler/btmcvolume.h	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/btmac/inc/btmonocmdhandler/btmcvolume.h	Fri Mar 12 15:43:23 2010 +0200
@@ -88,6 +88,8 @@
 
         TInt GetNewPhoneVol();
 
+        TBool IsActiveRemoteVolumeControl();
+        
     private:
         enum TVolSyncAction
             {
@@ -109,8 +111,6 @@
 		TInt iMaxSpkrVol; // Maximum volume level of the phone
 		TInt iStep;
         TVolSyncAction iAction;
-    	
-    	TBool iVolCtrlActivated;
     };
 
 
--- a/bluetoothengine/btmac/src/BTMonoCmdHandler/btmccallstatus.cpp	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/btmac/src/BTMonoCmdHandler/btmccallstatus.cpp	Fri Mar 12 15:43:23 2010 +0200
@@ -620,6 +620,14 @@
 void CBtmcCallStatus::ReportCallEventL(TInt aPrevStatus, TInt aNewStatus, TBool /*aOutgoing*/)
     {
     TRACE_FUNC_ENTRY
+    if ( iProtocol.ProtocolStatus().iProfile == EBtmcHSP)
+        {
+        // HSP 1.2 requires either RING indicator or in-band ringing
+        // tone, but not both.
+        TRACE_INFO((_L(" HSP connection, no call indicator")))  
+        return;
+        }
+    
     // CCWA
     if (iProtocol.ProtocolStatus().iCallWaitingNotif == EBTMonoATCallWaitingNotifEnabled && 
         (!(aPrevStatus & KCallRingingBit) && (aNewStatus & KCallRingingBit)) &&
--- a/bluetoothengine/btmac/src/BTMonoCmdHandler/btmcoperator.cpp	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/btmac/src/BTMonoCmdHandler/btmcoperator.cpp	Fri Mar 12 15:43:23 2010 +0200
@@ -122,7 +122,6 @@
 void CBtmcOperator::DoCancel()
     {
     TRACE_FUNC
-	iStore.CancelAsyncRequest(EMobilePhoneStoreRead);
     }
 
 // -------------------------------------------------------------------------------
--- a/bluetoothengine/btmac/src/BTMonoCmdHandler/btmcphonestatus.cpp	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/btmac/src/BTMonoCmdHandler/btmcphonestatus.cpp	Fri Mar 12 15:43:23 2010 +0200
@@ -302,14 +302,6 @@
         }
     }
 
-TInt CBtmcPhoneStatus::GetVolumeStatus()
-	{
-	if(iVol)
-		return iVol->GetVolume();
-	else
-		return 0;
-	}
-
 // -----------------------------------------------------------------------------
 // CBtmcPhoneStatus::CBtmcPhoneStatus
 // -----------------------------------------------------------------------------
--- a/bluetoothengine/btmac/src/BTMonoCmdHandler/btmcprotocol.cpp	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/btmac/src/BTMonoCmdHandler/btmcprotocol.cpp	Fri Mar 12 15:43:23 2010 +0200
@@ -389,7 +389,6 @@
         {
         iCallStatus->ReportCallStatusL();
         }
-    iVolumeSyncFromAccessory = EFalse;
     TRACE_FUNC_EXIT
     }
 
@@ -938,12 +937,15 @@
             LEAVE_IF_ERROR(aCmd.Parameter(0, param))
             TInt value;
             LEAVE_IF_ERROR(param.Int(value))
-            if (!iPhoneStatus)
+            // In HFP, AT+VGS is not valid before service level connection
+            // has established.
+            // In HSP, AT+VGS is allowed at any time.
+            if (!iPhoneStatus && iProtocolStatus->iProfile == EBtmcHSP )
                 {
                 iPhoneStatus = CBtmcPhoneStatus::NewL(*this, iPhone, iProtocolStatus->iProfile);
                 iPhoneStatus->SetVolumeControlFeatureL(ETrue);
                 }
-            if(iVolumeSyncFromAccessory)
+            if(iPhoneStatus)
                 {
                 iPhoneStatus->SetSpeakerVolumeL(value);
                 }
@@ -1025,37 +1027,9 @@
     CleanupStack::Pop(ok);
     SendResponseL(resarr);
     CleanupStack::PopAndDestroy(&resarr);
-    
-    // solution to volume sync - phone will always send its volume status back to accessory
-    
-    if( (aCmd.Id() == EATVGS) && (iVolumeSyncFromAccessory == EFalse) )
-    	{
-    	iVolumeSyncFromAccessory = ETrue;
-    	TInt vol(KErrNotFound);
-
-        if(iPhoneStatus)
-            {
-            vol = iPhoneStatus->GetVolumeStatus();
-            }
-
-    	if(vol > KErrNotFound) // volume exists
-    		{
-        TATParam param = TATParam();
-        LEAVE_IF_ERROR(aCmd.Parameter(0, param))
-        TInt value;
-        LEAVE_IF_ERROR(param.Int(value))
-        if(value != vol)
-    			{
-    			CATResult* event = CATResult::NewLC(EATVGS, EATUnsolicitedResult, vol);
-    			SendUnsoltResultL(*event);
-    			CleanupStack::PopAndDestroy(event);
-    			}
-    		}
-    	}
     CmdHandlingCompletedL();    
     }
 
-
 // -----------------------------------------------------------------------------
 // CBtmcProtocol::HandleActionCommandL
 // 
--- a/bluetoothengine/btmac/src/BTMonoCmdHandler/btmcvolume.cpp	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/btmac/src/BTMonoCmdHandler/btmcvolume.cpp	Fri Mar 12 15:43:23 2010 +0200
@@ -60,11 +60,13 @@
 void CBtmcVolume::SetSpeakerVolumeL(TInt aHfVol)
     {
     TRACE_FUNC
-    TRACE_INFO((_L("phone vol %d, acc vol %d"), iPhnSpkrVol, iAccSpkrVol))
+    TRACE_INFO((_L("current vols phone %d, acc %d"), iPhnSpkrVol, iAccSpkrVol))
+    // Store the new volume setting of headset regardless of 
+    // whether volume control is active or not currently
     iAccSpkrVol = HfToPhoneVolScale(aHfVol);
-    if (iVolCtrlActivated)
+    TRACE_INFO((_L("new acc vol %d"), iAccSpkrVol))
+    if ( IsActiveRemoteVolumeControl() )
         {
-        TRACE_INFO((_L("to new vol %d"), iAccSpkrVol))
         TInt vol = GetNewPhoneVol();
         if (vol != KNoAudioStreaming)
             {
@@ -73,10 +75,6 @@
             DoSetSpeakerVolL( prevPhVol );
             }
         }
-    else
-        {
-        TRACE_INFO((_L("volume control inactive!")))
-        }
     }
 
 void CBtmcVolume::SetMicrophoneVolumeL(TInt /*aHfVol*/)
@@ -86,13 +84,11 @@
 
 void CBtmcVolume::ActivateRemoteVolumeControl()
     {
-    if (!iVolCtrlActivated)
+    TRACE_FUNC
+    if (!IsActiveRemoteVolumeControl() )
         {
-        TRACE_FUNC
 		iVolLevelProperty.Subscribe(iActive->iStatus);     
         iActive->GoActive();
-
-        iVolCtrlActivated = ETrue;
         TInt vol = GetNewPhoneVol();
         TRACE_INFO((_L("current phone vol %d, acc vol %d"), vol, iAccSpkrVol))
         if (vol != KNoAudioStreaming)
@@ -109,11 +105,7 @@
 
 void CBtmcVolume::DeActivateRemoteVolumeControl()
     {
-    if (iVolCtrlActivated)
-        {
-        iVolCtrlActivated = EFalse;
-        iActive->Cancel();
-        }
+    iActive->Cancel();
     TRACE_FUNC
     }
 
@@ -242,21 +234,15 @@
             volClick = (iAccSpkrVol > iPhnSpkrVol) ? KPSVolumeUpClicked : KPSVolumeDownClicked;
             }        
         }
-     
+    TInt err( KErrNotFound );
     if( volClick )
         {
-        iAction = ESpeakerVolSet;
-        TInt err = iVolKeyEventProperty.Set( volClick );
-        if( err )
-            {
-            iAction = ESpeakerVolSubscribe;
-            TRACE_ERROR((_L("Set KMediaKeysVolumeKeyEvent err %d"), err));
-            }
+        err = iVolKeyEventProperty.Set( volClick );
+        TRACE_INFO((_L("Set KMediaKeysVolumeKeyEvent click %d err %d"), volClick, err));
         }
-    else
-        {        
-        iAction = ESpeakerVolSubscribe;
-        }
+    
+    iAction = err ? ESpeakerVolSubscribe : ESpeakerVolSet;
+
     TRACE_FUNC_EXIT 
     }
 
@@ -313,4 +299,9 @@
 	return iPhnSpkrVol;
 	}
 
+TBool CBtmcVolume::IsActiveRemoteVolumeControl()
+    {
+    return iActive->IsActive();
+    }
+
 // End of file
--- a/bluetoothengine/btnotif/src/BTNInqNotifier.cpp	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/btnotif/src/BTNInqNotifier.cpp	Fri Mar 12 15:43:23 2010 +0200
@@ -59,6 +59,7 @@
     {
     FLOG(_L("[BTNOTIF]\t CBTInqNotifier::~CBTInqNotifier()"));
     delete iUi;
+    iUi = NULL;
     FLOG(_L("[BTNOTIF]\t CBTInqNotifier::~CBTInqNotifier() completed"));
     }
 
@@ -84,7 +85,7 @@
     {
     FLOG(_L("[BTNOTIF]\t CBTInqNotifier::GetParamsL()"));
 
-    if( iUi || iReplySlot!=NULL || !iMessage.IsNull() )
+    if( !iMessage.IsNull() )
         {
         aMessage.Complete(KErrInUse);
         return;
@@ -124,6 +125,8 @@
     if( iUi )
         {
         iUi->Cancel();
+        delete iUi;
+        iUi = NULL;
         }
     CBTNotifierBase::Cancel();
     FLOG(_L("[BTNOTIF]\t CBTInqNotifier::Cancel() completed"));
--- a/bluetoothengine/btui/Ecom/src/BTUIPairedDevicesView.cpp	Fri Feb 19 22:59:18 2010 +0200
+++ b/bluetoothengine/btui/Ecom/src/BTUIPairedDevicesView.cpp	Fri Mar 12 15:43:23 2010 +0200
@@ -289,6 +289,11 @@
             TBTDevice device;
             device.iIndex = iContainer->CurrentItemIndex();
             iModel->GetDevice(device);
+            if ( device.iStatus & EStatusBtuiConnected )
+                {
+                // If device is already connected, we do nothing here. 
+                break;
+                }
             device.iOperation = EOpConnect;
             ConnectL( device, ETrue );
 	        break;            	
@@ -1069,6 +1074,13 @@
     TBTDevice device;
     device.iIndex = index;
     iModel->GetDevice(device);
+    
+    if ( !( device.iStatus & EStatusBtuiConnected) )
+        {
+        // If device is already disconnected, return immediately.
+        return;
+        }
+    
 	iDisconnectQueryDevice = device;//remember device related with query dialog
 
     // Create confirmation query
--- a/tsrc/public/basic/obexservapitest/src/ObexServAPItestBlocks.cpp	Fri Feb 19 22:59:18 2010 +0200
+++ b/tsrc/public/basic/obexservapitest/src/ObexServAPItestBlocks.cpp	Fri Mar 12 15:43:23 2010 +0200
@@ -21,7 +21,6 @@
 #include <e32svr.h>
 #include <StifParser.h>
 #include <Stiftestinterface.h>
-#include <btmsgtypeuid.h>
 #include <UiklafInternalCRKeys.h>
 #include <UikonInternalPSKeys.h>
 #include <obexutils.rsg>
@@ -30,6 +29,9 @@
 #include "ObexServAPItest.h"
 
 
+// Defined to coincide with the definition in btmsgtypeuid.h 
+const TUid KUidMsgTypeBt                 = {0x10009ED5};
+
 
 // ============================ MEMBER FUNCTIONS ===============================
 
--- a/tsrc/public/basic/obexservapitest/src/testlogger.cpp	Fri Feb 19 22:59:18 2010 +0200
+++ b/tsrc/public/basic/obexservapitest/src/testlogger.cpp	Fri Mar 12 15:43:23 2010 +0200
@@ -182,7 +182,7 @@
     buffer.Insert( 0, GetPrefix( aLevel ) );
 
     // Log a timestamp
-    TTimeStamp8 time;
+    TStifLoggerTimeStamp8 time;
     TRAP_IGNORE( LogTimeStampL( time ) );
     buffer.Insert( 0, time );
 
@@ -227,7 +227,7 @@
     buffer.Copy( converter );
 
     // Log a timestamp
-    TTimeStamp8 time;
+    TStifLoggerTimeStamp8 time;
     TRAP_IGNORE( LogTimeStampL( time ) );
     buffer.Insert( 0, time );
 
@@ -501,9 +501,9 @@
     iLog->Log( KJSSECTION );
     TBuf<KSysUtilVersionTextLength> version( _L( "Version unknown!" ) );
     (void) SysUtil::GetSWVersion( version );
-    TTimeStamp8 date;
+    TStifLoggerTimeStamp8 date;
     LogTimeStampL( date, EFalse );
-    TTimeStamp8 time;
+    TStifLoggerTimeStamp8 time;
     LogTimeStampL( time );
     TPtrC timePtr( time.Mid( 6, 13 ) );
     iLog->Log( KHtmlStatSection, &date, &timePtr, &version );