Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prepare a system stats global state for future "new version banner" #1246

Merged
merged 5 commits into from
Jan 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 0 additions & 130 deletions www/src/Pages/HomePage.jsx

This file was deleted.

99 changes: 99 additions & 0 deletions www/src/Pages/HomePage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import React, { useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { ProgressBar } from 'react-bootstrap';

import useSystemStats from '../Store/useSystemStats';
import Section from '../Components/Section';

export default function HomePage() {
const { t } = useTranslation('');
const {
latestVersion,
latestDownloadUrl,
currentVersion,
boardConfigProperties,
memoryReport,
getSystemStats,
loading,
} = useSystemStats();

useEffect(() => {
getSystemStats();
}, []);

if (loading) {
return (
<div className="d-flex justify-content-center align-items-center loading">
<div className="spinner-border" role="status">
<span className="visually-hidden">{t('Common:loading-text')}</span>
</div>
</div>
);
}
return (
<div>
<h1>{t('HomePage:header-text')}</h1>
<p>{t('HomePage:sub-header-text')}</p>
<Section title={t('HomePage:system-stats-header-text')}>
<div>
<strong className="system-text">{t('HomePage:version-text')}</strong>
<div className="system-text">{`${boardConfigProperties.label} (${boardConfigProperties.fileName}.uf2)`}</div>
<div className="system-text">
{t('HomePage:current-text', { version: currentVersion })}
</div>
<div className="system-text">
{t('HomePage:latest-text', { version: latestVersion })}
</div>
{latestVersion &&
currentVersion?.split('-').length == 1 &&
currentVersion !== latestVersion && (
<div className="mt-3 mb-3">
<a
target="_blank"
rel="noreferrer"
href={latestDownloadUrl}
className="btn btn-primary"
>
{t('HomePage:get-update-text')}
</a>
</div>
)}

<strong className="system-text">
{t('HomePage:memory-header-text')}
</strong>
<div className="system-text">
{t('HomePage:memory-flash-text')}: {memoryReport.usedFlash} /{' '}
{memoryReport.totalFlash} ({memoryReport.percentageFlash}%)
</div>
<div className="system-text">
{t('HomePage:memory-heap-text')}: {memoryReport.usedHeap} /{' '}
{memoryReport.totalHeap} ({memoryReport.percentageHeap}%)
</div>
<div className="system-text">
{t('HomePage:memory-static-allocations-text')}:{' '}
{memoryReport.staticAllocs}
</div>
<div>
{t('HomePage:memory-board-text')}: {memoryReport.physicalFlash}
</div>

<ProgressBar
className="my-1 system-text w-50"
now={memoryReport.percentageFlash}
label={`${t('HomePage:memory-flash-text')} ${
memoryReport.percentageFlash
}%`}
/>
<ProgressBar
className="my-1 system-text w-50"
now={memoryReport.percentageHeap}
label={`${t('HomePage:memory-heap-text')} ${
memoryReport.percentageHeap
}%`}
/>
</div>
</Section>
</div>
);
}
32 changes: 2 additions & 30 deletions www/src/Services/WebApi.js
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,8 @@ async function getAddonsOptions(setLoading) {
const data = response.data;
setLoading(false);

response.data.turboLedColor = rgbIntToHex(response.data.turboLedColor) || '#ffffff';
response.data.turboLedColor =
rgbIntToHex(response.data.turboLedColor) || '#ffffff';

// Merge saved keyMappings with defaults
const keyboardHostMap = Object.entries(data.keyboardHostMap).reduce(
Expand Down Expand Up @@ -614,33 +615,6 @@ async function setPeripheralOptions(mappings) {
});
}

async function getFirmwareVersion(setLoading) {
setLoading(true);

try {
const response = await Http.get(`${baseUrl}/api/getFirmwareVersion`);
console.log('got firmware version:', response.data);
setLoading(false);
return response.data;
} catch (error) {
setLoading(false);
console.error(error);
}
}

async function getMemoryReport(setLoading) {
setLoading(true);

try {
const response = await Http.get(`${baseUrl}/api/getMemoryReport`);
setLoading(false);
return response.data;
} catch (error) {
setLoading(false);
console.error(error);
}
}

async function getUsedPins(setLoading) {
setLoading(true);

Expand Down Expand Up @@ -734,8 +708,6 @@ export default {
getButtonLayoutDefs,
getSplashImage,
setSplashImage,
getFirmwareVersion,
getMemoryReport,
getUsedPins,
getHeldPins,
abortGetHeldPins,
Expand Down
110 changes: 110 additions & 0 deletions www/src/Store/useSystemStats.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import { create } from 'zustand';
import { baseUrl } from '../Services/WebApi';

const percentage = (x, y) => parseFloat(((x / y) * 100).toFixed(2));
const toKB = (x) => parseFloat((x / 1024).toFixed(2));

type State = {
latestVersion: string;
latestDownloadUrl: string;
currentVersion: string;
boardConfigProperties: {
label: string;
fileName: string;
};
memoryReport: {
percentageFlash: number;
percentageHeap: number;
physicalFlash: number;
staticAllocs: number;
totalFlash: number;
totalHeap: number;
usedFlash: number;
usedHeap: number;
};
loading: boolean;
error: boolean;
};

type Actions = {
getSystemStats: () => void;
};

const INITIAL_STATE: State = {
latestVersion: '',
latestDownloadUrl: '',
currentVersion: '',
boardConfigProperties: {
label: '',
fileName: '',
},
memoryReport: {
percentageFlash: 0,
percentageHeap: 0,
physicalFlash: 0,
staticAllocs: 0,
totalFlash: 0,
totalHeap: 0,
usedFlash: 0,
usedHeap: 0,
},
loading: false,
error: false,
};

const useSystemStats = create<State & Actions>()((set) => ({
...INITIAL_STATE,
getSystemStats: async () => {
set({ loading: true });

try {
const [firmwareVersion, memoryReport, latestRelease] = await Promise.all([
fetch(`${baseUrl}/api/getFirmwareVersion`).then((res) => res.json()),
fetch(`${baseUrl}/api/getMemoryReport`).then((res) => res.json()),
fetch(
'https://api.github.com/repos/OpenStickCommunity/GP2040-CE/releases/latest',
).then((res) => res.json()),
]);
const latestDownloadUrl =
latestRelease.assets?.find(
({ name }) =>
name
?.substring(name.lastIndexOf('_') + 1)
?.replace('.uf2', '')
?.toLowerCase() === firmwareVersion.boardConfig.toLowerCase(),
)?.browser_download_url ||
`https://github.com/OpenStickCommunity/GP2040-CE/releases/tag/${latestRelease.data.tag_name}`;

set({
currentVersion: firmwareVersion.version,
latestVersion: latestRelease.tag_name,
latestDownloadUrl,
boardConfigProperties: {
label: firmwareVersion.boardConfigLabel,
fileName: firmwareVersion.boardConfigFileName,
},
memoryReport: {
physicalFlash: toKB(memoryReport.physicalFlash),
staticAllocs: toKB(memoryReport.staticAllocs),
totalFlash: toKB(memoryReport.totalFlash),
totalHeap: toKB(memoryReport.totalHeap),
usedFlash: toKB(memoryReport.usedFlash),
usedHeap: toKB(memoryReport.usedHeap),
percentageFlash: percentage(
memoryReport.usedFlash,
memoryReport.totalFlash,
),
percentageHeap: percentage(
memoryReport.usedHeap,
memoryReport.totalHeap,
),
},
loading: false,
});
} catch (error) {
set({ error: true, loading: false });
}
},
}));

export default useSystemStats;
Loading