Skip to content

Commit

Permalink
chore: toggle day and month for water
Browse files Browse the repository at this point in the history
  • Loading branch information
mdvanes committed May 7, 2024
1 parent aebb9b4 commit ebdc4b4
Show file tree
Hide file tree
Showing 7 changed files with 81 additions and 16 deletions.
18 changes: 13 additions & 5 deletions apps/client/src/Components/Pages/Energy/Energy.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,21 @@ import TabList from "@mui/lab/TabList";
import TabPanel from "@mui/lab/TabPanel";
import Box from "@mui/material/Box";
import Tab from "@mui/material/Tab";
import { FC, useState } from "react";
import { FC, useEffect, useState } from "react";
import { ClimateChart } from "./charts/ClimateChart";
import { WaterChart } from "./charts/WaterChart";

export const Energy: FC = () => {
const [value, setValue] = useState("1");

useEffect(() => {
const params = new URL(document.location.href).searchParams;
const tab = params.get("tab");
if (tab) {
setValue(tab);
}
}, []);

const handleTabChange = (
_event: React.SyntheticEvent,
newValue: string
Expand All @@ -26,16 +34,16 @@ export const Energy: FC = () => {
aria-label="lab API tabs example"
>
<Tab label="Climate" value="1" />
{/* <Tab label="Gas" value="2" />
<Tab label="Electric" value="3" /> */}
<Tab label="Gas" value="2" />
<Tab label="Electric" value="3" />
<Tab label="Water" value="4" />
</TabList>
</Box>
<TabPanel value="1">
<ClimateChart />
</TabPanel>
{/* <TabPanel value="2">Item Two</TabPanel>
<TabPanel value="3">Item Three</TabPanel> */}
<TabPanel value="2">Item Two</TabPanel>
<TabPanel value="3">Item Three</TabPanel>
<TabPanel value="4">
<WaterChart />
</TabPanel>
Expand Down
29 changes: 25 additions & 4 deletions apps/client/src/Components/Pages/Energy/charts/WaterChart.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Chip, Stack } from "@mui/material";
import { FC } from "react";
import { FC, useState } from "react";
import {
useGetWaterQuery,
type GetWaterResponse,
Expand All @@ -11,19 +11,26 @@ type WaterSensorItem = GetWaterResponse[0][0] & {
liters?: number;
};

const INTERVAL = 1000 * 60 * 5;
// const INTERVAL = 1000 * 60 * 5;
const INTERVAL = 1000 * 60 * 60 * 24;

// TODO show last day, week, month

export const WaterChart: FC = () => {
const { data, isLoading, isFetching } = useGetWaterQuery();
const [mode, setMode] = useState<"day" | "month">("day");
// const mode: "day" | "month" = "day".toString() as "day" | "month";
const { data, isLoading, isFetching } = useGetWaterQuery({ range: mode });

const sensorEntries: WaterSensorItem[] = data?.[0] ?? [];

const interval = mode === "month" ? 1000 * 60 * 60 * 24 : 1000 * 60 * 5;

const dataAggregatedBy5Mins = sensorEntries.reduce<WaterSensorItem[]>(
(acc, next) => {
const prevEntry = acc.at(-1) ?? next;
const prevTime = new Date(prevEntry.last_changed ?? "0").getTime();
const nextTime = new Date(next.last_changed ?? "0").getTime();
if (nextTime <= prevTime + INTERVAL) {
if (nextTime <= prevTime + interval) {
return [
...acc.slice(0, -1),
{ ...prevEntry, liters: (prevEntry.liters ?? 0) + 1 },
Expand All @@ -36,6 +43,20 @@ export const WaterChart: FC = () => {

return (
<>
<button
onClick={() => {
setMode("day");
}}
>
day
</button>
<button
onClick={() => {
setMode("month");
}}
>
month
</button>
<Stack direction="row" spacing={1} marginBottom={1}>
{data &&
data.length &&
Expand Down
9 changes: 7 additions & 2 deletions apps/client/src/Services/generated/energyUsageApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ const injectedRtkApi = api
providesTags: ["temperature"],
}),
getWater: build.query<GetWaterApiResponse, GetWaterApiArg>({
query: () => ({ url: `/api/energyusage/water` }),
query: (queryArg) => ({
url: `/api/energyusage/water`,
params: { range: queryArg.range },
}),
providesTags: ["water"],
}),
}),
Expand All @@ -25,7 +28,9 @@ export type GetTemperaturesApiResponse =
/** status 200 Temperatures */ GetTemperaturesResponse;
export type GetTemperaturesApiArg = void;
export type GetWaterApiResponse = /** status 200 Water */ GetWaterResponse;
export type GetWaterApiArg = void;
export type GetWaterApiArg = {
range?: "day" | "month";
};
export type GetTemperaturesResponse = {
entity_id?: string;
state?: string;
Expand Down
27 changes: 24 additions & 3 deletions apps/server/src/energyusage/energyusage.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
HttpException,
HttpStatus,
Logger,
Query,
Request,
UseGuards,
} from "@nestjs/common";
Expand Down Expand Up @@ -210,13 +211,33 @@ export class EnergyUsageController {
@UseGuards(JwtAuthGuard)
@Get("/water")
async getWater(
@Request() req: AuthenticatedRequest
@Request() req: AuthenticatedRequest,
@Query("range") range: "day" | "month"
): Promise<EnergyUsageGetWaterResponse> {
this.logger.verbose(`[${req.user.name}] GET to /api/energyusage/water`);

// const mode: "day" | "month" = "month".toString() as "day" | "month";

// See https://developers.home-assistant.io/docs/api/rest/
try {
const date = new Date().toISOString().slice(0, 10);
const url = `${this.haApiConfig.baseUrl}/api/history/period/${date}T00:00:00Z?filter_entity_id=${this.haApiConfig.waterSensorId}`;
// crashes
// const date = new Date("2024-04-29").toISOString().slice(0, 10);
// earliest date that works, but show only 24 hours
// const date = new Date("2024-04-30").toISOString().slice(0, 10);
const startDate = new Date(
range === "month" ? "2024-05-01" : Date.now()
)
.toISOString()
.slice(0, 10);
this.logger.verbose(startDate);
const tomorrow = new Date(Date.now() + 1000 * 60 * 60 * 24)
.toISOString()
.slice(0, 10);
const url = `${this.haApiConfig.baseUrl}/api/history/period/${startDate}T00:00:00Z?end_time=${tomorrow}T00:00:00Z&filter_entity_id=${this.haApiConfig.waterSensorId}&minimal_response`;

// Default: 1 day from the selected date
// const date = new Date().toISOString().slice(0, 10);
// const url = `${this.haApiConfig.baseUrl}/api/history/period/${date}T00:00:00Z?filter_entity_id=${this.haApiConfig.waterSensorId}`;

const result = await got(url, {
headers: {
Expand Down
8 changes: 8 additions & 0 deletions libs/types/definitions/internal/energyUsage.yml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,14 @@ paths:
summary: Get water
description: Get water
operationId: getWater
parameters:
- in: query
name: range
schema:
type: string
enum:
- day
- month
responses:
'200':
description: Water
Expand Down
4 changes: 3 additions & 1 deletion libs/types/src/lib/generated/energyUsage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,9 @@ export interface operations {
};
getWater: {
parameters: {
query?: never;
query?: {
range?: "day" | "month";
};
header?: never;
path?: never;
cookie?: never;
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "homeremote",
"version": "3.6.1",
"version": "3.6.2",
"license": "MIT",
"scripts": {
"writeGitInfo": "ts-node --project ./tsconfig.node.json writeGitInfo.ts",
Expand Down

0 comments on commit ebdc4b4

Please sign in to comment.