htiui/HtiCommPlugins/HtiBtCommPlugin/BtEngine/src/BtSerialClient.cpp
changeset 0 d6fe6244b863
child 3 2703485a934c
equal deleted inserted replaced
-1:000000000000 0:d6fe6244b863
       
     1 /*
       
     2 * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
       
     3 * All rights reserved.
       
     4 * This component and the accompanying materials are made available
       
     5 * under the terms of "Eclipse Public License v1.0"
       
     6 * which accompanies this distribution, and is available
       
     7 * at the URL "http://www.eclipse.org/legal/epl-v10.html".
       
     8 *
       
     9 * Initial Contributors:
       
    10 * Nokia Corporation - initial contribution.
       
    11 *
       
    12 * Contributors:
       
    13 *
       
    14 * Description:  Bluetooth serial client.
       
    15 *
       
    16 */
       
    17 
       
    18 
       
    19 // INCLUDE FILES
       
    20 #include <e32std.h>
       
    21 #include <btengsettings.h>  // CBTEngSettings
       
    22 
       
    23 #include "BtSerialClient.h"
       
    24 #include "MessageServiceSearcher.h"
       
    25 #include "BtSerialEngine.pan"
       
    26 #include "HtiBtEngineLogging.h"
       
    27 #include "socketswriter.h"
       
    28 #include "socketsreader.h"
       
    29 
       
    30 const TInt KMaxBtStartWaitLoop   = 5;
       
    31 const TInt KBtStateQueryInterval = 1000000; // microseconds
       
    32 
       
    33 
       
    34 // ----------------------------------------------------------------------------
       
    35 EXPORT_C CBtSerialClient* CBtSerialClient::NewL(MBtSerialClientObserver& aObserver)
       
    36     {
       
    37     CBtSerialClient* self = new (ELeave) CBtSerialClient(aObserver);
       
    38     CleanupStack::PushL(self);
       
    39     self->ConstructL();
       
    40     CleanupStack::Pop(self);
       
    41     return self;
       
    42     }
       
    43 
       
    44 // ----------------------------------------------------------------------------
       
    45 CBtSerialClient::CBtSerialClient(MBtSerialClientObserver& aObserver)
       
    46 : CActive( CActive::EPriorityStandard ), iObserver(aObserver),
       
    47   iState( EWaitingToGetDevice ), iCurrentServiceIndex( 0 )
       
    48     {
       
    49     CActiveScheduler::Add( this );
       
    50     }
       
    51 
       
    52 // ----------------------------------------------------------------------------
       
    53 EXPORT_C CBtSerialClient::~CBtSerialClient()
       
    54     {
       
    55     delete iSocketReader;
       
    56     delete iSocketWriter;
       
    57 
       
    58     Cancel();
       
    59 
       
    60     iSocket.Close();
       
    61     iSocketServer.Close();
       
    62 
       
    63     delete iServiceSearcher;
       
    64     }
       
    65 
       
    66 // ----------------------------------------------------------------------------
       
    67 void CBtSerialClient::ConstructL()
       
    68     {
       
    69     LOG_D( "CBtSerialClient::ConstructL()" );
       
    70 
       
    71    // Check Bluetooth power state
       
    72     TBTPowerStateValue powerState = EBTPowerOff;
       
    73     CBTEngSettings* btSettings = CBTEngSettings::NewLC();
       
    74     TInt err = btSettings->GetPowerState( powerState );
       
    75     if ( err )
       
    76         {
       
    77         LOGFMT_W( "CBtSerialClient::ConstructL(): GetPowerState error %d", err );
       
    78         powerState = EBTPowerOff;
       
    79         }
       
    80 
       
    81     // If BT not on - try to set it on
       
    82     if ( powerState == EBTPowerOff )
       
    83         {
       
    84         LOG_I( "CBtSerialClient::ConstructL(): BT not on - setting power on" );
       
    85         err = btSettings->SetPowerState( EBTPowerOn );
       
    86         if ( err )
       
    87             {
       
    88             LOGFMT_E( "CBtSerialClient::ConstructL(): SetPowerState error %d", err );
       
    89             User::Leave( err );
       
    90             }
       
    91 
       
    92         // Wait until BT is reported to be on (or waiting time exceeds)
       
    93         TInt loopCounter = 0;
       
    94         while ( powerState == EBTPowerOff && loopCounter < KMaxBtStartWaitLoop )
       
    95             {
       
    96             btSettings->GetPowerState( powerState );
       
    97             LOGFMT_D( "CBtSerialClient::ConstructL(): BT power state %d", powerState );
       
    98             User::After( KBtStateQueryInterval );
       
    99             loopCounter++;
       
   100             }
       
   101 
       
   102         if ( powerState == EBTPowerOff )
       
   103             {
       
   104             LOG_E( "CBtSerialClient::ConstructL(): Could not turn BT on" );
       
   105             User::Leave( KErrCouldNotConnect );
       
   106             }
       
   107         LOG_I( "CBtSerialClient::ConstructL(): Continuing BT connect" );
       
   108         }
       
   109     CleanupStack::PopAndDestroy(); // btSettings
       
   110 
       
   111     iServiceSearcher = CMessageServiceSearcher::NewL();
       
   112     User::LeaveIfError( iSocketServer.Connect() );
       
   113     iSocketReader = CSocketsReader::NewL( *this, iSocket );
       
   114     iSocketWriter = CSocketsWriter::NewL( *this, iSocket );
       
   115     }
       
   116 
       
   117 // ----------------------------------------------------------------------------
       
   118 void CBtSerialClient::DoCancel()
       
   119     {
       
   120     LOG_W("CBtSerialClient::DoCancel(): Doing nothing");
       
   121     }
       
   122 
       
   123 // ----------------------------------------------------------------------------
       
   124 void CBtSerialClient::RunL()
       
   125     {
       
   126     if ( iStatus != KErrNone )
       
   127         {
       
   128         switch ( iState )
       
   129             {
       
   130             case EGettingDevice:
       
   131                 if ( iStatus == KErrCancel )
       
   132                     {
       
   133                     LOG_W( "CBtSerialClient: No device selected" );
       
   134                     }
       
   135                 iState = EWaitingToGetDevice;
       
   136                 iObserver.ConnectedToServer( iStatus.Int() );
       
   137                 break;
       
   138             case EGettingService:
       
   139                 LOGFMT_W( "CBtSerialClient: Failed to fetch remote service: %d", iStatus.Int() );
       
   140                 iObserver.ConnectedToServer( iStatus.Int() );
       
   141                 iState = EWaitingToGetDevice;
       
   142                 break;
       
   143             case EGettingConnection:
       
   144                 LOGFMT_W( "CBtSerialClient: Failed to connect to remote service: %d", iStatus.Int() );
       
   145                 if ( iCurrentServiceIndex < iServiceSearcher->ServiceCount() )
       
   146                     {
       
   147                     // Try another service
       
   148                     iCurrentServiceIndex++;
       
   149                     ConnectToServerL(); // establish RFComm connection
       
   150                     }
       
   151                 else
       
   152                     {
       
   153                     iState = EWaitingToGetDevice;
       
   154                     iObserver.ConnectedToServer( iStatus.Int() );
       
   155                     }
       
   156                 break;
       
   157             case EConnected:
       
   158                 LOGFMT_I( "CBtSerialClient: Lost connection: %d", iStatus.Int() )
       
   159                 DisconnectFromServer();
       
   160                 iState = EDisconnecting;
       
   161                 break;
       
   162             case EDisconnecting:
       
   163                 LOGFMT_I("CBtSerialClient: Disconnected from server: %d", iStatus.Int() );
       
   164                 iSocket.Close();
       
   165                 iState = EWaitingToGetDevice;
       
   166                 iObserver.DisconnectedFromServer();
       
   167                 break;
       
   168             default:
       
   169                 Panic( EBTPointToPointInvalidLogicState );
       
   170                 break;
       
   171             }
       
   172         }
       
   173     else // iStatus = KErrNone
       
   174         {
       
   175         switch ( iState )
       
   176             {
       
   177             case EGettingDevice:
       
   178                 // found a device now search for a suitable service
       
   179                 LOGFMT_I("CBtSerialClient: Found device: %S. Finding correct service.", &(iServiceSearcher->ResponseParams().DeviceName()) );
       
   180                 iState = EGettingService;
       
   181                 iStatus = KRequestPending;  // this means that the RunL can not
       
   182                                             // be called until this program
       
   183                                             // does something to iStatus
       
   184                 iBTServerDevice = iServiceSearcher->BTDevAddr();
       
   185                 iServiceSearcher->FindServiceL( iBTServerDevice, iStatus );
       
   186                 SetActive();
       
   187                 break;
       
   188             case EGettingService:
       
   189                 LOGFMT_I("CBtSerialClient: Found %d remote services", iServiceSearcher->ServiceCount());
       
   190                 iState = EGettingConnection;
       
   191                 ConnectToServerL(); // establish RFComm connection
       
   192                 break;
       
   193             case EGettingConnection:
       
   194                 LOG_I( "CBtSerialClient: Connected to remote service" );
       
   195                 iState = EConnected;
       
   196                 iObserver.ConnectedToServer( KErrNone );
       
   197                 break;
       
   198             case EDisconnecting:
       
   199                 LOG_I( "CBtSerialClient: Disconnecting" );
       
   200                 iSocket.Close();
       
   201                 iState = EWaitingToGetDevice;
       
   202                 iObserver.DisconnectedFromServer();
       
   203                 break;
       
   204             default:
       
   205                 LOGFMT_E( "CBtSerialClient: Invalid logic state in RunL: %d. Will panic", iState );
       
   206                 Panic( EBTPointToPointInvalidLogicState );
       
   207                 break;
       
   208             };
       
   209         }
       
   210     }
       
   211 
       
   212 // ----------------------------------------------------------------------------
       
   213 EXPORT_C void CBtSerialClient::ConnectL()
       
   214     {
       
   215     if ( iState == EWaitingToGetDevice && !IsActive() )
       
   216         {
       
   217         LOG_D( "CBtSerialClient: Connecting by user selection" );
       
   218         iState = EGettingDevice;
       
   219         iServiceSearcher->SelectDeviceByDiscoveryL( iStatus );
       
   220         SetActive();
       
   221         }
       
   222     else
       
   223         {
       
   224         LOG_W( "CBtSerialClient: Already connecting or connected" );
       
   225         User::Leave( KErrInUse );
       
   226         }
       
   227     }
       
   228 
       
   229 // ----------------------------------------------------------------------------
       
   230 EXPORT_C void CBtSerialClient::ConnectL( const TBTDevAddr aBTServerDevice,
       
   231                                          const TInt aPort )
       
   232     {
       
   233     if ( iState == EWaitingToGetDevice && !IsActive() )
       
   234         {
       
   235         if ( aPort >= 0 )
       
   236             {
       
   237             // If there was a valid port given, add it as the first port to try
       
   238             iServiceSearcher->AppendPort( aPort );
       
   239             }
       
   240         LOG_D( "CBtSerialClient: Connecting by address" );
       
   241         iBTServerDevice = aBTServerDevice;
       
   242         iServiceSearcher->FindServiceL( iBTServerDevice, iStatus );
       
   243         iState = EGettingService;
       
   244         iStatus = KRequestPending;  // this means that the RunL can not
       
   245                                     // be called until this program
       
   246                                     // does something to iStatus
       
   247         SetActive();
       
   248         }
       
   249     else
       
   250         {
       
   251         LOG_W("CBtSerialClient: Already connecting or connected");
       
   252         User::Leave( KErrInUse );
       
   253         }
       
   254     }
       
   255 
       
   256 // ----------------------------------------------------------------------------
       
   257 EXPORT_C void CBtSerialClient::ConnectL( const TDesC& aBTServerDeviceName,
       
   258                                          const TInt aPort )
       
   259     {
       
   260     if ( iState == EWaitingToGetDevice && !IsActive() )
       
   261         {
       
   262         if ( aPort >= 0 )
       
   263             {
       
   264             // If there was a valid port given, add it as the first port to try
       
   265             iServiceSearcher->AppendPort( aPort );
       
   266             }
       
   267         LOG_D( "CBtSerialClient: Connecting by name" );
       
   268         iState = EGettingDevice;
       
   269         iServiceSearcher->SelectDeviceByNameL( aBTServerDeviceName, iStatus );
       
   270         SetActive();
       
   271         }
       
   272     else
       
   273         {
       
   274         LOG_W( "CBtSerialClient: Already connecting or connected" );
       
   275         User::Leave( KErrInUse );
       
   276         }
       
   277     }
       
   278 
       
   279 // ----------------------------------------------------------------------------
       
   280 EXPORT_C TBTDevAddr CBtSerialClient::ServerAddressL()
       
   281     {
       
   282     if ( !Connected() )
       
   283         {
       
   284         User::Leave( KErrNotReady );
       
   285         }
       
   286     return iBTServerDevice;
       
   287     }
       
   288 
       
   289 // ----------------------------------------------------------------------------
       
   290 EXPORT_C void CBtSerialClient::Disconnect()
       
   291     {
       
   292     if ( iState == EConnected )
       
   293         {
       
   294         DisconnectFromServer();
       
   295         iState = EDisconnecting;
       
   296         }
       
   297     else
       
   298         {
       
   299         LOG_W( "CBtSerialClient: Disconnect: Not connected" );
       
   300         User::Leave( KErrDisconnected );
       
   301         }
       
   302     }
       
   303 
       
   304 // ----------------------------------------------------------------------------
       
   305 void CBtSerialClient::DisconnectFromServer()
       
   306     {
       
   307     // Terminate all operations
       
   308     iSocket.CancelAll();
       
   309     Cancel();
       
   310     iSocketReader->Cancel();
       
   311     iSocketWriter->CancelSending();
       
   312 
       
   313     LOG_I( "CBtSerialClient: Disconnecting from server" );
       
   314     iSocket.Shutdown( RSocket::ENormal, iStatus );
       
   315     SetActive();
       
   316     }
       
   317 
       
   318 // ----------------------------------------------------------------------------
       
   319 void CBtSerialClient::ConnectToServerL()
       
   320     {
       
   321     LOG_I("CBtSerialClient: ConnectToServerL")
       
   322     User::LeaveIfError( iSocket.Open( iSocketServer, KStrRFCOMM ) );
       
   323 
       
   324     TBTSockAddr address;
       
   325     address.SetBTAddr( iServiceSearcher->BTDevAddr() );
       
   326     address.SetPort( iServiceSearcher->Port( iCurrentServiceIndex ) );
       
   327 
       
   328     LOGFMT_I("CBtSerialClient: ConnectToServerL: Port = %d", address.Port() );
       
   329     iSocket.Connect( address, iStatus );
       
   330 
       
   331 #ifdef __WINS__
       
   332     User::After( 1 ); // Needed to allow emulator client to connect to server
       
   333 #endif
       
   334 
       
   335     SetActive();
       
   336     }
       
   337 
       
   338 // ----------------------------------------------------------------------------
       
   339 EXPORT_C void CBtSerialClient::SendL(const TDesC8& aData)
       
   340     {
       
   341     if ( !Connected() )
       
   342         {
       
   343         User::Leave( KErrNotReady );
       
   344         }
       
   345 
       
   346     LOGFMT_D("CBtSerialClient::SendL: Sending data (max first 32 bytes): \"%S\"", &(aData.Left(32)));
       
   347     iSocketWriter->SendL( aData ); // Add to data queue and start sending
       
   348     LOG_D("CBtSerialClient::SendL: Sent to socket");
       
   349     }
       
   350 
       
   351 EXPORT_C void CBtSerialClient::ReadAsyncL()
       
   352     {
       
   353     if ( !Connected() )
       
   354         {
       
   355         User::Leave( KErrNotReady );
       
   356         }
       
   357     iSocketReader->ReadAsync();
       
   358     }
       
   359 
       
   360 // ----------------------------------------------------------------------------
       
   361 EXPORT_C TInt CBtSerialClient::FreeSpaceInSendBuffer()
       
   362     {
       
   363     return iSocketWriter->FreeSpaceInSendBuffer();
       
   364     }
       
   365 
       
   366 // ----------------------------------------------------------------------------
       
   367 EXPORT_C TInt CBtSerialClient::SendBufferMaxSize()
       
   368     {
       
   369     return iSocketWriter->SendBufferMaxSize();
       
   370     }
       
   371 
       
   372 // ----------------------------------------------------------------------------
       
   373 EXPORT_C TBool CBtSerialClient::Connected()
       
   374     {
       
   375     return (iState == EConnected);
       
   376     }
       
   377 
       
   378 // ----------------------------------------------------------------------------
       
   379 EXPORT_C TBool CBtSerialClient::Connecting()
       
   380     {
       
   381     return ( ( iState == EGettingDevice ) ||
       
   382              ( iState == EGettingService ) ||
       
   383              ( iState == EGettingConnection ) );
       
   384     }
       
   385 
       
   386 // ----------------------------------------------------------------------------
       
   387 EXPORT_C TInt CBtSerialClient::ServicePort()
       
   388     {
       
   389     if ( !Connected() )
       
   390         {
       
   391         return KErrDisconnected;
       
   392         }
       
   393     return iServiceSearcher->Port( iCurrentServiceIndex );
       
   394     }
       
   395 
       
   396 // ----------------------------------------------------------------------------
       
   397 void CBtSerialClient::ReportError( TErrorType aErrorType, TInt aErrorCode )
       
   398     {
       
   399     LOGFMT_W( "CBtSerialClient::ReportError: %d", aErrorCode );
       
   400     // From socket reader or writer
       
   401     switch ( aErrorType )
       
   402         {
       
   403         case EDisconnected:
       
   404             {
       
   405             LOG_I( "CBtSerialClient: disconnected" );
       
   406             }
       
   407             break;
       
   408         case ETimeOutOnWrite:
       
   409             {
       
   410             LOG_I( "CBtSerialClient: timout writing data. Disconnecting from server" );
       
   411             }
       
   412             break;
       
   413         case EGeneralReadError:
       
   414             {
       
   415             LOG_I( "CBtSerialClient: general read error. Disconnecting from server" );
       
   416             }
       
   417             break;
       
   418         case EGeneralWriteError:
       
   419             {
       
   420             LOG_I( "CBtSerialClient: general write error. Disconnecting from server" );
       
   421             }
       
   422             break;
       
   423         }
       
   424     Disconnect();
       
   425     aErrorCode = aErrorCode;
       
   426     }
       
   427 
       
   428 // ----------------------------------------------------------------------------
       
   429  void CBtSerialClient::NewData( const TDesC8& aData )
       
   430     {
       
   431     iObserver.DataFromServer( aData );
       
   432     }
       
   433 
       
   434 // ----------------------------------------------------------------------------
       
   435 void CBtSerialClient::AllBufferedDataSent()
       
   436     {
       
   437     iObserver.AllBufferedDataSent();
       
   438     }
       
   439 
       
   440 // End of File