Initial commit

This commit is contained in:
thek4n 2026-06-12 00:49:58 +03:00
commit 89b089df93
2 changed files with 742 additions and 0 deletions

9
justfile Normal file
View File

@ -0,0 +1,9 @@
alias compile := build
build:
arduino-cli compile --fqbn esp8266:esp8266:nodemcuv2
alias flash := upload
upload:
arduino-cli upload --fqbn esp8266:esp8266:nodemcuv2 --port /dev/ttyUSB0

View File

@ -0,0 +1,733 @@
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <WebSocketsServer.h>
#include <ArduinoJson.h>
#include <vector>
// Настройки WiFi
const char* ssid = "ESP8266_LogicAnalyzer";
const char* password = "12345678";
// Настройки пинов (4 канала для ESP8266)
#define CH1_PIN 5 // D1
#define CH2_PIN 4 // D2
#define CH3_PIN 14 // D5
#define CH4_PIN 12 // D6
ESP8266WebServer server(80);
WebSocketsServer webSocket = WebSocketsServer(81);
// Буфер для данных - увеличен для 5 секунд при 5 кГц (25000 семплов)
#define MAX_BUFFER_SIZE 25000
uint8_t* logicBuffer;
volatile int bufferIndex = 0;
volatile bool samplingActive = false;
volatile unsigned long sampleRate = 5000; // Максимальная частота по умолчанию
volatile unsigned long lastSampleTime = 0;
// Флаги для отправки
volatile bool dataReady = false;
unsigned long lastSendTime = 0;
void setup() {
Serial.begin(115200);
// Выделяем память под буфер
logicBuffer = (uint8_t*)malloc(MAX_BUFFER_SIZE);
if (!logicBuffer) {
Serial.println("Ошибка выделения памяти!");
return;
}
// Настройка пинов
pinMode(CH1_PIN, INPUT_PULLUP);
pinMode(CH2_PIN, INPUT_PULLUP);
pinMode(CH3_PIN, INPUT_PULLUP);
pinMode(CH4_PIN, INPUT_PULLUP);
// Запуск WiFi точки доступа
WiFi.softAP(ssid, password);
Serial.print("Точка доступа создана. IP: ");
Serial.println(WiFi.softAPIP());
// Настройка веб-сервера
setupWebServer();
// Запуск WebSocket
webSocket.begin();
webSocket.onEvent(webSocketEvent);
server.begin();
Serial.println("Сервер запущен");
}
void setupWebServer() {
server.on("/", []() {
server.send(200, "text/html", getHTMLPage());
});
}
String getHTMLPage() {
// HTML страница вынесена в отдельную функцию
String html = R"rawliteral(
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
<title>ESP8266 Logic Analyzer</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
-webkit-tap-highlight-color: transparent;
}
body {
font-family: system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', sans-serif;
background: #0a0a0a;
color: #e0e0e0;
height: 100dvh;
overflow: hidden;
position: fixed;
width: 100%;
}
.app {
height: 100dvh;
display: flex;
flex-direction: column;
padding: 12px;
gap: 12px;
}
/* Заголовок */
.header {
flex-shrink: 0;
padding-bottom: 8px;
border-bottom: 1px solid #2a2a2a;
}
.header h1 {
font-size: 1.3rem;
font-weight: 600;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
}
/* Панель управления */
.controls {
flex-shrink: 0;
background: #141414;
border-radius: 16px;
padding: 12px;
display: flex;
flex-wrap: wrap;
gap: 12px;
align-items: center;
justify-content: space-between;
border: 1px solid #2a2a2a;
}
.control-group {
display: flex;
align-items: center;
gap: 8px;
background: #1e1e1e;
padding: 6px 12px;
border-radius: 12px;
}
.control-group label {
font-size: 0.85rem;
font-weight: 500;
color: #888;
}
select, button {
background: #2a2a2a;
color: #e0e0e0;
border: 1px solid #3a3a3a;
padding: 6px 12px;
border-radius: 10px;
font-size: 0.85rem;
cursor: pointer;
transition: all 0.2s ease;
}
select:hover, button:hover {
background: #3a3a3a;
border-color: #667eea;
}
button:active {
transform: scale(0.98);
}
.btn-start {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border: none;
font-weight: 600;
}
.btn-start:hover {
opacity: 0.9;
}
.btn-stop {
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
border: none;
font-weight: 600;
}
/* Контейнер с графиками */
.channels-container {
flex: 1;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 12px;
padding: 2px;
}
/* Канал */
.channel {
background: #141414;
border-radius: 16px;
padding: 12px;
border: 1px solid #2a2a2a;
transition: all 0.3s ease;
}
.channel-header {
display: flex;
justify-content: space-between;
align-items: baseline;
margin-bottom: 10px;
padding-bottom: 6px;
border-bottom: 1px solid #2a2a2a;
}
.channel-name {
font-weight: 600;
font-size: 0.9rem;
}
.channel-name.ch0 { color: #4ec9b0; }
.channel-name.ch1 { color: #dcdcaa; }
.channel-name.ch2 { color: #9cdcfe; }
.channel-name.ch3 { color: #ce9178; }
.channel-gpio {
font-size: 0.7rem;
color: #666;
font-family: monospace;
}
/* Canvas wrapper для скролла */
.canvas-wrapper {
overflow-x: auto;
overflow-y: hidden;
-webkit-overflow-scrolling: touch;
border-radius: 8px;
}
canvas {
display: block;
background: #0a0a0a;
border-radius: 8px;
cursor: grab;
}
canvas:active {
cursor: grabbing;
}
/* Маркеры времени */
.time-markers {
display: flex;
margin-top: 8px;
font-size: 0.7rem;
color: #666;
font-family: monospace;
overflow-x: auto;
white-space: nowrap;
}
.time-marker {
display: inline-block;
text-align: center;
}
/* Статус */
.status {
flex-shrink: 0;
background: #141414;
border-radius: 12px;
padding: 8px 12px;
font-size: 0.8rem;
font-family: monospace;
border: 1px solid #2a2a2a;
display: flex;
justify-content: space-between;
align-items: center;
}
.status-led {
width: 8px;
height: 8px;
border-radius: 50%;
background: #4caf50;
animation: pulse 2s infinite;
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
/* Скроллбар */
::-webkit-scrollbar {
width: 6px;
height: 6px;
}
::-webkit-scrollbar-track {
background: #1a1a1a;
border-radius: 10px;
}
::-webkit-scrollbar-thumb {
background: #3a3a3a;
border-radius: 10px;
}
::-webkit-scrollbar-thumb:hover {
background: #4a4a4a;
}
@media (max-width: 600px) {
.app {
padding: 8px;
gap: 8px;
}
.controls {
padding: 8px;
}
.control-group {
padding: 4px 8px;
}
.channel {
padding: 8px;
}
}
</style>
</head>
<body>
<div class="app">
<div class="header">
<h1>🔍 Logic Analyzer</h1>
</div>
<div class="controls">
<div class="control-group">
<label>📊 Частота</label>
<select id="sampleRate">
<option value="100">100 Гц</option>
<option value="200">200 Гц</option>
<option value="500">500 Гц</option>
<option value="1000">1 кГц</option>
<option value="2000">2 кГц</option>
<option value="5000" selected>5 кГц</option>
</select>
</div>
<div class="control-group">
<label>🔍 Масштаб</label>
<select id="timeScale">
<option value="0.5">0.5x</option>
<option value="1">1x</option>
<option value="2">2x</option>
<option value="5" selected>5x</option>
<option value="10">10x</option>
<option value="20">20x</option>
</select>
</div>
<div class="control-group">
<button id="startBtn" class="btn-start">▶ Старт</button>
<button id="stopBtn" class="btn-stop">⏹ Стоп</button>
</div>
</div>
<div class="channels-container" id="channels"></div>
<div class="status" id="status">
<span> Готов</span>
<div class="status-led"></div>
</div>
</div>
<script>
class LogicAnalyzer {
constructor() {
this.ws = null;
this.canvases = [];
this.contexts = [];
this.currentData = [[], [], [], []];
this.totalSamples = 0;
this.timeScale = 5;
this.sampleRate = 5000;
this.channelColors = ['#4ec9b0', '#dcdcaa', '#9cdcfe', '#ce9178'];
this.channelPins = [5, 4, 14, 12];
this.isConnected = false;
this.init();
}
init() {
this.createChannels();
this.connectWebSocket();
this.setupEventListeners();
}
createChannels() {
const channelsDiv = document.getElementById('channels');
channelsDiv.innerHTML = '';
for (let i = 0; i < 4; i++) {
const channelDiv = document.createElement('div');
channelDiv.className = 'channel';
channelDiv.innerHTML = `
<div class="channel-header">
<div class="channel-name ch${i}">Канал ${i + 1}</div>
<div class="channel-gpio">GPIO ${this.channelPins[i]}</div>
</div>
<div class="canvas-wrapper">
<canvas id="canvas${i}" width="1000" height="150"></canvas>
</div>
<div class="time-markers" id="markers${i}"></div>
`;
channelsDiv.appendChild(channelDiv);
const canvas = document.getElementById(`canvas${i}`);
canvas.width = 1000;
canvas.height = 150;
this.canvases.push(canvas);
this.contexts.push(canvas.getContext('2d'));
// Инициализация
this.contexts[i].fillStyle = '#0a0a0a';
this.contexts[i].fillRect(0, 0, canvas.width, canvas.height);
}
}
setupEventListeners() {
document.getElementById('startBtn').onclick = () => this.startSampling();
document.getElementById('stopBtn').onclick = () => this.stopSampling();
document.getElementById('timeScale').onchange = (e) => {
this.timeScale = parseFloat(e.target.value);
if (this.currentData[0].length > 0) {
this.drawAllWaveforms();
}
};
document.getElementById('sampleRate').onchange = (e) => {
this.sampleRate = parseInt(e.target.value);
};
}
connectWebSocket() {
this.ws = new WebSocket(`ws://${window.location.hostname}:81`);
this.ws.onopen = () => {
console.log('WebSocket connected');
this.isConnected = true;
this.updateStatus('Подключено', true);
};
this.ws.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
if (data.type === 'data') {
this.currentData = data.channels;
this.totalSamples = data.samples;
this.drawAllWaveforms();
} else if (data.type === 'status') {
this.updateStatus(data.message, true);
}
} catch (e) {
console.error('Parse error:', e);
}
};
this.ws.onclose = () => {
console.log('WebSocket disconnected');
this.isConnected = false;
this.updateStatus('Отключено, переподключение...', false);
setTimeout(() => this.connectWebSocket(), 1000);
};
this.ws.onerror = (error) => {
console.error('WebSocket error:', error);
this.updateStatus('Ошибка соединения', false);
};
}
updateStatus(message, isConnected) {
const statusDiv = document.getElementById('status');
const led = statusDiv.querySelector('.status-led');
statusDiv.querySelector('span:first-child').textContent = ` ${message}`;
if (isConnected) {
led.style.background = '#4caf50';
} else {
led.style.background = '#f44336';
}
}
startSampling() {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify({
command: 'start',
rate: this.sampleRate
}));
}
}
stopSampling() {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify({command: 'stop'}));
}
}
drawAllWaveforms() {
for (let ch = 0; ch < 4; ch++) {
if (this.currentData[ch] && this.currentData[ch].length > 0) {
this.drawWaveform(ch, this.currentData[ch]);
}
}
}
drawWaveform(channel, data) {
const canvas = this.canvases[channel];
const ctx = this.contexts[channel];
const width = canvas.width;
const height = canvas.height;
// Очистка
ctx.fillStyle = '#0a0a0a';
ctx.fillRect(0, 0, width, height);
if (!data || data.length === 0) return;
// Сетка
ctx.strokeStyle = '#1a1a1a';
ctx.lineWidth = 0.5;
// Горизонтальные линии
const midY = height / 2;
ctx.beginPath();
ctx.moveTo(0, midY);
ctx.lineTo(width, midY);
ctx.stroke();
// Вертикальные линии и маркеры времени
const totalTimeMs = (this.totalSamples / this.sampleRate) * 1000;
const numMarkers = Math.min(8, Math.floor(width / 80));
const markersDiv = document.getElementById(`markers${channel}`);
let markersHtml = '';
ctx.beginPath();
ctx.strokeStyle = '#1a1a1a';
for (let i = 0; i <= numMarkers; i++) {
const x = (i * width) / numMarkers;
ctx.moveTo(x, 0);
ctx.lineTo(x, height);
const timeMs = (i * totalTimeMs) / numMarkers;
markersHtml += `<div class="time-marker" style="width: ${width/numMarkers}px;">${timeMs.toFixed(1)}ms</div>`;
}
ctx.stroke();
markersDiv.innerHTML = markersHtml;
// Рисуем波形
const visibleDuration = this.timeScale * 1000; // ms
const visibleSamples = Math.min(
this.totalSamples,
Math.floor((visibleDuration / 1000) * this.sampleRate)
);
const samplesToShow = Math.min(visibleSamples, data.length);
const step = width / samplesToShow;
const startIndex = Math.max(0, data.length - samplesToShow);
ctx.beginPath();
ctx.strokeStyle = this.channelColors[channel];
ctx.lineWidth = 2;
let lastX = 0;
let lastY = data[startIndex] ? 10 : height - 10;
ctx.moveTo(lastX, lastY);
for (let i = 1; i < samplesToShow && (startIndex + i) < data.length; i++) {
const x = i * step;
const y = data[startIndex + i] ? 10 : height - 10;
if (Math.abs(y - lastY) > 0.1) {
ctx.lineTo(x, lastY);
ctx.lineTo(x, y);
} else {
ctx.lineTo(x, y);
}
lastY = y;
}
ctx.stroke();
// Подписи уровней
ctx.fillStyle = '#666';
ctx.font = '9px monospace';
ctx.fillText('HIGH', 5, 20);
ctx.fillText('LOW', 5, height - 5);
}
}
// Запуск приложения
window.addEventListener('DOMContentLoaded', () => {
new LogicAnalyzer();
});
</script>
</body>
</html>
)rawliteral";
return html;
}
void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length) {
switch(type) {
case WStype_DISCONNECTED:
Serial.printf("[%u] Отключен\n", num);
stopSampling();
break;
case WStype_CONNECTED:
Serial.printf("[%u] Подключен\n", num);
webSocket.sendTXT(num, "{\"type\":\"status\",\"message\":\"Готов к работе\"}");
break;
case WStype_TEXT:
{
StaticJsonDocument<256> doc;
DeserializationError error = deserializeJson(doc, payload);
if (!error) {
const char* command = doc["command"];
if (strcmp(command, "start") == 0) {
unsigned long newRate = doc["rate"];
if (newRate != sampleRate) {
stopSampling();
sampleRate = newRate;
}
startSampling();
Serial.printf("Начат сбор данных, частота: %lu Гц\n", sampleRate);
String statusMsg = "{\"type\":\"status\",\"message\":\"Сбор данных... " + String(sampleRate) + " Гц\"}";
webSocket.sendTXT(num, statusMsg);
}
else if (strcmp(command, "stop") == 0) {
stopSampling();
Serial.println("Сбор данных остановлен");
webSocket.sendTXT(num, "{\"type\":\"status\",\"message\":\"Остановлен\"}");
}
}
}
break;
}
}
void startSampling() {
if (samplingActive) return;
samplingActive = true;
bufferIndex = 0;
lastSampleTime = micros();
dataReady = false;
Serial.println("Sampling started");
}
void stopSampling() {
if (!samplingActive) return;
samplingActive = false;
if (bufferIndex > 0) {
sendData();
bufferIndex = 0;
}
Serial.println("Sampling stopped");
}
void IRAM_ATTR sampleData() {
if (!samplingActive) return;
if (bufferIndex >= MAX_BUFFER_SIZE) {
dataReady = true;
return;
}
uint8_t sample = 0;
sample |= (!digitalRead(CH1_PIN) << 0);
sample |= (!digitalRead(CH2_PIN) << 1);
sample |= (!digitalRead(CH3_PIN) << 2);
sample |= (!digitalRead(CH4_PIN) << 3);
logicBuffer[bufferIndex++] = sample;
}
void sendData() {
if (bufferIndex == 0) return;
StaticJsonDocument<JSON_OBJECT_SIZE(4) + MAX_BUFFER_SIZE * 2> doc;
doc["type"] = "data";
doc["samples"] = bufferIndex;
JsonArray channels = doc.createNestedArray("channels");
for (int ch = 0; ch < 4; ch++) {
JsonArray channelData = channels.createNestedArray();
for (int i = 0; i < bufferIndex; i++) {
channelData.add((logicBuffer[i] >> ch) & 1);
}
}
String output;
serializeJson(doc, output);
webSocket.broadcastTXT(output);
bufferIndex = 0;
}
void loop() {
server.handleClient();
webSocket.loop();
if (dataReady) {
dataReady = false;
sendData();
}
if (samplingActive) {
unsigned long now = micros();
unsigned long interval = 1000000 / sampleRate;
if (now - lastSampleTime >= interval) {
lastSampleTime = now;
sampleData();
}
}
// Небольшая задержка для стабильности
delay(1);
}