added graphs to the bin details section on the new page and started working on the sensors

This commit is contained in:
csawatzky 2026-05-22 13:12:54 -06:00
parent acdc18ce28
commit 67b251d865
13 changed files with 897 additions and 93 deletions

2
package-lock.json generated
View file

@ -46,7 +46,7 @@
"mui-tel-input": "^7.0.0", "mui-tel-input": "^7.0.0",
"notistack": "^3.0.1", "notistack": "^3.0.1",
"openweathermap-ts": "^1.2.10", "openweathermap-ts": "^1.2.10",
"protobuf-ts": "git+https://gitlab+deploy-token-50627:hv8mB4WkyvtjBpJKU1rN@gitlab.com/brandx/protobuf-ts.git#staging", "protobuf-ts": "git+https://gitlab+deploy-token-50627:hv8mB4WkyvtjBpJKU1rN@gitlab.com/brandx/protobuf-ts.git#master",
"query-string": "^9.2.1", "query-string": "^9.2.1",
"react": "^18.3.1", "react": "^18.3.1",
"react-beautiful-dnd": "^13.1.1", "react-beautiful-dnd": "^13.1.1",

View file

@ -12,21 +12,28 @@ import { Controller } from "models/Controller";
import { GrainCable } from "models/GrainCable"; import { GrainCable } from "models/GrainCable";
import { pond } from "protobuf-ts/pond"; import { pond } from "protobuf-ts/pond";
import BinDetails from "./components/binDetails"; import BinDetails from "./components/binDetails";
import { Plenum } from "models/Plenum";
import BinSensors from "./components/binSensors";
interface Props { interface Props {
bin: Bin bin: Bin
devices: Device[] devices: Device[]
cables?: GrainCable[] cables?: GrainCable[]
plenums?: Plenum[]
fans?: Controller[] fans?: Controller[]
heaters?: Controller[] heaters?: Controller[]
permissions: pond.Permission[] permissions: pond.Permission[]
componentDevices: Map<string, number> componentDevices: Map<string, number>
componentMap: Map<string, Component> componentMap: Map<string, Component>
binPrefs?: Map<string, pond.BinComponentPreferences> binPrefs?: Map<string, pond.BinComponentPreferences>
setPreferences: React.Dispatch<
React.SetStateAction<Map<string, pond.BinComponentPreferences> | undefined>
>;
updateBinCallback?: (bin: Bin) => void updateBinCallback?: (bin: Bin) => void
} }
export default function BinSummary(props: Props){ export default function BinSummary(props: Props){
const {bin, devices, fans, heaters, permissions, componentDevices, componentMap, binPrefs, updateBinCallback} = props const {bin, devices, fans, heaters, permissions, componentDevices, componentMap, binPrefs, updateBinCallback, cables = [], plenums = [], setPreferences} = props
//const [currentDevice, setCurrentDevice] = useState<Device | undefined>(undefined) //const [currentDevice, setCurrentDevice] = useState<Device | undefined>(undefined)
const isMobile = useMobile() const isMobile = useMobile()
@ -38,11 +45,9 @@ export default function BinSummary(props: Props){
const activity = (reading: string) => { const activity = (reading: string) => {
//if the device hasnt checked in in 6 hours = missing 12 hours = inactive within 6 hours = live //if the device hasnt checked in in 6 hours = missing 12 hours = inactive within 6 hours = live
let status = "Live" let status = "Live"
let colour = "#4caf50" let colour = "#4caf50"
let diff = moment().diff(moment(reading), "hour") let diff = moment().diff(moment(reading), "hour")
console.log(diff)
if(diff > 12){ if(diff > 12){
status = "Inactive" status = "Inactive"
colour = red[700] colour = red[700]
@ -172,24 +177,21 @@ export default function BinSummary(props: Props){
</Card> </Card>
</Grid2> </Grid2>
<Grid2 size={isMobile ? 12 : 5}> <Grid2 size={isMobile ? 12 : 5}>
<Card raised sx={{height: 600}}> <Card raised sx={{ height: 600, display: "flex", flexDirection: "column", overflow: "hidden" }}>
<BinDetails <BinDetails
bin={bin} bin={bin}
updateBinCallback={updateBinCallback} updateBinCallback={updateBinCallback}
componentDevices={componentDevices} componentDevices={componentDevices}
devices={devices} devices={devices}
linkedComponents={componentMap} linkedComponents={componentMap}
permissions={permissions}/> permissions={permissions}
cables={cables}
plenums={plenums}/>
</Card> </Card>
</Grid2> </Grid2>
<Grid2 size={12}> <Grid2 size={12}>
<Card> <Card>
{sensorData()} <BinSensors components={componentMap} bin={bin} preferences={binPrefs} setPreferences={setPreferences}/>
</Card>
</Grid2>
<Grid2 size={12}>
<Card>
{controllerStatus()}
</Card> </Card>
</Grid2> </Grid2>
</Grid2> </Grid2>

View file

@ -86,6 +86,7 @@ export default function bin3dVisualizer(props: Props){
setOpenModeChange(true) setOpenModeChange(true)
}} }}
> >
<MenuItem value={pond.BinMode.BIN_MODE_NONE}>Select Mode..</MenuItem>
<MenuItem value={pond.BinMode.BIN_MODE_STORAGE}>Storage</MenuItem> <MenuItem value={pond.BinMode.BIN_MODE_STORAGE}>Storage</MenuItem>
<MenuItem value={pond.BinMode.BIN_MODE_DRYING}>Drying</MenuItem> <MenuItem value={pond.BinMode.BIN_MODE_DRYING}>Drying</MenuItem>
<MenuItem value={pond.BinMode.BIN_MODE_HYDRATING}>Hydrating</MenuItem> <MenuItem value={pond.BinMode.BIN_MODE_HYDRATING}>Hydrating</MenuItem>
@ -161,6 +162,7 @@ export default function bin3dVisualizer(props: Props){
<Box> <Box>
<Typography sx={{fontWeight: 650, fontSize: 20}}> <Typography sx={{fontWeight: 650, fontSize: 20}}>
Controllers Controllers
</Typography>
{fans && fans.map(fan => { {fans && fans.map(fan => {
let isOn = controllerState(fan) let isOn = controllerState(fan)
return ( return (
@ -219,7 +221,6 @@ export default function bin3dVisualizer(props: Props){
</Box> </Box>
</Box> </Box>
)})} )})}
</Typography>
</Box> </Box>
// loop through controllers displaying each one // loop through controllers displaying each one

View file

@ -10,8 +10,6 @@ import React, { useCallback, useEffect, useState } from "react";
interface Props { interface Props {
linkedComponents: Map<string, Component>; //the component key to the component object linkedComponents: Map<string, Component>; //the component key to the component object
componentDevices: Map<string, number>; componentDevices: Map<string, number>;
bin: Bin
devices: Device[];
permissions: pond.Permission[] permissions: pond.Permission[]
} }
@ -45,68 +43,70 @@ export default function BinAlerts(props: Props){
}; };
const load = useCallback(()=>{ const load = useCallback(()=>{
//load the interactions for the linked components if(!loading){
setLoading(true) //load the interactions for the linked components
const newInteractions: Interaction[] = []; setLoading(true)
const interactionSourceMap = new Map<string, string>(); const newInteractions: Interaction[] = [];
const sinkOptions: Component[] = []; const interactionSourceMap = new Map<string, string>();
const run = async () => { const sinkOptions: Component[] = [];
// Run all component API fetches in parallel const run = async () => {
await Promise.all( // Run all component API fetches in parallel
[...linkedComponents].map(async ([key, comp]) => { await Promise.all(
const device = componentDevices.get(key); [...linkedComponents].map(async ([key, comp]) => {
const device = componentDevices.get(key);
if (device) {
const resp = await interactionsAPI.listInteractionsByComponent( if (device) {
device, const resp = await interactionsAPI.listInteractionsByComponent(
comp.location(), device,
undefined, comp.location(),
as undefined,
); as
);
resp.forEach(interaction => interactionSourceMap.set(interaction.key(), key));
newInteractions.push(...resp); resp.forEach(interaction => interactionSourceMap.set(interaction.key(), key));
} newInteractions.push(...resp);
}
// Collect controller components
if (extension(comp.type()).isController) { // Collect controller components
sinkOptions.push(comp); if (extension(comp.type()).isController) {
} sinkOptions.push(comp);
}) }
); })
}; );
};
run().then(() => {
newInteractions.forEach(interaction => { run().then(() => {
//alert and control are not mutally exclusive, it is possible to be both if the control is sending notifications newInteractions.forEach(interaction => {
if (interaction.isAlert()) { //alert and control are not mutally exclusive, it is possible to be both if the control is sending notifications
// Find matching alert if (interaction.isAlert()) {
let similarAlertIndex = alerts.findIndex(alert => // Find matching alert
matchConditions(interaction, alert) let similarAlertIndex = alerts.findIndex(alert =>
); matchConditions(interaction, alert)
);
const compKey = interactionSourceMap.get(interaction.key());
const component = compKey ? linkedComponents.get(compKey) : undefined; const compKey = interactionSourceMap.get(interaction.key());
const component = compKey ? linkedComponents.get(compKey) : undefined;
if (component) {
if (similarAlertIndex === -1) { if (component) {
alerts.push({ if (similarAlertIndex === -1) {
conditions: interaction.settings.conditions, alerts.push({
sourceComponents: [component], conditions: interaction.settings.conditions,
}); sourceComponents: [component],
} else { });
alerts[similarAlertIndex].sourceComponents.push(component); } else {
alerts[similarAlertIndex].sourceComponents.push(component);
}
}
}
});
setAlerts(alerts);
}).catch(err => {
console.error("Interaction fetch error:", err)
}).finally(() => {
setLoading(false)
})
} }
}
}
});
setAlerts(alerts);
}).catch(err => {
console.error("Interaction fetch error:", err)
}).finally(() => {
setLoading(false)
})
},[linkedComponents, interactionsAPI, componentDevices, as]) },[linkedComponents, interactionsAPI, componentDevices, as])
useEffect(()=>{ useEffect(()=>{

View file

@ -0,0 +1,410 @@
import { Avatar, Box, Button, CardHeader, Checkbox, FormControlLabel, Grid2, Theme, Tooltip, Typography } from "@mui/material";
import { useMobile, useThemeType } from "hooks";
import VPDDark from "assets/products/Ag/dryingDark.png";
import VPDLight from "assets/products/Ag/dryingLight.png";
import TrendLight from "assets/products/Ag/trendingLight.png";
import TrendDark from "assets/products/Ag/trendingDark.png";
import { useEffect, useState } from "react";
import { makeStyles } from "@mui/styles";
import moment, { Moment } from "moment";
import { blue, orange, teal } from "@mui/material/colors";
import { GrainDryingPoint } from "charts/GrainDryingChart";
import { GrainCable } from "models/GrainCable";
import { Plenum } from "models/Plenum";
import BinGraphsVPD from "bin/graphs/BinGraphsVPD";
import { UnitMeasurement } from "models/UnitMeasurement";
import { Bin } from "models";
import { useBinAPI, useGlobalState } from "providers";
import TimeBar from "common/time/TimeBar";
import { GetDefaultDateRange } from "common/time/DateRange";
import { ZoomOut } from "@mui/icons-material";
import BinGraphsTrending from "bin/graphs/BinGraphsTrending";
import { DataPoint, TrendPoint } from "charts/TrendingChart";
import WaterLight from "assets/products/Ag/waterContentLight.png";
import WaterDark from "assets/products/Ag/waterContentDark.png";
import { Pressure } from "models/Pressure";
import { DataPoint as WaterPoint } from "charts/WaterLevelChart";
import BinWaterLevel from "bin/graphs/BinWaterLevel";
import { Controller } from "models/Controller";
import { pond } from "protobuf-ts/pond";
interface Props {
cables: GrainCable[]
plenums: Plenum[]
componentDevices: Map<string, number>
bin: Bin
}
const useStyles = makeStyles((theme: Theme) =>{
return ({
root: {
display: "flex",
flexDirection: "column",
height: "100%",
overflow: "hidden",
},
toolbar: {
flexShrink: 0,
},
scrollContent: {
flex: 1,
minHeight: 0,
overflowY: "auto",
},
card: {
position: "relative",
display: "flex",
height: "100%",
flexDirection: "column",
overflow: "visible"
},
cardHeader: {
padding: theme.spacing(1),
paddingLeft: theme.spacing(2),
marginRight: 10
},
avatarIcon: {
width: 33,
height: 33
}
})
});
export default function BinAnalysisGraphs(props: Props){
const {cables, plenums, componentDevices, bin} = props
const themeType = useThemeType()
const classes = useStyles()
const [{user, as, showErrors}, dispatch] = useGlobalState()
const isMobile = useMobile()
const [xDomain, setXDomain] = useState<string[] | number[]>(["dataMin", "dataMax"]);
const [zoomed, setZoomed] = useState(false);
const [recentVPD, setRecentVPD] = useState<GrainDryingPoint | undefined>();
const [loading, setLoading] = useState(false)
// map using the component key and the unitmeasurements for that component
const [compMeasurements, setCompMeasurements] = useState<Map<string, UnitMeasurement[]>>(
new Map<string, UnitMeasurement[]>()
);
const binAPI = useBinAPI()
const defaultDateRange = GetDefaultDateRange()
const [startDate, setStartDate] = useState<Moment>(defaultDateRange.start);
const [endDate, setEndDate] = useState<Moment>(defaultDateRange.end);
const [recentPlenumTrend, setRecentPlenumTrend] = useState<TrendPoint | undefined>();
const [recentCableTrend, setRecentCableTrend] = useState<DataPoint | undefined>();
const [recentWaterContent, setRecentWaterContent] = useState<WaterPoint | undefined>();
useEffect(() => {
let measurementMap: Map<string, UnitMeasurement[]> = new Map<string, UnitMeasurement[]>();
if (!loading) {
setLoading(true);
//check if the bin has a fan to use the cfm in the drying graph
// if (bin.settings.fan?.type !== pond.FanType.FAN_TYPE_UNKNOWN) {
// setIncludeCFM(true);
// }
binAPI
.listBinComponentsMeasurements(
bin.key(),
startDate.toISOString(),
endDate.toISOString(),
showErrors,
showErrors,
as
)
.then(resp => {
resp.data.measurements.forEach((um: any) => {
let unitMeasurement = UnitMeasurement.any(um, user);
let entry = measurementMap.get(unitMeasurement.componentId);
if (entry) {
entry.push(unitMeasurement);
} else {
measurementMap.set(unitMeasurement.componentId, [unitMeasurement]);
}
});
setCompMeasurements(measurementMap);
setLoading(false);
});
}
}, [bin, binAPI, startDate, endDate, user, as]); // eslint-disable-line react-hooks/exhaustive-deps
const zoomOut = () => {
setXDomain(["dataMin", "dataMax"]);
setZoomed(false);
};
const zoomIn = (domain: string[] | number[]) => {
if (!isMobile) {
setXDomain(domain);
setZoomed(true);
}
};
const updateDateRange = (newStartDate: any, newEndDate: any) => {
let range = GetDefaultDateRange();
range.start = newStartDate;
range.end = newEndDate;
setStartDate(newStartDate);
setEndDate(newEndDate);
};
//this uses the components found in the bins status
const waterGraph = () => {
let moistureCables: pond.GrainCable[] = [];
bin.status.grainCables.forEach(cable => {
if (cable.relativeHumidity.length > 0) {
moistureCables.push(cable);
}
});
if (bin.status.plenums[0] && moistureCables[0] && bin.status.pressures[0] && bin.supportedGrain()) {
return (
<Box>
<BinWaterLevel
bin={bin}
// range={{ start: startDate, end: endDate }}
start={startDate.toISOString()}
end={endDate.toISOString()}
plenumKey={componentDevices.get(bin.status.plenums[0].key) + ":" + bin.status.plenums[0].key}
cableKey={componentDevices.get(moistureCables[0].key) + ":" + moistureCables[0].key}
pressureKey={componentDevices.get(bin.status.pressures[0].key) + ":" + bin.status.pressures[0].key}
fanKey={
bin.status.fans.length > 0
? componentDevices.get(bin.status.fans[0].key) + ":" + bin.status.fans[0].key
: undefined
}
newXDomain={xDomain}
multiGraphZoom={zoomIn}
multiGraphZoomOut
returnLast={lastWater => {
setRecentWaterContent(lastWater);
}}
/>
</Box>
);
} else {
return (
<Box minHeight={100} display="flex" justifyContent="center" alignItems="center">
<Typography style={{ fontWeight: 650 }}>
Plenum with pressure and moisture cable as well as an initial moisture and supported
grain type set in the bin settings required to calculate Water Content
</Typography>
</Box>
);
}
};
return (
<Box className={classes.root}>
<Box className={classes.toolbar} display="flex" justifyContent="space-between">
<Box>
<TimeBar startDate={startDate} endDate={endDate} updateDateRange={updateDateRange}/>
</Box>
<Box>
{zoomed && (
<Tooltip title="Zoom Out Graphs">
<Button variant="outlined" onClick={zoomOut}>
<ZoomOut />
</Button>
</Tooltip>
)}
<FormControlLabel
label="Show Errors"
control={
<Checkbox
checked={showErrors}
onChange={() => {
//setShowErrors(!showErrors);
dispatch({ key: "showErrors", value: !showErrors });
}}
/>
}
/>
</Box>
</Box>
<Box className={classes.scrollContent}>
<CardHeader
avatar={
<Avatar
variant="square"
src={themeType === "light" ? VPDDark : VPDLight}
className={classes.avatarIcon}
alt={"Drying Score"}
/>
}
title={
<Grid2 container direction="row" justifyContent="space-between">
<Grid2 >
<Typography style={{ fontSize: 25, fontWeight: 650 }}>
Drying vs. Hydrating
</Typography>
</Grid2>
</Grid2>
}
subheader={
recentVPD ? (
<Grid2 container>
<Grid2 size={{ xs: 12 }}>
<span>
<span style={{ color: recentVPD.dryScore > 0 ? orange[500] : blue[500] }}>
{recentVPD.dryScore > 0 ? "drying" : "hydrating"}
</span>
<span>{" : "}</span>
<span
style={{
color: recentVPD.dryScore > 0 ? orange[500] : blue[500],
fontWeight: 500
}}>
{recentVPD.dryScore.toFixed(2)}
</span>
<br />
</span>
</Grid2>
<Grid2 size={{ xs: 12 }}>
<Typography color="textSecondary" variant={"caption"}>
{moment(recentVPD.timestamp).fromNow()}
</Typography>
</Grid2>
</Grid2>
) : (
<Typography variant="body1" color="textPrimary">
No Data
</Typography>
)
}
/>
<Box padding={1}>
{cables.length > 0 && plenums.length > 0 ? (
<BinGraphsVPD
cables={cables}
plenums={plenums}
measurementMap={compMeasurements}
newXDomain={xDomain}
multiGraphZoom={zoomIn}
multiGraphZoomOut
//perBushelCFM={includeCFM ? bin.status.cfmPerBushel : undefined}
returnLastVPD={lastVPD => {
setRecentVPD(lastVPD);
}}
/>
) : (
<Box minHeight={100} display="flex" justifyContent="center" alignItems="center">
<Typography style={{ fontWeight: 650 }}>
Plenum and moisture cable required to calculate VPD
</Typography>
</Box>
)}
</Box>
<CardHeader
avatar={
<Avatar
variant="square"
src={themeType === "light" ? TrendDark : TrendLight}
className={classes.avatarIcon}
alt={"VPD"}
/>
}
title={
<Typography style={{ fontSize: 25, fontWeight: 650 }}>Moisture Trending</Typography>
}
subheader={
recentPlenumTrend && recentCableTrend ? (
<Grid2 container>
<Grid2 size={{ xs: 12 }}>
<span>
{"Plenum Moisture: "}
<span style={{ color: orange[500], fontWeight: 500 }}>
{recentPlenumTrend.trend.toFixed(2)}
</span>
<br />
</span>
<span>
{"Grain Moisture: "}
<span style={{ color: teal[500], fontWeight: 500 }}>
{recentCableTrend.moisture.toString()}
</span>
<br />
</span>
</Grid2>
<Grid2 size={{ xs: 12 }}>
<Typography color="textSecondary" variant={"caption"}>
{recentPlenumTrend.timestamp > recentCableTrend.timestamp
? moment(recentPlenumTrend.timestamp).fromNow()
: moment(recentCableTrend.timestamp).fromNow()}
</Typography>
</Grid2>
</Grid2>
) : (
<Typography variant="body1" color="textPrimary">
No Data
</Typography>
)
}
/>
<Box padding={1}>
{cables.length > 0 && plenums.length > 0 ? (
<BinGraphsTrending
cables={cables}
plenums={plenums}
measurementMap={compMeasurements}
bin={bin}
newXDomain={xDomain}
multiGraphZoom={zoomIn}
multiGraphZoomOut
returnLastMeasurements={(lastData, lastTrend) => {
setRecentCableTrend(lastData);
setRecentPlenumTrend(lastTrend);
}}
/>
) : (
<Box minHeight={100} display="flex" justifyContent="center" alignItems="center">
<Typography style={{ fontWeight: 650 }}>
Plenum and moisture cable required to calculate trending data
</Typography>
</Box>
)}
</Box>
<CardHeader
avatar={
<Avatar
variant="square"
src={themeType === "light" ? WaterDark : WaterLight}
className={classes.avatarIcon}
alt={"VPD"}
/>
}
title={
<Typography style={{ fontSize: 25, fontWeight: 650 }}>Grain Water Content</Typography>
}
subheader={
recentWaterContent &&
bin.settings.inventory &&
bin.settings.inventory.initialMoisture > 0 ? (
<Grid2 container>
<Grid2 size={{ xs: 12 }}>
<span>
{"Water Content: "}
<span style={{ color: blue[500], fontWeight: 500 }}>
{recentWaterContent.liters && !isNaN(recentWaterContent.liters)
? recentWaterContent.liters.toFixed(2)
: ""}
</span>
<br />
</span>
</Grid2>
<Grid2 size={{ xs: 12 }}>
<Typography color="textSecondary" variant={"caption"}>
{moment(recentWaterContent.timestamp).fromNow()}
</Typography>
</Grid2>
</Grid2>
) : (
<Typography variant="body1" color="textPrimary">
No Data
</Typography>
)
}
/>
<Box padding={1}>
{waterGraph()}
</Box>
</Box>
</Box>
)
}

View file

@ -0,0 +1,186 @@
import { LinearProgress } from "@mui/material";
import { Bin, Component, Device, Interaction } from "models";
import Controls, { Control } from "objects/objectInteractions/Controls";
import NewObjectInteraction from "objects/objectInteractions/NewObjectInteraction";
import { sameComponentID } from "pbHelpers/Component";
import { extension } from "pbHelpers/ComponentType";
import { pond } from "protobuf-ts/pond";
import { quack } from "protobuf-ts/quack";
import { useGlobalState } from "providers";
import interactionsAPI, { useInteractionsAPI } from "providers/pond/interactionsAPI";
import React, { useCallback, useEffect, useState } from "react";
interface Props {
linkedComponents: Map<string, Component>; //the component key to the component object
componentDevices: Map<string, number>;
devices: Device[];
permissions: pond.Permission[]
}
export default function BinControls(props: Props) {
const {linkedComponents, componentDevices, devices, permissions} = props
const [{as}] = useGlobalState()
const interactionsAPI = useInteractionsAPI()
const [controls, setControls] = useState<Control[]>([]);
const [selectedDevice, setSelectedDevice] = useState<Device | undefined>(undefined)
const [openNewInteraction, setOpenNewInteraction] = useState(false)
const [loading, setLoading] = useState(false)
const findDevice = (deviceID: number) => {
for (let device of devices) {
if (device.id() === deviceID) return device
}
}
const findSinkComponent = (sinks: Component[], interactionSink: quack.ComponentID, sourceDevice: number) => {
for (let component of sinks) {
if (sameComponentID(component.location(), interactionSink) && sourceDevice === componentDevices.get(component.key())){
return component
}
}
}
const matchConditions = (interaction: Interaction, set: Control) => {
//if the number of conditions are not the same they are different
if (interaction.settings.conditions.length !== set.conditions.length) {
return false;
}
//continue with the comparison
let matching = true;
interaction.settings.conditions.forEach((condition, i) => {
if (
condition.comparison !== set.conditions[i].comparison ||
condition.measurementType !== set.conditions[i].measurementType ||
condition.value !== set.conditions[i].value
) {
matching = false;
}
});
return matching;
};
const matchResult = (interaction: Interaction, set: Control) => {
let interactionResult = interaction.settings.result
let setResult = set.result
let matching = true
// if anything in the result for the interaction is different from the set make matching false
if(interactionResult?.type !== setResult?.type ||
interactionResult?.mode !== setResult?.mode ||
interactionResult?.value !== setResult?.value ||
interactionResult?.dutyCycle !== setResult?.dutyCycle
){
matching = false
}
return matching
}
const load = useCallback(()=>{
if(!loading){
setLoading(true)
const newInteractions: Interaction[] = [];
const interactionSourceMap = new Map<string, string>();
const sinkOptions: Component[] = [];
const controls: Control[] = [];
const run = async () => {
// Run all component API fetches in parallel
await Promise.all(
[...linkedComponents].map(async ([key, comp]) => {
const device = componentDevices.get(key);
if (device) {
const resp = await interactionsAPI.listInteractionsByComponent(
device,
comp.location(),
undefined,
as
);
resp.forEach(interaction => interactionSourceMap.set(interaction.key(), key));
newInteractions.push(...resp);
}
// Collect controller components
if (extension(comp.type()).isController) {
sinkOptions.push(comp);
}
})
);
};
run().then(() => {
newInteractions.forEach(interaction => {
if (interaction.isControl()) {
if (!interaction.settings.sink) return //if there is no sink it cant be a control so move on to the next
const compKey = interactionSourceMap.get(interaction.key());
if (!compKey) return //we have to have a valid component key
const component = linkedComponents.get(compKey);
const deviceID = componentDevices.get(compKey);
if (!deviceID) return //we have to know which device it is for
const controlDevice = findDevice(deviceID)
if (!controlDevice) return //failed to get the device from the array
const sinkComponent = findSinkComponent(sinkOptions, interaction.settings.sink, deviceID)
if (!sinkComponent) return //failed to get the correct sink component
let similarControlIndex = controls.findIndex(control =>
matchConditions(interaction, control) &&
matchResult(interaction, control) &&
sameComponentID(interaction.settings.sink, control.sinkComponent.location()) && //if the sink for the interaction is the same address as the existing control
deviceID === control.device.id() //if the device id for source component is the same as the device id in the control
);
if (component && interaction.settings.result) {
if (similarControlIndex === -1) {
controls.push({
conditions: interaction.settings.conditions,
result: interaction.settings.result,
sourceComponents: [component],
sinkComponent: sinkComponent,
device: controlDevice
});
} else {
controls[similarControlIndex].sourceComponents.push(component);
}
}
}
});
setControls(controls);
}).catch(err => {
console.error("Interaction fetch error:", err)
})
}
},[linkedComponents, interactionsAPI, componentDevices, as])
useEffect(() => {
load()
}, [load]);
return (
<React.Fragment>
<NewObjectInteraction
open={openNewInteraction}
onClose={(refresh) => {
setOpenNewInteraction(false)
if(refresh){
load()
}
}}
linkedComponents={linkedComponents}
componentDevices={componentDevices}
device={selectedDevice}/>
{loading ?
<LinearProgress />
:
<Controls
controls={controls}
devices={devices}
permissions={permissions}
addNew={(device) => {
console.log("new control")
setSelectedDevice(device)
setOpenNewInteraction(true)
}}
/>
}
</React.Fragment>
)
}

View file

@ -6,6 +6,11 @@ import { Bin, Component, Device } from "models";
import Alerts from "objects/objectInteractions/Alerts"; import Alerts from "objects/objectInteractions/Alerts";
import BinAlerts from "./binAlerts"; import BinAlerts from "./binAlerts";
import { pond } from "protobuf-ts/pond"; import { pond } from "protobuf-ts/pond";
import BinControls from "./binControls";
import BinAnalysisGraphs from "./binAnalysisGraphs";
import { GrainCable } from "models/GrainCable";
import { Plenum } from "models/Plenum";
import { Controller } from "models/Controller";
interface Props { interface Props {
bin: Bin bin: Bin
@ -14,6 +19,8 @@ interface Props {
componentDevices: Map<string, number>; componentDevices: Map<string, number>;
devices: Device[]; devices: Device[];
permissions: pond.Permission[] permissions: pond.Permission[]
cables: GrainCable[]
plenums: Plenum[]
} }
interface TabPanelProps { interface TabPanelProps {
@ -26,47 +33,57 @@ function TabPanelMine(props: TabPanelProps) {
const { children, value, index, ...other } = props; const { children, value, index, ...other } = props;
return ( return (
<div <Box
role="tabpanel" role="tabpanel"
hidden={value !== index} hidden={value !== index}
aria-labelledby={`simple-tab-${index}`} aria-labelledby={`simple-tab-${index}`}
sx={{
display: value === index ? "flex" : "none",
flexDirection: "column",
flex: 1,
minHeight: 0,
overflow: "hidden",
}}
{...other}> {...other}>
{value === index && <React.Fragment>{children}</React.Fragment>} {value === index && children}
</div> </Box>
); );
} }
export default function BinDetails (props: Props) { export default function BinDetails (props: Props) {
const {bin, updateBinCallback, linkedComponents, componentDevices, devices, permissions} = props const {bin, updateBinCallback, linkedComponents, componentDevices, devices, permissions, cables, plenums} = props
const [currentTab, setCurrentTab] = useState(0) const [currentTab, setCurrentTab] = useState(0)
//this is where we will have the tabs abd tab panels for the table view, alerts, interactions, and analysis //this is where we will have the tabs and tab panels for the table view, alerts, controls, and analysis
return ( return (
<Box> <Box sx={{ display: "flex", flexDirection: "column", height: "100%", overflow: "hidden" }}>
<Tabs <Tabs
value={currentTab} value={currentTab}
onChange={(_, value) => setCurrentTab(value)} onChange={(_, value) => setCurrentTab(value)}
indicatorColor="primary" indicatorColor="primary"
textColor="primary" textColor="primary"
variant="fullWidth"> variant="fullWidth"
sx={{ flexShrink: 0 }}>
<Tab label={"Table View"} value={0} /> <Tab label={"Table View"} value={0} />
<Tab label={"Alerts"} value={1} /> <Tab label={"Alerts"} value={1} />
<Tab label={"Controls"} value={2} /> <Tab label={"Controls"} value={2} />
<Tab label={"Analysis"} value={3} /> <Tab label={"Analysis"} value={3} />
</Tabs> </Tabs>
<Box sx={{ display: "flex", flexDirection: "column", flex: 1, minHeight: 0, overflow: "hidden" }}>
<TabPanelMine value={currentTab} index={0}> <TabPanelMine value={currentTab} index={0}>
<BinTableView bin={bin} updateBinCallback={updateBinCallback}/> <BinTableView bin={bin} updateBinCallback={updateBinCallback}/>
</TabPanelMine> </TabPanelMine>
<TabPanelMine value={currentTab} index={1}> <TabPanelMine value={currentTab} index={1}>
<BinAlerts bin={bin} componentDevices={componentDevices} devices={devices} linkedComponents={linkedComponents} permissions={permissions}/> <BinAlerts componentDevices={componentDevices} linkedComponents={linkedComponents} permissions={permissions}/>
</TabPanelMine> </TabPanelMine>
<TabPanelMine value={currentTab} index={2}> <TabPanelMine value={currentTab} index={2}>
<BinControls componentDevices={componentDevices} devices={devices} linkedComponents={linkedComponents} permissions={permissions}/>
</TabPanelMine> </TabPanelMine>
<TabPanelMine value={currentTab} index={3}> <TabPanelMine value={currentTab} index={3}>
<BinAnalysisGraphs bin={bin} cables={cables} plenums={plenums} componentDevices={componentDevices}/>
</TabPanelMine> </TabPanelMine>
</Box> </Box>
</Box>
) )
} }

View file

@ -0,0 +1,156 @@
import { Box, Grid2, Typography } from "@mui/material";
import { Bin, Component } from "models";
import { Ambient } from "models/Ambient";
import { CO2 } from "models/CO2";
import { Controller } from "models/Controller";
import { GrainCable } from "models/GrainCable";
import { Headspace } from "models/Headspace";
import { Plenum } from "models/Plenum";
import { Pressure } from "models/Pressure";
import { pond } from "protobuf-ts/pond";
import { quack } from "protobuf-ts/quack";
import React, { useEffect, useState } from "react";
interface Props {
bin: Bin
components: Map<string, Component>;
preferences?: Map<string, pond.BinComponentPreferences>;
setPreferences: React.Dispatch<
React.SetStateAction<Map<string, pond.BinComponentPreferences> | undefined>
>;
}
export default function BinSensors(props: Props){
const {bin, components, preferences, setPreferences} = props
const [cables, setCables] = useState<GrainCable[]>([])
const [plenums, setPlenums] = useState<Plenum[]>([])
const [ambient, setAmbient] = useState<Ambient[]>([])
const [pressures, setPressures] = useState<Pressure[]>([])
const [fans, setFans] = useState<Controller[]>([])
const [heaters, setHeaters] = useState<Controller[]>([])
//the above component preferences all have only components that are one type of sensor, however headspace has components of three different sensors T/H, CO2, and Lidar
const [headspaceTH, setHeadspaceTH] = useState<Headspace[]>([]) //the components in the headspace that measure temp/humidity
const [headspaceCO2, setHeadspaceCO2] = useState<CO2[]>([]) //the CO2 components in the headspace
const [headspaceLidar, setHeadspaceLidar] = useState<Component[]>([]) //the lidar components in the headspace
const [unassignedComponents, setUnassignedComponents] = useState<Component[]>([])
//using counts so i dont have to have to check multiple arrays for sensors and controllers
const [sensorCount, setSensorCount] = useState(0)
const [controllerCount, setControllerCount] = useState(0)
//organize the components into the correct 'positions' using the bins preferences
useEffect(()=>{
let unassigned: Component[] = []
let cables: GrainCable[] = []
let plenums: Plenum[] = []
let ambients: Ambient[] = []
let pressures: Pressure[] = []
let fans: Controller[] = []
let heaters: Controller[] = []
let headspaceTH: Headspace[] = []
let headspaceCO2: CO2[] = []
let headspaceLidar: Component[] = []
let sensorCount = 0
let controllerCount = 0
components.forEach(comp => {
if(preferences){
let pref = preferences.get(comp.key())
switch(pref?.type){
case pond.BinComponent.BIN_COMPONENT_GRAIN_CABLE:
cables.push(GrainCable.create(comp))
sensorCount++
break;
case pond.BinComponent.BIN_COMPONENT_PLENUM:
plenums.push(Plenum.create(comp))
sensorCount++
break;
case pond.BinComponent.BIN_COMPONENT_AMBIENT:
ambients.push(Ambient.create(comp))
sensorCount++
break;
case pond.BinComponent.BIN_COMPONENT_PRESSURE:
pressures.push(Pressure.create(comp))
sensorCount++
break;
case pond.BinComponent.BIN_COMPONENT_FAN:
fans.push(Controller.create(comp))
controllerCount++
break;
case pond.BinComponent.BIN_COMPONENT_HEATER:
heaters.push(Controller.create(comp))
controllerCount++
break;
case pond.BinComponent.BIN_COMPONENT_HEADSPACE:
if (comp.type() === quack.ComponentType.COMPONENT_TYPE_DHT) {
headspaceTH.push(Headspace.create(comp));
} else if (comp.type() === quack.ComponentType.COMPONENT_TYPE_LIDAR) {
headspaceLidar.push(comp);
} else if (comp.type() === quack.ComponentType.COMPONENT_TYPE_CO2) {
let coComp = CO2.create(comp)
headspaceCO2.push(coComp);
}
sensorCount++
break;
default:
unassigned.push(comp)
}
}else{
unassigned.push(comp)
}
})
// console.log(cables)
// console.log(unassigned)
setCables(cables)
setPlenums(plenums)
setPressures(pressures)
setAmbient(ambients)
setFans(fans)
setHeaters(heaters)
setHeadspaceTH(headspaceTH)
setHeadspaceCO2(headspaceCO2)
setHeadspaceLidar(headspaceLidar)
setUnassignedComponents(unassigned)
},[components, preferences])
const cableDisplay = (cable: GrainCable) => {
return (
<Box>
</Box>
)
}
return (
<Box>
{sensorCount > 0 &&
<React.Fragment>
<Typography>Sensors</Typography>
{cables.length > 0 &&
<React.Fragment>
<Typography>Cables</Typography>
<Grid2 container>
{cables.map(cable => {
return(
<Grid2 size={{xs: 6, xl: 4}}>
{cableDisplay(cable)}
</Grid2>
)
})}
</Grid2>
</React.Fragment>
}
{plenums.length }
</React.Fragment>
}
<Typography>Controllers</Typography>
{/* do all of the fans and heaters here */}
<Typography>Unassigned Components</Typography>
{/* list the components that have no assignment on the bin */}
</Box>
)
}

View file

@ -335,7 +335,7 @@ export default function BinTableView(props: Props) {
</TableHead> </TableHead>
<TableBody> <TableBody>
{binLevels.map((level, i) => ( {binLevels.map((level, i) => (
<TableRow> <TableRow key={i}>
<TableCell padding="none" className={classes.cellStyle}>{binLevels.length - i}</TableCell> <TableCell padding="none" className={classes.cellStyle}>{binLevels.length - i}</TableCell>
{levelDisplay(level)} {levelDisplay(level)}
</TableRow> </TableRow>

View file

@ -4,6 +4,7 @@ import { GrainCable } from "models/GrainCable";
import { Plenum } from "models/Plenum"; import { Plenum } from "models/Plenum";
import { UnitMeasurement } from "models/UnitMeasurement"; import { UnitMeasurement } from "models/UnitMeasurement";
import moment from "moment"; import moment from "moment";
import { pond } from "protobuf-ts/pond";
import { quack } from "protobuf-ts/quack"; import { quack } from "protobuf-ts/quack";
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import { avg } from "utils"; import { avg } from "utils";

View file

@ -213,15 +213,12 @@ export default function NewObjectInteraction(props: Props){
//display the components that match the type that was selected for the new alert //display the components that match the type that was selected for the new alert
const listMatchingComponents = () => { const listMatchingComponents = () => {
console.log("listing")
let matching: Component[] = []; let matching: Component[] = [];
console.log(validComponents)
validComponents.forEach(comp => { validComponents.forEach(comp => {
if (comp.type() === newAlertComponentType) { if (comp.type() === newAlertComponentType) {
matching.push(comp); matching.push(comp);
} }
}); });
console.log(matching)
return ( return (
<List> <List>
{matching.map(comp => ( {matching.map(comp => (

View file

@ -23,6 +23,11 @@ interface Props {
permissions: pond.Permission[] permissions: pond.Permission[]
} }
/**
* combines the alerts and the controls together to display them simultaneously, if you just want one or the other just use the specific component you want
* @param props
* @returns
*/
export default function ObjectInteractions(props: Props) { export default function ObjectInteractions(props: Props) {
const { linkedComponents, componentDevices, devices, objectKey, objectType, permissions } = props const { linkedComponents, componentDevices, devices, objectKey, objectType, permissions } = props
const [{as}] = useGlobalState() const [{as}] = useGlobalState()
@ -86,7 +91,7 @@ export default function ObjectInteractions(props: Props) {
} }
const load = useCallback(()=>{ const load = useCallback(()=>{
const newInteractions: Interaction[] = []; const newInteractions: Interaction[] = [];
const interactionSourceMap = new Map<string, string>(); const interactionSourceMap = new Map<string, string>();
const sinkOptions: Component[] = []; const sinkOptions: Component[] = [];
const alerts: Alert[] = []; const alerts: Alert[] = [];

View file

@ -14,7 +14,7 @@ import { Pressure } from "models/Pressure";
import { CO2 } from "models/CO2"; import { CO2 } from "models/CO2";
import moment from "moment"; import moment from "moment";
import { quack } from "protobuf-ts/quack"; import { quack } from "protobuf-ts/quack";
import { Box, Drawer, Grid2 as Grid, IconButton, Theme, Tooltip } from "@mui/material"; import { Box, Drawer, Grid2 as Grid, IconButton, ListItemIcon, ListItemText, Menu, MenuItem, Theme, Tooltip } from "@mui/material";
import { makeStyles } from "@mui/styles"; import { makeStyles } from "@mui/styles";
import NotesIcon from "@mui/icons-material/Notes"; import NotesIcon from "@mui/icons-material/Notes";
import TasksIcon from "products/Construction/TasksIcon"; import TasksIcon from "products/Construction/TasksIcon";
@ -43,6 +43,9 @@ const useStyles = makeStyles((theme: Theme) => {
border: "1px solid", border: "1px solid",
borderColor: theme.palette.divider borderColor: theme.palette.divider
}, },
menuPaper: {
borderRadius: "20px"
},
}) })
}) })
@ -298,6 +301,28 @@ export default function BinV2(){
* UI STUFF STARTS HERE * UI STUFF STARTS HERE
*/ */
const deviceMenu = () => {
return (
<Menu
id="groupMenu"
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={() => setAnchorEl(null)}
keepMounted
classes={{ paper: classes.menuPaper }}
disableAutoFocusItem>
{devices.map(dev => (
<MenuItem key={dev.id()} onClick={() => goToDevice(dev)}>
<ListItemIcon>
<BindaptIcon />
</ListItemIcon>
<ListItemText primary={dev.name()} />
</MenuItem>
))}
</Menu>
);
};
/** /**
* Header - consists of the actions and things that are always visible like * Header - consists of the actions and things that are always visible like
* opening the note/history and tasks drawers, navigating to the device and map pages, opening binsensors and settings etc. * opening the note/history and tasks drawers, navigating to the device and map pages, opening binsensors and settings etc.
@ -433,16 +458,20 @@ export default function BinV2(){
return ( return (
<PageContainer> <PageContainer>
{deviceMenu()}
{pageHeader()} {pageHeader()}
<BinSummary <BinSummary
bin={bin} bin={bin}
devices={devices} devices={devices}
fans={fans} fans={fans}
heaters={heaters} heaters={heaters}
cables={grainCables}
plenums={plenums}
permissions={permissions} permissions={permissions}
componentDevices={componentDevices} componentDevices={componentDevices}
componentMap={components} componentMap={components}
binPrefs={preferences} binPrefs={preferences}
setPreferences={setPreferences}
updateBinCallback={(bin) => { updateBinCallback={(bin) => {
setBin(bin) setBin(bin)
binAPI.updateBin(bin.key(), bin.settings).then(resp => { binAPI.updateBin(bin.key(), bin.settings).then(resp => {