This program simulates a simple protocol using a state machine. It prints messages as it moves through states based on events.
#include <stdio.h>
typedef enum {
STATE_IDLE,
STATE_WAIT_ACK,
STATE_PROCESS_DATA,
STATE_ERROR
} State;
typedef enum {
EVENT_START,
EVENT_ACK_RECEIVED,
EVENT_TIMEOUT
} Event;
State current_state = STATE_IDLE;
void handle_event(Event event) {
switch (current_state) {
case STATE_IDLE:
if (event == EVENT_START) {
printf("Starting protocol, waiting for ACK...\n");
current_state = STATE_WAIT_ACK;
}
break;
case STATE_WAIT_ACK:
if (event == EVENT_ACK_RECEIVED) {
printf("ACK received, processing data...\n");
current_state = STATE_PROCESS_DATA;
} else if (event == EVENT_TIMEOUT) {
printf("Timeout! Error occurred.\n");
current_state = STATE_ERROR;
}
break;
case STATE_PROCESS_DATA:
printf("Data processed successfully. Returning to idle.\n");
current_state = STATE_IDLE;
break;
case STATE_ERROR:
printf("Handling error, resetting to idle.\n");
current_state = STATE_IDLE;
break;
}
}
int main() {
handle_event(EVENT_START);
handle_event(EVENT_ACK_RECEIVED);
handle_event(EVENT_START);
handle_event(EVENT_TIMEOUT);
handle_event(EVENT_START);
handle_event(EVENT_ACK_RECEIVED);
handle_event(EVENT_START);
handle_event(EVENT_ACK_RECEIVED);
handle_event(EVENT_START);
handle_event(EVENT_TIMEOUT);
return 0;
}