Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 | 14x 14x 225x 225x 225x 11x 11x 11x 225x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 65x 69x 20x 20x 74x 74x 74x 74x 338x 19x 19x 93x 3x 3x 3x 87x 87x 87x 87x 87x 87x 87x 87x 87x 74x 74x 74x 74x 74x 74x 87x 87x 87x 87x 87x 87x 87x 79x 79x 79x 79x 79x 79x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 17x 17x 251x 251x 1x 1x 250x 250x 250x 35x 35x 35x 35x 35x 35x 29x 6x 35x 35x 12x 12x 65x 58x 56x 8x 8x 48x 9x 9x 10x 9x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 65x 58x 58x 40x 40x 40x 36705x 135x 135x 135x 135x 135x 135x 135x 135x 30x 30x 93x 93x 93x 93x 93x 93x 93x 93x 93x 32x 37x 37x 37x 37x 37x 225x 161x 37x 37x 37x 37x 37x 267x 522x 43x | // registry-manager.ts
// Manages I/O Registry for Arduino pin states with debouncing and change detection
import type { IOPinRecord } from "@shared/schema";
import type { PinStateBatcher } from "./pin-state-batcher";
import type { SerialOutputBatcher, SerialOutputTelemetry } from "./serial-output-batcher";
import { Logger } from "@shared/logger";
import { appendFileSync } from "fs";
import { join } from "path";
export interface RegistryUpdateCallback {
(registry: IOPinRecord[], baudrate: number | undefined, reason?: string): void;
}
export interface PerformanceMetrics {
timestamp: number;
intendedPinChangesPerSecond: number;
actualPinChangesPerSecond: number;
droppedPinChangesPerSecond: number;
batchesPerSecond: number;
avgStatesPerBatch: number;
serialOutputPerSecond: number;
serialBytesPerSecond: number;
serialBytesTotal: number;
serialIntendedBytesPerSecond: number;
serialDroppedBytesPerSecond: number;
}
export interface TelemetryUpdateCallback {
(metrics: PerformanceMetrics): void;
}
export interface RegistryManagerConfig {
onUpdate?: RegistryUpdateCallback;
onTelemetry?: TelemetryUpdateCallback;
enableTelemetry?: boolean;
}
/**
* Helper to clean up pin record by removing line: 0 from usedAt/definedAt
*/
function cleanupPinRecord(pin: IOPinRecord): IOPinRecord {
const cleaned = { ...pin };
// Remove definedAt if line is 0
Iif (cleaned.definedAt?.line === 0) {
delete (cleaned as any).definedAt;
}
// Filter out usedAt entries with line: 0
if (cleaned.usedAt && cleaned.usedAt.length > 0) {
cleaned.usedAt = cleaned.usedAt.filter(entry => entry.line !== 0);
// Remove usedAt entirely if empty
Eif (cleaned.usedAt.length === 0) {
delete (cleaned as any).usedAt;
}
}
return cleaned;
}
/**
* RegistryManager handles the collection and management of Arduino pin states.
* It provides debouncing to minimize WebSocket traffic and change detection
* to avoid sending duplicate registry data.
*/
export class RegistryManager {
private registry: IOPinRecord[] = [];
private isCollecting = false;
private registryHash = "";
private debounceTimer: NodeJS.Timeout | null = null;
private waitTimer: NodeJS.Timeout | null = null;
private heartbeatInterval: NodeJS.Timeout | null = null;
private waitingForRegistry = false;
private isDirty = false;
private baudrate: number | undefined = undefined; // undefined = Serial.begin() not found in code
private destroyed = false; // Prevent logging after destruction
private readonly logger = new Logger("RegistryManager");
private readonly onUpdateCallback?: RegistryUpdateCallback;
private readonly onTelemetryCallback?: TelemetryUpdateCallback;
private readonly enableTelemetry: boolean;
private pinStateBatcher: PinStateBatcher | null = null; // Reference to PinStateBatcher for telemetry
private serialOutputBatcher: SerialOutputBatcher | null = null; // Reference to SerialOutputBatcher for telemetry
// Telemetry tracking
private telemetry = {
incomingEvents: 0,
sentBatches: 0,
serialOutputEvents: 0, // track serial output events
serialOutputBytes: 0, // bytes in current interval
serialOutputBytesTotal: 0, // cumulative bytes since start
lastReportTime: Date.now(),
};
constructor(config: RegistryManagerConfig = {}) {
this.onUpdateCallback = config.onUpdate;
this.onTelemetryCallback = config.onTelemetry;
this.enableTelemetry = config.enableTelemetry ?? false;
// Telemetry heartbeat starts only when simulation is running
}
/**
* Set reference to PinStateBatcher for telemetry tracking
*/
setPinStateBatcher(batcher: PinStateBatcher | null): void {
this.pinStateBatcher = batcher;
}
/**
* Set reference to SerialOutputBatcher for telemetry tracking
*/
setSerialOutputBatcher(batcher: SerialOutputBatcher | null): void {
this.serialOutputBatcher = batcher;
}
/**
* Start 1-second heartbeat for telemetry reporting
*/
private startHeartbeat(): void {
Iif (this.heartbeatInterval) return;
this.heartbeatInterval = setInterval(() => {
Eif (!this.destroyed) {
const metrics = this.getPerformanceMetrics();
Eif (this.onTelemetryCallback) {
this.onTelemetryCallback(metrics);
}
}
}, 1000);
}
/**
* Stop telemetry heartbeat and clear interval
*/
private stopTelemetry(): void {
if (this.heartbeatInterval) {
clearInterval(this.heartbeatInterval);
this.heartbeatInterval = null;
}
}
/**
* Pause telemetry heartbeat (called when simulation is paused)
* Stops sending telemetry data while paused
*/
pauseTelemetry(): void {
this.stopTelemetry();
}
/**
* Resume telemetry heartbeat (called when simulation is resumed)
* Resets counters and restarts the heartbeat
*/
resumeTelemetry(): void {
Eif (this.onTelemetryCallback && this.enableTelemetry) {
// Reset timestamp for fresh start after pause
this.telemetry.lastReportTime = Date.now();
this.startHeartbeat();
}
}
/**
* Calculate and return current performance metrics
*/
private getPerformanceMetrics(): PerformanceMetrics {
const now = Date.now();
const timeElapsedMs = now - this.telemetry.lastReportTime;
const timeElapsedSec = timeElapsedMs / 1000;
// Get pin change telemetry from PinStateBatcher
let intendedPinChangesPerSecond = 0;
let actualPinChangesPerSecond = 0;
let droppedPinChangesPerSecond = 0;
let batchesPerSecond = 0;
let avgStatesPerBatch = 0;
if (this.pinStateBatcher) {
const batcherTelemetry = this.pinStateBatcher.getTelemetryAndReset();
intendedPinChangesPerSecond = timeElapsedSec > 0
? Math.round((batcherTelemetry.intended / timeElapsedSec) * 10) / 10
: 0;
actualPinChangesPerSecond = timeElapsedSec > 0
? Math.round((batcherTelemetry.actual / timeElapsedSec) * 10) / 10
: 0;
droppedPinChangesPerSecond = intendedPinChangesPerSecond - actualPinChangesPerSecond;
batchesPerSecond = timeElapsedSec > 0
? Math.round((batcherTelemetry.batches / timeElapsedSec) * 10) / 10
: 0;
avgStatesPerBatch = batcherTelemetry.batches > 0
? Math.round((batcherTelemetry.actual / batcherTelemetry.batches) * 10) / 10
: 0;
}
// Get serial output telemetry from SerialOutputBatcher
let serialOutputPerSecond = 0;
let serialBytesPerSecond = 0;
let serialIntendedBytesPerSecond = 0;
let serialDroppedBytesPerSecond = 0;
let serialBytesTotal = this.telemetry.serialOutputBytesTotal; // Fallback for no batcher
let batcherTelemetry: SerialOutputTelemetry | null = null;
if (this.serialOutputBatcher) {
batcherTelemetry = this.serialOutputBatcher.getTelemetryAndReset();
// Serial events = number of chunks sent (batch outputs)
serialOutputPerSecond = timeElapsedSec > 0
? Math.round((batcherTelemetry.chunks / timeElapsedSec) * 10) / 10
: 0;
// Serial bytes = actual bytes sent after rate limiting
serialBytesPerSecond = timeElapsedSec > 0
? Math.round((batcherTelemetry.actual / timeElapsedSec) * 10) / 10
: 0;
// Intended bytes = total bytes enqueued (before drops)
serialIntendedBytesPerSecond = timeElapsedSec > 0
? Math.round((batcherTelemetry.intended / timeElapsedSec) * 10) / 10
: 0;
// Dropped bytes per second
serialDroppedBytesPerSecond = timeElapsedSec > 0
? Math.round((batcherTelemetry.dropped / timeElapsedSec) * 10) / 10
: 0;
// Total bytes from batcher (cumulative, never reset)
serialBytesTotal = batcherTelemetry.totalBytes;
}
const metrics: PerformanceMetrics = {
timestamp: now,
intendedPinChangesPerSecond,
actualPinChangesPerSecond,
droppedPinChangesPerSecond,
batchesPerSecond,
avgStatesPerBatch,
serialOutputPerSecond,
serialBytesPerSecond,
serialBytesTotal, // Now from SerialOutputBatcher
serialIntendedBytesPerSecond,
serialDroppedBytesPerSecond,
};
// Reset counters for next period
this.telemetry.incomingEvents = 0;
this.telemetry.sentBatches = 0;
this.telemetry.serialOutputEvents = 0;
this.telemetry.serialOutputBytes = 0;
this.telemetry.lastReportTime = now;
Eif (!this.destroyed) {
this.logger.debug(
`Telemetry: intended: ${intendedPinChangesPerSecond} pin/s, actual: ${actualPinChangesPerSecond} pin/s (dropped: ${droppedPinChangesPerSecond}), ${batchesPerSecond} bat/s, ${avgStatesPerBatch} st/bat, ${serialOutputPerSecond} serial/s, SERIAL: intended=${batcherTelemetry?.intended ?? 0} bytes, actual=${batcherTelemetry?.actual ?? 0} bytes, dropped=${batcherTelemetry?.dropped ?? 0} bytes (${serialDroppedBytesPerSecond} B/s)`,
);
Iif (process.env.NODE_ENV !== "test" && !process.env.VITEST) {
// DEBUG: Write telemetry to file for inspection
try {
const debugPath = join(process.cwd(), "temp", "telemetry-debug.jsonl");
const debugLine = JSON.stringify({
timestamp: new Date(now).toISOString(),
serial: {
outputPerSec: serialOutputPerSecond,
bytesPerSec: serialBytesPerSecond,
intendedPerSec: serialIntendedBytesPerSecond,
intendedBytes: batcherTelemetry?.intended ?? 0,
actualBytes: batcherTelemetry?.actual ?? 0,
droppedBytes: batcherTelemetry?.dropped ?? 0,
droppedPerSec: serialDroppedBytesPerSecond,
bytesTotal: serialBytesTotal,
},
}) + "\n";
appendFileSync(debugPath, debugLine);
} catch {
// Silently ignore file write errors
}
}
}
return metrics;
}
/**
* Start collecting registry data (called when [[IO_REGISTRY_START]] marker is received)
*
* NEW: Implements "Initial Sync Flush" to ensure any runtime pin definitions (e.g., from updatePinMode)
* are sent to clients before the registry is cleared. This prevents losing pin definitions that arrive
* before the IO_REGISTRY_START marker.
*/
startCollection(): void {
Iif (this.destroyed) return;
// Collection start (not logged individually — too noisy).
// ROBUSTNESS: Flush current registry state before clearing
// This ensures any pins added via updatePinMode before IO_REGISTRY_START marker are sent
Iif (this.registry.length > 0 && this.isDirty) {
const hasDefinedPins = this.registry.some((p) => p.defined);
if (hasDefinedPins) {
this.logger.info(
`Initial Sync Flush: Sending ${this.registry.length} pins before clearing for new collection`,
);
const preCollectionHash = this.computeRegistryHash();
this.sendNow(preCollectionHash, "pre-collection-flush");
}
}
this.isCollecting = true;
this.registry = [];
// Reset telemetry counters and restart heartbeat
this.telemetry.incomingEvents = 0;
this.telemetry.sentBatches = 0;
this.telemetry.serialOutputEvents = 0;
this.telemetry.serialOutputBytes = 0;
this.telemetry.serialOutputBytesTotal = 0;
this.telemetry.lastReportTime = Date.now();
if (this.onTelemetryCallback && this.enableTelemetry) {
this.stopTelemetry(); // Clear any previous heartbeat
this.startHeartbeat();
}
}
/**
* Add a pin record to the registry (called for each [[IO_PIN:...]] marker)
*/
addPin(pinRecord: IOPinRecord): void {
Iif (this.destroyed) return;
if (!this.isCollecting) {
this.logger.warn("Received pin record while not collecting - ignoring");
return;
}
// Individual pin additions are not logged (20 per start is too noisy).
this.registry.push(pinRecord);
this.isDirty = true;
this.telemetry.incomingEvents++;
}
/**
* Finish collecting and send registry immediately (called when [[IO_REGISTRY_END]] marker is received)
* Structural changes (new pins discovered) must reach UI immediately, not throttled.
*/
finishCollection(): void {
Iif (this.destroyed) return;
this.logger.debug(
`Registry collection complete: ${this.registry.length} pins`,
);
this.isCollecting = false;
this.isDirty = true;
const nextHash = this.computeRegistryHash();
if (nextHash !== this.registryHash) {
this.sendNow(nextHash, "collection-complete");
} else {
this.isDirty = false;
}
this.waitingForRegistry = false;
if (this.waitTimer) {
clearTimeout(this.waitTimer);
this.waitTimer = null;
}
}
/**
* Set the baudrate (parsed from Serial.begin() in user code)
* Only set if baudrate is explicitly defined in the code (not default 9600)
*/
setBaudrate(baudrate: number): void {
if (this.destroyed) return;
if (baudrate > 0) {
// Only set if non-default (not 9600)
// This ensures we know that Serial.begin() was actually in the code
if (baudrate !== 9600) {
this.logger.debug(`Baudrate from Serial.begin(): ${baudrate}`);
this.baudrate = baudrate;
} else {
// Default 9600 might mean Serial.begin() wasn't in the code
// Leave as undefined so we don't send a false positive
this.logger.debug(`Serial.begin(9600) - not sending default bandrate`);
}
}
}
/**
* Update a pin's mode at runtime (called when [[PIN_MODE:pin:mode]] is received)
*/
updatePinMode(pin: number, mode: number): void {
Iif (this.destroyed) return;
const pinStr = pin >= 14 && pin <= 19 ? `A${pin - 14}` : String(pin);
const existing = this.registry.find((p) => p.pin === pinStr);
this.logger.debug(
`updatePinMode: pin=${pin} (${pinStr}), mode=${mode}, existing=${!!existing}, wasDefinedBefore=${existing?.defined || false}`,
);
if (existing) {
const wasDefinedBefore = existing.defined;
existing.pinMode = mode;
existing.defined = true;
// Track pinMode operation in usedAt
const pinModeOp = `pinMode:${mode}`;
Iif (!existing.usedAt) existing.usedAt = [];
const alreadyTracked = existing.usedAt.some(
(u) => u.operation === pinModeOp,
);
Eif (!alreadyTracked) {
existing.usedAt.push({ line: 0, operation: pinModeOp });
}
this.telemetry.incomingEvents++;
// Structural changes (defined: false -> true) must be sent immediately.
// If the pin was already defined, do not re-send the registry.
Iif (!wasDefinedBefore) {
this.logger.debug(
`Structural change: pin ${pinStr} marked as defined, sending immediately`,
);
this.logger.info(
`Registry send trigger: first-time pin use ${pinStr} (pinMode:${mode})`,
);
const nextHash = this.computeRegistryHash();
this.sendNow(nextHash, "pin-defined-changed");
}
} else {
// Create new pin record if not yet in registry
this.registry.push({
pin: pinStr,
defined: true,
pinMode: mode,
usedAt: [{ line: 0, operation: `pinMode:${mode}` }],
});
this.isDirty = true;
this.telemetry.incomingEvents++;
this.logger.debug(
`New pin record created: ${pinStr} with mode=${mode}, sending immediately`,
);
const nextHash = this.computeRegistryHash();
this.sendNow(nextHash, "pin-new-record");
}
}
/**
* Track a serial output event (called when serial data is sent)
*/
trackSerialOutput(bytes: number = 0): void {
if (this.destroyed) return;
this.telemetry.serialOutputEvents++;
this.telemetry.serialOutputBytes += bytes;
this.telemetry.serialOutputBytesTotal += bytes;
}
/**
* Enable message queuing until first registry is sent
*/
enableWaitMode(timeoutMs: number = 1500): void {
if (this.destroyed) return;
this.waitingForRegistry = true;
// Set fallback timer to release queue if registry never arrives
this.waitTimer = setTimeout(() => {
Eif (this.waitingForRegistry) {
this.logger.warn("Registry wait timeout - releasing queue");
this.waitingForRegistry = false;
}
}, timeoutMs);
}
/**
* Check if manager is currently waiting for first registry
*/
isWaiting(): boolean {
return this.waitingForRegistry;
}
/**
* Reset the manager state (called when simulation stops)
*/
reset(): void {
this.registry = [];
this.isCollecting = false;
this.registryHash = "";
this.waitingForRegistry = false;
this.isDirty = false;
this.stopTelemetry();
Iif (this.debounceTimer) {
clearTimeout(this.debounceTimer);
this.debounceTimer = null;
}
if (this.waitTimer) {
clearTimeout(this.waitTimer);
this.waitTimer = null;
}
// Reset complete (not logged — happens on every stop/start cycle).
}
/**
* Destroy the manager and prevent any further logging or callbacks
* This is called during test teardown to prevent "log after tests are done" errors
*/
destroy(): void {
this.destroyed = true;
// Clear all timers immediately
Iif (this.debounceTimer) {
clearTimeout(this.debounceTimer);
this.debounceTimer = null;
}
Iif (this.waitTimer) {
clearTimeout(this.waitTimer);
this.waitTimer = null;
}
this.stopTelemetry();
// Reset state without logging
this.registry = [];
this.isCollecting = false;
this.registryHash = "";
this.waitingForRegistry = false;
this.isDirty = false;
}
/**
* Get current registry snapshot
*/
getRegistry(): readonly IOPinRecord[] {
return [...this.registry];
}
/**
* Immediately send the registry via callback
* Cancels any pending throttle timer to ensure structural changes reach UI immediately
*/
private sendNow(hash: string, reason?: string): void {
// Cancel any pending throttle timer to ensure immediate send
Iif (this.debounceTimer) {
clearTimeout(this.debounceTimer);
this.debounceTimer = null;
}
this.registryHash = hash;
this.isDirty = false;
this.telemetry.sentBatches++;
Eif (this.onUpdateCallback) {
// Enhanced logging: show which pins are being sent, especially pin 13
const pinsList = this.registry.map((p) => `${p.pin}(def=${p.defined})`).join(",");
const hasPin13 = this.registry.some((p) => p.pin === "13");
Eif (reason && !this.destroyed) {
const baudInfo = this.baudrate !== undefined ? ` | baud=${this.baudrate}` : " | baud=not-defined";
this.logger.info(
`📤 Registry SEND [${reason}]: ${this.registry.length} pins [${pinsList}]${baudInfo} ${hasPin13 ? "✅ PIN13_INCLUDED" : "❌ NO_PIN13"}`,
);
}
// Clean up registry to remove useless line: 0 entries
const cleanedRegistry = this.registry.map(cleanupPinRecord);
// Only send baudrate if it was actually defined in the code
this.onUpdateCallback(cleanedRegistry, this.baudrate, reason);
}
}
private computeRegistryHash(): string {
const normalized = this.registry.map((pin) => ({
pin: pin.pin,
defined: pin.defined,
pinMode: pin.pinMode,
usedAt: pin.usedAt ? [...pin.usedAt] : [],
}));
normalized.sort((a, b) => a.pin.localeCompare(b.pin));
return JSON.stringify(normalized);
}
/**
* Legacy hash calculation removed in favor of isDirty flag
*/
}
|