#include <Arduino.h>
#include <Wire.h>
#include <string.h>
#include <Keypad.h>
#include <Servo.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <AES_CMAC.h>
#include <AES.h>
// ============================================================
// 1. НАЛАШТУВАННЯ ПАКЕТА
// ============================================================
const size_t PACKET_SIZE = 36;
const uint8_t HEADER_1 = 0xAA;
const uint8_t HEADER_2 = 0x55;
const uint8_t EXPECTED_LENGTH_FIELD = 0x1F;
const uint8_t EXPECTED_MESSAGE_TYPE = 0x01;
const uint8_t EXPECTED_PROTOCOL_VERSION = 0x01;
const uint8_t EXPECTED_RECEIVER_ID[4] = {
0x00, 0x00, 0x00, 0x01
};
const size_t CMAC_SIZE = 16;
const size_t CMAC_INPUT_SIZE = 15;
// ============================================================
// 2. ТЕСТОВИЙ HEX-ПАКЕТ
// ============================================================
const char* receivedPacket =
"AA 55 1F 01 01 03 00 00 00 01 "
"00 00 00 00 00 00 00 01 "
"A7 86 11 9C CF 93 B4 2B 33 53 94 F5 17 1D D9 3B "
"AA A0";
// ============================================================
// 3. КЛЮЧІ AES-128
// ============================================================
const uint8_t keyUser1[16] = {
0x2A, 0x7C, 0x91, 0x4E,
0xB3, 0x05, 0xD8, 0x62,
0xF1, 0x39, 0xA6, 0x80,
0x5D, 0xC4, 0x17, 0xEB
};
const uint8_t keyUser2[16] = {
0x6F, 0x12, 0xC8, 0xA5,
0x39, 0xE0, 0x74, 0xBD,
0x83, 0x2D, 0x51, 0x9A,
0xF6, 0x04, 0xCB, 0x17
};
const uint8_t keyUser3[16] = {
0xB4, 0x08, 0x63, 0xDE,
0x21, 0x95, 0xAF, 0x7C,
0x30, 0xE2, 0x49, 0x16,
0x8B, 0xD5, 0x0A, 0xF3
};
AESTiny128 aes128;
AES_CMAC cmac(aes128);
// ============================================================
// 4. OLED SSD1306
// ============================================================
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_ADDRESS 0x3C
Adafruit_SSD1306 display(
SCREEN_WIDTH,
SCREEN_HEIGHT,
&Wire,
-1
);
bool oledReady = false;
// ============================================================
// 5. KEYPAD 4x4
// ============================================================
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {
PA0, PA1, PA2, PA3
};
byte colPins[COLS] = {
PB12, PB13, PB14, PB15
};
Keypad keypad = Keypad(
makeKeymap(keys),
rowPins,
colPins,
ROWS,
COLS
);
// ============================================================
// 6. PIN-КОДИ
// ============================================================
const char PIN_USER1[] = "1234";
const char PIN_USER2[] = "2580";
const char PIN_USER3[] = "3691";
const char PIN_ADMIN[] = "8080";
const size_t PIN_LENGTH = 4;
char enteredPIN[PIN_LENGTH + 1] = "";
uint8_t enteredPINLength = 0;
// ============================================================
// 7. КЕРУВАННЯ ДВЕРИМА ТА ІНДИКАЦІЯ
// ============================================================
const uint8_t SERVO_PIN = PB0;
const uint8_t SERVO_CLOSED_ANGLE = 0;
const uint8_t SERVO_OPEN_ANGLE = 90;
const unsigned long DOOR_OPEN_DURATION = 15000UL;
const unsigned long OLED_MESSAGE_DURATION = 3000UL;
Servo doorServo;
bool doorAccessActive = false;
unsigned long doorOpenStartTime = 0;
const uint8_t DOOR_SENSOR_PIN = PB10;
int lastDoorState = HIGH;
bool doorSensorInitialized = false;
const uint8_t RED_LED_PIN = PB8;
const uint8_t GREEN_LED_PIN = PB9;
const uint8_t BLUE_LED_PIN = PB11;
const uint8_t BUZZER_PIN = PB5;
bool alarmActive = false;
// ============================================================
// 8. КЕРУВАННЯ СВІТЛОДІОДАМИ
// ============================================================
void setLEDs(bool red, bool green, bool blue) {
digitalWrite(RED_LED_PIN, red ? HIGH : LOW);
digitalWrite(GREEN_LED_PIN, green ? HIGH : LOW);
digitalWrite(BLUE_LED_PIN, blue ? HIGH : LOW);
}
void showWaitingStatus() {
if (alarmActive) {
return;
}
setLEDs(false, false, true);
}
void showAccessGrantedStatus() {
if (alarmActive) {
return;
}
setLEDs(false, true, false);
}
void showAccessDeniedStatus() {
if (alarmActive) {
return;
}
setLEDs(true, false, false);
}
// ============================================================
// 9. OLED: ВІДОБРАЖЕННЯ ПОВІДОМЛЕНЬ
// ============================================================
void showOLEDMessage(
const char* line1,
const char* line2 = "",
const char* line3 = ""
) {
if (!oledReady) {
return;
}
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.println(line1);
display.setCursor(0, 20);
display.println(line2);
display.setCursor(0, 40);
display.println(line3);
display.display();
}
// ============================================================
// 10. АКТИВАЦІЯ ТРИВОГИ
// ============================================================
void activateAlarm(const char* reason) {
if (alarmActive) {
return;
}
alarmActive = true;
doorAccessActive = false;
doorServo.write(SERVO_CLOSED_ANGLE);
setLEDs(true, false, false);
tone(BUZZER_PIN, 2000);
Serial.println();
Serial.println("SECURITY ALARM ACTIVATED");
Serial.print("Reason: ");
Serial.println(reason);
showOLEDMessage(
"SECURITY ALARM",
"UNAUTHORIZED",
"ACCESS DETECTED"
);
}
// ============================================================
// 11. ЕКРАН ВВЕДЕННЯ PIN
// ============================================================
void showPINEntry() {
if (!oledReady) {
return;
}
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
if (alarmActive) {
display.println("SECURITY ALARM");
display.setCursor(0, 18);
display.println("ADMIN PIN REQUIRED");
display.setCursor(0, 34);
display.print("PIN: ");
for (uint8_t i = 0; i < enteredPINLength; i++) {
display.print("*");
}
display.setCursor(0, 50);
display.println("# Confirm * Clear");
} else {
display.println("PIN AUTHORIZATION");
display.setCursor(0, 20);
display.print("PIN: ");
for (uint8_t i = 0; i < enteredPINLength; i++) {
display.print("*");
}
display.setCursor(0, 42);
display.println("# - Confirm");
display.setCursor(0, 54);
display.println("* - Clear");
}
display.display();
}
// ============================================================
// 12. НАДАННЯ ДОСТУПУ
// ============================================================
void grantDoorAccess(
const char* authorizationMethod,
uint8_t userID
) {
if (alarmActive) {
Serial.println("ACCESS BLOCKED: SECURITY ALARM ACTIVE");
return;
}
Serial.println();
Serial.print("ACCESS GRANTED: User ");
Serial.println(userID);
Serial.print("Method: ");
Serial.println(authorizationMethod);
doorServo.write(SERVO_OPEN_ANGLE);
showAccessGrantedStatus();
doorOpenStartTime = millis();
doorAccessActive = true;
Serial.println("Door unlocked.");
showOLEDMessage(
"ACCESS GRANTED",
"DOOR UNLOCKED",
"15 seconds"
);
}
// ============================================================
// 13. ВІДМОВА У ДОСТУПІ
// ============================================================
void denyDoorAccess(const char* reason) {
if (alarmActive) {
return;
}
Serial.println();
Serial.println("ACCESS DENIED");
Serial.print("Reason: ");
Serial.println(reason);
doorServo.write(SERVO_CLOSED_ANGLE);
doorAccessActive = false;
showAccessDeniedStatus();
showOLEDMessage(
"ACCESS DENIED",
reason,
"Door remains locked"
);
}
// ============================================================
// 14. АВТОМАТИЧНЕ ЗАКРИТТЯ ДВЕРЕЙ
// ============================================================
void updateDoorControl() {
if (!doorAccessActive || alarmActive) {
return;
}
if (millis() - doorOpenStartTime >= DOOR_OPEN_DURATION) {
doorServo.write(SERVO_CLOSED_ANGLE);
doorAccessActive = false;
Serial.println();
Serial.println("DOOR LOCKED");
if (digitalRead(DOOR_SENSOR_PIN) == LOW) {
activateAlarm(
"Door remained open after authorization timeout"
);
return;
}
showWaitingStatus();
showOLEDMessage(
"DOOR LOCKED",
"Access completed",
"Enter PIN"
);
}
}
// ============================================================
// 15. КОНТРОЛЬ СТАНУ ДВЕРЕЙ
// ============================================================
void updateDoorSensor() {
int currentDoorState = digitalRead(DOOR_SENSOR_PIN);
if (!doorSensorInitialized) {
lastDoorState = currentDoorState;
doorSensorInitialized = true;
if (currentDoorState == HIGH) {
Serial.println("Door state: CLOSED");
} else {
Serial.println("Door state: OPEN");
activateAlarm(
"Door was open during system initialization"
);
}
return;
}
if (currentDoorState != lastDoorState) {
lastDoorState = currentDoorState;
if (currentDoorState == HIGH) {
Serial.println("Door state: CLOSED");
} else {
Serial.println("Door state: OPEN");
if (!doorAccessActive) {
activateAlarm("Unauthorized door opening");
}
}
}
}
// ============================================================
// 16. ДОПОМІЖНІ ФУНКЦІЇ HEX
// ============================================================
int hexCharToValue(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'A' && c <= 'F') {
return c - 'A' + 10;
}
if (c >= 'a' && c <= 'f') {
return c - 'a' + 10;
}
return -1;
}
bool isHexWhitespace(char c) {
return c == ' ' ||
c == '\n' ||
c == '\r' ||
c == '\t';
}
// ============================================================
// 17. HEX -> BYTE ARRAY
// ============================================================
bool hexStringToBytes(
const char* hexString,
uint8_t* output,
size_t maxLength,
size_t &outputLength
) {
outputLength = 0;
int highNibble = -1;
for (size_t i = 0; hexString[i] != '\0'; i++) {
char c = hexString[i];
if (isHexWhitespace(c)) {
continue;
}
int value = hexCharToValue(c);
if (value < 0) {
return false;
}
if (highNibble < 0) {
highNibble = value;
} else {
if (outputLength >= maxLength) {
return false;
}
output[outputLength] =
(uint8_t)((highNibble << 4) | value);
outputLength++;
highNibble = -1;
}
}
if (highNibble >= 0) {
return false;
}
return true;
}
// ============================================================
// 18. CRC16-CCITT-FALSE
// ============================================================
uint16_t calculateCRC16(
const uint8_t* data,
size_t length
) {
uint16_t crc = 0xFFFF;
for (size_t i = 0; i < length; i++) {
crc ^= (uint16_t)data[i] << 8;
for (uint8_t bit = 0; bit < 8; bit++) {
if (crc & 0x8000) {
crc = (crc << 1) ^ 0x1021;
} else {
crc <<= 1;
}
}
}
return crc;
}
// ============================================================
// 19. ОТРИМАННЯ КЛЮЧА КОРИСТУВАЧА
// ============================================================
const uint8_t* getUserKey(uint8_t userID) {
switch (userID) {
case 1:
return keyUser1;
case 2:
return keyUser2;
case 3:
return keyUser3;
default:
return nullptr;
}
}
// ============================================================
// 20. ФОРМУВАННЯ ВХІДНИХ ДАНИХ ДЛЯ CMAC
// ============================================================
void buildCMACInput(
const uint8_t* packet,
uint8_t* cmacInput
) {
memcpy(
cmacInput,
packet + 3,
CMAC_INPUT_SIZE
);
}
// ============================================================
// 21. ПЕРЕВІРКА AES-128-CMAC
// ============================================================
bool verifyCMAC(
const uint8_t* packet,
uint8_t userID
) {
const uint8_t* userKey = getUserKey(userID);
if (userKey == nullptr) {
return false;
}
uint8_t cmacInput[CMAC_INPUT_SIZE];
uint8_t calculatedMAC[CMAC_SIZE];
buildCMACInput(packet, cmacInput);
cmac.generateMAC(
calculatedMAC,
userKey,
cmacInput,
sizeof(cmacInput)
);
uint8_t difference = 0;
for (size_t i = 0; i < CMAC_SIZE; i++) {
difference |= calculatedMAC[i] ^ packet[18 + i];
}
return difference == 0;
}
// ============================================================
// 22. ПЕРЕВІРКА ПРАВ ДОСТУПУ
// ============================================================
bool checkUserPermissions(uint8_t userID) {
switch (userID) {
case 1:
case 2:
return true;
case 3:
default:
return false;
}
}
// ============================================================
// 23. ОБРОБКА AUTH_REQUEST
// ============================================================
void processAuthRequest(const char* hexPacket) {
uint8_t packet[PACKET_SIZE];
size_t packetLength = 0;
Serial.println();
Serial.println("AUTH REQUEST");
bool conversionOK = hexStringToBytes(
hexPacket,
packet,
PACKET_SIZE,
packetLength
);
if (!conversionOK) {
denyDoorAccess("Invalid HEX packet");
return;
}
if (packetLength != PACKET_SIZE) {
denyDoorAccess("Invalid packet length");
return;
}
// Перевірка структури пакета.
if (packet[0] != HEADER_1 ||
packet[1] != HEADER_2) {
denyDoorAccess("Invalid packet header");
return;
}
if (packet[2] != EXPECTED_LENGTH_FIELD) {
denyDoorAccess("Invalid length field");
return;
}
if (packet[3] != EXPECTED_MESSAGE_TYPE) {
denyDoorAccess("Invalid message type");
return;
}
if (packet[4] != EXPECTED_PROTOCOL_VERSION) {
denyDoorAccess("Invalid protocol version");
return;
}
uint8_t userID = packet[5];
Serial.print("User: ");
Serial.println(userID);
if (userID < 1 || userID > 4) {
denyDoorAccess("Unknown user");
return;
}
if (memcmp(
packet + 6,
EXPECTED_RECEIVER_ID,
sizeof(EXPECTED_RECEIVER_ID)
) != 0) {
denyDoorAccess("Invalid receiver ID");
return;
}
// Перевірка CRC16.
uint16_t calculatedCRC = calculateCRC16(
packet + 2,
32
);
uint16_t receivedCRC =
((uint16_t)packet[34] << 8) |
packet[35];
if (calculatedCRC != receivedCRC) {
Serial.println("CRC: INVALID");
denyDoorAccess("CRC verification failed");
return;
}
Serial.println("CRC: VALID");
// Перевірка AES-128-CMAC.
bool cmacValid = verifyCMAC(packet, userID);
if (!cmacValid) {
Serial.println("CMAC: INVALID");
denyDoorAccess("CMAC verification failed");
return;
}
Serial.println("CMAC: VALID");
// Перевірка прав доступу.
bool accessGranted = checkUserPermissions(userID);
if (accessGranted) {
grantDoorAccess("ELECTRONIC KEY", userID);
} else {
denyDoorAccess("No electronic key access rights");
}
}
// ============================================================
// 24. ОЧИЩЕННЯ ВВЕДЕНОГО PIN
// ============================================================
void clearEnteredPIN() {
enteredPINLength = 0;
enteredPIN[0] = '\0';
showPINEntry();
}
// ============================================================
// 25. СКИДАННЯ ТРИВОГИ АДМІНІСТРАТОРОМ
// ============================================================
void resetSecurityAlarm() {
if (digitalRead(DOOR_SENSOR_PIN) != HIGH) {
Serial.println("ALARM RESET DENIED: Door is OPEN");
showOLEDMessage(
"ALARM ACTIVE",
"CLOSE THE DOOR",
"Then enter ADMIN PIN"
);
delay(1500);
clearEnteredPIN();
return;
}
alarmActive = false;
doorAccessActive = false;
doorServo.write(SERVO_CLOSED_ANGLE);
noTone(BUZZER_PIN);
setLEDs(false, false, true);
enteredPINLength = 0;
enteredPIN[0] = '\0';
Serial.println("SECURITY ALARM RESET");
Serial.println("Administrator authorized.");
showPINEntry();
}
// ============================================================
// 26. ПЕРЕВІРКА PIN
// ============================================================
void verifyEnteredPIN() {
// Обробка PIN під час тривоги.
if (alarmActive) {
if (enteredPINLength != PIN_LENGTH) {
Serial.println("Invalid PIN length.");
delay(1000);
clearEnteredPIN();
return;
}
enteredPIN[PIN_LENGTH] = '\0';
if (strcmp(enteredPIN, PIN_ADMIN) == 0) {
Serial.println("Administrator PIN accepted.");
resetSecurityAlarm();
return;
}
Serial.println("Invalid administrator PIN.");
showOLEDMessage(
"ALARM ACTIVE",
"INVALID ADMIN PIN",
"Try again"
);
delay(OLED_MESSAGE_DURATION);
clearEnteredPIN();
return;
}
// Звичайна PIN-авторизація.
if (enteredPINLength != PIN_LENGTH) {
denyDoorAccess("PIN must contain 4 digits");
delay(OLED_MESSAGE_DURATION);
clearEnteredPIN();
return;
}
enteredPIN[PIN_LENGTH] = '\0';
// PIN адміністратора.
if (strcmp(enteredPIN, PIN_ADMIN) == 0) {
Serial.println("Administrator PIN accepted.");
Serial.println("No active alarm to reset.");
showOLEDMessage(
"ADMINISTRATOR",
"PIN ACCEPTED",
"No active alarm"
);
delay(2500);
clearEnteredPIN();
return;
}
// User 1.
if (strcmp(enteredPIN, PIN_USER1) == 0) {
grantDoorAccess("BACKUP PIN", 1);
delay(OLED_MESSAGE_DURATION);
clearEnteredPIN();
return;
}
// User 2.
if (strcmp(enteredPIN, PIN_USER2) == 0) {
grantDoorAccess("BACKUP PIN", 2);
delay(OLED_MESSAGE_DURATION);
clearEnteredPIN();
return;
}
// User 3.
if (strcmp(enteredPIN, PIN_USER3) == 0) {
grantDoorAccess("BACKUP PIN", 3);
delay(OLED_MESSAGE_DURATION);
clearEnteredPIN();
return;
}
// Невідомий PIN.
denyDoorAccess("Invalid PIN");
delay(OLED_MESSAGE_DURATION);
clearEnteredPIN();
}
// ============================================================
// 27. ОБРОБКА НАТИСКАННЯ КЛАВІШ
// ============================================================
void processKeypadInput() {
char key = keypad.getKey();
if (key == NO_KEY) {
return;
}
if (key == '*') {
clearEnteredPIN();
return;
}
if (key == '#') {
verifyEnteredPIN();
return;
}
if (alarmActive &&
!(key >= '0' && key <= '9')) {
return;
}
if (key >= '0' && key <= '9') {
if (enteredPINLength < PIN_LENGTH) {
enteredPIN[enteredPINLength] = key;
enteredPINLength++;
enteredPIN[enteredPINLength] = '\0';
showPINEntry();
}
return;
}
}
// ============================================================
// 28. SETUP
// ============================================================
void setup() {
Serial.begin(115200);
delay(500);
Serial.println();
Serial.println("RECEIVER STARTING");
// GPIO.
pinMode(RED_LED_PIN, OUTPUT);
pinMode(GREEN_LED_PIN, OUTPUT);
pinMode(BLUE_LED_PIN, OUTPUT);
pinMode(DOOR_SENSOR_PIN, INPUT_PULLUP);
pinMode(BUZZER_PIN, OUTPUT);
noTone(BUZZER_PIN);
showWaitingStatus();
// Servo.
doorServo.attach(SERVO_PIN);
doorServo.write(SERVO_CLOSED_ANGLE);
delay(500);
// OLED.
Wire.begin();
oledReady = display.begin(
SSD1306_SWITCHCAPVCC,
OLED_ADDRESS
);
if (oledReady) {
showOLEDMessage(
"SYSTEM STARTING",
"STM32 RECEIVER",
"Please wait..."
);
} else {
Serial.println("WARNING: OLED unavailable");
}
// Keypad.
keypad.setDebounceTime(50);
keypad.setHoldTime(500);
// Датчик дверей.
updateDoorSensor();
Serial.println("RECEIVER READY");
// Обробка тестового AUTH_REQUEST.
if (!alarmActive) {
processAuthRequest(receivedPacket);
delay(OLED_MESSAGE_DURATION);
} else {
Serial.println("AUTH REQUEST SKIPPED: Alarm active");
}
// Екран введення PIN.
if (alarmActive) {
showPINEntry();
} else {
showWaitingStatus();
clearEnteredPIN();
}
}
// ============================================================
// 29. LOOP
// ============================================================
void loop() {
processKeypadInput();
updateDoorControl();
updateDoorSensor();
}
Loading
stm32-bluepill
stm32-bluepill
Loading
ssd1306
ssd1306