Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

iotdeviceadd

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 8

import React, { useEffect, useState } from "react";

import { Col, Container, Row, Button, Modal, Form } from "react-bootstrap";


import Breadcrumb from "react-bootstrap/Breadcrumb";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faArrowRight, faHouseChimney, faArrowLeft } from "@fortawesome/free-solid-
svg-icons";
import { useNavigate, useParams } from "react-router-dom";
import { useSelector } from "react-redux";
import { SealCheck } from "@phosphor-icons/react";
import axios from "axios";
import { useIOTDevice } from "../../hook/useIotDevice";
import { initialIOTDeviceData } from "../../state/iotDeviceComponentState";
import { fetchMachineAssignedStatus, fetchMachineOptions, saveMachineMapping } from
"../../services/allServices/IOTdeviceService";
import { Dropdown } from "primereact/dropdown";

export const IotDeviceFormSec = ({ isToggled }) => {


const { id } = useParams();
const { saveOrUpdateIotDeviceData, fetchIotDevicebyId } = useIOTDevice();

const [validated, setValidated] = useState(false);


const [iotDeviceData, setIOTdeviceData] = useState(initialIOTDeviceData);
const [show, setShow] = useState(false);
const [show01, setShow01] = useState(false);
const [modalMessage, setModalMessage] = useState("");
const [isError, setIsError] = useState(false);
const [machineOptions, setMachineOptions] = useState([]);
const [selectedMachine, setSelectedMachine] = useState("");
const [isAssigned, setIsAssigned] = useState(false);

const yardUuid = useSelector((state) => state.auth.yardUuid);


const navigate = useNavigate();

const handleClose = () => setShow01(false);

const handleNavigate = () => {


navigate("/pages/iot-device-list");
};

useEffect(() => {
if (id) {
const loadIotDevice = async () => {
const deviceData = await fetchIotDevicebyId(id);
if (deviceData) {
setIOTdeviceData({
...deviceData,
yardUuid: deviceData.yardUuid || yardUuid,
});
}
};
loadIotDevice();
}
}, [id, yardUuid]);

// useEffect(() => {
// if (iotDeviceData.deviceType) {
// // Fetch machine options based on device type
// axios
// .get(`http://localhost:9092/api/machines/get-machines/$
{iotDeviceData.deviceType}`)
// .then((response) => {
// if (response.data) {
// setMachineOptions(response.data);
// }
// })
// .catch((error) => {
// console.error("Error fetching machines:", error);
// });
// }
// }, [iotDeviceData.deviceType]);

useEffect(() => {
if (iotDeviceData.deviceType) {
// Use the service to fetch machine options
fetchMachineOptions(iotDeviceData.deviceType)
.then((options) => {
setMachineOptions(options); // Update machine options state
})
.catch((error) => {
console.error("Error fetching machines:", error);
});
}
}, [iotDeviceData.deviceType]);

const handleChange = (e) => {


const { name, value } = e.target;
setIOTdeviceData((prevData) => ({
...prevData,
[name]: value,
yardUuid: yardUuid, // Ensure yardId is included
}));
};

const handleMachineChange = (e) => {


setSelectedMachine(e.target.value);
};

const handleSubmit = async (event) => {


event.preventDefault();
const form = event.currentTarget;

if (form.checkValidity() === false) {


setValidated(true);
return;
} else {
// Save IoT device data
const response = await saveOrUpdateIotDeviceData(iotDeviceData);
if (response && response.status) {
// Success response for IoT data
const successMessage = response.message || "IoT Data Saved Successfully";
setModalMessage(successMessage);
setIsError(false);
setShow(true);
setIOTdeviceData(initialIOTDeviceData);
setValidated(false);
// Send machine mapping data to backend using service
try {
const machineMappingResponse = await saveMachineMapping(
response.data.id,
selectedMachine
);

// If machine mapping is successful


if (machineMappingResponse) {
('Machine successfully mapped');
} else {
console.error('Error mapping machine');
}
} catch (error) {
console.error('Error mapping machine:', error);
}
} else {
// Error response for IoT data
const errorMessage = response.message || "Unexpected error occurred";
setModalMessage(errorMessage);
setIsError(true);
setShow(true);
setTimeout(() => setShow(false), 3000);
console.error("Form submission failed:", errorMessage);
}
}
};

useEffect(() => {
if (selectedMachine) {
// Fetch the assigned status of the machine
axios
.get(`http://192.168.1.21:9092/api/machines/${selectedMachine}/$
{iotDeviceData.deviceType}/assigned`)
.then((response) => {
if (response.data !== undefined) {
setIsAssigned(response.data); // This will be either `true` or `false`
}
if (response.data === true) {
setShow01(true); // Show `show01` if the machine is not assigned
} else {
setShow01(false); // Hide `show01` if the machine is assigned
}
})
.catch((error) => {
console.error("Error fetching machines:", error);
});
}
}, [selectedMachine]);

// useEffect(() => {
// if (selectedMachine) {
// // Use the service to fetch the machine's assigned status
// fetchMachineAssignedStatus(selectedMachine, iotDeviceData.deviceType)
// .then((status) => {
// setIsAssigned(status); // Update assigned status
// setShow01(!status); // Show `show01` based on assigned status
// })
// .catch((error) => {
// console.error("Error fetching machines:", error);
// });
// }
// }, [selectedMachine, iotDeviceData.deviceType]);

const handleConfirm = () => {


("Unassigning previous device and continuing with the new one...");
setShow01(false); // Close the modal after confirmation
};

const BackPage = () => {


navigate("/pages/iot-device-list");
};

return (
<React.Fragment>
<div
className={isToggled ? "inner-content p-3 expand-inner-content" : "inner-
content p-3"}
>
<Container>
<Breadcrumb>
<Breadcrumb.Item href="/pages/dashboard">
<FontAwesomeIcon icon={faHouseChimney} />
</Breadcrumb.Item>
<Breadcrumb.Item href="/pages/iot-device-list">
IOT Device List
</Breadcrumb.Item>
<Breadcrumb.Item active>
{iotDeviceData.id ? "Edit Device" : "Add Device"}
</Breadcrumb.Item>
</Breadcrumb>
<Row>
<Col lg={12}>
<div className="title">
<h2 className="mb-0">
{iotDeviceData.id ? "Edit Device" : "Add Device"}
</h2>
</div>
</Col>
</Row>
<div className="form-wrap">
<Form noValidate validated={validated} onSubmit={handleSubmit}>
<Row className="mb-3">
{/* Iot Device Name */}
{/* Iot Device Name */}
<Col md="4">
<Form.Group
className="form-group"
controlId="validationCustom01"
>
<Form.Label>Device Name</Form.Label>
<Form.Control
name="deviceName"
value={iotDeviceData.deviceName}
onChange={handleChange}
required
type="text"
placeholder="Enter Device Name"
pattern="^[A-Za-z\s]+$"
/>
<Form.Control.Feedback type="invalid">
Please enter a valid Machine Name.
</Form.Control.Feedback>
</Form.Group>
</Col>

{/* Machine ID/Code */}


<Col md="4">
<Form.Group
className="form-group"
controlId="validationCustom04"
>
<Form.Label>Device Serial Number</Form.Label>
<Form.Control
name="deviceSerialNumber"
value={iotDeviceData.deviceSerialNumber}
onChange={handleChange}
required
type="text"
placeholder="Enter Serial Number"
/>
<Form.Control.Feedback type="invalid">
Please enter a valid Device Serial Number.
</Form.Control.Feedback>
</Form.Group>
</Col>

{/* Manufacturer Name */}


<Col md="4">
<Form.Group
className="form-group"
controlId="validationCustom06"
>
<Form.Label>Manufacturer Name</Form.Label>
<Form.Control
name="manufacturer"
value={iotDeviceData.manufacturer}
onChange={handleChange}
required
type="text"
placeholder="Enter Manufacturer Name"
/>
<Form.Control.Feedback type="invalid">
Please enter a valid Manufacturer Name.
</Form.Control.Feedback>
</Form.Group>
</Col>
{/* Device Event */}
<Col md="4">
<Form.Group controlId="deviceType" className="form-group">
<Form.Label>Device Type</Form.Label>
<div className="card flex justify-content-center border-0">
<Dropdown
value={iotDeviceData.deviceType}
options={[
{ label: 'Select Device Event', value: '' },
{ label: 'Lock', value: 'lock-event' },
{ label: 'Engine', value: 'engine-event' },
{ label: 'All', value: 'all' },
]}
onChange={(e) => handleChange({ target: { name:
'deviceType', value: e.value } })}
placeholder="Select Device Event"
required
/>
</div>
</Form.Group>
</Col>

{/* <Col md="4">


<Form.Group className="form-group" controlId="deviceType">
<Form.Label>Device Type</Form.Label>
<Form.Control
as="select"
name="deviceType"
value={iotDeviceData.deviceType}
onChange={handleChange}
required
>
<option value="">Select Device Event</option>
<option value="Lock">lock</option>
<option value="Engine">engine</option>
<option value="all">all</option>
</Form.Control>
</Form.Group>
</Col> */}

{/* Machine Dropdown */}


{/* <Col md="4">
<Form.Group className="form-group" controlId="machine">
<Form.Label>Machine</Form.Label>
<Form.Control
as="select"
value={selectedMachine}
onChange={handleMachineChange}
required
>
<option value="">Select Machine</option>
{machineOptions.map((machine) => (
<option key={machine.uuid} value={machine.uuid}>
{machine.machineName}
</option>
))}
</Form.Control>
</Form.Group>
</Col> */}

<Col md="4">
<Form.Group className="form-group" controlId="machine">
<div className="card flex justify-content-center border-0">
<Form.Label>Machine</Form.Label>
<Dropdown
value={selectedMachine}
options={machineOptions.map((machine) => ({
label: machine.machineName,
value: machine.uuid,
}))}
onChange={handleMachineChange}
placeholder="Select Machine"
required
/>
</div>
</Form.Group>
</Col>
</Row>
<Modal centered show={show01} onHide={handleClose}
className="success-modal">
<Modal.Body>
<Modal.Title className="fs-6 text-black text-center">
<SealCheck
size={50}
className={isError ? "text-danger d-block mx-auto mb-2" :
"text-success d-block mx-auto mb-2"}
/>
The device is already assigned. Do you want to unassign the
previous device and continue with the current one?
</Modal.Title>
<div className="text-center">
<Button variant="secondary" onClick={handleClose}
className="me-2">
Cancel
</Button>
<Button variant="danger" onClick={handleConfirm}>
Unassign and Continue
</Button>
</div>
</Modal.Body>
</Modal>

<div className="d-flex justify-content-between">


<Button type="submit" variant="primary" className="btn-style-
primary2 mt-2" onClick={BackPage}>
<div className="btn-icon-style">
<FontAwesomeIcon icon={faArrowLeft} />
</div>
Back
</Button>
<Button type="submit" variant="primary" className="btn-style-
primary mt-2">
<div className="btn-icon-style">
<FontAwesomeIcon icon={faArrowRight} />
</div>
{iotDeviceData.id ? "Update" : "Submit"}
</Button>
</div>
</Form>
</div>
<Modal centered show={show} onHide={handleClose} className="success-
modal">
<Modal.Body>
<Modal.Title className="fs-6 text-black text-center">
<SealCheck
size={50}
className={isError ? "text-danger d-block mx-auto mb-2" : "text-
success d-block mx-auto mb-2"}
/>
{modalMessage}
</Modal.Title>

{/* Conditionally render button based on error */}


{!isError && (
<Button
type="submit"
variant="primary"
className="btn-style-primary mt-3 mx-auto"
onClick={handleNavigate}
>
<div className="btn-icon-style">
<FontAwesomeIcon icon={faArrowRight} />
</div>
IOT Device List
</Button>
)}
</Modal.Body>
</Modal>
</Container>
</div>
</React.Fragment>
);
};

You might also like