Exemple #1
0
    ClientHeartbeat::ClientHeartbeat(zmq::context_t& context, const HeartbeatSettings& settings)
        : msFrequency_(settings.msRate), msPollingFrequency_(settings.msPollRate), msTimeout_(settings.msTimeout)
    {
      // Create the router's socket
      std::unique_ptr<zmq::socket_t> heartbeat(new zmq::socket_t(context, ZMQ_PAIR));
      heartbeat->connect(CLIENT_HB_SOCKET_ADDR.c_str());
      router_.add_socket(SocketID::HEARTBEAT, heartbeat);

      // Specify functionality 
      auto onRcvHEARTBEAT = [&] (const Message&m)
      { heartbeatArrived(lastReceivedTime_);};
      auto onRcvGOODBYE = [&] (const Message&m)
      { router_.stop();};

      auto timeout = [&] ()
      { monitorTimeout(lastReceivedTime_, router_, msTimeout_);};
      auto send = [&] ()
      { sendHeartbeat(lastSendTime_, router_, msFrequency_);};

      // Bind to router
      router_(SocketID::HEARTBEAT).onRcvHEARTBEAT.connect(onRcvHEARTBEAT);
      router_(SocketID::HEARTBEAT).onRcvGOODBYE.connect(onRcvGOODBYE);
      router_(SocketID::HEARTBEAT).onPoll.connect(timeout);
      router_(SocketID::HEARTBEAT).onPoll.connect(send);
      router_(SocketID::HEARTBEAT).onFailedSend.connect(failedSend);
    }
HeartbeatManager::HeartbeatManager(int queueSize, int interval, QObject *parent) : QThread(parent)
{
    m_queueSize = queueSize;
    m_inteval = interval;
    m_running = false;
    m_timer = new QTimer(this);
    connect(m_timer, SIGNAL(timeout()), this, SLOT(sendHeartbeat()));
}
void HeartbeatManager::run(){

    while(1){

        msleep(m_inteval);
        sendHeartbeat();
    }
}
Exemple #4
0
int8_t smartSleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrupt2, uint8_t mode2, unsigned long ms) {
	int8_t ret = sleep(interrupt1, mode1, interrupt2, mode2, ms);
	// notifiy controller about wake up
	sendHeartbeat();
	// listen for incoming messages
	wait(MY_SMART_SLEEP_WAIT_DURATION);
	return ret;
}
Exemple #5
0
// Message delivered through _msg
void _processInternalMessages() {
	bool isMetric;
	uint8_t type = _msg.type;

	#if !defined(MY_DISABLE_REMOTE_RESET)
		if (type == I_REBOOT) {
			// Requires MySensors or other bootloader with watchdogs enabled
			hwReboot();
		} else
	#endif
		if (type == I_CONFIG) {
		// Pick up configuration from controller (currently only metric/imperial)
		// and store it in eeprom if changed
	 	if (_msg.getString() == NULL) {
			isMetric = true;
		} else {
			isMetric = _msg.getString()[0] == 'M';
		}
		_cc.isMetric = isMetric;
		hwWriteConfig(EEPROM_CONTROLLER_CONFIG_ADDRESS, isMetric);
	} else if (type == I_PRESENTATION) {
		if (!mGetAck(_msg)) {
			// Re-send node presentation to controller
			#if defined(MY_RADIO_FEATURE)
				transportPresentNode();
			#endif
			if (presentation)
				presentation();
		}
	} else if (type == I_HEARTBEAT) {
		sendHeartbeat();
	} else if (type == I_TIME) {
		// Deliver time to callback
		if (receiveTime)
			receiveTime(_msg.getULong());
	}
	#if defined(MY_REPEATER_FEATURE)
		if (type == I_CHILDREN) {
			if (_msg.getString()[0] == 'C') {
				// Clears child relay data for this node
				debug(PSTR("clear routing table\n"));
				uint8_t i = 255;
				do {
					hwWriteConfig(EEPROM_ROUTES_ADDRESS+i, BROADCAST_ADDRESS);
				} while (i--);
				// Clear parent node id & distance to gw
				hwWriteConfig(EEPROM_PARENT_NODE_ID_ADDRESS, AUTO);
				hwWriteConfig(EEPROM_DISTANCE_ADDRESS, DISTANCE_INVALID);
				// Find parent node
				transportFindParentNode();
				_sendRoute(build(_msg, _nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_CHILDREN,false).set(""));
			}
		}
	#endif
}
void AbstractProtocol::startHeartbeats(int ms)
{
    QTimer *timer = new QTimer(this);
    //Send out a message every now and then, to keep the tcp connection alive
    connect(timer, &QTimer::timeout, [this]() {
        sendHeartbeat();
    });
    connect(this, SIGNAL(destroyed()), timer, SLOT(stop()));
    connect(this, SIGNAL(destroyed()), timer, SLOT(deleteLater()));
    timer->start(ms);
}
Exemple #7
0
bool RateListenPlan::execute() {
	// split each second up into 10 pieces, allocate 1/10 total write to each tenth second
	size_t leftThisSecond = settings.rate;
	size_t msgsPerTenth = settings.rate / 10;
	size_t leftThisTenth = msgsPerTenth;
	expected = 0;
	absolute_time startOfSecond = GetAbsoluteTime();
	absolute_time startOfTenth = startOfSecond;
	count = 0;
	totalCount = 0;
	for (;;) {
		boost::this_thread::interruption_point();
		if (leftThisTenth > 0) {
			Message* message = getMessage();
			if (message != NULL) {
				leftThisTenth--;
				leftThisSecond--;
				delete message->getData();
				delete message;
			}
		}
		absolute_time currTime = GetAbsoluteTime();
		int64_t tenthTime = GetTimeDurationMillisecs(startOfTenth, currTime);
		if (tenthTime > 100) {
			//start new tenth
			leftThisTenth = msgsPerTenth;
			startOfTenth = currTime;
		} else
			continue;
		int64_t secondTime = GetTimeDurationMillisecs(startOfSecond, currTime);
		if (secondTime >= 1000) {
			//might be 1 message left over, if rate is less than 10
			if (leftThisSecond > 0) {
				Message* message = getMessage();
				if (message != NULL) {
					leftThisSecond--;
					delete message->getData();
					delete message;
				}
			}
			leftThisSecond = settings.rate;
			startOfSecond = currTime;
			if (count > 0)
				std::cout << count << " messages received\n";
			count = 0;
			sendHeartbeat(expected);
		}
	}
	return true;
}
  void loop() {

    if (!finished) {
      collectingLoops++;
      finished = true;
      for (int i = 0; i < functionsTop; i++) {
        if (!functionComplete[i]) {
          wdt_reset();
          functionComplete[i] = heartbeatFunctions[i]();
          if (!functionComplete[i]) finished = false;
        }
      }
    }

    if (finished) {

      // After the heartbeatFunctions have completed, reset isAlive once
      if (!aliveReset) {
        isAlive = false;
        aliveReset = true;
      }

      uint32_t currentTime = micros();
      if (currentTime >= nextHeartbeat) {
        sendHeartbeat();

        // Set the micros delay for when the next heartbeat should be sent
        nextHeartbeat = currentTime + microsBetweenFrames;

        // Zero out the heartbeat state
        collectingLoops = 0;
        idleLoops = 0;
        aliveReset = false;

        for (int i = 0; i < MaxFunctions; i++) {
          functionComplete[i] = false;
          finished = false;
        }

      } else {
        idleLoops++;
      }
    }
  }
Exemple #9
0
Message* RateListenPlan::getMessage() {
	Message* result = subSocket->receive();
	if (result != NULL) {
		count++;
		totalCount++;
		if (expected == 0)
			expected = result->getCounter();
		if (result->getCounter() != expected) {
			std::cout << "message drop detected. expected " << expected << " got " << result->getCounter();
			std::cout << " skipped " << (result->getCounter() - expected) << "\n";
			std::cout << "total count this bucket: " << totalCount << std::endl;
			totalCount = 0;
		}
		expected = result->getCounter() + 1;
		if (totalCount % 1000 == 0)
			sendHeartbeat(result->getCounter());
	}
	return result;
}
	int ModManDecentral::loop(const ros::TimerEvent& event)
	{
		if (robot.state == voraus::Voraus::idle || robot.state == voraus::Voraus::working || robot.state == voraus::Voraus::failure)
		{
			//the robot will be unregistered if he didn't send a heartbeat-message after this time
			if (robot.lastHeartbeatTime < event.current_real - robot.maxTimeWithoutHeartbeat)
			{
				ROS_ERROR("%s master is lost. Trying to reconnect.", name.full.c_str());
				registerAtServer();
			}
			
			//a warning will be printed if the master didn't send a heartbeat-message after this time
			if (robot.lastHeartbeatTime < event.current_real - robot.maxTimeWithoutHeartbeat * 0.7)
			{
				ROS_WARN("%s no heartbeat from master since %.2f sec", name.full.c_str(), event.current_real.toSec() - robot.lastHeartbeatTime.toSec());
			}
			
			sendHeartbeat();
		}
	}
Exemple #11
0
void CGame::sendUserInput() {

	sf::Packet clientUpdate;
	short packetType;
	int input;

	packetType = CLIENT_UPDATE;
	clientUpdate << packetType;

	if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
		input = THRUSTUP;
		clientUpdate << input;

		gameClient.send(clientUpdate);
		return;

	}
	if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
		input = THRUSTDOWN;
		clientUpdate << input;

		gameClient.send(clientUpdate);
		return;
	}
	if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
		input = TURNLEFT;
		clientUpdate << input;

		gameClient.send(clientUpdate);
		return;
	}
	if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
		input = TURNRIGHT;
		clientUpdate << input;

		gameClient.send(clientUpdate);
		return;
	}
	sendHeartbeat();
}
Exemple #12
0
void CGame::receiveServerUpdate() {

	sf::Packet serverPacket;
	short packetType;

	while (gameClient.receive(&serverPacket) != 0) {

		serverPacket >> packetType;

		switch (packetType) {

		case SERVER_UPDATE:
			gameWorld.packetToWorld(serverPacket);
			break;
		case HEARTBEAT:
			sendHeartbeat();
			break;
		case DISCONNECT:
			setState(LOGIN);
			break;
		}
	}
}
Exemple #13
0
void XapClass::heartbeat(void) {
     if (after(heartbeatTimeout)) {      
       sendHeartbeat();
       resetHeartbeat();
     }
}
Exemple #14
0
// process all incoming server messages
void Visualight::processClient(){
  int available;

  if(millis()-lastHeartbeat > heartBeatInterval && reconnectCount == 0){
    sendHeartbeat();
  }

  if(millis()-connectTime > connectServerInterval){
    VPRINTLN(F("reconnect from timeout"));
    //reconnect = true;
    //connectTime = millis();
    if(!connectToServer()){
      reconnectCount++;
    }
  }
  else {
    available = wifly.available();

    if (available < 0) {
      VPRINT(F("reconnect from available()"));
      reconnectCount++;
      if(!connectToServer()){
        //reconnectCount++;
      }
    }
    else if(available > 0){
      connectTime = millis();
      char thisChar;
      thisChar = wifly.read();
      if( thisChar == 97){
        wifly.readBytesUntil('x', serBuf, 31);
        int duration;
        int red, green, blue, white;
        sscanf(serBuf,"%i,%i,%i,%i,%i,%i,%i",&red,&green,&blue,&white,&duration,&_frequency,&_blinkType); // INDIGO v0.1.1

          VPRINT("buf: ");
          VPRINTLN(serBuf);

        if(duration > 0 && _blinkType <=1){ //we are STARTING AN ALERT
          _durationTime = duration*1000; 
          _frequency = (_frequency+1); //* 100; //get the right freq out //100 - 1000
          setAlert(_blinkType, _durationTime, _frequency, red, green, blue, white);
        } 

        else if(_blinkType == 2){ // we are setting the start color here
					saveStartColor(red,green,blue,white);
        } 

        else if(_blinkType == 3){ // reset WiFi, become a server
          //this is sent from server when a bulb is deleted from a Visualight account.
          wifiReset(); //set isServer = true, turn on AP mode
        }

        else { //simple set color
          if(alerting){
  	        _durationTime = 0; // will time out any currently running alert
          }
            setColor(red, green, blue, white); 
        } 
        memset(serBuf,0,31);
      }
    }
  }
}
Exemple #15
0
int main(int argc, char *argv[]) {	
	leaderCommand = NULL;
	sendHeartBeatMillis = 5000;//send a heartbeat after this many millis
	heartBeatTimeoutMillis = sendHeartBeatMillis * 3;//assume leader is dead if no heartbeat after this long
	heartBeatMsgLength = strlen(heartBeatMsg);
	addrs = (struct sockaddr_in *)malloc(sizeof(struct sockaddr_in) * MAX_HOSTS);//using a list here would be more memory efficient
	if(addrs == NULL) {
		fprintf(stderr, "Could not allocate memory\n");
		exit(1);
	}
	parseArgs(argc, argv);
	myIpAndPortStr = (char *)malloc(ipAndPortStrLength);
	fromIpAndPortStr = (char *)malloc(ipAndPortStrLength);

	serverSock = socket(AF_INET, SOCK_DGRAM, 0);
	if (serverSock < 0) {
		fprintf(stderr, "Opening socket\n");
		exit(1);
	}
	struct sockaddr_in serverSockAddr;
	memset(&serverSockAddr, 0, sizeof(serverSockAddr));
	serverSockAddr.sin_family = AF_INET;
	serverSockAddr.sin_addr.s_addr = INADDR_ANY;
	serverSockAddr.sin_port = htons(serverPort);
	if (bind(serverSock, (struct sockaddr *)&serverSockAddr, sizeof(struct sockaddr)) < 0)  {
		perror("Binding socket");
		exit(1);
	}
	setIpAndPortStr(myIpAndPortStr, (struct sockaddr *)&serverSockAddr);

	struct pollfd fd;
	fd.fd = serverSock;
	fd.events = POLLIN;

	int isLeader = 0;
	leaderChanged(0);//initialize not leader

	while(1) {
		if(isLeader) {
			//send heartbeats unless we receive a heartbeat from someone else, then assume not leader
			long lastHeartbeatSentMillis = 0;
			long pollTimeout;
			int pollResult;
			while(1) {			
				//http://linux.die.net/man/2/poll	
				pollTimeout = lastHeartbeatSentMillis + sendHeartBeatMillis - getTimeMillis();				
				if(pollTimeout <= 0) {
					pollTimeout = sendHeartBeatMillis;
				}
				pollResult = poll(&fd, 1, (int)pollTimeout);
				if(pollResult < 0) {
					perror("IsLeader poll error");
				} else if(pollResult == 0) {
					sendHeartbeat();			
					lastHeartbeatSentMillis = getTimeMillis();
				} else {
					if(fd.revents & POLLIN) {
						if(recvHeartbeat()) {
							//someone else thinks they are the leader, compare from ip+port to me, whichever sorts lower is the leader
							//if i am the leader, immediately send a heartbeat msg, which will tell the other leader to not be the leader
							//since it will get to this same spot, and by comparing ip+port determine that it is not the leader
							setIpAndPortStr(fromIpAndPortStr, (struct sockaddr *)&from);
							if(strcmp(myIpAndPortStr, fromIpAndPortStr) < 0) {
								isLeader = 0;
								leaderChanged(isLeader);
								sendHeartbeat();
							}
						}						
						break;
					} else if(fd.revents & POLLERR) {
						//last message errored, what to do?
					}
				}
			}
		} else {
			long lastHeartbeatReceivedMillis = 0;
			int pollResult;
			long pollTimeout;
			while(1) {
				//listen for heartbeats, if don't hear heartbeat within x sec, assume self is leader
				pollTimeout = lastHeartbeatReceivedMillis + heartBeatTimeoutMillis - getTimeMillis();
				if(pollTimeout <= 0) {
					pollTimeout = heartBeatTimeoutMillis;
				}
				pollResult = poll(&fd, 1, (int)pollTimeout);
				if(pollResult < 0) {
					perror("IsNotLeader poll error");
				} else if(pollResult == 0) {
					isLeader = 1;
					leaderChanged(isLeader);
					sendHeartbeat();
					break;
					//no heartbeats received from leader, take over leadership
					//TODO random delay to prevent slave storm to take over leadership?
				} else {
					if(fd.revents & POLLIN) {
						if(recvHeartbeat()) {
							lastHeartbeatReceivedMillis = getTimeMillis();
						}
					}
				}		
			}		
		}
	}
	return 0;
}