Files
2026-07-29 15:02:58 +07:00

564 lines
19 KiB
TypeScript

import { IOT_DASHBOARD_IOT_API_BASE, IOT_FLOCKS_API_URL } from './constants.tsx';
import {
averageInsideTempCelsiusFromSensors,
humidityPercentFromSensors,
luxValueFromSensors,
} from './computeDashboard.ts';
import { celsiusFromHistoryTempField } from './format.ts';
import {
deviceKeyFromHistoryMetric,
isHvacHistoryMetric,
type IotDeviceHistoryMetric,
} from './deviceHistoryUtils.ts';
import {
deviceKeyFromFanNumber,
fanNumberFromMetric,
isFanHistoryMetric,
} from './fanHistoryUtils.ts';
import { fanTargetCelsiusFromSnapshot, type SetpointSnapshotData } from './fan1SetpointResolve.ts';
import { hvacSetpointFromSnapshot, type HvacDeviceKey } from './hvacSetpointResolve.ts';
import { preprocessFlockPayloadForPanel } from './preprocessFlockPayload.ts';
import type {
IotDeviceHistoryPoint,
IotFlockResultRow,
IotFlocksRaw,
IotHistoryMetric,
IotSensorHistoryPoint,
NumericSensor,
PayloadData,
} from './types.ts';
type TempField = number | NumericSensor | null | undefined;
function numericSensorField(
sensors: PayloadData['sensors'] | undefined,
key: 'ammonia' | 'co2' | 'water'
): number | null {
const raw = sensors?.[key] as NumericSensor | number | null | undefined;
if (raw === null || raw === undefined) return null;
if (typeof raw === 'number' && Number.isFinite(raw)) return raw;
const v = (raw as NumericSensor).value;
if (v === null || v === undefined || !Number.isFinite(Number(v))) return null;
return Number(v);
}
function windMsAfterPreprocess(data: PayloadData): number | null {
const v = data.sensors?.wind?.value;
if (v === null || v === undefined || !Number.isFinite(Number(v))) return null;
return Number(v);
}
type FlockHistoryMetric = Exclude<IotHistoryMetric, IotDeviceHistoryMetric>;
const EXTRACTORS: Record<FlockHistoryMetric, (data: PayloadData) => number | null> = {
avgTemp: (data) => averageInsideTempCelsiusFromSensors(data.sensors),
setPoint: () => null,
humidity: (data) => humidityPercentFromSensors(data.sensors),
outsideTemp: (data) => celsiusFromHistoryTempField(data.sensors?.temperatureOutside as TempField),
lux: (data) =>
luxValueFromSensors(data.sensors) ??
(Number.isFinite(Number(data.lux)) ? Number(data.lux) : null),
wind: windMsAfterPreprocess,
ammonia: (data) => numericSensorField(data.sensors, 'ammonia'),
co2: (data) => numericSensorField(data.sensors, 'co2'),
water: (data) => numericSensorField(data.sensors, 'water'),
temp1: (data) => celsiusFromHistoryTempField(data.sensors?.temperature1 as TempField),
temp2: (data) => celsiusFromHistoryTempField(data.sensors?.temperature2 as TempField),
temp3: (data) => celsiusFromHistoryTempField(data.sensors?.temperature3 as TempField),
};
type SetpointLogRow = {
fetched_at?: string;
updated_at?: string;
payload?: { data?: SetpointSnapshotData };
};
const HVAC_DEVICE_KEYS = ['H', 'H2', 'C'] as const;
type FlockSnapshot = {
atMs: number;
avgTemp: number | null;
deviceStatus: Record<string, 0 | 1>;
};
type TimedEvent =
| { atMs: number; kind: 'setpoint'; setpoint: number }
| { atMs: number; kind: 'status'; status: number };
function nearestFlockSnapshot(samples: FlockSnapshot[], atMs: number): FlockSnapshot | null {
if (samples.length === 0) return null;
let best: FlockSnapshot | null = null;
let bestDist = Infinity;
for (const s of samples) {
const dist = Math.abs(s.atMs - atMs);
if (dist < bestDist) {
bestDist = dist;
best = s;
}
}
return best;
}
function mergeDeviceHistoryEvents(events: TimedEvent[]): IotDeviceHistoryPoint[] {
const sorted = [...events].sort((a, b) => a.atMs - b.atMs);
let lastSetpoint: number | null = null;
let lastStatus: number | null = null;
const merged: IotDeviceHistoryPoint[] = [];
for (const ev of sorted) {
if (ev.kind === 'setpoint') lastSetpoint = ev.setpoint;
else lastStatus = ev.status;
if (lastSetpoint === null && lastStatus === null) continue;
merged.push({
atMs: ev.atMs,
setpoint: lastSetpoint,
status: lastStatus,
});
}
return merged;
}
function historyWindowBounds(maxAtMs?: number | null): { upperMs: number; cutoffMs: number } {
const now = Date.now();
const upperMs =
maxAtMs !== null && maxAtMs !== undefined && Number.isFinite(maxAtMs)
? Math.min(now, Number(maxAtMs))
: now;
return { upperMs, cutoffMs: upperMs - 24 * 60 * 60 * 1000 };
}
function rowUpdatedAtMs(row: IotFlockResultRow | null | undefined): number | null {
const rawAt = row?.payload?.data?.updatedAt;
if (!rawAt) return null;
const atMs = new Date(rawAt).getTime();
return Number.isFinite(atMs) ? atMs : null;
}
async function fetchFlocksPage(page: number): Promise<IotFlocksRaw & { next?: string | null }> {
const response = await fetch(`${IOT_FLOCKS_API_URL}?page=${page}&_=${Date.now()}`, {
cache: 'no-store',
headers: { Accept: 'application/json' },
});
if (!response.ok) throw new Error(`Gagal memuat riwayat (${response.status})`);
return (await response.json()) as IotFlocksRaw & { next?: string | null };
}
/**
* When the history window ends in the past (e.g. Estimasi Panen), jump to the newest
* page that still has rows on/before upperMs so we don't walk dozens of post-harvest pages.
*/
async function resolveFlocksHistoryStart(
upperMs: number
): Promise<{ startUrl: string; firstPage: (IotFlocksRaw & { next?: string | null }) | null }> {
if (Date.now() <= upperMs) {
return { startUrl: `${IOT_FLOCKS_API_URL}?_=${Date.now()}`, firstPage: null };
}
const firstPage = await fetchFlocksPage(1);
const firstRows = Array.isArray(firstPage.results) ? firstPage.results : [];
const hasEligibleOnFirst = firstRows.some((row) => {
const atMs = rowUpdatedAtMs(row);
return atMs !== null && atMs <= upperMs;
});
if (hasEligibleOnFirst) {
return { startUrl: `${IOT_FLOCKS_API_URL}?page=1&_=${Date.now()}`, firstPage };
}
const totalCount = Number(firstPage.count);
const pageSize = firstRows.length;
const totalPages =
Number.isFinite(totalCount) && totalCount > 0 && pageSize > 0
? Math.ceil(totalCount / pageSize)
: 1;
let lo = 2;
let hi = Math.max(1, totalPages);
let bestPage = totalPages;
let bestJson: (IotFlocksRaw & { next?: string | null }) | null = null;
while (lo <= hi) {
const mid = Math.floor((lo + hi) / 2);
const pageJson = await fetchFlocksPage(mid);
const rows = Array.isArray(pageJson.results) ? pageJson.results : [];
const hasEligible = rows.some((row) => {
const atMs = rowUpdatedAtMs(row);
return atMs !== null && atMs <= upperMs;
});
if (hasEligible) {
bestPage = mid;
bestJson = pageJson;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return {
startUrl: `${IOT_FLOCKS_API_URL}?page=${bestPage}&_=${Date.now()}`,
firstPage: bestJson,
};
}
async function loadFlockSnapshots24h(maxAtMs?: number | null): Promise<FlockSnapshot[]> {
const { upperMs, cutoffMs } = historyWindowBounds(maxAtMs);
const snapshots: FlockSnapshot[] = [];
const { startUrl, firstPage } = await resolveFlocksHistoryStart(upperMs);
let nextUrl: string | null = startUrl;
let pendingFirstPage = firstPage;
let safetyPageCount = 0;
const maxPages = 30;
while (nextUrl && safetyPageCount < maxPages) {
let json: IotFlocksRaw & { next?: string | null };
if (pendingFirstPage) {
json = pendingFirstPage;
pendingFirstPage = null;
} else {
const response = await fetch(nextUrl, {
cache: 'no-store',
headers: { Accept: 'application/json' },
});
if (!response.ok) throw new Error(`Gagal memuat riwayat kipas (${response.status})`);
json = (await response.json()) as IotFlocksRaw & { next?: string | null };
}
const rows = Array.isArray(json.results) ? json.results : [];
if (rows.length === 0) break;
let pageHasDataInOrAfterWindow = false;
for (const row of rows) {
const payloadData = (row as IotFlockResultRow)?.payload?.data;
if (!payloadData?.updatedAt) continue;
const atMs = new Date(payloadData.updatedAt).getTime();
if (!Number.isFinite(atMs)) continue;
if (atMs > upperMs) {
pageHasDataInOrAfterWindow = true;
continue;
}
if (atMs < cutoffMs) continue;
pageHasDataInOrAfterWindow = true;
const normalized = preprocessFlockPayloadForPanel(payloadData);
const deviceStatus: Record<string, 0 | 1> = {};
for (let fanNumber = 1; fanNumber <= 11; fanNumber += 1) {
const deviceKey = deviceKeyFromFanNumber(fanNumber);
const rawStatus = normalized.device?.[deviceKey]?.status;
deviceStatus[deviceKey] = Number(rawStatus) === 1 ? 1 : 0;
}
for (const deviceKey of HVAC_DEVICE_KEYS) {
const rawStatus = normalized.device?.[deviceKey]?.status;
deviceStatus[deviceKey] = Number(rawStatus) === 1 ? 1 : 0;
}
snapshots.push({
atMs,
avgTemp: averageInsideTempCelsiusFromSensors(normalized.sensors),
deviceStatus,
});
}
if (!pageHasDataInOrAfterWindow) break;
const nextFromApi = json.next ?? null;
nextUrl = nextFromApi ? nextFromApi.replace('http://', 'https://') : null;
safetyPageCount += 1;
}
snapshots.sort((a, b) => a.atMs - b.atMs);
return snapshots;
}
function statusEventsFromSnapshots(snapshots: FlockSnapshot[], deviceKey: string): TimedEvent[] {
return snapshots.map((snapshot) => ({
atMs: snapshot.atMs,
kind: 'status' as const,
status: snapshot.deviceStatus[deviceKey] ?? 0,
}));
}
async function loadFanSetpointLogEvents24h(
flockId: string,
fanNumber: number,
flockSnapshots: FlockSnapshot[],
maxAtMs?: number | null
): Promise<TimedEvent[]> {
const safeId = String(flockId || '').trim();
if (!safeId) return [];
const { upperMs, cutoffMs } = historyWindowBounds(maxAtMs);
const base = `${IOT_DASHBOARD_IOT_API_BASE}/flock/${encodeURIComponent(safeId)}/setpoint/logs/`;
const events: TimedEvent[] = [];
let totalPage = 1;
for (let page = 1; page <= totalPage; page += 1) {
const response = await fetch(`${base}?page=${page}&_=${Date.now()}`, {
cache: 'no-store',
headers: { Accept: 'application/json' },
});
if (!response.ok) throw new Error(`Gagal memuat log setpoint (${response.status})`);
const json = (await response.json()) as SetpointLogsPageJson;
if (page === 1) {
const tp = Number(json.totalPage);
const fromApi = Number.isFinite(tp) && tp >= 1 ? Math.floor(tp) : 1;
totalPage = Math.min(fromApi, MAX_SETPOINT_LOG_PAGES);
}
const rows = Array.isArray(json.data) ? json.data : [];
for (const row of rows) {
const rawAt = row.fetched_at || row.updated_at;
if (!rawAt) continue;
const atMs = new Date(rawAt).getTime();
if (!Number.isFinite(atMs) || atMs < cutoffMs || atMs > upperMs) continue;
const inner = row.payload?.data;
const nearest = nearestFlockSnapshot(flockSnapshots, atMs);
const avgInsideTemp = nearest?.avgTemp ?? null;
const setpoint = fanTargetCelsiusFromSnapshot(inner, fanNumber, avgInsideTemp);
if (setpoint === null) continue;
events.push({ atMs, kind: 'setpoint', setpoint });
}
}
return events;
}
async function loadHvacSetpointLogEvents24h(
flockId: string,
deviceKey: HvacDeviceKey,
flockSnapshots: FlockSnapshot[],
maxAtMs?: number | null
): Promise<TimedEvent[]> {
const safeId = String(flockId || '').trim();
if (!safeId) return [];
const { upperMs, cutoffMs } = historyWindowBounds(maxAtMs);
const base = `${IOT_DASHBOARD_IOT_API_BASE}/flock/${encodeURIComponent(safeId)}/setpoint/logs/`;
const events: TimedEvent[] = [];
let totalPage = 1;
for (let page = 1; page <= totalPage; page += 1) {
const response = await fetch(`${base}?page=${page}&_=${Date.now()}`, {
cache: 'no-store',
headers: { Accept: 'application/json' },
});
if (!response.ok) throw new Error(`Gagal memuat log setpoint (${response.status})`);
const json = (await response.json()) as SetpointLogsPageJson;
if (page === 1) {
const tp = Number(json.totalPage);
const fromApi = Number.isFinite(tp) && tp >= 1 ? Math.floor(tp) : 1;
totalPage = Math.min(fromApi, MAX_SETPOINT_LOG_PAGES);
}
const rows = Array.isArray(json.data) ? json.data : [];
for (const row of rows) {
const rawAt = row.fetched_at || row.updated_at;
if (!rawAt) continue;
const atMs = new Date(rawAt).getTime();
if (!Number.isFinite(atMs) || atMs < cutoffMs || atMs > upperMs) continue;
const inner = row.payload?.data;
const nearest = nearestFlockSnapshot(flockSnapshots, atMs);
const isActive = nearest?.deviceStatus[deviceKey] === 1;
const setpoint = hvacSetpointFromSnapshot(inner, deviceKey, {
avgInsideTemp: nearest?.avgTemp ?? null,
isActive: Boolean(isActive),
});
if (setpoint === null) continue;
events.push({ atMs, kind: 'setpoint', setpoint });
}
}
return events;
}
/**
* 24h device chart: setpoint (°C, from setpoint logs + panel logic) and status (flocks snapshots).
* Optional `maxAtMs` caps the window end (e.g. Estimasi Panen).
*/
export async function loadDeviceHistory24h(
metric: IotDeviceHistoryMetric,
flockId: string | null | undefined,
maxAtMs?: number | null
): Promise<IotDeviceHistoryPoint[]> {
const deviceKey = deviceKeyFromHistoryMetric(metric);
const flockSnapshots = await loadFlockSnapshots24h(maxAtMs);
if (isFanHistoryMetric(metric)) {
const fanNumber = fanNumberFromMetric(metric);
const [statusEvents, setpointEvents] = await Promise.all([
Promise.resolve(statusEventsFromSnapshots(flockSnapshots, deviceKey)),
loadFanSetpointLogEvents24h(String(flockId || '').trim(), fanNumber, flockSnapshots, maxAtMs),
]);
return mergeDeviceHistoryEvents([...statusEvents, ...setpointEvents]);
}
if (isHvacHistoryMetric(metric)) {
const [statusEvents, setpointEvents] = await Promise.all([
Promise.resolve(statusEventsFromSnapshots(flockSnapshots, deviceKey)),
loadHvacSetpointLogEvents24h(
String(flockId || '').trim(),
deviceKey as HvacDeviceKey,
flockSnapshots,
maxAtMs
),
]);
return mergeDeviceHistoryEvents([...statusEvents, ...setpointEvents]);
}
return [];
}
/**
* 24h fan chart: setpoint (°C, from setpoint logs + panel logic) and status (flocks snapshots).
*/
export async function loadFanHistory24h(
fanNumber: number,
flockId: string | null | undefined,
maxAtMs?: number | null
): Promise<IotDeviceHistoryPoint[]> {
if (!Number.isInteger(fanNumber) || fanNumber < 1 || fanNumber > 11) return [];
return loadDeviceHistory24h(`fan${fanNumber}` as IotDeviceHistoryMetric, flockId, maxAtMs);
}
/** @deprecated Use {@link loadDeviceHistory24h} */
export async function loadFan1History24h(
flockId: string | null | undefined,
maxAtMs?: number | null
): Promise<IotDeviceHistoryPoint[]> {
return loadDeviceHistory24h('fan1', flockId, maxAtMs);
}
type SetpointLogsPageJson = {
data?: SetpointLogRow[];
totalPage?: number;
};
const MAX_SETPOINT_LOG_PAGES = 50;
/**
* 24h series from `GET .../flock/{id}/setpoint/logs/?page=N` (current setpoint per log row).
*/
export async function loadSetpointHistory24hFromLogs(
flockId: string,
maxAtMs?: number | null
): Promise<IotSensorHistoryPoint[]> {
const safeId = String(flockId || '').trim();
if (!safeId) return [];
const { upperMs, cutoffMs } = historyWindowBounds(maxAtMs);
const base = `${IOT_DASHBOARD_IOT_API_BASE}/flock/${encodeURIComponent(safeId)}/setpoint/logs/`;
const points: IotSensorHistoryPoint[] = [];
let totalPage = 1;
for (let page = 1; page <= totalPage; page += 1) {
const response = await fetch(`${base}?page=${page}&_=${Date.now()}`, {
cache: 'no-store',
headers: { Accept: 'application/json' },
});
if (!response.ok) throw new Error(`Gagal memuat log setpoint (${response.status})`);
const json = (await response.json()) as SetpointLogsPageJson;
if (page === 1) {
const tp = Number(json.totalPage);
const fromApi = Number.isFinite(tp) && tp >= 1 ? Math.floor(tp) : 1;
totalPage = Math.min(fromApi, MAX_SETPOINT_LOG_PAGES);
}
const rows = Array.isArray(json.data) ? json.data : [];
for (const row of rows) {
const rawAt = row.fetched_at || row.updated_at;
if (!rawAt) continue;
const atMs = new Date(rawAt).getTime();
if (!Number.isFinite(atMs) || atMs < cutoffMs || atMs > upperMs) continue;
const raw = row.payload?.data?.setpoint_sekarang?.current_setpoint;
const n = Number(raw);
if (!Number.isFinite(n)) continue;
points.push({ atMs, value: n });
}
}
points.sort((a, b) => a.atMs - b.atMs);
return points;
}
/**
* Loads 24h history from `/api/iot/flocks/` (same source as panel), except **setPoint**
* which uses per-flock setpoint logs on dashboard CPSP.
* Optional `maxAtMs` caps the window end (e.g. Estimasi Panen).
*/
export async function loadIotSensorHistory24h(
metric: FlockHistoryMetric,
flockId?: string | null,
maxAtMs?: number | null
): Promise<IotSensorHistoryPoint[]> {
if (metric === 'setPoint') {
return loadSetpointHistory24hFromLogs(String(flockId || '').trim(), maxAtMs);
}
const extract = EXTRACTORS[metric];
const { upperMs, cutoffMs } = historyWindowBounds(maxAtMs);
const points: IotSensorHistoryPoint[] = [];
const { startUrl, firstPage } = await resolveFlocksHistoryStart(upperMs);
let nextUrl: string | null = startUrl;
let pendingFirstPage = firstPage;
let safetyPageCount = 0;
const maxPages = 30;
while (nextUrl && safetyPageCount < maxPages) {
let json: IotFlocksRaw & { next?: string | null };
if (pendingFirstPage) {
json = pendingFirstPage;
pendingFirstPage = null;
} else {
const response = await fetch(nextUrl, {
cache: 'no-store',
headers: { Accept: 'application/json' },
});
if (!response.ok) throw new Error(`Gagal memuat riwayat (${response.status})`);
json = (await response.json()) as IotFlocksRaw & { next?: string | null };
}
const rows = Array.isArray(json.results) ? json.results : [];
if (rows.length === 0) break;
let pageHasDataInOrAfterWindow = false;
for (const row of rows) {
const payloadData = (row as IotFlockResultRow)?.payload?.data;
if (!payloadData) continue;
const rawAt = payloadData.updatedAt;
if (!rawAt) continue;
const atMs = new Date(rawAt).getTime();
if (!Number.isFinite(atMs)) continue;
if (atMs > upperMs) {
pageHasDataInOrAfterWindow = true;
continue;
}
if (atMs < cutoffMs) continue;
pageHasDataInOrAfterWindow = true;
const normalized = preprocessFlockPayloadForPanel(payloadData);
const value = extract(normalized);
if (value === null) continue;
points.push({ atMs, value: Number(value) });
}
if (!pageHasDataInOrAfterWindow) break;
const nextFromApi = json.next ?? null;
nextUrl = nextFromApi ? nextFromApi.replace('http://', 'https://') : null;
safetyPageCount += 1;
}
points.sort((a, b) => a.atMs - b.atMs);
return points;
}