Пример #1
0
void ListAllDynamixels(int usb2ax_index) {
  int baud_num, dxl_id;
  int model_num, firmware_version;
  for (baud_num = 3; baud_num >= 0; baud_num--) {
    if(InitDXL(usb2ax_index, baud_num) == 0 ) {
      printf("Failed to open device: %d, baud num: %d\n", usb2ax_index, baud_num);
      TerminateDXL();
      return;
    } else {
      printf("Searching on device: %d, baud num: %d\n", usb2ax_index, baud_num);
    }

    for (dxl_id = 0; dxl_id < 200; dxl_id++) {
      if (SendPing(dxl_id, &model_num, &firmware_version)) {
        printf("Device found| Baud rate: %d, ID: %d, Model number: %d, Firmware version: %d\n", baud_num, dxl_id, model_num, firmware_version);
      }
    }
    // ID 200 is one of the controllers or something.
    // ID 253 is USB2AX
    // ID 254 is broadcast
    for (dxl_id = 201; dxl_id < 253; dxl_id++) {
      if (SendPing(dxl_id, &model_num, &firmware_version)) {
        printf("Device found| Baud rate: %d, ID: %d, Model number: %d, Firmware version: %d\n", baud_num, dxl_id, model_num, firmware_version);
      }
    }
  }
}
Пример #2
0
void ProcessMerkleBlock(CNode& pfrom, CDataStream& vRecv,
        ThinBlockWorker& worker,
        const TxFinder& txfinder) {

    CMerkleBlock merkleBlock;
    vRecv >> merkleBlock;

    uint256 hash = merkleBlock.header.GetHash();
    pfrom.AddInventoryKnown(CInv(MSG_BLOCK, hash));


    if (!worker.isAvailable() && worker.blockHash() != hash)
        LogPrint("thin", "expected peer %d to be working on %s, "
                "but received block %s, switching peer to new block\n",
                pfrom.id, worker.blockStr(), hash.ToString());

    if (HaveBlockData(hash)) {
        LogPrint("thin", "already had block %s, "
                "ignoring merkleblock (peer %d)\n",
                hash.ToString(), pfrom.id);
        worker.setAvailable();
        return;
    }

    worker.setToWork(hash);

    if (worker.isStubBuilt()) {
        LogPrint("thin", "already built thin block stub "
                "%s (peer %d)\n", hash.ToString(), pfrom.id);
        SendPing(pfrom);
        return;
    }

    LogPrint("thin", "building thin block %s (peer %d) ",
            hash.ToString(), pfrom.id);

    // Now attempt to reconstruct the block from the state of our memory pool.
    // The peer should have already sent us the transactions we need before
    // sending us this message. If it didn't, we just ignore the message
    // entirely for now.
    try {
        worker.buildStub(merkleBlock, txfinder);
        SendPing(pfrom);
    }
    catch (const thinblock_error& e) {
        pfrom.PushMessage("reject", std::string("merkleblock"),
                REJECT_MALFORMED, std::string("bad merkle tree"), hash);
        Misbehaving(pfrom.GetId(), 10);  // FIXME: Is this DoS policy reasonable? Immediate disconnect is better?
        LogPrintf("%s peer=%d", e.what(), pfrom.GetId());
        worker.setAvailable();
        return;
    }
}
Пример #3
0
IrcSocket::IrcSocket (QObject *parent)
  :QTcpSocket (parent),
   needPing (true),
   numBytesIn (0),
   numBytesOut (0)
{
  sockCount++;
  setObjectName (QString("IrcSocket-%1").arg(sockCount));
  hostName = objectName ();
  pingTimer = new QTimer (this);
  scriptTimer = new QTimer (this);
  connect (pingTimer, SIGNAL (timeout()),
           this, SLOT (SendPing()));
  connect (scriptTimer, SIGNAL (timeout()), 
           this, SLOT (SendScriptHead()));
  connect (this, SIGNAL (error (QAbstractSocket::SocketError)),
           this, SLOT (SockError (QAbstractSocket::SocketError)));
  connect (this, SIGNAL (connected()),
           this, SLOT (DidConnect ()));
  connect (this, SIGNAL (disconnected ()),
           this, SLOT (DidDisconnect ()));
  connect (this, SIGNAL (readyRead ()),
           this, SLOT (Receive ()));
  connect (this, SIGNAL (bytesWritten (qint64)),
           this, SLOT (CountBytesOut (qint64)));
qDebug () << " IrcSocket " << objectName();
}
Пример #4
0
// Triggered by world every 500ms
void WardenMgr::Update(uint32 diff)
{
    if (!m_Enabled)
        return;

    m_PingTimer.Update(diff);

    if (m_PingTimer.Passed())
    {
        if (m_PingOut && m_Disconnected)
        {
            m_Disconnected = !InitializeCommunication();
            m_PingTimer.Reset();
        }
        else if (m_PingOut && !m_Disconnected)
        {
            SetDisconnected();
        }
        else
        {
            SendPing();
            m_PingTimer.Reset();
        }
    }

    ACE_Time_Value t(0.001);
    int res = ACE_Reactor::instance()->run_reactor_event_loop(t);
}
void
TestEndpointBridgeSubParent::Main()
{
  if (!SendPing()) {
    fail("sending Ping");
  }
}
Пример #6
0
FSessionManager::FSessionManager( const IMessageBusRef& InMessageBus )
	: MessageBusPtr(InMessageBus)
{
	// fill in the owner array
	FString Filter;

	if (FParse::Value(FCommandLine::Get(), TEXT("SessionFilter="), Filter))
	{
		// Allow support for -SessionFilter=Filter1+Filter2+Filter3
		int32 PlusIdx = Filter.Find(TEXT("+"));

		while (PlusIdx != INDEX_NONE)
		{
			FString Owner = Filter.Left(PlusIdx);
			FilteredOwners.Add(Owner);
			Filter = Filter.Right(Filter.Len() - (PlusIdx + 1));
			PlusIdx = Filter.Find(TEXT("+"));
		}

		FilteredOwners.Add(Filter);
	}

	// connect to message bus
	MessageEndpoint = FMessageEndpoint::Builder("FSessionManager", InMessageBus)
		.Handling<FEngineServicePong>(this, &FSessionManager::HandleEnginePongMessage)
		.Handling<FSessionServicePong>(this, &FSessionManager::HandleSessionPongMessage);

	// initialize ticker
	TickDelegateHandle = FTicker::GetCoreTicker().AddTicker(FTickerDelegate::CreateRaw(this, &FSessionManager::HandleTicker), 1.f);

	SendPing();
}
Пример #7
0
void
TestAsyncReturnsParent::Main()
{
  SendNoReturn()->Then(MessageLoop::current()->SerialEventTarget(), __func__,
                       [](bool unused) {
                         fail("resolve handler should not be called");
                       },
                       [](PromiseRejectReason aReason) {
                         // MozPromise asserts in debug build if the
                         // handler is not called
                         if (aReason != PromiseRejectReason::ChannelClosed) {
                           fail("reject with wrong reason");
                         }
                         passed("reject handler called on channel close");
                       });
  SendPing()->Then(MessageLoop::current()->SerialEventTarget(), __func__,
                   [this](bool one) {
                     if (one) {
                       passed("take one argument");
                     } else {
                       fail("get one argument but has wrong value");
                     }
                     Close();
                   },
                   [](PromiseRejectReason aReason) {
                     fail("sending Ping");
                   });
}
void
TestLatencyParent::PingPongTrial()
{
    mStart = TimeStamp::Now();
    if (!SendPing())
        fail("sending Ping()");
}
Пример #9
0
void RSSIModule::TimerEventHandler(u16 passedTime, u32 appTimer)
{
	if(configuration.pingInterval != 0 && node->appTimerMs - configuration.lastPingTimer > configuration.pingInterval)
	{
		configuration.lastPingTimer = node->appTimerMs;
		SendPing(DEST_BOARD_ID);
	}
}
static void AppDoWork(AJ_BusAttachment* bus, uint32_t sessionId)
{
    AJ_Printf("AppDoWork");
    /*
     * This function is called if there are no messages to unmarshal
     */
    g_iterCount = g_iterCount + 1;
    SendPing(bus, sessionId, g_iterCount);
}
Пример #11
0
int KGameserverEyes::DoPing(DWORD dwFrames)
{
	if ( dwFrames > m_dwNextPingFrame )
	{
		SendPing();
		m_dwNextPingFrame = dwFrames + m_dwPingInterval;
	}
	return 1;
}
int main( void )
{
  // Stop watchdog timer to prevent time out reset
  WDTCTL = WDTPW + WDTHOLD;
  __delay_cycles(1600000);
  IPstackInit();
  unsigned char target[] = {192,168,0,70};
  SendPing(target);
  //IPstackHTMLPost(url, data, reply );

  while(1) IPstackIdle();
}
Пример #13
0
bool FSessionManager::HandleTicker( float DeltaTime )
{
	FDateTime Now = FDateTime::UtcNow();

	// @todo gmp: don't expire sessions for now
//	FindExpiredSessions(Now);

	if (Now >= LastPingTime + FTimespan::FromSeconds(2.5))
	{
		SendPing();
	}

	return true;
}
Пример #14
0
static void AppDoWork(AJ_BusAttachment* bus, uint32_t sessionId, const char* serviceName)
{
    AJ_AlwaysPrintf(("AppDoWork\n"));
    /*
     * This function is called if there are no messages to unmarshal
     * Alternate between alljoyn_test ping and Bus ping
     */
    g_iterCount = g_iterCount + 1;
    if (g_iterCount & 1) {
        SendPing(bus, sessionId, serviceName, g_iterCount);
    } else {
        AJ_BusPing(bus, serviceName, PING_TIMEOUT);
    }
}
Пример #15
0
bool PingModule::TerminalCommandHandler(string commandName, vector<string> commandArgs)
{
	if(commandArgs.size() >= 2 && commandArgs[1] == moduleName)
	{
		//React on commands, return true if handled, false otherwise
		if(commandName == "pingmod"){
			nodeID targetNodeId = atoi(commandArgs[0].c_str());

			return(SendPing(targetNodeId));
		}
	}

	//Must be called to allow the module to get and set the config
	return Module::TerminalCommandHandler(commandName, commandArgs);
}
Пример #16
0
void CGnuLocal::LanModeOn()
{
	m_pCore->Disconnect(NETWORK_GNUTELLA);
	m_pCore->Disconnect(NETWORK_G2);

	m_pCore->Connect(NETWORK_GNUTELLA);

	/*m_pComm->m_pCache->m_GnuPerm.clear();
	m_pComm->m_pCache->m_GnuReal.clear();
	m_pComm->m_pCache->m_AltWebCaches.clear();
	m_pPrefs->m_BlockList.clear();*/

	m_pPrefs->m_LanMode = true;

	m_pComm->m_NetworkName	= "GNUCLEAR";

	SendPing();
}
Пример #17
0
// check ping times and handle pings as required
void UPAConsumer::ProcessPings(RsslChannel* chnl)
{
   time_t currentTime = 0;

   // get current time 
   time(&currentTime);

   // time to send a ping
   if (currentTime >= nextSendPingTime_)
   {
      /* send ping to server */
      if (chnl && SendPing(chnl) != RSSL_RET_SUCCESS)
      {
		RecoverConnection();
         return;
      }

      // schedule next
      nextSendPingTime_ = currentTime + (time_t)pingTimeoutClient_;
   }

   // time to check if we received anything
   if (currentTime >= nextReceivePingTime_)
   {
      //  check if client received message from server since last time 
      if (receivedServerMsg_)
      {
         // reset flag/
         receivedServerMsg_ = RSSL_FALSE;

         // schedule next time

         nextReceivePingTime_ = currentTime + (time_t)pingTimeoutServer_;
      }
      else // lost contact
      {
         t42log_error("Lost contact with server...\n");
         RecoverConnection();
         return;
      }
   }
}
Пример #18
0
void NetClient::SendUpdates( void )
{
	// Reduce update rate temporarily in high-ping situations.
	double temp_netrate = NetRate;
	temp_netrate /= ((int) LatestPing() / 100) + 1;
	
	// Send an update if it's time to do so.
	if( Connected && Raptor::Game->PlayerID && (NetClock.ElapsedSeconds() >= (1.0 / temp_netrate)) )
	{
		NetClock.Reset();
		
		if( PingClock.ElapsedSeconds() >= (1.0 / PingRate) )
		{
			PingClock.Reset();
			SendPing();
		}
		
		SendUpdate();
	}
}
Пример #19
0
void
TestSanityParent::Main()
{
    if (!SendPing(0, 0.5f, 0))
        fail("sending Ping");
}
Пример #20
0
void cXVDRData::Action()
{
  uint32_t lastPing = 0;
  cResponsePacket* vresp;

  SetPriority(19);

  while (Running())
  {
    // try to reconnect
    if(ConnectionLost() && !TryReconnect())
    {
      SleepMs(1000);
      continue;
   }

    // read message
    vresp = cXVDRSession::ReadMessage();

    // check if the connection is still up
    if (vresp == NULL)
    {
      if(time(NULL) - lastPing > 5)
      {
        lastPing = time(NULL);

        if(!SendPing())
          SignalConnectionLost();
      }
      continue;
    }

    // CHANNEL_REQUEST_RESPONSE

    if (vresp->getChannelID() == XVDR_CHANNEL_REQUEST_RESPONSE)
    {

      CMD_LOCK;
      SMessages::iterator it = m_queue.find(vresp->getRequestID());
      if (it != m_queue.end())
      {
        it->second.pkt = vresp;
        it->second.event->Signal();
      }
      else
      {
        delete vresp;
      }
    }

    // CHANNEL_STATUS

    else if (vresp->getChannelID() == XVDR_CHANNEL_STATUS)
    {
      if (vresp->getRequestID() == XVDR_STATUS_MESSAGE)
      {
        uint32_t type = vresp->extract_U32();
        char* msgstr  = vresp->extract_String();
        std::string text = msgstr;

        if (g_bCharsetConv)
          XBMC->UnknownToUTF8(text);

        if (type == 2)
          XBMC->QueueNotification(QUEUE_ERROR, text.c_str());
        if (type == 1)
          XBMC->QueueNotification(QUEUE_WARNING, text.c_str());
        else
          XBMC->QueueNotification(QUEUE_INFO, text.c_str());

        delete[] msgstr;
      }
      else if (vresp->getRequestID() == XVDR_STATUS_RECORDING)
      {
                          vresp->extract_U32(); // device currently unused
        uint32_t on     = vresp->extract_U32();
        char* str1      = vresp->extract_String();
        char* str2      = vresp->extract_String();

        PVR->Recording(str1, str2, on);
        PVR->TriggerTimerUpdate();

        delete[] str1;
        delete[] str2;
      }
      else if (vresp->getRequestID() == XVDR_STATUS_TIMERCHANGE)
      {
        XBMC->Log(LOG_DEBUG, "Server requested timer update");
        PVR->TriggerTimerUpdate();
      }
      else if (vresp->getRequestID() == XVDR_STATUS_CHANNELCHANGE)
      {
        XBMC->Log(LOG_DEBUG, "Server requested channel update");
        PVR->TriggerChannelUpdate();
      }
      else if (vresp->getRequestID() == XVDR_STATUS_RECORDINGSCHANGE)
      {
        XBMC->Log(LOG_DEBUG, "Server requested recordings update");
        PVR->TriggerRecordingUpdate();
      }

      delete vresp;
    }

    // UNKOWN CHANNELID

    else if (!OnResponsePacket(vresp))
    {
      XBMC->Log(LOG_ERROR, "%s - Rxd a response packet on channel %lu !!", __FUNCTION__, vresp->getChannelID());
      delete vresp;
    }
  }
}
Пример #21
0
int AJ_Main(void)
{
    int done = FALSE;
    AJ_Status status = AJ_OK;
    AJ_BusAttachment bus;
    uint8_t connected = FALSE;
    uint32_t sessionId = 0;
    AJ_Status authStatus = AJ_ERR_NULL;

    /*
     * One time initialization before calling any other AllJoyn APIs
     */
    AJ_Initialize();

    AJ_PrintXML(ProxyObjects);
    AJ_RegisterObjects(NULL, ProxyObjects);

    while (!done) {
        AJ_Message msg;

        if (!connected) {
            status = AJ_StartClientByName(&bus, NULL, CONNECT_TIMEOUT, FALSE, ServiceName, ServicePort, &sessionId, NULL, fullServiceName);
            if (status == AJ_OK) {
                AJ_InfoPrintf(("StartClient returned %d, sessionId=%u\n", status, sessionId));
                connected = TRUE;
                if (authenticate) {
                    AJ_BusSetPasswordCallback(&bus, PasswordCallback);
                    authStatus = AJ_BusAuthenticatePeer(&bus, fullServiceName, AuthCallback, &authStatus);
                } else {
                    authStatus = AJ_OK;
                }
            } else {
                AJ_InfoPrintf(("StartClient returned %d\n", status));
                break;
            }
        }

        if (authStatus != AJ_ERR_NULL) {
            if (authStatus != AJ_OK) {
                AJ_Disconnect(&bus);
                break;
            }
            authStatus = AJ_ERR_NULL;
            SendPing(&bus, sessionId);
        }

        status = AJ_UnmarshalMsg(&bus, &msg, UNMARSHAL_TIMEOUT);

        if (AJ_ERR_TIMEOUT == status) {
            AppDoWork();
            continue;
        }

        if (AJ_OK == status) {
            switch (msg.msgId) {
            case AJ_REPLY_ID(PRX_PING):
                {
                    AJ_Arg arg;

                    if (AJ_OK == AJ_UnmarshalArg(&msg, &arg)) {
                        AJ_AlwaysPrintf(("%s.Ping (path=%s) returned \"%s\".\n", InterfaceName,
                                         ServicePath, arg.val.v_string));

                        if (strcmp(arg.val.v_string, pingString) == 0) {
                            AJ_InfoPrintf(("Ping was successful.\n"));
                        } else {
                            AJ_InfoPrintf(("Ping returned different string.\n"));
                        }
                    } else {
                        AJ_ErrPrintf(("Bad ping response.\n"));
                    }

                    done = TRUE;
                }
                break;

            case AJ_SIGNAL_SESSION_LOST_WITH_REASON:
                /*
                 * Force a disconnect
                 */
                {
                    uint32_t id, reason;
                    AJ_UnmarshalArgs(&msg, "uu", &id, &reason);
                    AJ_AlwaysPrintf(("Session lost. ID = %u, reason = %u", id, reason));
                }
                status = AJ_ERR_SESSION_LOST;
                break;

            default:
                /*
                 * Pass to the built-in handlers
                 */
                status = AJ_BusHandleBusMessage(&msg);
                break;
            }
        }

        /*
         * Messages must be closed to free resources
         */
        AJ_CloseMsg(&msg);

        if (status == AJ_ERR_READ) {
            AJ_AlwaysPrintf(("AllJoyn disconnect.\n"));
            AJ_Disconnect(&bus);
            exit(0);
        }
    }

    AJ_AlwaysPrintf(("SecureClient EXIT %d.\n", status));

    return status;
}
Пример #22
0
void CHarmonyHub::Do_Work()
{
	_log.Log(LOG_STATUS,"Harmony Hub: Worker thread started..."); 
	//start with getting the activities

	int scounter = 0;
	int mcounter = 0;
	bool bFirstTime = true;

	while (!m_stoprequested)
	{
		sleep_milliseconds(500);

		if (m_stoprequested)
			break;

		mcounter++;
		if (mcounter<2)
			continue;
		mcounter = 0;

		scounter++;

		if (scounter % 12 == 0)
		{
			m_LastHeartbeat=mytime(NULL);
		}

		if (m_bDoLogin)
		{
			if ((scounter%HARMONY_RETRY_LOGIN_SECONDS == 0) || (bFirstTime))
			{
				bFirstTime = false;
				if(Login() && SetupCommandSocket())
				{
					m_bDoLogin=false;
					if (!UpdateCurrentActivity())
					{
						Logout();
						m_bDoLogin = true;
					}
					else
					{
						if (!UpdateActivities())
						{
							Logout();
							m_bDoLogin = true;
						}
					}
				}
			}
			continue;
		}

		if (scounter % HARMONY_PING_INTERVAL_SECONDS == 0)
		{
			//Ping the server
			if (!SendPing())
			{
				_log.Log(LOG_STATUS, "Harmony Hub: Error pinging server.. Resetting connection.");
				Logout();
			}
			continue;
		}
		bool bIsDataReadable = true;
		m_commandcsocket->canRead(&bIsDataReadable, 0.5f);
		if (bIsDataReadable)
		{
			boost::lock_guard<boost::mutex> lock(m_mutex);
			std::string strData;
			while (bIsDataReadable)
			{
				if (memset(m_databuffer, 0, BUFFER_SIZE) > 0)
				{
					m_commandcsocket->read(m_databuffer, BUFFER_SIZE, false);
					std::string szNewData = std::string(m_databuffer);
					if (!szNewData.empty())
					{
						strData.append(m_databuffer);
						m_commandcsocket->canRead(&bIsDataReadable, 0.4f);
					}
					else
						bIsDataReadable = false;
				}
				else
					bIsDataReadable = false;
			}
			if (!strData.empty())
				CheckIfChanging(strData);
		}
	}
	_log.Log(LOG_STATUS,"Harmony Hub: Worker stopped...");
}
Пример #23
0
void F2M_MinerConnection::Update()
{
    fd_set readSet, writeSet, exceptSet;
    FD_ZERO(&readSet);
    FD_ZERO(&writeSet);
    FD_ZERO(&exceptSet);

    FD_SET(mSocket, &readSet);
    FD_SET(mSocket, &writeSet);
    FD_SET(mSocket, &exceptSet);

    timeval waitTime;
    waitTime.tv_sec = 2;
    waitTime.tv_usec = 0;

    int result = select(FD_SETSIZE, &readSet, &writeSet, &exceptSet, &waitTime);
    if( result > 0 )
    {        
        mCanRead = (FD_ISSET(mSocket, &readSet) != 0);
        mCanWrite = (FD_ISSET(mSocket, &writeSet) != 0);

        if( mConnectionState == F2M_MinerConnection::Connecting )
        {
            if( FD_ISSET(mSocket, &writeSet) )
            {
                // Connection succeeded                
                mConnectionState = F2M_MinerConnection::Connected;
                SendIdentityPacket();
            }
            else if( FD_ISSET(mSocket, &exceptSet) )
            {
                // Connection failed
                mConnectionState = F2M_MinerConnection::Disconnected;
            }
        }
    }
    
    // Read data    
    if( mCanRead && mConnectionState == F2M_MinerConnection::Connected )
    {
        char dataBuffer[1024 * 8];
        int bytesRead = recv(mSocket, dataBuffer, sizeof(dataBuffer), 0);
        mAliveTime = time(0);
        if( bytesRead > 0 )
        {
            char* dataPtr = dataBuffer;
            while( bytesRead > 0 )
            {
                int consumed = 0;
                switch( dataPtr[0] )
                {
                    case 3:     // Work Command
                        ProcessWorkCommand(dataPtr);
                        consumed = 173;
                        break;
                    case 4:     // Stop Command
                        mStopWork = true;
                        consumed = 1;
                        break;
                    case 5:     // Ping
                        SendPing();
                        consumed = 1;
                        break;
                }
                bytesRead -= consumed;
                dataPtr += consumed;
            }
        }
        else if( bytesRead == 0 )
        {
            // Connection closed
            Disconnect();
        }
        else
        {
            SocketError err = F2M_Socket_GetLastError();
            switch( err )
            {
                case SE_ConnectionAborted:
                case SE_ConnectionReset:
                    Disconnect();
                    break;
                default:
                    break;
            }
        }
    }

    if( mConnectionState == F2M_MinerConnection::Connected )
    {
        time_t now = time(0);
        unsigned int timeSinceSeen = now - mAliveTime;
        if( timeSinceSeen > 5 )
        {
            SendPing();
            mAliveTime = now;
        }
    }
}
Пример #24
0
void
TestBridgeSubParent::Main()
{
    if (!SendPing())
        fail("sending Ping");
}
int AJ_Main(void)
{
    AJ_Status status = AJ_OK;
    AJ_BusAttachment bus;
    uint8_t connected = FALSE;
    uint32_t sessionId = 0;
    AJ_Status authStatus = AJ_ERR_NULL;

    /*
     * One time initialization before calling any other AllJoyn APIs
     */
    AJ_Initialize();

    AJ_PrintXML(ProxyObjects);
    AJ_RegisterObjects(NULL, ProxyObjects);

    while (TRUE) {
        AJ_Message msg;

        if (!connected) {
            status = AJ_StartClient(&bus, NULL, CONNECT_TIMEOUT, FALSE, ServiceName, ServicePort, &sessionId, NULL);
            if (status == AJ_OK) {
                AJ_Printf("StartClient returned %d, sessionId=%u\n", status, sessionId);
                AJ_Printf("Connected to Daemon:%s\n", AJ_GetUniqueName(&bus));
                connected = TRUE;
#ifdef SECURE_INTERFACE
                AJ_BusSetPasswordCallback(&bus, PasswordCallback);
                status = AJ_BusAuthenticatePeer(&bus, ServiceName, AuthCallback, &authStatus);
                if (status != AJ_OK) {
                    AJ_Printf("AJ_BusAuthenticatePeer returned %d\n", status);
                }
#else
                authStatus = AJ_OK;
#endif
            } else {
                AJ_Printf("StartClient returned %d\n", status);
                break;
            }
        }

        if (authStatus != AJ_ERR_NULL) {
            if (authStatus != AJ_OK) {
                AJ_Disconnect(&bus);
                break;
            }
            authStatus = AJ_ERR_NULL;
            AJ_BusSetLinkTimeout(&bus, sessionId, 10 * 1000);
        }

        status = AJ_UnmarshalMsg(&bus, &msg, UNMARSHAL_TIMEOUT);
        if (status != AJ_OK) {
            if (status == AJ_ERR_TIMEOUT) {
                AppDoWork(&bus, sessionId);
                continue;
            }
        } else {
            switch (msg.msgId) {

            case AJ_REPLY_ID(AJ_METHOD_SET_LINK_TIMEOUT):
                {
                    uint32_t disposition;
                    uint32_t timeout;
                    status = AJ_UnmarshalArgs(&msg, "uu", &disposition, &timeout);
                    if (disposition == AJ_SETLINKTIMEOUT_SUCCESS) {
                        AJ_Printf("Link timeout set to %d\n", timeout);
                    } else {
                        AJ_Printf("SetLinkTimeout failed %d\n", disposition);
                    }
                    SendPing(&bus, sessionId, 1);
                }
                break;

            case AJ_REPLY_ID(PRX_MY_PING):
                {
                    AJ_Arg arg;
                    AJ_UnmarshalArg(&msg, &arg);
                    status = SendGetProp(&bus, sessionId);
                }
                break;

            case AJ_REPLY_ID(PRX_GET_PROP):
                {
                    const char* sig;
                    status = AJ_UnmarshalVariant(&msg, &sig);
                    if (status == AJ_OK) {
                        status = AJ_UnmarshalArgs(&msg, sig, &g_iterCount);
                        AJ_Printf("Get prop reply %d\n", g_iterCount);

                        if (status == AJ_OK) {
                            g_iterCount = g_iterCount + 1;
                            status = SendSetProp(&bus, sessionId, g_iterCount);
                        }
                    }
                }
                break;

            case AJ_REPLY_ID(PRX_SET_PROP):
                AJ_Printf("Set prop reply\n");
                break;

            case AJ_SIGNAL_SESSION_LOST_WITH_REASON:
                /*
                 * Force a disconnect
                 */
                {
                    uint32_t id, reason;
                    AJ_UnmarshalArgs(&msg, "uu", &id, &reason);
                    AJ_Printf("Session lost. ID = %u, reason = %u", id, reason);
                }
                status = AJ_ERR_SESSION_LOST;
                break;

            default:
                /*
                 * Pass to the built-in handlers
                 */
                status = AJ_BusHandleBusMessage(&msg);
                break;
            }
        }
        /*
         * Messages must be closed to free resources
         */
        AJ_CloseMsg(&msg);

        if ((status == AJ_ERR_SESSION_LOST) || (status == AJ_ERR_READ) || (status == AJ_ERR_LINK_DEAD)) {
            AJ_Printf("AllJoyn disconnect\n");
            AJ_Printf("Disconnected from Daemon:%s\n", AJ_GetUniqueName(&bus));
            AJ_Disconnect(&bus);
            return status;
        }
    }
    AJ_Printf("clientlite EXIT %d\n", status);

    return status;
}
Пример #26
0
int AJ_Main()
#endif
{
    AJ_Status status = AJ_OK;
    AJ_BusAttachment bus;
    uint8_t connected = FALSE;
    uint32_t sessionId = 0;
    AJ_Status authStatus = AJ_ERR_NULL;
#ifdef SECURE_INTERFACE
    uint32_t suites[AJ_AUTH_SUITES_NUM];
    size_t numsuites = 0;
    uint8_t clearkeys = FALSE;
#endif

#ifdef MAIN_ALLOWS_ARGS
#if defined(SECURE_INTERFACE) || defined(SECURE_OBJECT)
    ac--;
    av++;
    /*
     * Enable authentication mechanism by command line
     */
    if (ac) {
        if (0 == strncmp(*av, "-ek", 3)) {
            clearkeys = TRUE;
            ac--;
            av++;
        } else if (0 == strncmp(*av, "-e", 2)) {
            ac--;
            av++;
        }
        if (!ac) {
            AJ_AlwaysPrintf(("-e(k) requires an auth mechanism.\n"));
            return 1;
        }
        while (ac) {
            if (0 == strncmp(*av, "ECDHE_ECDSA", 11)) {
                suites[numsuites++] = AUTH_SUITE_ECDHE_ECDSA;
            } else if (0 == strncmp(*av, "ECDHE_PSK", 9)) {
                suites[numsuites++] = AUTH_SUITE_ECDHE_PSK;
            } else if (0 == strncmp(*av, "ECDHE_NULL", 10)) {
                suites[numsuites++] = AUTH_SUITE_ECDHE_NULL;
            }
            ac--;
            av++;
        }
    }
#endif
#else
    suites[numsuites++] = AUTH_SUITE_ECDHE_ECDSA;
    clearkeys = TRUE;
#endif

#ifdef SECURE_INTERFACE
    if (numsuites == 0) {
        /* Default security to ECDHE_NULL, if not explicit elsewhere */
        suites[numsuites++] = AUTH_SUITE_ECDHE_NULL;
    }
#endif

    /*
     * One time initialization before calling any other AllJoyn APIs
     */
    AJ_Initialize();

    AJ_PrintXML(ProxyObjects);
    AJ_RegisterObjects(NULL, ProxyObjects);

    while (TRUE) {
        AJ_Message msg;

        if (!connected) {
#if defined (ANNOUNCE_BASED_DISCOVERY)
            status = AJ_StartClientByPeerDescription(&bus, NULL, CONNECT_TIMEOUT, FALSE, &pingServicePeer, testServicePort, &sessionId, g_peerServiceName, NULL);
#elif defined (NGNS)
            status = AJ_StartClientByInterface(&bus, NULL, CONNECT_TIMEOUT, FALSE, testInterfaceNames, &sessionId, g_peerServiceName, NULL);
#else
            status = AJ_StartClientByName(&bus, NULL, CONNECT_TIMEOUT, FALSE, testServiceName, testServicePort, &sessionId, NULL, g_peerServiceName);
#endif
            if (status == AJ_OK) {
                AJ_AlwaysPrintf(("StartClient returned %d, sessionId=%u, serviceName=%s\n", status, sessionId, g_peerServiceName));
                AJ_AlwaysPrintf(("Connected to Daemon:%s\n", AJ_GetUniqueName(&bus)));
                connected = TRUE;
#if defined(SECURE_INTERFACE) || defined(SECURE_OBJECT)
                AJ_BusEnableSecurity(&bus, suites, numsuites);
                AJ_BusSetAuthListenerCallback(&bus, AuthListenerCallback);
                if (clearkeys) {
                    AJ_ClearCredentials(AJ_GENERIC_MASTER_SECRET | AJ_CRED_TYPE_GENERIC);
                    AJ_ClearCredentials(AJ_GENERIC_ECDSA_MANIFEST | AJ_CRED_TYPE_GENERIC);
                    AJ_ClearCredentials(AJ_GENERIC_ECDSA_KEYS | AJ_CRED_TYPE_GENERIC);
                }
                status = AJ_BusAuthenticatePeer(&bus, g_peerServiceName, AuthCallback, &authStatus);
                if (status != AJ_OK) {
                    AJ_AlwaysPrintf(("AJ_BusAuthenticatePeer returned %d\n", status));
                }
#else
                authStatus = AJ_OK;
#endif
            } else {
                AJ_AlwaysPrintf(("StartClient returned %d\n", status));
                break;
            }
        }


        AJ_AlwaysPrintf(("Auth status %d and AllJoyn status %d\n", authStatus, status));

        if (status == AJ_ERR_RESOURCES) {
            AJ_InfoPrintf(("Peer is busy, disconnecting and retrying auth...\n"));
            AJ_Disconnect(&bus);
            connected = FALSE;
            continue;
        }

        if (authStatus != AJ_ERR_NULL) {
            if (authStatus != AJ_OK) {
                AJ_Disconnect(&bus);
                break;
            }
            authStatus = AJ_ERR_NULL;
            AJ_BusSetLinkTimeout(&bus, sessionId, 10 * 1000);
        }

        status = AJ_UnmarshalMsg(&bus, &msg, UNMARSHAL_TIMEOUT);
        if (status != AJ_OK) {
            if (status == AJ_ERR_TIMEOUT) {
                AppDoWork(&bus, sessionId, g_peerServiceName);
                continue;
            }
        } else {
            switch (msg.msgId) {

            case AJ_REPLY_ID(AJ_METHOD_SET_LINK_TIMEOUT):
                {
                    uint32_t disposition;
                    uint32_t timeout;
                    status = AJ_UnmarshalArgs(&msg, "uu", &disposition, &timeout);
                    if (disposition == AJ_SETLINKTIMEOUT_SUCCESS) {
                        AJ_AlwaysPrintf(("Link timeout set to %d\n", timeout));
                    } else {
                        AJ_AlwaysPrintf(("SetLinkTimeout failed %d\n", disposition));
                    }
                    SendPing(&bus, sessionId, g_peerServiceName, 1);
                }
                break;

            case AJ_REPLY_ID(AJ_METHOD_BUS_PING):
                {
                    uint32_t disposition;
                    status = AJ_UnmarshalArgs(&msg, "u", &disposition);
                    if (disposition == AJ_PING_SUCCESS) {
                        AJ_AlwaysPrintf(("Bus Ping reply received\n"));
                    } else {
                        AJ_AlwaysPrintf(("Bus Ping failed, disconnecting: %d\n", disposition));
                        status = AJ_ERR_LINK_DEAD;
                    }
                }
                break;

            case AJ_REPLY_ID(PRX_MY_PING):
                {
                    AJ_Arg arg;
                    AJ_UnmarshalArg(&msg, &arg);
                    AJ_AlwaysPrintf(("Got ping reply\n"));
                    AJ_InfoPrintf(("INFO Got ping reply\n"));
                    status = SendGetProp(&bus, sessionId, g_peerServiceName);
                }
                break;

            case AJ_REPLY_ID(PRX_GET_PROP):
                {
                    const char* sig;
                    status = AJ_UnmarshalVariant(&msg, &sig);
                    if (status == AJ_OK) {
                        status = AJ_UnmarshalArgs(&msg, sig, &g_iterCount);
                        AJ_AlwaysPrintf(("Get prop reply %d\n", g_iterCount));

                        if (status == AJ_OK) {
                            g_iterCount = g_iterCount + 1;
                            status = SendSetProp(&bus, sessionId, g_peerServiceName, g_iterCount);
                        }
                    }
                }
                break;

            case AJ_REPLY_ID(PRX_SET_PROP):
                AJ_AlwaysPrintf(("Set prop reply\n"));
                break;

            case AJ_SIGNAL_SESSION_LOST_WITH_REASON:
                /*
                 * Force a disconnect
                 */
                {
                    uint32_t id, reason;
                    AJ_UnmarshalArgs(&msg, "uu", &id, &reason);
                    AJ_AlwaysPrintf(("Session lost. ID = %u, reason = %u\n", id, reason));
                }
                status = AJ_ERR_SESSION_LOST;
                break;

            default:
                /*
                 * Pass to the built-in handlers
                 */
                status = AJ_BusHandleBusMessage(&msg);
                break;
            }
        }
        /*
         * Messages must be closed to free resources
         */
        AJ_CloseMsg(&msg);

        if ((status == AJ_ERR_SESSION_LOST) || (status == AJ_ERR_READ) || (status == AJ_ERR_WRITE) || (status == AJ_ERR_LINK_DEAD)) {
            AJ_AlwaysPrintf(("AllJoyn disconnect\n"));
            AJ_AlwaysPrintf(("Disconnected from Daemon:%s\n", AJ_GetUniqueName(&bus)));
            AJ_Disconnect(&bus);
            break;
        }
    }
    AJ_AlwaysPrintf(("clientlite EXIT %d\n", status));

    return status;
}
Пример #27
0
    void PollPeerPingTimer( Peer& peer, std::time_t currentTime, bool executeNowIgnoringTimeouts=false )
    {
        bool noPingsReceivedYet =
                !peer.privateEndpoint.pingReceived
                && !peer.publicEndpoint.pingReceived
                && !peer.pingEndpoint.pingReceived;

        if( !noPingsReceivedYet ){
            // check whether we should attempt to re-establish the link
            // due to no traffic arriving for PEER_ESTABLISHMENT_RETRY_TIME_SECONDS

            std::time_t mostRecentPingTime = 0;
            if( peer.privateEndpoint.pingReceived )
                mostRecentPingTime = std::max( mostRecentPingTime, peer.privateEndpoint.lastPingReceiveTime );
            if( peer.publicEndpoint.pingReceived )
                mostRecentPingTime = std::max( mostRecentPingTime, peer.publicEndpoint.lastPingReceiveTime );
            if( peer.pingEndpoint.pingReceived )
                mostRecentPingTime = std::max( mostRecentPingTime, peer.pingEndpoint.lastPingReceiveTime );
            
            if( (int)std::difftime(currentTime, mostRecentPingTime) > PEER_ESTABLISHMENT_RETRY_TIME_SECONDS ){

                peer.pingPeriodCount = 0;
                executeNowIgnoringTimeouts = true;
            }
        }


        bool inEstablishmentPhase =
                ( ( peer.pingPeriodCount < ESTABLISHMENT_PING_PERIOD_COUNT )
                &&  ( !peer.privateEndpoint.pingReceived ) )
                || noPingsReceivedYet;

        if( inEstablishmentPhase ){
            int pingPeriod;
            if( peer.pingPeriodCount < ESTABLISHMENT_PING_PERIOD_COUNT ){
            
                pingPeriod = (int) (IDLE_PING_PERIOD_SECONDS *
                        ((double)(peer.pingPeriodCount + 1) / (double) ESTABLISHMENT_PING_PERIOD_COUNT));

            }else{
                pingPeriod = IDLE_PING_PERIOD_SECONDS;
            }

            if( currentTime >= (peer.lastPingPeriodTime + pingPeriod)
                    || executeNowIgnoringTimeouts ){
                SendPing( peer.privateEndpoint, currentTime );
                SendPing( peer.publicEndpoint, currentTime );
                if( peer.pingEndpoint.pingReceived )
                    SendPing( peer.pingEndpoint, currentTime );

                peer.lastPingPeriodTime = currentTime;
                ++peer.pingPeriodCount;
            }
        
        }else{

            PeerEndpoint *peerEndpointToUse = SelectEndpoint( peer );
            assert( peerEndpointToUse != 0 );

            bool sendPing = false;

            if( executeNowIgnoringTimeouts ){

                sendPing = true;

            }else{
            
                if( peerEndpointToUse->sentPingsCount == 0 ){

                    sendPing = true;

                }else{

                    int secondsSinceLastPing = (int)std::difftime(currentTime, peerEndpointToUse->lastPingSendTime);

                    if( peerEndpointToUse->forwardedPacketsCount == 0 ){

                        if( secondsSinceLastPing >= IDLE_PING_PERIOD_SECONDS ){
                        
                            sendPing = true;
                        }

                    }else{

                        int secondsSinceLastForwardedTraffic =
                                (int)std::difftime(currentTime, peerEndpointToUse->lastPacketForwardTime);

                        if( secondsSinceLastForwardedTraffic >= IDLE_PING_PERIOD_SECONDS ){

                            if( secondsSinceLastPing >= IDLE_PING_PERIOD_SECONDS ){
                                sendPing = true;
                            }

                        }else if( secondsSinceLastPing >= ACTIVE_PING_PERIOD_SECONDS ){
                            sendPing = true;
                        }
                    }
                }
            }

            if( sendPing ){
                SendPing( *peerEndpointToUse, currentTime );
                peer.lastPingPeriodTime = currentTime;
                ++peer.pingPeriodCount;
            }
        }
    }