#define _LCD_TYPE 1 #include #include #include #include #include #include #include #include #define SS_PIN_1 5 #define RST_PIN_1 2 #define SS_PIN_2 13 #define RST_PIN_2 14 #define GREEN_PIN 4 #define RED_PIN 26 #define BUZZER_PIN 27 #define RXD2 16 #define TXD2 17 HardwareSerial SerialPort(2); LCD_1602_RUS lcd(0x27, 16, 2); MFRC522 rfid1(SS_PIN_1, RST_PIN_1); MFRC522 rfid2(SS_PIN_2, RST_PIN_2); RCSwitch mySwitch = RCSwitch(); enum CommState { WAITING_HELLO, RUNNING, SHUTDOWN }; CommState commState = WAITING_HELLO; unsigned long lastHelloSent = 0; unsigned long lastHelloReply = 0; unsigned long lastRxFromRpi = 0; // <--- НОВОЕ: время последнего пакета от RPi const unsigned long HELLO_INTERVAL = 1000; const unsigned long HELLO_REPLY_COOLDOWN_MS = 500; const unsigned long RX_TIMEOUT_MS = 60000; // <--- НОВОЕ: таймаут 60 секунд // --- Melodies --- int notes_hello[] = {NOTE_C6, NOTE_D6, NOTE_E6, NOTE_F6, 0, NOTE_C6, 0, NOTE_C6}; int dur_hello[] = {10, 10, 10, 10, 4, 4, 5, 4}; int hello_len = 8; int notes_accept[] = {NOTE_C6, NOTE_E6}; int dur_accept[] = {10, 10}; int accept_len = 2; int notes_decline[] = {NOTE_G4, 0, NOTE_G4, 0, NOTE_G4}; int dur_decline[] = {25, 25, 25, 25, 25}; int decline_len = 5; struct MelodyPlayer { int pin; int *notes; int *durations; int count; int step = 0; unsigned long nextTime = 0; bool active = false; void start(int p, int *n, int *d, int c) { pin = p; notes = n; durations = d; count = c; step = 0; active = true; nextTime = millis(); } void update() { if (!active) return; unsigned long now = millis(); if (now >= nextTime) { if (step < count) { int duration = 1000 / durations[step]; tone(pin, notes[step], duration); nextTime = now + duration * 1.3; step++; } else { noTone(pin); active = false; } } } void stop_all() { active = false; noTone(pin); } }; MelodyPlayer melody; // --- UI state --- bool lcdMessageActive = false; unsigned long lcdMessageUntil = 0; String lastTimeStr = ""; String currentLine0 = ""; String currentLine1 = ""; bool waitForMelody = false; bool ledHoldActive = false; unsigned long ledHoldStart = 0; const unsigned long LED_HOLD_MS = 3000; // --- Radio burst --- unsigned long burstCode = 0; unsigned long burstStart = 0; unsigned long burstLast = 0; int burstCount = 0; const unsigned long BURST_WINDOW_MS = 500; const unsigned long BURST_END_GAP_MS = 150; // ---------- UTF-8 helpers ---------- int lcdPrintUtf8Trunc(const String &text, int maxChars) { int charsWritten = 0; int byteIdx = 0; int len = text.length(); while (byteIdx < len && charsWritten < maxChars) { unsigned char c = (unsigned char)text[byteIdx]; int bytes = 1; if ((c & 0x80) == 0) bytes = 1; else if ((c & 0xE0) == 0xC0) bytes = 2; else if ((c & 0xF0) == 0xE0) bytes = 3; else if ((c & 0xF8) == 0xF0) bytes = 4; if (byteIdx + bytes > len) bytes = len - byteIdx; String ch = text.substring(byteIdx, byteIdx + bytes); lcd.print(ch); byteIdx += bytes; charsWritten++; } return charsWritten; } void writeLine0(const String &text) { if (currentLine0 == text) return; lcd.setCursor(0, 0); int n = lcdPrintUtf8Trunc(text, 16); for (int i = n; i < 16; i++) lcd.print(" "); currentLine0 = text; } void writeLine1(const String &text) { if (currentLine1 == text) return; lcd.setCursor(0, 1); int n = lcdPrintUtf8Trunc(text, 16); for (int i = n; i < 16; i++) lcd.print(" "); currentLine1 = text; } // ---------- Helpers ---------- void sendHello() { StaticJsonDocument<64> doc; doc["type"] = "hello"; doc["role"] = "esp"; serializeJson(doc, SerialPort); SerialPort.println(); } String formatUID(MFRC522::Uid &uid) { String s = ""; for (byte i = 0; i < uid.size; i++) { if (uid.uidByte[i] < 0x10) s += "0"; s += String(uid.uidByte[i], HEX); } s.toUpperCase(); return s; } void sendRfid(int channel, const String &uid) { StaticJsonDocument<128> doc; doc["type"] = "rfid"; doc["channel"] = channel; doc["uid"] = uid; serializeJson(doc, SerialPort); SerialPort.println(); } void sendIr(uint32_t code) { StaticJsonDocument<64> doc; doc["type"] = "ir"; char buf[11]; sprintf(buf, "0x%08X", code); doc["code"] = buf; serializeJson(doc, SerialPort); SerialPort.println(); } void finalizeRadioBurst() { if (burstCount == 0) return; StaticJsonDocument<96> doc; doc["type"] = "radio"; doc["code"] = burstCode; doc["count"] = burstCount; serializeJson(doc, SerialPort); SerialPort.println(); burstCount = 0; burstCode = 0; } void initialScreen() { lcd.clear(); currentLine0 = ""; currentLine1 = ""; writeLine1("Поднесите метку"); writeLine0(lastTimeStr.length() > 0 ? lastTimeStr : "---"); } void handleRfidResult(int channel, bool granted, const String &uid) { Serial.print("Rfid result: ch="); Serial.print(channel); Serial.print(" granted="); Serial.print(granted); Serial.print(" uid="); Serial.println(uid); if (channel == 1) { writeLine0(granted ? "Проходите :)" : "Доступ запрещ."); writeLine1("UID:" + uid); lcdMessageActive = true; lcdMessageUntil = millis() + 2000; if (granted) melody.start(BUZZER_PIN, notes_accept, dur_accept, accept_len); else melody.start(BUZZER_PIN, notes_decline, dur_decline, decline_len); } else if (channel == 2) { if (granted) { digitalWrite(GREEN_PIN, HIGH); digitalWrite(RED_PIN, LOW); melody.start(BUZZER_PIN, notes_accept, dur_accept, accept_len); } else { digitalWrite(RED_PIN, HIGH); digitalWrite(GREEN_PIN, LOW); melody.start(BUZZER_PIN, notes_decline, dur_decline, decline_len); } ledHoldActive = true; ledHoldStart = millis(); } } void processMessage(const String &line) { String trimmed = line; trimmed.trim(); if (trimmed.length() == 0) return; StaticJsonDocument<256> doc; if (deserializeJson(doc, trimmed)) { Serial.println("JSON parse failed"); return; } const char *type = doc["type"]; if (!type) return; if (strcmp(type, "hello") == 0) { unsigned long now = millis(); if (commState == WAITING_HELLO) { commState = RUNNING; // --- ВКЛЮЧАЕМ ПОДСВЕТКУ ПРИ ВОССТАНОВЛЕНИИ СВЯЗИ --- lcd.backlight(); // --- ПРИВЕТСТВЕННЫЙ ЭКРАН ESP --- lcd.clear(); currentLine0 = "LabStand 2.0"; currentLine1 = "от СКБ \"КИТ\""; lcd.setCursor(0, 0); lcd.print(currentLine0); lcd.setCursor(0, 1); lcd.print(currentLine1); melody.start(BUZZER_PIN, notes_hello, dur_hello, hello_len); waitForMelody = true; sendHello(); lastHelloReply = now; } else if (commState == SHUTDOWN) { commState = RUNNING; lcd.backlight(); // --- ПРИВЕТСТВЕННЫЙ ЭКРАН ESP --- lcd.clear(); currentLine0 = "LabStand 2.0"; currentLine1 = "от СКБ \"КИТ\""; lcd.setCursor(0, 0); lcd.print(currentLine0); lcd.setCursor(0, 1); lcd.print(currentLine1); melody.stop_all(); melody.start(BUZZER_PIN, notes_hello, dur_hello, hello_len); waitForMelody = true; lcdMessageActive = false; ledHoldActive = false; digitalWrite(GREEN_PIN, LOW); digitalWrite(RED_PIN, LOW); sendHello(); lastHelloReply = now; } else if (now - lastHelloReply >= HELLO_REPLY_COOLDOWN_MS) { sendHello(); lastHelloReply = now; } return; } if (commState != RUNNING) return; if (strcmp(type, "time") == 0) { const char *val = doc["value"]; if (val) { String newTime = String(val); if (newTime != lastTimeStr) { lastTimeStr = newTime; if (!lcdMessageActive && !waitForMelody) { writeLine0(lastTimeStr); } } } } else if (strcmp(type, "rfid_result") == 0) { int channel = doc["channel"] | 0; const char *res = doc["result"] | ""; const char *uid = doc["uid"] | ""; handleRfidResult(channel, strcmp(res, "granted") == 0, String(uid)); } else if (strcmp(type, "shutdown") == 0) { lcd.clear(); currentLine0 = ""; currentLine1 = ""; lcd.setCursor(0, 0); lcd.print("Выключение"); delay(500); digitalWrite(GREEN_PIN, LOW); digitalWrite(RED_PIN, LOW); melody.stop_all(); lcd.noBacklight(); lcdMessageActive = false; ledHoldActive = false; waitForMelody = false; commState = SHUTDOWN; } } void pollSensors() { if (rfid1.PICC_IsNewCardPresent() && rfid1.PICC_ReadCardSerial()) { sendRfid(1, formatUID(rfid1.uid)); rfid1.PICC_HaltA(); } if (rfid2.PICC_IsNewCardPresent() && rfid2.PICC_ReadCardSerial()) { sendRfid(2, formatUID(rfid2.uid)); rfid2.PICC_HaltA(); } if (IrReceiver.decode()) { uint32_t code = IrReceiver.decodedIRData.decodedRawData; if (code != 0) sendIr(code); IrReceiver.resume(); } if (mySwitch.available()) { unsigned long code = mySwitch.getReceivedValue(); mySwitch.resetAvailable(); if (code != 0) { unsigned long now = millis(); if (code == burstCode && (now - burstStart) < BURST_WINDOW_MS) { burstCount++; burstLast = now; } else { finalizeRadioBurst(); burstCode = code; burstStart = now; burstLast = now; burstCount = 1; } } } } void setup() { Serial.begin(115200); SerialPort.begin(115200, SERIAL_8N1, RXD2, TXD2); pinMode(GREEN_PIN, OUTPUT); pinMode(RED_PIN, OUTPUT); pinMode(BUZZER_PIN, OUTPUT); digitalWrite(GREEN_PIN, LOW); digitalWrite(RED_PIN, LOW); lcd.init(); lcd.backlight(); // --- ЗАСТАВКА ПРИ СТАРТЕ (2 СЕКУНДЫ) --- lcd.setCursor(0,0); lcd.print("LabStand 2.0"); lcd.setCursor(0,1); lcd.print("ESP32 Unit"); delay(2000); lcd.clear(); lcd.setCursor(0,0); lcd.print("Ожидание связи"); lcd.setCursor(0,1); lcd.print("с Raspberry"); SPI.begin(); rfid1.PCD_Init(); rfid2.PCD_Init(); mySwitch.enableReceive(digitalPinToInterrupt(34)); IrReceiver.begin(35, DISABLE_LED_FEEDBACK); lastRxFromRpi = millis(); // <--- Инициализация таймера связи } void loop() { // Чтение UART и обновление таймера while (SerialPort.available()) { String line = SerialPort.readStringUntil('\n'); if (line.length() > 0) { lastRxFromRpi = millis(); // <--- Обновляем время последнего пакета processMessage(line); } } // Проверка таймаута связи (только в режиме RUNNING) if (commState == RUNNING && (millis() - lastRxFromRpi > RX_TIMEOUT_MS)) { // Потеря связи с RPi более 60 секунд commState = WAITING_HELLO; lcd.noBacklight(); lcd.clear(); currentLine0 = ""; currentLine1 = ""; melody.stop_all(); digitalWrite(GREEN_PIN, LOW); digitalWrite(RED_PIN, LOW); ledHoldActive = false; lcdMessageActive = false; waitForMelody = false; lastHelloSent = millis(); // Сброс таймера отправки hello Serial.println("Connection lost, standby mode"); } if (commState == WAITING_HELLO) { if (millis() - lastHelloSent >= HELLO_INTERVAL) { sendHello(); lastHelloSent = millis(); } } else if (commState == RUNNING) { pollSensors(); } if (burstCount > 0 && (millis() - burstLast) >= BURST_END_GAP_MS) { finalizeRadioBurst(); } melody.update(); if (waitForMelody && !melody.active) { waitForMelody = false; initialScreen(); } if (lcdMessageActive && millis() >= lcdMessageUntil) { lcdMessageActive = false; writeLine0(lastTimeStr.length() > 0 ? lastTimeStr : "---"); writeLine1("Поднесите метку"); } if (ledHoldActive && millis() - ledHoldStart >= LED_HOLD_MS) { digitalWrite(GREEN_PIN, LOW); digitalWrite(RED_PIN, LOW); ledHoldActive = false; } delay(1); }