⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 btcon_msgclient.cpp

📁 C++实现的BlueTooth
💻 CPP
字号:
/*****************************************************************************

 COPYRIGHT All rights reserved Sony Ericsson Mobile Communications AB 2005.



 The software is the copyrighted work of Sony Ericsson Mobile Communications AB.

 The use of the software is subject to the terms of the end-user license

 agreement which accompanies or is included with the software. The software is

 provided "as is" and Sony Ericsson specifically disclaim any warranty or

 condition whatsoever regarding merchantability or fitness for a specific

 purpose, title or non-infringement. No warranty of any kind is made in

 relation to the condition, suitability, availability, accuracy, reliability,

 merchantability and/or non-infringement of the software provided herein.



 *****************************************************************************/


// BTCon_AppUi.cpp
//
//

#include <eikenv.h>         // CEikonEnv
#include <QBTselectdlg.h>   // CQBTUISelectDialog
#include <btsdp.h>          // CSdpAgent

#include "BTCon_AppView.h"
#include "BTCon_MsgClient.h"


_LIT8(KTest, "Connection Test");
_LIT(KSending, "sending: ");

const TInt KServiceClass = 0x1101;    //  SerialPort


CMsgClient* CMsgClient::NewL(CBTConAppView* aView)
  {
  CMsgClient* self = NewLC(aView);
  CleanupStack::Pop(self);
  return self;
  }
  
CMsgClient* CMsgClient::NewLC(CBTConAppView* aView)
  {
  CMsgClient* self = new (ELeave) CMsgClient(aView);
  CleanupStack::PushL(self);
  self->ConstructL();
  return self;
  }

CMsgClient::~CMsgClient()
  {
  Disconnect(EFalse);

  Deque();
  }

void CMsgClient::ConnectL()
  {
  if(iCurrentState == EInitStage && !IsActive())
    {
    iCurrentState = ESearchForDevice;

    TBTDevAddr devAddr;
    TBTDeviceName devName;
    TBTDeviceClass devClass;
    TInt serviceFilter = -1;
    CQBTUISelectDialog* dialog = new (ELeave) CQBTUISelectDialog(
                                      devAddr,
                                      devName,
                                      devClass,
                                      CQBTUISelectDialog::EQBTDeviceFilterAll,
                                      serviceFilter);

    // Launch "Select Bluetooth device" dialog.
    if (dialog->LaunchSingleSelectDialogLD())
      {
      iResultPckg().SetDeviceAddress(devAddr);
      iResultPckg().SetDeviceName(devName);
      iResultPckg().SetDeviceClass(devClass);

      iStatus = KErrNone;
      RunL();
      }
    else
      {
      iStatus = KErrCancel; // Error or cancel
      RunL();
      }
    }
  else
    {
    iPtrView->UpdateEditText(_L("Client busy"));
    User::Leave(KErrInUse);
    }
  }

void CMsgClient::Disconnect(TBool aDisplayInfo)
  {
  switch(iCurrentState)
    {
    case ESearchForService:
      {
      iCurrentState = EDisconnecting;
      TRequestStatus* status = &iStatus;
      User::RequestComplete(status, KErrNotFound);
      return;
      }
      break;
    case EConnecting :
      iSocket.CancelConnect();
      break;
    case EReading:
      iSocket.CancelRecv();
      break;
    case EWriting:
    case ESendingTestMsg:
      iSocket.CancelWrite();
      break;
    default:
      break;
    }
  iSocket.Close();
  iSocketServ.Close();

  iCurrentState = EInitStage;

  if( iWriteMsgBuf )
    {
    delete iWriteMsgBuf;
    iWriteMsgBuf = 0;
    }

  if(aDisplayInfo)
    iPtrView->UpdateEditText(_L("Disconected"));
  }

void CMsgClient::SendMsgL(const TDesC& aMsg)
  {
  // check if is not already doing writing or canceling reading
  if( iBusyWriting != EFalse || iCurrentState == ECancelReading )
    {
    iPtrView->UpdateEditText(_L("SendMsgL err: writing..."));
    return;
    }
  // if in reading state, cancel reading first
  if( iCurrentState == EReading )
    {
    iSocket.CancelRecv();
    iCurrentState = ECancelReading;
    iPtrView->UpdateEditText(_L("Reading was started: canceling..."));
    if( iWriteMsgBuf != NULL )
      {
      delete iWriteMsgBuf;
      iWriteMsgBuf = NULL;
      }
    iWriteMsgBuf = HBufC8::NewL(aMsg.Length());
    TPtr8 bufPtr = iWriteMsgBuf->Des();
    bufPtr.Append(aMsg);
    if( !IsActive() )
      SetActive();
    }
  // if in writing state, just simply write
  else if( iCurrentState == EWriting )
    {
    // give info: sending msg
    TBuf<50> buf;
    buf.Append(KSending);
    buf.Append(aMsg);
    iPtrView->UpdateEditText(buf);

    iCurrentState = EWriting;
    iBusyWriting = ETrue;

    HBufC8* msgH = HBufC8::NewL(aMsg.Length());
    TPtr8 bufPtr = msgH->Des();
    bufPtr.Append(aMsg);

    TRAPD(err, iSocket.Write(*msgH, iStatus));
    if(err != KErrNone)
      {
      TBuf<256> buf;
      buf.Format(_L("SendMsgErr: %d"), err);
      iPtrView->UpdateEditText(buf);
      }
    if( !IsActive() )
      SetActive();
    }
  // do not try to send when in idle or connecting state
  }

void CMsgClient::DoSendMsgAfterCanceling()
  {
  // give info: sending msg
  TBuf<30> msg;
  msg.Copy(*iWriteMsgBuf);
  TBuf<50> buf;
  buf.Append(KSending);
  buf.Append(msg);
  iPtrView->UpdateEditText(buf);

  iCurrentState = EWriting;
  iBusyWriting = ETrue;

  TRAPD(err, iSocket.Write(*iWriteMsgBuf, iStatus));
  if(err != KErrNone)
    {
    TBuf<256> buf;
    buf.Format(_L("SendMsgErr: %d"), err);
    iPtrView->UpdateEditText(buf);
    }

  if( !IsActive() )
    SetActive();
  }

void CMsgClient::AttributeRequestComplete(TSdpServRecordHandle /*aHandle*/,
                                          TInt aError)
  {
  if (aError != KErrNone)
    {
    TBuf<256> buf;
    buf.Format(_L("AttReqCompl, connect failed %d"), aError);
    iPtrView->UpdateEditText(buf);
    TRequestStatus* status = &iStatus;
    User::RequestComplete(status, aError);
    return;
    }

  if(!iHasFoundService)
    {
    iPtrView->UpdateEditText(_L("Making another SDP request"));
    iSdpAgent->NextRecordRequestL();
    }
  else
    {
    if (aError == KErrNone && !iHasFoundService)
        {
        aError = KErrNotFound;
        }
    TBuf<256> buf;
    buf.Format(_L("AttReqCompl finished, %d"), aError);
    iPtrView->UpdateEditText(buf);
    TRequestStatus* status = &iStatus;
    User::RequestComplete(status, aError);
    }
  }

void CMsgClient::AttributeRequestResult(TSdpServRecordHandle /*aHandle*/,
                                        TSdpAttributeID aAttrID,
                                        CSdpAttrValue* aAttrValue)
  {
  TBuf<256> buf;
  buf.Format(_L("Got attrib: id: %d type: %d"), aAttrID, aAttrValue->Type());
  iPtrView->UpdateEditText(buf);
  
  aAttrValue->AcceptVisitorL(*this);
  }

void CMsgClient::NextRecordRequestComplete(TInt aError,
                                           TSdpServRecordHandle aHandle,
                                           TInt aTotalRecordsCount)
  {
  if( aError != KErrNone )
    {
    TBuf<256> buf;
    buf.Format(_L("ConnectionFailed %d"), aError);
    iPtrView->UpdateEditText(buf);
    TRequestStatus* status = &iStatus;
    User::RequestComplete(status, aError);
    }
  else if(aTotalRecordsCount == 0)
    {
    iPtrView->UpdateEditText(_L("NRRC No records"));
    TRequestStatus* status = &iStatus;
    User::RequestComplete(status, KErrNotFound);
    return;
    }
  else
    {
    iSdpAgent->AttributeRequestL(aHandle, KSdpAttrIdProtocolDescriptorList);
    }
  }

void CMsgClient::VisitAttributeValueL(CSdpAttrValue& aValue,
                                      TSdpElementType aType)
  {
  TBuf<256> buf;
  buf.Format(_L("VisAttVal type: %d"), aType);
  if (aValue.Type() == ETypeUUID)
    {
    TUUID uuid = aValue.UUID();
    TBuf<256> uuidBuf;
    uuidBuf.Copy(uuid.ShortestForm());
    uuidBuf.SetMax();
    buf.Format(_L(" UUID %02X.%02X.%02X.%02X"),
                     uuidBuf[0], uuidBuf[1],
                     uuidBuf[2], uuidBuf[3]);
    iPtrView->UpdateEditText(buf);
    }
  else if (aValue.Type() == ETypeUint)
    {
    iRemotePort = aValue.Uint();
    buf.Format(_L("iRemotePort: %d"), iRemotePort);
    iPtrView->UpdateEditText(buf);
    iHasFoundService = ETrue;
    }
  }

void CMsgClient::StartListL(CSdpAttrValueList& /*aList*/)
  {
  }

void CMsgClient::EndListL()
  {
  }

void CMsgClient::DoCancel()
  {
  }

void CMsgClient::RunL()
  {
  if (iStatus != KErrNone)
    {
    switch (iCurrentState)
      {
      case ESearchForDevice:
        if (iStatus == KErrCancel)
          CEikonEnv::InfoWinL(_L("No device selected"), KNullDesC);
        iCurrentState = EInitStage;
        break;

      case ESearchForService:
      case EConnecting:
      case EDisconnecting:
        {
        TBuf<256> buf;
        buf.Format(_L("Connection error: %d"), iStatus.Int());
        iPtrView->UpdateEditText(buf);

        delete iSdpAgent;
        iSdpAgent = NULL;

        iCurrentState = EInitStage;
        iHasFoundService = EFalse;
        Cancel();
        }
        break;

      case ESendingTestMsg:
        {
        iCurrentState = ESearchForService;
        RetryEstablishingConection();
        SetActive();
        }
        break;

      case EWriting:
        {
        TBuf<256> buf;
        buf.Format(_L("Send error: %d"), iStatus.Int());
        iPtrView->UpdateEditText(buf);
        Disconnect(ETrue);
        }
        break;

      case ECancelReading :
        {
        TBuf<256> buf;
        buf.Format(_L("reading cancelled: %d"), iStatus.Int());
        iPtrView->UpdateEditText(buf);
        iCurrentState = EWriting;
        DoSendMsgAfterCanceling();
        }
        break;

      case EReading:
        {
        TBuf<256> buf;
        buf.Format(_L("Reading error: %d"), iStatus.Int());
        iPtrView->UpdateEditText(buf);
        Disconnect(ETrue);
        }
        break;

      default:
        TBuf<256> buf;
        buf.Format(_L("Unexpected Bluetooth state %d"), iCurrentState);
        iPtrView->UpdateEditText(buf);
        break;
      }
    }
  else 
    {
    switch (iCurrentState)
      {
      case ESearchForDevice:
        {
        // found device, write name
        TBuf<256> buf;
        buf.Append(_L("Selected "));
        buf.Append(iResultPckg().DeviceName());
        iPtrView->UpdateEditText(buf);
        // since device is choosen, search for service
        iCurrentState = ESearchForService;
        // block untill status is changed
        iStatus = KRequestPending;
        FindServiceL();
        SetActive();
        }
        break;

      case ESearchForService:
        iPtrView->UpdateEditText(_L("Found service, connecting"));
        iCurrentState = EConnecting;
        ConnectToServerL();
        break;

      case EConnecting:
        iCurrentState = ESendingTestMsg;
        CheckConectionValidity();
        break;

      case ESendingTestMsg:
        iPtrView->UpdateEditText(_L("Finished sending test Msg"));
        iPtrView->UpdateEditText(_L("Connected"));

        iCurrentState = EReading;
        RequestData(); //  Get more data
        break;

      case EReading:
        {
        HBufC* text = HBufC::NewLC(iMsgBuffer.Length());
        text->Des().Copy(iMsgBuffer);
        // add new message to listbox
        TBuf<256> buf;
        buf.Append(_L("got: "));
        buf.Append(*text);
        iPtrView->UpdateEditText(buf);
        CleanupStack::PopAndDestroy(text);
        RequestData(); //  Get more data
        }
        break;

      case EWriting :
        iBusyWriting = EFalse;
        iPtrView->UpdateEditText(_L("Message sent"));
        iCurrentState = EReading;
        RequestData(); //  Get more data
        break;

      case EDisconnecting:
        iPtrView->UpdateEditText(_L("Disconnected"));
        iCurrentState = EInitStage;
        break;

      default:
        iPtrView->UpdateEditText(_L("Panic: EBTPointToPointInvalidLogicState"));
        break;
      };
    }
  }

CMsgClient::CMsgClient(CBTConAppView* aView) : CActive(CActive::EPriorityStandard),
  iPtrView(aView), iCurrentState(EInitStage), iWriteMsgBuf(0)
  {
  CActiveScheduler::Add(this);
  }

void CMsgClient::ConstructL()
  {
  }

void CMsgClient::RequestData()
  {
  iSocket.RecvOneOrMore(iMsgBuffer, 0, iStatus, iLength);
  SetActive();
  }

void CMsgClient::ConnectToServerL()
  {
  iBusyWriting = EFalse;

  User::LeaveIfError(iSocketServ.Connect());

  User::LeaveIfError(iSocket.Open(iSocketServ, _L("RFCOMM")));

  TBTSockAddr address;
  address.SetBTAddr(iResultPckg().BDAddr());
  address.SetPort(iRemotePort);

  iSocket.Connect(address, iStatus);

  SetActive();
  }

void CMsgClient::FindServiceL()
  {
  if (!iResultPckg().IsValidBDAddr())
    {
    iPtrView->UpdateEditText(_L("FindServiceL left"));
    User::Leave(KErrNotFound);
    }

  iHasFoundService = EFalse;

  // delete any existing agent and search pattern
  delete iSdpSearchPattern;
  iSdpSearchPattern = NULL;

  delete iSdpAgent;
  iSdpAgent = NULL;

  iSdpAgent = CSdpAgent::NewL(*this, iResultPckg().BDAddr());

  iSdpSearchPattern = CSdpSearchPattern::NewL();

  iSdpSearchPattern->AddL(KServiceClass); 

  iSdpAgent->SetRecordFilterL(*iSdpSearchPattern);

  iSdpAgent->NextRecordRequestL();
  }

void CMsgClient::CheckConectionValidity()
  {
  TBuf<256> buf;
  buf.Format(_L("CheckConectionValidity"));
  iPtrView->UpdateEditText(buf);

  TRAPD(err, iSocket.Write(KTest, iStatus));
  SetActive();
  }

void CMsgClient::RetryEstablishingConection()
  {
  iPtrView->UpdateEditText(_L("RetryEstablishingConection"));

  iStatus = KRequestPending;
  iHasFoundService = EFalse;

  iSocket.Close();
  iSdpAgent->NextRecordRequestL();
  }


⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -