Skip to content

Commit

Permalink
Get data.ts files (#30)
Browse files Browse the repository at this point in the history
* feat: get lastdata from database

* fix: function if in data.ts
  • Loading branch information
jordyBSK authored Jun 18, 2024
1 parent ad260bc commit 16af540
Show file tree
Hide file tree
Showing 6 changed files with 166 additions and 104 deletions.
6 changes: 2 additions & 4 deletions docker-compose.prod.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# Use postgres/example user/password credentials
version: '3.9'
version: "3.9"
services:

esphome:
image: esphome/esphome:2024.4
volumes:
Expand Down Expand Up @@ -64,9 +63,8 @@ services:
dockerfile: Dockerfile/Dockerfile.Nginx
image: nginx-memoires-info
ports:
- '80:80'
- "80:80"
depends_on:
- php
- postg-rest
- esphome

6 changes: 2 additions & 4 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# Use postgres/example user/password credentials
version: '3.9'
version: "3.9"
services:

esphome:
image: esphome/esphome:2024.4
volumes:
Expand Down Expand Up @@ -66,7 +65,7 @@ services:
web:
image: nginx:1.26-alpine-otel
ports:
- '80:80'
- "80:80"
volumes:
- ./Interface/dist:/var/www/memoires-info/html
- ./nginx.conf:/etc/nginx/conf.d/default.conf
Expand All @@ -76,4 +75,3 @@ services:
- postg-rest
- adminer
- esphome

60 changes: 33 additions & 27 deletions nextjs-interface/src/app/dashboard/page.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
"use client"
"use client";
import { PieChartTemperature } from "@/app/ui/dashboard/PieChartTemperature";
import { PieChartHumidity } from "@/app/ui/dashboard/PieChartHumidity";
import { useState, useEffect } from 'react';
import {redirect} from "next/navigation";
import { useState, useEffect } from "react";
import { redirect } from "next/navigation";
import { getToken } from "@/lib/context";
import { useFetchData, useLastData } from "@/lib/data";

const ESPList = [
{ name: "ESP N°1" },
Expand All @@ -20,34 +22,38 @@ export default function Page() {
const [token, setToken] = useState<string | null>(null);

useEffect(() => {
const storedToken = localStorage.getItem('token');
if (storedToken) {
setToken(storedToken);
if (getToken) {
setToken(getToken);
} else {
redirect("/login")
redirect("/login");
}
}, []);
const precision = "month";

const monthData = useFetchData(precision);
const humidity = useLastData("humidity");

const temperature = useLastData("temperature");
return (
<>
<div className="px-auto grid h-fit w-full min-w-[500px] grid-cols-1 gap-10 xl:grid-cols-2 2xl:grid-cols-3">
{ESPList.map((esp, index) => {
return (
<div
className="flex h-full flex-col items-center rounded-2xl border-2 text-center"
key={index}
>
<h2 className="w-full border-b-2 pb-5 pt-5 text-center text-gray-800">
{esp.name}
</h2>
<div className="sm:py-auto flex h-full w-full flex-row py-14">
<PieChartTemperature data={tempData} />
<PieChartHumidity data={humiData} />
</div>
</div>
);
})}
</div>
</>
<>
<div className="px-auto grid h-fit w-full min-w-[500px] grid-cols-1 gap-10 xl:grid-cols-2 2xl:grid-cols-3">
{ESPList.map((esp, index) => {
return (
<div
className="flex h-full flex-col items-center rounded-2xl border-2 text-center"
key={index}
>
<h2 className="w-full border-b-2 pb-5 pt-5 text-center text-gray-800">
{esp.name}
</h2>
<div className="sm:py-auto flex h-full w-full flex-row py-14">
<PieChartTemperature data={tempData} />
<PieChartHumidity data={humiData} />
</div>
</div>
);
})}
</div>
</>
);
}
137 changes: 68 additions & 69 deletions nextjs-interface/src/app/ui/login/LoginElement.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"use client";

import React, {FormEvent, useState} from "react";
import React, { FormEvent, useState } from "react";
import {
Card,
CardContent,
Expand All @@ -12,89 +12,88 @@ import {
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { SampleContext } from "@/lib/context";

export function LoginElement() {

const SampleContext = {
urlData: "http://climate-guardian.home/postgrest",
urlLogin: "http://climate-guardian.home/php",
urlCurrent: "http://localhost:3000"
};

const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");

const submit = async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();

await fetch(`${SampleContext.urlLogin}/login.php?username=${username}&password=${password}`, {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(reponse => {
if (reponse.error) {
setError(reponse.error);
}
if (reponse.token) {
localStorage.setItem('token', reponse.token);
localStorage.setItem('username', username);
window.location.replace(`${SampleContext.urlCurrent}/dashboard`);
}
})
.catch(e => {
console.log(e)
});
await fetch(
`${SampleContext.urlLogin}/login.php?username=${username}&password=${password}`,
{
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
},
)
.then((response) => response.json())
.then((reponse) => {
if (reponse.error) {
setError(reponse.error);
}
if (reponse.token) {
localStorage.setItem("token", reponse.token);
localStorage.setItem("username", username);
window.location.replace(`${SampleContext.urlCurrent}/dashboard`);
}
})
.catch((e) => {
console.log(e);
});
};
return (
<div className="mt-80 flex justify-center">
<form method="get" onSubmit={submit} className="mx-auto max-w-xs">
<Card className="w-full max-w-lg">
<CardHeader>
<CardTitle className="text-2xl">Login</CardTitle>
<CardDescription>
Enter your email below to login to your account.
</CardDescription>
</CardHeader>
<CardContent className="grid gap-4">
<div className="grid gap-2">
<Label htmlFor="username">Username</Label>
<Input
<Card className="w-full max-w-lg">
<CardHeader>
<CardTitle className="text-2xl">Login</CardTitle>
<CardDescription>
Enter your email below to login to your account.
</CardDescription>
</CardHeader>
<CardContent className="grid gap-4">
<div className="grid gap-2">
<Label htmlFor="username">Username</Label>
<Input
value={username}
autoComplete={"username"}
onChange={(e) => setUsername(e.target.value)}
id="username"
type="text"
placeholder="Username"
required
/>
</div>
<div className="grid gap-2">
<Label htmlFor="password">Password</Label>
<Input
id="username"
type="text"
placeholder="Username"
required
/>
</div>
<div className="grid gap-2">
<Label htmlFor="password">Password</Label>
<Input
value={password}
onChange={(e) => setPassword(e.target.value)}
id="password"
type="password"
placeholder="*****************"
required
/>
</div>
</CardContent>
<CardFooter className="flex flex-col gap-5">
<Button className="w-full" type={"submit"}>Sign in</Button>
<a
href="/dashboard"
className="w-full rounded-[7px] border-2 border-gray-800 p-2 text-center hover:bg-gray-800 hover:text-white"
>
Go to dashboard
</a>
</CardFooter>
</Card>
{error && <p className="text-red-500 mt-2">{error}</p>}
id="password"
type="password"
placeholder="*****************"
required
/>
</div>
</CardContent>
<CardFooter className="flex flex-col gap-5">
<Button className="w-full" type={"submit"}>
Sign in
</Button>
<a
href="/dashboard"
className="w-full rounded-[7px] border-2 border-gray-800 p-2 text-center hover:bg-gray-800 hover:text-white"
>
Go to dashboard
</a>
</CardFooter>
</Card>
{error && <p className="mt-2 text-red-500">{error}</p>}
</form>
</div>
);
Expand Down
21 changes: 21 additions & 0 deletions nextjs-interface/src/lib/context.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
export const SampleContext = {
urlData: "http://climate-guardian.home/postgrest",
urlLogin: "http://climate-guardian.home/php",
urlCurrent: "http://localhost:3000",
};

export function getToken() {
return localStorage.getItem("token");
}

export interface AverageData {
avg_temperature: number;
avg_humidity: number;
date: string;
}
export interface data {
temperature: number;
humidity: number;
timestamp: string;
ip: string;
}
40 changes: 40 additions & 0 deletions nextjs-interface/src/lib/data.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { useEffect, useState } from "react";
import { SampleContext, getToken, AverageData, data } from "@/lib/context";

export const useFetchData = (precision: string) => {
const [data, setData] = useState<AverageData[]>([]);

useEffect(() => {
const url = `${SampleContext.urlData}/rpc/avg_date?delta=${precision}`;
fetch(url, { headers: { Authorization: `Bearer ${getToken()}` } })
.then((response) => response.json())
.then((apiData: AverageData[]) => {
setData(apiData);
})
.catch((e) => {
console.error("Une erreur s'est produite :", e);
});
});
return data;
};

export function useLastData(type: string) {
const [temperature, setTemperature] = useState<number | undefined>(undefined);

useEffect(() => {
const url = `${SampleContext.urlData}/data?limit=1&order=timestamp.desc`;
fetch(url, { headers: { Authorization: `Bearer ${getToken()}` } })
.then((response) => response.json())
.then((apiData: data[]) => {
if (apiData && apiData.length > 0) {
if (type == "humidity") {
setTemperature(apiData[0].humidity);
} else setTemperature(apiData[0].temperature);
}
})
.catch((e) => {
console.error("Une erreur s'est produite :", e);
});
}, [type]);
return temperature;
}

0 comments on commit 16af540

Please sign in to comment.