480 lines
15 KiB
TypeScript
480 lines
15 KiB
TypeScript
import { IOT_DASHBOARD_IOT_API_BASE, IOT_FLOCKS_API_URL } from './constants.tsx';
|
|
import { averageInsideTempCelsiusFromSensors } from './computeDashboard.ts';
|
|
import {
|
|
resolveCoolerDisplayTargetCelsius,
|
|
type CoolerSettingSnapshot,
|
|
} from './coolerSetpointResolve.ts';
|
|
import { normalizeTargetCelsius, resolveFan1DisplayTargetCelsius } from './fan1SetpointResolve.ts';
|
|
import type { IotFlockResultRow, IotFlocksRaw, PayloadData } from './types.ts';
|
|
|
|
type FlocksPageJson = IotFlocksRaw & { next?: string | null };
|
|
|
|
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;
|
|
}
|
|
|
|
function compareRowIdAsc(a: IotFlockResultRow, b: IotFlockResultRow): number {
|
|
const aId = Number(a?.id);
|
|
const bId = Number(b?.id);
|
|
if (!Number.isFinite(aId) && !Number.isFinite(bId)) return 0;
|
|
if (!Number.isFinite(aId)) return -1;
|
|
if (!Number.isFinite(bId)) return 1;
|
|
return aId - bId;
|
|
}
|
|
|
|
function pickLatestRowById(rows: IotFlockResultRow[]): IotFlockResultRow | null {
|
|
if (rows.length === 0) return null;
|
|
const sortedById = [...rows].sort(compareRowIdAsc);
|
|
return sortedById[sortedById.length - 1] ?? null;
|
|
}
|
|
|
|
function pickLatestRowAtOrBefore(
|
|
rows: IotFlockResultRow[],
|
|
maxAtMs: number
|
|
): IotFlockResultRow | null {
|
|
const eligible = rows.filter((row) => {
|
|
const atMs = rowUpdatedAtMs(row);
|
|
return atMs !== null && atMs <= maxAtMs;
|
|
});
|
|
return pickLatestRowById(eligible);
|
|
}
|
|
|
|
async function fetchFlocksPage(page: number): Promise<FlocksPageJson> {
|
|
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 data IoT flocks API');
|
|
return (await response.json()) as FlocksPageJson;
|
|
}
|
|
|
|
/**
|
|
* Newest flock snapshot whose `updatedAt` is on/before `maxAtMs`.
|
|
* Pages are newest-first; binary-searches when the first page is entirely after the cap.
|
|
*/
|
|
async function findLatestFlockRowAtOrBefore(maxAtMs: number): Promise<{
|
|
raw: IotFlocksRaw;
|
|
row: IotFlockResultRow;
|
|
}> {
|
|
const firstPage = await fetchFlocksPage(1);
|
|
const firstRows = Array.isArray(firstPage.results) ? firstPage.results : [];
|
|
if (firstRows.length === 0) {
|
|
throw new Error('Data flock tidak ditemukan dari API');
|
|
}
|
|
|
|
const fromFirstPage = pickLatestRowAtOrBefore(firstRows, maxAtMs);
|
|
if (fromFirstPage) {
|
|
return {
|
|
raw: {
|
|
count: Number(fromFirstPage.id),
|
|
results: firstRows,
|
|
},
|
|
row: fromFirstPage,
|
|
};
|
|
}
|
|
|
|
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 bestRow: IotFlockResultRow | null = null;
|
|
let bestPageRows: IotFlockResultRow[] = [];
|
|
|
|
while (lo <= hi) {
|
|
const mid = Math.floor((lo + hi) / 2);
|
|
const page = await fetchFlocksPage(mid);
|
|
const rows = Array.isArray(page.results) ? page.results : [];
|
|
const eligible = pickLatestRowAtOrBefore(rows, maxAtMs);
|
|
|
|
if (eligible) {
|
|
bestRow = eligible;
|
|
bestPageRows = rows;
|
|
// Look for a newer eligible row on an earlier (newer) page.
|
|
hi = mid - 1;
|
|
} else {
|
|
// Entire page is after the cap — go older.
|
|
lo = mid + 1;
|
|
}
|
|
}
|
|
|
|
if (!bestRow) {
|
|
throw new Error('Tidak ada data IoT pada/ sebelum tanggal estimasi panen');
|
|
}
|
|
|
|
return {
|
|
raw: {
|
|
count: Number(bestRow.id),
|
|
results: bestPageRows.length > 0 ? bestPageRows : [bestRow],
|
|
},
|
|
row: bestRow,
|
|
};
|
|
}
|
|
|
|
export function latestResultRow(rawData: IotFlocksRaw | null): IotFlockResultRow | null {
|
|
const list = Array.isArray(rawData?.results) ? rawData.results : [];
|
|
if (list.length === 0) return null;
|
|
|
|
const countFromApi = Number(rawData?.count);
|
|
if (Number.isFinite(countFromApi)) {
|
|
const byCountId = list.find((row) => Number(row?.id) === countFromApi);
|
|
if (byCountId) return byCountId;
|
|
}
|
|
|
|
return pickLatestRowById(list);
|
|
}
|
|
|
|
export function apiResponseCounts(rawData: IotFlocksRaw | null): number {
|
|
const countFromApi = Number(rawData?.count);
|
|
if (Number.isFinite(countFromApi)) return countFromApi;
|
|
return Array.isArray(rawData?.results) ? rawData.results.length : 0;
|
|
}
|
|
|
|
/** Inner `data` shape for setpoint (dashboard log payload matches former open-flock `setpoint` body). */
|
|
type OpenFlockSetpointResponse = {
|
|
data?: {
|
|
setpoint_sekarang?: {
|
|
current_setpoint?: number | string | null;
|
|
};
|
|
fan_table?: Array<{
|
|
name?: string | null;
|
|
temp_target?: number | string | null;
|
|
}>;
|
|
setting?: {
|
|
fan?: {
|
|
lv2?: {
|
|
target_on?: number | string | null;
|
|
};
|
|
dirrect?: {
|
|
target_on?: number | string | null;
|
|
};
|
|
};
|
|
heater?: Array<{
|
|
name?: string | null;
|
|
target_on?: number | string | null;
|
|
target_off?: number | string | null;
|
|
sensor_in_use?: string | null;
|
|
}>;
|
|
cooler?: CoolerSettingSnapshot;
|
|
};
|
|
};
|
|
};
|
|
|
|
type SetpointLogsListResponse = {
|
|
data?: Array<{
|
|
payload?: OpenFlockSetpointResponse;
|
|
}>;
|
|
};
|
|
|
|
type OpenFlockSetpointParsed = {
|
|
currentSetpoint: number | null;
|
|
fanTargetTemperature: Record<string, number>;
|
|
fan1TargetOnLv2: number | null;
|
|
/** `setting.fan.dirrect.target_on` (°C after normalization). */
|
|
fan1TargetOnDirect: number | null;
|
|
heaterTargetTemperature: Record<string, { targetOn?: number; targetOff?: number }>;
|
|
coolerSetting: CoolerSettingSnapshot | undefined;
|
|
};
|
|
|
|
type TabelAlarmBand = {
|
|
nilai?: number | string | null;
|
|
sensor_in_use?: string | null;
|
|
};
|
|
|
|
type OpenFlockTabelAlarmResponse = {
|
|
data?: {
|
|
humidity?: {
|
|
nilai?: number | string | null;
|
|
};
|
|
batas_atas?: TabelAlarmBand;
|
|
batas_bawah_1?: TabelAlarmBand;
|
|
batas_bawah_2?: TabelAlarmBand;
|
|
};
|
|
};
|
|
|
|
type TabelAlarmPayload = {
|
|
humidityAlarmNilai: number | null;
|
|
batasAtasNilai: number | null;
|
|
batasAtasSensorInUse: string | null;
|
|
batasBawah1Nilai: number | null;
|
|
batasBawah1SensorInUse: string | null;
|
|
batasBawah2Nilai: number | null;
|
|
batasBawah2SensorInUse: string | null;
|
|
};
|
|
|
|
function normalizeSetpointCelsius(raw: number | string | null | undefined): number | null {
|
|
const n = Number(raw);
|
|
if (!Number.isFinite(n)) return null;
|
|
return n;
|
|
}
|
|
|
|
function normalizeHeaterDelta(raw: number | string | null | undefined): number | null {
|
|
const n = Number(raw);
|
|
if (!Number.isFinite(n)) return null;
|
|
return n;
|
|
}
|
|
|
|
function normalizeHumidityAlarmThreshold(raw: number | string | null | undefined): number | null {
|
|
const n = Number(raw);
|
|
if (!Number.isFinite(n)) return null;
|
|
// `/tabelalarm` often returns humidity in tenths, e.g. 760 = 76.0%.
|
|
return n > 100 ? n / 10 : n;
|
|
}
|
|
|
|
function normalizeTempAlarmThresholdCelsius(
|
|
raw: number | string | null | undefined
|
|
): number | null {
|
|
const n = Number(raw);
|
|
if (!Number.isFinite(n)) return null;
|
|
return n;
|
|
}
|
|
|
|
function normalizeSensorInUse(raw: string | null | undefined): string | null {
|
|
const s = String(raw || '').trim();
|
|
return s || null;
|
|
}
|
|
|
|
function parseTabelAlarmResponse(json: OpenFlockTabelAlarmResponse): TabelAlarmPayload {
|
|
const data = json?.data;
|
|
return {
|
|
humidityAlarmNilai: normalizeHumidityAlarmThreshold(data?.humidity?.nilai),
|
|
batasAtasNilai: normalizeTempAlarmThresholdCelsius(data?.batas_atas?.nilai),
|
|
batasAtasSensorInUse: normalizeSensorInUse(data?.batas_atas?.sensor_in_use),
|
|
batasBawah1Nilai: normalizeTempAlarmThresholdCelsius(data?.batas_bawah_1?.nilai),
|
|
batasBawah1SensorInUse: normalizeSensorInUse(data?.batas_bawah_1?.sensor_in_use),
|
|
batasBawah2Nilai: normalizeTempAlarmThresholdCelsius(data?.batas_bawah_2?.nilai),
|
|
batasBawah2SensorInUse: normalizeSensorInUse(data?.batas_bawah_2?.sensor_in_use),
|
|
};
|
|
}
|
|
|
|
function parseSetpointSnapshot(
|
|
inner: OpenFlockSetpointResponse['data'] | undefined
|
|
): OpenFlockSetpointParsed {
|
|
const rawCurrent = inner?.setpoint_sekarang?.current_setpoint;
|
|
const currentSetpoint = normalizeSetpointCelsius(rawCurrent);
|
|
|
|
const fanTargetTemperature: Record<string, number> = {};
|
|
const fan1TargetOnLv2 = normalizeTargetCelsius(inner?.setting?.fan?.lv2?.target_on);
|
|
const fan1TargetOnDirect = normalizeTargetCelsius(inner?.setting?.fan?.dirrect?.target_on);
|
|
|
|
const fanTable = Array.isArray(inner?.fan_table) ? inner.fan_table : [];
|
|
for (const row of fanTable) {
|
|
const name = String(row?.name || '').trim();
|
|
const match = /^Fan\s+(\d{1,2})$/i.exec(name);
|
|
if (!match) continue;
|
|
const fanNumber = Number(match[1]);
|
|
if (!Number.isFinite(fanNumber) || fanNumber < 1 || fanNumber > 11) continue;
|
|
const target = normalizeTargetCelsius(row?.temp_target);
|
|
if (target === null) continue;
|
|
fanTargetTemperature[`B${fanNumber}`] = target;
|
|
}
|
|
|
|
const heaterTargetTemperature: Record<string, { targetOn?: number; targetOff?: number }> = {};
|
|
const heaterRows = Array.isArray(inner?.setting?.heater) ? inner.setting.heater : [];
|
|
for (const heater of heaterRows) {
|
|
const name = String(heater?.name || '').trim();
|
|
const match = /^Heater\s+(\d{1,2})$/i.exec(name);
|
|
if (!match) continue;
|
|
const heaterNumber = Number(match[1]);
|
|
if (!Number.isFinite(heaterNumber) || heaterNumber < 1) continue;
|
|
const key = heaterNumber === 1 ? 'H' : `H${heaterNumber}`;
|
|
const targetOn = normalizeHeaterDelta(heater?.target_on);
|
|
const targetOff = normalizeHeaterDelta(heater?.target_off);
|
|
if (targetOn === null && targetOff === null) continue;
|
|
heaterTargetTemperature[key] = {
|
|
...(targetOn !== null && { targetOn }),
|
|
...(targetOff !== null && { targetOff }),
|
|
};
|
|
}
|
|
|
|
const coolerSetting = inner?.setting?.cooler;
|
|
|
|
return {
|
|
currentSetpoint,
|
|
fanTargetTemperature,
|
|
fan1TargetOnLv2,
|
|
fan1TargetOnDirect,
|
|
heaterTargetTemperature,
|
|
coolerSetting,
|
|
};
|
|
}
|
|
|
|
async function loadCurrentSetpointByFlockId(flockId: string): Promise<OpenFlockSetpointParsed> {
|
|
const safeFlockId = String(flockId || '').trim();
|
|
if (!safeFlockId) {
|
|
return {
|
|
currentSetpoint: null,
|
|
fanTargetTemperature: {},
|
|
fan1TargetOnLv2: null,
|
|
fan1TargetOnDirect: null,
|
|
heaterTargetTemperature: {},
|
|
coolerSetting: undefined,
|
|
};
|
|
}
|
|
|
|
try {
|
|
const response = await fetch(
|
|
`${IOT_DASHBOARD_IOT_API_BASE}/flock/${encodeURIComponent(safeFlockId)}/setpoint/logs/`,
|
|
{
|
|
cache: 'no-store',
|
|
headers: {
|
|
Accept: 'application/json',
|
|
},
|
|
}
|
|
);
|
|
if (!response.ok) {
|
|
return {
|
|
currentSetpoint: null,
|
|
fanTargetTemperature: {},
|
|
fan1TargetOnLv2: null,
|
|
fan1TargetOnDirect: null,
|
|
heaterTargetTemperature: {},
|
|
coolerSetting: undefined,
|
|
};
|
|
}
|
|
const json = (await response.json()) as SetpointLogsListResponse;
|
|
const inner = json?.data?.[0]?.payload?.data;
|
|
return parseSetpointSnapshot(inner);
|
|
} catch {
|
|
return {
|
|
currentSetpoint: null,
|
|
fanTargetTemperature: {},
|
|
fan1TargetOnLv2: null,
|
|
fan1TargetOnDirect: null,
|
|
heaterTargetTemperature: {},
|
|
coolerSetting: undefined,
|
|
};
|
|
}
|
|
}
|
|
|
|
const EMPTY_TABEL_ALARM: TabelAlarmPayload = {
|
|
humidityAlarmNilai: null,
|
|
batasAtasNilai: null,
|
|
batasAtasSensorInUse: null,
|
|
batasBawah1Nilai: null,
|
|
batasBawah1SensorInUse: null,
|
|
batasBawah2Nilai: null,
|
|
batasBawah2SensorInUse: null,
|
|
};
|
|
|
|
async function loadTabelAlarmByFlockId(flockId: string): Promise<TabelAlarmPayload> {
|
|
const safeFlockId = String(flockId || '').trim();
|
|
if (!safeFlockId) return EMPTY_TABEL_ALARM;
|
|
|
|
try {
|
|
const response = await fetch(
|
|
`${IOT_DASHBOARD_IOT_API_BASE}/flock/${encodeURIComponent(safeFlockId)}/tabelalarm`,
|
|
{
|
|
cache: 'no-store',
|
|
headers: {
|
|
Accept: 'application/json',
|
|
},
|
|
}
|
|
);
|
|
if (!response.ok) return EMPTY_TABEL_ALARM;
|
|
|
|
const json = (await response.json()) as OpenFlockTabelAlarmResponse;
|
|
return parseTabelAlarmResponse(json);
|
|
} catch {
|
|
return EMPTY_TABEL_ALARM;
|
|
}
|
|
}
|
|
|
|
export type LoadDashboardDataOptions = {
|
|
/** Inclusive upper bound (ms). When set and live data is newer, freeze at last reading on/before this time. */
|
|
maxAtMs?: number | null;
|
|
};
|
|
|
|
export async function loadDashboardData(
|
|
options?: LoadDashboardDataOptions
|
|
): Promise<{ raw: IotFlocksRaw; data: PayloadData }> {
|
|
const maxAtMs =
|
|
options?.maxAtMs !== null && options?.maxAtMs !== undefined && Number.isFinite(options.maxAtMs)
|
|
? Number(options.maxAtMs)
|
|
: null;
|
|
|
|
let raw: IotFlocksRaw;
|
|
let latestRow: IotFlockResultRow | null;
|
|
|
|
if (maxAtMs !== null && Date.now() > maxAtMs) {
|
|
const capped = await findLatestFlockRowAtOrBefore(maxAtMs);
|
|
raw = capped.raw;
|
|
latestRow = capped.row;
|
|
} else {
|
|
const response = await fetch(`${IOT_FLOCKS_API_URL}?_=${Date.now()}`, {
|
|
cache: 'no-store',
|
|
headers: { Accept: 'application/json' },
|
|
});
|
|
if (!response.ok) throw new Error('Gagal memuat data IoT flocks API');
|
|
raw = (await response.json()) as IotFlocksRaw;
|
|
latestRow = latestResultRow(raw);
|
|
}
|
|
|
|
const result = latestRow?.payload?.data;
|
|
const latestId = latestRow?.id;
|
|
|
|
if (latestId === undefined || latestId === null || !result) {
|
|
throw new Error('Data flock tidak ditemukan dari API');
|
|
}
|
|
|
|
const setpointData = await loadCurrentSetpointByFlockId(latestRow?.flock_id || '');
|
|
const tabelAlarm = await loadTabelAlarmByFlockId(latestRow?.flock_id || '');
|
|
const fanTargetTemperature = { ...setpointData.fanTargetTemperature };
|
|
const avgInsideTemp = averageInsideTempCelsiusFromSensors(result.sensors);
|
|
const fanTableB1 = fanTargetTemperature.B1;
|
|
const fan1Target = resolveFan1DisplayTargetCelsius({
|
|
avgInsideTemp,
|
|
direct: setpointData.fan1TargetOnDirect,
|
|
lv2: setpointData.fan1TargetOnLv2,
|
|
fanTableB1,
|
|
});
|
|
if (fan1Target !== null) fanTargetTemperature.B1 = fan1Target;
|
|
|
|
const isCoolerOn = Number(result.device?.C?.status) === 1;
|
|
const coolerTargetTemperature = isCoolerOn
|
|
? resolveCoolerDisplayTargetCelsius(avgInsideTemp, setpointData.coolerSetting)
|
|
: null;
|
|
|
|
const dataWithSetpoint: PayloadData = {
|
|
...result,
|
|
...(setpointData.currentSetpoint !== null && { setpointCurrent: setpointData.currentSetpoint }),
|
|
...(Object.keys(fanTargetTemperature).length > 0 && {
|
|
fanTargetTemperature,
|
|
}),
|
|
...(Object.keys(setpointData.heaterTargetTemperature).length > 0 && {
|
|
heaterTargetTemperature: setpointData.heaterTargetTemperature,
|
|
}),
|
|
...(isCoolerOn && { coolerTargetTemperature }),
|
|
...(tabelAlarm.humidityAlarmNilai !== null && {
|
|
humidityAlarmNilai: tabelAlarm.humidityAlarmNilai,
|
|
}),
|
|
...(tabelAlarm.batasAtasNilai !== null && {
|
|
batasAtasNilai: tabelAlarm.batasAtasNilai,
|
|
...(tabelAlarm.batasAtasSensorInUse && {
|
|
batasAtasSensorInUse: tabelAlarm.batasAtasSensorInUse,
|
|
}),
|
|
}),
|
|
...(tabelAlarm.batasBawah1Nilai !== null && {
|
|
batasBawah1Nilai: tabelAlarm.batasBawah1Nilai,
|
|
...(tabelAlarm.batasBawah1SensorInUse && {
|
|
batasBawah1SensorInUse: tabelAlarm.batasBawah1SensorInUse,
|
|
}),
|
|
}),
|
|
...(tabelAlarm.batasBawah2Nilai !== null && {
|
|
batasBawah2Nilai: tabelAlarm.batasBawah2Nilai,
|
|
...(tabelAlarm.batasBawah2SensorInUse && {
|
|
batasBawah2SensorInUse: tabelAlarm.batasBawah2SensorInUse,
|
|
}),
|
|
}),
|
|
};
|
|
|
|
return { raw, data: dataWithSetpoint };
|
|
}
|