This commit is contained in:
Daniel Ledda
2020-11-18 22:51:30 +01:00
parent 841861ee87
commit 4b0c5bc9ab
8 changed files with 100 additions and 78 deletions

View File

@@ -1,6 +1,7 @@
import Chart from "chart.js/dist/Chart.bundle.min";
import type {ChartPoint} from "chart.js";
import {generateClimateChartConfig} from "./climateChartConfig";
import {config} from "./main";
interface Snapshot {
id: number,
@@ -25,11 +26,17 @@ class ClimateChart {
private onLoadedCallback: () => void = () => {};
private onErrorCallback: (e: Error) => void = () => {};
private errorLog: string = "";
private readonly rootUrl: string;
private readonly canvasId: string;
private readonly dataEndpointBase: string;
private readonly domId: string;
private readonly minutesDisplayed: number = 60;
constructor(rootUrl: string, canvasId: string, minutesDisplayed: number) {
constructor(domId: string, minutesDisplayed: number) {
this.domId = domId;
if (config.development) {
this.dataEndpointBase = "http://tortedda.local/climate/data";
} else {
this.dataEndpointBase = "data";
}
this.minutesDisplayed = Math.floor(minutesDisplayed);
if (minutesDisplayed < 0 || Math.floor(minutesDisplayed) !== minutesDisplayed) {
console.warn(`Minutes passed were ${ minutesDisplayed }, which is invalid. ${ this.minutesDisplayed } minutes are being shown instead.`);
@@ -37,17 +44,8 @@ class ClimateChart {
this.initChart().catch((e) => {this.logError(e);});
}
private async getInitialDataBlob(): Promise<SnapshotRecords> {
const data = await fetch("data?since=" + new Date((new Date().getTime() - this.minutesDisplayed * 60000)).toISOString());
const payload = await data.json();
if (payload.snapshots.length < 0) {
throw new Error("Bad response - no snapshots found!");
}
return payload;
}
private async initChart() {
const canvasElement = document.getElementById(this.canvasId);
const canvasElement = document.getElementById(this.domId);
let ctx: CanvasRenderingContext2D;
if (ClimateChart.isCanvas(canvasElement)) {
ctx = canvasElement.getContext('2d');
@@ -59,8 +57,8 @@ class ClimateChart {
const payload = await this.getInitialDataBlob();
this.latestSnapshot = payload.snapshots[0];
this.insertSnapshots(...payload.snapshots);
this.rerender();
setInterval(async () => this.updateFromServer().catch(e => this.logError(e)), 30 * 1000);
this.chart.update();
this.onLoadedCallback();
}
catch (e) {
@@ -68,18 +66,29 @@ class ClimateChart {
}
}
private async getInitialDataBlob(): Promise<SnapshotRecords> {
const minutesAsDate = (new Date().getTime() - this.minutesDisplayed * 60000);
const dataEndpoint = `${ this.dataEndpointBase }?since=${ new Date(minutesAsDate).toISOString() }`;
const payload = await (await fetch(dataEndpoint)).json();
if (payload.snapshots.length < 0) {
throw new Error("Bad response - no snapshots found!");
}
return payload;
}
private async updateFromServer() {
const lastTimeInChart = (new Date(this.latestSnapshot.time)).toISOString();
const url = "data?since=" + lastTimeInChart;
const lastTimeInChart = this.latestSnapshot.time;
const url = `${ this.dataEndpointBase }?since=${ new Date(this.latestSnapshot.time + "+00:00").toISOString() }`;
try {
const payload: SnapshotRecords = await (await fetch(url)).json();
if (payload.snapshots.length > 0) {
const latestSnapshotIsNew = new Date(payload.snapshots[0].time).getTime() > new Date(lastTimeInChart).getTime();
if (latestSnapshotIsNew) {
this.removeExpiredPointsAfter(lastTimeInChart);
const newLatestTime = new Date(payload.snapshots[0].time).getTime();
if (newLatestTime > new Date(lastTimeInChart).getTime()) {
console.log(payload);
this.removePointsOlderThan(newLatestTime - this.minutesDisplayed * 60000);
this.latestSnapshot = payload.snapshots[0];
this.insertSnapshots(...payload.snapshots);
this.chart.update();
this.rerender();
}
}
}
@@ -88,6 +97,10 @@ class ClimateChart {
}
}
private rerender() {
this.chart.update();
}
private insertSnapshots(...snapshots: Snapshot[]) {
for (const snapshot of snapshots.reverse()) {
this.humidityPointList().push({x: snapshot.time, y: snapshot.humidity});
@@ -96,11 +109,10 @@ class ClimateChart {
}
}
private removeExpiredPointsAfter(referenceTime: string) {
private removePointsOlderThan(referenceTime: number) {
for (let i = 0; i < this.humidityPointList().length; i++) {
const timeOnPoint = this.humidityPointList()[i].x;
const timeElapsedSinceReference = Date.parse(referenceTime) - Date.parse(timeOnPoint);
if (timeElapsedSinceReference > this.minutesDisplayed * 60000) {
if (new Date(timeOnPoint).getTime() < referenceTime) {
this.humidityPointList().splice(i, 1);
this.tempPointList().splice(i, 1);
this.co2PointList().splice(i, 1);
@@ -119,7 +131,7 @@ class ClimateChart {
}
private co2PointList(): ClimatePoint[] {
return this.chart.data.datasets[1].data as ClimatePoint[];
return this.chart.data.datasets[2].data as ClimatePoint[];
}
onLoaded(callback: () => void) {

View File

@@ -11,9 +11,9 @@ interface ClimateChartSettings {
}
}
const defaultHumidityColor = 'rgb(45,141,45)';
const defaultTempColor = 'rgb(0,134,222)';
const defaultCo2Color = 'rgb(194,30,30)';
const defaultHumidityColor = 'rgb(196,107,107)';
const defaultTempColor = 'rgb(173,136,68)';
const defaultCo2Color = 'rgb(52,133,141)';
export function generateClimateChartConfig(settings: ClimateChartSettings): ChartConfiguration {
return {
@@ -41,8 +41,13 @@ export function generateClimateChartConfig(settings: ClimateChartSettings): Char
},
options: {
title: {
display: true,
display: true,
text: 'Ledda\'s Room Climate',
fontSize: 50,
},
legend: {
position: "top",
align: "end",
},
scales: {
xAxes: [{

View File

@@ -0,0 +1,3 @@
{
"development": false
}

View File

@@ -1,4 +1,6 @@
import ClimateChart from "./ClimateChart";
import config from "./config.json";
export {config};
const CHART_DOM_ID: string = "myChart";
let rootUrl: string = "";
@@ -16,7 +18,7 @@ function createClimateChart() {
minutesDisplayed = parsedMins;
}
}
return new ClimateChart(rootUrl, CHART_DOM_ID, minutesDisplayed);
return new ClimateChart(CHART_DOM_ID, minutesDisplayed);
}
const overlay = document.createElement('div');
@@ -33,7 +35,7 @@ document.onreadystatechange = (e) => {
});
climateChart.onErrored((e) => {
overlay.classList.remove('hidden');
textContainer.innerText = `An error occurred: ${e}\nTry restarting the page.`;
textContainer.innerText = `An error occurred: ${e}\nTry reloading the page.`;
});
document.onreadystatechange = () => {};
};
};