test
This commit is contained in:
parent
89b089df93
commit
4a5f9f4575
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
|
||||
firmware/logic_analyzer/root_html.h
|
||||
40
assets/root.html
Normal file
40
assets/root.html
Normal file
@ -0,0 +1,40 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset='UTF-8'>";
|
||||
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
|
||||
<title>Logic Analyzer</title>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
function connectWebSocket() {
|
||||
ws = new WebSocket('ws://' + window.location.hostname + ':81');
|
||||
|
||||
ws.onopen = function() {
|
||||
console.log('WebSocket connected');
|
||||
updateStatus('Подключено');
|
||||
};
|
||||
|
||||
ws.onmessage = function(event) {
|
||||
const data = JSON.parse(event.data);
|
||||
if (data.type === 'data') {
|
||||
currentData = data.channels;
|
||||
currentSamples = data.samples;
|
||||
drawAllWaveforms();
|
||||
} else if (data.type === 'status') {
|
||||
updateStatus(data.message);
|
||||
}
|
||||
};
|
||||
|
||||
ws.onclose = function() {
|
||||
console.log('WebSocket disconnected');
|
||||
updateStatus('Отключено. Переподключение...');
|
||||
setTimeout(connectWebSocket, 1000);
|
||||
};
|
||||
}
|
||||
170
firmware/logic_analyzer/logic_analyzer.ino
Normal file
170
firmware/logic_analyzer/logic_analyzer.ino
Normal file
@ -0,0 +1,170 @@
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ESP8266WebServer.h>
|
||||
#include <WebSocketsServer.h>
|
||||
#include <ArduinoJson.h>
|
||||
|
||||
#include "root_html.h"
|
||||
|
||||
#define CH1_PIN D0
|
||||
#define CH2_PIN D1
|
||||
#define CH3_PIN D2
|
||||
#define CH4_PIN D5
|
||||
#define CH5_PIN D6
|
||||
#define CH6_PIN D7
|
||||
|
||||
#define WIFI_AP_SSID "ESP8266_LogicAnalyzer"
|
||||
#define WIFI_AP_PASS "12345678"
|
||||
|
||||
#define WEBSERVER_PORT 80
|
||||
#define WEBSOCKET_PORT 81
|
||||
|
||||
|
||||
const uint8_t PINS[] = {
|
||||
CH1_PIN, CH2_PIN, CH3_PIN,
|
||||
CH4_PIN, CH5_PIN, CH6_PIN,
|
||||
};
|
||||
|
||||
volatile bool g_sample_active = false;
|
||||
|
||||
ESP8266WebServer server(WEBSERVER_PORT);
|
||||
WebSocketsServer webSocket = WebSocketsServer(WEBSOCKET_PORT);
|
||||
|
||||
|
||||
typedef union {
|
||||
unsigned char mask;
|
||||
struct {
|
||||
unsigned a0:1;
|
||||
unsigned a1:1;
|
||||
unsigned a2:1;
|
||||
unsigned a3:1;
|
||||
unsigned a4:1;
|
||||
unsigned a5:1;
|
||||
unsigned a6:1;
|
||||
unsigned a7:1;
|
||||
} byte;
|
||||
} Sample;
|
||||
|
||||
#define SAMPLES_BUFFER_CAP 64
|
||||
Sample SAMPLES[SAMPLES_BUFFER_CAP] = {};
|
||||
volatile uint8_t g_samples_idx = 0;
|
||||
|
||||
|
||||
Sample takeSample() {
|
||||
Sample data;
|
||||
data.mask = 0;
|
||||
|
||||
int pins_len = sizeof(PINS) / sizeof(PINS[0]);
|
||||
|
||||
for (uint8_t i = 0; i < pins_len; ++i) {
|
||||
data.mask |= (!(!digitalRead(PINS[i])) << i);
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
void SerialSendPins(Sample ps) {
|
||||
Serial.print("0b");
|
||||
Serial.println(ps.mask, BIN);
|
||||
}
|
||||
|
||||
void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length) {
|
||||
switch(type) {
|
||||
case WStype_DISCONNECTED:
|
||||
stopSampling();
|
||||
break;
|
||||
|
||||
case WStype_CONNECTED:
|
||||
startSampling();
|
||||
webSocket.sendTXT(num, "{\"type\":\"status\",\"message\":\"Connected\"}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void startSampling() {
|
||||
g_sample_active = true;
|
||||
}
|
||||
|
||||
void stopSampling() {
|
||||
g_sample_active = false;
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
|
||||
int pins_len = sizeof(PINS) / sizeof(PINS[0]);
|
||||
|
||||
for (uint8_t i = 0; i < pins_len; ++i) {
|
||||
pinMode(PINS[i], INPUT);
|
||||
}
|
||||
|
||||
WiFi.softAP(WIFI_AP_SSID, WIFI_AP_PASS);
|
||||
Serial.print("IP: ");
|
||||
Serial.println(WiFi.softAPIP());
|
||||
|
||||
setupWebServer();
|
||||
webSocket.begin();
|
||||
webSocket.onEvent(webSocketEvent);
|
||||
|
||||
server.begin();
|
||||
Serial.println("Ready");
|
||||
}
|
||||
|
||||
void setupWebServer() {
|
||||
server.on("/", rootHandler);
|
||||
}
|
||||
|
||||
void rootHandler() {
|
||||
server.send(200, "text/html", assets_root_html, assets_root_html_len);
|
||||
}
|
||||
|
||||
void appendSamples() {
|
||||
if (!g_sample_active) return;
|
||||
|
||||
static unsigned long lastTime = 0;
|
||||
unsigned long now = micros();
|
||||
unsigned long interval_mks = 100;
|
||||
|
||||
if (now - lastTime < interval_mks) return;
|
||||
|
||||
lastTime = now;
|
||||
|
||||
if (g_samples_idx == SAMPLES_BUFFER_CAP - 1) return;
|
||||
|
||||
SAMPLES[g_samples_idx] = takeSample();
|
||||
g_samples_idx++;
|
||||
}
|
||||
|
||||
void websocketSendSamples() {
|
||||
if (g_samples_idx != SAMPLES_BUFFER_CAP - 1) return;
|
||||
|
||||
static unsigned long lastTime = 0;
|
||||
unsigned long now = millis();
|
||||
|
||||
unsigned long interval_ms = 100;
|
||||
|
||||
if (now - lastTime < interval_ms) return;
|
||||
|
||||
lastTime = now;
|
||||
|
||||
// конвертировать SAMPLES в json
|
||||
String output = "{\"type\":\"data\",\"len\":" + String(SAMPLES_BUFFER_CAP) + ",\"data\":[";
|
||||
for (int i = 0; i < SAMPLES_BUFFER_CAP; ++i) {
|
||||
output += String(SAMPLES[i].mask);
|
||||
if (i < SAMPLES_BUFFER_CAP - 1) output += ",";
|
||||
}
|
||||
output += "]}";
|
||||
|
||||
webSocket.broadcastTXT(output);
|
||||
|
||||
g_samples_idx = 0;
|
||||
}
|
||||
|
||||
void loop() {
|
||||
server.handleClient();
|
||||
webSocket.loop();
|
||||
|
||||
appendSamples();
|
||||
websocketSendSamples();
|
||||
|
||||
delay(1);
|
||||
}
|
||||
12
justfile
12
justfile
@ -1,9 +1,19 @@
|
||||
alias compile := build
|
||||
#!/usr/bin/env -S just --justfile
|
||||
|
||||
alias compile := build
|
||||
build:
|
||||
#!/bin/sh
|
||||
xxd -i assets/root.html > firmware/logic_analyzer/root_html.h
|
||||
cd firmware/logic_analyzer
|
||||
arduino-cli compile --fqbn esp8266:esp8266:nodemcuv2
|
||||
|
||||
|
||||
alias flash := upload
|
||||
|
||||
[working-directory: 'firmware/logic_analyzer']
|
||||
upload:
|
||||
arduino-cli upload --fqbn esp8266:esp8266:nodemcuv2 --port /dev/ttyUSB0
|
||||
|
||||
|
||||
monitor:
|
||||
arduino-cli monitor --port /dev/ttyUSB0
|
||||
|
||||
@ -1,733 +0,0 @@
|
||||
#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);
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user