예제 #1
0
void QBluetoothSocketPrivate::connectToService(const QBluetoothAddress &address, quint16 port, QIODevice::OpenMode openMode)
{
    Q_Q(QBluetoothSocket);
    Q_UNUSED(openMode);
    
    TBTSockAddr a;

    if(address.isNull())
        {
        socketError = QBluetoothSocket::UnknownSocketError;
        emit q->error(socketError);
        return;
        }
    TInt err = KErrNone;
    a.SetPort(port);
    // Trap TBTDevAddr constructor which may panic
    TRAP(err, a.SetBTAddr(TBTDevAddr(address.toUInt64())));
    if(err == KErrNone)
        err = iSocket->Connect(a);
    if (err == KErrNone) {
        q->setSocketState(QBluetoothSocket::ConnectingState);
    } else {
        socketError = QBluetoothSocket::UnknownSocketError;
        emit q->error(socketError);
    }
}
예제 #2
0
void CBTBasebandSAP::LocalName(TSockAddr& aAddr) const
	{
	LOG_FUNC
	// base class just returns address as a BTSockAddr
	TBTSockAddr btAddr;
	btAddr.SetBTAddr(iLinksMan.LinkManagerProtocol().LocalBTAddress());
	aAddr = btAddr;
	}
예제 #3
0
// Looks up the name of the device with the given address.
// Arguments:
//  - wantedAddr - address of the device to look up. Note that the address 
//    is expected without colons!! e.g. "000D9319C868"
//  - aDeviceName - the object to hold the name once it is found
//  - ignoreCache - if True, performs a remote name request even if the device
//    name is known in the cache from a previous request.
//
// Returns an error code.
static TInt LookupName(TBTDevAddr& wantedAddr, THostName* aDeviceName, 
    bool ignoreCache)
{
    TInt err = KErrNone;
    RSocketServ socketServer;
    RHostResolver hostResolver;
    TRequestStatus status; 
    TNameEntry nameEntry;        
    
    // make a TInquirySockAddr with the address of the device we want to look up
    TBTSockAddr sockAddr;
    sockAddr.SetBTAddr(wantedAddr);
    TInquirySockAddr addr = addr.Cast(sockAddr);
    
    // connect 
    err = socketServer.Connect();
    if (err) 
        return err;    
        
    // load protocol for discovery
	TProtocolDesc protocolDesc;
	err = socketServer.FindProtocol(_L("BTLinkManager"), protocolDesc);
	if (!err) { 
        
        // initialize host resolver
        err = hostResolver.Open(socketServer, protocolDesc.iAddrFamily, protocolDesc.iProtocol);
    	if (!err) {
        	            
        	// Request name lookup.
        	// We don't need to call SetIAC() if we're just doing name lookup.
        	// Don't put KHostResInquiry flag in SetAction(), because that
        	// will start a device inquiry, when we just want to find the one 
        	// name.
        	if (ignoreCache) {
        	    addr.SetAction(KHostResName|KHostResIgnoreCache);
	        } else {
    	        addr.SetAction(KHostResName);
	        }
        	
        	hostResolver.GetByAddress(addr, nameEntry, status);
        	
        	User::WaitForRequest(status);
        	
            if (status == KErrNone) {
                *aDeviceName = nameEntry().iName;
                err = KErrNone;
            } else {
                err = KErrGeneral;
            }
            
            hostResolver.Close();
        }
    }
    
    socketServer.Close();
    
    return err; 
}
예제 #4
0
// ----------------------------------------------------------------------------
// CChatBt::ConnectToServerL()
// Connect to the server.
// ----------------------------------------------------------------------------
//
void CChatBt::ConnectToServerL()
    {
    HBufC* strConnecting = StringLoader
        ::LoadLC ( R_CHAT_STR_CONNECTING );
    iLog.LogL( *strConnecting );
    CleanupStack::PopAndDestroy( strConnecting );

    User::LeaveIfError( iSocket.Open( iSocketServer, KStrRFCOMM ) );

    TBTSockAddr address;
    address.SetBTAddr( iServiceSearcher->BTDevAddr() );
    address.SetPort( iServiceSearcher->Port() );

    iSocket.Connect( address, iStatus );
  
    iActiveSocket = &iSocket;
  
    #ifdef __WINS__
        // Fix to allow emulator client to connect to server
        User::After( 1 );     
    #endif
  
    SetActive();
    }
/** Reads the device selection from the ini file and sets the notifier up with the right addresses
and channel/port details.

@return KErrNone if the operation succeeded.
		Any other standard Symbian error code
 */
TInt CT_BTGPSDeviceListHandler::HandleDeviceSelection()
{
    if(iDeviceListConfig.iDeviceSelection.Length() == 0)
    {
        //Nothing to do, no device specified
        return KErrNone;
    }

    TInt err = KErrNone;
    TInt overallErr = KErrNone;
    TInt endPosition = 0;
    TInt listLength = iDeviceListConfig.iDeviceSelection.Length();

    //Loop through the devices in the ini file, adding them to the notifier
    while(listLength > 0)
    {
        err = KErrNone;

        TPtrC tempDeviceList(iDeviceListConfig.iDeviceSelection.Right(listLength));

        endPosition = tempDeviceList.Find(_L(","));
        if(endPosition == KErrNotFound)
        {
            //No more commas in the list, at the end of the file
            endPosition = tempDeviceList.Length();
        }

        TPtrC currentDevice(tempDeviceList.Mid(0, endPosition));

        TBuf<4> deviceId(currentDevice);
        deviceId.TrimAll();

        //Find this device in the BT device list
        TPtrC btAddress;
        if(!iBTListConfigFile->FindVar(deviceId, _L("Address"), btAddress))
        {
            INFO_PRINTF2(_L("ERROR - Cannot find device with id: %S, not adding to Notifier"), &deviceId);
            overallErr = err = KErrNotFound;
        }

        //If the device address has been found
        if(err == KErrNone)
        {
            TInt64 hwAddrInt(0);
            TLex lex(btAddress);
            TBTSockAddr socketAddress;

            err = lex.Val(hwAddrInt, EHex);
            if(err == KErrNone)
            {
                socketAddress.SetBTAddr(hwAddrInt);
            }

            //Get the port information
            TInt port = 0;
            if(!iBTListConfigFile->FindVar(deviceId, _L("Port"), port))
            {
                port = 1;
            }
            socketAddress.SetPort(port);

            //Get the device type
            TInt deviceType;
            if(!iBTListConfigFile->FindVar(deviceId, _L("Type"), deviceType))
            {
                //Device type not present, just add as a standard Simulation device
                deviceType = 2;
            }

            //Create the device in the neighbourhood
            RBtGpsSim sim;
            TInt err = sim.Connect();

            if (err == KErrNone)
            {
                RBtGpsSimDevice simDevice;
                err = simDevice.Open(sim, socketAddress);
                if (err == KErrNotFound)
                {
                    // Create a device Entry
                    TBtGpsSimDeviceType simType = static_cast<TBtGpsSimDeviceType>(deviceType);
                    err = simDevice.Create(sim, simType, socketAddress);
                    if(err == KErrNone)
                    {
                        simDevice.SetParameter(EBtGpsSimAuthorised, ETrue);
                        simDevice.SetParameter(EBtGpsSimPin, _L8("0000"));
                    }
                }

                //Add the device to the notifier list
                if(err == KErrNone)
                {
                    err = simDevice.AddToSelectionList();
                }

                //Check to see whether the device was successfully added
                if(err != KErrNone)
                {
                    INFO_PRINTF3(_L("ERROR %d - Cannot add device with ID %S, to the Notifier"), err, &deviceId);
                    overallErr = err;
                }

                simDevice.Close();
            }
            sim.Close();
        }

        //Get Ready for the next device
        listLength -= endPosition + 1;
    }

    return overallErr;
}
/** Returns the details for the next BT GPS Device  This is either the next available device
in the list or a randomly generated unavailable device.  The device type returned is the actual
type of device the BT GPS device should be. It may be added to the Configuration API list as a
different device type.

@param aCurrentDeviceNum [IN] Current position in the list
@param aSocketAddress [OUT] Address of the device
@param aDeviceType [OUT] Type of GPS Device (TBtGpsSimDeviceType)

@return KErrNone if the operation succeeded.
		KErrNotFound if the next device should be an available device, but cannot be found in the BT device list
		Any other standard Symbian error code
 */
TInt CT_BTGPSDeviceListHandler::GetNextDeviceDetails(TInt aCurrentDeviceNum, TBTSockAddr& aSocketAddress,
        TInt& aDeviceType)
{
    TInt err = KErrNone;
    TBuf<2> num;
    TInt port = 0;

    num.AppendNum(aCurrentDeviceNum);
    TInt found = iDeviceListConfig.iDevicePositions.Find(num);
    if((found != KErrNotFound) && (iCheckAvailableDevice))
    {
        //Get the id for the next BT device to add to the list
        TPtrC tempdeviceBuffer(iDeviceListConfig.iAvailableDevices.Right(iAvailableDeviceBufferLength));
        TInt endDevicePosition = 0;

        //Find the next comma
        endDevicePosition = tempdeviceBuffer.Find(_L(","));
        if(endDevicePosition == KErrNotFound)
        {
            //No more commas in the list, at the end of the file
            endDevicePosition = tempdeviceBuffer.Length();
        }

        TPtrC deviceBuf(tempdeviceBuffer.Mid(0, endDevicePosition));
        iAvailableDeviceBufferLength -= (endDevicePosition + 1);
        if(iAvailableDeviceBufferLength <= 0)
        {
            iCheckAvailableDevice = EFalse;
        }

        TBuf<4> deviceId(deviceBuf);
        deviceId.TrimAll();

        //Find this device in the BT device list
        TPtrC btAddress;
        if(!iBTListConfigFile->FindVar(deviceId, _L("Address"), btAddress))
        {
            err = KErrNotFound;
        }
        TInt64 hwAddrInt(0);
        TLex lex(btAddress);
        err = lex.Val(hwAddrInt, EHex);
        if(err == KErrNone)
        {
            aSocketAddress.SetBTAddr(hwAddrInt);
        }

        //Read the device Port information
        if(!iBTListConfigFile->FindVar(deviceId, _L("Port"), port))
        {
            port = 0;
        }

        aSocketAddress.SetPort(port);

        TInt deviceType;
        if(!iBTListConfigFile->FindVar(deviceId, _L("Type"), deviceType))
        {
            //No device type, device added as standard BT Device
            deviceType = 2;
        }
        aDeviceType = deviceType;
    }
    else
    {
        //Adding an unavailable device to the list
        aSocketAddress.SetBTAddr(GenerateUniqueBTDevAddr());
        aSocketAddress.SetPort(port);
        aDeviceType = -1;
    }

    return err;
}
예제 #7
0
void CAzqBtGPSReader::RunL()
{

	iCallbackTimer->Cancel();

	switch(iState)
	{
		case ENoState:
		break;

		case EInquiringDevices:
			{
				if( iStatus !=KErrNone)
					{
						iHostResolver.Close();

						if(iStatus == KErrHostResNoMoreResults)
							{

	    							{
	    							iGPSData.Reset();
									_LIT(KGPSStateUpdate,"BT GPS Search finished...");
									iObserver.OnGPSStateUpdate(KGPSStateUpdate,iGPSData );
										}

						    //choose and connect to BT GPS modules
						    if(iBtGPSArray.Count()>0)
						    	{
						    		User::LeaveIfError(iSendingSocket.Open(iSocketServer,RFCOMM));
		    						TBTSockAddr address;
		    						address.SetBTAddr(iBtGPSArray[0]);
		    						// GPS devices usually use port 1 as data channel
		    						// so we don't have to query it
		    						address.SetPort(1);

		    							{
		    							iGPSData.Reset();
		    							iState = EConnecting;
										_LIT(KGPSStateUpdate,"Trying to connect to first device");
										iObserver.OnGPSStateUpdate(KGPSStateUpdate,iGPSData );
											}


		    						iSendingSocket.Connect(address, iStatus);
		    						SetActive();
		    						ResetBtTimer();

						    	}
						    else
						    	{

						    		{
						    		iGPSData.Reset();
						    		iState = ENoState;
									_LIT(KGPSStateUpdate,"No BT GPS. Retry press 9");
									iObserver.OnGPSStateUpdate(KGPSStateUpdate,iGPSData );
									}


						    	}

							}
						else
							{
								{
								iGPSData.Reset();
								iState = ENoState;
								_LIT(KGPSStateUpdate,"Search failed. Retry press 9");
								iObserver.OnGPSStateUpdate(KGPSStateUpdate,iGPSData );
									}



							}
					}
				else
					{

					TInquirySockAddr &addr = TInquirySockAddr::Cast(iNameEntry().iAddr);

					if(addr.MajorClassOfDevice() == KBtGPSMajorClass)
						{
							//add to array...
							iBtGPSArray.AppendL(addr.BTAddr());

								{
								iGPSData.Reset();
							_LIT(KGPSStateUpdate,"Found %d BT GPS, Searching...");
							TBuf<128> buf;
							buf.Format(KGPSStateUpdate, iBtGPSArray.Count());
							iObserver.OnGPSStateUpdate(buf,iGPSData );
								}
						}

					    ///////////get next device
						iState = EInquiringDevices;
						iHostResolver.Next(iNameEntry, iStatus);
						SetActive();
						ResetBtTimer();
						///////////////////////////////////
					}
			}
		break;

		case EConnecting:
			{
				if( iStatus !=KErrNone)
					{
						//remove previous device from array
						if(iBtGPSArray.Count()>0)
							{
							iBtGPSArray.Remove(0);
							}

						//if more gps devices remaining to try
						if(iBtGPSArray.Count()>0)
							{
								//socket alraedy opened...

								TBTSockAddr address;
								address.SetBTAddr(iBtGPSArray[0]);
								// GPS devices usually use port 1 as data channel
								// so we don't have to query it
								address.SetPort(1);

								iState = EConnecting;

									{
									iGPSData.Reset();
									_LIT(KGPSStateUpdate,"Connecting next device");
									iObserver.OnGPSStateUpdate(KGPSStateUpdate,iGPSData );
										}

								iSendingSocket.Connect(address, iStatus);
								SetActive();
								ResetBtTimer();
							}
						else//finished list
							{
								{
								iGPSData.Reset();
								iState = ENoState;

								_LIT(KGPSStateUpdate,"Connect GPS failed. Retry press 9");
								iObserver.OnGPSStateUpdate(KGPSStateUpdate,iGPSData );
									}

								iSendingSocket.Close();
							}
					}
				else
					{
						iState = EReading;
							{
							_LIT(KGPSStateUpdate,"Reading GPS data...");
							iObserver.OnGPSStateUpdate(KGPSStateUpdate,iGPSData );
								}
						iWaitGPSReadyRetry = 0; //only related if iSyncTimeWhenValid is ETrue
						line.Zero();
						iLineHeadReceivedTime = 0;//just to make sure it's fresh
						iSendingSocket.RecvOneOrMore(data, 0, iStatus, iReadDataLength);
						SetActive();
						ResetBtTimer();
					}
			}
		break;

		case EReading:
			{

				if( iStatus !=KErrNone)
					{

						{
						iGPSData.Reset();
						iState = ENoState;

						_LIT(KGPSStateUpdate,"Read GPS failed. Retry press 9");
						iObserver.OnGPSStateUpdate(KGPSStateUpdate,iGPSData );
							}


						iSendingSocket.Close();
						return;
					}

				iState = EReadComplete;

				iGPSData.Reset();//prepare for new data

				int rpos = 0;

				while ((rpos = data.Locate('\r')) != KErrNotFound)
				{
					TPtrC8 leftr(0,0);
					leftr.Set(data.Left(rpos));

					TInt leftrlen = leftr.Length();

					if(leftrlen + line.Length() < line.MaxLength())
						{
							if(line.Length()==0)
								iLineHeadReceivedTime.HomeTime();
							line.Append(leftr);
						}
					else
					{
						line.Zero();

						if(leftrlen + line.Length() < line.MaxLength())
							{
								//if(line.Length()==0) sure it is, see above lines
									iLineHeadReceivedTime.HomeTime();
								line.Append(leftr);
							}
					}

					if(rpos+1<data.Length())
						{
							data.Copy(data.Mid(rpos+1));

							if(data[0] == '\n')
								data.Delete(0,1);
						}
					else
						{
							data.Zero();
						}



					TGPSData gpsdata;
					TTimeIntervalMicroSeconds proctime;

					if(iLineHeadReceivedTime == TTime(0))//just in case...
						{
						iLineHeadReceivedTime.HomeTime();
						CAknWarningNote* informationNote = new (ELeave) CAknWarningNote(ETrue);
						//informationNote->SetTimeout(CAknNoteDialog::EShortTimeout);
						_LIT(KConfirmText,"Warning: No read-offset time correction");
						informationNote->ExecuteLD(KConfirmText);
						}

					if(gpsdata.ParseGPSInput(line,iLineHeadReceivedTime,proctime))
					{


						if((gpsdata.POS_STAT.Length() == 0) || (gpsdata.POS_STAT.Length()>0 && gpsdata.POS_STAT[0]!='A'))//if data NOT valid
							{
							///////////////BEGIN parsed but NOT valid data

							if(iSyncTimeWhenValid)//if the NetMonview is in the "Awaiting Fresh GPS Params State for the first time of session - needs time sync"
								{
									if(iWaitGPSReadyRetry>=KMaxWaitGPSReadyRetries)
									{
										//max retries finished, notify as in EReadcomplete state as set by above
										_LIT(KGPSStateUpdate,"GPS Connected but Not Ready");
										iObserver.OnGPSStateUpdate(KGPSStateUpdate,iGPSData );
										iSyncTimeWhenValid = EFalse;
									}
									else
									{
									//don't notify as in EReadcomplete state yet...
									iState = EReading;
									iWaitGPSReadyRetry++;
									TBuf<64> buf;
									_LIT(KGPSStateUpdateFormat,"GPS NotReady: TimeSync retry %d/%d");

									buf.Format(KGPSStateUpdateFormat,iWaitGPSReadyRetry,KMaxWaitGPSReadyRetries);

									iObserver.OnGPSStateUpdate(buf,iGPSData );
									}
								}
							else
								{
									_LIT(KGPSStateUpdate,"GPS Connected but Not Ready");
									iObserver.OnGPSStateUpdate(KGPSStateUpdate,iGPSData );
								}




									//latdeg = londeg = latmin = lonmin = latsec = lonsec = 0;
									line.Zero();


									if(data.Length()>0)
										{
											if(line.Length() + data.Length() < line.MaxLength())
												{
												iLineHeadReceivedTime.HomeTime();
												line.Append(data);
												}
											else
												{
													line.Zero();
													if(line.Length() + data.Length() < line.MaxLength())
														{
														//line is zero len from line.Zero() above
														iLineHeadReceivedTime.HomeTime();
														line.Append(data);
														}
												}
										}

									data.Zero();

									iState = EReading;
									iSendingSocket.RecvOneOrMore(data, 0, iStatus, iReadDataLength);
									SetActive();
									ResetBtTimer();
									return;
									///////////////END not valid
								}

						////////// boyond here is the VALID case


						////////////set device's UTC time
						if(iSyncTimeWhenValid)
							{

										TTime devTime;
										devTime.HomeTime();
										TDateTime dt = devTime.DateTime();


										if(gpsdata.POS_UTC.Length() < 6 || gpsdata.DATE.Length() < 6)
										{
											//line not ready/full... do nothing
										}
										else
										{

											//All NMEA chars are ASCII

											dt.SetHour((gpsdata.POS_UTC[0]-48)*10+(gpsdata.POS_UTC[1]-48));
											dt.SetMinute((gpsdata.POS_UTC[2]-48)*10+(gpsdata.POS_UTC[3]-48));
											dt.SetSecond((gpsdata.POS_UTC[4]-48)*10+(gpsdata.POS_UTC[5]-48));


											dt.SetDay((gpsdata.DATE[0]-48)*10+(gpsdata.DATE[1]-48) -1);

											dt.SetMonth(TMonth((gpsdata.DATE[2]-48)*10+(gpsdata.DATE[3]-48) -1));

											dt.SetYear((gpsdata.DATE[4]-48)*10+(gpsdata.DATE[5]-48)+KY2K);



											if(gpsdata.POS_UTC.Length()>9 && gpsdata.POS_UTC.Find(_L8("."))>0)
											{
												dt.SetMicroSecond((gpsdata.POS_UTC[7]-48)*KONEHUNDREDTHOUSAND+(gpsdata.POS_UTC[8]-48)*KTENTHOUSAND+(gpsdata.POS_UTC[9]-48)*1000);
											}

											devTime = dt;
											devTime += proctime;
#ifdef EKA2
											User::SetUTCTime(devTime);
#else
											//TODO: detect timezone and add accordingly
											TTime hometime(devTime);
											hometime += TTimeIntervalHours(7);
											User::SetHomeTime(hometime);
#endif


											iSyncTimeWhenValid = EFalse;

											CAknConfirmationNote* informationNote = new (ELeave) CAknConfirmationNote(EFalse);
											//informationNote->SetTimeout(CAknNoteDialog::EShortTimeout);
											_LIT(KConfirmText,"GPS TimeSync Successful");
											informationNote->ExecuteLD(KConfirmText);
											//TODO: report to scheduler that device time has changed? OR let scheduler detect device time change?


										}

							}
						/////////////////////////

							//SET LAT LON values...
							TBuf<1> ref;


							if(gpsdata.LAT.Length() < iGPSData.iLat.MaxLength()   && gpsdata.LAT_REF.Length()==1)
								{
							iGPSData.iLat.Copy(gpsdata.LAT);
							ref.Zero();
							ref.Copy(gpsdata.LAT_REF);
							iGPSData.iLat+=ref;
								}

							if(gpsdata.LON.Length() < iGPSData.iLon.MaxLength() && gpsdata.LON_REF.Length()==1)
								{
							iGPSData.iLon.Copy(gpsdata.LON);
							ref.Zero();
							ref.Copy(gpsdata.LON_REF);
							iGPSData.iLon+=ref;
								}






						_LIT(KGPSStateUpdate,"Connected to GPS");
						iObserver.OnGPSStateUpdate(KGPSStateUpdate,iGPSData );


					}//END if gps parsed


					line.Zero();
				}


				if(data.Length()>0)
					{
						if(line.Length() + data.Length() < line.MaxLength())
							{
								if(line.Length()==0) //if not appending data to previous line
									iLineHeadReceivedTime.HomeTime();
								line.Append(data);
							}
						else
							{
								line.Zero();
								if(line.Length() + data.Length() < line.MaxLength())
									{
										//if(line.Length()==0) sure it is, see above lines
											iLineHeadReceivedTime.HomeTime();
										line.Append(data);
									}
							}
					}

				data.Zero();

				iState = EReading;
				iSendingSocket.RecvOneOrMore(data, 0, iStatus, iReadDataLength);
				SetActive();
				ResetBtTimer();
			}
			break;
	}


}