add parse int

This commit is contained in:
2025-06-07 17:07:54 +01:00
parent ca733ba483
commit 6a2a793797
6 changed files with 223 additions and 118 deletions

View File

@@ -11,7 +11,7 @@ const Connectivity = () => {
const [mqttConfig, setMqttConfig] = useState({
enabled: false,
host: '',
port: 1883,
port: 1883, // Inicialmente trata-se como número
username: '',
password: '',
topic: '',
@@ -21,7 +21,6 @@ const Connectivity = () => {
// Carregar as configurações Wi-Fi e MQTT
useEffect(() => {
const load = async () => {
try {
const wifi = await get('/api/v1/config/wifi');
setWifiConfig(wifi); // Atualiza as configurações Wi-Fi
@@ -55,7 +54,12 @@ const Connectivity = () => {
// Salvar configuração MQTT
const saveMqtt = async () => {
try {
await post('/api/v1/config/mqtt', mqttConfig); // Envia as configurações de MQTT para o servidor
// Garante que o valor de port seja sempre um número válido
const updatedMqttConfig = {
...mqttConfig,
port: parseInt(mqttConfig.port, 10) || 1883, // Caso o valor seja inválido, define como 1883
};
await post('/api/v1/config/mqtt', updatedMqttConfig); // Envia as configurações de MQTT para o servidor
setMqttMsg('Configuração MQTT gravada!');
} catch (error) {
setMqttMsg('Erro ao gravar MQTT.');
@@ -67,20 +71,18 @@ const Connectivity = () => {
{loading ? (
<p>A carregar...</p>
) : (
<>
{/* Configuração Wi-Fi */}
<h2 className="text-xl font-semibold mt-4">Configuração Wi-Fi</h2>
{wifiMsg && <div className="p-2 bg-gray-200 rounded mb-2">{wifiMsg}</div>}
<form className="flex flex-col gap-4" onSubmit={e => { e.preventDefault(); saveWifi(); }}>
<div>
<div>
<label className="flex items-center gap-2">
Ativar WIFI
<input
type="checkbox"
checked={wifiConfig.enabled}
onChange={e => setMqttConfig({ ...wifiConfig, enabled: e.target.checked })}
onChange={e => setWifiConfig({ ...wifiConfig, enabled: e.target.checked })}
/>
</label>
</div>
@@ -90,9 +92,10 @@ const Connectivity = () => {
<input
id="wifi-ssid"
type="text"
className="border border-gray-300 rounded px-3 py-2 w-full"
className={`border border-gray-300 rounded px-3 py-2 w-full ${!wifiConfig.enabled ? 'bg-gray-200 text-gray-500 cursor-not-allowed' : ''}`}
value={wifiConfig.ssid}
onChange={e => setWifiConfig({ ...wifiConfig, ssid: e.target.value })}
disabled={!wifiConfig.enabled}
/>
</div>
@@ -101,17 +104,24 @@ const Connectivity = () => {
<input
id="wifi-password"
type="password"
className="border border-gray-300 rounded px-3 py-2 w-full"
className={`border border-gray-300 rounded px-3 py-2 w-full ${!wifiConfig.enabled ? 'bg-gray-200 text-gray-500 cursor-not-allowed' : ''}`}
value={wifiConfig.password}
onChange={e => setWifiConfig({ ...wifiConfig, password: e.target.value })}
disabled={!wifiConfig.enabled}
/>
</div>
<div>
<button className="bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700" type="submit">Guardar</button>
<button
className={`bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700`}
type="submit"
>
Guardar
</button>
</div>
</form>
{/* Configuração MQTT */}
<h2 className="text-xl font-semibold mt-6">Configuração MQTT</h2>
{mqttMsg && <div className="p-2 bg-gray-200 rounded mb-2">{mqttMsg}</div>}
<form className="flex flex-col gap-4" onSubmit={e => { e.preventDefault(); saveMqtt(); }}>
@@ -131,9 +141,10 @@ const Connectivity = () => {
<input
id="mqtt-host"
type="text"
className="border border-gray-300 rounded px-3 py-2 w-full"
className={`border border-gray-300 rounded px-3 py-2 w-full ${!mqttConfig.enabled ? 'bg-gray-200 text-gray-500 cursor-not-allowed' : ''}`}
value={mqttConfig.host}
onChange={e => setMqttConfig({ ...mqttConfig, host: e.target.value })}
disabled={!mqttConfig.enabled}
/>
</div>
@@ -142,9 +153,10 @@ const Connectivity = () => {
<input
id="mqtt-port"
type="number"
className="border border-gray-300 rounded px-3 py-2 w-full"
className={`border border-gray-300 rounded px-3 py-2 w-full ${!mqttConfig.enabled ? 'bg-gray-200 text-gray-500 cursor-not-allowed' : ''}`}
value={mqttConfig.port}
onChange={e => setMqttConfig({ ...mqttConfig, port: parseInt(e.target.value || 0) })}
onChange={e => setMqttConfig({ ...mqttConfig, port: parseInt(e.target.value || 0, 10) || 1883 })}
disabled={!mqttConfig.enabled}
/>
</div>
@@ -153,9 +165,10 @@ const Connectivity = () => {
<input
id="mqtt-username"
type="text"
className="border border-gray-300 rounded px-3 py-2 w-full"
className={`border border-gray-300 rounded px-3 py-2 w-full ${!mqttConfig.enabled ? 'bg-gray-200 text-gray-500 cursor-not-allowed' : ''}`}
value={mqttConfig.username}
onChange={e => setMqttConfig({ ...mqttConfig, username: e.target.value })}
disabled={!mqttConfig.enabled}
/>
</div>
@@ -164,9 +177,10 @@ const Connectivity = () => {
<input
id="mqtt-password"
type="password"
className="border border-gray-300 rounded px-3 py-2 w-full"
className={`border border-gray-300 rounded px-3 py-2 w-full ${!mqttConfig.enabled ? 'bg-gray-200 text-gray-500 cursor-not-allowed' : ''}`}
value={mqttConfig.password}
onChange={e => setMqttConfig({ ...mqttConfig, password: e.target.value })}
disabled={!mqttConfig.enabled}
/>
</div>
@@ -175,14 +189,20 @@ const Connectivity = () => {
<input
id="mqtt-topic"
type="text"
className="border border-gray-300 rounded px-3 py-2 w-full"
className={`border border-gray-300 rounded px-3 py-2 w-full ${!mqttConfig.enabled ? 'bg-gray-200 text-gray-500 cursor-not-allowed' : ''}`}
value={mqttConfig.topic}
onChange={e => setMqttConfig({ ...mqttConfig, topic: e.target.value })}
disabled={!mqttConfig.enabled}
/>
</div>
<div>
<button className="bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700" type="submit">Guardar</button>
<button
className={`bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700`}
type="submit"
>
Guardar
</button>
</div>
</form>
</>

View File

@@ -47,6 +47,21 @@ export default function ElectricalNetwork() {
}
};
// Função para lidar com as alterações de valores numéricos
const handleLoadBalancingCurrentLimitChange = (e) => {
setLoadBalancing({
...loadBalancing,
currentLimit: parseInt(e.target.value, 10) || 0 // Converte para número
});
};
const handleSolarCapacityChange = (e) => {
setSolar({
...solar,
capacity: parseFloat(e.target.value) || 0 // Converte para número
});
};
return (
<PageLayout title="Rede Elétrica">
{msg && <div className="p-2 mb-2 bg-green-600 text-white rounded">{msg}</div>}
@@ -140,7 +155,7 @@ export default function ElectricalNetwork() {
type="number"
className="border border-gray-300 rounded px-3 py-2 w-full"
value={loadBalancing.currentLimit}
onChange={e => setLoadBalancing({ ...loadBalancing, currentLimit: e.target.value })}
onChange={handleLoadBalancingCurrentLimitChange} // Aplicando a conversão para número
/>
</div>
@@ -152,7 +167,7 @@ export default function ElectricalNetwork() {
type="number"
className="border border-gray-300 rounded px-3 py-2 w-full"
value={solar.capacity}
onChange={e => setSolar({ ...solar, capacity: e.target.value })}
onChange={handleSolarCapacityChange} // Aplicando a conversão para número
/>
</div>
<div>

View File

@@ -1,5 +1,3 @@
// src/pages/LoadBalancing.js
import { useState, useEffect } from 'react';
import { get, post } from '../api';
import PageLayout from '../components/PageLayout';
@@ -66,6 +64,11 @@ export default function LoadBalancing() {
}
};
// Função para lidar com a mudança na corrente máxima
const handleMaxChargingCurrentChange = (e) => {
setMaxChargingCurrent(parseInt(e.target.value, 10)); // Garantir que o valor seja um número
};
return (
<PageLayout title="Configuração de Load Balancing">
{msg && <div className="p-2 mb-2 bg-green-600 text-white rounded">{msg}</div>}
@@ -96,7 +99,7 @@ export default function LoadBalancing() {
min="1"
max="32"
className="border border-gray-300 rounded px-3 py-2 w-full"
onChange={(e) => setMaxChargingCurrent(e.target.value)}
onChange={handleMaxChargingCurrentChange} // Alterado para usar a função que converte o valor
/>
</div>

View File

@@ -8,6 +8,7 @@ const OCPP = () => {
const [loading, setLoading] = useState(true);
const [config, setConfig] = useState({
enabled: false,
url: '',
chargeBoxId: '',
certificate: '',
@@ -48,61 +49,74 @@ const OCPP = () => {
<p>A carregar...</p>
) : (
<>
{status && (
<div>
<p>Versão: {status.ocpp_version}</p>
<p>Status: {status.status}</p>
</div>
)}
{msg && <div className="p-2 mb-2 bg-gray-200 rounded">{msg}</div>}
<form className="flex flex-col gap-4" onSubmit={e => { e.preventDefault(); save(); }}>
<div>
<label className="block mb-1" htmlFor="ocpp-url">Servidor:</label>
<input
id="ocpp-url"
type="text"
className="border border-gray-300 rounded px-3 py-2 w-full"
value={config.url}
onChange={e => setConfig({ ...config, url: e.target.value })}
/>
</div>
<div>
<label className="flex items-center gap-2">
Ativar OCPP
<input
type="checkbox"
checked={config.enabled}
onChange={e => setConfig({ ...config, enabled: e.target.checked })} // Corrigido para usar e.target.checked
/>
</label>
</div>
<div>
<label className="block mb-1" htmlFor="ocpp-id">Charge Box ID:</label>
<input
id="ocpp-id"
type="text"
className="border border-gray-300 rounded px-3 py-2 w-full"
value={config.chargeBoxId}
onChange={e => setConfig({ ...config, chargeBoxId: e.target.value })}
/>
</div>
<div>
<label className="block mb-1" htmlFor="ocpp-url">Servidor:</label>
<input
id="ocpp-url"
type="text"
className={`border border-gray-300 rounded px-3 py-2 w-full ${!config.enabled ? 'bg-gray-200 text-gray-500 cursor-not-allowed' : ''}`}
value={config.url}
onChange={e => setConfig({ ...config, url: e.target.value })}
disabled={!config.enabled} // Desabilita o campo se o checkbox estiver desmarcado
/>
</div>
<div>
<label className="block mb-1" htmlFor="ocpp-id">Charge Box ID:</label>
<input
id="ocpp-id"
type="text"
className={`border border-gray-300 rounded px-3 py-2 w-full ${!config.enabled ? 'bg-gray-200 text-gray-500 cursor-not-allowed' : ''}`}
value={config.chargeBoxId}
onChange={e => setConfig({ ...config, chargeBoxId: e.target.value })}
disabled={!config.enabled} // Desabilita o campo se o checkbox estiver desmarcado
/>
</div>
<div>
<label className="block mb-1" htmlFor="ocpp-cert">Certificado:</label>
<textarea
id="ocpp-cert"
className={`border border-gray-300 rounded px-3 py-2 w-full ${!config.enabled ? 'bg-gray-200 text-gray-500 cursor-not-allowed' : ''}`}
value={config.certificate}
onChange={e => setConfig({ ...config, certificate: e.target.value })}
disabled={!config.enabled} // Desabilita o campo se o checkbox estiver desmarcado
/>
</div>
<div>
<label className="block mb-1" htmlFor="ocpp-key">Chave Privada:</label>
<textarea
id="ocpp-key"
className={`border border-gray-300 rounded px-3 py-2 w-full ${!config.enabled ? 'bg-gray-200 text-gray-500 cursor-not-allowed' : ''}`}
value={config.privateKey}
onChange={e => setConfig({ ...config, privateKey: e.target.value })}
disabled={!config.enabled} // Desabilita o campo se o checkbox estiver desmarcado
/>
</div>
<div>
<button className={`bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700`} type="submit">Guardar</button>
</div>
</form>
<div>
<label className="block mb-1" htmlFor="ocpp-cert">Certificado:</label>
<textarea
id="ocpp-cert"
className="border border-gray-300 rounded px-3 py-2 w-full"
value={config.certificate}
onChange={e => setConfig({ ...config, certificate: e.target.value })}
/>
</div>
<div>
<label className="block mb-1" htmlFor="ocpp-key">Chave Privada:</label>
<textarea
id="ocpp-key"
className="border border-gray-300 rounded px-3 py-2 w-full"
value={config.privateKey}
onChange={e => setConfig({ ...config, privateKey: e.target.value })}
/>
</div>
<div>
<button className="bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700" type="submit">Guardar</button>
</div>
</form>
</>
)}
</PageLayout>

View File

@@ -1,20 +1,24 @@
// src/pages/Security.jsx
import React, { useState } from 'react';
import React, { useState, useEffect } from 'react';
import PageLayout from '../components/PageLayout';
import { post, get } from '../api'; // Supondo que os métodos post e get estejam definidos na API.
const Security = () => {
// Estado para armazenar se MFA está habilitado e os métodos de autenticação
const [isMFAEnabled, setIsMFAEnabled] = useState(false);
// Estado para armazenar os métodos de autenticação
const [authMethods, setAuthMethods] = useState({
RFID: false,
App: false,
Password: true,
Password: false,
});
// Estado para armazenar a lista de usuários
const [users, setUsers] = useState([
{ username: 'admin' },
{ username: 'user1' },
]);
// Estado para o novo nome de usuário
const [newUser, setNewUser] = useState('');
// Função para alterar os métodos de autenticação
const handleAuthMethodChange = (method) => {
setAuthMethods({
...authMethods,
@@ -22,22 +26,54 @@ const Security = () => {
});
};
const addUser = (username) => {
setUsers([...users, { username }]);
// Função para buscar os dados de autenticação da API
const fetchAuthMethods = async () => {
try {
const data = await get('/api/v1/config/auth-methods'); // Busca os dados de authMethods da API
setAuthMethods(data); // Preenche o estado com os dados recebidos
} catch (error) {
console.error('Erro ao buscar configurações de autenticação:', error);
alert('Erro ao buscar configurações de autenticação.');
}
};
// Função para enviar os dados para a API
const handleSubmit = async (e) => {
e.preventDefault(); // Evita que a página seja recarregada ao enviar o formulário
try {
await post('/api/v1/config/auth-methods', authMethods); // Envia os dados de authMethods para o servidor
alert('Configurações de Autorização salvas com sucesso!');
} catch (error) {
console.error('Erro ao salvar configurações:', error);
alert('Erro ao salvar configurações.');
}
};
// Função para adicionar um novo usuário
const addUser = () => {
if (newUser.trim() !== '') {
setUsers([...users, { username: newUser }]);
setNewUser(''); // Limpa o campo de entrada após adicionar
}
};
// Função para remover um usuário
const removeUser = (username) => {
setUsers(users.filter((user) => user.username !== username));
};
// Use o useEffect para buscar os dados de autenticação quando o componente for montado
useEffect(() => {
fetchAuthMethods();
}, []);
return (
<PageLayout title="Segurança">
{/* Métodos de Autorização */}
<div className="mb-5">
<h2 className="text-xl font-semibold mb-2">Métodos de Autorização</h2>
<div className="flex flex-col gap-2">
<form className="flex flex-col gap-2" onSubmit={handleSubmit}>
<label className="flex items-center gap-2">
RFID
<input
@@ -62,37 +98,54 @@ const Security = () => {
onChange={() => handleAuthMethodChange('Password')}
/>
</label>
</div>
<button
type="submit"
className="bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700 mt-4"
>
Salvar Configurações
</button>
</form>
</div>
{/* Utilizador */}
<div className="overflow-x-auto mb-5">
<h2 className="text-xl font-semibold mb-4">Utilizador</h2>
<table className="min-w-full border border-gray-300 text-left table-auto">
<thead className="bg-gray-100">
<tr>
<th className="border-b p-2 text-sm font-medium text-gray-700">Nome de Usuário</th>
<th className="border-b p-2 text-sm font-medium text-gray-700">Ações</th>
</tr>
</thead>
<tbody>
{users.map((user, index) => (
<tr key={index} className="hover:bg-gray-50">
<td className="border-b p-2 text-sm">{user.username}</td>
<td className="border-b p-2 text-sm text-red-600">
<button onClick={() => removeUser(user.username)}>Remover</button>
</td>
</tr>
))}
</tbody>
</table>
<div className="mt-4">
<button className="bg-green-600 text-white px-4 py-2 rounded" onClick={() => addUser('newuser', 'User')}>Adicionar Novo Usuário</button>
</div>
</div>
{/* Utilizadores */}
<div className="overflow-x-auto mb-5">
<h2 className="text-xl font-semibold mb-4">Utilizadores</h2>
<table className="min-w-full border border-gray-300 text-left table-auto">
<thead className="bg-gray-100">
<tr>
<th className="border-b p-2 text-sm font-medium text-gray-700">Nome de Usuário</th>
<th className="border-b p-2 text-sm font-medium text-gray-700">Ações</th>
</tr>
</thead>
<tbody>
{users.map((user, index) => (
<tr key={index} className="hover:bg-gray-50">
<td className="border-b p-2 text-sm">{user.username}</td>
<td className="border-b p-2 text-sm text-red-600">
<button onClick={() => removeUser(user.username)}>Remover</button>
</td>
</tr>
))}
</tbody>
</table>
<div className="mt-4">
<input
type="text"
className="border border-gray-300 rounded px-3 py-2 w-full mb-2"
value={newUser}
onChange={(e) => setNewUser(e.target.value)} // Atualiza o valor do novo nome de usuário
placeholder="Digite o nome de usuário"
/>
<button
className="bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700 w-full"
onClick={addUser}
>
Adicionar Novo Usuário
</button>
</div>
</div>
</PageLayout>
);

View File

@@ -31,11 +31,11 @@ const Settings = () => {
fetchSettings();
}, []);
const handleCurrentLimitChange = (e) => setCurrentLimit(e.target.value);
const handlePowerLimitChange = (e) => setPowerLimit(e.target.value);
const handleEnergyLimitChange = (e) => setEnergyLimit(e.target.value);
const handleChargingTimeLimitChange = (e) => setChargingTimeLimit(e.target.value);
const handleTemperatureLimitChange = (e) => setTemperatureLimit(e.target.value);
const handleCurrentLimitChange = (e) => setCurrentLimit(parseInt(e.target.value, 10));
const handlePowerLimitChange = (e) => setPowerLimit(parseInt(e.target.value, 10));
const handleEnergyLimitChange = (e) => setEnergyLimit(parseInt(e.target.value, 10));
const handleChargingTimeLimitChange = (e) => setChargingTimeLimit(parseInt(e.target.value, 10));
const handleTemperatureLimitChange = (e) => setTemperatureLimit(parseInt(e.target.value, 10));
const handleSubmit = async (e) => {
e.preventDefault();