-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathInventory.jsx
752 lines (652 loc) · 24.4 KB
/
Inventory.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
import React, {useState, useEffect} from "react";
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import Grid from '@mui/material/Grid';
import Card from '@mui/material/Card';
import CardActions from '@mui/material/CardActions';
import CardContent from '@mui/material/CardContent';
import MenuItem from '@mui/material/MenuItem';
import Select from '@mui/material/Select';
import InputLabel from '@mui/material/InputLabel';
import Chip from '@mui/material/Chip';
import Typography from '@mui/material/Typography';
import { MQTTProvider, useMQTT } from './providers/MQTTContext';
import ManageInventoryMenu from './components/ManageInventoryMenu';
import Box from '@mui/material/Box';
import Divider from '@mui/material/Divider';
import FormControlLabel from '@mui/material/FormControlLabel';
import FormControl from '@mui/material/FormControl';
import Button from '@mui/material/Button';
import Switch from '@mui/material/Switch';
import AddIcon from '@mui/icons-material/Add';
import CloseIcon from '@mui/icons-material/Close';
import FlareIcon from '@mui/icons-material/Flare';
import DeleteIcon from '@mui/icons-material/Delete';
import IconButton from '@mui/material/IconButton';
import TextField from '@mui/material/TextField';
import Tooltip from '@mui/material/Tooltip';
import LoadingButton from '@mui/lab/LoadingButton';
import CheckIcon from '@mui/icons-material/Check';
import RestartAltIcon from '@mui/icons-material/RestartAlt';
import RemoveCircleOutlineRoundedIcon from '@mui/icons-material/RemoveCircleOutlineRounded';
import CircularProgress from '@mui/material/CircularProgress';
import { useConfirm } from 'material-ui-confirm';
import { useNavigate } from 'react-router-dom';
import UnderlineSpan from "./components/UnderlineSpan";
import PioreactorIcon from "./components/PioreactorIcon";
import PioreactorIconWithModel from "./components/PioreactorIconWithModel";
import PowerSettingsNewIcon from '@mui/icons-material/PowerSettingsNew';
import {getConfig, disconnectedGrey, lostRed, inactiveGrey, readyGreen} from "./utilities"
import PlayCircleOutlinedIcon from '@mui/icons-material/PlayCircleOutlined';
import Snackbar from '@mui/material/Snackbar';
import Badge from '@mui/material/Badge';
import { useExperiment } from './providers/ExperimentContext';
const textIcon = {verticalAlign: "middle", margin: "0px 3px"}
function Header(props) {
return (
<Box>
<Box sx={{ display: "flex", justifyContent: "space-between", mb: 1 }}>
<Typography variant="h5" component="h1">
<Box fontWeight="fontWeightBold">
Inventory
</Box>
</Typography>
<Box sx={{display: "flex", flexDirection: "row", justifyContent: "flex-start", flexFlow: "wrap"}}>
<AddNewPioreactor setWorkers={props.setWorkers}/>
<Divider orientation="vertical" flexItem variant="middle"/>
<ManageInventoryMenu/>
</Box>
</Box>
<Divider sx={{marginTop: "0px", marginBottom: "15px"}} />
</Box>
)
}
function AddNewPioreactor(props){
const [open, setOpen] = useState(false);
const [name, setName] = useState("");
const [model, setModel] = useState("pioreactor_20ml"); // setModel isn't used yet
const [version, setVersion] = useState("");
const [isError, setIsError] = useState(false)
const [errorMsg, setErrorMsg] = useState("")
const [isSuccess, setIsSuccess] = useState(false)
const [successMsg, setSuccessMsg] = useState("")
const [isRunning, setIsRunning] = useState(false)
const [expectedPathMsg, setExpectedPathMsg] = useState("")
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
const handleNameChange = evt => {
setName(evt.target.value)
}
const handleVersionChange = evt => {
setVersion(evt.target.value)
}
const onSubmit = (event) =>{
event.preventDefault()
if (!name) {
setIsError(true)
setErrorMsg("Provide the hostname for the new Pioreactor worker")
return
}
else if (!version) {
setIsError(true)
setErrorMsg("Provide the model for the new Pioreactor worker. You can change the model later, too.")
return
}
setIsError(false)
setIsSuccess(false)
setIsRunning(true)
setExpectedPathMsg("Setting up your new Pioreactor...")
fetch('/api/workers/setup', {
method: "POST",
body: JSON.stringify({name: name, model: model, version: version}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
})
.then(response => {
setIsRunning(false)
setExpectedPathMsg("")
if(!response.ok){
setIsError(true)
response.json().then(data => setErrorMsg(`Unable to complete connection. The following error occurred: ${data.error}`))
} else {
setIsSuccess(true)
props.setWorkers((prevWorkers) => [...prevWorkers, {pioreactor_unit: name, is_active: true}])
setSuccessMsg(`Success! Rebooting ${name} now. Add another?`)
}
})
}
return (
<React.Fragment>
<Button onClick={handleClickOpen} style={{textTransform: 'none', float: "right", marginRight: "0px"}} color="primary">
<AddIcon fontSize="15" sx={textIcon}/> Add new Pioreactor
</Button>
<Dialog open={open} onClose={handleClose} aria-labelledby="form-dialog-title">
<DialogTitle>
Add a new Pioreactor to your cluster
<IconButton
aria-label="close"
onClick={handleClose}
sx={{
position: 'absolute',
right: 8,
top: 8,
color: (theme) => theme.palette.grey[500],
}}
size="large">
<CloseIcon />
</IconButton>
</DialogTitle>
<DialogContent>
<p>First, follow the instructions <a rel="noopener noreferrer" target="_blank" href="https://docs.pioreactor.com/user-guide/software-set-up#adding-additional-workers-to-your-cluster">here</a> to set up your new Pioreactor's worker software.</p>
<p>After,
<ol>
<li> worker image installation is complete and,</li>
<li> the new worker is powered on and, </li>
<li> the new worker is displaying a blue light, </li>
</ol>
provide the hostname you used when installing the Pioreactor image onto the Raspberry Pi, and the Pioreactor model (this can be changed later).</p>
<p>Your existing leader will automatically connect the new Pioreactor to the cluster. When finished, the new Pioreactor will show up on this page after a refresh.</p>
<div>
<TextField
required
size="small"
id="new-pioreactor-name"
label="Hostname"
variant="outlined"
sx={{mt: "15px", maxWidth: "195px"}}
onChange={handleNameChange}
value={name}
/>
<FormControl required sx={{mt: "15px", ml: "10px", minWidth: "195px"}} variant="outlined" size="small">
<InputLabel >Pioreactor model</InputLabel>
<Select
value={version}
onChange={handleVersionChange}
label="Pioreactor model"
>
<MenuItem value={"pioreactor_40ml|1.0"}>Pioreactor 40ml, v1.0</MenuItem>
<Divider/>
<MenuItem value={"pioreactor_20ml|1.1"}>Pioreactor 20ml, v1.1</MenuItem>
<MenuItem value={"pioreactor_20ml|1.0"}>Pioreactor 20ml, v1.0</MenuItem>
</Select>
</FormControl>
</div>
<Box sx={{minHeight: "60px", alignItems: "center", display: "flex"}}>
{isError ? <p><CloseIcon sx={{verticalAlign: "middle", margin: "0px 3px", color: lostRed}}/>{errorMsg}</p> : <React.Fragment/>}
{isRunning ? <p>{expectedPathMsg}</p> : <React.Fragment/>}
{isSuccess ? <p><CheckIcon sx={{verticalAlign: "middle", margin: "0px 3px", color: readyGreen}}/>{successMsg}</p> : <React.Fragment/>}
</Box>
<Box sx={{display: "flex", justifyContent: "flex-end"}}>
<LoadingButton
variant="contained"
color="primary"
sx={{marginTop: "10px", textTransform: 'none'}}
onClick={onSubmit}
type="submit"
loading={isRunning}
disabled={!name || !version}
endIcon={ <PioreactorIcon /> }
>
Add Pioreactor
</LoadingButton>
</Box>
</DialogContent>
</Dialog>
</React.Fragment>
);}
function modelStringFromModelNameAndModelVersion(modelName, modelVersion){
if (modelName === "pioreactor_20ml"){
return `Pioreactor 20ml, v${modelVersion}`
} else if (modelName === "pioreactor_40ml"){
return `Pioreactor 40ml, v${modelVersion}`
} else {
return "Unknown model"
}
}
function modelNameAndModelVersionFromModelString(modelString) {
const match = modelString.match(/^Pioreactor (\d+ml), v(.+)$/);
if (match) {
const modelName = `pioreactor_${match[1]}`;
const modelVersion = match[2];
return { modelName, modelVersion };
}
return { modelName: "unknown", modelVersion: null };
}
function WorkerCard({worker, config, leaderVersion}) {
const unit = worker.pioreactor_unit
const isLeader = (config['cluster.topology']?.leader_hostname === unit)
const [activeStatus, setActiveStatus] = React.useState(worker.is_active ? "active" : "inactive")
const [model, setModel] = React.useState([worker.model_name, worker.model_version])
const [experimentAssigned, setExperimentAssigned] = React.useState(null)
const {client, subscribeToTopic} = useMQTT();
const [state, setState] = React.useState(null)
const [versions, setVersions] = React.useState({})
const [ipv4, setIpv4] = React.useState(null)
const [WLANaddress, setWLANaddress] = React.useState(null)
const [ETHAddress, setETHAddress] = React.useState(null)
const { selectExperiment } = useExperiment();
const navigate = useNavigate()
const [snackbarOpen, setSnackbarOpen] = useState(false);
const isActive = () => {
return activeStatus === "active"
}
const handleSnackbarClose = (e, reason) => {
if (reason === 'clickaway') {
return;
}
setSnackbarOpen(false)
}
const onMonitorData = (topic, message, packet) => {
const setting = topic.toString().split('/').pop()
switch (setting) {
case "$state":
setState(message.toString());
break;
case "versions":
if (message.toString()){
setVersions(JSON.parse(message.toString()));
} else {
setVersions({})
}
break;
case "ipv4":
setIpv4(message.toString());
break;
case "wlan_mac_address":
setWLANaddress(message.toString());
break;
case "eth_mac_address":
setETHAddress(message.toString());
break;
default:
break;
}
}
const getIndicatorDotColor = (state) => {
if (state === "disconnected") {
return disconnectedGrey
}
else if (state === "lost"){
return lostRed
}
else if (state === null){
return "#ececec"
}
else {
return "#2FBB39"
}
}
const getInicatorLabel = (state, isActive) => {
if ((state === "disconnected") && isActive) {
return "Offline"
}
else if ((state === "disconnected") && !isActive){
return "Offline, change inventory status in config.ini"
}
else if (state === "lost"){
return "Lost, something went wrong. Try manually power-cycling the unit."
}
else if (state === null){
return "Waiting for information..."
}
else {
return "Online"
}
}
const handleModelChange = (event) => {
const { modelName, modelVersion } = modelNameAndModelVersionFromModelString(event.target.value);
setModel([modelName, modelVersion]);
setSnackbarOpen(true)
fetch(`/api/workers/${unit}/model`, {
method: "PUT",
body: JSON.stringify({model_name: modelName, model_version: modelVersion}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
}
const indicatorDotColor = getIndicatorDotColor(state)
const indicatorDotShadow = 2
const indicatorLabel = getInicatorLabel(state, isActive())
React.useEffect(() => {
if (unit && client) {
subscribeToTopic(`pioreactor/${unit}/$experiment/monitor/+`, onMonitorData, "WorkerCard");
const fetchExperiment = async () => {
try {
const response = await fetch(`/api/workers/${unit}/experiment`);
if (!response.ok) {
throw new Error(`No experiment found.`);
}
const json = await response.json();
setExperimentAssigned(json['experiment']);
} catch (error) {
return
}
};
fetchExperiment();
}
}, [unit, client]);
const handleStatusChange = (event) => {
setActiveStatus(event.target.checked ? "active" : "inactive");
fetch(`/api/workers/${unit}/is_active`, {
method: "PUT",
body: JSON.stringify({is_active: Number(event.target.checked) }),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
};
const onExperimentClick = () => {
selectExperiment(experimentAssigned)
navigate("/overview")
}
const softwareVersion = () => {
const { app: workerVersion } = versions;
if (!workerVersion) return "-";
if (leaderVersion && workerVersion !== leaderVersion) {
return (
<UnderlineSpan title={`Not aligned with leader's version, ${leaderVersion}`}>
{workerVersion} ❌
</UnderlineSpan>
);
}
return workerVersion;
};
return (
<>
<Card sx={{ minWidth: 275 }}>
<CardContent>
<div style={{display: "flex", justifyContent: "space-between"}}>
<div style={{display: "flex", justifyContent: "left"}}>
<Typography sx={{
fontSize: 20,
color: "rgba(0, 0, 0, 0.87)",
fontWeight: 500,
...(isActive() ? {} : { color: inactiveGrey }),
}}
gutterBottom>
<PioreactorIconWithModel model={model[0]} />
{unit}
</Typography>
<Tooltip title={indicatorLabel} placement="right">
<div>
<div className="indicator-dot" style={{boxShadow: `0 0 ${indicatorDotShadow}px ${indicatorDotColor}, inset 0 0 12px ${indicatorDotColor}`}}/>
</div>
</Tooltip>
</div>
<div>
<FormControl component="fieldset">
<FormControlLabel
checked={isActive()}
control={<Switch color="primary" onChange={handleStatusChange} size="small" />}
label={activeStatus ==="active" ? "Active" : "Inactive"}
labelPlacement="start"
/>
</FormControl>
</div>
</div>
<Box sx={{display: "flex", justifyContent: "left", ml: .5}}>
{experimentAssigned ? (
<>
<Typography variant="subtitle2" color={isActive() ? "inherit" : inactiveGrey}> Assigned to <Chip icon=<PlayCircleOutlinedIcon/> disabled={!isActive()} size="small" label={experimentAssigned} clickable onClick={onExperimentClick} /> </Typography>
</>)
: <Typography variant="subtitle2" color={isActive() ? "inherit" : inactiveGrey}> Unassigned </Typography>
}
</Box>
<Divider sx={{margin: "5px 0px"}}/>
<table style={{borderCollapse: "separate", borderSpacing: "5px", fontSize: "0.90rem"}}>
<tbody style={{color: isActive() ? "inherit" : inactiveGrey}}>
<tr>
<td style={{textAlign: "left", minWidth: "120px", color: ""}}>
Model
</td>
<td >
<Select
labelId="modelSelect"
variant="standard"
value={modelStringFromModelNameAndModelVersion(model[0], model[1])}
onChange={handleModelChange}
label="Model"
disableUnderline={true}
sx={{
"& .MuiSelect-standard": {
color: isActive() ? "inherit" : inactiveGrey
}
}}
>
<MenuItem value={"Pioreactor 40ml, v1.0"}>Pioreactor 40ml, v1.0</MenuItem>
<Divider/>
<MenuItem value={"Pioreactor 20ml, v1.1"}>Pioreactor 20ml, v1.1</MenuItem>
<MenuItem value={"Pioreactor 20ml, v1.0"}>Pioreactor 20ml, v1.0</MenuItem>
</Select>
</td>
</tr>
<tr>
<td style={{textAlign: "left", minWidth: "120px", color: ""}}>
Software version
</td>
<td >
<code style={{backgroundColor: "rgba(0, 0, 0, 0.07)", padding: "1px 4px"}}>{softwareVersion()}</code>
</td>
</tr>
<tr>
<td style={{textAlign: "left", minWidth: "120px", color: ""}}>
IPv4
</td>
<td>
<code style={{backgroundColor: "rgba(0, 0, 0, 0.07)", padding: "1px 4px"}}>{ipv4 || "-"}</code>
</td>
</tr>
<tr>
<td style={{textAlign: "left", minWidth: "120px", color: ""}}>
Raspberry Pi
</td>
<td >
<code style={{backgroundColor: "rgba(0, 0, 0, 0.07)", padding: "1px 4px"}}>{versions.rpi_machine || "-"}</code>
</td>
</tr>
<tr>
<td style={{textAlign: "left", minWidth: "120px", color: ""}}>
WLAN MAC
</td>
<td>
<code style={{backgroundColor: "rgba(0, 0, 0, 0.07)", padding: "1px 4px"}}>{WLANaddress || "-"}</code>
</td>
</tr>
<tr>
<td style={{textAlign: "left", minWidth: "120px", color: ""}}>
Ethernet MAC
</td>
<td>
<code style={{backgroundColor: "rgba(0, 0, 0, 0.07)", padding: "1px 4px"}}>{ETHAddress || "-"}</code>
</td>
</tr>
</tbody>
</table>
<Divider sx={{margin: "5px 0px"}}/>
</CardContent>
<CardActions sx={{display: "flex", justifyContent: "space-between"}}>
<Box>
<Blink unit={unit}/>
</Box>
<Box>
<Unassign unit={unit} experimentAssigned={experimentAssigned} setExperimentAssigned={setExperimentAssigned} />
<Reboot unit={unit} />
<Shutdown unit={unit} />
<Remove unit={unit} isLeader={isLeader}/>
</Box>
</CardActions>
</Card>
<Snackbar
anchorOrigin={{vertical: "bottom", horizontal: "center"}}
open={snackbarOpen}
onClose={handleSnackbarClose}
message={`Updated ${unit} to ${modelStringFromModelNameAndModelVersion(model[0], model[1])}`}
autoHideDuration={2500}
key={"snackbar" + unit + "model"}
/>
</>
)}
function Blink({unit}){
const [flashing, setFlashing] = useState(false)
const onClick = () => {
setFlashing(true)
fetch(`/api/workers/${unit}/blink`, {method: "POST"})
}
return (
<Button style={{textTransform: 'none'}} className={flashing ? 'blinkled' : ''} onClick={onClick} color="primary">
<FlareIcon color="primary" fontSize="15" sx={textIcon}/> Identify
</Button>
)}
function Reboot({unit}) {
const confirm = useConfirm();
const rebootWorker = () => {
confirm({
description: 'Rebooting this Pioreactor will halt all activity and make the Pioreactor inaccessible for a few minutes.',
title: `Reboot ${unit}?`,
confirmationText: "Confirm",
confirmationButtonProps: {color: "primary"},
cancellationButtonProps: {color: "secondary"},
}).then(() => {
fetch(`/api/units/${unit}/system/reboot`, {method: "POST"})
}).catch(() => {});
};
return (
<Button style={{textTransform: "none"}} size="small" onClick={rebootWorker}>
<RestartAltIcon fontSize="small" sx={textIcon} />Reboot
</Button>
)}
function Shutdown({unit}) {
const confirm = useConfirm();
const shworker = () => {
confirm({
description: 'Shutting down this Pioreactor will halt all activity and require a power-cycle to bring it back up.',
title: `Shutdown ${unit}?`,
confirmationText: "Confirm",
confirmationButtonProps: {color: "primary"},
cancellationButtonProps: {color: "secondary"},
}).then(() => {
fetch(`/api/units/${unit}/system/shutdown`, {method: "POST"})
}).catch(() => {});
};
return (
<Button style={{textTransform: "none"}} size="small" onClick={shworker}>
<PowerSettingsNewIcon fontSize="small" sx={textIcon} />Shutdown
</Button>
)}
function Unassign({unit, experimentAssigned, setExperimentAssigned}) {
const unassignWorker = () => {
fetch(`/api/experiments/${experimentAssigned}/workers/${unit}`, {method: "DELETE"})
.then((res) => {
if (res.ok){
setExperimentAssigned(null)
}
})
};
return (
<Button disabled={!experimentAssigned} style={{textTransform: "none"}} size="small" onClick={unassignWorker}>
<RemoveCircleOutlineRoundedIcon fontSize="small" sx={textIcon} />Unassign
</Button>
)}
function Remove({unit, isLeader}) {
const navigate = useNavigate()
const confirm = useConfirm();
const removeWorker = () => {
confirm({
description: 'Removing this Pioreactor will unassign it from any experiments, halt all activity running, and remove it from your inventory. No experiment data is removed, and calibration data still exists on the worker.',
title: `Remove ${unit} from inventory?`,
confirmationText: "Confirm",
confirmationButtonProps: {color: "primary"},
cancellationButtonProps: {color: "secondary"},
}).then(() => {
fetch(`/api/workers/${unit}`, {method: "DELETE"})
.then((response) => {
if (response.ok){
navigate(0)
}
})
}).catch(() => {});
};
return (
<Button color="secondary" style={{textTransform: "none"}} disabled={isLeader} size="small" onClick={removeWorker}>
<DeleteIcon disabled={isLeader} color={isLeader ? "text.disabled" : "secondary"} fontSize="small" sx={textIcon}/> Remove
</Button>
)}
function InventoryDisplay({isLoading, workers, config}){
const [leaderVersion, setLeaderVersion] = React.useState(null)
React.useEffect(() => {
async function getLeaderVersion() {
await fetch("/unit_api/versions/app")
.then((response) => {
return response.json();
})
.then((data) => {
setLeaderVersion(data['version'])
});
}
getLeaderVersion()
}, [])
return (
<Grid container spacing={2}>
{isLoading ? <div style={{textAlign: "center", margin: 'auto', marginTop: "50px"}}><CircularProgress /> </div>: (
<>
{workers.map(worker =>
<Grid key={worker.pioreactor_unit} item md={6} xs={12} sm={12}>
<WorkerCard worker={worker} config={config} leaderVersion={leaderVersion}/>
</Grid>
)}
</>
)}
</Grid>
)}
function Inventory({title}) {
const [workers, setWorkers] = useState([]);
const [config, setConfig] = useState({})
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
document.title = title;
}, [title]);
useEffect(() => {
getConfig(setConfig)
fetchWorkers();
}, []);
const fetchWorkers = async () => {
setIsLoading(true)
try {
const response = await fetch(`/api/workers`);
if (response.ok) {
const data = await response.json();
setWorkers(data);
} else {
console.error('Failed to fetch workers:', response.statusText);
}
} catch (error) {
console.error('Error fetching workers:', error);
} finally {
setIsLoading(false)
}
};
return (
<MQTTProvider name="cluster" config={config}>
<Grid container spacing={2} >
<Grid item md={12} xs={12}>
<Header setWorkers={setWorkers}/>
<InventoryDisplay isLoading={isLoading} workers={workers} config={config} />
<Grid item xs={12}>
<p style={{textAlign: "center", marginTop: "30px"}}>Learn more about <a href="https://docs.pioreactor.com/user-guide/create-cluster" target="_blank" rel="noopener noreferrer">inventory and cluster management</a>.</p>
</Grid>
</Grid>
</Grid>
</MQTTProvider>
)
}
export default Inventory;