Esempio n. 1
0
int main (int argc, char **argv)
{
	std::string input;
	std::string file = "./10021.response";
	char buf[1024];

	if (argc > 1)
		file = argv[1];

	FSM fsm;
	fsm.init(file);

	// XXX: integrating into deceptiond framework
	// timeouts can be set via the InputStream obj
	// '>>' tokenizes using \s ;( this should be different using
	// the InputStream
	while(1) {
		std::cin.getline(buf, 1023, '\n');
		if (buf[0] == 0)
			break;
		input = buf;
		fsm.parse(input);
	}

	return 0;
}
Esempio n. 2
0
void disconnectedUpdate() {
  if(Particle.connected()) {
    connectionFsm.transitionTo(Online);
  } else if(connectionFsm.timeInCurrentState() > DISCONNECTED_TIMEOUT) {
    connectionFsm.transitionTo(Offline);
  }
}
void HandlePollCompleteResponse(
        FSM & fsm,
        const mf::api::upload::poll_upload::Response & response
    )
{
    if (response.quickkey)
    {
        if (response.filename)
        {
            // Filename was changed
            fsm.ProcessEvent(event::PollComplete{
                *response.quickkey,
                *response.filename
                });
        }
        else
        {
            fsm.ProcessEvent(event::PollComplete{
                *response.quickkey,
                fsm.filename()
                });
        }
    }
    else
    {
        fsm.ProcessEvent(event::Error{
            make_error_code(api::api_code::ContentInvalidData),
            "Successful response missing quickkey"
            });
    }
}
/* Create random input file with i states and MAX_EVENTS events */
void create_test_file(const string& filename, int states, int events) {
	FSM fsm = create_initial_FSM(states, events);
	make_accessible(fsm);
	ofstream file_out(filename);
	if (EXTENSION == ".txt") fsm.print_txt(file_out);
	else if (EXTENSION == ".fsm") fsm.print_fsm(file_out);
	file_out.close();
}
Esempio n. 5
0
	bool FSMTask::onenter(Agent* pAgent)
	{
		BEHAVIAC_UNUSED_VAR(pAgent);
		FSM* fsm = (FSM*)this->m_node;
		this->m_activeChildIndex = 0;

		this->m_currentNodeId = fsm->GetInitialId();

		return true;
	}
Esempio n. 6
0
void error(String message) {
  if(self.isInState(Start)) {
    sd.initErrorPrint(&terminal);
  } else {
    sd.errorPrint(&terminal);
  }
  terminal.flush();

  errorMessage = message;
  self.transitionTo(Error);
}
Esempio n. 7
0
void updateSnuze() {
  if(-1 == clicks) {
    self.transitionTo(Clock);

    return;
  }
  if(snuzeRuntime.check()) {
    self.transitionTo(Alarm);

    return;
  }
}
Esempio n. 8
0
top (sc_module_name name) : sc_module (name), clk("Clk", period){
	fsm = new FSM("Statemachine", 100, 30); //Creating a new state machine with limit = 100.
	fsm->tick(clk);
	fsm->portA(Aout);
	fsm->X(Xin);

	Xcount = 0;
	Acount = 0;
	Xinput = false;

	SC_HAS_PROCESS(top);
	SC_CTHREAD(testbed, clk);
}
Esempio n. 9
0
void updateAlarm() {
  RGB.brightness(map(abs((millis() % 2000) - 1000), 0, 1000, 0, 255));

  switch(clicks) {
    case -1:
      self.transitionTo(Clock);

      return;
    case 1:
      self.transitionTo(Snuze);

      return;
  }
}
Esempio n. 10
0
bool TestCase3::onInit()
{
    FSM *fsm = new FSMA();
    fsm->create("fsm3").start();
    fsm->subscribeBcEvent("TestEvt1");


    EvtStream data;
    std::string input = "000 hello world! 300 abc123";
    data << 23 << input;
    fsm->sendBcEvent("TestEvt1", data);

    return true;
}
Esempio n. 11
0
FSM * FSM::create(std::string state, std::function<void()> onEnter)
{
	FSM* fsm = new FSM(state, onEnter);
	if ( fsm && fsm->init())
	{
		fsm->autorelease();
		return fsm;
	}
	else
	{
		CC_SAFE_DELETE(fsm);
		return nullptr;
	}
}
Esempio n. 12
0
void updateStart() {
  if(Time.now() > 10000 && millis() > 5000) {
    self.transitionTo(Clock);

    return;
  }
}
Esempio n. 13
0
void offlineUpdate() {
  digitalWrite(LIGHT_PIN, LIGHT_ON);

  if(Particle.connected()) {
    connectionFsm.transitionTo(Online);
  }
}
Esempio n. 14
0
/* This function rerturns the fsm to be equivalent to (fsm1|fsm2) 
 * XXX : Use with caution. This modifies fsm1, but the return value must be 
 * stored back in fsm1 for this to be effective.
 *
 * DO NOT try something like "fsm1 | fsm1", this will ave 
 */
FSM * FSM::operator | (FSM& rhs)
{
	/* Create a new (empty) start and end FSM */
	FSM *startFSM = new FSM();
	FSM *endFSM   = new FSM();

	/* Concatenate one of the two fsm-s with the start and end */
	this->concatenate (*endFSM);
	startFSM->concatenate (*this);

	/* Create a transition to the start state of other fsm */
	rhs.concatenate (*endFSM);

	/* Create a transition from the end state of other fsm */
	startFSM->startState.createTransition ('e', EPSILON, &(rhs.startState));
	return startFSM;
}
Esempio n. 15
0
FSM* IRParser::parseFSM(llvm::MDNode* node){
    FSM* fsm = new FSM();

    //Parse initial state
    MDString* initialState = cast<MDString>(node->getOperand(0));

    //Parse all fsm state
    MDNode* stateArray = cast<MDNode>(node->getOperand(1));

    for (unsigned i = 0, e = stateArray->getNumOperands(); i != e; ++i){
        MDString* stateMD = cast<MDString>(stateArray->getOperand(i));
        fsm->addState(stateMD->getString());
    }

    // set the initial state after initializing the states
    fsm->setInitialState(initialState->getString());


    //Parse transition
    MDNode* transitionsArray = cast<MDNode>(node->getOperand(2));

    for (unsigned i = 0, e = transitionsArray->getNumOperands(); i != e; ++i){
        MDNode* transitionArray = cast<MDNode>(transitionsArray->getOperand(i));
        MDString* source = cast<MDString>(transitionArray->getOperand(0));


        Value* targetValue = transitionArray->getOperand(1);

        //In case of "undefined" state, no target are given
        if (targetValue != NULL){
            MDNode* targetsArray = cast<MDNode>(targetValue);
            for (unsigned j = 0, f = targetsArray->getNumOperands() ; j != f; ++j){
                MDNode* targetArray = cast<MDNode>(targetsArray->getOperand(j));

                Action* action = getAction(cast<MDNode>(targetArray->getOperand(0)));
                MDString* target = cast<MDString>(targetArray->getOperand(1));


                fsm->addTransition(source->getString(), target->getString(), action);
            }
        }
    }

    return fsm;
}
Esempio n. 16
0
int main()
{
    enum Message { on, off, ack };
    Message messageArray[10] = { on,off,off,ack,ack,ack,ack,on,off,off };
    FSM* context = new FSM(B::getInstance());
    for (int index=0; index < 10; index++)
    {
        if(messageArray[index] == on)
            context->on();
        else if(messageArray[index] == off)
            context->off();
        else if(messageArray[index] == ack)
            context->ack();
        cout<<endl;
    }

    return 1;
}
Esempio n. 17
0
/* This function returns the fsm that accepts the repetition of strings 
 * accepted by given fsm.
 */
FSM * FSM::repeat ()
{
	/* Create a new (empty) FSM. */
	FSM *startFSM = new FSM();
	FSM *endFSM   = new FSM();

	/* Loop back from the accept state of the fsm to the start state */
	acceptState->createTransition ('e', EPSILON, &startState);
	acceptState->isFinalState = true;

	/* Concatenate the endFSM state with fsm */
	this->concatenate (*endFSM);
	/* Concatenate the startFSM with 'this' fsm */
	startFSM->concatenate (*this);

	/* Create a epsilon-transition from startFSM to endFSM */
	startFSM->startState.createTransition ('e', EPSILON, startFSM->acceptState);

	return startFSM;
}
Esempio n. 18
0
FSM fsm_simple() {
    FSM fsm;
    int even = fsm.addState("Even", true);
    int odd = fsm.addState("Odd");
    fsm.addTransition(even, even, 1, "1");
    fsm.addTransition(even, odd, 0, "0");
    fsm.addTransition(odd, odd, 1, "1");
    fsm.addTransition(odd, even, 0, "0");
    return fsm;
}
Esempio n. 19
0
void loop() {
  if(!Particle.connected()) {
    Particle.connect();
  }

  button.Update();
  clicks = button.clicks;

  self.update();

  Blynk.run();
}
void StartPoll(const std::string & upload_key, FSM & fsm)
{
    if (upload_key.empty())
    {
        assert(!"Reached poll upload without upload key");
        fsm.ProcessEvent(
                event::Error{make_error_code(uploader::errc::LogicError),
                             "Filsize unavailable."});
        return;
    }

    auto fsmp = fsm.AsFrontShared();

    fsm.GetSessionMaintainer()->Call(
            mf::api::upload::poll_upload::Request(upload_key),
            [fsmp, upload_key](
                    const mf::api::upload::poll_upload::Response & response)
            {
                HandlePollResponse(upload_key, *fsmp, response);
            });
}
Esempio n. 21
0
void make_accessible(FSM& fsm) {
	vector<int> current_access(fsm.nstates);
	int current = 0; //Initial state
	queue<int> BFS; //Breadth First Search
	BFS.push(current); 
	do_BFS(BFS, current, current_access, fsm);
	/* While there exists an inaccessible state */
	int inaccessible_state = fsm.find_inaccessible(current_access);
	while(inaccessible_state != -1) {
		int event_out = rand() % fsm.nevents;
		int state_out = rand() % fsm.nstates;
		while (transition_is_invalid(fsm, current_access, state_out, event_out)) {
			state_out = rand() % fsm.nstates;
			event_out = rand() % fsm.nevents;
		}
		/* Add transition from accessible state to inaccessible state */
		fsm.transitions[state_out][event_out] = inaccessible_state;
		BFS.push(inaccessible_state);
		do_BFS(BFS, inaccessible_state, current_access, fsm);
		inaccessible_state = fsm.find_inaccessible(current_access);
	}
}
Esempio n. 22
0
void updateClock() {
  uint8_t currentMinute = Time.minute();

  if(currentMinute != previousMinute) {
    previousMinute = currentMinute;

    if(alarms.check()) {
      self.transitionTo(Alarm);

      return;
    }
  }
}
Esempio n. 23
0
/********************
 * Loop function
 * ******************/
void loop(){
  char key;

  percent = led.getOutputPercent(now());
  analogWrite(ledPin, 255 * percent / 100);

  key = kpd.get_key();
  if (key != '\0')
  {
    computeKeypadInput(key);
  }
  fsm.update();
}
Esempio n. 24
0
/**
 * In case you are curious: this treats the FSM like a recognizer. It
 * resets the FSM to a default state and then processes each character
 * in the input string. If at the end of the string it is in an
 * accepting state, it means the FSM matched that string.
 *
 * the 'exp' param tells us if we actually expect it to recognize it.
 *
 * the 'is_bogus' param tells us if we expect the FSM to go into a
 * terminally bogus state, meaning it absolutely won't recognize the
 * input, no matter what comes next.
 *
 * It is possible for it to be in an unaccepted state without being
 * bogus. For example the string "BA" is not accepted, but if the next
 * character is "G", then the FSM would be in an accepted state.
 **/
void recognize(FSM& fsm, string input, bool exp, bool is_bogus) {
    fsm.setState(fsm.getDefaultState());
    State* st;
    st = fsm.getState(fsm.getCurrentState());
    if (st == NULL) {
        IsTrue("Null", false, "Current State is NULL");
        return;
    }
    //  cout << "Initial state: " << st << endl;
    string::iterator it = input.begin();
    for(; it != input.end(); it++) {
        char c = *it;
        int sig = (int) c;
        fsm.handleSignal(sig);
        st = fsm.getState(fsm.getCurrentState());
        //    cout << "After " << c << ", current state: " << st << endl;
    }
    IsTrue(input, fsm.isAcceptState() == exp, "Wrong Accept State");
    if (is_bogus) {
        st = fsm.getState(fsm.getCurrentState());
        IsTrue("Bogus", st->label == "Bogus State", "Should be in Bogus state");
    }
}
void HandlePollResponse(
        const std::string & upload_key,
        FSM & fsm,
        const mf::api::upload::poll_upload::Response & response
    )
{
    // if result is negative, it indicates a failure
    if ( response.result < 0 )
    {
        fsm.ProcessEvent(event::Error{
            std::error_code(response.result, poll_result_category()),
            "Poll upload bad response"
            });
    }
    else if( response.fileerror != 0 )
    {
        fsm.ProcessEvent(event::Error{
            std::error_code(response.fileerror,
                poll_upload_file_error_category()),
            "Poll upload file error received"
            });
    }
    else if( response.status == 99 )
    {
        HandlePollCompleteResponse(fsm, response);
    }
    else
    {
        auto timer = fsm.Timer();

        timer->expires_from_now( std::chrono::seconds(
                poll_upload_retry_timeout_seconds) );

        timer->async_wait( boost::bind( &RetryPoll<FSM>, upload_key,
                fsm.AsFrontShared(), boost::asio::placeholders::error));
    }
}
Esempio n. 26
0
FSM* IRWriter::writeFSM(FSM* fsm){
    list<llvm::Function*>::iterator it;

    FSM* newFSM = new FSM();

    //Copy states of the source fsm
    std::map<std::string, FSM::State*>::iterator itState;
    std::map<std::string, FSM::State*>* states = fsm->getStates();

    for (itState = states->begin(); itState != states->end(); itState++){
        newFSM->addState(itState->first);
    }

    //Copy transitions of the source fsm
    map<string, Action*>::iterator itActionsMap;
    std::map<std::string, FSM::Transition*>::iterator itTransition;
    std::map<std::string, FSM::Transition*>* transitions = fsm->getTransitions();
    for (itTransition = transitions->begin(); itTransition != transitions->end(); itTransition++){
        FSM::Transition* transition = itTransition->second;
        FSM::State* sourceState = transition->getSourceState();
        list<FSM::NextStateInfo*>::iterator itNextStateInfo;
        list<FSM::NextStateInfo*>* nextStateInfos = transition->getNextStateInfo();

        for (itNextStateInfo = nextStateInfos->begin(); itNextStateInfo != nextStateInfos->end(); itNextStateInfo++){
            FSM::State* targetState = (*itNextStateInfo)->getTargetState();
            Action* targetAction = (*itNextStateInfo)->getAction();

            newFSM->addTransition(sourceState->getName(), targetState->getName(), getAction(targetAction));
        }
    }

    //Set initiale state of the FSM
    newFSM->setInitialState(fsm->getInitialState()->getName());

    return newFSM;
}
Esempio n. 27
0
void renderError() {
  Display.setTextColor(RED, BLACK);

  /***** Error Message *****/
  Display.setTextSize(1);
  Display.setCursor(1, 55);

  Display.println(errorMessage);

  if(self.isInState(Start)) {
    sd.initErrorPrint(&Display);
  } else {
    sd.errorPrint(&Display);
  }
}
void HandlePollCompleteResponse(
        FSM & fsm,
        const mf::api::upload::poll_upload::Response & response)
{
    assert(response.response_data);
    const auto & response_data = *response.response_data;

    if (!response_data.quickkey)
    {
        fsm.ProcessEvent(
                event::Error{make_error_code(api::api_code::ContentInvalidData),
                             "Successful response missing quickkey"});
    }
    else if (!response_data.revision)
    {
        fsm.ProcessEvent(
                event::Error{make_error_code(api::api_code::ContentInvalidData),
                             "Successful response missing revision"});
    }
    else
    {
        if (response_data.filename)
        {
            // Filename was changed
            fsm.ProcessEvent(event::PollComplete{*response_data.quickkey,
                                                 *response_data.filename,
                                                 *response_data.revision});
        }
        else
        {
            fsm.ProcessEvent(event::PollComplete{*response_data.quickkey,
                                                 fsm.filename(),
                                                 *response_data.revision});
        }
    }
}
    void operator()(
            Event const &,
            FSM & fsm,
            SourceState&,
            TargetState&
        )
    {
        namespace instant = mf::api::upload::instant;

        auto request = instant::Request( fsm.filename(), fsm.hash(),
            fsm.filesize());

        switch (fsm.onDuplicateAction())
        {
            case OnDuplicateAction::Fail:
                // This is the default, same as "skip" and doesn't need to be
                // set.
                break;
            case OnDuplicateAction::Replace:
                request.SetActionOnDuplicate(instant::ActionOnDuplicate::Replace);
                break;
            case OnDuplicateAction::AutoRename:
                request.SetActionOnDuplicate(instant::ActionOnDuplicate::Keep);
                break;
            default:
                assert(!"Invalid duplicate action.");
                break;
        }

        UploadTarget target_folder = fsm.targetFolder();
        boost::apply_visitor(TargetSetter(&request), target_folder);

        auto fsmp = fsm.AsFrontShared();

        fsm.GetSessionMaintainer()->Call(
            request,
            [fsmp](const instant::Response & response)
            {
                if (response.error_code)
                {
                    fsmp->ProcessEvent(event::Error{response.error_code,
                        "Failed to instant upload file."});
                }
                else
                {
                    fsmp->ProcessEvent(event::InstantSuccess{ response.quickkey,
                        response.filename });
                }
            });
    }
Esempio n. 30
0
void render() {
  uint32_t start = millis();

  if(clear) {
    clear = false;
    Display.fillScreen(BLACK);
  }

  if(true == self.isInState(Error)) {
    renderError();
  } else {
    renderClock();
  }

  renderStatus();

  frameTime = millis() - start;
}