Merge pull request #475 from proddy/dev

Changes to Table (sorting, format, search)
This commit is contained in:
Proddy
2022-04-24 19:20:16 -04:00
committed by GitHub
27 changed files with 2583 additions and 1971 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -7,27 +7,28 @@
"@emotion/react": "^11.9.0",
"@emotion/styled": "^11.8.1",
"@msgpack/msgpack": "^2.7.2",
"@mui/icons-material": "^5.6.0",
"@mui/material": "^5.6.0",
"@types/lodash": "^4.14.181",
"@types/node": "^17.0.23",
"@mui/icons-material": "^5.6.2",
"@mui/material": "^5.6.2",
"@table-library/react-table-library": "^3.1.0",
"@types/lodash": "^4.14.182",
"@types/node": "^17.0.26",
"@types/react": "^17.0.43",
"@types/react-dom": "^17.0.14",
"@types/react-router-dom": "^5.3.3",
"async-validator": "^4.0.7",
"async-validator": "^4.0.8",
"axios": "^0.26.1",
"http-proxy-middleware": "^2.0.4",
"http-proxy-middleware": "^2.0.6",
"jwt-decode": "^3.1.2",
"lodash": "^4.17.21",
"notistack": "^2.0.3",
"notistack": "^2.0.4",
"parse-ms": "^3.0.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-app-rewired": "^2.2.1",
"react-dropzone": "^12.0.4",
"react-dom": "^17.0.2",
"react-dropzone": "^12.0.5",
"react-icons": "^4.3.1",
"react-router-dom": "^6.3.0",
"react-scripts": "5.0.0",
"react-scripts": "5.0.1",
"sockette": "^2.0.6",
"typescript": "^4.6.3"
},

View File

@@ -14,6 +14,7 @@ import {
ValidatedPasswordField,
ValidatedTextField
} from '../../components';
import { APProvisionMode, APSettings } from '../../types';
import { numberValue, updateValue, useRest } from '../../utils';
import * as APApi from '../../api/ap';

View File

@@ -1,6 +1,6 @@
import { FC, useContext, useState } from 'react';
import { Button, IconButton, Table, TableBody, TableCell, TableFooter, TableHead, TableRow } from '@mui/material';
import { Button, IconButton, Box } from '@mui/material';
import SaveIcon from '@mui/icons-material/Save';
import DeleteIcon from '@mui/icons-material/Delete';
import PersonAddIcon from '@mui/icons-material/PersonAdd';
@@ -9,6 +9,10 @@ import CheckIcon from '@mui/icons-material/Check';
import CloseIcon from '@mui/icons-material/Close';
import VpnKeyIcon from '@mui/icons-material/VpnKey';
import { Table } from '@table-library/react-table-library/table';
import { useTheme } from '@table-library/react-table-library/theme';
import { Header, HeaderRow, HeaderCell, Body, Row, Cell } from '@table-library/react-table-library/table';
import * as SecurityApi from '../../api/security';
import { SecuritySettings, User } from '../../types';
import { ButtonRow, FormLoader, MessageBox, SectionContent } from '../../components';
@@ -19,16 +23,6 @@ import { AuthenticatedContext } from '../../contexts/authentication';
import GenerateToken from './GenerateToken';
import UserForm from './UserForm';
function compareUsers(a: User, b: User) {
if (a.username < b.username) {
return -1;
}
if (a.username > b.username) {
return 1;
}
return 0;
}
const ManageUsersForm: FC = () => {
const { loadData, saving, data, setData, saveData, errorMessage } = useRest<SecuritySettings>({
read: SecurityApi.readSecuritySettings,
@@ -40,6 +34,45 @@ const ManageUsersForm: FC = () => {
const [generatingToken, setGeneratingToken] = useState<string>();
const authenticatedContext = useContext(AuthenticatedContext);
const table_theme = useTheme({
BaseRow: `
font-size: 14px;
color: white;
`,
HeaderRow: `
text-transform: uppercase;
background-color: black;
color: #90CAF9;
border-bottom: 1px solid #e0e0e0;
`,
Row: `
&:nth-of-type(odd) {
background-color: #303030;
}
&:nth-of-type(even) {
background-color: #1e1e1e;
}
border-top: 1px solid #565656;
border-bottom: 1px solid #565656;
position: relative;
z-index: 1;
&:not(:last-of-type) {
margin-bottom: -1px;
}
&:not(:first-of-type) {
margin-top: -1px;
}
&:hover {
color: white;
}
`,
BaseCell: `
border-top: 1px solid transparent;
border-right: 1px solid transparent;
border-bottom: 1px solid transparent;
`
});
const content = () => {
if (!data) {
return <FormLoader onRetry={loadData} errorMessage={errorMessage} />;
@@ -48,13 +81,14 @@ const ManageUsersForm: FC = () => {
const noAdminConfigured = () => !data.users.find((u) => u.admin);
const removeUser = (toRemove: User) => {
const users = data.users.filter((u) => u.username !== toRemove.username);
const users = data.users.filter((u) => u.id !== toRemove.id);
setData({ ...data, users });
};
const createUser = () => {
setCreating(true);
setUser({
id: '',
username: '',
password: '',
admin: true
@@ -72,7 +106,7 @@ const ManageUsersForm: FC = () => {
const doneEditingUser = () => {
if (user) {
const users = [...data.users.filter((u) => u.username !== user.username), user];
const users = [...data.users.filter((u) => u.id !== user.id), user];
setData({ ...data, users });
setUser(undefined);
}
@@ -82,8 +116,8 @@ const ManageUsersForm: FC = () => {
setGeneratingToken(undefined);
};
const generateToken = (username: string) => {
setGeneratingToken(username);
const generateToken = (id: string) => {
setGeneratingToken(id);
};
const onSubmit = async () => {
@@ -93,66 +127,71 @@ const ManageUsersForm: FC = () => {
return (
<>
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Username</TableCell>
<TableCell align="center">is Admin?</TableCell>
<TableCell />
</TableRow>
</TableHead>
<TableBody>
{data.users.sort(compareUsers).map((u) => (
<TableRow key={u.username}>
<TableCell component="th" scope="row">
{u.username}
</TableCell>
<TableCell align="center">{u.admin ? <CheckIcon /> : <CloseIcon />}</TableCell>
<TableCell align="center">
<IconButton
size="small"
disabled={!authenticatedContext.me.admin}
aria-label="Generate Token"
onClick={() => generateToken(u.username)}
>
<VpnKeyIcon />
</IconButton>
<IconButton size="small" aria-label="Delete" onClick={() => removeUser(u)}>
<DeleteIcon />
</IconButton>
<IconButton size="small" aria-label="Edit" onClick={() => editUser(u)}>
<EditIcon />
</IconButton>
</TableCell>
</TableRow>
))}
</TableBody>
<TableFooter>
<TableRow>
<TableCell colSpan={2} />
<TableCell align="center">
<Button startIcon={<PersonAddIcon />} variant="outlined" color="secondary" onClick={createUser}>
Add
</Button>
</TableCell>
</TableRow>
</TableFooter>
<Table data={{ nodes: data.users }} theme={table_theme}>
{(tableList: any) => (
<>
<Header>
<HeaderRow>
<HeaderCell>USERNAME</HeaderCell>
<HeaderCell>IS ADMIN</HeaderCell>
<HeaderCell />
</HeaderRow>
</Header>
<Body>
{tableList.map((u: User, index: number) => (
<Row key={u.id} item={u}>
<Cell>{u.id}</Cell>
<Cell>{u.admin ? <CheckIcon /> : <CloseIcon />}</Cell>
<Cell>
<IconButton
size="small"
disabled={!authenticatedContext.me.admin}
aria-label="Generate Token"
onClick={() => generateToken(u.id)}
>
<VpnKeyIcon />
</IconButton>
<IconButton size="small" aria-label="Delete" onClick={() => removeUser(u)}>
<DeleteIcon />
</IconButton>
<IconButton size="small" aria-label="Edit" onClick={() => editUser(u)}>
<EditIcon />
</IconButton>
</Cell>
</Row>
))}
</Body>
</>
)}
</Table>
{noAdminConfigured() && (
<MessageBox level="warning" message="You must have at least one admin user configured" my={2} />
)}
<ButtonRow>
<Button
startIcon={<SaveIcon />}
disabled={saving || noAdminConfigured()}
variant="outlined"
color="primary"
type="submit"
onClick={onSubmit}
>
Save
</Button>
</ButtonRow>
<Box display="flex" flexWrap="wrap">
<Box flexGrow={1} sx={{ '& button': { mt: 2 } }}>
<Button
startIcon={<SaveIcon />}
disabled={saving || noAdminConfigured()}
variant="outlined"
color="primary"
type="submit"
onClick={onSubmit}
>
Save
</Button>
</Box>
<Box flexWrap="nowrap" whiteSpace="nowrap">
<ButtonRow>
<Button startIcon={<PersonAddIcon />} variant="outlined" color="secondary" onClick={createUser}>
Add
</Button>
</ButtonRow>
</Box>
</Box>
<GenerateToken username={generatingToken} onClose={closeGenerateToken} />
<UserForm
user={user}

File diff suppressed because it is too large Load Diff

View File

@@ -3,25 +3,23 @@ import { useSnackbar } from 'notistack';
import {
Avatar,
Button,
Table,
TableContainer,
TableBody,
TableCell,
TableHead,
TableRow,
List,
ListItem,
ListItemAvatar,
ListItemText,
Theme,
useTheme,
Box,
Dialog,
DialogActions,
DialogContent,
DialogTitle
DialogTitle,
Theme,
useTheme
} from '@mui/material';
import { Table } from '@table-library/react-table-library/table';
import { useTheme as tableTheme } from '@table-library/react-table-library/theme';
import { Header, HeaderRow, HeaderCell, Body, Row, Cell } from '@table-library/react-table-library/table';
import DeviceHubIcon from '@mui/icons-material/DeviceHub';
import RefreshIcon from '@mui/icons-material/Refresh';
import PermScanWifiIcon from '@mui/icons-material/PermScanWifi';
@@ -32,14 +30,12 @@ import { AuthenticatedContext } from '../contexts/authentication';
import { ButtonRow, FormLoader, SectionContent } from '../components';
import { Status, busConnectionStatus } from './types';
import { Status, busConnectionStatus, Stat } from './types';
import { formatDurationSec, pluralize } from '../utils';
import { formatDurationSec, pluralize, extractErrorMessage, useRest } from '../utils';
import * as EMSESP from './api';
import { extractErrorMessage, useRest } from '../utils';
export const isConnected = ({ status }: Status) => status !== busConnectionStatus.BUS_STATUS_OFFLINE;
const busStatusHighlight = ({ status }: Status, theme: Theme) => {
@@ -60,7 +56,7 @@ const busStatus = ({ status }: Status) => {
case busConnectionStatus.BUS_STATUS_CONNECTED:
return 'Connected';
case busConnectionStatus.BUS_STATUS_TX_ERRORS:
return 'Tx issues - try a different Tx-Mode';
return 'Tx issues - try a different Tx Mode';
case busConnectionStatus.BUS_STATUS_OFFLINE:
return 'Disconnected';
default:
@@ -68,41 +64,17 @@ const busStatus = ({ status }: Status) => {
}
};
const formatRow = (name: string, success: number, fail: number, quality: number) => {
if (success === 0 && fail === 0) {
return (
<TableRow>
<TableCell sx={{ color: 'gray' }}>{name}</TableCell>
<TableCell />
<TableCell />
<TableCell />
</TableRow>
);
const showQuality = (stat: Stat) => {
if (stat.q === 0 || stat.s + stat.f === 0) {
return;
}
return (
<TableRow>
<TableCell>{name}</TableCell>
<TableCell>{Intl.NumberFormat().format(success)}</TableCell>
<TableCell>{Intl.NumberFormat().format(fail)}</TableCell>
{showQuality(quality)}
</TableRow>
);
};
const showQuality = (quality: number) => {
if (quality === 0) {
return <TableCell />;
if (stat.q === 100) {
return <div style={{ color: '#00FF7F' }}>{stat.q}%</div>;
}
if (quality === 100) {
return <TableCell sx={{ color: '#00FF7F' }}>{quality}%</TableCell>;
}
if (quality >= 95) {
return <TableCell sx={{ color: 'orange' }}>{quality}%</TableCell>;
if (stat.q >= 95) {
return <div style={{ color: 'orange' }}>{stat.q}%</div>;
} else {
return <TableCell sx={{ color: 'red' }}>{quality}%</TableCell>;
return <div style={{ color: 'red' }}>{stat.q}%</div>;
}
};
@@ -115,6 +87,48 @@ const DashboardStatus: FC = () => {
const { me } = useContext(AuthenticatedContext);
const stats_theme = tableTheme({
BaseRow: `
font-size: 14px;
color: white;
`,
HeaderRow: `
text-transform: uppercase;
background-color: black;
color: #90CAF9;
border-bottom: 1px solid #e0e0e0;
`,
Row: `
&:nth-of-type(odd) {
background-color: #303030;
}
&:nth-of-type(even) {
background-color: #1e1e1e;
}
border-top: 1px solid #565656;
border-bottom: 1px solid #565656;
position: relative;
z-index: 1;
&:not(:last-of-type) {
margin-bottom: -1px;
}
&:not(:first-of-type) {
margin-top: -1px;
}
&:hover {
color: white;
}
`,
BaseCell: `
border-top: 1px solid transparent;
border-right: 1px solid transparent;
border-bottom: 1px solid transparent;
&:nth-of-type(1) {
flex: 1;
}
`
});
useEffect(() => {
const timer = setInterval(() => loadData(), 30000);
return () => {
@@ -183,27 +197,30 @@ const DashboardStatus: FC = () => {
/>
</ListItem>
<Box m={3}></Box>
<TableContainer>
<Table size="small">
<TableHead>
<TableRow>
<TableCell></TableCell>
<TableCell>SUCCESS</TableCell>
<TableCell>FAIL</TableCell>
<TableCell>QUALITY</TableCell>
</TableRow>
</TableHead>
<TableBody>
{formatRow('EMS Telegrams Received (Rx)', data.rx_received, data.rx_fails, data.rx_quality)}
{formatRow('EMS Reads (Tx)', data.tx_reads, data.tx_read_fails, data.tx_read_quality)}
{formatRow('EMS Writes (Tx)', data.tx_writes, data.tx_write_fails, data.tx_write_quality)}
{formatRow('Temperature Sensor Reads', data.sensor_reads, data.sensor_fails, data.sensor_quality)}
{formatRow('Analog Sensor Reads', data.analog_reads, data.analog_fails, data.analog_quality)}
{formatRow('MQTT Publishes', data.mqtt_count, data.mqtt_fails, data.mqtt_quality)}
{formatRow('API Calls', data.api_calls, data.api_fails, data.api_quality)}
</TableBody>
</Table>
</TableContainer>
<Table data={{ nodes: data.stats }} theme={stats_theme} layout={{ custom: true }}>
{(tableList: any) => (
<>
<Header>
<HeaderRow>
<HeaderCell></HeaderCell>
<HeaderCell>SUCCESS</HeaderCell>
<HeaderCell>FAIL</HeaderCell>
<HeaderCell>QUALITY</HeaderCell>
</HeaderRow>
</Header>
<Body>
{tableList.map((stat: Stat) => (
<Row key={stat.id} item={stat}>
<Cell>{stat.id}</Cell>
<Cell>{Intl.NumberFormat().format(stat.s)}</Cell>
<Cell>{Intl.NumberFormat().format(stat.f)}</Cell>
<Cell>{showQuality(stat)}</Cell>
</Row>
))}
</Body>
</>
)}
</Table>
</List>
{renderScanDialog()}
<Box display="flex" flexWrap="wrap">

View File

@@ -2,10 +2,6 @@ import { FC, useState, useEffect, useCallback } from 'react';
import {
Button,
Table,
TableBody,
TableHead,
TableRow,
Typography,
Box,
MenuItem,
@@ -14,22 +10,31 @@ import {
DialogContent,
DialogTitle,
ToggleButton,
ToggleButtonGroup
ToggleButtonGroup,
Tooltip,
Grid,
TextField
} from '@mui/material';
import TableCell, { tableCellClasses } from '@mui/material/TableCell';
import { styled } from '@mui/material/styles';
import { Table } from '@table-library/react-table-library/table';
import { useTheme } from '@table-library/react-table-library/theme';
import { useSort, SortToggleType } from '@table-library/react-table-library/sort';
import { Header, HeaderRow, HeaderCell, Body, Row, Cell } from '@table-library/react-table-library/table';
import { useSnackbar } from 'notistack';
import SaveIcon from '@mui/icons-material/Save';
import CancelIcon from '@mui/icons-material/Cancel';
import EditOffOutlinedIcon from '@mui/icons-material/EditOffOutlined';
import FavoriteBorderOutlinedIcon from '@mui/icons-material/FavoriteBorderOutlined';
import StarIcon from '@mui/icons-material/Star';
import VisibilityOffOutlinedIcon from '@mui/icons-material/VisibilityOffOutlined';
import CommentsDisabledOutlinedIcon from '@mui/icons-material/CommentsDisabledOutlined';
import SettingsBackupRestoreIcon from '@mui/icons-material/SettingsBackupRestore';
import KeyboardArrowUpOutlinedIcon from '@mui/icons-material/KeyboardArrowUpOutlined';
import KeyboardArrowDownOutlinedIcon from '@mui/icons-material/KeyboardArrowDownOutlined';
import UnfoldMoreOutlinedIcon from '@mui/icons-material/UnfoldMoreOutlined';
import SearchIcon from '@mui/icons-material/Search';
import FilterListIcon from '@mui/icons-material/FilterList';
import { ButtonRow, FormLoader, ValidatedTextField, SectionContent } from '../components';
@@ -37,26 +42,116 @@ import * as EMSESP from './api';
import { extractErrorMessage } from '../utils';
import { DeviceShort, Devices, DeviceEntity } from './types';
const StyledTableCell = styled(TableCell)(({ theme }) => ({
[`&.${tableCellClasses.head}`]: {
backgroundColor: '#607d8b'
}
}));
import { DeviceShort, Devices, DeviceEntity, DeviceEntityMask } from './types';
const SettingsCustomization: FC = () => {
const { enqueueSnackbar } = useSnackbar();
const [deviceEntities, setDeviceEntities] = useState<DeviceEntity[]>();
const [deviceEntities, setDeviceEntities] = useState<DeviceEntity[]>([{ id: '', v: 0, s: '', m: 0, w: false }]);
const [devices, setDevices] = useState<Devices>();
const [errorMessage, setErrorMessage] = useState<string>();
const [selectedDevice, setSelectedDevice] = useState<number>(0);
const [confirmReset, setConfirmReset] = useState<boolean>(false);
const [selectedFilters, setSelectedFilters] = useState<number>(0);
const [search, setSearch] = useState('');
// eslint-disable-next-line
const [masks, setMasks] = useState(() => ['']);
const entities_theme = useTheme({
BaseRow: `
font-size: 14px;
color: white;
height: 32px;
`,
HeaderRow: `
text-transform: uppercase;
background-color: black;
border-bottom: 1px solid #e0e0e0;
color: #90CAF9;
font-weight: 500;
`,
Row: `
background-color: #1e1e1e;
border-top: 1px solid #565656;
border-bottom: 1px solid #565656;
position: relative;
z-index: 1;
&:not(:last-of-type) {
margin-bottom: -1px;
}
&:not(:first-of-type) {
margin-top: -1px;
}
&:hover {
z-index: 2;
color: white;
border-top: 1px solid #177ac9;
border-bottom: 1px solid #177ac9;
},
&.tr.tr-body.row-select.row-select-single-selected, &.tr.tr-body.row-select.row-select-selected {
background-color: #3d4752;
color: white;
font-weight: normal;
z-index: 2;
border-top: 1px solid #177ac9;
border-bottom: 1px solid #177ac9;
}
`,
BaseCell: `
padding-left: 8px;
border-top: 1px solid transparent;
border-right: 1px solid transparent;
border-bottom: 1px solid transparent;
&:nth-of-type(1) {
left: 0px;
min-width: 124px;
width: 124px;
padding-left: 0px;
}
&:nth-of-type(2) {
min-width: 70%;
width: 70%;
}
`,
HeaderCell: `
padding-left: 0px;
&:nth-of-type(1) {
padding-left: 24px;
}
&:nth-of-type(3) {
border-left: 1px solid #565656;
}
`
});
const getSortIcon = (state: any, sortKey: any) => {
if (state.sortKey === sortKey && state.reverse) {
return <KeyboardArrowDownOutlinedIcon />;
}
if (state.sortKey === sortKey && !state.reverse) {
return <KeyboardArrowUpOutlinedIcon />;
}
return <UnfoldMoreOutlinedIcon />;
};
const entity_sort = useSort(
{ nodes: deviceEntities },
{},
{
sortIcon: {
iconDefault: <UnfoldMoreOutlinedIcon />,
iconUp: <KeyboardArrowUpOutlinedIcon />,
iconDown: <KeyboardArrowDownOutlinedIcon />
},
sortToggleType: SortToggleType.AlternateWithReset,
sortFns: {
NAME: (array) => array.sort((a, b) => a.id.localeCompare(b.id))
}
}
);
const fetchDevices = useCallback(async () => {
try {
setDevices((await EMSESP.readDevices()).data);
@@ -93,47 +188,112 @@ const SettingsCustomization: FC = () => {
return value;
}
const getMaskNumber = (newMask: string[]) => {
var new_mask = 0;
for (let entry of newMask) {
new_mask |= Number(entry);
}
return new_mask;
};
const getMaskString = (m: number) => {
var new_masks = [];
if ((m & 1) === 1) {
new_masks.push('1');
}
if ((m & 2) === 2) {
new_masks.push('2');
}
if ((m & 4) === 4) {
new_masks.push('4');
}
if ((m & 8) === 8) {
new_masks.push('8');
}
return new_masks;
};
const maskDisabled = (set: boolean) => {
setDeviceEntities(
deviceEntities.map(function (de) {
if ((de.m & selectedFilters || !selectedFilters) && de.id.toLowerCase().includes(search.toLowerCase())) {
return {
...de,
m: set
? de.m | (DeviceEntityMask.DV_API_MQTT_EXCLUDE | DeviceEntityMask.DV_WEB_EXCLUDE)
: de.m & ~(DeviceEntityMask.DV_API_MQTT_EXCLUDE | DeviceEntityMask.DV_WEB_EXCLUDE)
};
} else {
return de;
}
})
);
};
function compareDevices(a: DeviceShort, b: DeviceShort) {
if (a.s < b.s) {
return -1;
}
if (a.s > b.s) {
return 1;
}
return 0;
}
const changeSelectedDevice = (event: React.ChangeEvent<HTMLInputElement>) => {
const selected_device = parseInt(event.target.value, 10);
setSelectedDevice(selected_device);
fetchDeviceEntities(selected_device);
};
const resetCustomization = async () => {
try {
await EMSESP.resetCustomizations();
enqueueSnackbar('All customizations have been removed. Restarting...', { variant: 'info' });
} catch (error: any) {
enqueueSnackbar(extractErrorMessage(error, 'Problem resetting customizations'), { variant: 'error' });
} finally {
setConfirmReset(false);
}
};
const saveCustomization = async () => {
if (deviceEntities && selectedDevice) {
const masked_entities = deviceEntities
.filter((de) => de.m !== de.om)
.map((new_de) => new_de.m.toString(16).padStart(2, '0') + new_de.s);
if (masked_entities.length > 60) {
enqueueSnackbar('Selected entities exceeded limit of 60. Please Save in batches', { variant: 'warning' });
return;
}
try {
const response = await EMSESP.writeMaskedEntities({
id: selectedDevice,
entity_ids: masked_entities
});
if (response.status === 200) {
enqueueSnackbar('Customization saved', { variant: 'success' });
} else {
enqueueSnackbar('Customization save failed', { variant: 'error' });
}
} catch (error: any) {
enqueueSnackbar(extractErrorMessage(error, 'Problem sending entity list'), { variant: 'error' });
}
setInitialMask(deviceEntities);
}
};
const renderDeviceList = () => {
if (!devices) {
return <FormLoader errorMessage={errorMessage} />;
}
function compareDevices(a: DeviceShort, b: DeviceShort) {
if (a.s < b.s) {
return -1;
}
if (a.s > b.s) {
return 1;
}
return 0;
}
const changeSelectedDevice = (event: React.ChangeEvent<HTMLInputElement>) => {
const selected_device = parseInt(event.target.value, 10);
setSelectedDevice(selected_device);
fetchDeviceEntities(selected_device);
};
return (
<>
<Box color="warning.main">
<Typography variant="body2">Select a device and customize each of its entities using the options:</Typography>
<Typography mt={1} ml={2} display="block" variant="body2" sx={{ alignItems: 'center', display: 'flex' }}>
<FavoriteBorderOutlinedIcon color="success" sx={{ fontSize: 13 }} />
&nbsp;mark it as favorite to be listed at the top of the Dashboard
</Typography>
<Typography ml={2} display="block" variant="body2" sx={{ alignItems: 'center', display: 'flex' }}>
<EditOffOutlinedIcon color="secondary" sx={{ fontSize: 13 }} />
&nbsp;make it read-only, only if it has write operation available
</Typography>
<Typography ml={2} display="block" variant="body2" sx={{ alignItems: 'center', display: 'flex' }}>
<CommentsDisabledOutlinedIcon color="secondary" sx={{ fontSize: 13 }} />
&nbsp;excluded it from MQTT and API outputs
</Typography>
<Typography ml={2} mb={1} display="block" variant="body2" sx={{ alignItems: 'center', display: 'flex' }}>
<VisibilityOffOutlinedIcon color="secondary" sx={{ fontSize: 13 }} />
&nbsp;hide it from the Dashboard
</Typography>
<Typography variant="body2">Select a device and customize each of its entities using the options.</Typography>
</Box>
<ValidatedTextField
name="device"
@@ -158,131 +318,177 @@ const SettingsCustomization: FC = () => {
);
};
const saveCustomization = async () => {
if (deviceEntities && selectedDevice) {
const masked_entities = deviceEntities
.filter((de) => de.m !== de.om)
.map((new_de) => new_de.m.toString(16).padStart(2, '0') + new_de.s);
if (masked_entities.length > 50) {
enqueueSnackbar(
'Too many selected entities (' + masked_entities.length + '). Limit is 50. Please Save in batches',
{ variant: 'warning' }
);
return;
}
try {
const response = await EMSESP.writeMaskedEntities({
id: selectedDevice,
entity_ids: masked_entities
});
if (response.status === 200) {
enqueueSnackbar('Customization saved', { variant: 'success' });
} else {
enqueueSnackbar('Customization save failed', { variant: 'error' });
}
} catch (error: any) {
enqueueSnackbar(extractErrorMessage(error, 'Problem sending entity list'), { variant: 'error' });
}
setInitialMask(deviceEntities);
}
};
const renderDeviceData = () => {
if (devices?.devices.length === 0 || !deviceEntities) {
if (devices?.devices.length === 0 || deviceEntities[0].id === '') {
return;
}
const setMask = (de: DeviceEntity, newMask: string[]) => {
var new_mask = 0;
for (let entry of newMask) {
new_mask |= Number(entry);
}
de.m = new_mask;
setMasks(newMask);
};
const getMask = (de: DeviceEntity) => {
var new_masks = [];
if ((de.m & 1) === 1 || de.n === '') {
new_masks.push('1');
}
if ((de.m & 2) === 2) {
new_masks.push('2');
}
if ((de.m & 4) === 4 && de.w) {
new_masks.push('4');
}
if ((de.m & 8) === 8) {
new_masks.push('8');
}
return new_masks;
};
const shown_data = deviceEntities.filter(
(de) => (de.m & selectedFilters || !selectedFilters) && de.id.toLowerCase().includes(search.toLowerCase())
);
return (
<Table size="small" padding="normal">
<TableHead>
<TableRow>
<StyledTableCell align="center">OPTIONS</StyledTableCell>
<StyledTableCell align="left">ENTITY NAME (CODE)</StyledTableCell>
<StyledTableCell align="right">VALUE</StyledTableCell>
</TableRow>
</TableHead>
<TableBody>
{deviceEntities.map((de) => (
<TableRow key={de.s} hover>
<StyledTableCell padding="none">
<ToggleButtonGroup
size="small"
color="secondary"
value={getMask(de)}
onChange={(event, mask) => {
setMask(de, mask);
}}
>
<ToggleButton value="8" color="success" disabled={(de.m & 1) !== 0 || de.n === ''}>
<FavoriteBorderOutlinedIcon sx={{ fontSize: 14 }} />
</ToggleButton>
<ToggleButton value="4" disabled={!de.w}>
<EditOffOutlinedIcon sx={{ fontSize: 14 }} />
</ToggleButton>
<ToggleButton value="2">
<CommentsDisabledOutlinedIcon sx={{ fontSize: 14 }} />
</ToggleButton>
<ToggleButton value="1">
<VisibilityOffOutlinedIcon sx={{ fontSize: 14 }} />
</ToggleButton>
</ToggleButtonGroup>
</StyledTableCell>
<StyledTableCell>
{de.n}&nbsp;({de.s})
</StyledTableCell>
<StyledTableCell align="right">{formatValue(de.v)}</StyledTableCell>
</TableRow>
))}
</TableBody>
</Table>
);
};
<>
<Grid container mb={1} mt={0} spacing={1} direction="row" justifyContent="flex-start" alignItems="center">
<Grid item>
<Typography variant="subtitle2" color="primary">
#:
</Typography>
</Grid>
<Grid item>
<Typography variant="subtitle2">
{shown_data.length}/{deviceEntities.length}
</Typography>
</Grid>
<Grid item>
<SearchIcon color="primary" sx={{ fontSize: 16, verticalAlign: 'middle' }} />:
</Grid>
<Grid item xs={2}>
<TextField
size="small"
variant="outlined"
onChange={(event) => {
setSearch(event.target.value);
}}
/>
</Grid>
<Grid item>
<FilterListIcon color="primary" sx={{ fontSize: 14, verticalAlign: 'middle' }} />:
</Grid>
<Grid item>
<ToggleButtonGroup
size="small"
color="secondary"
value={getMaskString(selectedFilters)}
onChange={(event, mask) => {
setSelectedFilters(getMaskNumber(mask));
}}
>
<ToggleButton value="8">
<Tooltip arrow placement="top" title="mark it as favorite to be listed at the top of the Dashboard">
<StarIcon sx={{ fontSize: 14 }} />
</Tooltip>
</ToggleButton>
<ToggleButton value="4">
<Tooltip arrow placement="top" title="make it read-only, only if it has write operation available">
<EditOffOutlinedIcon sx={{ fontSize: 14 }} />
</Tooltip>
</ToggleButton>
<ToggleButton value="2">
<Tooltip arrow placement="top" title="excluded it from MQTT and API outputs">
<CommentsDisabledOutlinedIcon sx={{ fontSize: 14 }} />
</Tooltip>
</ToggleButton>
<ToggleButton value="1">
<Tooltip arrow placement="top" title="hide it from the Dashboard">
<VisibilityOffOutlinedIcon sx={{ fontSize: 14 }} />
</Tooltip>
</ToggleButton>
</ToggleButtonGroup>
</Grid>
const resetCustomization = async () => {
try {
await EMSESP.resetCustomizations();
enqueueSnackbar('All customizations have been removed. Restarting...', { variant: 'info' });
} catch (error: any) {
enqueueSnackbar(extractErrorMessage(error, 'Problem resetting customizations'), { variant: 'error' });
} finally {
setConfirmReset(false);
}
<Grid item>
<CommentsDisabledOutlinedIcon color="primary" sx={{ fontSize: 14, verticalAlign: 'middle' }} />
<VisibilityOffOutlinedIcon color="primary" sx={{ fontSize: 14, verticalAlign: 'middle' }} />:
</Grid>
<Grid item>
<Button
size="small"
sx={{ fontSize: 10 }}
variant="outlined"
color="inherit"
onClick={() => maskDisabled(false)}
>
enable
</Button>
</Grid>
<Grid item>
<Button
size="small"
sx={{ fontSize: 10 }}
variant="outlined"
color="inherit"
onClick={() => maskDisabled(true)}
>
disable
</Button>
</Grid>
</Grid>
<Table
data={{ nodes: shown_data }}
theme={entities_theme}
sort={entity_sort}
layout={{ custom: true, horizontalScroll: true }}
>
{(tableList: any) => (
<>
<Header>
<HeaderRow>
<HeaderCell pinLeft>OPTIONS</HeaderCell>
<HeaderCell resize>
<Button
fullWidth
style={{ fontSize: '14px', justifyContent: 'flex-start' }}
endIcon={getSortIcon(entity_sort.state, 'NAME')}
onClick={() => entity_sort.fns.onToggleSort({ sortKey: 'NAME' })}
>
NAME
</Button>
</HeaderCell>
<HeaderCell>VALUE</HeaderCell>
<HeaderCell />
</HeaderRow>
</Header>
<Body>
{tableList.map((de: DeviceEntity) => (
<Row key={de.id} item={de}>
<Cell>
<ToggleButtonGroup
size="small"
color="secondary"
value={getMaskString(de.m)}
onChange={(event, mask) => {
de.m = getMaskNumber(mask);
if (de.m & DeviceEntityMask.DV_WEB_EXCLUDE) {
de.m = de.m & ~DeviceEntityMask.DV_FAVORITE;
}
setMasks(['']);
}}
>
<ToggleButton value="8" disabled={(de.m & 1) !== 0 || de.id === ''}>
<StarIcon sx={{ fontSize: 14 }} />
</ToggleButton>
<ToggleButton value="4" disabled={!de.w || (de.m & 3) === 3}>
<EditOffOutlinedIcon sx={{ fontSize: 14 }} />
</ToggleButton>
<ToggleButton value="2">
<CommentsDisabledOutlinedIcon sx={{ fontSize: 14 }} />
</ToggleButton>
<ToggleButton value="1">
<VisibilityOffOutlinedIcon sx={{ fontSize: 14 }} />
</ToggleButton>
</ToggleButtonGroup>
</Cell>
<Cell>
{de.id}&nbsp;({de.s})
</Cell>
<Cell>{formatValue(de.v)}</Cell>
</Row>
))}
</Body>
</>
)}
</Table>
</>
);
};
const renderResetDialog = () => (
<Dialog open={confirmReset} onClose={() => setConfirmReset(false)}>
<DialogTitle>Reset</DialogTitle>
<DialogContent dividers>
Are you sure you want remove all customizations? EMS-ESP will then restart.
Are you sure you want remove all customizations including the custom settings of the Temperature and Analog
sensors?
</DialogContent>
<DialogActions>
<Button startIcon={<CancelIcon />} variant="outlined" onClick={() => setConfirmReset(false)} color="secondary">

View File

@@ -38,38 +38,23 @@ export enum busConnectionStatus {
BUS_STATUS_OFFLINE = 2
}
export interface Stat {
id: string; // name
s: number; // success
f: number; // fail
q: number; // quality
}
export interface Status {
status: busConnectionStatus;
tx_mode: number;
rx_received: number;
tx_reads: number;
tx_writes: number;
rx_quality: number;
tx_read_quality: number;
tx_write_quality: number;
tx_read_fails: number;
tx_write_fails: number;
rx_fails: number;
sensor_fails: number;
sensor_reads: number;
sensor_quality: number;
analog_fails: number;
analog_reads: number;
analog_quality: number;
mqtt_count: number;
mqtt_fails: number;
mqtt_quality: number;
api_calls: number;
api_fails: number;
api_quality: number;
uptime: number;
num_devices: number;
num_sensors: number;
num_analogs: number;
uptime: number;
stats: Stat[];
}
export interface Device {
i: number; // id
id: string; // id index
t: string; // type
b: string; // brand
n: string; // name
@@ -80,7 +65,7 @@ export interface Device {
}
export interface Sensor {
is: string; // id string
id: string; // id string
n: string; // name/alias
t?: number; // temp, optional
o: number; // offset
@@ -88,9 +73,10 @@ export interface Sensor {
}
export interface Analog {
i: number;
id: string; // id string
g: number; // GPIO
n: string;
v?: number;
v: number; // is optional
u: number;
o: number;
f: number;
@@ -98,7 +84,7 @@ export interface Analog {
}
export interface WriteSensor {
id_str: string;
id: string;
name: string;
offset: number;
}
@@ -126,11 +112,11 @@ export interface Devices {
}
export interface DeviceValue {
v?: any; // value, in any format
id: string; // index, contains mask+name
v: any; // value, in any format
u: number; // uom
n: string; // name
c: string; // command
l: string[]; // list
c?: string; // command, optional
l?: string[]; // list, optional
h?: string; // help text, optional
s?: string; // steps for up/down, optional
m?: string; // min, optional
@@ -143,8 +129,8 @@ export interface DeviceData {
}
export interface DeviceEntity {
v?: any; // value, in any format
n: string; // name
id: string; // name
v: any; // value, in any format
s: string; // shortname
m: number; // mask
om?: number; // original mask before edits
@@ -277,7 +263,7 @@ export interface WriteValue {
}
export interface WriteAnalog {
id: number;
gpio: number;
name: string;
factor: number;
offset: number;

View File

@@ -1,4 +1,5 @@
export interface User {
id: string; // needed for Table
username: string;
password: string;
admin: boolean;

View File

@@ -43,6 +43,7 @@ class SecuritySettings {
JsonArray users = root.createNestedArray("users");
for (User user : settings.users) {
JsonObject userRoot = users.createNestedObject();
userRoot["id"] = user.username; // for React Table
userRoot["username"] = user.username;
userRoot["password"] = user.password;
userRoot["admin"] = user.admin;

View File

@@ -253,7 +253,7 @@ const UPLOAD_FIRMWARE_ENDPOINT = REST_ENDPOINT_ROOT + 'uploadFirmware'
const SIGN_IN_ENDPOINT = REST_ENDPOINT_ROOT + 'signIn'
const GENERATE_TOKEN_ENDPOINT = REST_ENDPOINT_ROOT + 'generateToken'
const system_status = {
emsesp_version: '3.4.0demo',
emsesp_version: '3.4demo',
esp_platform: 'ESP32',
max_alloc_heap: 113792,
psram_size: 0,
@@ -270,8 +270,8 @@ const system_status = {
security_settings = {
jwt_secret: 'naughty!',
users: [
{ username: 'admin', password: 'admin', admin: true },
{ username: 'guest', password: 'guest', admin: false },
{ id: 'admin', username: 'admin', password: 'admin', admin: true },
{ id: 'guest', username: 'guest', password: 'guest', admin: false },
],
}
const features = {
@@ -362,11 +362,11 @@ const emsesp_devices = {
}
const emsesp_coredata = {
// devices: [],
devices: [
{
i: 2,
id: '2',
t: 'Boiler',
s: 'Boiler',
b: 'Nefit',
n: 'GBx72/Trendline/Cerapur/Greenstar Si/27i',
d: 8,
@@ -375,9 +375,8 @@ const emsesp_coredata = {
e: 68,
},
{
i: 1,
id: '1',
t: 'Thermostat',
s: 'Thermostat',
b: '',
n: 'RC20/Moduline 300',
d: 23,
@@ -386,9 +385,8 @@ const emsesp_coredata = {
e: 5,
},
{
i: 4,
id: '4',
t: 'Thermostat',
s: 'Thermostat',
b: 'Buderus',
n: 'RC100/Moduline 1000/1010',
d: 16,
@@ -403,49 +401,37 @@ const emsesp_coredata = {
const emsesp_sensordata = {
sensors: [
{ is: '28-233D-9497-0C03', n: 'Dallas 1', t: 25.7, o: 1.2, u: 1 },
{ is: '28-243D-7437-1E3A', n: 'Dallas 2 outside', t: 26.1, o: 0, u: 1 },
{ is: '28-243E-7437-1E3B', n: 'Zolder', t: 27.1, o: 0, u: 16 },
{ is: '28-183D-1892-0C33', n: 'Roof', o: 2, u: 1 },
{ id: '28-233D-9497-0C03', n: 'Dallas 1', t: 25.7, o: 1.2, u: 1 },
{ id: '28-243D-7437-1E3A', n: 'Dallas 2 outside', t: 26.1, o: 0, u: 1 },
{ id: '28-243E-7437-1E3B', n: 'Zolder', t: 27.1, o: 0, u: 16 },
{ id: '28-183D-1892-0C33', n: 'Roof', o: 2, u: 1 },
],
// sensors: [],
analogs: [
{ i: 36, n: 'motor', u: 0, o: 17, f: 0, t: 0 },
{ i: 37, n: 'External switch', v: 13, u: 0, o: 17, f: 0, t: 1 },
{ i: 39, n: 'Pulse count', v: 144, u: 0, o: 0, f: 0, t: 2 },
{ i: 40, n: 'Pressure', v: 16, u: 17, o: 0, f: 0, t: 3 },
{ id: '1', g: 36, n: 'motor', v: 0, u: 0, o: 17, f: 0, t: 0 },
{ id: '2', g: 37, n: 'External switch', v: 13, u: 0, o: 17, f: 0, t: 1 },
{ id: '3', g: 39, n: 'Pulse count', v: 144, u: 0, o: 0, f: 0, t: 2 },
{ id: '4', g: 40, n: 'Pressure', v: 16, u: 17, o: 0, f: 0, t: 3 },
],
// analogs: [],
}
const status = {
analog_fails: 0,
analog_quality: 100,
analog_reads: 203,
api_calls: 4,
api_fails: 0,
api_quality: 100,
mqtt_count: 40243,
mqtt_fails: 0,
mqtt_quality: 100,
num_analogs: 1,
num_devices: 2,
num_sensors: 1,
rx_fails: 11,
rx_quality: 100,
rx_received: 56506,
sensor_fails: 0,
sensor_quality: 100,
sensor_reads: 15438,
status: 0,
tx_mode: 1,
tx_read_fails: 0,
tx_read_quality: 100,
tx_reads: 9026,
tx_write_fails: 2,
tx_write_quality: 95,
tx_writes: 33,
uptime: 77186,
num_devices: 2,
num_sensors: 1,
num_analogs: 1,
stats: [
{ id: 'EMS Telegrams Received (Rx)', s: 56506, f: 11, q: 100 },
{ id: 'EMS Reads (Tx)', s: 9026, f: 0, q: 100 },
{ id: 'EMS Writes (Tx)', s: 33, f: 2, q: 95 },
{ id: 'Temperature Sensor Reads', s: 56506, f: 11, q: 100 },
{ id: 'Analog Sensor Reads', s: 0, f: 0, q: 100 },
{ id: 'MQTT Publishes', s: 12, f: 10, q: 20 },
{ id: 'API Calls', s: 0, f: 0, q: 0 },
],
}
// Dashboard data
@@ -455,31 +441,28 @@ const emsesp_devicedata_1 = {
{
v: '(0)',
u: 0,
n: '00error code',
c: '',
id: '00error code',
},
{
v: '14:54:39 06/06/2021',
u: 0,
n: '00date/time',
c: '',
id: '00date/time',
},
{
v: 18,
u: 1,
n: '00hc1 selected room temperature',
id: '00hc1 selected room temperature',
c: 'hc1/seltemp',
},
{
v: 22.6,
u: 1,
n: '00hc1 current room temperature',
c: '',
id: '00hc1 current room temperature',
},
{
v: 'auto',
u: 0,
n: '00hc1 mode',
id: '00hc1 mode',
c: 'hc1/mode',
},
],
@@ -488,81 +471,81 @@ const emsesp_devicedata_1 = {
const emsesp_devicedata_2 = {
label: 'Boiler: Nefit GBx72/Trendline/Cerapur/Greenstar Si/27i',
data: [
{ u: 0, n: '08reset', c: 'reset', l: ['-', 'maintenance', 'error'] },
{ v: 'false', u: 0, n: '08heating active' },
{ v: 'false', u: 0, n: '04tapwater active' },
{ v: 5, u: 1, n: '04selected flow temperature', c: 'selflowtemp' },
{ v: 0, u: 3, n: '0Eburner selected max power', c: 'selburnpow' },
{ v: 0, u: 3, n: '00heating pump modulation' },
{ v: 53.4, u: 1, n: '00current flow temperature' },
{ v: 52.7, u: 1, n: '00return temperature' },
{ v: 1.3, u: 10, n: '00system pressure' },
{ v: 54.9, u: 1, n: '00actual boiler temperature' },
{ v: 'false', u: 0, n: '00gas' },
{ v: 'false', u: 0, n: '00gas stage 2' },
{ v: 0, u: 9, n: '00flame current' },
{ v: 'false', u: 0, n: '00heating pump' },
{ v: 'false', u: 0, n: '00fan' },
{ v: 'false', u: 0, n: '00ignition' },
{ v: 'false', u: 0, n: '00oil preheating' },
{ v: 'true', u: 0, n: '00heating activated', c: 'heatingactivated', l: ['off', 'on'] },
{ v: 80, u: 1, n: '00heating temperature', c: 'heatingtemp' },
{ v: 70, u: 3, n: '00burner pump max power', c: 'pumpmodmax' },
{ v: 30, u: 3, n: '00burner pump min power', c: 'pumpmodmin' },
{ v: 1, u: 8, n: '00pump delay', c: 'pumpdelay' },
{ v: 10, u: 8, n: '00burner min period', c: 'burnminperiod' },
{ v: 0, u: 3, n: '00burner min power', c: 'burnminpower' },
{ v: 50, u: 3, n: '00burner max power', c: 'burnmaxpower' },
{ v: -6, u: 2, n: '00hysteresis on temperature', c: 'boilhyston' },
{ v: 6, u: 2, n: '00hysteresis off temperature', c: 'boilhystoff' },
{ v: 0, u: 1, n: '00set flow temperature' },
{ v: 0, u: 3, n: '00burner set power' },
{ v: 0, u: 3, n: '00burner current power' },
{ v: 326323, u: 0, n: '00burner starts' },
{ v: 553437, u: 8, n: '00total burner operating time' },
{ v: 451286, u: 8, n: '00total heat operating time' },
{ v: 4672173, u: 8, n: '00total UBA operating time' },
{ v: '1C(210) 06.06.2020 12:07 (0 min)', u: 0, n: '00last error code' },
{ v: '0H', u: 0, n: '00service code' },
{ v: 203, u: 0, n: '00service code number' },
{ v: 'H00', u: 0, n: '00maintenance message' },
{ v: 'manual', u: 0, n: '00maintenance scheduled', c: 'maintenance', l: ['off', 'time', 'date', 'manual'] },
{ v: 6000, u: 7, n: '00time to next maintenance', c: 'maintenancetime' },
{ v: '01.01.2012', u: 0, n: '00next maintenance date', c: 'maintenancedate', o: 'Format: < dd.mm.yyyy >' },
{ v: 'true', u: 0, n: '00dhw turn on/off', c: 'wwtapactivated', l: ['off', 'on'] },
{ v: 62, u: 1, n: '00dhw set temperature' },
{ v: 60, u: 1, n: '00dhw selected temperature', c: 'wwseltemp' },
{ v: 'flow', u: 0, n: '00dhw type' },
{ v: 'hot', u: 0, n: '00dhw comfort', c: 'wwcomfort', l: ['hot', 'eco', 'intelligent'] },
{ v: 40, u: 2, n: '00dhw flow temperature offset', c: 'wwflowtempoffset' },
{ v: 100, u: 3, n: '00dhw max power', c: 'wwmaxpower' },
{ v: 'false', u: 0, n: '00dhw circulation pump available', c: 'wwcircpump', l: ['off', 'on'] },
{ v: '3-way valve', u: 0, n: '00dhw charging type' },
{ v: -5, u: 2, n: '00dhw hysteresis on temperature', c: 'wwhyston' },
{ v: 0, u: 2, n: '00dhw hysteresis off temperature', c: 'wwhystoff' },
{ v: 70, u: 1, n: '00dhw disinfection temperature', c: 'wwdisinfectiontemp' },
{ v: 0, u: 0, id: '08reset', c: 'reset', l: ['-', 'maintenance', 'error'] },
{ v: 'false', u: 0, id: '08heating active' },
{ v: 'false', u: 0, id: '04tapwater active' },
{ v: 5, u: 1, id: '04selected flow temperature', c: 'selflowtemp' },
{ v: 0, u: 3, id: '0Eburner selected max power', c: 'selburnpow' },
{ v: 0, u: 3, id: '00heating pump modulation' },
{ v: 53.4, u: 1, id: '00current flow temperature' },
{ v: 52.7, u: 1, id: '00return temperature' },
{ v: 1.3, u: 10, id: '00system pressure' },
{ v: 54.9, u: 1, id: '00actual boiler temperature' },
{ v: 'false', u: 0, id: '00gas' },
{ v: 'false', u: 0, id: '00gas stage 2' },
{ v: 0, u: 9, id: '00flame current' },
{ v: 'false', u: 0, id: '00heating pump' },
{ v: 'false', u: 0, id: '00fan' },
{ v: 'false', u: 0, id: '00ignition' },
{ v: 'false', u: 0, id: '00oil preheating' },
{ v: 'true', u: 0, id: '00heating activated', c: 'heatingactivated', l: ['off', 'on'] },
{ v: 80, u: 1, id: '00heating temperature', c: 'heatingtemp' },
{ v: 70, u: 3, id: '00burner pump max power', c: 'pumpmodmax' },
{ v: 30, u: 3, id: '00burner pump min power', c: 'pumpmodmin' },
{ v: 1, u: 8, id: '00pump delay', c: 'pumpdelay' },
{ v: 10, u: 8, id: '00burner min period', c: 'burnminperiod' },
{ v: 0, u: 3, id: '00burner min power', c: 'burnminpower' },
{ v: 50, u: 3, id: '00burner max power', c: 'burnmaxpower' },
{ v: -6, u: 2, id: '00hysteresis on temperature', c: 'boilhyston' },
{ v: 6, u: 2, id: '00hysteresis off temperature', c: 'boilhystoff' },
{ v: 0, u: 1, id: '00set flow temperature' },
{ v: 0, u: 3, id: '00burner set power' },
{ v: 0, u: 3, id: '00burner current power' },
{ v: 326323, u: 0, id: '00burner starts' },
{ v: 553437, u: 8, id: '00total burner operating time' },
{ v: 451286, u: 8, id: '00total heat operating time' },
{ v: 4672173, u: 8, id: '00total UBA operating time' },
{ v: '1C(210) 06.06.2020 12:07 (0 min)', u: 0, id: '00last error code' },
{ v: '0H', u: 0, id: '00service code' },
{ v: 203, u: 0, id: '00service code number' },
{ v: 'H00', u: 0, id: '00maintenance message' },
{ v: 'manual', u: 0, id: '00maintenance scheduled', c: 'maintenance', l: ['off', 'time', 'date', 'manual'] },
{ v: 6000, u: 7, id: '00time to next maintenance', c: 'maintenancetime' },
{ v: '01.01.2012', u: 0, id: '00next maintenance date', c: 'maintenancedate', o: 'Format: < dd.mm.yyyy >' },
{ v: 'true', u: 0, id: '00dhw turn on/off', c: 'wwtapactivated', l: ['off', 'on'] },
{ v: 62, u: 1, id: '00dhw set temperature' },
{ v: 60, u: 1, id: '00dhw selected temperature', c: 'wwseltemp' },
{ v: 'flow', u: 0, id: '00dhw type' },
{ v: 'hot', u: 0, id: '00dhw comfort', c: 'wwcomfort', l: ['hot', 'eco', 'intelligent'] },
{ v: 40, u: 2, id: '00dhw flow temperature offset', c: 'wwflowtempoffset' },
{ v: 100, u: 3, id: '00dhw max power', c: 'wwmaxpower' },
{ v: 'false', u: 0, id: '00dhw circulation pump available', c: 'wwcircpump', l: ['off', 'on'] },
{ v: '3-way valve', u: 0, id: '00dhw charging type' },
{ v: -5, u: 2, id: '00dhw hysteresis on temperature', c: 'wwhyston' },
{ v: 0, u: 2, id: '00dhw hysteresis off temperature', c: 'wwhystoff' },
{ v: 70, u: 1, id: '00dhw disinfection temperature', c: 'wwdisinfectiontemp' },
{
v: 'off',
u: 0,
n: '00dhw circulation pump mode',
id: '00dhw circulation pump mode',
c: 'wwcircmode',
l: ['off', '1x3min', '2x3min', '3x3min', '4x3min', '5x3min', '6x3min', 'continuous'],
},
{ v: 'false', u: 0, n: '00dhw circulation active', c: 'wwcirc', l: ['off', 'on'] },
{ v: 47.3, u: 1, n: '00dhw current intern temperature' },
{ v: 0, u: 4, n: '00dhw current tap water flow' },
{ v: 47.3, u: 1, n: '00dhw storage intern temperature' },
{ v: 'true', u: 0, n: '00dhw activated', c: 'wwactivated', l: ['off', 'on'] },
{ v: 'false', u: 0, n: '00dhw one time charging', c: 'wwonetime', l: ['off', 'on'] },
{ v: 'false', u: 0, n: '00dhw disinfecting', c: 'wwdisinfecting', l: ['off', 'on'] },
{ v: 'false', u: 0, n: '00dhw charging' },
{ v: 'false', u: 0, n: '00dhw recharging' },
{ v: 'true', u: 0, n: '00dhw temperature ok' },
{ v: 'false', u: 0, n: '00dhw active' },
{ v: 'true', u: 0, n: '00dhw 3way valve active' },
{ v: 0, u: 3, n: '00dhw set pump power' },
{ v: 288768, u: 0, n: '00dhw starts' },
{ v: 102151, u: 8, n: '00dhw active time' },
{ v: 'false', u: 0, id: '00dhw circulation active', c: 'wwcirc', l: ['off', 'on'] },
{ v: 47.3, u: 1, id: '00dhw current intern temperature' },
{ v: 0, u: 4, id: '00dhw current tap water flow' },
{ v: 47.3, u: 1, id: '00dhw storage intern temperature' },
{ v: 'true', u: 0, id: '00dhw activated', c: 'wwactivated', l: ['off', 'on'] },
{ v: 'false', u: 0, id: '00dhw one time charging', c: 'wwonetime', l: ['off', 'on'] },
{ v: 'false', u: 0, id: '00dhw disinfecting', c: 'wwdisinfecting', l: ['off', 'on'] },
{ v: 'false', u: 0, id: '00dhw charging' },
{ v: 'false', u: 0, id: '00dhw recharging' },
{ v: 'true', u: 0, id: '00dhw temperature ok' },
{ v: 'false', u: 0, id: '00dhw active' },
{ v: 'true', u: 0, id: '00dhw 3way valve active' },
{ v: 0, u: 3, id: '00dhw set pump power' },
{ v: 288768, u: 0, id: '00dhw starts' },
{ v: 102151, u: 8, id: '00dhw active time' },
],
}
@@ -572,19 +555,19 @@ const emsesp_devicedata_4 = {
{
v: 16,
u: 1,
n: '00hc2 selected room temperature',
id: '08hc2 selected room temperature',
c: 'hc2/seltemp',
},
{
v: 18.6,
u: 1,
n: '00hc2 current room temperature',
id: '02hc2 current room temperature',
c: '',
},
{
v: 'off',
u: 0,
n: '00hc2 mode',
id: '02hc2 mode',
c: 'hc2/mode',
},
],
@@ -593,35 +576,35 @@ const emsesp_devicedata_4 = {
const emsesp_deviceentities_1 = [
{
v: '(0)',
n: 'error code',
id: 'error code',
s: 'errorcode',
m: 0,
w: false,
},
{
v: '14:54:39 06/06/2021',
n: 'date/time',
id: 'date/time',
s: 'datetime',
m: 0,
w: false,
},
{
v: 18.2,
n: 'hc1 selected room temperature',
id: 'hc1 selected room temperature',
s: 'hc1/seltemp',
m: 0,
w: true,
},
{
v: 22.6,
n: 'hc1 current room temperature',
id: 'hc1 current room temperature',
s: 'hc1/curtemp',
m: 0,
w: false,
},
{
v: 'auto',
n: 'hc1 mode',
id: 'hc1 mode',
s: 'hc1/mode',
m: 0,
w: true,
@@ -629,107 +612,107 @@ const emsesp_deviceentities_1 = [
]
const emsesp_deviceentities_2 = [
{ v: false, n: 'heating active', s: 'heatingactive', m: 0 },
{ v: false, n: 'tapwater active', s: 'tapwateractive', m: 0 },
{ v: 5, n: 'selected flow temperature', s: 'selflowtemp', m: 0 },
{ v: 0, n: 'burner selected max power', s: 'selburnpow', m: 0 },
{ v: 0, n: 'heating pump modulation', s: 'heatingpumpmod', m: 0 },
{ n: 'heating pump 2 modulation', s: 'heatingpump2mod', m: 0 },
{ n: 'outside temperature', s: 'outdoortemp', m: 0 },
{ v: 53, n: 'current flow temperature', s: 'curflowtemp', m: 0 },
{ v: 51.8, n: 'return temperature', s: 'rettemp', m: 0 },
{ n: 'mixing switch temperature', s: 'switchtemp', m: 0 },
{ v: 1.3, n: 'system pressure', s: 'syspress', m: 0 },
{ v: 54.6, n: 'actual boiler temperature', s: 'boiltemp', m: 0 },
{ n: 'exhaust temperature', s: 'exhausttemp', m: 0 },
{ v: false, n: 'gas', s: 'burngas', m: 0 },
{ v: false, n: 'gas stage 2', s: 'burngas2', m: 0 },
{ v: 0, n: 'flame current', s: 'flamecurr', m: 0 },
{ v: false, n: 'heating pump', s: 'heatingpump', m: 0 },
{ v: false, n: 'fan', s: 'fanwork', m: 0 },
{ v: false, n: 'ignition', s: 'ignwork', m: 0 },
{ v: false, n: 'oil preheating', s: 'oilpreheat', m: 0 },
{ v: true, n: 'heating activated', s: 'heatingactivated', m: 0 },
{ v: 80, n: 'heating temperature', s: 'heatingtemp', m: 0 },
{ v: 70, n: 'burner pump max power', s: 'pumpmodmax', m: 0 },
{ v: 30, n: 'burner pump min power', s: 'pumpmodmin', m: 0 },
{ v: 1, n: 'pump delay', s: 'pumpdelay', m: 0 },
{ v: 10, n: 'burner min period', s: 'burnminperiod', m: 0 },
{ v: 0, n: 'burner min power', s: 'burnminpower', m: 0 },
{ v: 50, n: 'burner max power', s: 'burnmaxpower', m: 0 },
{ v: -6, n: 'hysteresis on temperature', s: 'boilhyston', m: 0 },
{ v: 6, n: 'hysteresis off temperature', s: 'boilhystoff', m: 0 },
{ v: 0, n: 'set flow temperature', s: 'setflowtemp', m: 0 },
{ v: 0, n: 'burner set power', s: 'setburnpow', m: 0 },
{ v: 0, n: 'burner current power', s: 'curburnpow', m: 0 },
{ v: 326323, n: 'burner starts', s: 'burnstarts', m: 0 },
{ v: 553437, n: 'total burner operating time', s: 'burnworkmin', m: 0 },
{ v: 451286, n: 'total heat operating time', s: 'heatworkmin', m: 0 },
{ v: 4672175, n: 'total UBA operating time', s: 'ubauptime', m: 0 },
{ v: '1C(210) 06.06.2020 12:07 (0 min)', n: 'last error code', s: 'lastcode', m: 0 },
{ v: '0H', n: 'service code', s: 'servicecode', m: 0 },
{ v: 203, n: 'service code number', s: 'servicecodenumber', m: 0 },
{ v: 'H00', n: 'maintenance message', s: 'maintenancemessage', m: 0 },
{ v: 'manual', n: 'maintenance scheduled', s: 'maintenance', m: 0 },
{ v: 6000, n: 'time to next maintenance', s: 'maintenancetime', m: 0 },
{ v: '01.01.2012', n: 'next maintenance date', s: 'maintenancedate', m: 0 },
{ v: true, n: 'dhw turn on/off', s: 'wwtapactivated', m: 0 },
{ v: 62, n: 'dhw set temperature', s: 'wwsettemp', m: 0 },
{ v: 60, n: 'dhw selected temperature', s: 'wwseltemp', m: 0 },
{ n: 'dhw selected lower temperature', s: 'wwseltemplow', m: 2 },
{ n: 'dhw selected temperature for off', s: 'wwseltempoff', m: 2 },
{ n: 'dhw single charge temperature', s: 'wwseltempsingle', m: 2 },
{ v: 'flow', n: 'dhw type', s: 'wwtype', m: 0 },
{ v: 'hot', n: 'dhw comfort', s: 'wwcomfort', m: 0 },
{ v: 40, n: 'dhw flow temperature offset', s: 'wwflowtempoffset', m: 0 },
{ v: 100, n: 'dhw max power', s: 'wwmaxpower', m: 0 },
{ v: false, n: 'dhw circulation pump available', s: 'wwcircpump', m: 0 },
{ v: '3-way valve', n: 'dhw charging type', s: 'wwchargetype', m: 0 },
{ v: -5, n: 'dhw hysteresis on temperature', s: 'wwhyston', m: 0 },
{ v: 0, n: 'dhw hysteresis off temperature', s: 'wwhystoff', m: 0 },
{ v: 70, n: 'dhw disinfection temperature', s: 'wwdisinfectiontemp', m: 0 },
{ v: 'off', n: 'dhw circulation pump mode', s: 'wwcircmode', m: 0 },
{ v: false, n: 'dhw circulation active', s: 'wwcirc', m: 0 },
{ v: 46.4, n: 'dhw current intern temperature', s: 'wwcurtemp', m: 0 },
{ n: 'dhw current extern temperature', s: 'wwcurtemp2', m: 2 },
{ v: 0, n: 'dhw current tap water flow', s: 'wwcurflow', m: 0 },
{ v: 46.3, n: 'dhw storage intern temperature', s: 'wwstoragetemp1', m: 0 },
{ n: 'dhw storage extern temperature', s: 'wwstoragetemp2', m: 2 },
{ v: true, n: 'dhw activated', s: 'wwactivated', m: 0 },
{ v: false, n: 'dhw one time charging', s: 'wwonetime', m: 0 },
{ v: false, n: 'dhw disinfecting', s: 'wwdisinfecting', m: 0 },
{ v: false, n: 'dhw charging', s: 'wwcharging', m: 0 },
{ v: false, n: 'dhw recharging', s: 'wwrecharging', m: 0 },
{ v: true, n: 'dhw temperature ok', s: 'wwtempok', m: 0 },
{ v: false, n: 'dhw active', s: 'wwactive', m: 0 },
{ v: true, n: 'dhw 3way valve active', s: 'ww3wayvalve', m: 0 },
{ v: 0, n: 'dhw set pump power', s: 'wwsetpumppower', m: 0 },
{ n: 'dhw mixer temperature', s: 'wwmixertemp', m: 2 },
{ n: 'dhw cylinder middle temperature (TS3)', s: 'wwcylmiddletemp', m: 2 },
{ v: 288768, n: 'dhw starts', s: 'wwstarts', m: 0 },
{ v: 102151, n: 'dhw active time', s: 'wwworkm', m: 0 },
{ v: false, id: 'heating active', s: 'heatingactive', m: 0, w: false },
{ v: false, id: 'tapwater active', s: 'tapwateractive', m: 0, w: false },
{ v: 5, id: 'selected flow temperature', s: 'selflowtemp', m: 0, w: true },
{ v: 0, id: 'burner selected max power', s: 'selburnpow', m: 0, w: true },
{ v: 0, id: 'heating pump modulation', s: 'heatingpumpmod', m: 0, w: false },
{ id: 'heating pump 2 modulation', s: 'heatingpump2mod', m: 0, w: false },
{ id: 'outside temperature', s: 'outdoortemp', m: 0, w: false },
{ v: 53, id: 'current flow temperature', s: 'curflowtemp', m: 0, w: false },
{ v: 51.8, id: 'return temperature', s: 'rettemp', m: 0, w: false },
{ id: 'mixing switch temperature', s: 'switchtemp', m: 0, w: false },
{ v: 1.3, id: 'system pressure', s: 'syspress', m: 0, w: false },
{ v: 54.6, id: 'actual boiler temperature', s: 'boiltemp', m: 0, w: false },
{ id: 'exhaust temperature', s: 'exhausttemp', m: 0, w: false },
{ v: false, id: 'gas', s: 'burngas', m: 0, w: false },
{ v: false, id: 'gas stage 2', s: 'burngas2', m: 0, w: false },
{ v: 0, id: 'flame current', s: 'flamecurr', m: 0, w: false },
{ v: false, id: 'heating pump', s: 'heatingpump', m: 0, w: false },
{ v: false, id: 'fan', s: 'fanwork', m: 0, w: false },
{ v: false, id: 'ignition', s: 'ignwork', m: 0, w: false },
{ v: false, id: 'oil preheating', s: 'oilpreheat', m: 0, w: false },
{ v: true, id: 'heating activated', s: 'heatingactivated', m: 0, w: false },
{ v: 80, id: 'heating temperature', s: 'heatingtemp', m: 0, w: false },
{ v: 70, id: 'burner pump max power', s: 'pumpmodmax', m: 0, w: false },
{ v: 30, id: 'burner pump min power', s: 'pumpmodmin', m: 0, w: false },
{ v: 1, id: 'pump delay', s: 'pumpdelay', m: 0, w: false },
{ v: 10, id: 'burner min period', s: 'burnminperiod', m: 0, w: false },
{ v: 0, id: 'burner min power', s: 'burnminpower', m: 0, w: false },
{ v: 50, id: 'burner max power', s: 'burnmaxpower', m: 0, w: false },
{ v: -6, id: 'hysteresis on temperature', s: 'boilhyston', m: 0, w: false },
{ v: 6, id: 'hysteresis off temperature', s: 'boilhystoff', m: 0, w: false },
{ v: 0, id: 'set flow temperature', s: 'setflowtemp', m: 0, w: true },
{ v: 0, id: 'burner set power', s: 'setburnpow', m: 0, w: false },
{ v: 0, id: 'burner current power', s: 'curburnpow', m: 0, w: false },
{ v: 326323, id: 'burner starts', s: 'burnstarts', m: 0, w: false },
{ v: 553437, id: 'total burner operating time', s: 'burnworkmin', m: 0, w: false },
{ v: 451286, id: 'total heat operating time', s: 'heatworkmin', m: 0, w: false },
{ v: 4672175, id: 'total UBA operating time', s: 'ubauptime', m: 0, w: false },
{ v: '1C(210) 06.06.2020 12:07 (0 min)', id: 'last error code', s: 'lastcode', m: 0, w: false },
{ v: '0H', id: 'service code', s: 'servicecode', m: 0, w: false },
{ v: 203, id: 'service code number', s: 'servicecodenumber', m: 0, w: false },
{ v: 'H00', id: 'maintenance message', s: 'maintenancemessage', m: 0, w: false },
{ v: 'manual', id: 'maintenance scheduled', s: 'maintenance', m: 0, w: false },
{ v: 6000, id: 'time to next maintenance', s: 'maintenancetime', m: 0, w: false },
{ v: '01.01.2012', id: 'next maintenance date', s: 'maintenancedate', m: 0, w: false },
{ v: true, id: 'dhw turn on/off', s: 'wwtapactivated', m: 0, w: false },
{ v: 62, id: 'dhw set temperature', s: 'wwsettemp', m: 0, w: false },
{ v: 60, id: 'dhw selected temperature', s: 'wwseltemp', m: 0, w: true },
{ id: 'dhw selected lower temperature', s: 'wwseltemplow', m: 2 },
{ id: 'dhw selected temperature for off', s: 'wwseltempoff', m: 2 },
{ id: 'dhw single charge temperature', s: 'wwseltempsingle', m: 2 },
{ v: 'flow', id: 'dhw type', s: 'wwtype', m: 0, w: false },
{ v: 'hot', id: 'dhw comfort', s: 'wwcomfort', m: 0, w: false },
{ v: 40, id: 'dhw flow temperature offset', s: 'wwflowtempoffset', m: 0, w: false },
{ v: 100, id: 'dhw max power', s: 'wwmaxpower', m: 0, w: false },
{ v: false, id: 'dhw circulation pump available', s: 'wwcircpump', m: 0, w: false },
{ v: '3-way valve', id: 'dhw charging type', s: 'wwchargetype', m: 0, w: false },
{ v: -5, id: 'dhw hysteresis on temperature', s: 'wwhyston', m: 0, w: false },
{ v: 0, id: 'dhw hysteresis off temperature', s: 'wwhystoff', m: 0, w: false },
{ v: 70, id: 'dhw disinfection temperature', s: 'wwdisinfectiontemp', m: 0, w: false },
{ v: 'off', id: 'dhw circulation pump mode', s: 'wwcircmode', m: 0, w: false },
{ v: false, id: 'dhw circulation active', s: 'wwcirc', m: 0, w: false },
{ v: 46.4, id: 'dhw current intern temperature', s: 'wwcurtemp', m: 0, w: false },
{ id: 'dhw current extern temperature', s: 'wwcurtemp2', m: 2 },
{ v: 0, id: 'dhw current tap water flow', s: 'wwcurflow', m: 0, w: false },
{ v: 46.3, id: 'dhw storage intern temperature', s: 'wwstoragetemp1', m: 0, w: false },
{ id: 'dhw storage extern temperature', s: 'wwstoragetemp2', m: 2 },
{ v: true, id: 'dhw activated', s: 'wwactivated', m: 0, w: false },
{ v: false, id: 'dhw one time charging', s: 'wwonetime', m: 0, w: false },
{ v: false, id: 'dhw disinfecting', s: 'wwdisinfecting', m: 0, w: false },
{ v: false, id: 'dhw charging', s: 'wwcharging', m: 0, w: false },
{ v: false, id: 'dhw recharging', s: 'wwrecharging', m: 0, w: false },
{ v: true, id: 'dhw temperature ok', s: 'wwtempok', m: 0, w: false },
{ v: false, id: 'dhw active', s: 'wwactive', m: 0, w: false },
{ v: true, id: 'dhw 3way valve active', s: 'ww3wayvalve', m: 0, w: false },
{ v: 0, id: 'dhw set pump power', s: 'wwsetpumppower', m: 0, w: true },
{ id: 'dhw mixer temperature', s: 'wwmixertemp', m: 2 },
{ id: 'dhw cylinder middle temperature (TS3)', s: 'wwcylmiddletemp', m: 2 },
{ v: 288768, id: 'dhw starts', s: 'wwstarts', m: 0, w: false },
{ v: 102151, id: 'dhw active time', s: 'wwworkm', m: 0, w: false },
]
const emsesp_deviceentities_4 = [
{
v: 16,
n: 'hc2 selected room temperature',
id: 'hc2 selected room temperature',
s: 'hc2/seltemp',
m: 0,
m: 8,
w: true,
},
{
v: 18.5,
n: 'hc2 current room temperature',
id: 'hc2 current room temperature',
s: 'hc2/curtemp',
m: 3,
m: 2,
w: false,
},
{
v: 'off',
n: 'hc2 mode',
id: 'hc2 mode',
s: 'hc2/mode',
m: 3,
m: 2,
w: true,
},
]
@@ -870,9 +853,11 @@ rest_server.post(EMSESP_SETTINGS_ENDPOINT, (req, res) => {
// res.status(200).json(settings); // no restart needed
})
rest_server.get(EMSESP_CORE_DATA_ENDPOINT, (req, res) => {
console.log('send back core data...')
res.json(emsesp_coredata)
})
rest_server.get(EMSESP_SENSOR_DATA_ENDPOINT, (req, res) => {
console.log('send back sensor data...')
res.json(emsesp_sensordata)
})
rest_server.get(EMSESP_DEVICES_ENDPOINT, (req, res) => {
@@ -887,6 +872,7 @@ rest_server.get(EMSESP_STATUS_ENDPOINT, (req, res) => {
})
rest_server.post(EMSESP_DEVICEDATA_ENDPOINT, (req, res) => {
const id = req.body.id
console.log('send back device data for ' + id)
if (id === 1) {
const encoded = msgpack.encode(emsesp_devicedata_1)
res.write(encoded, 'binary')
@@ -930,15 +916,15 @@ function updateMask(entity, de, dd) {
objIndex = de.findIndex((obj) => obj.s == name)
if (objIndex !== -1) {
de[objIndex].m = new_mask
const fullname = de[objIndex].n
objIndex = dd.data.findIndex((obj) => obj.n.slice(2) == fullname)
const fullname = de[objIndex].id
objIndex = dd.data.findIndex((obj) => obj.id.slice(2) == fullname)
if (objIndex !== -1) {
// see if the mask has changed
const old_mask = parseInt(dd.data[objIndex].n.slice(0, 2), 16)
const old_mask = parseInt(dd.data[objIndex].id.slice(0, 2), 16)
if (old_mask !== new_mask) {
const mask_hex = entity.slice(0, 2)
console.log('Updating ' + dd.data[objIndex].n + ' -> ' + mask_hex + fullname)
dd.data[objIndex].n = mask_hex + fullname
console.log('Updating ' + dd.data[objIndex].id + ' -> ' + mask_hex + fullname)
dd.data[objIndex].id = mask_hex + fullname
}
}
} else {
@@ -948,6 +934,7 @@ function updateMask(entity, de, dd) {
rest_server.post(EMSESP_MASKED_ENTITIES_ENDPOINT, (req, res) => {
const id = req.body.id
console.log('customization id = ' + id)
console.log(req.body.entity_ids)
for (const entity of req.body.entity_ids) {
if (id === 1) {
@@ -986,7 +973,7 @@ rest_server.post(EMSESP_WRITE_VALUE_ENDPOINT, (req, res) => {
rest_server.post(EMSESP_WRITE_SENSOR_ENDPOINT, (req, res) => {
const sensor = req.body
console.log('Write sensor: ' + JSON.stringify(sensor))
objIndex = emsesp_sensordata.sensors.findIndex((obj) => obj.is == sensor.id_str)
objIndex = emsesp_sensordata.sensors.findIndex((obj) => obj.id == sensor.id)
emsesp_sensordata.sensors[objIndex].n = sensor.name
emsesp_sensordata.sensors[objIndex].o = sensor.offset
res.sendStatus(200)
@@ -995,12 +982,13 @@ rest_server.post(EMSESP_WRITE_SENSOR_ENDPOINT, (req, res) => {
rest_server.post(EMSESP_WRITE_ANALOG_ENDPOINT, (req, res) => {
const analog = req.body
console.log('Write analog: ' + JSON.stringify(analog))
objIndex = emsesp_sensordata.analogs.findIndex((obj) => obj.i == analog.id)
objIndex = emsesp_sensordata.analogs.findIndex((obj) => obj.i == analog.i)
if (objIndex === -1) {
console.log('new analog')
emsesp_sensordata.analogs.push({
i: analog.id,
id: analog.i.toString(),
i: analog.i,
n: analog.name,
f: analog.factor,
o: analog.offset,
@@ -1009,9 +997,10 @@ rest_server.post(EMSESP_WRITE_ANALOG_ENDPOINT, (req, res) => {
})
} else {
if (analog.type === -1) {
console.log('removing analog ' + analog.id)
console.log('removing analog ' + analog.i)
emsesp_sensordata.analogs[objIndex].t = -1
} else {
console.log('updating analog ' + analog.i)
emsesp_sensordata.analogs[objIndex].n = analog.name
emsesp_sensordata.analogs[objIndex].o = analog.offset
emsesp_sensordata.analogs[objIndex].f = analog.factor

View File

@@ -61,10 +61,7 @@ extra_scripts =
pre:scripts/build_interface.py
scripts/rename_fw.py
board = esp32dev
platform = espressif32
; platform_packages =
; toolchain-xtensa32@~2.80400.0
; framework-arduinoespressif32@https://github.com/espressif/arduino-esp32.git
platform = espressif32@3.5.0
board_build.partitions = esp32_partition_app1984k_spiffs64k.csv
build_flags = ${common.build_flags}
build_unflags = ${common.unbuild_flags}

View File

@@ -69,7 +69,7 @@ void AnalogSensor::reload() {
// update existing sensors
bool found = false;
for (const auto & sensor : settings.analogCustomizations) { //search customlist
if (sensor_.id() == sensor.id) {
if (sensor_.gpio() == sensor.gpio) {
// for output sensors set value to new start-value
if ((sensor.type == AnalogType::COUNTER || sensor.type >= AnalogType::DIGITAL_OUT)
&& (sensor_.type() != sensor.type || sensor_.offset() != sensor.offset || sensor_.factor() != sensor.factor)) {
@@ -94,12 +94,12 @@ void AnalogSensor::reload() {
for (const auto & sensor : settings.analogCustomizations) {
bool found = false;
for (const auto & sensor_ : sensors_) {
if (sensor_.id() == sensor.id) {
if (sensor_.gpio() == sensor.gpio) {
found = true;
}
}
if (!found) {
sensors_.emplace_back(sensor.id, sensor.name, sensor.offset, sensor.factor, sensor.uom, sensor.type);
sensors_.emplace_back(sensor.gpio, sensor.name, sensor.offset, sensor.factor, sensor.uom, sensor.type);
sensors_.back().ha_registered = false; // this will trigger recrate of the HA config
if (sensor.type == AnalogType::COUNTER || sensor.type >= AnalogType::DIGITAL_OUT) {
sensors_.back().set_value(sensor.offset);
@@ -112,64 +112,64 @@ void AnalogSensor::reload() {
});
// sort the list based on GPIO (id)
std::sort(sensors_.begin(), sensors_.end(), [](const Sensor & a, const Sensor & b) { return a.id() < b.id(); });
// std::sort(sensors_.begin(), sensors_.end(), [](const Sensor & a, const Sensor & b) { return a.id() < b.id(); });
// activate each sensor
for (auto & sensor : sensors_) {
sensor.ha_registered = false; // force HA configs to be re-created
if (sensor.type() == AnalogType::ADC) {
LOG_DEBUG(F("Adding analog ADC sensor on GPIO%d"), sensor.id());
LOG_DEBUG(F("Adding analog ADC sensor on GPIO%d"), sensor.gpio());
// analogSetPinAttenuation does not work with analogReadMilliVolts
sensor.analog_ = 0; // initialize
sensor.last_reading_ = 0;
} else if (sensor.type() == AnalogType::COUNTER) {
LOG_DEBUG(F("Adding analog I/O Counter sensor on GPIO%d"), sensor.id());
pinMode(sensor.id(), INPUT_PULLUP);
if (sensor.id() == 25 || sensor.id() == 26) {
dacWrite(sensor.id(), 255);
LOG_DEBUG(F("Adding analog I/O Counter sensor on GPIO%d"), sensor.gpio());
pinMode(sensor.gpio(), INPUT_PULLUP);
if (sensor.gpio() == 25 || sensor.gpio() == 26) {
dacWrite(sensor.gpio(), 255);
}
sensor.polltime_ = 0;
sensor.poll_ = digitalRead(sensor.id());
sensor.poll_ = digitalRead(sensor.gpio());
publish_sensor(sensor);
} else if (sensor.type() == AnalogType::TIMER || sensor.type() == AnalogType::RATE) {
LOG_DEBUG(F("Adding analog Timer/Rate sensor on GPIO%d"), sensor.id());
pinMode(sensor.id(), INPUT_PULLUP);
LOG_DEBUG(F("Adding analog Timer/Rate sensor on GPIO%d"), sensor.gpio());
pinMode(sensor.gpio(), INPUT_PULLUP);
sensor.polltime_ = uuid::get_uptime();
sensor.last_polltime_ = uuid::get_uptime();
sensor.poll_ = digitalRead(sensor.id());
sensor.poll_ = digitalRead(sensor.gpio());
sensor.set_offset(0);
sensor.set_value(0);
publish_sensor(sensor);
} else if (sensor.type() == AnalogType::DIGITAL_IN) {
LOG_DEBUG(F("Adding analog Read sensor on GPIO%d"), sensor.id());
pinMode(sensor.id(), INPUT_PULLUP);
sensor.set_value(digitalRead(sensor.id())); // initial value
sensor.set_uom(0); // no uom, just for safe measures
LOG_DEBUG(F("Adding analog Read sensor on GPIO%d"), sensor.gpio());
pinMode(sensor.gpio(), INPUT_PULLUP);
sensor.set_value(digitalRead(sensor.gpio())); // initial value
sensor.set_uom(0); // no uom, just for safe measures
sensor.polltime_ = 0;
sensor.poll_ = digitalRead(sensor.id());
sensor.poll_ = digitalRead(sensor.gpio());
publish_sensor(sensor);
} else if (sensor.type() == AnalogType::DIGITAL_OUT) {
LOG_DEBUG(F("Adding analog Write sensor on GPIO%d"), sensor.id());
pinMode(sensor.id(), OUTPUT);
if (sensor.id() == 25 || sensor.id() == 26) {
LOG_DEBUG(F("Adding analog Write sensor on GPIO%d"), sensor.gpio());
pinMode(sensor.gpio(), OUTPUT);
if (sensor.gpio() == 25 || sensor.gpio() == 26) {
if (sensor.offset() > 255) {
sensor.set_offset(255);
} else if (sensor.offset() < 0) {
sensor.set_offset(0);
}
dacWrite(sensor.id(), sensor.offset());
dacWrite(sensor.gpio(), sensor.offset());
sensor.set_value(sensor.offset());
} else {
digitalWrite(sensor.id(), sensor.offset() > 0 ? 1 : 0);
sensor.set_value(digitalRead(sensor.id()));
digitalWrite(sensor.gpio(), sensor.offset() > 0 ? 1 : 0);
sensor.set_value(digitalRead(sensor.gpio()));
}
sensor.set_uom(0); // no uom, just for safe measures
publish_sensor(sensor);
} else if (sensor.type() >= AnalogType::PWM_0) {
LOG_DEBUG(F("Adding PWM output sensor on GPIO%d"), sensor.id());
LOG_DEBUG(F("Adding PWM output sensor on GPIO%d"), sensor.gpio());
uint channel = sensor.type() - AnalogType::PWM_0;
ledcSetup(channel, sensor.factor(), 13);
ledcAttachPin(sensor.id(), channel);
ledcAttachPin(sensor.gpio(), channel);
if (sensor.offset() > 100) {
sensor.set_offset(100);
} else if (sensor.offset() < 0) {
@@ -193,8 +193,8 @@ void AnalogSensor::measure() {
// go through the list of adc sensors
for (auto & sensor : sensors_) {
if (sensor.type() == AnalogType::ADC) {
uint16_t a = analogReadMilliVolts(sensor.id()); // e.g. ADC1_CHANNEL_0_GPIO_NUM
if (!sensor.analog_) { // init first time
uint16_t a = analogReadMilliVolts(sensor.gpio()); // e.g. ADC1_CHANNEL_0_GPIO_NUM
if (!sensor.analog_) { // init first time
sensor.analog_ = a;
sensor.sum_ = a * 512;
} else { // simple moving average filter
@@ -218,7 +218,7 @@ void AnalogSensor::measure() {
if (sensor.type() == AnalogType::DIGITAL_IN || sensor.type() == AnalogType::COUNTER || sensor.type() == AnalogType::TIMER
|| sensor.type() == AnalogType::RATE) {
auto old_value = sensor.value(); // remember current value before reading
auto current_reading = digitalRead(sensor.id());
auto current_reading = digitalRead(sensor.gpio());
if (sensor.poll_ != current_reading) { // check for pinchange
sensor.polltime_ = uuid::get_uptime(); // remember time of pinchange
sensor.poll_ = current_reading;
@@ -258,17 +258,17 @@ void AnalogSensor::loop() {
}
// update analog information name and offset
bool AnalogSensor::update(uint8_t id, const std::string & name, float offset, float factor, uint8_t uom, int8_t type) {
bool AnalogSensor::update(uint8_t gpio, const std::string & name, float offset, float factor, uint8_t uom, int8_t type) {
boolean found_sensor = false; // see if we can find the sensor in our customization list
EMSESP::webCustomizationService.update(
[&](WebCustomization & settings) {
for (auto & AnalogCustomization : settings.analogCustomizations) {
if (AnalogCustomization.id == id) {
if (AnalogCustomization.gpio == gpio) {
found_sensor = true; // found the record
// see if it's marked for deletion
if (type == AnalogType::MARK_DELETED) {
LOG_DEBUG(F("Removing analog sensor ID %d"), id);
LOG_DEBUG(F("Removing analog sensor GPIO %d"), gpio);
settings.analogCustomizations.remove(AnalogCustomization);
} else {
// update existing record
@@ -277,7 +277,7 @@ bool AnalogSensor::update(uint8_t id, const std::string & name, float offset, fl
AnalogCustomization.factor = factor;
AnalogCustomization.uom = uom;
AnalogCustomization.type = type;
LOG_DEBUG(F("Customizing existing analog sensor ID %d"), id);
LOG_DEBUG(F("Customizing existing analog GPIO %d"), gpio);
}
return StateUpdateResult::CHANGED; // persist the change
}
@@ -288,7 +288,7 @@ bool AnalogSensor::update(uint8_t id, const std::string & name, float offset, fl
// if the sensor exists and we're using HA, delete the old HA record
if (found_sensor && Mqtt::ha_enabled()) {
remove_ha_topic(id); // id is the GPIO
remove_ha_topic(gpio); // the GPIO
}
// we didn't find it, it's new, so create and store it
@@ -296,14 +296,14 @@ bool AnalogSensor::update(uint8_t id, const std::string & name, float offset, fl
EMSESP::webCustomizationService.update(
[&](WebCustomization & settings) {
auto newSensor = AnalogCustomization();
newSensor.id = id;
newSensor.gpio = gpio;
newSensor.name = name;
newSensor.offset = offset;
newSensor.factor = factor;
newSensor.uom = uom;
newSensor.type = type;
settings.analogCustomizations.push_back(newSensor);
LOG_DEBUG(F("Adding new customization for analog sensor ID %d"), id);
LOG_DEBUG(F("Adding new customization for analog sensor GPIO %d"), gpio);
return StateUpdateResult::CHANGED; // persist the change
},
"local");
@@ -339,15 +339,15 @@ void AnalogSensor::publish_sensor(const Sensor & sensor) const {
}
// send empty config topic to remove the entry from HA
void AnalogSensor::remove_ha_topic(const uint8_t id) const {
void AnalogSensor::remove_ha_topic(const uint8_t gpio) const {
if (!Mqtt::ha_enabled()) {
return;
}
#ifdef EMSESP_DEBUG
LOG_DEBUG(F("Removing HA config for analog sensor ID %d"), id);
LOG_DEBUG(F("Removing HA config for analog sensor GPIO %d"), gpio);
#endif
char topic[Mqtt::MQTT_TOPIC_MAX_SIZE];
snprintf(topic, sizeof(topic), "sensor/%s/analogsensor_%d/config", Mqtt::base().c_str(), id);
snprintf(topic, sizeof(topic), "sensor/%s/analogsensor_%d/config", Mqtt::base().c_str(), gpio);
Mqtt::publish_ha(topic);
}
@@ -372,7 +372,7 @@ void AnalogSensor::publish_values(const bool force) {
if (Mqtt::is_nested() || Mqtt::ha_enabled()) {
// nested
char s[10];
JsonObject dataSensor = doc.createNestedObject(Helpers::smallitoa(s, sensor.id()));
JsonObject dataSensor = doc.createNestedObject(Helpers::smallitoa(s, sensor.gpio()));
dataSensor["name"] = sensor.name();
switch (sensor.type()) {
case AnalogType::COUNTER:
@@ -391,7 +391,7 @@ void AnalogSensor::publish_values(const bool force) {
// create HA config
if (Mqtt::ha_enabled() && (!sensor.ha_registered || force)) {
LOG_DEBUG(F("Recreating HA config for analog sensor ID %d"), sensor.id());
LOG_DEBUG(F("Recreating HA config for analog sensor GPIO %d"), sensor.gpio());
StaticJsonDocument<EMSESP_JSON_SIZE_MEDIUM> config;
@@ -400,13 +400,13 @@ void AnalogSensor::publish_values(const bool force) {
config["stat_t"] = stat_t;
char str[50];
snprintf(str, sizeof(str), "{{value_json['%d'].value}}", sensor.id());
snprintf(str, sizeof(str), "{{value_json['%d'].value}}", sensor.gpio());
config["val_tpl"] = str;
snprintf(str, sizeof(str), "Analog Sensor %s", sensor.name().c_str());
config["name"] = str;
snprintf(str, sizeof(str), "analogsensor_%d", sensor.id());
snprintf(str, sizeof(str), "analogsensor_%d", sensor.gpio());
config["uniq_id"] = str;
JsonObject dev = config.createNestedObject("dev");
@@ -414,7 +414,7 @@ void AnalogSensor::publish_values(const bool force) {
ids.add("ems-esp");
char topic[Mqtt::MQTT_TOPIC_MAX_SIZE];
snprintf(topic, sizeof(topic), "sensor/%s/analogsensor_%d/config", Mqtt::base().c_str(), sensor.id());
snprintf(topic, sizeof(topic), "sensor/%s/analogsensor_%d/config", Mqtt::base().c_str(), sensor.gpio());
Mqtt::publish_ha(topic, config.as<JsonObject>());
@@ -437,7 +437,7 @@ void AnalogSensor::publish_values(const bool force) {
bool AnalogSensor::get_value_info(JsonObject & output, const char * cmd, const int8_t id) const {
for (const auto & sensor : sensors_) {
if (strcmp(cmd, sensor.name().c_str()) == 0) {
output["id"] = sensor.id();
output["gpio"] = sensor.gpio();
output["name"] = sensor.name();
output["type"] = sensor.type();
output["uom"] = sensor.uom();
@@ -460,7 +460,7 @@ bool AnalogSensor::command_info(const char * value, const int8_t id, JsonObject
for (const auto & sensor : sensors_) {
if (id == -1) { // show number and id
JsonObject dataSensor = output.createNestedObject(sensor.name());
dataSensor["id"] = sensor.id();
dataSensor["gpio"] = sensor.gpio();
dataSensor["type"] = FL_(enum_sensortype)[sensor.type()];
if (sensor.type() == AnalogType::ADC) {
dataSensor["uom"] = EMSdevice::uom_to_string(sensor.uom());
@@ -486,8 +486,8 @@ bool AnalogSensor::command_info(const char * value, const int8_t id, JsonObject
}
// this creates the sensor, initializing everything
AnalogSensor::Sensor::Sensor(const uint8_t id, const std::string & name, const float offset, const float factor, const uint8_t uom, const int8_t type)
: id_(id)
AnalogSensor::Sensor::Sensor(const uint8_t gpio, const std::string & name, const float offset, const float factor, const uint8_t uom, const int8_t type)
: gpio_(gpio)
, name_(name)
, offset_(offset)
, factor_(factor)
@@ -500,20 +500,20 @@ AnalogSensor::Sensor::Sensor(const uint8_t id, const std::string & name, const f
std::string AnalogSensor::Sensor::name() const {
if (name_.empty()) {
char name[50];
snprintf(name, sizeof(name), "Analog Sensor GPIO%d", id_);
snprintf(name, sizeof(name), "Analog Sensor GPIO%d", gpio_);
return name;
}
return name_;
}
// set the counter value, id is gpio-no
bool AnalogSensor::command_setvalue(const char * value, const int8_t id) {
bool AnalogSensor::command_setvalue(const char * value, const int8_t gpio) {
float val;
if (!Helpers::value2float(value, val)) {
return false;
}
for (auto & sensor : sensors_) {
if (sensor.id() == id) {
if (sensor.gpio() == gpio) {
if (sensor.type() == AnalogType::COUNTER) {
if (val < 0 || value[0] == '+') { // sign corrects values
sensor.set_offset(sensor.value() + val);
@@ -529,18 +529,18 @@ bool AnalogSensor::command_setvalue(const char * value, const int8_t id) {
return true;
} else if (sensor.type() == AnalogType::DIGITAL_OUT) {
uint8_t v = val;
if (sensor.id() == 25 || sensor.id() == 26) {
if (sensor.gpio() == 25 || sensor.gpio() == 26) {
sensor.set_offset(v);
sensor.set_value(v);
pinMode(sensor.id(), OUTPUT);
dacWrite(sensor.id(), sensor.offset());
pinMode(sensor.gpio(), OUTPUT);
dacWrite(sensor.gpio(), sensor.offset());
publish_sensor(sensor);
return true;
} else if (v == 0 || v == 1) {
sensor.set_offset(v);
sensor.set_value(v);
pinMode(sensor.id(), OUTPUT);
digitalWrite(sensor.id(), sensor.offset() > 0 ? 1 : 0);
pinMode(sensor.gpio(), OUTPUT);
digitalWrite(sensor.gpio(), sensor.offset() > 0 ? 1 : 0);
publish_sensor(sensor);
return true;
}

View File

@@ -36,7 +36,7 @@ class AnalogSensor {
public:
class Sensor {
public:
Sensor(const uint8_t id, const std::string & name, const float offset, const float factor, const uint8_t uom, const int8_t type);
Sensor(const uint8_t gpio, const std::string & name, const float offset, const float factor, const uint8_t uom, const int8_t type);
~Sensor() = default;
void set_offset(const float offset) {
@@ -48,8 +48,8 @@ class AnalogSensor {
name_ = name;
}
uint8_t id() const {
return id_;
uint8_t gpio() const {
return gpio_;
}
float value() const {
@@ -99,7 +99,7 @@ class AnalogSensor {
uint32_t last_polltime_ = 0; // for timer
private:
uint8_t id_;
uint8_t gpio_;
std::string name_;
float offset_;
float factor_;
@@ -157,7 +157,7 @@ class AnalogSensor {
return sensors_.size();
}
bool update(uint8_t id, const std::string & name, float offset, float factor, uint8_t uom, int8_t type);
bool update(uint8_t gpio, const std::string & name, float offset, float factor, uint8_t uom, int8_t type);
bool get_value_info(JsonObject & output, const char * cmd, const int8_t id) const;
#ifdef EMSESP_DEBUG
@@ -171,7 +171,7 @@ class AnalogSensor {
static uuid::log::Logger logger_;
void remove_ha_topic(const uint8_t id) const;
bool command_setvalue(const char * value, const int8_t id);
bool command_setvalue(const char * value, const int8_t gpio);
void measure();
bool command_info(const char * value, const int8_t id, JsonObject & output) const;
bool command_commands(const char * value, const int8_t id, JsonObject & output);

View File

@@ -149,7 +149,7 @@ void DallasSensor::loop() {
// check if we already have this sensor
bool found = false;
for (auto & sensor : sensors_) {
if (sensor.id() == get_id(addr)) {
if (sensor.internal_id() == get_id(addr)) {
t += sensor.offset();
if (t != sensor.temperature_c) {
publish_sensor(sensor);
@@ -171,7 +171,7 @@ void DallasSensor::loop() {
sensors_.back().apply_customization();
publish_sensor(sensors_.back()); // call publish single
// sort the sensors based on name
std::sort(sensors_.begin(), sensors_.end(), [](const Sensor & a, const Sensor & b) { return a.name() < b.name(); });
// std::sort(sensors_.begin(), sensors_.end(), [](const Sensor & a, const Sensor & b) { return a.name() < b.name(); });
}
} else {
sensorfails_++;
@@ -180,12 +180,12 @@ void DallasSensor::loop() {
default:
sensorfails_++;
LOG_ERROR(F("Unknown dallas sensor %s"), Sensor(addr).id_str().c_str());
LOG_ERROR(F("Unknown dallas sensor %s"), Sensor(addr).id().c_str());
break;
}
} else {
sensorfails_++;
LOG_ERROR(F("Invalid dallas sensor %s"), Sensor(addr).id_str().c_str());
LOG_ERROR(F("Invalid dallas sensor %s"), Sensor(addr).id().c_str());
}
} else {
if (!parasite_) {
@@ -229,7 +229,7 @@ bool DallasSensor::temperature_convert_complete() {
int16_t DallasSensor::get_temperature_c(const uint8_t addr[]) {
#ifndef EMSESP_STANDALONE
if (!bus_.reset()) {
LOG_ERROR(F("Bus reset failed before reading scratchpad from %s"), Sensor(addr).id_str().c_str());
LOG_ERROR(F("Bus reset failed before reading scratchpad from %s"), Sensor(addr).id().c_str());
return EMS_VALUE_SHORT_NOTSET;
}
YIELD;
@@ -241,7 +241,7 @@ int16_t DallasSensor::get_temperature_c(const uint8_t addr[]) {
YIELD;
if (!bus_.reset()) {
LOG_ERROR(F("Bus reset failed after reading scratchpad from %s"), Sensor(addr).id_str().c_str());
LOG_ERROR(F("Bus reset failed after reading scratchpad from %s"), Sensor(addr).id().c_str());
return EMS_VALUE_SHORT_NOTSET;
}
YIELD;
@@ -257,7 +257,7 @@ int16_t DallasSensor::get_temperature_c(const uint8_t addr[]) {
scratchpad[6],
scratchpad[7],
scratchpad[8],
Sensor(addr).id_str().c_str());
Sensor(addr).id().c_str());
return EMS_VALUE_SHORT_NOTSET;
}
@@ -290,15 +290,15 @@ int16_t DallasSensor::get_temperature_c(const uint8_t addr[]) {
}
// update dallas information name and offset
bool DallasSensor::update(const std::string & id_str, const std::string & name, int16_t offset) {
bool DallasSensor::update(const std::string & id, const std::string & name, int16_t offset) {
// find the sensor
for (auto & sensor : sensors_) {
if (sensor.id_str() == id_str) {
if (sensor.id() == id) {
// found a match, update the sensor object
// if HA is enabled then delete the old record
if (Mqtt::ha_enabled()) {
remove_ha_topic(id_str);
remove_ha_topic(id);
}
sensor.set_name(name);
@@ -310,21 +310,21 @@ bool DallasSensor::update(const std::string & id_str, const std::string & name,
// look it up to see if it exists
bool found = false;
for (auto & SensorCustomization : settings.sensorCustomizations) {
if (SensorCustomization.id_str == id_str) {
if (SensorCustomization.id == id) {
SensorCustomization.name = name;
SensorCustomization.offset = offset;
found = true;
LOG_DEBUG(F("Customizing existing sensor ID %s"), id_str.c_str());
LOG_DEBUG(F("Customizing existing sensor ID %s"), id.c_str());
break;
}
}
if (!found) {
SensorCustomization newSensor = SensorCustomization();
newSensor.id_str = id_str;
newSensor.id = id;
newSensor.name = name;
newSensor.offset = offset;
settings.sensorCustomizations.push_back(newSensor);
LOG_DEBUG(F("Adding new customization for sensor ID %s"), id_str.c_str());
LOG_DEBUG(F("Adding new customization for sensor ID %s"), id.c_str());
}
sensor.ha_registered = false; // it's changed so we may need to recreate the HA config
return StateUpdateResult::CHANGED;
@@ -361,7 +361,7 @@ bool DallasSensor::command_info(const char * value, const int8_t id, JsonObject
for (const auto & sensor : sensors_) {
if (id == -1) { // show number and id
JsonObject dataSensor = output.createNestedObject(sensor.name());
dataSensor["id_str"] = sensor.id_str();
dataSensor["id"] = sensor.id();
if (Helpers::hasValue(sensor.temperature_c)) {
dataSensor["temp"] = Helpers::round2((float)(sensor.temperature_c), 10, EMSESP::system_.fahrenheit() ? 2 : 0);
}
@@ -377,8 +377,8 @@ bool DallasSensor::command_info(const char * value, const int8_t id, JsonObject
bool DallasSensor::get_value_info(JsonObject & output, const char * cmd, const int8_t id) {
for (const auto & sensor : sensors_) {
if (strcmp(cmd, sensor.name().c_str()) == 0) {
output["id_str"] = sensor.id_str();
output["name"] = sensor.name();
output["id"] = sensor.id();
output["name"] = sensor.name();
if (Helpers::hasValue(sensor.temperature_c)) {
output["value"] = Helpers::round2((float)(sensor.temperature_c), 10, EMSESP::system_.fahrenheit() ? 2 : 0);
}
@@ -408,15 +408,15 @@ void DallasSensor::publish_sensor(const Sensor & sensor) {
}
// send empty config topic to remove the entry from HA
void DallasSensor::remove_ha_topic(const std::string & id_str) {
void DallasSensor::remove_ha_topic(const std::string & id) {
if (!Mqtt::ha_enabled()) {
return;
}
#ifdef EMSESP_DEBUG
LOG_DEBUG(F("Removing HA config for temperature sensor ID %s"), id_str.c_str());
LOG_DEBUG(F("Removing HA config for temperature sensor ID %s"), id.c_str());
#endif
// use '_' as HA doesn't like '-' in the topic name
std::string sensorid = id_str;
std::string sensorid = id;
std::replace(sensorid.begin(), sensorid.end(), '-', '_');
char topic[Mqtt::MQTT_TOPIC_MAX_SIZE];
snprintf(topic, sizeof(topic), "sensor/%s/dallassensor_%s/config", Mqtt::base().c_str(), sensorid.c_str());
@@ -442,7 +442,7 @@ void DallasSensor::publish_values(const bool force) {
for (auto & sensor : sensors_) {
bool has_value = Helpers::hasValue(sensor.temperature_c);
if (Mqtt::is_nested() || Mqtt::ha_enabled()) {
JsonObject dataSensor = doc.createNestedObject(sensor.id_str());
JsonObject dataSensor = doc.createNestedObject(sensor.id());
dataSensor["name"] = sensor.name();
if (has_value) {
dataSensor["temp"] = Helpers::round2((float)(sensor.temperature_c), 10, EMSESP::system_.fahrenheit() ? 2 : 0);
@@ -455,7 +455,7 @@ void DallasSensor::publish_values(const bool force) {
// to e.g. homeassistant/sensor/ems-esp/dallassensor_28-233D-9497-0C03/config
if (Mqtt::ha_enabled()) {
if (!sensor.ha_registered || force) {
LOG_DEBUG(F("Recreating HA config for sensor ID %s"), sensor.id_str().c_str());
LOG_DEBUG(F("Recreating HA config for sensor ID %s"), sensor.id().c_str());
StaticJsonDocument<EMSESP_JSON_SIZE_MEDIUM> config;
config["dev_cla"] = FJSON("temperature");
@@ -467,13 +467,13 @@ void DallasSensor::publish_values(const bool force) {
config["unit_of_meas"] = EMSdevice::uom_to_string(DeviceValueUOM::DEGREES);
char str[50];
snprintf(str, sizeof(str), "{{value_json['%s'].temp}}", sensor.id_str().c_str());
snprintf(str, sizeof(str), "{{value_json['%s'].temp}}", sensor.id().c_str());
config["val_tpl"] = str;
snprintf(str, sizeof(str), "Temperature Sensor %s", sensor.name().c_str());
config["name"] = str;
snprintf(str, sizeof(str), "dallasensor_%s", sensor.id_str().c_str());
snprintf(str, sizeof(str), "dallasensor_%s", sensor.id().c_str());
config["uniq_id"] = str;
JsonObject dev = config.createNestedObject("dev");
@@ -482,7 +482,7 @@ void DallasSensor::publish_values(const bool force) {
char topic[Mqtt::MQTT_TOPIC_MAX_SIZE];
// use '_' as HA doesn't like '-' in the topic name
std::string sensorid = sensor.id_str();
std::string sensorid = sensor.id();
std::replace(sensorid.begin(), sensorid.end(), '-', '_');
snprintf(topic, sizeof(topic), "sensor/%s/dallassensor_%s/config", Mqtt::base().c_str(), sensorid.c_str());
@@ -500,18 +500,18 @@ void DallasSensor::publish_values(const bool force) {
// skip crc from id
DallasSensor::Sensor::Sensor(const uint8_t addr[])
: id_(((uint64_t)addr[0] << 48) | ((uint64_t)addr[1] << 40) | ((uint64_t)addr[2] << 32) | ((uint64_t)addr[3] << 24) | ((uint64_t)addr[4] << 16)
| ((uint64_t)addr[5] << 8) | ((uint64_t)addr[6])) {
: internal_id_(((uint64_t)addr[0] << 48) | ((uint64_t)addr[1] << 40) | ((uint64_t)addr[2] << 32) | ((uint64_t)addr[3] << 24) | ((uint64_t)addr[4] << 16)
| ((uint64_t)addr[5] << 8) | ((uint64_t)addr[6])) {
// create ID string
char id[20];
snprintf(id,
sizeof(id),
char id_s[20];
snprintf(id_s,
sizeof(id_s),
"%02X-%04X-%04X-%04X",
(unsigned int)(id_ >> 48) & 0xFF,
(unsigned int)(id_ >> 32) & 0xFFFF,
(unsigned int)(id_ >> 16) & 0xFFFF,
(unsigned int)(id_)&0xFFFF);
id_str_ = std::string(id);
(unsigned int)(internal_id_ >> 48) & 0xFF,
(unsigned int)(internal_id_ >> 32) & 0xFFFF,
(unsigned int)(internal_id_ >> 16) & 0xFFFF,
(unsigned int)(internal_id_)&0xFFFF);
id_ = std::string(id_s);
name_ = std::string{}; // name (alias) is empty
offset_ = 0; // 0 degrees offset
}
@@ -525,7 +525,7 @@ uint64_t DallasSensor::get_id(const uint8_t addr[]) {
// if empty, return the ID as a string
std::string DallasSensor::Sensor::name() const {
if (name_.empty()) {
return id_str_;
return id_;
}
return name_;
}
@@ -538,9 +538,9 @@ bool DallasSensor::Sensor::apply_customization() {
if (!sensors.empty()) {
for (const auto & sensor : sensors) {
#if defined(EMSESP_DEBUG)
LOG_DEBUG(F("Loading customization for dallas sensor %s"), sensor.id_str.c_str());
LOG_DEBUG(F("Loading customization for dallas sensor %s"), sensor.id.c_str());
#endif
if (id_str_ == sensor.id_str) {
if (id_ == sensor.id) {
set_name(sensor.name);
set_offset(sensor.offset);
return true;

View File

@@ -40,12 +40,12 @@ class DallasSensor {
Sensor(const uint8_t addr[]);
~Sensor() = default;
uint64_t id() const {
return id_;
uint64_t internal_id() const {
return internal_id_;
}
std::string id_str() const {
return id_str_;
std::string id() const {
return id_;
}
int16_t offset() const {
@@ -67,8 +67,8 @@ class DallasSensor {
bool ha_registered = false;
private:
uint64_t id_;
std::string id_str_;
uint64_t internal_id_;
std::string id_;
std::string name_;
int16_t offset_;
};
@@ -109,7 +109,7 @@ class DallasSensor {
return sensors_.size();
}
bool update(const std::string & id_str, const std::string & name, int16_t offset);
bool update(const std::string & id, const std::string & name, int16_t offset);
#ifdef EMSESP_DEBUG
void test();
@@ -150,7 +150,7 @@ class DallasSensor {
bool temperature_convert_complete();
int16_t get_temperature_c(const uint8_t addr[]);
uint64_t get_id(const uint8_t addr[]);
void remove_ha_topic(const std::string & id_str);
void remove_ha_topic(const std::string & id);
bool command_info(const char * value, const int8_t id, JsonObject & output);
bool command_commands(const char * value, const int8_t id, JsonObject & output);

View File

@@ -193,7 +193,7 @@ class Boiler : public EMSdevice {
// Pool unit
int8_t poolSetTemp_;
/*
/*
* Hybrid heatpump with telegram 0xBB is readable and writeable in boiler and thermostat
* thermostat always overwrites settings in boiler
* enable settings here if no thermostat is used in system

View File

@@ -346,7 +346,7 @@ std::shared_ptr<Thermostat::HeatingCircuit> Thermostat::heating_circuit(std::sha
heating_circuits_.push_back(new_hc);
// sort based on hc number so there's a nice order when displaying
// TODO temporarily commented out the HC sorting until I'm 100% sure the return object still references the newly created object
// NOTE temporarily commented out the HC sorting until I'm 100% sure the return object still references the newly created object
// not sure if new_hc and heating_circuits_.back() will still reference the new HC after its sorted - to check!
// std::sort(heating_circuits_.begin(), heating_circuits_.end());

View File

@@ -656,119 +656,118 @@ void EMSdevice::generate_values_web(JsonObject & output) {
output["label"] = to_string_short();
JsonArray data = output.createNestedArray("data");
// do two passes. First for all entities marked as favorites, then for all others. This sorts the list.
for (int8_t fav = 1; fav >= 0; fav--) {
for (auto & dv : devicevalues_) {
// check conditions:
// 1. full_name cannot be empty
// 2. it must have a valid value, if it is not a command like 'reset'
// 3. show favorites first
bool show = (fav && dv.has_state(DeviceValueState::DV_FAVORITE)) || (!fav && !dv.has_state(DeviceValueState::DV_FAVORITE));
if (show && !dv.has_state(DeviceValueState::DV_WEB_EXCLUDE) && dv.full_name && (dv.hasValue() || (dv.type == DeviceValueType::CMD))) {
JsonObject obj = data.createNestedObject(); // create the object, we know there is a value
uint8_t fahrenheit = 0;
for (auto & dv : devicevalues_) {
// check conditions:
// 1. full_name cannot be empty
// 2. it must have a valid value, if it is not a command like 'reset'
// 3. show favorites first
if (!dv.has_state(DeviceValueState::DV_WEB_EXCLUDE) && dv.full_name && (dv.hasValue() || (dv.type == DeviceValueType::CMD))) {
JsonObject obj = data.createNestedObject(); // create the object, we know there is a value
uint8_t fahrenheit = 0;
// handle Booleans (true, false), use strings, no native true/false)
if (dv.type == DeviceValueType::BOOL) {
bool value_b = (bool)*(uint8_t *)(dv.value_p);
if (EMSESP::system_.bool_format() == BOOL_FORMAT_10) {
obj["v"] = value_b ? 1 : 0;
} else {
char s[7];
obj["v"] = Helpers::render_boolean(s, value_b);
}
}
// handle TEXT strings
else if (dv.type == DeviceValueType::STRING) {
obj["v"] = (char *)(dv.value_p);
}
// handle ENUMs
else if ((dv.type == DeviceValueType::ENUM) && (*(uint8_t *)(dv.value_p) < dv.options_size)) {
obj["v"] = dv.options[*(uint8_t *)(dv.value_p)];
}
// handle numbers
else {
// If a divider is specified, do the division to 2 decimals places and send back as double/float
// otherwise force as an integer whole
// the nested if's is necessary due to the way the ArduinoJson templates are pre-processed by the compiler
int8_t divider = (dv.options_size == 1) ? Helpers::atoint(read_flash_string(dv.options[0]).c_str()) : 0;
fahrenheit = !EMSESP::system_.fahrenheit() ? 0 : (dv.uom == DeviceValueUOM::DEGREES) ? 2 : (dv.uom == DeviceValueUOM::DEGREES_R) ? 1 : 0;
if ((dv.type == DeviceValueType::INT) && Helpers::hasValue(*(int8_t *)(dv.value_p))) {
obj["v"] = Helpers::round2(*(int8_t *)(dv.value_p), divider, fahrenheit);
} else if ((dv.type == DeviceValueType::UINT) && Helpers::hasValue(*(uint8_t *)(dv.value_p))) {
obj["v"] = Helpers::round2(*(uint8_t *)(dv.value_p), divider, fahrenheit);
} else if ((dv.type == DeviceValueType::SHORT) && Helpers::hasValue(*(int16_t *)(dv.value_p))) {
obj["v"] = Helpers::round2(*(int16_t *)(dv.value_p), divider, fahrenheit);
} else if ((dv.type == DeviceValueType::USHORT) && Helpers::hasValue(*(uint16_t *)(dv.value_p))) {
obj["v"] = Helpers::round2(*(uint16_t *)(dv.value_p), divider, fahrenheit);
} else if ((dv.type == DeviceValueType::ULONG) && Helpers::hasValue(*(uint32_t *)(dv.value_p))) {
obj["v"] = Helpers::round2(*(uint32_t *)(dv.value_p), divider, fahrenheit);
} else if ((dv.type == DeviceValueType::TIME) && Helpers::hasValue(*(uint32_t *)(dv.value_p))) {
uint32_t time_value = *(uint32_t *)(dv.value_p);
obj["v"] = (divider > 0) ? time_value / divider : time_value; // sometimes we need to divide by 60
}
}
// add the unit of measure (uom)
obj["u"] = fahrenheit ? (uint8_t)DeviceValueUOM::FAHRENHEIT : dv.uom;
auto mask = Helpers::hextoa((uint8_t)(dv.state >> 4), false); // create mask to a 2-char string
// add name, prefixing the tag if it exists
if ((dv.tag == DeviceValueTAG::TAG_NONE) || tag_to_string(dv.tag).empty()) {
obj["n"] = mask + read_flash_string(dv.full_name);
} else if (dv.tag < DeviceValueTAG::TAG_HC1) {
obj["n"] = mask + tag_to_string(dv.tag) + " " + read_flash_string(dv.full_name);
// handle Booleans (true, false), use strings, no native true/false)
if (dv.type == DeviceValueType::BOOL) {
bool value_b = (bool)*(uint8_t *)(dv.value_p);
if (EMSESP::system_.bool_format() == BOOL_FORMAT_10) {
obj["v"] = value_b ? 1 : 0;
} else {
obj["n"] = mask + tag_to_string(dv.tag) + " " + read_flash_string(dv.full_name);
char s[7];
obj["v"] = Helpers::render_boolean(s, value_b);
}
}
// add commands and options
if (dv.has_cmd && !dv.has_state(DeviceValueState::DV_READONLY)) {
// add the name of the Command function
if (dv.tag >= DeviceValueTAG::TAG_HC1) {
obj["c"] = tag_to_mqtt(dv.tag) + "/" + read_flash_string(dv.short_name);
} else {
obj["c"] = dv.short_name;
}
// add the Command options
if (dv.type == DeviceValueType::ENUM || (dv.type == DeviceValueType::CMD && dv.options_size > 1)) {
JsonArray l = obj.createNestedArray("l");
for (uint8_t i = 0; i < dv.options_size; i++) {
if (!read_flash_string(dv.options[i]).empty()) {
l.add(read_flash_string(dv.options[i]));
}
}
} else if (dv.type == DeviceValueType::BOOL) {
JsonArray l = obj.createNestedArray("l");
char result[10];
l.add(Helpers::render_boolean(result, false));
l.add(Helpers::render_boolean(result, true));
}
// add command help template
else if (dv.type == DeviceValueType::STRING || dv.type == DeviceValueType::CMD) {
if (dv.options_size == 1) {
obj["h"] = dv.options[0];
// handle TEXT strings
else if (dv.type == DeviceValueType::STRING) {
obj["v"] = (char *)(dv.value_p);
}
// handle ENUMs
else if ((dv.type == DeviceValueType::ENUM) && (*(uint8_t *)(dv.value_p) < dv.options_size)) {
obj["v"] = dv.options[*(uint8_t *)(dv.value_p)];
}
// handle numbers
else {
// If a divider is specified, do the division to 2 decimals places and send back as double/float
// otherwise force as an integer whole
// the nested if's is necessary due to the way the ArduinoJson templates are pre-processed by the compiler
int8_t divider = (dv.options_size == 1) ? Helpers::atoint(read_flash_string(dv.options[0]).c_str()) : 0;
fahrenheit = !EMSESP::system_.fahrenheit() ? 0 : (dv.uom == DeviceValueUOM::DEGREES) ? 2 : (dv.uom == DeviceValueUOM::DEGREES_R) ? 1 : 0;
if ((dv.type == DeviceValueType::INT) && Helpers::hasValue(*(int8_t *)(dv.value_p))) {
obj["v"] = Helpers::round2(*(int8_t *)(dv.value_p), divider, fahrenheit);
} else if ((dv.type == DeviceValueType::UINT) && Helpers::hasValue(*(uint8_t *)(dv.value_p))) {
obj["v"] = Helpers::round2(*(uint8_t *)(dv.value_p), divider, fahrenheit);
} else if ((dv.type == DeviceValueType::SHORT) && Helpers::hasValue(*(int16_t *)(dv.value_p))) {
obj["v"] = Helpers::round2(*(int16_t *)(dv.value_p), divider, fahrenheit);
} else if ((dv.type == DeviceValueType::USHORT) && Helpers::hasValue(*(uint16_t *)(dv.value_p))) {
obj["v"] = Helpers::round2(*(uint16_t *)(dv.value_p), divider, fahrenheit);
} else if ((dv.type == DeviceValueType::ULONG) && Helpers::hasValue(*(uint32_t *)(dv.value_p))) {
obj["v"] = Helpers::round2(*(uint32_t *)(dv.value_p), divider, fahrenheit);
} else if ((dv.type == DeviceValueType::TIME) && Helpers::hasValue(*(uint32_t *)(dv.value_p))) {
uint32_t time_value = *(uint32_t *)(dv.value_p);
obj["v"] = (divider > 0) ? time_value / divider : time_value; // sometimes we need to divide by 60
} else {
// must have a value for sorting to work
obj["v"] = "";
}
}
// add the unit of measure (uom)
obj["u"] = fahrenheit ? (uint8_t)DeviceValueUOM::FAHRENHEIT : dv.uom;
auto mask = Helpers::hextoa((uint8_t)(dv.state >> 4), false); // create mask to a 2-char string
// add name, prefixing the tag if it exists. This is the id used for the table sorting
if ((dv.tag == DeviceValueTAG::TAG_NONE) || tag_to_string(dv.tag).empty()) {
obj["id"] = mask + read_flash_string(dv.full_name);
} else if (dv.tag < DeviceValueTAG::TAG_HC1) {
obj["id"] = mask + tag_to_string(dv.tag) + " " + read_flash_string(dv.full_name);
} else {
obj["id"] = mask + tag_to_string(dv.tag) + " " + read_flash_string(dv.full_name);
}
// add commands and options
if (dv.has_cmd && !dv.has_state(DeviceValueState::DV_READONLY)) {
// add the name of the Command function
if (dv.tag >= DeviceValueTAG::TAG_HC1) {
obj["c"] = tag_to_mqtt(dv.tag) + "/" + read_flash_string(dv.short_name);
} else {
obj["c"] = dv.short_name;
}
// add the Command options
if (dv.type == DeviceValueType::ENUM || (dv.type == DeviceValueType::CMD && dv.options_size > 1)) {
JsonArray l = obj.createNestedArray("l");
for (uint8_t i = 0; i < dv.options_size; i++) {
if (!read_flash_string(dv.options[i]).empty()) {
l.add(read_flash_string(dv.options[i]));
}
}
// add steps to numeric values with divider/multiplier
else {
int8_t divider = (dv.options_size == 1) ? Helpers::atoint(read_flash_string(dv.options[0]).c_str()) : 0;
char s[10];
if (divider > 0) {
obj["s"] = Helpers::render_value(s, (float)1 / divider, 1);
} else if (divider < 0) {
obj["s"] = Helpers::render_value(s, (-1) * divider, 0);
}
int16_t dv_set_min, dv_set_max;
if (dv.get_min_max(dv_set_min, dv_set_max)) {
obj["m"] = Helpers::render_value(s, dv_set_min, 0);
obj["x"] = Helpers::render_value(s, dv_set_max, 0);
}
} else if (dv.type == DeviceValueType::BOOL) {
JsonArray l = obj.createNestedArray("l");
char result[10];
l.add(Helpers::render_boolean(result, false));
l.add(Helpers::render_boolean(result, true));
}
// add command help template
else if (dv.type == DeviceValueType::STRING || dv.type == DeviceValueType::CMD) {
if (dv.options_size == 1) {
obj["h"] = dv.options[0];
}
}
// add steps to numeric values with divider/multiplier
else {
int8_t divider = (dv.options_size == 1) ? Helpers::atoint(read_flash_string(dv.options[0]).c_str()) : 0;
char s[10];
if (divider > 0) {
obj["s"] = Helpers::render_value(s, (float)1 / divider, 1);
} else if (divider < 0) {
obj["s"] = Helpers::render_value(s, (-1) * divider, 0);
}
int16_t dv_set_min, dv_set_max;
if (dv.get_min_max(dv_set_min, dv_set_max)) {
obj["m"] = Helpers::render_value(s, dv_set_min, 0);
obj["x"] = Helpers::render_value(s, dv_set_max, 0);
}
}
}
@@ -838,19 +837,22 @@ void EMSdevice::generate_values_web_all(JsonArray & output) {
obj["v"] = (divider > 0) ? time_value / divider : time_value * factor; // sometimes we need to divide by 60
}
}
} else {
// must always have v for sorting to work in web
obj["v"] = "";
}
// add name, prefixing the tag if it exists
// add name, prefixing the tag if it exists as the id (key for table sorting)
if (dv.full_name) {
if ((dv.tag == DeviceValueTAG::TAG_NONE) || tag_to_string(dv.tag).empty()) {
obj["n"] = dv.full_name;
obj["id"] = dv.full_name;
} else {
char name[50];
snprintf(name, sizeof(name), "%s %s", tag_to_string(dv.tag).c_str(), read_flash_string(dv.full_name).c_str());
obj["n"] = name;
obj["id"] = name;
}
} else {
obj["n"] = "";
obj["id"] = "";
}
// shortname

View File

@@ -432,12 +432,12 @@ void EMSESP::show_sensor_values(uuid::console::Shell & shell) {
(fahrenheit == 0) ? 'C' : 'F',
COLOR_RESET,
Helpers::render_value(s2, sensor.offset(), 10, fahrenheit),
sensor.id_str().c_str());
sensor.id().c_str());
} else {
shell.printfln(F(" %s (offset %s, ID: %s)"),
sensor.name().c_str(),
Helpers::render_value(s, sensor.offset(), 10, fahrenheit),
sensor.id_str().c_str());
sensor.id().c_str());
}
}
shell.println();

View File

@@ -1036,7 +1036,7 @@ bool System::command_customizations(const char * value, const int8_t id, JsonObj
JsonArray sensorsJson = node.createNestedArray("sensors");
for (const auto & sensor : settings.sensorCustomizations) {
JsonObject sensorJson = sensorsJson.createNestedObject();
sensorJson["id_str"] = sensor.id_str; // key, is
sensorJson["id"] = sensor.id; // key
sensorJson["name"] = sensor.name; // n
sensorJson["offset"] = sensor.offset; // o
}
@@ -1044,7 +1044,7 @@ bool System::command_customizations(const char * value, const int8_t id, JsonObj
JsonArray analogJson = node.createNestedArray("analogs");
for (const AnalogCustomization & sensor : settings.analogCustomizations) {
JsonObject sensorJson = analogJson.createNestedObject();
sensorJson["gpio"] = sensor.id;
sensorJson["gpio"] = sensor.gpio;
sensorJson["name"] = sensor.name;
if (EMSESP::system_.enum_format() == ENUM_FORMAT_INDEX) {
sensorJson["type"] = sensor.type;

View File

@@ -550,6 +550,11 @@ void Test::run_test(uuid::console::Shell & shell, const std::string & cmd, const
if (command == "dallas") {
shell.printfln(F("Testing adding Dallas sensor"));
emsesp::EMSESP::dallassensor_.test();
}
if (command == "dallas_full") {
shell.printfln(F("Testing adding and changing Dallas sensor"));
Mqtt::ha_enabled(true);
Mqtt::nested_format(1);
// Mqtt::nested_format(0);

View File

@@ -1 +1 @@
#define EMSESP_APP_VERSION "3.4.0b12"
#define EMSESP_APP_VERSION "3.4.0b12t4"

View File

@@ -61,7 +61,7 @@ void WebCustomization::read(WebCustomization & settings, JsonObject & root) {
JsonArray sensorsJson = root.createNestedArray("sensors");
for (const SensorCustomization & sensor : settings.sensorCustomizations) {
JsonObject sensorJson = sensorsJson.createNestedObject();
sensorJson["id_str"] = sensor.id_str; // is
sensorJson["id"] = sensor.id; // is
sensorJson["name"] = sensor.name; // n
sensorJson["offset"] = sensor.offset; // o
}
@@ -70,7 +70,7 @@ void WebCustomization::read(WebCustomization & settings, JsonObject & root) {
JsonArray analogJson = root.createNestedArray("analogs");
for (const AnalogCustomization & sensor : settings.analogCustomizations) {
JsonObject sensorJson = analogJson.createNestedObject();
sensorJson["id"] = sensor.id; // i
sensorJson["gpio"] = sensor.gpio; // g
sensorJson["name"] = sensor.name; // n
sensorJson["offset"] = sensor.offset; // o
sensorJson["factor"] = sensor.factor; // f
@@ -101,7 +101,7 @@ StateUpdateResult WebCustomization::update(JsonObject & root, WebCustomization &
for (const JsonObject sensorJson : root["sensors"].as<JsonArray>()) {
// create each of the sensor, overwritting any previous settings
auto sensor = SensorCustomization();
sensor.id_str = sensorJson["id_str"].as<std::string>();
sensor.id = sensorJson["id"].as<std::string>();
sensor.name = sensorJson["name"].as<std::string>();
sensor.offset = sensorJson["offset"];
settings.sensorCustomizations.push_back(sensor); // add to list
@@ -114,7 +114,7 @@ StateUpdateResult WebCustomization::update(JsonObject & root, WebCustomization &
for (const JsonObject analogJson : root["analogs"].as<JsonArray>()) {
// create each of the sensor, overwritting any previous settings
auto sensor = AnalogCustomization();
sensor.id = analogJson["id"];
sensor.gpio = analogJson["gpio"];
sensor.name = analogJson["name"].as<std::string>();
sensor.offset = analogJson["offset"];
sensor.factor = analogJson["factor"];

View File

@@ -35,14 +35,14 @@ namespace emsesp {
// Customization for dallas sensor
class SensorCustomization {
public:
std::string id_str;
std::string id;
std::string name;
uint16_t offset;
};
class AnalogCustomization {
public:
uint8_t id;
uint8_t gpio;
std::string name;
float offset;
float factor;
@@ -51,7 +51,7 @@ class AnalogCustomization {
// used for removing from a list
bool operator==(const AnalogCustomization & a) const {
return id == a.id;
return gpio == a.gpio;
}
bool operator!=(const AnalogCustomization & a) const {
return !operator==(a);

View File

@@ -76,17 +76,18 @@ void WebDataService::core_data(AsyncWebServerRequest * request) {
// list is already sorted by device type
// Ignore Contoller
JsonArray devices = root.createNestedArray("devices");
char buffer[3];
for (const auto & emsdevice : EMSESP::emsdevices) {
if (emsdevice && (emsdevice->device_type() != EMSdevice::DeviceType::CONTROLLER || emsdevice->count_entities() > 0)) {
JsonObject obj = devices.createNestedObject();
obj["i"] = emsdevice->unique_id(); // a unique id
obj["t"] = emsdevice->device_type_name(); // type
obj["b"] = emsdevice->brand_to_string(); // brand
obj["n"] = emsdevice->name(); // name
obj["d"] = emsdevice->device_id(); // deviceid
obj["p"] = emsdevice->product_id(); // productid
obj["v"] = emsdevice->version(); // version
obj["e"] = emsdevice->count_entities(); // number of entities (device values)
obj["id"] = Helpers::smallitoa(buffer, emsdevice->unique_id()); // a unique id as a string
obj["t"] = emsdevice->device_type_name(); // type
obj["b"] = emsdevice->brand_to_string(); // brand
obj["n"] = emsdevice->name(); // name
obj["d"] = emsdevice->device_id(); // deviceid
obj["p"] = emsdevice->product_id(); // productid
obj["v"] = emsdevice->version(); // version
obj["e"] = emsdevice->count_entities(); // number of entities (device values)
}
}
@@ -110,8 +111,8 @@ void WebDataService::sensor_data(AsyncWebServerRequest * request) {
if (EMSESP::dallassensor_.have_sensors()) {
for (const auto & sensor : EMSESP::dallassensor_.sensors()) {
JsonObject obj = sensors.createNestedObject();
obj["is"] = sensor.id_str(); // id
obj["n"] = sensor.name(); // name
obj["id"] = sensor.id(); // id as string
obj["n"] = sensor.name(); // name
if (EMSESP::system_.fahrenheit()) {
if (Helpers::hasValue(sensor.temperature_c)) {
obj["t"] = (float)sensor.temperature_c * 0.18 + 32;
@@ -129,14 +130,16 @@ void WebDataService::sensor_data(AsyncWebServerRequest * request) {
}
// analog sensors
// assume list is already sorted by id
JsonArray analogs = root.createNestedArray("analogs");
if (EMSESP::analog_enabled() && EMSESP::analogsensor_.have_sensors()) {
uint8_t count = 0;
char buffer[3];
for (const auto & sensor : EMSESP::analogsensor_.sensors()) {
// don't send if it's marked for removal
if (sensor.type() != AnalogSensor::AnalogType::MARK_DELETED) {
JsonObject obj = analogs.createNestedObject();
obj["i"] = sensor.id();
obj["id"] = Helpers::smallitoa(buffer, ++count); // needed for sorting table
obj["g"] = sensor.gpio();
obj["n"] = sensor.name();
obj["u"] = sensor.uom();
obj["o"] = sensor.offset();
@@ -145,6 +148,8 @@ void WebDataService::sensor_data(AsyncWebServerRequest * request) {
if (sensor.type() != AnalogSensor::AnalogType::NOTUSED) {
obj["v"] = Helpers::round2(sensor.value(), 0); // is optional and is a float
} else {
obj["v"] = 0; // must have a value for web sorting to work
}
}
}
@@ -170,6 +175,13 @@ void WebDataService::device_data(AsyncWebServerRequest * request, JsonVariant &
JsonObject output = response->getRoot();
emsdevice->generate_values_web(output);
#endif
// #ifdef EMSESP_USE_SERIAL
// #ifdef EMSESP_DEBUG
// serializeJson(output, Serial);
// #endif
// #endif
response->setLength();
request->send(response);
return;
@@ -246,8 +258,8 @@ void WebDataService::write_sensor(AsyncWebServerRequest * request, JsonVariant &
if (json.is<JsonObject>()) {
JsonObject sensor = json;
std::string id_str = sensor["id_str"]; // this is the key
std::string name = sensor["name"];
std::string id = sensor["id"]; // this is the key
std::string name = sensor["name"];
// calculate offset. We'll convert it to an int and * 10
float offset = sensor["offset"];
@@ -255,7 +267,7 @@ void WebDataService::write_sensor(AsyncWebServerRequest * request, JsonVariant &
if (EMSESP::system_.fahrenheit()) {
offset10 = offset / 0.18;
}
ok = EMSESP::dallassensor_.update(id_str, name, offset10);
ok = EMSESP::dallassensor_.update(id, name, offset10);
}
AsyncWebServerResponse * response = request->beginResponse(ok ? 200 : 204);
@@ -268,13 +280,13 @@ void WebDataService::write_analog(AsyncWebServerRequest * request, JsonVariant &
if (json.is<JsonObject>()) {
JsonObject analog = json;
uint8_t id = analog["id"]; // this is the unique key
uint8_t gpio = analog["gpio"]; // this is the unique key, the GPIO
std::string name = analog["name"];
float factor = analog["factor"];
float offset = analog["offset"];
uint8_t uom = analog["uom"];
int8_t type = analog["type"];
ok = EMSESP::analogsensor_.update(id, name, offset, factor, uom, type);
ok = EMSESP::analogsensor_.update(gpio, name, offset, factor, uom, type);
}
AsyncWebServerResponse * response = request->beginResponse(ok ? 200 : 204);

View File

@@ -129,34 +129,57 @@ void WebStatusService::webStatusService(AsyncWebServerRequest * request) {
auto * response = new AsyncJsonResponse(false, EMSESP_JSON_SIZE_MEDIUM_DYN);
JsonObject root = response->getRoot();
root["status"] = EMSESP::bus_status(); // 0, 1 or 2
root["num_devices"] = EMSESP::count_devices(); // excluding Controller
root["num_sensors"] = EMSESP::dallassensor_.no_sensors();
root["num_analogs"] = EMSESP::analogsensor_.no_sensors();
root["tx_mode"] = EMSESP::txservice_.tx_mode();
root["rx_received"] = EMSESP::rxservice_.telegram_count();
root["tx_reads"] = EMSESP::txservice_.telegram_read_count();
root["tx_writes"] = EMSESP::txservice_.telegram_write_count();
root["rx_quality"] = EMSESP::rxservice_.quality();
root["tx_read_quality"] = EMSESP::txservice_.read_quality();
root["tx_write_quality"] = EMSESP::txservice_.write_quality();
root["rx_fails"] = EMSESP::rxservice_.telegram_error_count();
root["tx_read_fails"] = EMSESP::txservice_.telegram_read_fail_count();
root["tx_write_fails"] = EMSESP::txservice_.telegram_write_fail_count();
root["sensor_fails"] = EMSESP::dallassensor_.fails();
root["sensor_reads"] = EMSESP::dallassensor_.reads();
root["sensor_quality"] = EMSESP::dallassensor_.reads() == 0 ? 100 : 100 - (uint8_t)((100 * EMSESP::dallassensor_.fails()) / EMSESP::dallassensor_.reads());
root["analog_fails"] = EMSESP::analogsensor_.fails();
root["analog_reads"] = EMSESP::analogsensor_.reads();
root["analog_quality"] = EMSESP::analogsensor_.reads() == 0 ? 100 : 100 - (uint8_t)((100 * EMSESP::analogsensor_.fails()) / EMSESP::analogsensor_.reads());
root["mqtt_fails"] = Mqtt::publish_fails();
root["mqtt_count"] = Mqtt::publish_count();
root["mqtt_quality"] = Mqtt::publish_count() == 0 ? 100 : 100 - (Mqtt::publish_fails() * 100) / (Mqtt::publish_count() + Mqtt::publish_fails());
root["api_calls"] = WebAPIService::api_count(); // + WebAPIService::api_fails();
root["api_fails"] = WebAPIService::api_fails();
root["api_quality"] =
WebAPIService::api_count() == 0 ? 100 : 100 - (WebAPIService::api_fails() * 100) / (WebAPIService::api_count() + WebAPIService::api_fails());
root["uptime"] = EMSbus::bus_uptime();
root["status"] = EMSESP::bus_status(); // 0, 1 or 2
root["tx_mode"] = EMSESP::txservice_.tx_mode();
root["uptime"] = EMSbus::bus_uptime();
root["num_devices"] = EMSESP::count_devices(); // excluding Controller
root["num_sensors"] = EMSESP::dallassensor_.no_sensors();
root["num_analogs"] = EMSESP::analogsensor_.no_sensors();
JsonArray statsJson = root.createNestedArray("stats");
JsonObject statJson;
statJson = statsJson.createNestedObject();
statJson["id"] = "EMS Telegrams Received (Rx)";
statJson["s"] = EMSESP::rxservice_.telegram_count();
statJson["f"] = EMSESP::rxservice_.telegram_error_count();
statJson["q"] = EMSESP::rxservice_.quality();
statJson = statsJson.createNestedObject();
statJson["id"] = "EMS Reads (Tx)";
statJson["s"] = EMSESP::txservice_.telegram_read_count();
statJson["f"] = EMSESP::txservice_.telegram_read_fail_count();
statJson["q"] = EMSESP::txservice_.read_quality();
statJson = statsJson.createNestedObject();
statJson["id"] = "EMS Writes (Tx)";
statJson["s"] = EMSESP::txservice_.telegram_write_count();
statJson["f"] = EMSESP::txservice_.telegram_write_fail_count();
statJson["q"] = EMSESP::txservice_.write_quality();
statJson = statsJson.createNestedObject();
statJson["id"] = "Temperature Sensor Reads";
statJson["s"] = EMSESP::dallassensor_.reads();
statJson["f"] = EMSESP::dallassensor_.fails();
statJson["q"] = EMSESP::dallassensor_.reads() == 0 ? 100 : 100 - (uint8_t)((100 * EMSESP::dallassensor_.fails()) / EMSESP::dallassensor_.reads());
statJson = statsJson.createNestedObject();
statJson["id"] = "Analog Sensor Reads";
statJson["s"] = EMSESP::analogsensor_.reads();
statJson["f"] = EMSESP::analogsensor_.fails();
statJson["q"] = EMSESP::analogsensor_.reads() == 0 ? 100 : 100 - (uint8_t)((100 * EMSESP::analogsensor_.fails()) / EMSESP::analogsensor_.reads());
statJson = statsJson.createNestedObject();
statJson["id"] = "MQTT Publishes";
statJson["s"] = Mqtt::publish_count();
statJson["f"] = Mqtt::publish_fails();
statJson["q"] = Mqtt::publish_count() == 0 ? 100 : 100 - (Mqtt::publish_fails() * 100) / (Mqtt::publish_count() + Mqtt::publish_fails());
statJson = statsJson.createNestedObject();
statJson["id"] = "API Calls";
statJson["s"] = WebAPIService::api_count(); // + WebAPIService::api_fails();
statJson["f"] = WebAPIService::api_fails();
statJson["q"] = WebAPIService::api_count() == 0 ? 100 : 100 - (WebAPIService::api_fails() * 100) / (WebAPIService::api_count() + WebAPIService::api_fails());
response->setLength();
request->send(response);