const assert = require('node:assert/strict'); const fs = require('node:fs'); const os = require('node:os'); const path = require('node:path'); const test = require('node:test'); const temporaryRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'photobioreactor-')); const temporaryLogs = path.join(temporaryRoot, 'logs'); const temporaryData = path.join(temporaryRoot, 'data'); const temporaryRuntime = path.join(temporaryRoot, 'runtime.json'); fs.mkdirSync(temporaryLogs, { recursive: true }); fs.mkdirSync(temporaryData, { recursive: true }); process.env.LOGS_DIRECTORY = temporaryLogs; process.env.DATA_DIRECTORY = temporaryData; process.env.RUNTIME_CONFIG_FILE = temporaryRuntime; process.env.EZO_MODE = 'demo'; const { app, HISTORY_FILES } = require('../api/server'); const { collectReadings, publishReading } = require('../api/acquisition-service'); let server; let baseUrl; test.before(async () => { await new Promise((resolve) => { server = app.listen(0, '127.0.0.1', resolve); }); const address = server.address(); baseUrl = `http://127.0.0.1:${address.port}`; }); test.after(async () => { await new Promise((resolve, reject) => { server.close((error) => error ? reject(error) : resolve()); }); fs.rmSync(temporaryRoot, { recursive: true, force: true }); }); test('returns real CSV history for all sensors', async () => { fs.writeFileSync( path.join(temporaryLogs, 'temperature.csv'), 'timestamp,value\n2026-06-22T12:00:00.000Z,25.1\n' ); fs.writeFileSync( path.join(temporaryLogs, 'ph.csv'), 'timestamp,value\n2026-06-22T12:00:00.000Z,7.2\n' ); fs.writeFileSync(path.join(temporaryLogs, 'do.csv'), 'timestamp,value\n'); fs.writeFileSync(path.join(temporaryLogs, 'ec.csv'), 'timestamp,value\n'); const response = await fetch(`${baseUrl}/api/sensors/all`); const data = await response.json(); assert.equal(response.status, 200); assert.equal(data.length, 2); assert.ok(data[0].Timestamp); assert.ok(data[0].Sensor); assert.equal(typeof data[0].Valor, 'number'); }); test('all history export respects enabled sensors', async () => { fs.writeFileSync( path.join(temporaryLogs, 'temperature.csv'), 'timestamp,value\n2026-06-22T12:00:00.000Z,25.1\n' ); fs.writeFileSync( path.join(temporaryLogs, 'ph.csv'), 'timestamp,value\n2026-06-22T12:00:00.000Z,7.2\n' ); fs.writeFileSync(path.join(temporaryLogs, 'do.csv'), 'timestamp,value\n'); fs.writeFileSync(path.join(temporaryLogs, 'ec.csv'), 'timestamp,value\n'); await fetch(`${baseUrl}/api/config/runtime`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ rate: 1, enabledSensors: ['temperature'] }) }); const response = await fetch(`${baseUrl}/api/sensors/all`); const data = await response.json(); assert.equal(response.status, 200); assert.equal(data.length, 1); assert.equal(data[0].Sensor, 'RTD'); }); test('serves the dashboard in local development mode', async () => { const response = await fetch(`${baseUrl}/`); const html = await response.text(); assert.equal(response.status, 200); assert.match(html, /Panel del Fotobiorreactor/); }); test('validates sensor commands', async () => { const invalidResponse = await fetch(`${baseUrl}/api/sensors/invalid/command`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ command: 'r' }) }); assert.equal(invalidResponse.status, 400); const validResponse = await fetch(`${baseUrl}/api/sensors/ph/command`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ command: 'r' }) }); const validData = await validResponse.json(); assert.equal(validResponse.status, 200); assert.equal(validData.success, true); assert.equal(validData.mode, 'demo'); }); test('rejects undocumented calibration syntax', async () => { const response = await fetch(`${baseUrl}/api/sensors/do/command`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ command: 'Cal,atm' }) }); const data = await response.json(); assert.equal(response.status, 400); assert.match(data.error, /documentados/); }); test('persists logging rates used by acquisition', async () => { const invalidResponse = await fetch(`${baseUrl}/api/config/logging`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ rate: 3 }) }); assert.equal(invalidResponse.status, 400); const validResponse = await fetch(`${baseUrl}/api/config/logging`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ rate: 5 }) }); const validData = await validResponse.json(); assert.equal(validResponse.status, 200); assert.equal(validData.rate, 5); const readResponse = await fetch(`${baseUrl}/api/config/logging`); const readData = await readResponse.json(); assert.equal(readData.rate, 5); assert.equal(JSON.parse(fs.readFileSync(temporaryRuntime)).loggingRateSeconds, 5); }); test('persists enabled sensors used by acquisition', async () => { const response = await fetch(`${baseUrl}/api/config/runtime`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ rate: 1, enabledSensors: ['temperature'] }) }); const data = await response.json(); assert.equal(response.status, 200); assert.deepEqual(data.enabledSensors, ['temperature']); const readResponse = await fetch(`${baseUrl}/api/config/runtime`); const readData = await readResponse.json(); assert.deepEqual(readData.enabledSensors, ['temperature']); }); test('rejects empty enabled sensor configuration', async () => { const response = await fetch(`${baseUrl}/api/config/runtime`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ rate: 1, enabledSensors: [] }) }); assert.equal(response.status, 400); }); test('demo acquisition writes live JSON and CSV files', async () => { await fetch(`${baseUrl}/api/config/runtime`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ rate: 1, enabledSensors: ['temperature', 'ph', 'do', 'ec'] }) }); const result = await collectReadings(); assert.equal(result.mode, 'demo'); for (const file of ['EZORTD.json', 'EZOPH.json', 'EZODO.json', 'EZOEC.json']) { const data = JSON.parse(fs.readFileSync(path.join(temporaryData, file))); assert.equal(data.online, true); assert.ok(data.timestamp); } for (const file of ['temperature.csv', 'ph.csv', 'do.csv', 'ec.csv']) { assert.match( fs.readFileSync(path.join(temporaryLogs, file), 'utf8'), /^timestamp,value/m ); } }); test('disabled sensors are published as disabled without CSV rows', async () => { await fetch(`${baseUrl}/api/config/runtime`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ rate: 1, enabledSensors: ['temperature'] }) }); fs.rmSync(path.join(temporaryLogs, 'ph.csv'), { force: true }); const result = await collectReadings(); const phData = JSON.parse(fs.readFileSync(path.join(temporaryData, 'EZOPH.json'))); assert.equal(result.results.find((item) => item.sensorId === 'ph').disabled, true); assert.equal(phData.disabled, true); assert.equal(fs.existsSync(path.join(temporaryLogs, 'ph.csv')), false); }); test('hardware null readings are marked offline and not appended as zero', async () => { const timestamp = new Date().toISOString(); const csvPath = path.join(temporaryLogs, 'ph.csv'); fs.rmSync(csvPath, { force: true }); const online = await publishReading('ph', null, timestamp, 'hardware'); const data = JSON.parse(fs.readFileSync(path.join(temporaryData, 'EZOPH.json'))); assert.equal(online, false); assert.equal(data.online, false); assert.equal(data.error, 'Lectura no disponible'); assert.equal(fs.existsSync(csvPath), false); }); test('clears historical CSV files and preserves headers', async () => { for (const name of Object.keys(HISTORY_FILES)) { fs.writeFileSync(path.join(temporaryLogs, `${name}.csv`), 'old,data\n1,2\n'); } const response = await fetch(`${baseUrl}/api/history/clear`, { method: 'POST' }); assert.equal(response.status, 200); for (const [name, header] of Object.entries(HISTORY_FILES)) { const content = fs.readFileSync( path.join(temporaryLogs, `${name}.csv`), 'utf8' ); assert.equal(content, header); } });