add own entities read from ems-bus with free factor

This commit is contained in:
MichaelDvP
2023-03-31 16:50:49 +02:00
parent 36d5df65b8
commit fa50846a05
29 changed files with 1232 additions and 20 deletions

View File

@@ -67,6 +67,19 @@ const GeneralFileUpload: FC<UploadFileProps> = ({ uploadGeneralFile }) => {
}
};
const downloadEntities = async () => {
try {
const response = await EMSESP.getEntities();
if (response.status !== 200) {
toast.error(LL.PROBLEM_LOADING());
} else {
saveFile(response.data, 'entities');
}
} catch (error) {
toast.error(extractErrorMessage(error, LL.PROBLEM_LOADING()));
}
};
const downloadSchedule = async () => {
try {
const response = await EMSESP.getSchedule();
@@ -125,6 +138,14 @@ const GeneralFileUpload: FC<UploadFileProps> = ({ uploadGeneralFile }) => {
>
{LL.CUSTOMIZATIONS()}
</Button>
<Button sx={{ ml: 2 }}
startIcon={<DownloadIcon />}
variant="outlined"
color="primary"
onClick={() => downloadEntities()}
>
{LL.ENTITIES()}
</Button>
<Box color="warning.main">
<Typography mt={2} mb={1} variant="body2">
{LL.DOWNLOAD_SCHEDULE_TEXT()}{' '}

View File

@@ -318,7 +318,9 @@ const de: Translation = {
SCHEDULE_SAVED: 'Plan gespeichert',
SCHEDULE_TIMER_1: 'beim Start',
SCHEDULE_TIMER_2: 'jede Minute',
SCHEDULE_TIMER_3: 'jede Stunde'
SCHEDULE_TIMER_3: 'jede Stunde',
CUSTOM_ENTITIES: 'Individuelle Entitäten',
ENTITIES_HELP_1: 'Abfrage von Werten auf dem EMS-Bus'
};
export default de;

View File

@@ -318,7 +318,9 @@ const en: Translation = {
SCHEDULE_SAVED: 'Schedule updated',
SCHEDULE_TIMER_1: 'on startup',
SCHEDULE_TIMER_2: 'every minute',
SCHEDULE_TIMER_3: 'every hour'
SCHEDULE_TIMER_3: 'every hour',
CUSTOM_ENTITIES: 'Custom entities',
ENTITIES_HELP_1: 'Fetch custom entities from the EMS-bus'
};
export default en;

View File

@@ -318,7 +318,9 @@ const fr: Translation = {
SCHEDULE_SAVED: 'Schedule updated', // TODO translate
SCHEDULE_TIMER_1: 'on startup', // TODO translate
SCHEDULE_TIMER_2: 'every minute', // TODO translate
SCHEDULE_TIMER_3: 'every hour' // TODO translate
SCHEDULE_TIMER_3: 'every hour', // TODO translate
CUSTOM_ENTITIES: 'Custom entities',
ENTITIES_HELP_1: 'Fetch custom entities from the EMS-bus'
};
export default fr;

View File

@@ -318,7 +318,9 @@ const nl: Translation = {
SCHEDULE_SAVED: 'Schedule updated', // TODO translate
SCHEDULE_TIMER_1: 'on startup', // TODO translate
SCHEDULE_TIMER_2: 'every minute', // TODO translate
SCHEDULE_TIMER_3: 'every hour' // TODO translate
SCHEDULE_TIMER_3: 'every hour', // TODO translate
CUSTOM_ENTITIES: 'Custom entities',
ENTITIES_HELP_1: 'Fetch custom entities from the EMS-bus'
};
export default nl;

View File

@@ -318,7 +318,9 @@ const no: Translation = {
SCHEDULE_SAVED: 'Planlegger er oppdatert',
SCHEDULE_TIMER_1: 'ved oppstart',
SCHEDULE_TIMER_2: 'hvert minutt',
SCHEDULE_TIMER_3: 'hver time'
SCHEDULE_TIMER_3: 'hver time',
CUSTOM_ENTITIES: 'Custom entities',
ENTITIES_HELP_1: 'Fetch custom entities from the EMS-bus'
};
export default no;

View File

@@ -318,7 +318,9 @@ const pl: BaseTranslation = {
SCHEDULE_SAVED: 'Harmonogram został uaktualniony.',
SCHEDULE_TIMER_1: 'przy starcie',
SCHEDULE_TIMER_2: 'co minutę',
SCHEDULE_TIMER_3: 'co godzinę'
SCHEDULE_TIMER_3: 'co godzinę',
CUSTOM_ENTITIES: 'Custom entities',
ENTITIES_HELP_1: 'Fetch custom entities from the EMS-bus'
};
export default pl;

View File

@@ -318,7 +318,9 @@ const sv: Translation = {
SCHEDULE_SAVED: 'Schedule updated', // TODO translate
SCHEDULE_TIMER_1: 'on startup', // TODO translate
SCHEDULE_TIMER_2: 'every minute', // TODO translate
SCHEDULE_TIMER_3: 'every hour' // TODO translate
SCHEDULE_TIMER_3: 'every hour', // TODO translate
CUSTOM_ENTITIES: 'Custom entities',
ENTITIES_HELP_1: 'Fetch custom entities from the EMS-bus'
};
export default sv;

View File

@@ -318,7 +318,9 @@ const tr: Translation = {
SCHEDULE_SAVED: 'Schedule updated', // TODO translate
SCHEDULE_TIMER_1: 'on startup', // TODO translate
SCHEDULE_TIMER_2: 'every minute', // TODO translate
SCHEDULE_TIMER_3: 'every hour' // TODO translate
SCHEDULE_TIMER_3: 'every hour', // TODO translate
CUSTOM_ENTITIES: 'Custom entities',
ENTITIES_HELP_1: 'Fetch custom entities from the EMS-bus'
};
export default tr;

View File

@@ -2,7 +2,7 @@ import { FC } from 'react';
import { CgSmartHomeBoiler } from 'react-icons/cg';
import { FaSolarPanel } from 'react-icons/fa';
import { MdThermostatAuto, MdOutlineSensors } from 'react-icons/md';
import { MdThermostatAuto, MdOutlineSensors, MdOutlineExtension } from 'react-icons/md';
import { GiHeatHaze } from 'react-icons/gi';
import { TiFlowSwitch } from 'react-icons/ti';
import { VscVmConnect } from 'react-icons/vsc';
@@ -31,6 +31,7 @@ const enum DeviceType {
PUMP,
GENERIC,
HEATSOURCE,
CUSTOM,
UNKNOWN
}
@@ -61,6 +62,8 @@ const DeviceIcon: FC<DeviceIconProps> = ({ type_id }) => {
return <AiOutlineAlert />;
case DeviceType.PUMP:
return <AiOutlineChrome />;
case DeviceType.CUSTOM:
return <MdOutlineExtension />;
default:
return null;
}

View File

@@ -10,6 +10,7 @@ import { useI18nContext } from 'i18n/i18n-react';
import SettingsApplication from './SettingsApplication';
import SettingsCustomization from './SettingsCustomization';
import SettingsScheduler from './SettingsScheduler';
import SettingsEntities from './SettingsEntities';
const Settings: FC = () => {
const { LL } = useI18nContext();
@@ -23,11 +24,13 @@ const Settings: FC = () => {
<Tab value="application" label={LL.APPLICATION_SETTINGS()} />
<Tab value="customization" label={LL.CUSTOMIZATIONS()} />
<Tab value="scheduler" label={LL.SCHEDULER()} />
<Tab value="customentities" label={LL.CUSTOM_ENTITIES()} />
</RouterTabs>
<Routes>
<Route path="application" element={<SettingsApplication />} />
<Route path="customization" element={<SettingsCustomization />} />
<Route path="scheduler" element={<SettingsScheduler />} />
<Route path="customentities" element={<SettingsEntities />} />
<Route path="/*" element={<Navigate replace to="application" />} />
</Routes>
</>

View File

@@ -245,6 +245,7 @@ const SettingsCustomization: FC = () => {
if (devices) {
const selected_device = parseInt(event.target.value, 10);
setSelectedDevice(selected_device);
setNumChanges(0);
fetchDeviceEntities(devices?.devices[selected_device].i);
setRestartNeeded(false);
}

View File

@@ -0,0 +1,491 @@
import { FC, useState, useEffect, useCallback } from 'react';
import { unstable_useBlocker as useBlocker } from 'react-router-dom';
import {
Button,
Typography,
Box,
Grid,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
TextField,
MenuItem,
InputAdornment
} from '@mui/material';
import { useTheme } from '@table-library/react-table-library/theme';
import { Table, Header, HeaderRow, HeaderCell, Body, Row, Cell } from '@table-library/react-table-library/table';
import { toast } from 'react-toastify';
import RemoveIcon from '@mui/icons-material/RemoveCircleOutline';
import WarningIcon from '@mui/icons-material/Warning';
import CancelIcon from '@mui/icons-material/Cancel';
import DoneIcon from '@mui/icons-material/Done';
import AddIcon from '@mui/icons-material/Add';
import { ValidatedTextField, ButtonRow, FormLoader, SectionContent, BlockNavigation } from 'components';
import { DeviceValueUOM_s, EntityItem } from './types';
import { extractErrorMessage, updateValue } from 'utils';
import { validate } from 'validators';
import { entityItemValidation } from './validators';
import { useI18nContext } from 'i18n/i18n-react';
import { ValidateFieldsError } from 'async-validator';
import * as EMSESP from './api';
const SettingsEntities: FC = () => {
const { LL, locale } = useI18nContext();
const [numChanges, setNumChanges] = useState<number>(0);
const blocker = useBlocker(numChanges !== 0);
const emptyEntity = {
device_id: 8,
type_id: 2,
offset: 0,
factor: 1,
uom: 0,
val_type: 2,
name: 'name',
deleted: false
};
const [entity, setEntity] = useState<EntityItem[]>([emptyEntity]);
const [entityItem, setEntityItem] = useState<EntityItem>();
const [errorMessage, setErrorMessage] = useState<string>();
const [creating, setCreating] = useState<boolean>(false);
const [fieldErrors, setFieldErrors] = useState<ValidateFieldsError>();
useEffect(() => {
setNumChanges(getNumChanges());
});
const entity_theme = useTheme({
Table: `
--data-table-library_grid-template-columns: repeat(1, minmax(60px, 1fr)) 80px 80px 80px 80px;
`,
BaseRow: `
font-size: 14px;
.td {
height: 32px;
}
`,
BaseCell: `
&:nth-of-type(2) {
text-align: center;
}
&:nth-of-type(3) {
text-align: center;
}
&:nth-of-type(4) {
text-align: center;
}
&:nth-of-type(5) {
text-align: right;
}
`,
HeaderRow: `
text-transform: uppercase;
background-color: black;
color: #90CAF9;
.th {
border-bottom: 1px solid #565656;
height: 36px;
}
`,
Row: `
background-color: #1e1e1e;
position: relative;
cursor: pointer;
.td {
border-top: 1px solid #565656;
border-bottom: 1px solid #565656;
}
&:hover .td {
border-top: 1px solid #177ac9;
border-bottom: 1px solid #177ac9;
}
&:nth-of-type(odd) .td {
background-color: #303030;
}
`
});
const fetchEntities = useCallback(async () => {
try {
const response = await EMSESP.readEntities();
setOriginalEntity(response.data.entity);
} catch (error) {
setErrorMessage(extractErrorMessage(error, LL.PROBLEM_LOADING()));
}
}, [LL]);
useEffect(() => {
fetchEntities();
}, [fetchEntities]);
const setOriginalEntity = (data: EntityItem[]) => {
setEntity(
data.map((ei) => ({
...ei,
o_device_id: ei.device_id,
o_type_id: ei.type_id,
o_offset: ei.offset,
o_factor: ei.factor,
o_uom: ei.uom,
o_val_type: ei.val_type,
o_name: ei.name,
o_deleted: ei.deleted
}))
);
};
function hasEntityChanged(ei: EntityItem) {
return (
ei.device_id !== ei.o_device_id ||
ei.type_id !== ei.o_type_id ||
ei.name !== ei.o_name ||
ei.offset !== ei.o_offset ||
ei.uom !== ei.o_uom ||
ei.factor !== ei.o_factor ||
ei.val_type !== ei.o_val_type ||
ei.deleted !== ei.o_deleted
);
}
const getNumChanges = () => {
if (!entity) {
return 0;
}
return entity.filter((ei) => hasEntityChanged(ei)).length;
};
const saveEntity = async () => {
if (entity) {
try {
const response = await EMSESP.writeEntities({
entity: entity
.filter((ei) => !ei.deleted)
.map((condensed_ei) => {
return {
device_id: condensed_ei.device_id,
type_id: condensed_ei.type_id,
offset: condensed_ei.offset,
factor: condensed_ei.factor,
val_type: condensed_ei.val_type,
uom: condensed_ei.uom,
name: condensed_ei.name
};
})
});
if (response.status === 200) {
toast.success(LL.SUCCESS());
} else {
toast.error(LL.PROBLEM_UPDATING());
}
} catch (error) {
toast.error(extractErrorMessage(error, LL.PROBLEM_UPDATING()));
}
setOriginalEntity(entity);
}
};
const editEntityItem = (ei: EntityItem) => {
setCreating(false);
setEntityItem(ei);
};
const addEntityItem = () => {
setCreating(true);
setEntityItem({
device_id: 8,
type_id: 2,
offset: 0,
factor: 1,
val_type: 2,
uom: 0,
name: 'name',
deleted: false
});
};
const updateEntityItem = () => {
if (entityItem) {
setEntity([...entity.filter((ei) => creating || ei.o_name !== entityItem.o_name), entityItem]);
}
setEntityItem(undefined);
};
function formatValue(value: any, uom: number) {
if (value === undefined) {
return '';
}
if (uom === 0) {
return new Intl.NumberFormat().format(value);
}
return new Intl.NumberFormat().format(value) + ' ' + DeviceValueUOM_s[uom];
}
function showHex(value: string, digit: number) {
if (digit === 4) {
return '0x' + ('000' + value).slice(-4);
}
return '0x' + ('0' + value).slice(-2);
}
const renderEntity = () => {
if (!entity) {
return <FormLoader errorMessage={errorMessage} />;
}
return (
<Table
data={{ nodes: entity.filter((ei) => !ei.deleted).sort((a, b) => a.name.localeCompare(b.time)) }}
theme={entity_theme}
layout={{ custom: true }}
>
{(tableList: any) => (
<>
<Header>
<HeaderRow>
<HeaderCell>{LL.NAME(0)}</HeaderCell>
<HeaderCell stiff>Device ID</HeaderCell>
<HeaderCell stiff>Type ID</HeaderCell>
<HeaderCell stiff>Offset</HeaderCell>
<HeaderCell stiff>{LL.VALUE()}</HeaderCell>
</HeaderRow>
</Header>
<Body>
{tableList.map((ei: EntityItem) => (
<Row key={ei.name} item={ei} onClick={() => editEntityItem(ei)}>
<Cell>{ei.name}</Cell>
<Cell>{showHex(ei.device_id, 2)}</Cell>
<Cell>{showHex(ei.type_id, 4)}</Cell>
<Cell>{ei.offset}</Cell>
<Cell>{formatValue(ei.value, ei.uom)}</Cell>
</Row>
))}
</Body>
</>
)}
</Table>
);
};
const removeEntityItem = (ei: EntityItem) => {
ei.deleted = true;
setEntityItem(ei);
updateEntityItem();
};
const validateEntityItem = async () => {
if (entityItem) {
try {
setFieldErrors(undefined);
await validate(entityItemValidation(entity, entityItem), entityItem);
updateEntityItem();
} catch (errors: any) {
setFieldErrors(errors);
}
}
};
const closeDialog = () => {
setEntityItem(undefined);
setFieldErrors(undefined);
};
const renderEditEntity = () => {
if (entityItem) {
return (
<Dialog open={!!entityItem} onClose={() => closeDialog()}>
<DialogTitle>
{creating ? LL.ADD(1) + ' ' + LL.NEW() : LL.EDIT()}&nbsp;{LL.CUSTOM_ENTITIES()}
</DialogTitle>
<DialogContent dividers>
<Box display="flex" flexWrap="wrap" mb={1}>
<Box flexGrow={1}></Box>
<Box flexWrap="nowrap" whiteSpace="nowrap"></Box>
</Box>
<Grid container spacing={2}>
<Grid item xs={12}>
<ValidatedTextField
fieldErrors={fieldErrors}
name="name"
label={LL.NAME(0)}
value={entityItem.name}
margin="normal"
fullWidth
onChange={updateValue(setEntityItem)}
/>
</Grid>
<Grid item xs={4}>
<ValidatedTextField
name="device_id"
label="Device ID"
margin="normal"
fullWidth
value={entityItem.device_id}
onChange={updateValue(setEntityItem)}
InputProps={{
startAdornment: <InputAdornment position="start">0x</InputAdornment>
}}
/>
</Grid>
<Grid item xs={4}>
<ValidatedTextField
name="type_id"
label="Type ID"
margin="normal"
fullWidth
value={entityItem.type_id}
onChange={updateValue(setEntityItem)}
InputProps={{
startAdornment: <InputAdornment position="start">0x</InputAdornment>
}}
/>
</Grid>
<Grid item xs={4}>
<ValidatedTextField
name="offset"
label="Offset"
margin="normal"
fullWidth
type="number"
value={entityItem.offset}
onChange={updateValue(setEntityItem)}
/>
</Grid>
<Grid item xs={4}>
<ValidatedTextField
name="val_type"
label="Value Type"
value={entityItem.val_type}
variant="outlined"
onChange={updateValue(setEntityItem)}
margin="normal"
fullWidth
select
>
<MenuItem value={0}>BOOL</MenuItem>
<MenuItem value={1}>INT</MenuItem>
<MenuItem value={2}>UINT</MenuItem>
<MenuItem value={3}>SHORT</MenuItem>
<MenuItem value={4}>USHORT</MenuItem>
<MenuItem value={5}>ULONG</MenuItem>
<MenuItem value={6}>TIME</MenuItem>
</ValidatedTextField>
</Grid>
{entityItem.val_type !== 0 && (
<>
<Grid item xs={4}>
<ValidatedTextField
name="factor"
label={LL.FACTOR()}
value={entityItem.factor}
variant="outlined"
onChange={updateValue(setEntityItem)}
fullWidth
margin="normal"
type="number"
inputProps={{ step: '0.001' }}
/>
</Grid>
<Grid item xs={4}>
<ValidatedTextField
name="uom"
label={LL.UNIT()}
value={entityItem.uom}
margin="normal"
fullWidth
onChange={updateValue(setEntityItem)}
select
>
{DeviceValueUOM_s.map((val, i) => (
<MenuItem key={i} value={i}>
{val}
</MenuItem>
))}
</ValidatedTextField>
</Grid>
</>
)}
</Grid>
</DialogContent>
<DialogActions>
{!creating && (
<Box flexGrow={1}>
<Button
startIcon={<RemoveIcon />}
variant="outlined"
color="error"
onClick={() => removeEntityItem(entityItem)}
>
{LL.REMOVE()}
</Button>
</Box>
)}
<Button startIcon={<CancelIcon />} variant="outlined" onClick={() => closeDialog()} color="secondary">
{LL.CANCEL()}
</Button>
<Button
startIcon={creating ? <AddIcon /> : <DoneIcon />}
variant="outlined"
type="submit"
onClick={() => validateEntityItem()}
color="primary"
>
{creating ? LL.ADD(0) : LL.UPDATE()}
</Button>
</DialogActions>
</Dialog>
);
}
};
return (
<SectionContent title={LL.CUSTOM_ENTITIES()} titleGutter>
{blocker ? <BlockNavigation blocker={blocker} /> : null}
<Box mb={2} color="warning.main">
<Typography variant="body2">{LL.ENTITIES_HELP_1()}</Typography>
</Box>
{renderEntity()}
{renderEditEntity()}
<Box display="flex" flexWrap="wrap">
<Box flexGrow={1}>
{numChanges !== 0 && (
<ButtonRow>
<Button startIcon={<CancelIcon />} variant="outlined" onClick={() => fetchEntities()} color="secondary">
{LL.CANCEL()}
</Button>
<Button
startIcon={<WarningIcon color="warning" />}
variant="contained"
color="info"
onClick={() => saveEntity()}
>
{LL.APPLY_CHANGES(numChanges)}
</Button>
</ButtonRow>
)}
</Box>
<Box flexWrap="nowrap" whiteSpace="nowrap">
<ButtonRow>
<Button startIcon={<AddIcon />} variant="outlined" color="secondary" onClick={() => addEntityItem()}>
{LL.ADD(0)}
</Button>
</ButtonRow>
</Box>
</Box>
</SectionContent>
);
};
export default SettingsEntities;

View File

@@ -17,7 +17,8 @@ import {
WriteSensor,
WriteAnalog,
SensorData,
Schedule
Schedule,
Entities
} from './types';
export function restart(): AxiosPromise<void> {
@@ -96,6 +97,18 @@ export function getCustomizations(): AxiosPromise<void> {
return AXIOS.get('/getCustomizations');
}
export function getEntities(): AxiosPromise<void> {
return AXIOS.get('/getEntities');
}
export function readEntities(): AxiosPromise<void> {
return AXIOS.get('/entity');
}
export function writeEntities(entities: Entities): AxiosPromise<void> {
return AXIOS.post('/entity', entities);
}
export function getSchedule(): AxiosPromise<Schedule> {
return AXIOS.get('/getSchedule');
}

View File

@@ -337,3 +337,27 @@ export enum ScheduleFlag {
SCHEDULE_SAT = 64,
SCHEDULE_TIMER = 128
}
export interface EntityItem {
name: string;
device_id: string;
type_id: string;
offset: number;
factor: number;
uom: number;
val_type: number;
value?: number;
o_name?: string;
o_device_id?: string;
o_type_id?: string;
o_offset?: number;
o_factor?: number;
o_uom?: number;
o_val_type?: number;
deleted?: boolean; // optional
o_deleted?: boolean;
}
export interface Entities {
entity: EntityItem[];
}

View File

@@ -1,6 +1,6 @@
import Schema, { InternalRuleItem } from 'async-validator';
import { IP_OR_HOSTNAME_VALIDATOR } from 'validators/shared';
import { Settings, ScheduleItem } from './types';
import { Settings, ScheduleItem, EntityItem } from './types';
export const GPIO_VALIDATOR = {
validator(rule: InternalRuleItem, value: number, callback: (error?: string) => void) {
@@ -101,12 +101,47 @@ export const schedulerItemValidation = (schedule: ScheduleItem[], scheduleItem:
]
});
export const uniqueNameValidator = (schedule: ScheduleItem[], o_name?: string) => ({
validator(rule: InternalRuleItem, name: string, callback: (error?: string) => void) {
if (name && o_name && o_name !== name && schedule.find((si) => si.name === name)) {
callback('Name already in use');
} else {
callback();
export const uniqueNameValidator = (schedule: ScheduleItem[], o_name?: string) => ({
validator(rule: InternalRuleItem, name: string, callback: (error?: string) => void) {
if (name && o_name && o_name !== name && schedule.find((si) => si.name === name)) {
callback('Name already in use');
} else {
callback();
}
}
}
});
});
export const entityItemValidation = (entity: EntityItem[], entityItem: EntityItem) =>
new Schema({
name: [
{ required: true, message: 'Name is required' },
{
type: 'string',
pattern: /^[a-zA-Z0-9_\\.]{1,15}$/,
message: "Must be <15 characters: alpha numeric, '_' or '.'"
},
...[uniqueEntityNameValidator(entity, entityItem.o_name)]
],
device_id: [
{ required: true, message: 'Device_id is required' },
{ type: 'string', pattern: /^[A-F0-9]{1,2}$/, message: 'Must be a hex number' }
],
type_id: [
{ required: true, message: 'Type_id is required' },
{ type: 'string', pattern: /^[A-F0-9]{1,4}$/, message: 'Must be a hex number' }
],
offset: [
{ required: true, message: 'Offset is required' },
{ type: 'number', min: 0, max: 255, message: 'Must be between 0 and 255' }
]
});
export const uniqueEntityNameValidator = (entity: EntityItem[], o_name?: string) => ({
validator(rule: InternalRuleItem, name: string, callback: (error?: string) => void) {
if (name && o_name && o_name !== name && entity.find((ei) => ei.name === name)) {
callback('Name already in use');
} else {
callback();
}
}
});