chore: initialize repository and staged implementation plan

This commit is contained in:
Mikhail committed 2026-11-26 15:23:50 +03:00
commit cb0e9d156f
48 files changed
+7343

No files matched your search

+395
View File
@@ -0,0 +1,395 @@
#define _LCD_TYPE 1
#include <LCD_1602_RUS_ALL.h>
#include <SPI.h>
#include <MFRC522.h>
#include <Wire.h>
#include <pitches.h>
#include <RCSwitch.h>
#include <IRremote.hpp>
#include <ArduinoJson.h>
#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);
}
+93
View File
@@ -0,0 +1,93 @@
/*************************************************
* Public Constants
*************************************************/
#define NOTE_B0 31
#define NOTE_C1 33
#define NOTE_CS1 35
#define NOTE_D1 37
#define NOTE_DS1 39
#define NOTE_E1 41
#define NOTE_F1 44
#define NOTE_FS1 46
#define NOTE_G1 49
#define NOTE_GS1 52
#define NOTE_A1 55
#define NOTE_AS1 58
#define NOTE_B1 62
#define NOTE_C2 65
#define NOTE_CS2 69
#define NOTE_D2 73
#define NOTE_DS2 78
#define NOTE_E2 82
#define NOTE_F2 87
#define NOTE_FS2 93
#define NOTE_G2 98
#define NOTE_GS2 104
#define NOTE_A2 110
#define NOTE_AS2 117
#define NOTE_B2 123
#define NOTE_C3 131
#define NOTE_CS3 139
#define NOTE_D3 147
#define NOTE_DS3 156
#define NOTE_E3 165
#define NOTE_F3 175
#define NOTE_FS3 185
#define NOTE_G3 196
#define NOTE_GS3 208
#define NOTE_A3 220
#define NOTE_AS3 233
#define NOTE_B3 247
#define NOTE_C4 262
#define NOTE_CS4 277
#define NOTE_D4 294
#define NOTE_DS4 311
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_FS4 370
#define NOTE_G4 392
#define NOTE_GS4 415
#define NOTE_A4 440
#define NOTE_AS4 466
#define NOTE_B4 494
#define NOTE_C5 523
#define NOTE_CS5 554
#define NOTE_D5 587
#define NOTE_DS5 622
#define NOTE_E5 659
#define NOTE_F5 698
#define NOTE_FS5 740
#define NOTE_G5 784
#define NOTE_GS5 831
#define NOTE_A5 880
#define NOTE_AS5 932
#define NOTE_B5 988
#define NOTE_C6 1047
#define NOTE_CS6 1109
#define NOTE_D6 1175
#define NOTE_DS6 1245
#define NOTE_E6 1319
#define NOTE_F6 1397
#define NOTE_FS6 1480
#define NOTE_G6 1568
#define NOTE_GS6 1661
#define NOTE_A6 1760
#define NOTE_AS6 1865
#define NOTE_B6 1976
#define NOTE_C7 2093
#define NOTE_CS7 2217
#define NOTE_D7 2349
#define NOTE_DS7 2489
#define NOTE_E7 2637
#define NOTE_F7 2794
#define NOTE_FS7 2960
#define NOTE_G7 3136
#define NOTE_GS7 3322
#define NOTE_A7 3520
#define NOTE_AS7 3729
#define NOTE_B7 3951
#define NOTE_C8 4186
#define NOTE_CS8 4435
#define NOTE_D8 4699
#define NOTE_DS8 4978