#include <stdio.h>
#include <stdbool.h>
// Define all possible states
typedef enum {
STATE_LOCKED,
STATE_UNLOCKING,
STATE_UNLOCKED,
STATE_LOCKING,
STATE_COUNT // Total number of states
} State;
// Function pointer type for state handlers
typedef void (*StateHandler)(void);
// Current state variable
State currentState = STATE_LOCKED;
// Simulated input functions
bool unlockButtonPressed() {
static int count = 0;
return (++count == 2); // Press at step 2
}
bool doorOpened() {
static int count = 0;
return (++count == 4); // Opened at step 4
}
bool doorClosed() {
static int count = 0;
return (++count == 6); // Closed at step 6
}
// State handler functions
void stateLocked() {
printf("[LOCKED] Waiting...\n");
if (unlockButtonPressed()) {
printf("Unlock button pressed.\n");
currentState = STATE_UNLOCKING;
}
}
void stateUnlocking() {
printf("[UNLOCKING] Door is being unlocked...\n");
currentState = STATE_UNLOCKED;
}
void stateUnlocked() {
printf("[UNLOCKED] Door is unlocked.\n");
if (doorOpened()) {
printf("Door opened.\n");
}
if (doorClosed()) {
printf("Door closed. Locking...\n");
currentState = STATE_LOCKING;
}
}
void stateLocking() {
printf("[LOCKING] Door is being locked...\n");
currentState = STATE_LOCKED;
}
// State handler table (function pointer array)
StateHandler stateTable[STATE_COUNT] = {
stateLocked,
stateUnlocking,
stateUnlocked,
stateLocking
};
int main() {
// Simulate system loop
for (int i = 0; i < 10; i++) {
printf("\nCycle %d:\n", i + 1);
if (currentState < STATE_COUNT) {
stateTable[currentState](); // Call the current state's handler
}
}
return 0;
}