81 lines
2.4 KiB
JavaScript
81 lines
2.4 KiB
JavaScript
import React, { useState, useEffect, useCallback } from "react";
|
|
import PropTypes from "prop-types";
|
|
import { IconButton, Tooltip } from "@material-ui/core";
|
|
import { PowerSettingsNew } from "@material-ui/icons";
|
|
import { useTranslation } from "react-i18next";
|
|
import { useToast } from "../../../hooks";
|
|
import * as api from "../api";
|
|
|
|
const initialState = { on: false };
|
|
const defaultPingInterval = 1200000; //20 minutes
|
|
|
|
const WakeComponent = ({ machine, addLog }) => {
|
|
const [state, setState] = useState(initialState);
|
|
const [trigger, setTrigger] = useState(false);
|
|
const { t } = useTranslation();
|
|
const { success, error } = useToast();
|
|
|
|
const pingInterval =
|
|
process.env.REACT_APP_MACHINE_PING_INTERVAL || defaultPingInterval;
|
|
|
|
const getCurrentDateTime = useCallback(() => {
|
|
const currentDateTime = Date.now();
|
|
const result = t("DATE_FORMAT", {
|
|
date: { value: currentDateTime, format: "DD-MM-YYYY HH:mm:ss" }
|
|
});
|
|
return result;
|
|
}, [t]);
|
|
|
|
const wakeMachine = useCallback(async () => {
|
|
const result = await api.wakeMachine(machine.macAddress);
|
|
setState(prev => ({ ...prev, on: result.success }));
|
|
addLog(
|
|
`[${getCurrentDateTime()}] [Wake]: Success: ${result.success}. Status: ${
|
|
result.status
|
|
}`
|
|
);
|
|
if (result.success) {
|
|
success(result.status);
|
|
} else {
|
|
error(result.status);
|
|
}
|
|
}, [addLog, getCurrentDateTime, success, error, machine.macAddress]);
|
|
|
|
useEffect(() => {
|
|
api.pingMachine(machine.iPv4Address || machine.machineName).then(result => {
|
|
setState(prev => ({ ...prev, on: result.success }));
|
|
addLog(
|
|
`[${getCurrentDateTime()}] [Ping]: Success: ${
|
|
result.success
|
|
}. Status: ${result.status}`
|
|
);
|
|
});
|
|
setTimeout(() => {
|
|
setTrigger(prev => !prev);
|
|
}, pingInterval);
|
|
}, [machine, addLog, getCurrentDateTime, pingInterval, trigger]);
|
|
|
|
return (
|
|
<Tooltip title={t(state.on ? "Machine.PoweredOn" : "Machine.Actions.Wake")}>
|
|
<span>
|
|
<IconButton
|
|
id={`machine-${machine.machineId}-wake`}
|
|
size={"small"}
|
|
disabled={state.on}
|
|
onClick={wakeMachine}
|
|
style={state.on ? { color: "#33cc33" } : {}}
|
|
>
|
|
<PowerSettingsNew />
|
|
</IconButton>
|
|
</span>
|
|
</Tooltip>
|
|
);
|
|
};
|
|
|
|
WakeComponent.propTypes = {
|
|
machine: PropTypes.object.isRequired,
|
|
addLog: PropTypes.func.isRequired
|
|
};
|
|
|
|
export default WakeComponent;
|