From 5c4dfcb9aead872445527b118ff5f63f0e036c3d Mon Sep 17 00:00:00 2001 From: proddy Date: Sun, 7 Jun 2026 18:26:35 +0200 Subject: [PATCH 01/44] first try --- interface/src/AuthenticatedRouting.tsx | 2 + interface/src/api/app.ts | 23 +- interface/src/app/main/Commands.tsx | 284 +++++++++++++++++ interface/src/app/main/CommandsDialog.tsx | 188 +++++++++++ interface/src/app/main/Dashboard.tsx | 2 + interface/src/app/main/DeviceIcon.tsx | 1 + interface/src/app/main/DevicesDialog.tsx | 8 +- interface/src/app/main/Scheduler.tsx | 39 +-- interface/src/app/main/SchedulerDialog.tsx | 168 ++++------ interface/src/app/main/types.ts | 27 +- interface/src/app/main/validators.ts | 19 ++ .../src/components/layout/LayoutMenu.tsx | 7 + interface/src/i18n/cz/index.ts | 8 +- interface/src/i18n/de/index.ts | 8 +- interface/src/i18n/en/index.ts | 12 +- interface/src/i18n/fr/index.ts | 8 +- interface/src/i18n/it/index.ts | 8 +- interface/src/i18n/nl/index.ts | 8 +- interface/src/i18n/no/index.ts | 8 +- interface/src/i18n/pl/index.ts | 8 +- interface/src/i18n/sk/index.ts | 8 +- interface/src/i18n/sv/index.ts | 8 +- interface/src/i18n/tr/index.ts | 8 +- mock-api/restServer.ts | 171 ++++++---- src/core/command.cpp | 6 + src/core/emsdevice.cpp | 5 + src/core/emsdevice.h | 2 + src/core/emsesp.cpp | 9 + src/core/emsesp.h | 2 + src/core/locale_translations.h | 1 + src/core/mqtt.cpp | 1 + src/core/system.cpp | 6 + src/web/WebCommandService.cpp | 292 ++++++++++++++++++ src/web/WebCommandService.h | 75 +++++ src/web/WebDataService.cpp | 42 ++- src/web/WebSchedulerService.cpp | 236 ++++---------- src/web/WebSchedulerService.h | 9 +- src/web/WebStatusService.cpp | 4 +- 38 files changed, 1282 insertions(+), 439 deletions(-) create mode 100644 interface/src/app/main/Commands.tsx create mode 100644 interface/src/app/main/CommandsDialog.tsx create mode 100644 src/web/WebCommandService.cpp create mode 100644 src/web/WebCommandService.h diff --git a/interface/src/AuthenticatedRouting.tsx b/interface/src/AuthenticatedRouting.tsx index 1bab479ae..ae4eeb1b6 100644 --- a/interface/src/AuthenticatedRouting.tsx +++ b/interface/src/AuthenticatedRouting.tsx @@ -1,6 +1,7 @@ import { memo, useContext } from 'react'; import { Navigate, Route, Routes } from 'react-router'; +import Commands from 'app/main/Commands'; import CustomEntities from 'app/main/CustomEntities'; import Customizations from 'app/main/Customizations'; import Dashboard from 'app/main/Dashboard'; @@ -65,6 +66,7 @@ const AuthenticatedRouting = memo(() => { } /> } /> + } /> } /> } /> diff --git a/interface/src/api/app.ts b/interface/src/api/app.ts index 668e61904..e352b8692 100644 --- a/interface/src/api/app.ts +++ b/interface/src/api/app.ts @@ -4,6 +4,8 @@ import type { APIcall, Action, Activity, + CommandItem, + Commands, CoreData, DashboardData, DeviceData, @@ -102,8 +104,7 @@ export const readSchedule = () => o_deleted: si.deleted, o_flags: si.flags, o_time: si.time, - o_cmd: si.cmd, - o_value: si.value, + o_cmd_name: si.cmd_name, o_name: si.name })); } @@ -111,6 +112,24 @@ export const readSchedule = () => export const writeSchedule = (data: Schedule) => alovaInstance.Post('/rest/schedule', data); +// Commands +export const readCommands = () => + alovaInstance.Get('/rest/commands', { + // @ts-expect-error - exactOptionalPropertyTypes compatibility issue + transform(data) { + const commands = (data as Commands).commands; + return commands.map((ci) => ({ + ...ci, + o_id: ci.id, + o_cmd: ci.cmd, + o_value: ci.value, + o_name: ci.name + })); + } + }); +export const writeCommands = (data: Commands) => + alovaInstance.Post('/rest/commands', data); + // Modules export const readModules = () => alovaInstance.Get('/rest/modules', { diff --git a/interface/src/app/main/Commands.tsx b/interface/src/app/main/Commands.tsx new file mode 100644 index 000000000..495d8634d --- /dev/null +++ b/interface/src/app/main/Commands.tsx @@ -0,0 +1,284 @@ +import { useEffect, useState } from 'react'; +import { useBlocker } from 'react-router'; +import { toast } from 'react-toastify'; + +import AddIcon from '@mui/icons-material/Add'; +import CancelIcon from '@mui/icons-material/Cancel'; +import WarningIcon from '@mui/icons-material/Warning'; +import { Box, Button, Typography } from '@mui/material'; + +import { + Body, + Cell, + Header, + HeaderCell, + HeaderRow, + Row, + Table +} from '@table-library/react-table-library/table'; +import { useTheme } from '@table-library/react-table-library/theme'; +import { updateState, useRequest } from 'alova/client'; +import { + BlockNavigation, + ButtonRow, + FormLoader, + SectionContent, + useLayoutTitle +} from 'components'; +import { useI18nContext } from 'i18n/i18n-react'; +import { useInterval } from 'utils'; + +import { readCommands, writeCommands } from '../../api/app'; +import CommandsDialog from './CommandsDialog'; +import type { CommandItem, Commands as CommandsType } from './types'; +import { commandItemValidation } from './validators'; + +const INTERVAL_DELAY = 30000; +const MIN_ID = -100; +const MAX_ID = 100; + +const DEFAULT_COMMAND_ITEM: Omit = { + cmd: '', + value: '', + name: '', + deleted: false +}; + +const commandsTheme = { + Table: ` + --data-table-library_grid-template-columns: repeat(1, minmax(100px, 1fr)) repeat(1, minmax(100px, 1fr)) 160px; + `, + BaseRow: ` + font-size: 14px; + .td { + height: 32px; + } + `, + BaseCell: ` + &:nth-of-type(1) { + padding: 8px; + } + `, + HeaderRow: ` + text-transform: uppercase; + background-color: black; + color: #90CAF9; + .th { + border-bottom: 1px solid #565656; + height: 36px; + } + `, + Row: ` + background-color: #1e1e1e; + position: relative; + cursor: pointer; + .td { + border-bottom: 1px solid #565656; + } + &:hover .td { + background-color: #177ac9; + } + ` +}; + +const CommandsPage = () => { + const { LL } = useI18nContext(); + const [numChanges, setNumChanges] = useState(0); + const blocker = useBlocker(numChanges !== 0); + const [selectedItem, setSelectedItem] = useState(); + const [creating, setCreating] = useState(false); + const [dialogOpen, setDialogOpen] = useState(false); + + useLayoutTitle(LL.COMMANDS()); + + const { + data: commands, + send: fetchCommands, + error + } = useRequest(readCommands, { + initialData: [] + }); + + const { send: updateCommands } = useRequest( + (data: CommandsType) => writeCommands(data), + { immediate: false } + ); + + const hasChanged = (ci: CommandItem) => + ci.id !== ci.o_id || + (ci.name || '') !== (ci.o_name || '') || + ci.cmd !== ci.o_cmd || + ci.value !== ci.o_value || + ci.deleted !== ci.o_deleted; + + useInterval(() => { + if (numChanges === 0) { + void fetchCommands(); + } + }, INTERVAL_DELAY); + + const theme = useTheme(commandsTheme); + + const saveCommands = async () => { + try { + await updateCommands({ + commands: commands + .filter((ci: CommandItem) => !ci.deleted) + .map((ci: CommandItem) => ({ + id: ci.id, + cmd: ci.cmd, + value: ci.value, + name: ci.name + })) + }); + toast.success(LL.UPDATED_OF(LL.COMMANDS(1))); + } catch (error: unknown) { + const message = error instanceof Error ? error.message : String(error); + toast.error(message); + } finally { + await fetchCommands(); + setNumChanges(0); + } + }; + + const editItem = (ci: CommandItem) => { + setCreating(false); + setSelectedItem(ci); + setDialogOpen(true); + if (ci.o_name === undefined) { + ci.o_name = ci.name; + } + }; + + const onDialogClose = () => { + setDialogOpen(false); + }; + + const onDialogCancel = async () => { + await fetchCommands().then(() => { + setNumChanges(0); + }); + }; + + const onDialogSave = (updatedItem: CommandItem) => { + setDialogOpen(false); + void updateState(readCommands(), (data: CommandItem[]) => { + const new_data = creating + ? [...data, updatedItem] + : data.map((ci) => + ci.id === updatedItem.id ? { ...ci, ...updatedItem } : ci + ); + setNumChanges(new_data.filter((ci) => hasChanged(ci)).length); + return new_data; + }); + }; + + const addItem = () => { + setCreating(true); + const newItem: CommandItem = { + id: Math.floor(Math.random() * (MAX_ID - MIN_ID) + MIN_ID), + ...DEFAULT_COMMAND_ITEM + }; + setSelectedItem(newItem); + setDialogOpen(true); + }; + + const filteredCommands = commands.filter((ci: CommandItem) => !ci.deleted); + + const renderCommands = () => { + if (!commands) { + return ( + + ); + } + + return ( + + {(tableList: CommandItem[]) => ( + <> +
+ + {LL.COMMAND(0)} + {LL.VALUE(0)} + {LL.NAME(0)} + +
+ + {tableList.map((ci: CommandItem) => ( + editItem(ci)}> + {ci.cmd} + {ci.value} + {ci.name} + + ))} + + + )} +
+ ); + }; + + return ( + + {blocker ? : null} + + {LL.COMMANDS_HELP_1()}. + + {renderCommands()} + + {selectedItem && ( + + )} + + + + {numChanges !== 0 && ( + + + + + )} + + + + + + + + + ); +}; + +export default CommandsPage; diff --git a/interface/src/app/main/CommandsDialog.tsx b/interface/src/app/main/CommandsDialog.tsx new file mode 100644 index 000000000..1d71995cc --- /dev/null +++ b/interface/src/app/main/CommandsDialog.tsx @@ -0,0 +1,188 @@ +import { useEffect, useState } from 'react'; +import { toast } from 'react-toastify'; + +import AddIcon from '@mui/icons-material/Add'; +import CancelIcon from '@mui/icons-material/Cancel'; +import DoneIcon from '@mui/icons-material/Done'; +import PlayArrowIcon from '@mui/icons-material/PlayArrow'; +import RemoveIcon from '@mui/icons-material/RemoveCircleOutlined'; +import { + Box, + Button, + Dialog, + DialogActions, + DialogContent, + DialogTitle, + TextField +} from '@mui/material'; + +import { callAction } from '@/api/app'; +import { dialogStyle } from 'CustomTheme'; +import { useRequest } from 'alova/client'; +import type Schema from 'async-validator'; +import type { ValidateFieldsError } from 'async-validator'; +import { ValidatedTextField } from 'components'; +import { useI18nContext } from 'i18n/i18n-react'; +import { updateValue } from 'utils'; +import { ValidationError, validate } from 'validators'; + +import type { CommandItem } from './types'; + +interface CommandsDialogProps { + open: boolean; + creating: boolean; + onClose: () => void; + onSave: (ci: CommandItem) => void; + selectedItem: CommandItem; + validator: Schema; +} + +const CommandsDialog = ({ + open, + creating, + onClose, + onSave, + selectedItem, + validator +}: CommandsDialogProps) => { + const { LL } = useI18nContext(); + const [editItem, setEditItem] = useState(selectedItem); + const [fieldErrors, setFieldErrors] = useState(); + + const updateFormValue = updateValue( + setEditItem as unknown as React.Dispatch< + React.SetStateAction> + > + ); + + useEffect(() => { + if (open) { + setFieldErrors(undefined); + setEditItem(selectedItem); + } + }, [open, selectedItem]); + + const handleSave = async (itemToSave: CommandItem) => { + try { + setFieldErrors(undefined); + await validate(validator, itemToSave); + onSave(itemToSave); + } catch (error) { + setFieldErrors((error as ValidationError).fieldErrors); + } + }; + + const save = async () => { + await handleSave(editItem); + }; + + const { send: executeCommand } = useRequest( + (id: string) => callAction({ action: 'executeCommand', param: id }), + { immediate: false } + ) + .onSuccess(() => { + toast.success(LL.EXECUTE_COMMAND_SENT()); + }) + .onError((error) => { + toast.error(String(error.error?.message || 'An error occurred')); + }); + + const execute = async () => { + await executeCommand(editItem.name); + }; + + const remove = () => { + onSave({ ...editItem, deleted: true }); + }; + + const handleClose = ( + _event: React.SyntheticEvent, + reason: 'backdropClick' | 'escapeKeyDown' + ) => { + if (reason !== 'backdropClick') { + onClose(); + } + }; + + return ( + + + {creating ? `${LL.ADD(1)} ${LL.NEW(0)}` : LL.EDIT()}  + {LL.COMMAND(1)} + + + + + + + + + {!creating && ( + + + + )} + + + {!creating && editItem.cmd !== '' && ( + + )} + + + ); +}; + +export default CommandsDialog; diff --git a/interface/src/app/main/Dashboard.tsx b/interface/src/app/main/Dashboard.tsx index f404ed3f7..e90cbca19 100644 --- a/interface/src/app/main/Dashboard.tsx +++ b/interface/src/app/main/Dashboard.tsx @@ -180,6 +180,8 @@ const Dashboard = memo(() => { return LL.ANALOG_SENSORS(); case DeviceType.TEMPERATURESENSOR: return LL.TEMP_SENSORS(); + case DeviceType.COMMAND: + return LL.COMMANDS(); case DeviceType.SCHEDULER: return LL.SCHEDULER(); default: diff --git a/interface/src/app/main/DeviceIcon.tsx b/interface/src/app/main/DeviceIcon.tsx index 79207ff37..1266e9b55 100644 --- a/interface/src/app/main/DeviceIcon.tsx +++ b/interface/src/app/main/DeviceIcon.tsx @@ -38,6 +38,7 @@ const deviceIconLookup: Record = { [DeviceType.CUSTOM]: MdPlaylistAdd, [DeviceType.UNKNOWN]: MdOutlineSensors, [DeviceType.SYSTEM]: null, + [DeviceType.COMMAND]: MdPlaylistAdd, [DeviceType.SCHEDULER]: MdMoreTime, [DeviceType.GENERIC]: MdOutlineSensors, [DeviceType.VENTILATION]: PiFan diff --git a/interface/src/app/main/DevicesDialog.tsx b/interface/src/app/main/DevicesDialog.tsx index ce0526292..314476024 100644 --- a/interface/src/app/main/DevicesDialog.tsx +++ b/interface/src/app/main/DevicesDialog.tsx @@ -64,12 +64,12 @@ const DevicesDialog = ({ } }, [open, selectedItem]); - const { send: executeSchedule } = useRequest( - (id: string) => callAction({ action: 'executeSchedule', param: id }), + const { send: executeCommand } = useRequest( + (id: string) => callAction({ action: 'executeCommand', param: id }), { immediate: false } ) .onSuccess(() => { - toast.success(LL.EXECUTE_SCHEDULE_SENT()); + toast.success(LL.EXECUTE_COMMAND_SENT()); }) .onError((error) => { toast.error(String(error.error?.message || 'An error occurred')); @@ -79,7 +79,7 @@ const DevicesDialog = ({ try { setFieldErrors(undefined); if (editItem.v === undefined && editItem.c !== undefined) { - await executeSchedule(editItem.c); + await executeCommand(editItem.c); } else { await validate(validator, editItem); } diff --git a/interface/src/app/main/Scheduler.tsx b/interface/src/app/main/Scheduler.tsx index 1bb612854..e30a54e89 100644 --- a/interface/src/app/main/Scheduler.tsx +++ b/interface/src/app/main/Scheduler.tsx @@ -29,7 +29,7 @@ import { import { useI18nContext } from 'i18n/i18n-react'; import { useInterval } from 'utils'; -import { readSchedule, writeSchedule } from '../../api/app'; +import { readCommands, readSchedule, writeSchedule } from '../../api/app'; import SettingsSchedulerDialog from './SchedulerDialog'; import { ScheduleFlag } from './types'; import type { Schedule, ScheduleItem } from './types'; @@ -54,14 +54,13 @@ const DEFAULT_SCHEDULE_ITEM: Omit = { deleted: false, flags: FLAG_ALL_DAYS, time: '', - cmd: '', - value: '', + cmd_name: '', name: '' }; const scheduleTheme = { Table: ` - --data-table-library_grid-template-columns: 36px 210px 100px 192px repeat(1, minmax(100px, 1fr)) 160px; + --data-table-library_grid-template-columns: 36px 220px repeat(1, minmax(20px, 1fr)) 192px 160px; `, BaseRow: ` font-size: 14px; @@ -70,11 +69,8 @@ const scheduleTheme = { } `, BaseCell: ` - &:nth-of-type(2) { - text-align: center; - } &:nth-of-type(1) { - text-align: center; + text-align: 8px; } `, HeaderRow: ` @@ -100,7 +96,6 @@ const scheduleTheme = { }; const scheduleTypeLabels: Record = { - [ScheduleFlag.SCHEDULE_IMMEDIATE]: 'Immediate', [ScheduleFlag.SCHEDULE_TIMER]: 'Timer', [ScheduleFlag.SCHEDULE_CONDITION]: 'Condition', [ScheduleFlag.SCHEDULE_ONCHANGE]: 'On Change' @@ -125,6 +120,11 @@ const Scheduler = () => { initialData: [] }); + const { data: commandNames } = useRequest(readCommands, { + initialData: [], + initializing: true + }); + const { send: updateSchedule } = useRequest( (data: Schedule) => writeSchedule(data), { @@ -140,8 +140,7 @@ const Scheduler = () => { si.deleted !== si.o_deleted || si.flags !== si.o_flags || si.time !== si.o_time || - si.cmd !== si.o_cmd || - si.value !== si.o_value + si.cmd_name !== si.o_cmd_name ); }; @@ -177,8 +176,7 @@ const Scheduler = () => { active: condensed_si.active, flags: condensed_si.flags, time: condensed_si.time, - cmd: condensed_si.cmd, - value: condensed_si.value, + cmd_name: condensed_si.cmd_name, name: condensed_si.name })) }); @@ -289,7 +287,6 @@ const Scheduler = () => { {LL.SCHEDULE(0)} {LL.TIME(0)}/Cond. {LL.COMMAND(0)} - {LL.VALUE(0)} {LL.NAME(0)} @@ -297,12 +294,10 @@ const Scheduler = () => { {tableList.map((si: ScheduleItem) => ( editScheduleItem(si)}> - {si.flags !== ScheduleFlag.SCHEDULE_IMMEDIATE && ( - - )} + @@ -322,8 +317,7 @@ const Scheduler = () => { {si.time} - {si.cmd} - {si.value} + {si.cmd_name} {si.name} ))} @@ -351,6 +345,7 @@ const Scheduler = () => { selectedItem={selectedScheduleItem} validator={schedulerItemValidation(schedule, selectedScheduleItem)} dow={dow} + commandNames={commandNames.map((ci) => ci.name)} /> )} diff --git a/interface/src/app/main/SchedulerDialog.tsx b/interface/src/app/main/SchedulerDialog.tsx index 8e1be27b5..bd124b9eb 100644 --- a/interface/src/app/main/SchedulerDialog.tsx +++ b/interface/src/app/main/SchedulerDialog.tsx @@ -1,10 +1,8 @@ import { useEffect, useState } from 'react'; -import { toast } from 'react-toastify'; import AddIcon from '@mui/icons-material/Add'; import CancelIcon from '@mui/icons-material/Cancel'; import DoneIcon from '@mui/icons-material/Done'; -import PlayArrowIcon from '@mui/icons-material/PlayArrow'; import RemoveIcon from '@mui/icons-material/RemoveCircleOutlined'; import { Box, @@ -15,15 +13,14 @@ import { DialogContent, DialogTitle, Grid, + MenuItem, TextField, ToggleButton, ToggleButtonGroup, Typography } from '@mui/material'; -import { callAction } from '@/api/app'; import { dialogStyle } from 'CustomTheme'; -import { useRequest } from 'alova/client'; import type Schema from 'async-validator'; import type { ValidateFieldsError } from 'async-validator'; import { BlockFormControlLabel, ValidatedTextField } from 'components'; @@ -77,6 +74,7 @@ interface SchedulerDialogProps { selectedItem: ScheduleItem; validator: Schema; dow: string[]; + commandNames: string[]; } const SchedulerDialog = ({ @@ -86,7 +84,8 @@ const SchedulerDialog = ({ onSave, selectedItem, validator, - dow + dow, + commandNames }: SchedulerDialogProps) => { const { LL } = useI18nContext(); const [editItem, setEditItem] = useState(selectedItem); @@ -103,12 +102,6 @@ const SchedulerDialog = ({ if (open) { setFieldErrors(undefined); setEditItem(selectedItem); - // Set the flags based on type when page is loaded: - // 0-127 is day schedule - // 128 is timer - // 129 is on change - // 130 is on condition - // 132 is immediate setScheduleType( selectedItem.flags <= SCHEDULE_TYPE_THRESHOLD ? ScheduleFlag.SCHEDULE_DAY @@ -131,21 +124,6 @@ const SchedulerDialog = ({ await handleSave(editItem); }; - const { send: executeSchedule } = useRequest( - (id: string) => callAction({ action: 'executeSchedule', param: id }), - { immediate: false } - ) - .onSuccess(() => { - toast.success(LL.EXECUTE_SCHEDULE_SENT()); - }) - .onError((error) => { - toast.error(String(error.error?.message || 'An error occurred')); - }); - - const execute = async () => { - await executeSchedule(editItem.name); - }; - const remove = () => { onSave({ ...editItem, deleted: true }); }; @@ -197,7 +175,6 @@ const SchedulerDialog = ({ const isDaySchedule = scheduleType === ScheduleFlag.SCHEDULE_DAY; const isTimerSchedule = scheduleType === ScheduleFlag.SCHEDULE_TIMER; - const isImmediateSchedule = scheduleType === ScheduleFlag.SCHEDULE_IMMEDIATE; const needsTimeField = isDaySchedule || isTimerSchedule; const dowFlags = getFlagDOWstring(editItem.flags); @@ -214,7 +191,6 @@ const SchedulerDialog = ({ if (scheduleType === ScheduleFlag.SCHEDULE_TIMER) return LL.TIMER(1); if (scheduleType === ScheduleFlag.SCHEDULE_CONDITION) return LL.CONDITION(); if (scheduleType === ScheduleFlag.SCHEDULE_ONCHANGE) return LL.ONCHANGE(); - if (scheduleType === ScheduleFlag.SCHEDULE_IMMEDIATE) return LL.IMMEDIATE(); return LL.TIME(1); })(); @@ -269,14 +245,6 @@ const SchedulerDialog = ({ {LL.CONDITION()} - - - {LL.IMMEDIATE()} - - {isDaySchedule && ( @@ -294,74 +262,66 @@ const SchedulerDialog = ({ )} - {!isImmediateSchedule && ( - <> - - - } - label={LL.ACTIVE()} + + - - - {needsTimeField ? ( - <> - - {isTimerSchedule && ( - - {LL.SCHEDULER_HELP_2()} - - )} - - ) : ( - + } + label={LL.ACTIVE()} + /> + + + {needsTimeField ? ( + <> + + {isTimerSchedule && ( + + {LL.SCHEDULER_HELP_2()} + )} - - - )} - + + ) : ( + + )} + + > + {commandNames.map((name) => ( + + {name} + + ))} + {creating ? LL.ADD(0) : LL.UPDATE()} - {isImmediateSchedule && !creating && editItem.cmd !== '' && ( - - )} ); diff --git a/interface/src/app/main/types.ts b/interface/src/app/main/types.ts index 391c22a01..137078120 100644 --- a/interface/src/app/main/types.ts +++ b/interface/src/app/main/types.ts @@ -354,16 +354,14 @@ export interface ScheduleItem { deleted?: boolean; flags: number; time: string; // also used for Condition and On Change - cmd: string; - value: string; + cmd_name: string; // references a named Command name: string; o_id?: number; o_active?: boolean; o_deleted?: boolean; o_flags?: number; o_time?: string; - o_cmd?: string; - o_value?: string; + o_cmd_name?: string; o_name?: string; } @@ -371,6 +369,23 @@ export interface Schedule { readonly schedule: readonly ScheduleItem[]; } +export interface CommandItem { + id: number; + cmd: string; + value: string; + name: string; + deleted?: boolean; + o_id?: number; + o_cmd?: string; + o_value?: string; + o_name?: string; + o_deleted?: boolean; +} + +export interface Commands { + readonly commands: readonly CommandItem[]; +} + export interface ModuleItem { id: number; // unique index key: string; @@ -401,8 +416,7 @@ export enum ScheduleFlag { SCHEDULE_DAY = 0, // no bits set SCHEDULE_TIMER = 128, // bit 8 SCHEDULE_ONCHANGE = 129, // bit 1 - SCHEDULE_CONDITION = 130, // bit 2 - SCHEDULE_IMMEDIATE = 132 // bit 3 + SCHEDULE_CONDITION = 130 // bit 2 } export interface EntityItem { @@ -445,6 +459,7 @@ export const enum DeviceType { ANALOGSENSOR = 2, SCHEDULER = 3, CUSTOM = 4, + COMMAND = 5, BOILER, THERMOSTAT, MIXER, diff --git a/interface/src/app/main/validators.ts b/interface/src/app/main/validators.ts index 0c87821ea..4bef5f07f 100644 --- a/interface/src/app/main/validators.ts +++ b/interface/src/app/main/validators.ts @@ -4,6 +4,7 @@ import { IP_OR_HOSTNAME_VALIDATOR } from 'validators/shared'; import type { AnalogSensor, + CommandItem, DeviceValue, EntityItem, ScheduleItem, @@ -237,6 +238,24 @@ export const schedulerItemValidation = ( NAME_PATTERN_REQUIRED, uniqueNameValidator(schedule, scheduleItem.o_name) ], + cmd_name: [ + { required: true, message: 'Command is required' } + ] + }); + +export const uniqueCommandNameValidator = (commands: CommandItem[], o_name?: string) => + createUniqueNameValidator(commands, o_name); + +export const commandItemValidation = ( + commands: CommandItem[], + commandItem: CommandItem +) => + new Schema({ + name: [ + { required: true, message: 'Name is required' }, + NAME_PATTERN_REQUIRED, + uniqueCommandNameValidator(commands, commandItem.o_name) + ], cmd: [ { required: true, message: 'Command is required' }, { diff --git a/interface/src/components/layout/LayoutMenu.tsx b/interface/src/components/layout/LayoutMenu.tsx index 5d52921a6..090dadf4c 100644 --- a/interface/src/components/layout/LayoutMenu.tsx +++ b/interface/src/components/layout/LayoutMenu.tsx @@ -7,6 +7,7 @@ import ConstructionIcon from '@mui/icons-material/Construction'; import KeyboardArrowDown from '@mui/icons-material/KeyboardArrowDown'; import LiveHelpIcon from '@mui/icons-material/LiveHelp'; import MoreTimeIcon from '@mui/icons-material/MoreTime'; +import PlaylistPlayIcon from '@mui/icons-material/PlaylistPlay'; import PlaylistAddIcon from '@mui/icons-material/PlaylistAdd'; import SensorsIcon from '@mui/icons-material/Sensors'; import SettingsIcon from '@mui/icons-material/Settings'; @@ -80,6 +81,12 @@ const LayoutMenuComponent = () => { disabled={!me.admin} to={`/customizations`} /> + item.name); + const namedSchedules = emsesp_schedule.schedule.filter((item: any) => item.name); if (namedSchedules.length > 0) { - const scheduler_data = namedSchedules.map((item, index) => ({ + const scheduler_data = namedSchedules.map((item: any, index: number) => ({ id: DeviceTypeUniqueID.SCHEDULER_UID * 100 + index, dv: { id: '00' + item.name, c: item.name, - ...(item.flags === ScheduleFlag.SCHEDULE_IMMEDIATE - ? {} - : { - v: item.active ? 'on' : 'off', - l: ['off', 'on'] - }) + v: item.active ? 'on' : 'off', + l: ['off', 'on'] } })); dashboard_object = { @@ -4788,6 +4814,24 @@ router }; dashboard_nodes.push(dashboard_object); } + + // add the command items (executable from dashboard) + const namedCommands = emsesp_commands.commands.filter((item: any) => item.name); + if (namedCommands.length > 0) { + const command_data = namedCommands.map((item: any, index: number) => ({ + id: DeviceTypeUniqueID.COMMAND_UID * 100 + index, + dv: { + id: '00' + item.name, + c: item.name + } + })); + dashboard_object = { + id: DeviceTypeUniqueID.COMMAND_UID, + t: DeviceType.COMMAND, + nodes: command_data + }; + dashboard_nodes.push(dashboard_object); + } } else { // for testing only // add the custom entity data @@ -4877,6 +4921,15 @@ router return status(200); }) + // Commands + .post(EMSESP_COMMANDS_ENDPOINT, async (request: any) => { + const content = await request.json(); + emsesp_commands = content; + console.log('commands saved', emsesp_commands); + return status(200); + }) + .get(EMSESP_COMMANDS_ENDPOINT, () => emsesp_commands) + // Scheduler .post(EMSESP_SCHEDULE_ENDPOINT, async (request: any) => { const content = await request.json(); @@ -4977,15 +5030,17 @@ router } if (id === DeviceTypeUniqueID.SCHEDULER_UID) { // toggle scheduler - // find the schedule in emsesp_schedule via the name and toggle the active const objIndex = emsesp_schedule.schedule.findIndex( - (obj) => obj.name === command + (obj: any) => obj.name === command ); if (objIndex !== -1) { emsesp_schedule.schedule[objIndex].active = value; console.log("Toggle schedule '" + command + "' to " + value); } } + if (id === DeviceTypeUniqueID.COMMAND_UID) { + console.log("Execute command '" + command + "'"); + } // await delay(1000); // wait to show spinner // console.log( @@ -5246,9 +5301,9 @@ router } else if (action === 'upgradeImportantMessages') { // check upgrade important messages return upgradeImportantMessages(content.param); - } else if (action === 'executeSchedule') { - // execute schedule - return executeSchedule(content.param); + } else if (action === 'executeCommand') { + // execute command + return executeCommand(content.param); } } return status(404); // cmd not found diff --git a/src/core/command.cpp b/src/core/command.cpp index 39cc17c1a..264509dfb 100644 --- a/src/core/command.cpp +++ b/src/core/command.cpp @@ -716,6 +716,10 @@ bool Command::device_has_commands(const uint8_t device_type) { return true; } + if (device_type == EMSdevice::DeviceType::COMMAND) { + return true; + } + if (device_type == EMSdevice::DeviceType::CUSTOM) { return true; } @@ -741,6 +745,7 @@ bool Command::device_has_commands(const uint8_t device_type) { void Command::show_devices(uuid::console::Shell & shell) { shell.printf("%s ", EMSdevice::device_type_2_device_name(EMSdevice::DeviceType::SYSTEM)); shell.printf("%s ", EMSdevice::device_type_2_device_name(EMSdevice::DeviceType::CUSTOM)); + shell.printf("%s ", EMSdevice::device_type_2_device_name(EMSdevice::DeviceType::COMMAND)); shell.printf("%s ", EMSdevice::device_type_2_device_name(EMSdevice::DeviceType::SCHEDULER)); if (EMSESP::sensor_enabled()) { shell.printf("%s ", EMSdevice::device_type_2_device_name(EMSdevice::DeviceType::TEMPERATURESENSOR)); @@ -779,6 +784,7 @@ void Command::show_all(uuid::console::Shell & shell) { // show system ones first show(shell, EMSdevice::DeviceType::SYSTEM, true); show(shell, EMSdevice::DeviceType::CUSTOM, true); + show(shell, EMSdevice::DeviceType::COMMAND, true); show(shell, EMSdevice::DeviceType::SCHEDULER, true); // then sensors diff --git a/src/core/emsdevice.cpp b/src/core/emsdevice.cpp index 8b7ed7c11..41a83ecb8 100644 --- a/src/core/emsdevice.cpp +++ b/src/core/emsdevice.cpp @@ -145,6 +145,8 @@ const char * EMSdevice::device_type_2_device_name(const uint8_t device_type) { return F_(scheduler); case DeviceType::CUSTOM: return F_(custom); + case DeviceType::COMMAND: + return F_(commands); case DeviceType::BOILER: return F_(boiler); case DeviceType::THERMOSTAT: @@ -297,6 +299,9 @@ uint8_t EMSdevice::device_name_2_device_type(const char * topic) { if (!strcmp(lowtopic, F_(scheduler))) { return DeviceType::SCHEDULER; } + if (!strcmp(lowtopic, F_(commands))) { + return DeviceType::COMMAND; + } if (!strcmp(lowtopic, F_(system))) { return DeviceType::SYSTEM; } diff --git a/src/core/emsdevice.h b/src/core/emsdevice.h index 44e781f88..93a0595f9 100644 --- a/src/core/emsdevice.h +++ b/src/core/emsdevice.h @@ -405,6 +405,7 @@ class EMSdevice { // Unique Identifiers for each Device type, used in Dashboard table // 100 and above is reserved for DeviceType enum DeviceTypeUniqueID : uint8_t { + COMMAND_UID = 95, SCHEDULER_UID = 96, ANALOGSENSOR_UID = 97, TEMPERATURESENSOR_UID = 98, @@ -417,6 +418,7 @@ class EMSdevice { ANALOGSENSOR, // for internal analog sensors SCHEDULER, // for internal schedule CUSTOM, // for user defined entities + COMMAND, // for user defined commands BOILER, // from here on enum the ems-devices THERMOSTAT, MIXER, diff --git a/src/core/emsesp.cpp b/src/core/emsesp.cpp index 202bf3d59..e49c07b00 100644 --- a/src/core/emsesp.cpp +++ b/src/core/emsesp.cpp @@ -56,6 +56,7 @@ ESP32React EMSESP::esp32React(&webServer, &dummyFS); WebSettingsService EMSESP::webSettingsService = WebSettingsService(&webServer, &dummyFS, EMSESP::esp32React.getSecurityManager()); WebCustomizationService EMSESP::webCustomizationService = WebCustomizationService(&webServer, &dummyFS, EMSESP::esp32React.getSecurityManager()); WebSchedulerService EMSESP::webSchedulerService = WebSchedulerService(&webServer, &dummyFS, EMSESP::esp32React.getSecurityManager()); +WebCommandService EMSESP::webCommandService = WebCommandService(&webServer, &dummyFS, EMSESP::esp32React.getSecurityManager()); WebCustomEntityService EMSESP::webCustomEntityService = WebCustomEntityService(&webServer, &dummyFS, EMSESP::esp32React.getSecurityManager()); WebModulesService EMSESP::webModulesService = WebModulesService(&webServer, &dummyFS, EMSESP::esp32React.getSecurityManager()); #else @@ -63,6 +64,7 @@ ESP32React EMSESP::esp32React(&webServer, &LittleFS); WebSettingsService EMSESP::webSettingsService = WebSettingsService(&webServer, &LittleFS, EMSESP::esp32React.getSecurityManager()); WebCustomizationService EMSESP::webCustomizationService = WebCustomizationService(&webServer, &LittleFS, EMSESP::esp32React.getSecurityManager()); WebSchedulerService EMSESP::webSchedulerService = WebSchedulerService(&webServer, &LittleFS, EMSESP::esp32React.getSecurityManager()); +WebCommandService EMSESP::webCommandService = WebCommandService(&webServer, &LittleFS, EMSESP::esp32React.getSecurityManager()); WebCustomEntityService EMSESP::webCustomEntityService = WebCustomEntityService(&webServer, &LittleFS, EMSESP::esp32React.getSecurityManager()); WebModulesService EMSESP::webModulesService = WebModulesService(&webServer, &LittleFS, EMSESP::esp32React.getSecurityManager()); #endif @@ -682,6 +684,7 @@ void EMSESP::publish_other_values() { // publish_device_values(EMSdevice::DeviceType::GENERIC); webSchedulerService.publish(); + webCommandService.publish(); webCustomEntityService.publish(); } @@ -788,6 +791,11 @@ bool EMSESP::get_device_value_info(JsonObject root, const char * cmd, const int8 return webSchedulerService.get_value_info(root, cmd); } + // commands + if (devicetype == DeviceType::COMMAND) { + return webCommandService.get_value_info(root, cmd); + } + // custom entities if (devicetype == DeviceType::CUSTOM) { return webCustomEntityService.get_value_info(root, cmd); @@ -1761,6 +1769,7 @@ void EMSESP::start() { // this will also handle any MQTT subscriptions webCustomizationService.begin(); // load the customizations webSchedulerService.begin(); // load the scheduler events + webCommandService.begin(); // load the user commands webCustomEntityService.begin(); // load the custom telegram reads // perform any system upgrades diff --git a/src/core/emsesp.h b/src/core/emsesp.h index 920f16309..5ec896b9b 100644 --- a/src/core/emsesp.h +++ b/src/core/emsesp.h @@ -51,6 +51,7 @@ #include "../web/WebSettingsService.h" #include "../web/WebCustomizationService.h" #include "../web/WebSchedulerService.h" +#include "../web/WebCommandService.h" #include "../web/WebAPIService.h" #include "../web/WebLogService.h" #include "../web/WebCustomEntityService.h" @@ -260,6 +261,7 @@ class EMSESP { static WebLogService webLogService; static WebCustomizationService webCustomizationService; static WebSchedulerService webSchedulerService; + static WebCommandService webCommandService; static WebCustomEntityService webCustomEntityService; static WebModulesService webModulesService; diff --git a/src/core/locale_translations.h b/src/core/locale_translations.h index 06e397e7a..db34b25f5 100644 --- a/src/core/locale_translations.h +++ b/src/core/locale_translations.h @@ -76,6 +76,7 @@ MAKE_WORD_TRANSLATION(watch_cmd, "watch incoming telegrams", "Beobachte eingehen MAKE_WORD_TRANSLATION(publish_cmd, "publish all to MQTT", "Publiziere MQTT", "publiceer alles naar MQTT", "publicera allt till MQTT", "opublikuj wszystko na MQTT", "Publiser alt til MQTT", "publier tout vers MQTT", "Hepsini MQTTye gönder", "pubblica tutto su MQTT", "zverejniť všetko na MQTT", "publikovat vše do MQTT") MAKE_WORD_TRANSLATION(system_info_cmd, "show system info", "Zeige Systeminformationen", "toon systeemstatus", "visa systeminformation", "pokaż status systemu", "vis system status", "afficher les informations système", "Sistem Durumunu Göster", "visualizza stati di sistema", "zobraziť stav systému", "zobrazit informace o systému") MAKE_WORD_TRANSLATION(schedule_cmd, "enable schedule item", "Aktiviere Zeitplanelemente", "activeer tijdschema item", "aktivera schemalagt objekt", "aktywuj wybrany harmonogram", "aktiver planlagt element", "activer élément programmé", "program öğesini etkinleştir", "abilitare l'elemento programmato", "povoliť položku plánovania", "povolit položku plánování") +MAKE_WORD_TRANSLATION(command_cmd, "execute command", "Befehl ausführen", "opdracht uitvoeren", "kör kommando", "wykonaj polecenie", "kjør kommando", "exécuter commande", "komut çalıştır", "esegui comando", "vykonať príkaz", "provést příkaz") MAKE_WORD_TRANSLATION(entity_cmd, "set custom value", "Sende eigene Entitäten", "verstuur custom waarde", "sätt ett eget värde", "wyślij własną wartość", "sett egendefinert verdi", "définir valeur personnalisée", "özel değer ayarla", "imposta valori personalizzati", "nastaviť vlastnú hodnotu", "nastavit vlastní hodnotu") MAKE_WORD_TRANSLATION(commands_response, "get response", "Hole Antwort", "Verzoek om antwoord", "hämta svar", "uzyskaj odpowiedź", "få svar", "obtenir réponse", "yanıt al", "ottieni risposta", "získať odpoveď", "získat odpověď") MAKE_WORD_TRANSLATION(coldshot_cmd, "send a cold shot of water", "Zugabe einer Menge kalten Wassers", "stuur koud water", "sckicka en liten mängd kallvatten", "uruchom tryśnięcie zimnej wody", "send kaldtvannspuls", "envoyer de l'eau froide", "soğuk su gönder", "invia acqua fredda", "pošlite studenú dávku vody", "poslat studenou vodu") diff --git a/src/core/mqtt.cpp b/src/core/mqtt.cpp index 44e9c85cc..25113bfdb 100644 --- a/src/core/mqtt.cpp +++ b/src/core/mqtt.cpp @@ -510,6 +510,7 @@ void Mqtt::on_connect() { // send initial MQTT messages for some of our services EMSESP::system_.send_heartbeat(); // send heartbeat EMSESP::webCustomEntityService.publish(true); + EMSESP::webCommandService.publish(true); EMSESP::webSchedulerService.publish(true); EMSESP::analogsensor_.publish_values(true); EMSESP::temperaturesensor_.publish_values(true); diff --git a/src/core/system.cpp b/src/core/system.cpp index 3190fc77e..2815fa28d 100644 --- a/src/core/system.cpp +++ b/src/core/system.cpp @@ -2610,6 +2610,12 @@ bool System::command_info(const char * value, const int8_t id, JsonObject output obj["name"] = F_(scheduler); obj["entities"] = EMSESP::webSchedulerService.count_entities(); } + if (EMSESP::webCommandService.count_entities()) { + JsonObject obj = devices.add(); + obj["type"] = F_(commands); + obj["name"] = F_(commands); + obj["entities"] = EMSESP::webCommandService.count_entities(); + } if (EMSESP::webCustomEntityService.count_entities()) { JsonObject obj = devices.add(); obj["type"] = F_(custom); diff --git a/src/web/WebCommandService.cpp b/src/web/WebCommandService.cpp new file mode 100644 index 000000000..cf841c188 --- /dev/null +++ b/src/web/WebCommandService.cpp @@ -0,0 +1,292 @@ +/* + * EMS-ESP - https://github.com/emsesp/EMS-ESP + * Copyright 2020-2025 emsesp.org + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "emsesp.h" +#include "WebCommandService.h" + +#include "shuntingYard.h" + +namespace emsesp { + +WebCommandService::WebCommandService(AsyncWebServer * server, FS * fs, SecurityManager * securityManager) + : _httpEndpoint(WebCommands::read, WebCommands::update, this, server, EMSESP_COMMAND_SERVICE_PATH, securityManager, AuthenticationPredicates::IS_AUTHENTICATED) + , _fsPersistence(WebCommands::read, WebCommands::update, this, fs, EMSESP_COMMAND_FILE) { +} + +void WebCommandService::begin() { + _fsPersistence.readFromFS(); + + EMSESP::webCommandService.read([&](WebCommands & webCommands) { commandItems_ = &webCommands.commandItems; }); + + EMSESP::logger().info("Starting Commands service"); + char topic[Mqtt::MQTT_TOPIC_MAX_SIZE]; + snprintf(topic, sizeof(topic), "%s/#", F_(commands)); + Mqtt::subscribe(EMSdevice::DeviceType::COMMAND, topic, nullptr); +} + +void WebCommands::read(WebCommands & webCommands, JsonObject root) { + JsonArray items = root["commands"].to(); + uint8_t counter = 1; + for (const CommandItem & ci : webCommands.commandItems) { + JsonObject obj = items.add(); + obj["id"] = counter++; + obj["cmd"] = ci.cmd; + obj["value"] = ci.value; + obj["name"] = (const char *)ci.name; + } +} + +StateUpdateResult WebCommands::update(JsonObject root, WebCommands & webCommands) { + Command::erase_device_commands(EMSdevice::DeviceType::COMMAND); + webCommands.commandItems.clear(); + + auto items = root["commands"].as(); + for (const JsonObject item : items) { + auto ci = CommandItem(); + ci.cmd = item["cmd"].as(); + ci.value = item["value"].as(); + strlcpy(ci.name, item["name"].as(), sizeof(ci.name)); + + webCommands.commandItems.push_back(ci); + if (webCommands.commandItems.back().name[0] != '\0') { + Command::add( + EMSdevice::DeviceType::COMMAND, + webCommands.commandItems.back().name, + [](const char * value, const int8_t id) { + return EMSESP::webCommandService.executeCommand(value); + }, + FL_(command_cmd), + CommandFlag::ADMIN_ONLY); + } + } + return StateUpdateResult::CHANGED; +} + +// find a command item by name (case-insensitive) +const CommandItem * WebCommandService::find(const char * name) { + if (name == nullptr || name[0] == '\0') { + return nullptr; + } + auto lower_name = Helpers::toLower(name); + for (const CommandItem & ci : *commandItems_) { + if (ci.name[0] != '\0' && Helpers::toLower(ci.name) == lower_name) { + return &ci; + } + } + return nullptr; +} + +// execute a named command — looks up by name and runs it +// called from console 'call commands ', API/MQTT, web UI +bool WebCommandService::executeCommand(const char * name) { + const CommandItem * ci = find(name); + if (!ci) { + EMSESP::logger().warning("Command '%s' not found", name ? name : ""); + return false; + } + return executeCommand(ci->name, ci->cmd, ci->value); +} + +// execute a command with explicit cmd and value strings +// handles both HTTP URLs (JSON format) and internal API commands +bool WebCommandService::executeCommand(const char * name, const std::string & command, const std::string & data) { + std::string cmd = Helpers::toLower(command); + + // handle HTTP commands (JSON with url/method/value) + JsonDocument doc; + if (deserializeJson(doc, cmd) == DeserializationError::Ok) { + std::string url = doc["url"] | ""; + auto q = url.find_first_of('?'); + if (q != std::string::npos) { + auto s = url.substr(q + 1); + auto l = s.length(); + commands(s, false); + url.replace(q + 1, l, s); + } + std::string value = doc["value"] | data; + std::string method = doc["method"] | "GET"; + commands(value, false); + auto lower_url = Helpers::toLower(url.c_str()); + if (lower_url.starts_with("http://") || lower_url.starts_with("https://")) { + std::string result; + int httpResult = http_request(url, method, value, doc["header"].as(), result); + if (httpResult != 200) { + EMSESP::logger().warning("Command '%s': URL command failed with http code %d", name, httpResult); + return false; + } +#if defined(EMSESP_DEBUG) + EMSESP::logger().debug("Command '%s': URL '%s' successful with http code %d", name, url.c_str(), httpResult); +#endif + return true; + } + } + + // handle internal API commands + doc.clear(); + JsonObject input = doc.to(); + if (!data.empty()) { + input["data"] = data; + } + + JsonDocument doc_output; + JsonObject output = doc_output.to(); + + char command_str[COMMAND_MAX_LENGTH]; + snprintf(command_str, sizeof(command_str), "/api/%s", cmd.c_str()); + + uint8_t return_code = Command::process(command_str, true, input, output); + if (return_code == CommandRet::OK) { +#if defined(EMSESP_DEBUG) + EMSESP::logger().debug("Command '%s' (%s with data '%s') was successful", name, cmd.c_str(), data.c_str()); +#endif + if (data.empty() && output.size()) { + Mqtt::queue_publish("response", output); + } + return true; + } + + char error[100]; + if (output.size()) { + snprintf(error, sizeof(error), "Command '%s': %s", name ? name : "", (const char *)output["message"]); + } else { + snprintf(error, sizeof(error), "Command '%s': %s failed with error %s", name, cmd.c_str(), Command::return_code_string(return_code)); + } + EMSESP::logger().warning(error); + return false; +} + +bool WebCommandService::get_value_info(JsonObject output, const char * cmd) { + if (commandItems_->empty()) { + return true; + } + + if (!strlen(cmd) || !strcmp(cmd, F_(values)) || !strcmp(cmd, F_(info))) { + for (const CommandItem & ci : *commandItems_) { + if (ci.name[0] != '\0') { + output[(const char *)ci.name] = ci.cmd; + } + } + return true; + } + + if (!strcmp(cmd, F_(entities))) { + for (const CommandItem & ci : *commandItems_) { + if (ci.name[0] != '\0') { + get_value_json(output[ci.name].to(), ci); + } + } + return true; + } + + if (!strcmp(cmd, F_(metrics))) { + std::string metrics = get_metrics_prometheus(); + if (!metrics.empty()) { + output["api_data"] = metrics; + return true; + } + return false; + } + + // look up specific command by name + const char * attribute_s = Command::get_attribute(cmd); + for (const CommandItem & ci : *commandItems_) { + if (Helpers::toLower(ci.name) == cmd) { + get_value_json(output, ci); + return Command::get_attribute(output, cmd, attribute_s); + } + } + + return false; +} + +std::string WebCommandService::get_metrics_prometheus() { + std::string result; + result.reserve(commandItems_->size() * 100); + for (const CommandItem & ci : *commandItems_) { + if (ci.name[0] == '\0') { + continue; + } + result += (std::string) "# HELP emsesp_cmd_" + ci.name + " " + ci.name + "\n"; + result += (std::string) "# TYPE emsesp_cmd_" + ci.name + " gauge\n"; + result += (std::string) "emsesp_cmd_" + ci.name + " 1\n"; + } + return result; +} + +void WebCommandService::get_value_json(JsonObject output, const CommandItem & ci) { + output["name"] = (const char *)ci.name; + output["fullname"] = (const char *)ci.name; + output["type"] = "command"; + output["command"] = ci.cmd; + output["cmd_data"] = ci.value; + bool hasName = ci.name[0] != '\0'; + output["readable"] = hasName; + output["writeable"] = hasName; + output["visible"] = hasName; +} + +void WebCommandService::publish(const bool force) { + if (!Mqtt::enabled() || commandItems_->empty()) { + return; + } + if (force && !EMSESP::mqtt_.get_publish_onchange(0)) { + return; + } + + JsonDocument doc(PSRAM_DOC); + JsonObject output = doc.to(); + for (const CommandItem & ci : *commandItems_) { + if (ci.name[0] != '\0' && !output[ci.name].is()) { + output[(const char *)ci.name] = ci.cmd; + } + } + + if (!doc.isNull()) { + char topic[Mqtt::MQTT_TOPIC_MAX_SIZE]; + snprintf(topic, sizeof(topic), "%s_data", F_(commands)); + Mqtt::queue_publish(topic, output); + } +} + +uint8_t WebCommandService::count_entities() { + return static_cast(commandItems_ ? commandItems_->size() : 0); +} + +#if defined(EMSESP_TEST) +void WebCommandService::load_test_data() { + update([&](WebCommands & webCommands) { + webCommands.commandItems.clear(); + + auto ci = CommandItem(); + ci.cmd = "system/fetch"; + ci.value = "10"; + strcpy(ci.name, "test_cmd1"); + webCommands.commandItems.push_back(ci); + + ci = CommandItem(); + ci.cmd = "system/message"; + ci.value = "hello"; + strcpy(ci.name, "test_cmd2"); + webCommands.commandItems.push_back(ci); + + return StateUpdateResult::CHANGED; + }); +} +#endif + +} // namespace emsesp diff --git a/src/web/WebCommandService.h b/src/web/WebCommandService.h new file mode 100644 index 000000000..563a4ed50 --- /dev/null +++ b/src/web/WebCommandService.h @@ -0,0 +1,75 @@ +/* + * EMS-ESP - https://github.com/emsesp/EMS-ESP + * Copyright 2020-2025 emsesp.org + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include + +#ifndef WebCommandService_h +#define WebCommandService_h + +#define EMSESP_COMMAND_FILE "/config/emsespCommands.json" +#define EMSESP_COMMAND_SERVICE_PATH "/rest/commands" // GET and POST + +namespace emsesp { + +class CommandItem { + public: + stringPSRAM cmd; + stringPSRAM value; + char name[20]; +}; + +class WebCommands { + public: + std::list> commandItems; + + static void read(WebCommands & webCommands, JsonObject root); + static StateUpdateResult update(JsonObject root, WebCommands & webCommands); +}; + +class WebCommandService : public StatefulService { + public: + WebCommandService(AsyncWebServer * server, FS * fs, SecurityManager * securityManager); + + void begin(); + void publish(const bool force = false); + bool get_value_info(JsonObject output, const char * cmd); + void get_value_json(JsonObject output, const CommandItem & commandItem); + + bool executeCommand(const char * name); + bool executeCommand(const char * name, const std::string & cmd, const std::string & value); + + const CommandItem * find(const char * name); + + uint8_t count_entities(); + + std::string get_metrics_prometheus(); + +#if defined(EMSESP_TEST) + void load_test_data(); +#endif + + private: + HttpEndpoint _httpEndpoint; + FSPersistence _fsPersistence; + + std::list> * commandItems_; +}; + +} // namespace emsesp + +#endif diff --git a/src/web/WebDataService.cpp b/src/web/WebDataService.cpp index d8a8a5195..e2f5c4469 100644 --- a/src/web/WebDataService.cpp +++ b/src/web/WebDataService.cpp @@ -250,6 +250,9 @@ void WebDataService::write_device_value(AsyncWebServerRequest * request, JsonVar case EMSdevice::DeviceTypeUniqueID::SCHEDULER_UID: device_type = EMSdevice::DeviceType::SCHEDULER; break; + case EMSdevice::DeviceTypeUniqueID::COMMAND_UID: + device_type = EMSdevice::DeviceType::COMMAND; + break; case EMSdevice::DeviceTypeUniqueID::TEMPERATURESENSOR_UID: device_type = EMSdevice::DeviceType::TEMPERATURESENSOR; break; @@ -478,11 +481,11 @@ void WebDataService::dashboard_data(AsyncWebServerRequest * request) { } } - // show scheduler items + // show scheduler items (active state toggles) if (EMSESP::webSchedulerService.count_entities()) { JsonObject obj = nodes.add(); - obj["id"] = EMSdevice::DeviceTypeUniqueID::SCHEDULER_UID; // it's unique id - obj["t"] = EMSdevice::DeviceType::SCHEDULER; // device type number + obj["id"] = EMSdevice::DeviceTypeUniqueID::SCHEDULER_UID; + obj["t"] = EMSdevice::DeviceType::SCHEDULER; JsonArray nodes = obj["nodes"].to(); uint8_t count = 0; @@ -495,14 +498,31 @@ void WebDataService::dashboard_data(AsyncWebServerRequest * request) { dv["id"] = std::string("00") + scheduleItem.name; dv["c"] = scheduleItem.name; - // for immediate schedules, we don't show the active/inactive state or on/off options - if (scheduleItem.flags != SCHEDULEFLAG_SCHEDULE_IMMEDIATE) { - char s[12]; - dv["v"] = Helpers::render_boolean(s, scheduleItem.active, true); - JsonArray l = dv["l"].to(); - l.add(Helpers::render_boolean(s, false, true)); // False option - l.add(Helpers::render_boolean(s, true, true)); // True option - } + char s[12]; + dv["v"] = Helpers::render_boolean(s, scheduleItem.active, true); + JsonArray l = dv["l"].to(); + l.add(Helpers::render_boolean(s, false, true)); + l.add(Helpers::render_boolean(s, true, true)); + } + }); + } + + // show command items (executable from dashboard) + if (EMSESP::webCommandService.count_entities()) { + JsonObject obj = nodes.add(); + obj["id"] = EMSdevice::DeviceTypeUniqueID::COMMAND_UID; + obj["t"] = EMSdevice::DeviceType::COMMAND; + JsonArray nodes = obj["nodes"].to(); + uint8_t count = 0; + + EMSESP::webCommandService.read([&](const WebCommands & webCommands) { + for (const CommandItem & ci : webCommands.commandItems) { + JsonObject node = nodes.add(); + node["id"] = (EMSdevice::DeviceTypeUniqueID::COMMAND_UID * 100) + count++; + + JsonObject dv = node["dv"].to(); + dv["id"] = std::string("00") + ci.name; + dv["c"] = ci.name; } }); } diff --git a/src/web/WebSchedulerService.cpp b/src/web/WebSchedulerService.cpp index 0fdf60984..2c01d9777 100644 --- a/src/web/WebSchedulerService.cpp +++ b/src/web/WebSchedulerService.cpp @@ -57,21 +57,18 @@ void WebScheduler::read(WebScheduler & webScheduler, JsonObject root) { JsonArray schedule = root["schedule"].to(); uint8_t counter = 1; for (const ScheduleItem & scheduleItem : webScheduler.scheduleItems) { - JsonObject si = schedule.add(); - si["id"] = counter++; // id is only used to render the table and must be unique. 0 is for Dashboard - si["flags"] = scheduleItem.flags; - si["active"] = scheduleItem.flags != SCHEDULEFLAG_SCHEDULE_IMMEDIATE ? scheduleItem.active : false; - si["time"] = scheduleItem.flags != SCHEDULEFLAG_SCHEDULE_IMMEDIATE ? scheduleItem.time : ""; - si["cmd"] = scheduleItem.cmd; - si["value"] = scheduleItem.value; - si["name"] = (const char *)scheduleItem.name; + JsonObject si = schedule.add(); + si["id"] = counter++; + si["flags"] = scheduleItem.flags; + si["active"] = scheduleItem.active; + si["time"] = scheduleItem.time; + si["cmd_name"] = scheduleItem.cmd_name; + si["name"] = (const char *)scheduleItem.name; } } // call on initialization and also when the Schedule web page is saved -// this loads the data into the internal class StateUpdateResult WebScheduler::update(JsonObject root, WebScheduler & webScheduler) { - // reset the list Command::erase_device_commands(EMSdevice::DeviceType::SCHEDULER); for (ScheduleItem & scheduleItem : webScheduler.scheduleItems) { char key[sizeof(scheduleItem.name) + 2]; @@ -83,28 +80,23 @@ StateUpdateResult WebScheduler::update(JsonObject root, WebScheduler & webSchedu webScheduler.scheduleItems.clear(); EMSESP::webSchedulerService.ha_reset(); - // build up the list of schedule items auto scheduleItems = root["schedule"].as(); for (const JsonObject schedule : scheduleItems) { - // create each schedule item, overwriting any previous settings - // ignore the id (as this is only used in the web for table rendering) - auto si = ScheduleItem(); - si.active = schedule["active"]; - si.flags = schedule["flags"]; - si.time = si.flags == SCHEDULEFLAG_SCHEDULE_IMMEDIATE ? "" : schedule["time"].as(); - si.cmd = schedule["cmd"].as(); - si.value = schedule["value"].as(); + auto si = ScheduleItem(); + si.active = schedule["active"]; + si.flags = schedule["flags"]; + si.time = schedule["time"].as(); + si.cmd_name = schedule["cmd_name"].as(); strlcpy(si.name, schedule["name"].as(), sizeof(si.name)); - // calculated elapsed minutes si.elapsed_min = Helpers::string2minutes(si.time.c_str()); - si.retry_cnt = 0xFF; // no startup retries + si.retry_cnt = 0xFF; - webScheduler.scheduleItems.push_back(si); // add to list + webScheduler.scheduleItems.push_back(si); if (webScheduler.scheduleItems.back().name[0] != '\0') { char key[sizeof(webScheduler.scheduleItems.back().name) + 2]; snprintf(key, sizeof(key), "s:%s", webScheduler.scheduleItems.back().name); - if (EMSESP::nvs_.isKey(key) && webScheduler.scheduleItems.back().flags != SCHEDULEFLAG_SCHEDULE_IMMEDIATE) { + if (EMSESP::nvs_.isKey(key)) { webScheduler.scheduleItems.back().active = EMSESP::nvs_.getBool(key); } Command::add( @@ -140,12 +132,9 @@ bool WebSchedulerService::command_setvalue(const char * value, const int8_t id, publish(); } - // save new state to nvs #2946 - if (scheduleItem.flags != SCHEDULEFLAG_SCHEDULE_IMMEDIATE) { - char key[sizeof(scheduleItem.name) + 2]; - snprintf(key, sizeof(key), "s:%s", scheduleItem.name); - EMSESP::nvs_.putBool(key, scheduleItem.active); - } + char key[sizeof(scheduleItem.name) + 2]; + snprintf(key, sizeof(key), "s:%s", scheduleItem.name); + EMSESP::nvs_.putBool(key, scheduleItem.active); return true; } } @@ -225,11 +214,10 @@ void WebSchedulerService::get_value_json(JsonObject output, const ScheduleItem & output["onchange"] = scheduleItem.time; } else if (scheduleItem.flags == SCHEDULEFLAG_SCHEDULE_TIMER) { output["timer"] = scheduleItem.time; - } else if (scheduleItem.flags != SCHEDULEFLAG_SCHEDULE_IMMEDIATE) { + } else { output["time"] = scheduleItem.time; } - output["command"] = scheduleItem.cmd; - output["cmd_data"] = scheduleItem.value; + output["cmd_name"] = scheduleItem.cmd_name; bool hasName = scheduleItem.name[0] != '\0'; output["readable"] = hasName; output["writeable"] = hasName; @@ -339,80 +327,14 @@ uint8_t WebSchedulerService::count_entities() { return static_cast(scheduleItems_ ? scheduleItems_->size() : 0); } -// execute scheduled command -// return true if successful, false if not -bool WebSchedulerService::command(const char * name, const std::string & command, const std::string & data) { - std::string cmd = Helpers::toLower(command); - - // check http commands. e.g. - // tasmota(get): http:///cm?cmnd=power%20ON - // shelly(get): http:///relais/0?turn=on - // parse json - JsonDocument doc; - if (deserializeJson(doc, cmd) == DeserializationError::Ok) { - std::string url = doc["url"] | ""; - // for a GET with parameters replace commands with values - // don't search the complete url, it may contain a devicename in path - auto q = url.find_first_of('?'); - if (q != std::string::npos) { - auto s = url.substr(q + 1); // copy only parameters - auto l = s.length(); - commands(s, false); - url.replace(q + 1, l, s); - } - std::string value = doc["value"] | data; // extract value if its in the command, or take the data - std::string method = doc["method"] | "GET"; // default GET - commands(value, false); - auto lower_url = Helpers::toLower(url.c_str()); - if (lower_url.starts_with("http://") || lower_url.starts_with("https://")) { - std::string result; - int httpResult = http_request(url, method, value, doc["header"].as(), result); - if (httpResult != 200) { - EMSESP::logger().warning("Schedule '%s': URL command failed with http code %d", name, httpResult); - return false; - } -#if defined(EMSESP_DEBUG) - EMSESP::logger().debug("Schedule %s: URL '%s' command successful with http code %d", name, url.c_str(), httpResult); -#endif - return true; - } - // we can add other json tests here +// execute the command associated with a schedule item +// looks up the named command in WebCommandService and runs it +bool WebSchedulerService::runScheduleCommand(const ScheduleItem & si) { + if (si.cmd_name.empty()) { + EMSESP::logger().warning("Schedule '%s': no command assigned", si.name); + return false; } - - doc.clear(); - JsonObject input = doc.to(); - if (!data.empty()) { // empty data queries a value - input["data"] = data; - } - - JsonDocument doc_output; // only for commands without output - JsonObject output = doc_output.to(); - - // prefix "api/" to command string - char command_str[COMMAND_MAX_LENGTH]; - snprintf(command_str, sizeof(command_str), "/api/%s", cmd.c_str()); - - uint8_t return_code = Command::process(command_str, true, input, output); // admin set - if (return_code == CommandRet::OK) { -#if defined(EMSESP_DEBUG) - EMSESP::logger().debug("Schedule command '%s' with data '%s' was successful", cmd.c_str(), data.c_str()); -#endif - if (data.empty() && output.size()) { - Mqtt::queue_publish("response", output); - } - return true; - } - - char error[100]; - if (output.size()) { - // check for empty name - snprintf(error, sizeof(error), "Schedule %s: %s", name ? name : "", (const char *)output["message"]); // use error message if we have it - } else { - snprintf(error, sizeof(error), "Schedule %s: command %s failed with error %s", name, cmd.c_str(), Command::return_code_string(return_code)); - } - - EMSESP::logger().warning(error); - return false; + return EMSESP::webCommandService.executeCommand(si.cmd_name.c_str()); } // called from emsesp.cpp on every entity-change @@ -427,31 +349,16 @@ bool WebSchedulerService::onChange(const char * cmd) { return false; } -// system/message evaluates its own argument later (deferred via raw_value, computed in loop()), -// so pre-computing it here would make any {url} or expression inside it run twice. Pass -// system/message its value raw; compute() everything else as before. -// templated because ScheduleItem's strings use a PSRAM allocator, not std::string. -template -static std::string compute_cmd_value(const C & cmd, const V & value) { - if (Helpers::toLower(cmd.c_str()) == "system/message") { - return std::string(value.c_str()); - } - return compute(value.c_str()); -} - // handle condition schedules, parse string stored in schedule.time field void WebSchedulerService::condition() { for (ScheduleItem & scheduleItem : *scheduleItems_) { if (scheduleItem.active && scheduleItem.flags == SCHEDULEFLAG_SCHEDULE_CONDITION) { auto match = compute(scheduleItem.time.c_str()); -#ifdef EMESESP_DEBUG - // EMSESP::logger().debug("condition match: %s", match.c_str()); -#endif if (match.length() == 1 && match[0] == '1' && scheduleItem.retry_cnt == 0xFF) { - scheduleItem.retry_cnt = command(scheduleItem.name, scheduleItem.cmd.c_str(), compute_cmd_value(scheduleItem.cmd, scheduleItem.value)) ? 1 : 0xFF; + scheduleItem.retry_cnt = runScheduleCommand(scheduleItem) ? 1 : 0xFF; } else if (match.length() == 1 && match[0] == '0' && scheduleItem.retry_cnt == 1) { scheduleItem.retry_cnt = 0xFF; - } else if (match.length() != 1) { // the match is not boolean + } else if (match.length() != 1) { #if defined(EMSESP_DEBUG) EMSESP::logger().debug("condition result: %s", match.c_str()); #endif @@ -462,17 +369,15 @@ void WebSchedulerService::condition() { // process any scheduled jobs void WebSchedulerService::loop() { - // initialize static value on startup static int8_t last_tm_min = -2; // invalid value also used for startup commands static uint32_t last_uptime_min = 0; static uint32_t last_uptime_sec = 0; - if (!raw_value.empty()) { // process a value from system/message command + if (!raw_value.empty()) { computed_value = compute(raw_value); raw_value.clear(); } - // get list of scheduler events and exit if it's empty if (scheduleItems_->empty()) { return; } @@ -480,21 +385,10 @@ void WebSchedulerService::loop() { // check if we have onChange events while (!cmd_changed_.empty()) { ScheduleItem si = *cmd_changed_.front(); - command(si.name, si.cmd.c_str(), compute_cmd_value(si.cmd, si.value)); + runScheduleCommand(si); cmd_changed_.pop_front(); } - for (ScheduleItem & scheduleItem : *scheduleItems_) { - if (scheduleItem.active && scheduleItem.flags == SCHEDULEFLAG_SCHEDULE_IMMEDIATE) { - command(scheduleItem.name, scheduleItem.cmd.c_str(), compute_cmd_value(scheduleItem.cmd, scheduleItem.value)); - scheduleItem.active = false; - publish_single(scheduleItem.name, false); - if (EMSESP::mqtt_.get_publish_onchange(0)) { - publish(); - } - } - } - // check conditions every 10 seconds, start after one minute uint32_t uptime_sec = uuid::get_uptime_sec() / 10; if (last_uptime_sec != uptime_sec && uptime_sec > 5) { @@ -506,64 +400,49 @@ void WebSchedulerService::loop() { if (last_tm_min == -2) { for (ScheduleItem & scheduleItem : *scheduleItems_) { if (scheduleItem.active && scheduleItem.flags == SCHEDULEFLAG_SCHEDULE_TIMER && scheduleItem.elapsed_min == 0) { - scheduleItem.retry_cnt = command(scheduleItem.name, scheduleItem.cmd.c_str(), compute_cmd_value(scheduleItem.cmd, scheduleItem.value)) ? 0xFF : 0; + scheduleItem.retry_cnt = runScheduleCommand(scheduleItem) ? 0xFF : 0; } } - last_tm_min = -1; // startup done, now use for RTC + last_tm_min = -1; } // check timer every minute, sync to EMS-ESP clock uint32_t uptime_min = uuid::get_uptime_sec() / 60; if (last_uptime_min != uptime_min) { for (ScheduleItem & scheduleItem : *scheduleItems_) { - // retry startup commands not yet executed if (scheduleItem.active && scheduleItem.flags == SCHEDULEFLAG_SCHEDULE_TIMER && scheduleItem.elapsed_min == 0 && scheduleItem.retry_cnt < MAX_STARTUP_RETRIES) { - scheduleItem.retry_cnt = command(scheduleItem.name, scheduleItem.cmd.c_str(), scheduleItem.value.c_str()) ? 0xFF : scheduleItem.retry_cnt + 1; + scheduleItem.retry_cnt = runScheduleCommand(scheduleItem) ? 0xFF : scheduleItem.retry_cnt + 1; } - // scheduled timer commands if (scheduleItem.active && scheduleItem.flags == SCHEDULEFLAG_SCHEDULE_TIMER && scheduleItem.elapsed_min > 0 && (uptime_min % scheduleItem.elapsed_min == 0)) { - command(scheduleItem.name, scheduleItem.cmd.c_str(), compute_cmd_value(scheduleItem.cmd, scheduleItem.value)); + runScheduleCommand(scheduleItem); } } last_uptime_min = uptime_min; } - // check calender, sync to RTC, only execute if year is valid + // check calendar, sync to RTC, only execute if year is valid time_t now = time(nullptr); tm * tm = localtime(&now); if (tm->tm_min != last_tm_min && tm->tm_year > 120) { - // find the real dow and minute from RTC - uint8_t real_dow = 1 << tm->tm_wday; // 1 is Sunday + uint8_t real_dow = 1 << tm->tm_wday; uint16_t real_min = tm->tm_hour * 60 + tm->tm_min; for (const ScheduleItem & scheduleItem : *scheduleItems_) { uint8_t dow = scheduleItem.flags & SCHEDULEFLAG_SCHEDULE_TIMER ? 0 : scheduleItem.flags; if (scheduleItem.active && (real_dow & dow) && real_min == scheduleItem.elapsed_min) { - command(scheduleItem.name, scheduleItem.cmd.c_str(), compute_cmd_value(scheduleItem.cmd, scheduleItem.value)); + runScheduleCommand(scheduleItem); } } last_tm_min = tm->tm_min; } } -// execute a schedule item immediately -bool WebSchedulerService::executeSchedule(const char * name) { - for (ScheduleItem & scheduleItem : *scheduleItems_) { - if (scheduleItem.flags == SCHEDULEFLAG_SCHEDULE_IMMEDIATE && strcmp(scheduleItem.name, name) == 0) { - EMSESP::logger().info("Executing schedule '%s'", name); - return command(scheduleItem.name, scheduleItem.cmd.c_str(), compute_cmd_value(scheduleItem.cmd, scheduleItem.value)); - } - } - EMSESP::logger().warning("Schedule '%s' not found", name); - return false; // not found -} - // process schedules async void WebSchedulerService::scheduler_task(void * pvParameters) { while (1) { - delay(10); // no need to hurry + delay(10); if (EMSESP::system_.systemStatus() == SYSTEM_STATUS::SYSTEM_STATUS_NORMAL) { EMSESP::webSchedulerService.loop(); } @@ -573,39 +452,34 @@ void WebSchedulerService::scheduler_task(void * pvParameters) { #endif } -// hard coded tests #if defined(EMSESP_TEST) void WebSchedulerService::load_test_data() { update([&](WebScheduler & webScheduler) { - webScheduler.scheduleItems.clear(); // delete all existing schedules + webScheduler.scheduleItems.clear(); - // test 1 - auto si = ScheduleItem(); - si.active = true; - si.flags = 1; // day schedule - si.time = "12:00"; - si.cmd = "system/fetch"; - si.value = "10"; + auto si = ScheduleItem(); + si.active = true; + si.flags = 1; // day schedule + si.time = "12:00"; + si.cmd_name = "test_cmd1"; strcpy(si.name, "test_scheduler1"); si.elapsed_min = 0; - si.retry_cnt = 0xFF; // no startup retries + si.retry_cnt = 0xFF; webScheduler.scheduleItems.push_back(si); - // test 2 - si = ScheduleItem(); - si.active = false; - si.flags = SCHEDULEFLAG_SCHEDULE_IMMEDIATE; // immediate - si.time = "13:00"; - si.cmd = "system/message"; - si.value = "20"; - strcpy(si.name, "test_scheduler2"); // to make sure its excluded from Dashboard - si.elapsed_min = 0; - si.retry_cnt = 0xFF; // no startup retries + si = ScheduleItem(); + si.active = true; + si.flags = SCHEDULEFLAG_SCHEDULE_TIMER; + si.time = "01:00"; + si.cmd_name = "test_cmd2"; + strcpy(si.name, "test_scheduler2"); + si.elapsed_min = 60; + si.retry_cnt = 0xFF; webScheduler.scheduleItems.push_back(si); - return StateUpdateResult::CHANGED; // persist the changes + return StateUpdateResult::CHANGED; }); } #endif diff --git a/src/web/WebSchedulerService.h b/src/web/WebSchedulerService.h index 281f44a0b..4ee03e0c3 100644 --- a/src/web/WebSchedulerService.h +++ b/src/web/WebSchedulerService.h @@ -41,11 +41,9 @@ // 128 (0x80) is timer // 129 (0x81) is on change // 130 (0x82) is on condition -// 132 (0x84) is immediate #define SCHEDULEFLAG_SCHEDULE_TIMER 0x80 // 7th bit for Timer #define SCHEDULEFLAG_SCHEDULE_ONCHANGE 0x81 // 7th+1st bit for OnChange #define SCHEDULEFLAG_SCHEDULE_CONDITION 0x82 // 7th+2nd bit for Condition -#define SCHEDULEFLAG_SCHEDULE_IMMEDIATE 0x84 // 7th+3rd bit for Immediate #define MAX_STARTUP_RETRIES 3 // retry the start-up commands x times @@ -57,8 +55,7 @@ class ScheduleItem { uint8_t flags; // bit flags, see SCHEDULEFLAG_* defines uint16_t elapsed_min; // total mins from 00:00 stringPSRAM time; // HH:MM - stringPSRAM cmd; - stringPSRAM value; + stringPSRAM cmd_name; // references a named command from WebCommandService char name[20]; uint8_t retry_cnt; }; @@ -88,8 +85,6 @@ class WebSchedulerService : public StatefulService { uint8_t count_entities(); bool onChange(const char * cmd); - bool executeSchedule(const char * name); - std::string get_metrics_prometheus(); std::string raw_value; @@ -105,7 +100,7 @@ class WebSchedulerService : public StatefulService { #endif static void scheduler_task(void * pvParameters); - bool command(const char * name, const std::string & cmd, const std::string & data); + bool runScheduleCommand(const ScheduleItem & si); void condition(); HttpEndpoint _httpEndpoint; diff --git a/src/web/WebStatusService.cpp b/src/web/WebStatusService.cpp index 8cb934cdf..4ae37bb47 100644 --- a/src/web/WebStatusService.cpp +++ b/src/web/WebStatusService.cpp @@ -232,8 +232,8 @@ void WebStatusService::action(AsyncWebServerRequest * request, JsonVariant json) EMSESP::mqtt_.reset_mqtt(); } else if (action == "upgradeImportantMessages") { root["upgradeImportantMessageType"] = upgradeImportantMessages(param); - } else if (action == "executeSchedule") { - ok = EMSESP::webSchedulerService.executeSchedule(param.c_str()); + } else if (action == "executeCommand") { + ok = EMSESP::webCommandService.executeCommand(param.c_str()); } #if defined(EMSESP_STANDALONE) && !defined(EMSESP_UNITY) From 8a45e790718f658c955af63393db732c7dd5a437 Mon Sep 17 00:00:00 2001 From: proddy Date: Mon, 8 Jun 2026 10:03:32 +0200 Subject: [PATCH 02/44] updates --- src/core/locale_translations.h | 2 +- src/test/test.cpp | 5 ++++- src/test/test.h | 2 +- src/web/WebCommandService.cpp | 38 ++++++++++++++++++++++----------- src/web/WebSchedulerService.cpp | 18 ++++++++++++++++ 5 files changed, 50 insertions(+), 15 deletions(-) diff --git a/src/core/locale_translations.h b/src/core/locale_translations.h index db34b25f5..f5ece66ac 100644 --- a/src/core/locale_translations.h +++ b/src/core/locale_translations.h @@ -75,7 +75,7 @@ MAKE_WORD_TRANSLATION(format_cmd, "factory reset EMS-ESP", "EMS-ESP auf Werksein MAKE_WORD_TRANSLATION(watch_cmd, "watch incoming telegrams", "Beobachte eingehende Telegramme", "inkomende telegrammen bekijken", "visa inkommande telegram", "obserwuj przyczodzące telegramy", "se innkommende telegrammer", "surveiller les télégrammes entrants", "Gelen telegramları izle", "guardare i telegrammi in arrivo", "sledovať prichádzajúce telegramy", "sledovat příchozí telegramy") MAKE_WORD_TRANSLATION(publish_cmd, "publish all to MQTT", "Publiziere MQTT", "publiceer alles naar MQTT", "publicera allt till MQTT", "opublikuj wszystko na MQTT", "Publiser alt til MQTT", "publier tout vers MQTT", "Hepsini MQTTye gönder", "pubblica tutto su MQTT", "zverejniť všetko na MQTT", "publikovat vše do MQTT") MAKE_WORD_TRANSLATION(system_info_cmd, "show system info", "Zeige Systeminformationen", "toon systeemstatus", "visa systeminformation", "pokaż status systemu", "vis system status", "afficher les informations système", "Sistem Durumunu Göster", "visualizza stati di sistema", "zobraziť stav systému", "zobrazit informace o systému") -MAKE_WORD_TRANSLATION(schedule_cmd, "enable schedule item", "Aktiviere Zeitplanelemente", "activeer tijdschema item", "aktivera schemalagt objekt", "aktywuj wybrany harmonogram", "aktiver planlagt element", "activer élément programmé", "program öğesini etkinleştir", "abilitare l'elemento programmato", "povoliť položku plánovania", "povolit položku plánování") +MAKE_WORD_TRANSLATION(schedule_cmd, "enable/disable schedule item", "Aktiviere/Deaktiviere Zeitplanelemente", "activeer/deactiveer tijdschema item", "aktivera/deaktivera schemalagt objekt", "aktywuj/deaktywuj wybrany harmonogram", "aktiver/deaktiver planlagt element", "activer/deactiver élément programmé", "program öğesini etkinleştir/devre dışı bırak", "abilitare/disabilitare l'elemento programmato", "povoliť/deaktivovať položku plánovania", "povolit/deaktivovat položku plánování") MAKE_WORD_TRANSLATION(command_cmd, "execute command", "Befehl ausführen", "opdracht uitvoeren", "kör kommando", "wykonaj polecenie", "kjør kommando", "exécuter commande", "komut çalıştır", "esegui comando", "vykonať príkaz", "provést příkaz") MAKE_WORD_TRANSLATION(entity_cmd, "set custom value", "Sende eigene Entitäten", "verstuur custom waarde", "sätt ett eget värde", "wyślij własną wartość", "sett egendefinert verdi", "définir valeur personnalisée", "özel değer ayarla", "imposta valori personalizzati", "nastaviť vlastnú hodnotu", "nastavit vlastní hodnotu") MAKE_WORD_TRANSLATION(commands_response, "get response", "Hole Antwort", "Verzoek om antwoord", "hämta svar", "uzyskaj odpowiedź", "få svar", "obtenir réponse", "yanıt al", "ottieni risposta", "získať odpoveď", "získat odpověď") diff --git a/src/test/test.cpp b/src/test/test.cpp index ba2c64842..d0435583a 100644 --- a/src/test/test.cpp +++ b/src/test/test.cpp @@ -350,6 +350,7 @@ void Test::run_test(uuid::console::Shell & shell, const std::string & cmd, const EMSESP::webCustomEntityService.load_test_data(); // custom entities EMSESP::webCustomizationService.load_test_data(); // set customizations - this will overwrite any settings in the FS EMSESP::temperaturesensor_.load_test_data(); // add temperature sensors + EMSESP::webCommandService.load_test_data(); // add command items EMSESP::webSchedulerService.load_test_data(); // add scheduler data shell.invoke_command("show values"); @@ -406,7 +407,7 @@ void Test::run_test(uuid::console::Shell & shell, const std::string & cmd, const if (command == "scheduler") { shell.printfln("Adding Scheduler items..."); - // add some dummy entities + EMSESP::webCommandService.load_test_data(); EMSESP::webSchedulerService.load_test_data(); #ifdef EMSESP_STANDALONE @@ -1116,6 +1117,7 @@ void Test::run_test(uuid::console::Shell & shell, const std::string & cmd, const EMSESP::webCustomEntityService.load_test_data(); // custom entities EMSESP::webCustomizationService.load_test_data(); // set customizations - this will overwrite any settings in the FS EMSESP::temperaturesensor_.load_test_data(); // add temperature sensors + EMSESP::webCommandService.load_test_data(); // add command items EMSESP::webSchedulerService.load_test_data(); // run scheduler tests, and conditions JsonDocument doc; @@ -1379,6 +1381,7 @@ void Test::run_test(uuid::console::Shell & shell, const std::string & cmd, const EMSESP::webCustomEntityService.load_test_data(); // custom entities EMSESP::webCustomizationService.load_test_data(); // set customizations - this will overwrite any settings in the FS EMSESP::temperaturesensor_.load_test_data(); // add temperature sensors + EMSESP::webCommandService.load_test_data(); // add command items EMSESP::webSchedulerService.load_test_data(); // run scheduler tests, and conditions request.method(HTTP_GET); diff --git a/src/test/test.h b/src/test/test.h index 9ca860f51..51be36cc9 100644 --- a/src/test/test.h +++ b/src/test/test.h @@ -64,7 +64,7 @@ namespace emsesp { // #define EMSESP_DEBUG_DEFAULT "hpmode" // #define EMSESP_DEBUG_DEFAULT "shuntingyard" // #define EMSESP_DEBUG_DEFAULT "src" -#define EMSESP_DEBUG_DEFAULT "led" +// #define EMSESP_DEBUG_DEFAULT "led" #ifndef EMSESP_DEBUG_DEFAULT #define EMSESP_DEBUG_DEFAULT "general" diff --git a/src/web/WebCommandService.cpp b/src/web/WebCommandService.cpp index cf841c188..9e7445f30 100644 --- a/src/web/WebCommandService.cpp +++ b/src/web/WebCommandService.cpp @@ -37,10 +37,14 @@ void WebCommandService::begin() { char topic[Mqtt::MQTT_TOPIC_MAX_SIZE]; snprintf(topic, sizeof(topic), "%s/#", F_(commands)); Mqtt::subscribe(EMSdevice::DeviceType::COMMAND, topic, nullptr); + +#if defined(EMSESP_TEST) + load_test_data(); +#endif } void WebCommands::read(WebCommands & webCommands, JsonObject root) { - JsonArray items = root["commands"].to(); + JsonArray items = root["commands"].to(); uint8_t counter = 1; for (const CommandItem & ci : webCommands.commandItems) { JsonObject obj = items.add(); @@ -57,8 +61,8 @@ StateUpdateResult WebCommands::update(JsonObject root, WebCommands & webCommands auto items = root["commands"].as(); for (const JsonObject item : items) { - auto ci = CommandItem(); - ci.cmd = item["cmd"].as(); + auto ci = CommandItem(); + ci.cmd = item["cmd"].as(); ci.value = item["value"].as(); strlcpy(ci.name, item["name"].as(), sizeof(ci.name)); @@ -67,9 +71,7 @@ StateUpdateResult WebCommands::update(JsonObject root, WebCommands & webCommands Command::add( EMSdevice::DeviceType::COMMAND, webCommands.commandItems.back().name, - [](const char * value, const int8_t id) { - return EMSESP::webCommandService.executeCommand(value); - }, + [](const char * value, const int8_t id) { return EMSESP::webCommandService.executeCommand(value); }, FL_(command_cmd), CommandFlag::ADMIN_ONLY); } @@ -99,7 +101,7 @@ bool WebCommandService::executeCommand(const char * name) { EMSESP::logger().warning("Command '%s' not found", name ? name : ""); return false; } - return executeCommand(ci->name, ci->cmd, ci->value); + return executeCommand(ci->name, std::string(ci->cmd.c_str()), std::string(ci->value.c_str())); } // execute a command with explicit cmd and value strings @@ -111,7 +113,7 @@ bool WebCommandService::executeCommand(const char * name, const std::string & co JsonDocument doc; if (deserializeJson(doc, cmd) == DeserializationError::Ok) { std::string url = doc["url"] | ""; - auto q = url.find_first_of('?'); + auto q = url.find_first_of('?'); if (q != std::string::npos) { auto s = url.substr(q + 1); auto l = s.length(); @@ -269,21 +271,33 @@ uint8_t WebCommandService::count_entities() { #if defined(EMSESP_TEST) void WebCommandService::load_test_data() { + Command::erase_device_commands(EMSdevice::DeviceType::COMMAND); update([&](WebCommands & webCommands) { webCommands.commandItems.clear(); - auto ci = CommandItem(); - ci.cmd = "system/fetch"; + auto ci = CommandItem(); + ci.cmd = "system/fetch"; ci.value = "10"; strcpy(ci.name, "test_cmd1"); webCommands.commandItems.push_back(ci); - ci = CommandItem(); - ci.cmd = "system/message"; + ci = CommandItem(); + ci.cmd = "system/message"; ci.value = "hello"; strcpy(ci.name, "test_cmd2"); webCommands.commandItems.push_back(ci); + for (const auto & item : webCommands.commandItems) { + if (item.name[0] != '\0') { + Command::add( + EMSdevice::DeviceType::COMMAND, + item.name, + [](const char * value, const int8_t id) { return EMSESP::webCommandService.executeCommand(value); }, + FL_(command_cmd), + CommandFlag::ADMIN_ONLY); + } + } + return StateUpdateResult::CHANGED; }); } diff --git a/src/web/WebSchedulerService.cpp b/src/web/WebSchedulerService.cpp index 2c01d9777..049eaa404 100644 --- a/src/web/WebSchedulerService.cpp +++ b/src/web/WebSchedulerService.cpp @@ -49,6 +49,10 @@ void WebSchedulerService::begin() { #endif } #endif + +#if defined(EMSESP_TEST) + load_test_data(); +#endif } // this creates the scheduler file, saving it to the FS @@ -454,6 +458,7 @@ void WebSchedulerService::scheduler_task(void * pvParameters) { #if defined(EMSESP_TEST) void WebSchedulerService::load_test_data() { + Command::erase_device_commands(EMSdevice::DeviceType::SCHEDULER); update([&](WebScheduler & webScheduler) { webScheduler.scheduleItems.clear(); @@ -479,6 +484,19 @@ void WebSchedulerService::load_test_data() { webScheduler.scheduleItems.push_back(si); + for (const auto & item : webScheduler.scheduleItems) { + if (item.name[0] != '\0') { + Command::add( + EMSdevice::DeviceType::SCHEDULER, + item.name, + [name = std::string(item.name)](const char * value, const int8_t id) { + return EMSESP::webSchedulerService.command_setvalue(value, id, name.c_str()); + }, + FL_(schedule_cmd), + CommandFlag::ADMIN_ONLY); + } + } + return StateUpdateResult::CHANGED; }); } From ecf416dc0a5b81498141b29cb7850b4f0500c24a Mon Sep 17 00:00:00 2001 From: proddy Date: Mon, 8 Jun 2026 20:41:05 +0200 Subject: [PATCH 03/44] formatting --- interface/src/app/main/SchedulerDialog.tsx | 6 +----- interface/src/app/main/validators.ts | 10 +++++----- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/interface/src/app/main/SchedulerDialog.tsx b/interface/src/app/main/SchedulerDialog.tsx index bd124b9eb..b4e946f38 100644 --- a/interface/src/app/main/SchedulerDialog.tsx +++ b/interface/src/app/main/SchedulerDialog.tsx @@ -286,11 +286,7 @@ const SchedulerDialog = ({ onChange={updateFormValue} /> {isTimerSchedule && ( - + {LL.SCHEDULER_HELP_2()} )} diff --git a/interface/src/app/main/validators.ts b/interface/src/app/main/validators.ts index 4bef5f07f..a1c2e7d26 100644 --- a/interface/src/app/main/validators.ts +++ b/interface/src/app/main/validators.ts @@ -238,13 +238,13 @@ export const schedulerItemValidation = ( NAME_PATTERN_REQUIRED, uniqueNameValidator(schedule, scheduleItem.o_name) ], - cmd_name: [ - { required: true, message: 'Command is required' } - ] + cmd_name: [{ required: true, message: 'Command is required' }] }); -export const uniqueCommandNameValidator = (commands: CommandItem[], o_name?: string) => - createUniqueNameValidator(commands, o_name); +export const uniqueCommandNameValidator = ( + commands: CommandItem[], + o_name?: string +) => createUniqueNameValidator(commands, o_name); export const commandItemValidation = ( commands: CommandItem[], From ba7ea60af56d6d29c3e80f2f7ddccfc3c429021a Mon Sep 17 00:00:00 2001 From: proddy Date: Mon, 8 Jun 2026 20:41:11 +0200 Subject: [PATCH 04/44] typo --- interface/src/app/main/Commands.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interface/src/app/main/Commands.tsx b/interface/src/app/main/Commands.tsx index 495d8634d..b734c6c36 100644 --- a/interface/src/app/main/Commands.tsx +++ b/interface/src/app/main/Commands.tsx @@ -1,4 +1,4 @@ -import { useEffect, useState } from 'react'; +import { useState } from 'react'; import { useBlocker } from 'react-router'; import { toast } from 'react-toastify'; @@ -131,7 +131,7 @@ const CommandsPage = () => { name: ci.name })) }); - toast.success(LL.UPDATED_OF(LL.COMMANDS(1))); + toast.success(LL.UPDATED_OF(LL.COMMANDS(0))); } catch (error: unknown) { const message = error instanceof Error ? error.message : String(error); toast.error(message); From 4085a961457c1576cc290b331b198516fc7e4c09 Mon Sep 17 00:00:00 2001 From: proddy Date: Mon, 8 Jun 2026 20:41:21 +0200 Subject: [PATCH 05/44] formatting --- interface/src/components/layout/LayoutMenu.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/src/components/layout/LayoutMenu.tsx b/interface/src/components/layout/LayoutMenu.tsx index 090dadf4c..bcfafac5d 100644 --- a/interface/src/components/layout/LayoutMenu.tsx +++ b/interface/src/components/layout/LayoutMenu.tsx @@ -7,8 +7,8 @@ import ConstructionIcon from '@mui/icons-material/Construction'; import KeyboardArrowDown from '@mui/icons-material/KeyboardArrowDown'; import LiveHelpIcon from '@mui/icons-material/LiveHelp'; import MoreTimeIcon from '@mui/icons-material/MoreTime'; -import PlaylistPlayIcon from '@mui/icons-material/PlaylistPlay'; import PlaylistAddIcon from '@mui/icons-material/PlaylistAdd'; +import PlaylistPlayIcon from '@mui/icons-material/PlaylistPlay'; import SensorsIcon from '@mui/icons-material/Sensors'; import SettingsIcon from '@mui/icons-material/Settings'; import StarIcon from '@mui/icons-material/Star'; From 643744d8d9270cd02ff272ffa0fca8fa5e9cd13a Mon Sep 17 00:00:00 2001 From: proddy Date: Mon, 8 Jun 2026 20:41:31 +0200 Subject: [PATCH 06/44] formatting --- mock-api/restServer.ts | 44 +++++++++++++++++++++++------------------- 1 file changed, 24 insertions(+), 20 deletions(-) diff --git a/mock-api/restServer.ts b/mock-api/restServer.ts index bc4dd4488..ee5c3f812 100644 --- a/mock-api/restServer.ts +++ b/mock-api/restServer.ts @@ -318,10 +318,10 @@ function updateMask(entity: any, de: any, dd: any) { const old_custom_name = dd.nodes[dd_objIndex].cn; console.log( 'comparing names, old (' + - old_custom_name + - ') with new (' + - new_custom_name + - ')' + old_custom_name + + ') with new (' + + new_custom_name + + ')' ); if (old_custom_name !== new_custom_name) { changed = true; @@ -438,9 +438,9 @@ function upgradeImportantMessages(version: string) { console.log( 'upgradeImportantMessageType: version=' + - version + - ' type=' + - upgradeImportantMessageType_n + version + + ' type=' + + upgradeImportantMessageType_n ); return { upgradeImportantMessageType: upgradeImportantMessageType_n }; } @@ -487,17 +487,17 @@ function get_versions() { console.log( 'getVersions: current=' + - THIS_VERSION + - ' stable=' + - LATEST_STABLE_VERSION + - ' (upgradeable=' + - (STABLE_VERSION_IS_UPGRADEABLE ? 'YES' : 'NO') + - ') dev=' + - LATEST_DEV_VERSION + - ' (upgradeable=' + - (DEV_VERSION_IS_UPGRADEABLE ? 'YES' : 'NO') + - ')' + - (MOCK_OFFLINE ? ' [offline]' : '') + THIS_VERSION + + ' stable=' + + LATEST_STABLE_VERSION + + ' (upgradeable=' + + (STABLE_VERSION_IS_UPGRADEABLE ? 'YES' : 'NO') + + ') dev=' + + LATEST_DEV_VERSION + + ' (upgradeable=' + + (DEV_VERSION_IS_UPGRADEABLE ? 'YES' : 'NO') + + ')' + + (MOCK_OFFLINE ? ' [offline]' : '') ); return data; } @@ -4796,7 +4796,9 @@ router } // add the scheduler data - const namedSchedules = emsesp_schedule.schedule.filter((item: any) => item.name); + const namedSchedules = emsesp_schedule.schedule.filter( + (item: any) => item.name + ); if (namedSchedules.length > 0) { const scheduler_data = namedSchedules.map((item: any, index: number) => ({ id: DeviceTypeUniqueID.SCHEDULER_UID * 100 + index, @@ -4816,7 +4818,9 @@ router } // add the command items (executable from dashboard) - const namedCommands = emsesp_commands.commands.filter((item: any) => item.name); + const namedCommands = emsesp_commands.commands.filter( + (item: any) => item.name + ); if (namedCommands.length > 0) { const command_data = namedCommands.map((item: any, index: number) => ({ id: DeviceTypeUniqueID.COMMAND_UID * 100 + index, From 223700a1a8ac9cfd6b22cae3fb530eb248ff4312 Mon Sep 17 00:00:00 2001 From: proddy Date: Mon, 8 Jun 2026 20:41:39 +0200 Subject: [PATCH 07/44] update --- CHANGELOG_LATEST.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG_LATEST.md b/CHANGELOG_LATEST.md index b483725d2..da70841b8 100644 --- a/CHANGELOG_LATEST.md +++ b/CHANGELOG_LATEST.md @@ -8,6 +8,7 @@ For more details go to [emsesp.org](https://emsesp.org/). - user-requested LED blink [#3063](https://github.com/emsesp/EMS-ESP32/issues/3063) - KM300 at address 0x4A [#3084](https://github.com/emsesp/EMS-ESP32/issues/3084) +- Commands Service that can be called via MQTT or API or used in the Scheduler Service ## Fixed From 192357f4f3b03578c2d22d527f275652beacf8ac Mon Sep 17 00:00:00 2001 From: proddy Date: Mon, 8 Jun 2026 20:41:47 +0200 Subject: [PATCH 08/44] 3.9.0-dev.12 --- src/emsesp_version.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/emsesp_version.h b/src/emsesp_version.h index f23c4d33f..a0b2b0af5 100644 --- a/src/emsesp_version.h +++ b/src/emsesp_version.h @@ -1 +1 @@ -#define EMSESP_APP_VERSION "3.9.0-dev.11" +#define EMSESP_APP_VERSION "3.9.0-dev.12" From fd359ab9edbe705b5418df83b339a9726fd1fa89 Mon Sep 17 00:00:00 2001 From: proddy Date: Mon, 8 Jun 2026 20:42:08 +0200 Subject: [PATCH 09/44] optional value when calling commands --- src/web/WebCommandService.cpp | 62 ++++++++++++++++++++--------------- src/web/WebCommandService.h | 6 ++-- 2 files changed, 39 insertions(+), 29 deletions(-) diff --git a/src/web/WebCommandService.cpp b/src/web/WebCommandService.cpp index 9e7445f30..5a62c6da3 100644 --- a/src/web/WebCommandService.cpp +++ b/src/web/WebCommandService.cpp @@ -24,8 +24,8 @@ namespace emsesp { WebCommandService::WebCommandService(AsyncWebServer * server, FS * fs, SecurityManager * securityManager) - : _httpEndpoint(WebCommands::read, WebCommands::update, this, server, EMSESP_COMMAND_SERVICE_PATH, securityManager, AuthenticationPredicates::IS_AUTHENTICATED) - , _fsPersistence(WebCommands::read, WebCommands::update, this, fs, EMSESP_COMMAND_FILE) { + : _httpEndpoint(WebCommands::read, WebCommands::update, this, server, EMSESP_COMMANDS_SERVICE_PATH, securityManager, AuthenticationPredicates::IS_AUTHENTICATED) + , _fsPersistence(WebCommands::read, WebCommands::update, this, fs, EMSESP_COMMANDS_FILE) { } void WebCommandService::begin() { @@ -67,14 +67,14 @@ StateUpdateResult WebCommands::update(JsonObject root, WebCommands & webCommands strlcpy(ci.name, item["name"].as(), sizeof(ci.name)); webCommands.commandItems.push_back(ci); - if (webCommands.commandItems.back().name[0] != '\0') { - Command::add( - EMSdevice::DeviceType::COMMAND, - webCommands.commandItems.back().name, - [](const char * value, const int8_t id) { return EMSESP::webCommandService.executeCommand(value); }, - FL_(command_cmd), - CommandFlag::ADMIN_ONLY); - } + Command::add( + EMSdevice::DeviceType::COMMAND, + webCommands.commandItems.back().name, + [name = std::string(webCommands.commandItems.back().name)](const char * value, const int8_t id) { + return EMSESP::webCommandService.executeCommand(name.c_str(), value); // value is optional + }, + FL_(command_cmd), + CommandFlag::ADMIN_ONLY); } return StateUpdateResult::CHANGED; } @@ -94,14 +94,15 @@ const CommandItem * WebCommandService::find(const char * name) { } // execute a named command — looks up by name and runs it -// called from console 'call commands ', API/MQTT, web UI -bool WebCommandService::executeCommand(const char * name) { +bool WebCommandService::executeCommand(const char * name, const char * value) { const CommandItem * ci = find(name); if (!ci) { EMSESP::logger().warning("Command '%s' not found", name ? name : ""); return false; } - return executeCommand(ci->name, std::string(ci->cmd.c_str()), std::string(ci->value.c_str())); + // if there is a value use it, otherwise use the command's default value + std::string cmd_value = value ? value : ci->value.c_str(); + return executeCommand(ci->name, std::string(ci->cmd.c_str()), cmd_value); } // execute a command with explicit cmd and value strings @@ -231,22 +232,22 @@ std::string WebCommandService::get_metrics_prometheus() { } void WebCommandService::get_value_json(JsonObject output, const CommandItem & ci) { - output["name"] = (const char *)ci.name; - output["fullname"] = (const char *)ci.name; - output["type"] = "command"; - output["command"] = ci.cmd; - output["cmd_data"] = ci.value; - bool hasName = ci.name[0] != '\0'; - output["readable"] = hasName; - output["writeable"] = hasName; - output["visible"] = hasName; + output["name"] = (const char *)ci.name; + // output["fullname"] = (const char *)ci.name; + // output["type"] = "command"; + output["command"] = ci.cmd; + output["value"] = ci.value; + // bool hasName = ci.name[0] != '\0'; + // output["readable"] = hasName; + // output["writeable"] = hasName; + // output["visible"] = hasName; } void WebCommandService::publish(const bool force) { if (!Mqtt::enabled() || commandItems_->empty()) { return; } - if (force && !EMSESP::mqtt_.get_publish_onchange(0)) { + if (force && !EMSESP::mqtt_.get_publish_onchange(EMSdevice::DeviceType::SYSTEM)) { return; } @@ -278,21 +279,30 @@ void WebCommandService::load_test_data() { auto ci = CommandItem(); ci.cmd = "system/fetch"; ci.value = "10"; - strcpy(ci.name, "test_cmd1"); + strcpy(ci.name, "fetch_values"); webCommands.commandItems.push_back(ci); ci = CommandItem(); ci.cmd = "system/message"; ci.value = "hello"; - strcpy(ci.name, "test_cmd2"); + strcpy(ci.name, "send_message"); webCommands.commandItems.push_back(ci); + ci = CommandItem(); + ci.cmd = "system/message"; + ci.value = "{\"url\":\"http://emsesp.org/versions.json\"}"; + strcpy(ci.name, "get_versions"); + webCommands.commandItems.push_back(ci); + + // manually add the commands for (const auto & item : webCommands.commandItems) { if (item.name[0] != '\0') { Command::add( EMSdevice::DeviceType::COMMAND, item.name, - [](const char * value, const int8_t id) { return EMSESP::webCommandService.executeCommand(value); }, + [name = std::string(item.name)](const char * value, const int8_t id) { + return EMSESP::webCommandService.executeCommand(name.c_str(), value); + }, FL_(command_cmd), CommandFlag::ADMIN_ONLY); } diff --git a/src/web/WebCommandService.h b/src/web/WebCommandService.h index 563a4ed50..c4d54cbf4 100644 --- a/src/web/WebCommandService.h +++ b/src/web/WebCommandService.h @@ -21,8 +21,8 @@ #ifndef WebCommandService_h #define WebCommandService_h -#define EMSESP_COMMAND_FILE "/config/emsespCommands.json" -#define EMSESP_COMMAND_SERVICE_PATH "/rest/commands" // GET and POST +#define EMSESP_COMMANDS_FILE "/config/emsespCommands.json" +#define EMSESP_COMMANDS_SERVICE_PATH "/rest/commands" // GET and POST namespace emsesp { @@ -50,7 +50,7 @@ class WebCommandService : public StatefulService { bool get_value_info(JsonObject output, const char * cmd); void get_value_json(JsonObject output, const CommandItem & commandItem); - bool executeCommand(const char * name); + bool executeCommand(const char * name, const char * value = nullptr); bool executeCommand(const char * name, const std::string & cmd, const std::string & value); const CommandItem * find(const char * name); From 96e3fdc3236fa01b1c40f04fa9c82091e5e50588 Mon Sep 17 00:00:00 2001 From: proddy Date: Mon, 8 Jun 2026 20:42:42 +0200 Subject: [PATCH 10/44] use EMSdevice::DeviceType::SYSTEM --- src/core/analogsensor.cpp | 4 ++-- src/core/temperaturesensor.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/analogsensor.cpp b/src/core/analogsensor.cpp index 170399e85..77c88a093 100644 --- a/src/core/analogsensor.cpp +++ b/src/core/analogsensor.cpp @@ -25,7 +25,7 @@ uuid::log::Logger AnalogSensor::logger_{F_(analogsensor), uuid::log::Facility std::vector AnalogSensor::exclude_types_; #ifndef EMSESP_STANDALONE -portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED; +portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED; volatile unsigned long AnalogSensor::edge[] = {0, 0, 0}; volatile unsigned long AnalogSensor::edgecnt[] = {0, 0, 0}; @@ -671,7 +671,7 @@ void AnalogSensor::publish_values(const bool force) { publish_sensor(sensor); } return; - } else if (!EMSESP::mqtt_.get_publish_onchange(0)) { + } else if (!EMSESP::mqtt_.get_publish_onchange(EMSdevice::DeviceType::SYSTEM)) { return; // wait for first time period } } diff --git a/src/core/temperaturesensor.cpp b/src/core/temperaturesensor.cpp index 493db0da2..437aac353 100644 --- a/src/core/temperaturesensor.cpp +++ b/src/core/temperaturesensor.cpp @@ -489,7 +489,7 @@ void TemperatureSensor::publish_values(const bool force) { publish_sensor(sensor); } return; - } else if (!EMSESP::mqtt_.get_publish_onchange(0)) { + } else if (!EMSESP::mqtt_.get_publish_onchange(EMSdevice::DeviceType::SYSTEM)) { return; // wait for first time period } } From 0d146013853ed58cfda36771b3753277a7977716 Mon Sep 17 00:00:00 2001 From: proddy Date: Mon, 8 Jun 2026 20:43:03 +0200 Subject: [PATCH 11/44] optimize --- src/web/WebSchedulerService.cpp | 82 ++++++++++++++++----------------- 1 file changed, 41 insertions(+), 41 deletions(-) diff --git a/src/web/WebSchedulerService.cpp b/src/web/WebSchedulerService.cpp index 049eaa404..4741e3344 100644 --- a/src/web/WebSchedulerService.cpp +++ b/src/web/WebSchedulerService.cpp @@ -86,37 +86,39 @@ StateUpdateResult WebScheduler::update(JsonObject root, WebScheduler & webSchedu auto scheduleItems = root["schedule"].as(); for (const JsonObject schedule : scheduleItems) { - auto si = ScheduleItem(); - si.active = schedule["active"]; - si.flags = schedule["flags"]; - si.time = schedule["time"].as(); - si.cmd_name = schedule["cmd_name"].as(); + // create each schedule item, overwriting any previous settings + // ignore the id (as this is only used in the web for table rendering) + auto si = ScheduleItem(); + si.active = schedule["active"]; + si.flags = schedule["flags"]; + si.time = schedule["time"].as(); + si.cmd_name = schedule["cmd_name"].as(); strlcpy(si.name, schedule["name"].as(), sizeof(si.name)); + // calculated elapsed minutes si.elapsed_min = Helpers::string2minutes(si.time.c_str()); si.retry_cnt = 0xFF; webScheduler.scheduleItems.push_back(si); - if (webScheduler.scheduleItems.back().name[0] != '\0') { - char key[sizeof(webScheduler.scheduleItems.back().name) + 2]; - snprintf(key, sizeof(key), "s:%s", webScheduler.scheduleItems.back().name); - if (EMSESP::nvs_.isKey(key)) { - webScheduler.scheduleItems.back().active = EMSESP::nvs_.getBool(key); - } - Command::add( - EMSdevice::DeviceType::SCHEDULER, - webScheduler.scheduleItems.back().name, - [webScheduler](const char * value, const int8_t id) { - return EMSESP::webSchedulerService.command_setvalue(value, id, webScheduler.scheduleItems.back().name); - }, - FL_(schedule_cmd), - CommandFlag::ADMIN_ONLY); + char key[sizeof(webScheduler.scheduleItems.back().name) + 2]; + snprintf(key, sizeof(key), "s:%s", webScheduler.scheduleItems.back().name); + if (EMSESP::nvs_.isKey(key)) { + webScheduler.scheduleItems.back().active = EMSESP::nvs_.getBool(key); } + Command::add( + EMSdevice::DeviceType::SCHEDULER, + webScheduler.scheduleItems.back().name, + [name = std::string(webScheduler.scheduleItems.back().name)](const char * value, const int8_t id) { + return EMSESP::webSchedulerService.command_setvalue(value, id, name.c_str()); + }, + FL_(schedule_cmd), + CommandFlag::ADMIN_ONLY); } return StateUpdateResult::CHANGED; } // set active by api command +// value is a boolean to enable/disable the schedule item bool WebSchedulerService::command_setvalue(const char * value, const int8_t id, const char * name) { bool v; if (!Helpers::value2bool(value, v)) { @@ -132,7 +134,7 @@ bool WebSchedulerService::command_setvalue(const char * value, const int8_t id, scheduleItem.active = v; publish_single(name, v); - if (EMSESP::mqtt_.get_publish_onchange(0)) { + if (EMSESP::mqtt_.get_publish_onchange(EMSdevice::DeviceType::SYSTEM)) { publish(); } @@ -211,7 +213,7 @@ void WebSchedulerService::get_value_json(JsonObject output, const ScheduleItem & output["name"] = (const char *)scheduleItem.name; output["fullname"] = (const char *)scheduleItem.name; output["type"] = "boolean"; - Mqtt::add_value_bool(output, "value", scheduleItem.active); + Mqtt::add_value_bool(output, "active", scheduleItem.active); if (scheduleItem.flags == SCHEDULEFLAG_SCHEDULE_CONDITION) { output["condition"] = scheduleItem.time; } else if (scheduleItem.flags == SCHEDULEFLAG_SCHEDULE_ONCHANGE) { @@ -221,11 +223,11 @@ void WebSchedulerService::get_value_json(JsonObject output, const ScheduleItem & } else { output["time"] = scheduleItem.time; } - output["cmd_name"] = scheduleItem.cmd_name; - bool hasName = scheduleItem.name[0] != '\0'; - output["readable"] = hasName; - output["writeable"] = hasName; - output["visible"] = hasName; + output["cmd_name"] = scheduleItem.cmd_name; + // bool hasName = scheduleItem.name[0] != '\0'; + // output["readable"] = hasName; + // output["writeable"] = hasName; + // output["visible"] = hasName; } // publish single value @@ -256,7 +258,7 @@ void WebSchedulerService::publish(const bool force) { publish_single(scheduleItem.name, scheduleItem.active); } return; - } else if (!EMSESP::mqtt_.get_publish_onchange(0)) { + } else if (!EMSESP::mqtt_.get_publish_onchange(EMSdevice::DeviceType::SYSTEM)) { return; // wait for first time period } } @@ -282,7 +284,6 @@ void WebSchedulerService::publish(const bool force) { snprintf(val_obj, sizeof(val_obj), "value_json['%s']", scheduleItem.name); snprintf(val_cond, sizeof(val_cond), "%s is defined", val_obj); - // Optimized: use stack buffer instead of string concatenation to avoid heap allocations char val_tpl[150]; if (Mqtt::discovery_type() == Mqtt::discoveryType::HOMEASSISTANT) { snprintf(val_tpl, sizeof(val_tpl), "{{%s if %s}}", val_obj, val_cond); @@ -296,7 +297,7 @@ void WebSchedulerService::publish(const bool force) { config["uniq_id"] = uniq_s; config["name"] = (const char *)scheduleItem.name; - // Optimized: use stack buffer instead of string concatenation + char def_ent_id[80]; snprintf(def_ent_id, sizeof(def_ent_id), "switch.%s", uniq_s); config["def_ent_id"] = def_ent_id; @@ -341,8 +342,7 @@ bool WebSchedulerService::runScheduleCommand(const ScheduleItem & si) { return EMSESP::webCommandService.executeCommand(si.cmd_name.c_str()); } -// called from emsesp.cpp on every entity-change -// queue schedules to be handled executed in scheduler-loop +// queue schedules to be handled executed in WebSchedulerService::loop() called from emsesp.cpp bool WebSchedulerService::onChange(const char * cmd) { for (ScheduleItem & scheduleItem : *scheduleItems_) { if (scheduleItem.active && scheduleItem.flags == SCHEDULEFLAG_SCHEDULE_ONCHANGE && Helpers::toLower(scheduleItem.time.c_str()) == Helpers::toLower(cmd)) { @@ -462,22 +462,22 @@ void WebSchedulerService::load_test_data() { update([&](WebScheduler & webScheduler) { webScheduler.scheduleItems.clear(); - auto si = ScheduleItem(); - si.active = true; - si.flags = 1; // day schedule - si.time = "12:00"; - si.cmd_name = "test_cmd1"; + auto si = ScheduleItem(); + si.active = true; + si.flags = 1; // day schedule + si.time = "12:00"; + si.cmd_name = "fetch_values"; strcpy(si.name, "test_scheduler1"); si.elapsed_min = 0; si.retry_cnt = 0xFF; webScheduler.scheduleItems.push_back(si); - si = ScheduleItem(); - si.active = true; - si.flags = SCHEDULEFLAG_SCHEDULE_TIMER; - si.time = "01:00"; - si.cmd_name = "test_cmd2"; + si = ScheduleItem(); + si.active = true; + si.flags = SCHEDULEFLAG_SCHEDULE_TIMER; + si.time = "01:00"; + si.cmd_name = "send_message"; strcpy(si.name, "test_scheduler2"); si.elapsed_min = 60; si.retry_cnt = 0xFF; From e53aaffd4d87703517bd364219148f32ac69a384 Mon Sep 17 00:00:00 2001 From: proddy Date: Mon, 8 Jun 2026 20:43:11 +0200 Subject: [PATCH 12/44] add comment --- src/web/WebSchedulerService.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/web/WebSchedulerService.h b/src/web/WebSchedulerService.h index 4ee03e0c3..cf2e74ce4 100644 --- a/src/web/WebSchedulerService.h +++ b/src/web/WebSchedulerService.h @@ -51,7 +51,7 @@ namespace emsesp { class ScheduleItem { public: - boolean active; + boolean active; // on or off uint8_t flags; // bit flags, see SCHEDULEFLAG_* defines uint16_t elapsed_min; // total mins from 00:00 stringPSRAM time; // HH:MM From 064548316e5d59da7e5c56378ab35ed50d5d3dc8 Mon Sep 17 00:00:00 2001 From: proddy Date: Mon, 8 Jun 2026 20:43:27 +0200 Subject: [PATCH 13/44] dont show unused json elements --- src/web/WebCustomEntityService.cpp | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/web/WebCustomEntityService.cpp b/src/web/WebCustomEntityService.cpp index 416091c19..b8aa024e1 100644 --- a/src/web/WebCustomEntityService.cpp +++ b/src/web/WebCustomEntityService.cpp @@ -234,7 +234,7 @@ bool WebCustomEntityService::command_setvalue(const char * value, const int8_t i } publish_single(entityItem); - if (EMSESP::mqtt_.get_publish_onchange(0)) { + if (EMSESP::mqtt_.get_publish_onchange(EMSdevice::DeviceType::SYSTEM)) { publish(); } char cmd[COMMAND_MAX_LENGTH]; @@ -415,13 +415,13 @@ std::string WebCustomEntityService::get_metrics_prometheus() { // build the json for specific entity void WebCustomEntityService::get_value_json(JsonObject output, CustomEntityItem const & entity) { - output["name"] = (const char *)entity.name; - output["fullname"] = (const char *)entity.name; - output["storage"] = entity.ram == 1 ? "ram" : entity.ram == 2 ? "nvs" : "ems"; - output["type"] = entity.value_type == DeviceValueType::BOOL ? "boolean" : entity.value_type == DeviceValueType::STRING ? "string" : F_(number); - output["readable"] = true; + output["name"] = (const char *)entity.name; + output["fullname"] = (const char *)entity.name; + output["storage"] = entity.ram == 1 ? "ram" : entity.ram == 2 ? "nvs" : "ems"; + output["type"] = entity.value_type == DeviceValueType::BOOL ? "boolean" : entity.value_type == DeviceValueType::STRING ? "string" : F_(number); + // output["readable"] = true; output["writeable"] = entity.writeable; - output["visible"] = true; + // output["visible"] = true; if (entity.ram == 0) { output["device_id"] = Helpers::hextoa(entity.device_id); @@ -470,7 +470,7 @@ void WebCustomEntityService::publish(const bool force) { publish_single(entityItem); } return; - } else if (!EMSESP::mqtt_.get_publish_onchange(0)) { + } else if (!EMSESP::mqtt_.get_publish_onchange(EMSdevice::DeviceType::SYSTEM)) { return; // wait for first time period } } @@ -729,7 +729,7 @@ bool WebCustomEntityService::get_value(const std::shared_ptr & t entity.data = data.c_str(); if (Mqtt::publish_single()) { publish_single(entity); - } else if (EMSESP::mqtt_.get_publish_onchange(0)) { + } else if (EMSESP::mqtt_.get_publish_onchange(EMSdevice::DeviceType::SYSTEM)) { has_change = true; } char cmd[COMMAND_MAX_LENGTH]; @@ -751,7 +751,7 @@ bool WebCustomEntityService::get_value(const std::shared_ptr & t entity.value = value; if (Mqtt::publish_single()) { publish_single(entity); - } else if (EMSESP::mqtt_.get_publish_onchange(0)) { + } else if (EMSESP::mqtt_.get_publish_onchange(EMSdevice::DeviceType::SYSTEM)) { has_change = true; } char cmd[COMMAND_MAX_LENGTH]; From 2102180c464fa55e3d04de139f6998da37c8dc00 Mon Sep 17 00:00:00 2001 From: proddy Date: Mon, 8 Jun 2026 20:43:42 +0200 Subject: [PATCH 14/44] add commands to system backup --- src/core/system.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/core/system.cpp b/src/core/system.cpp index 2815fa28d..6e576080b 100644 --- a/src/core/system.cpp +++ b/src/core/system.cpp @@ -1592,6 +1592,7 @@ static const std::pair SECTION_MAP[] = { {NTP_SETTINGS_FILE, "NTP"}, {SECURITY_SETTINGS_FILE, "Security"}, {EMSESP_SETTINGS_FILE, "Settings"}, + {EMSESP_COMMANDS_FILE, "Commands"}, {EMSESP_SCHEDULER_FILE, "Schedule"}, {EMSESP_CUSTOMIZATION_FILE, "Customizations"}, {EMSESP_CUSTOMENTITY_FILE, "Entities"}, @@ -1667,6 +1668,8 @@ void System::exportSystemBackup(JsonObject output) { exportSettings("settings", SECURITY_SETTINGS_FILE, node); exportSettings("settings", EMSESP_SETTINGS_FILE, node); + node = nodes.add(); + exportSettings("commands", EMSESP_COMMANDS_FILE, node); node = nodes.add(); exportSettings("schedule", EMSESP_SCHEDULER_FILE, node); node = nodes.add(); From afee7246c6ed2c592519b08834ab3712fdc72280 Mon Sep 17 00:00:00 2001 From: proddy Date: Mon, 8 Jun 2026 20:44:00 +0200 Subject: [PATCH 15/44] prevent STA warning --- src/core/network.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/network.cpp b/src/core/network.cpp index 90ae94d01..bf1ba7972 100644 --- a/src/core/network.cpp +++ b/src/core/network.cpp @@ -82,7 +82,7 @@ void Network::begin() { WiFi.persistent(false); WiFi.setAutoReconnect(false); WiFi.mode(WIFI_STA); - WiFi.disconnect(true, true); // wipe old settings in NVS + WiFi.disconnect(true); // turn STA off; don't eraseap here (STA netif not started yet -> log_e, and persistent(false) means nothing is in NVS anyway) WiFi.setScanMethod(WIFI_ALL_CHANNEL_SCAN); WiFi.setHostname(hostname_.c_str()); // updates shared default_hostname buffer WiFi.enableSTA(true); // creates the STA netif From 9370ae69eca81c5bd5bfe940a43b98f3d3f607f1 Mon Sep 17 00:00:00 2001 From: proddy Date: Mon, 8 Jun 2026 20:44:09 +0200 Subject: [PATCH 16/44] cleanup --- src/core/emsesp.cpp | 26 +++++++++++--------------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/src/core/emsesp.cpp b/src/core/emsesp.cpp index e49c07b00..c536000e9 100644 --- a/src/core/emsesp.cpp +++ b/src/core/emsesp.cpp @@ -51,24 +51,20 @@ uint32_t EMSESP::last_fetch_ = 0; AsyncWebServer webServer(80); #if defined(EMSESP_STANDALONE) -FS dummyFS; -ESP32React EMSESP::esp32React(&webServer, &dummyFS); -WebSettingsService EMSESP::webSettingsService = WebSettingsService(&webServer, &dummyFS, EMSESP::esp32React.getSecurityManager()); -WebCustomizationService EMSESP::webCustomizationService = WebCustomizationService(&webServer, &dummyFS, EMSESP::esp32React.getSecurityManager()); -WebSchedulerService EMSESP::webSchedulerService = WebSchedulerService(&webServer, &dummyFS, EMSESP::esp32React.getSecurityManager()); -WebCommandService EMSESP::webCommandService = WebCommandService(&webServer, &dummyFS, EMSESP::esp32React.getSecurityManager()); -WebCustomEntityService EMSESP::webCustomEntityService = WebCustomEntityService(&webServer, &dummyFS, EMSESP::esp32React.getSecurityManager()); -WebModulesService EMSESP::webModulesService = WebModulesService(&webServer, &dummyFS, EMSESP::esp32React.getSecurityManager()); +FS dummyFS; +auto& fsRef = dummyFS; #else -ESP32React EMSESP::esp32React(&webServer, &LittleFS); -WebSettingsService EMSESP::webSettingsService = WebSettingsService(&webServer, &LittleFS, EMSESP::esp32React.getSecurityManager()); -WebCustomizationService EMSESP::webCustomizationService = WebCustomizationService(&webServer, &LittleFS, EMSESP::esp32React.getSecurityManager()); -WebSchedulerService EMSESP::webSchedulerService = WebSchedulerService(&webServer, &LittleFS, EMSESP::esp32React.getSecurityManager()); -WebCommandService EMSESP::webCommandService = WebCommandService(&webServer, &LittleFS, EMSESP::esp32React.getSecurityManager()); -WebCustomEntityService EMSESP::webCustomEntityService = WebCustomEntityService(&webServer, &LittleFS, EMSESP::esp32React.getSecurityManager()); -WebModulesService EMSESP::webModulesService = WebModulesService(&webServer, &LittleFS, EMSESP::esp32React.getSecurityManager()); +auto& fsRef = LittleFS; #endif +ESP32React EMSESP::esp32React(&webServer, &fsRef); +WebSettingsService EMSESP::webSettingsService = WebSettingsService(&webServer, &fsRef, EMSESP::esp32React.getSecurityManager()); +WebCustomizationService EMSESP::webCustomizationService = WebCustomizationService(&webServer, &fsRef, EMSESP::esp32React.getSecurityManager()); +WebSchedulerService EMSESP::webSchedulerService = WebSchedulerService(&webServer, &fsRef, EMSESP::esp32React.getSecurityManager()); +WebCommandService EMSESP::webCommandService = WebCommandService(&webServer, &fsRef, EMSESP::esp32React.getSecurityManager()); +WebCustomEntityService EMSESP::webCustomEntityService = WebCustomEntityService(&webServer, &fsRef, EMSESP::esp32React.getSecurityManager()); +WebModulesService EMSESP::webModulesService = WebModulesService(&webServer, &fsRef, EMSESP::esp32React.getSecurityManager()); + WebActivityService EMSESP::webActivityService = WebActivityService(&webServer, EMSESP::esp32React.getSecurityManager()); WebStatusService EMSESP::webStatusService = WebStatusService(&webServer, EMSESP::esp32React.getSecurityManager()); WebDataService EMSESP::webDataService = WebDataService(&webServer, EMSESP::esp32React.getSecurityManager()); From 7ee6dcf0e04832e588e4a2a90092eca08728e9aa Mon Sep 17 00:00:00 2001 From: proddy Date: Mon, 8 Jun 2026 20:44:21 +0200 Subject: [PATCH 17/44] call commands can override value --- src/core/command.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/core/command.cpp b/src/core/command.cpp index 264509dfb..359288f9a 100644 --- a/src/core/command.cpp +++ b/src/core/command.cpp @@ -378,7 +378,12 @@ uint8_t Command::call(const uint8_t device_type, const char * command, const cha if (!strcmp(cmd, F_(commands))) { return Command::list(device_type, output); } - if (EMSESP::get_device_value_info(output, cmd, id, device_type)) { // entity = cmd + // for the Commands device, calling a named command executes it (using its stored value) + // rather than returning its definition, so skip the value-info lookup and fall through + // to the registered command function. The list keywords above are still handled. + bool is_named_command = (device_type == EMSdevice::DeviceType::COMMAND) && strcmp(cmd, F_(info)) && strcmp(cmd, F_(values)) + && strcmp(cmd, F_(entities)) && strcmp(cmd, F_(metrics)); + if (!is_named_command && EMSESP::get_device_value_info(output, cmd, id, device_type)) { // entity = cmd LOG_DEBUG("Fetched device entity/attributes for %s/%s (id=%d)", dname, cmd, id); return CommandRet::OK; } From 88d7124874ed09b89eda6189660472c3292b7749 Mon Sep 17 00:00:00 2001 From: proddy Date: Mon, 8 Jun 2026 20:47:54 +0200 Subject: [PATCH 18/44] update --- project-words.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/project-words.txt b/project-words.txt index 8d6209c83..e84ea5537 100644 --- a/project-words.txt +++ b/project-words.txt @@ -1341,4 +1341,5 @@ serialises SPIRAM optimisations IILE -Sumr \ No newline at end of file +Sumr +eraseap \ No newline at end of file From f93b5290ff7614993a301b972c972c7ff6efef58 Mon Sep 17 00:00:00 2001 From: proddy Date: Mon, 8 Jun 2026 20:48:09 +0200 Subject: [PATCH 19/44] add comment --- scripts/generate_test_api.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/scripts/generate_test_api.py b/scripts/generate_test_api.py index d881caa32..c66cbcc85 100644 --- a/scripts/generate_test_api.py +++ b/scripts/generate_test_api.py @@ -6,6 +6,8 @@ Workflow: 2. Extract everything between the START/END "CUT HERE" markers. 3. Write that block to test/test_api/test_api.h. 4. Run `pio run -e native-test -t exec`. + +run with `python3 scripts/generate_test_api.py` """ import subprocess From 7d94dc7cf07d7477ad9974ef7dbe748ee9a2ecf6 Mon Sep 17 00:00:00 2001 From: proddy Date: Mon, 8 Jun 2026 20:48:22 +0200 Subject: [PATCH 20/44] update tests --- test/test_api/test_api.h | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/test/test_api/test_api.h b/test/test_api/test_api.h index c11b7e08e..9efe5727d 100644 --- a/test/test_api/test_api.h +++ b/test/test_api/test_api.h @@ -95,7 +95,7 @@ void test_19() { } void test_20() { - auto expected_response = "[{\"name\":\"test_seltemp\",\"fullname\":\"test_seltemp\",\"storage\":\"ram\",\"type\":\"number\",\"readable\":true,\"writeable\":true,\"visible\":true,\"ent_cat\":\"diagnostic\",\"value\":\"14\"}]"; + auto expected_response = "[{\"name\":\"test_seltemp\",\"fullname\":\"test_seltemp\",\"storage\":\"ram\",\"type\":\"number\",\"writeable\":true,\"ent_cat\":\"diagnostic\",\"value\":\"14\"}]"; TEST_ASSERT_EQUAL_STRING(expected_response, call_url("/api/custom/test_seltemp")); } @@ -105,22 +105,22 @@ void test_21() { } void test_22() { - auto expected_response = "[{\"name\":\"test_custom\",\"fullname\":\"test_custom\",\"storage\":\"ems\",\"type\":\"number\",\"readable\":true,\"writeable\":true,\"visible\":true,\"device_id\":\"0x08\",\"type_id\":\"0x18\",\"offset\":0,\"factor\":1,\"ent_cat\":\"diagnostic\",\"uom\":\"°C\",\"state_class\":\"measurement\",\"device_class\":\"temperature\",\"value\":0}]"; + auto expected_response = "[{\"name\":\"test_custom\",\"fullname\":\"test_custom\",\"storage\":\"ems\",\"type\":\"number\",\"writeable\":true,\"device_id\":\"0x08\",\"type_id\":\"0x18\",\"offset\":0,\"factor\":1,\"ent_cat\":\"diagnostic\",\"uom\":\"°C\",\"state_class\":\"measurement\",\"device_class\":\"temperature\",\"value\":0}]"; TEST_ASSERT_EQUAL_STRING(expected_response, call_url("/api/custom/test_custom")); } void test_23() { - auto expected_response = "[{\"system\":{\"version\":\"dev\",\"uptime\":\"000+00:00:00.000\",\"uptimeSec\":0,\"resetReason\":\"Unknown / Unknown\",\"txpause\":false,\"gpios_allowed\":\"0, 2, 5, 18, 23\",\"gpios_in_use\":\"0, 2, 5, 18, 23\",\"gpios_available\":\"\"},\"network\":{\"network\":\"WiFi\",\"hostname\":\"ems-esp\",\"RSSI\":-23,\"TxPowerSetting\":0,\"staticIP\":false,\"lowBandwidth\":false,\"disableSleep\":true,\"enableMDNS\":true,\"enableCORS\":false},\"ntp\":{\"NTPstatus\":\"disconnected\",\"enabled\":true,\"server\":\"pool.ntp.org\",\"tzLabel\":\"Europe/London\",\"NTPStatus\":\"disconnected\"},\"ap\":{\"provisionMode\":\"always\",\"ssid\":\"ems-esp\"},\"mqtt\":{\"MQTTStatus\":\"disconnected\",\"MQTTPublishes\":0,\"MQTTQueued\":0,\"MQTTPublishFails\":0,\"MQTTReconnects\":0,\"enabled\":true,\"clientID\":\"ems-esp\",\"keepAlive\":60,\"cleanSession\":false,\"entityFormat\":1,\"base\":\"ems-esp\",\"discoveryPrefix\":\"homeassistant\",\"discoveryType\":0,\"nestedFormat\":1,\"haEnabled\":true,\"mqttQos\":0,\"mqttRetain\":false,\"publishTimeHeartbeat\":60,\"publishTimeBoiler\":10,\"publishTimeThermostat\":10,\"publishTimeSolar\":10,\"publishTimeMixer\":10,\"publishTimeWater\":0,\"publishTimeOther\":10,\"publishTimeSensor\":10,\"publishSingle\":false,\"publish2command\":false,\"sendResponse\":false},\"syslog\":{\"enabled\":false},\"modbus\":{\"enabled\":false},\"sensor\":{\"temperatureSensors\":3,\"temperatureSensorReads\":0,\"temperatureSensorFails\":0},\"analog\":{\"enabled\":true,\"analogSensors\":5,\"analogSensorReads\":0,\"analogSensorFails\":0},\"api\":{\"APICalls\":0,\"APIFails\":0},\"bus\":{\"busStatus\":\"connected\",\"busProtocol\":\"Buderus\",\"busTelegramsReceived\":8,\"busReads\":0,\"busWrites\":0,\"busIncompleteTelegrams\":0,\"busReadsFailed\":0,\"busWritesFailed\":0,\"busRxLineQuality\":100,\"busTxLineQuality\":100},\"settings\":{\"boardProfile\":\"S32\",\"locale\":\"en\",\"txMode\":5,\"emsBusID\":73,\"showerTimer\":false,\"showerMinDuration\":180,\"showerAlert\":false,\"hideLed\":false,\"noTokenApi\":false,\"readonlyMode\":false,\"fahrenheit\":false,\"dallasParasite\":false,\"boolFormat\":1,\"boolDashboard\":1,\"enumFormat\":1,\"analogEnabled\":true,\"telnetEnabled\":true,\"maxWebLogBuffer\":25,\"modbusEnabled\":false,\"forceHeatingOff\":false,\"developerMode\":false},\"devices\":[{\"type\":\"boiler\",\"name\":\"My Custom Boiler\",\"deviceID\":\"0x08\",\"productID\":123,\"brand\":\"\",\"version\":\"01.00\",\"entities\":39,\"handlersReceived\":\"0x18\",\"handlersFetched\":\"0x14 0x33\",\"handlersPending\":\"0xBF 0x10 0x11 0xC2 0xC6 0x15 0x1C 0x19 0x1A 0x35 0x34 0x2A 0xD1 0xE3 0xE4 0xE5 0xE9 0x02E0 0x2E 0x3B\"},{\"type\":\"thermostat\",\"name\":\"FW120\",\"deviceID\":\"0x10\",\"productID\":192,\"brand\":\"\",\"version\":\"01.00\",\"entities\":12,\"handlersReceived\":\"0x016F\",\"handlersFetched\":\"0x0170 0x0171\",\"handlersPending\":\"0xA3 0x06 0xA2 0x12 0x13 0x0172 0x0165 0x0168\"},{\"type\":\"temperaturesensor\",\"name\":\"temperaturesensor\",\"entities\":3},{\"type\":\"analogsensor\",\"name\":\"analogsensor\",\"entities\":5},{\"type\":\"scheduler\",\"name\":\"scheduler\",\"entities\":2},{\"type\":\"custom\",\"name\":\"custom\",\"entities\":4}]}]"; + auto expected_response = "[{\"system\":{\"version\":\"dev\",\"uptime\":\"000+00:00:00.000\",\"uptimeSec\":0,\"resetReason\":\"Unknown / Unknown\",\"txpause\":false,\"gpios_allowed\":\"0, 2, 5, 18, 23\",\"gpios_in_use\":\"0, 2, 5, 18, 23\",\"gpios_available\":\"\"},\"network\":{\"network\":\"WiFi\",\"hostname\":\"ems-esp\",\"RSSI\":-23,\"TxPowerSetting\":0,\"staticIP\":false,\"lowBandwidth\":false,\"disableSleep\":true,\"enableMDNS\":true,\"enableCORS\":false},\"ntp\":{\"NTPstatus\":\"disconnected\",\"enabled\":true,\"server\":\"pool.ntp.org\",\"tzLabel\":\"Europe/London\",\"NTPStatus\":\"disconnected\"},\"ap\":{\"provisionMode\":\"always\",\"ssid\":\"ems-esp\"},\"mqtt\":{\"MQTTStatus\":\"disconnected\",\"MQTTPublishes\":0,\"MQTTQueued\":0,\"MQTTPublishFails\":0,\"MQTTReconnects\":0,\"enabled\":true,\"clientID\":\"ems-esp\",\"keepAlive\":60,\"cleanSession\":false,\"entityFormat\":1,\"base\":\"ems-esp\",\"discoveryPrefix\":\"homeassistant\",\"discoveryType\":0,\"nestedFormat\":1,\"haEnabled\":true,\"mqttQos\":0,\"mqttRetain\":false,\"publishTimeHeartbeat\":60,\"publishTimeBoiler\":10,\"publishTimeThermostat\":10,\"publishTimeSolar\":10,\"publishTimeMixer\":10,\"publishTimeWater\":0,\"publishTimeOther\":10,\"publishTimeSensor\":10,\"publishSingle\":false,\"publish2command\":false,\"sendResponse\":false},\"syslog\":{\"enabled\":false},\"modbus\":{\"enabled\":false},\"sensor\":{\"temperatureSensors\":3,\"temperatureSensorReads\":0,\"temperatureSensorFails\":0},\"analog\":{\"enabled\":true,\"analogSensors\":5,\"analogSensorReads\":0,\"analogSensorFails\":0},\"api\":{\"APICalls\":0,\"APIFails\":0},\"bus\":{\"busStatus\":\"connected\",\"busProtocol\":\"Buderus\",\"busTelegramsReceived\":8,\"busReads\":0,\"busWrites\":0,\"busIncompleteTelegrams\":0,\"busReadsFailed\":0,\"busWritesFailed\":0,\"busRxLineQuality\":100,\"busTxLineQuality\":100},\"settings\":{\"boardProfile\":\"S32\",\"locale\":\"en\",\"txMode\":5,\"emsBusID\":73,\"showerTimer\":false,\"showerMinDuration\":180,\"showerAlert\":false,\"hideLed\":false,\"noTokenApi\":false,\"readonlyMode\":false,\"fahrenheit\":false,\"dallasParasite\":false,\"boolFormat\":1,\"boolDashboard\":1,\"enumFormat\":1,\"analogEnabled\":true,\"telnetEnabled\":true,\"maxWebLogBuffer\":25,\"modbusEnabled\":false,\"forceHeatingOff\":false,\"developerMode\":false},\"devices\":[{\"type\":\"boiler\",\"name\":\"My Custom Boiler\",\"deviceID\":\"0x08\",\"productID\":123,\"brand\":\"\",\"version\":\"01.00\",\"entities\":39,\"handlersReceived\":\"0x18\",\"handlersFetched\":\"0x14 0x33\",\"handlersPending\":\"0xBF 0x10 0x11 0xC2 0xC6 0x15 0x1C 0x19 0x1A 0x35 0x34 0x2A 0xD1 0xE3 0xE4 0xE5 0xE9 0x02E0 0x2E 0x3B\"},{\"type\":\"thermostat\",\"name\":\"FW120\",\"deviceID\":\"0x10\",\"productID\":192,\"brand\":\"\",\"version\":\"01.00\",\"entities\":12,\"handlersReceived\":\"0x016F\",\"handlersFetched\":\"0x0170 0x0171\",\"handlersPending\":\"0xA3 0x06 0xA2 0x12 0x13 0x0172 0x0165 0x0168\"},{\"type\":\"temperaturesensor\",\"name\":\"temperaturesensor\",\"entities\":3},{\"type\":\"analogsensor\",\"name\":\"analogsensor\",\"entities\":5},{\"type\":\"scheduler\",\"name\":\"scheduler\",\"entities\":2},{\"type\":\"commands\",\"name\":\"commands\",\"entities\":3},{\"type\":\"custom\",\"name\":\"custom\",\"entities\":4}]}]"; TEST_ASSERT_EQUAL_STRING(expected_response, call_url("/api/system")); } void test_24() { - auto expected_response = "[{\"system\":{\"version\":\"dev\",\"uptime\":\"000+00:00:00.000\",\"uptimeSec\":0,\"resetReason\":\"Unknown / Unknown\",\"txpause\":false,\"gpios_allowed\":\"0, 2, 5, 18, 23\",\"gpios_in_use\":\"0, 2, 5, 18, 23\",\"gpios_available\":\"\"},\"network\":{\"network\":\"WiFi\",\"hostname\":\"ems-esp\",\"RSSI\":-23,\"TxPowerSetting\":0,\"staticIP\":false,\"lowBandwidth\":false,\"disableSleep\":true,\"enableMDNS\":true,\"enableCORS\":false},\"ntp\":{\"NTPstatus\":\"disconnected\",\"enabled\":true,\"server\":\"pool.ntp.org\",\"tzLabel\":\"Europe/London\",\"NTPStatus\":\"disconnected\"},\"ap\":{\"provisionMode\":\"always\",\"ssid\":\"ems-esp\"},\"mqtt\":{\"MQTTStatus\":\"disconnected\",\"MQTTPublishes\":0,\"MQTTQueued\":0,\"MQTTPublishFails\":0,\"MQTTReconnects\":0,\"enabled\":true,\"clientID\":\"ems-esp\",\"keepAlive\":60,\"cleanSession\":false,\"entityFormat\":1,\"base\":\"ems-esp\",\"discoveryPrefix\":\"homeassistant\",\"discoveryType\":0,\"nestedFormat\":1,\"haEnabled\":true,\"mqttQos\":0,\"mqttRetain\":false,\"publishTimeHeartbeat\":60,\"publishTimeBoiler\":10,\"publishTimeThermostat\":10,\"publishTimeSolar\":10,\"publishTimeMixer\":10,\"publishTimeWater\":0,\"publishTimeOther\":10,\"publishTimeSensor\":10,\"publishSingle\":false,\"publish2command\":false,\"sendResponse\":false},\"syslog\":{\"enabled\":false},\"modbus\":{\"enabled\":false},\"sensor\":{\"temperatureSensors\":3,\"temperatureSensorReads\":0,\"temperatureSensorFails\":0},\"analog\":{\"enabled\":true,\"analogSensors\":5,\"analogSensorReads\":0,\"analogSensorFails\":0},\"api\":{\"APICalls\":0,\"APIFails\":0},\"bus\":{\"busStatus\":\"connected\",\"busProtocol\":\"Buderus\",\"busTelegramsReceived\":8,\"busReads\":0,\"busWrites\":0,\"busIncompleteTelegrams\":0,\"busReadsFailed\":0,\"busWritesFailed\":0,\"busRxLineQuality\":100,\"busTxLineQuality\":100},\"settings\":{\"boardProfile\":\"S32\",\"locale\":\"en\",\"txMode\":5,\"emsBusID\":73,\"showerTimer\":false,\"showerMinDuration\":180,\"showerAlert\":false,\"hideLed\":false,\"noTokenApi\":false,\"readonlyMode\":false,\"fahrenheit\":false,\"dallasParasite\":false,\"boolFormat\":1,\"boolDashboard\":1,\"enumFormat\":1,\"analogEnabled\":true,\"telnetEnabled\":true,\"maxWebLogBuffer\":25,\"modbusEnabled\":false,\"forceHeatingOff\":false,\"developerMode\":false},\"devices\":[{\"type\":\"boiler\",\"name\":\"My Custom Boiler\",\"deviceID\":\"0x08\",\"productID\":123,\"brand\":\"\",\"version\":\"01.00\",\"entities\":39,\"handlersReceived\":\"0x18\",\"handlersFetched\":\"0x14 0x33\",\"handlersPending\":\"0xBF 0x10 0x11 0xC2 0xC6 0x15 0x1C 0x19 0x1A 0x35 0x34 0x2A 0xD1 0xE3 0xE4 0xE5 0xE9 0x02E0 0x2E 0x3B\"},{\"type\":\"thermostat\",\"name\":\"FW120\",\"deviceID\":\"0x10\",\"productID\":192,\"brand\":\"\",\"version\":\"01.00\",\"entities\":12,\"handlersReceived\":\"0x016F\",\"handlersFetched\":\"0x0170 0x0171\",\"handlersPending\":\"0xA3 0x06 0xA2 0x12 0x13 0x0172 0x0165 0x0168\"},{\"type\":\"temperaturesensor\",\"name\":\"temperaturesensor\",\"entities\":3},{\"type\":\"analogsensor\",\"name\":\"analogsensor\",\"entities\":5},{\"type\":\"scheduler\",\"name\":\"scheduler\",\"entities\":2},{\"type\":\"custom\",\"name\":\"custom\",\"entities\":4}]}]"; + auto expected_response = "[{\"system\":{\"version\":\"dev\",\"uptime\":\"000+00:00:00.000\",\"uptimeSec\":0,\"resetReason\":\"Unknown / Unknown\",\"txpause\":false,\"gpios_allowed\":\"0, 2, 5, 18, 23\",\"gpios_in_use\":\"0, 2, 5, 18, 23\",\"gpios_available\":\"\"},\"network\":{\"network\":\"WiFi\",\"hostname\":\"ems-esp\",\"RSSI\":-23,\"TxPowerSetting\":0,\"staticIP\":false,\"lowBandwidth\":false,\"disableSleep\":true,\"enableMDNS\":true,\"enableCORS\":false},\"ntp\":{\"NTPstatus\":\"disconnected\",\"enabled\":true,\"server\":\"pool.ntp.org\",\"tzLabel\":\"Europe/London\",\"NTPStatus\":\"disconnected\"},\"ap\":{\"provisionMode\":\"always\",\"ssid\":\"ems-esp\"},\"mqtt\":{\"MQTTStatus\":\"disconnected\",\"MQTTPublishes\":0,\"MQTTQueued\":0,\"MQTTPublishFails\":0,\"MQTTReconnects\":0,\"enabled\":true,\"clientID\":\"ems-esp\",\"keepAlive\":60,\"cleanSession\":false,\"entityFormat\":1,\"base\":\"ems-esp\",\"discoveryPrefix\":\"homeassistant\",\"discoveryType\":0,\"nestedFormat\":1,\"haEnabled\":true,\"mqttQos\":0,\"mqttRetain\":false,\"publishTimeHeartbeat\":60,\"publishTimeBoiler\":10,\"publishTimeThermostat\":10,\"publishTimeSolar\":10,\"publishTimeMixer\":10,\"publishTimeWater\":0,\"publishTimeOther\":10,\"publishTimeSensor\":10,\"publishSingle\":false,\"publish2command\":false,\"sendResponse\":false},\"syslog\":{\"enabled\":false},\"modbus\":{\"enabled\":false},\"sensor\":{\"temperatureSensors\":3,\"temperatureSensorReads\":0,\"temperatureSensorFails\":0},\"analog\":{\"enabled\":true,\"analogSensors\":5,\"analogSensorReads\":0,\"analogSensorFails\":0},\"api\":{\"APICalls\":0,\"APIFails\":0},\"bus\":{\"busStatus\":\"connected\",\"busProtocol\":\"Buderus\",\"busTelegramsReceived\":8,\"busReads\":0,\"busWrites\":0,\"busIncompleteTelegrams\":0,\"busReadsFailed\":0,\"busWritesFailed\":0,\"busRxLineQuality\":100,\"busTxLineQuality\":100},\"settings\":{\"boardProfile\":\"S32\",\"locale\":\"en\",\"txMode\":5,\"emsBusID\":73,\"showerTimer\":false,\"showerMinDuration\":180,\"showerAlert\":false,\"hideLed\":false,\"noTokenApi\":false,\"readonlyMode\":false,\"fahrenheit\":false,\"dallasParasite\":false,\"boolFormat\":1,\"boolDashboard\":1,\"enumFormat\":1,\"analogEnabled\":true,\"telnetEnabled\":true,\"maxWebLogBuffer\":25,\"modbusEnabled\":false,\"forceHeatingOff\":false,\"developerMode\":false},\"devices\":[{\"type\":\"boiler\",\"name\":\"My Custom Boiler\",\"deviceID\":\"0x08\",\"productID\":123,\"brand\":\"\",\"version\":\"01.00\",\"entities\":39,\"handlersReceived\":\"0x18\",\"handlersFetched\":\"0x14 0x33\",\"handlersPending\":\"0xBF 0x10 0x11 0xC2 0xC6 0x15 0x1C 0x19 0x1A 0x35 0x34 0x2A 0xD1 0xE3 0xE4 0xE5 0xE9 0x02E0 0x2E 0x3B\"},{\"type\":\"thermostat\",\"name\":\"FW120\",\"deviceID\":\"0x10\",\"productID\":192,\"brand\":\"\",\"version\":\"01.00\",\"entities\":12,\"handlersReceived\":\"0x016F\",\"handlersFetched\":\"0x0170 0x0171\",\"handlersPending\":\"0xA3 0x06 0xA2 0x12 0x13 0x0172 0x0165 0x0168\"},{\"type\":\"temperaturesensor\",\"name\":\"temperaturesensor\",\"entities\":3},{\"type\":\"analogsensor\",\"name\":\"analogsensor\",\"entities\":5},{\"type\":\"scheduler\",\"name\":\"scheduler\",\"entities\":2},{\"type\":\"commands\",\"name\":\"commands\",\"entities\":3},{\"type\":\"custom\",\"name\":\"custom\",\"entities\":4}]}]"; TEST_ASSERT_EQUAL_STRING(expected_response, call_url("/api/system/info")); } void test_25() { - auto expected_response = "[{\"api_data\":\"# HELP emsesp_system_uptimesec uptimeSec\\n# TYPE emsesp_system_uptimesec gauge\\nemsesp_system_uptimesec 0\\n# HELP emsesp_system_txpause txpause\\n# TYPE emsesp_system_txpause gauge\\nemsesp_system_txpause 0\\n# HELP emsesp_system_info info\\n# TYPE emsesp_system_info gauge\\nemsesp_system_info{version=\\\"dev\\\", resetreason=\\\"Unknown / Unknown\\\", gpios_allowed=\\\"0, 2, 5, 18, 23\\\", gpios_in_use=\\\"0, 2, 5, 18, 23\\\"} 1\\n# HELP emsesp_network_rssi RSSI\\n# TYPE emsesp_network_rssi gauge\\nemsesp_network_rssi -23\\n# HELP emsesp_network_txpowersetting TxPowerSetting\\n# TYPE emsesp_network_txpowersetting gauge\\nemsesp_network_txpowersetting 0\\n# HELP emsesp_network_staticip staticIP\\n# TYPE emsesp_network_staticip gauge\\nemsesp_network_staticip 0\\n# HELP emsesp_network_lowbandwidth lowBandwidth\\n# TYPE emsesp_network_lowbandwidth gauge\\nemsesp_network_lowbandwidth 0\\n# HELP emsesp_network_disablesleep disableSleep\\n# TYPE emsesp_network_disablesleep gauge\\nemsesp_network_disablesleep 1\\n# HELP emsesp_network_enablemdns enableMDNS\\n# TYPE emsesp_network_enablemdns gauge\\nemsesp_network_enablemdns 1\\n# HELP emsesp_network_enablecors enableCORS\\n# TYPE emsesp_network_enablecors gauge\\nemsesp_network_enablecors 0\\n# HELP emsesp_network_info info\\n# TYPE emsesp_network_info gauge\\nemsesp_network_info{network=\\\"WiFi\\\", hostname=\\\"ems-esp\\\"} 1\\n# HELP emsesp_ntp_enabled enabled\\n# TYPE emsesp_ntp_enabled gauge\\nemsesp_ntp_enabled 1\\n# HELP emsesp_ntp_info info\\n# TYPE emsesp_ntp_info gauge\\nemsesp_ntp_info{ntpstatus=\\\"disconnected\\\", server=\\\"pool.ntp.org\\\", tzlabel=\\\"Europe/London\\\"} 1\\n# HELP emsesp_ap_info info\\n# TYPE emsesp_ap_info gauge\\nemsesp_ap_info{provisionmode=\\\"always\\\", ssid=\\\"ems-esp\\\"} 1\\n# HELP emsesp_mqtt_mqttpublishes MQTTPublishes\\n# TYPE emsesp_mqtt_mqttpublishes gauge\\nemsesp_mqtt_mqttpublishes 0\\n# HELP emsesp_mqtt_mqttqueued MQTTQueued\\n# TYPE emsesp_mqtt_mqttqueued gauge\\nemsesp_mqtt_mqttqueued 0\\n# HELP emsesp_mqtt_mqttpublishfails MQTTPublishFails\\n# TYPE emsesp_mqtt_mqttpublishfails gauge\\nemsesp_mqtt_mqttpublishfails 0\\n# HELP emsesp_mqtt_mqttreconnects MQTTReconnects\\n# TYPE emsesp_mqtt_mqttreconnects gauge\\nemsesp_mqtt_mqttreconnects 0\\n# HELP emsesp_mqtt_enabled enabled\\n# TYPE emsesp_mqtt_enabled gauge\\nemsesp_mqtt_enabled 1\\n# HELP emsesp_mqtt_keepalive keepAlive\\n# TYPE emsesp_mqtt_keepalive gauge\\nemsesp_mqtt_keepalive 60\\n# HELP emsesp_mqtt_cleansession cleanSession\\n# TYPE emsesp_mqtt_cleansession gauge\\nemsesp_mqtt_cleansession 0\\n# HELP emsesp_mqtt_entityformat entityFormat\\n# TYPE emsesp_mqtt_entityformat gauge\\nemsesp_mqtt_entityformat 1\\n# HELP emsesp_mqtt_discoverytype discoveryType\\n# TYPE emsesp_mqtt_discoverytype gauge\\nemsesp_mqtt_discoverytype 0\\n# HELP emsesp_mqtt_nestedformat nestedFormat\\n# TYPE emsesp_mqtt_nestedformat gauge\\nemsesp_mqtt_nestedformat 1\\n# HELP emsesp_mqtt_haenabled haEnabled\\n# TYPE emsesp_mqtt_haenabled gauge\\nemsesp_mqtt_haenabled 1\\n# HELP emsesp_mqtt_mqttqos mqttQos\\n# TYPE emsesp_mqtt_mqttqos gauge\\nemsesp_mqtt_mqttqos 0\\n# HELP emsesp_mqtt_mqttretain mqttRetain\\n# TYPE emsesp_mqtt_mqttretain gauge\\nemsesp_mqtt_mqttretain 0\\n# HELP emsesp_mqtt_publishtimeheartbeat publishTimeHeartbeat\\n# TYPE emsesp_mqtt_publishtimeheartbeat gauge\\nemsesp_mqtt_publishtimeheartbeat 60\\n# HELP emsesp_mqtt_publishtimeboiler publishTimeBoiler\\n# TYPE emsesp_mqtt_publishtimeboiler gauge\\nemsesp_mqtt_publishtimeboiler 10\\n# HELP emsesp_mqtt_publishtimethermostat publishTimeThermostat\\n# TYPE emsesp_mqtt_publishtimethermostat gauge\\nemsesp_mqtt_publishtimethermostat 10\\n# HELP emsesp_mqtt_publishtimesolar publishTimeSolar\\n# TYPE emsesp_mqtt_publishtimesolar gauge\\nemsesp_mqtt_publishtimesolar 10\\n# HELP emsesp_mqtt_publishtimemixer publishTimeMixer\\n# TYPE emsesp_mqtt_publishtimemixer gauge\\nemsesp_mqtt_publishtimemixer 10\\n# HELP emsesp_mqtt_publishtimewater publishTimeWater\\n# TYPE emsesp_mqtt_publishtimewater gauge\\nemsesp_mqtt_publishtimewater 0\\n# HELP emsesp_mqtt_publishtimeother publishTimeOther\\n# TYPE emsesp_mqtt_publishtimeother gauge\\nemsesp_mqtt_publishtimeother 10\\n# HELP emsesp_mqtt_publishtimesensor publishTimeSensor\\n# TYPE emsesp_mqtt_publishtimesensor gauge\\nemsesp_mqtt_publishtimesensor 10\\n# HELP emsesp_mqtt_publishsingle publishSingle\\n# TYPE emsesp_mqtt_publishsingle gauge\\nemsesp_mqtt_publishsingle 0\\n# HELP emsesp_mqtt_publish2command publish2command\\n# TYPE emsesp_mqtt_publish2command gauge\\nemsesp_mqtt_publish2command 0\\n# HELP emsesp_mqtt_sendresponse sendResponse\\n# TYPE emsesp_mqtt_sendresponse gauge\\nemsesp_mqtt_sendresponse 0\\n# HELP emsesp_mqtt_info info\\n# TYPE emsesp_mqtt_info gauge\\nemsesp_mqtt_info{mqttstatus=\\\"disconnected\\\", clientid=\\\"ems-esp\\\", base=\\\"ems-esp\\\", discoveryprefix=\\\"homeassistant\\\"} 1\\n# HELP emsesp_syslog_enabled enabled\\n# TYPE emsesp_syslog_enabled gauge\\nemsesp_syslog_enabled 0\\n# HELP emsesp_modbus_enabled enabled\\n# TYPE emsesp_modbus_enabled gauge\\nemsesp_modbus_enabled 0\\n# HELP emsesp_sensor_temperaturesensors temperatureSensors\\n# TYPE emsesp_sensor_temperaturesensors gauge\\nemsesp_sensor_temperaturesensors 3\\n# HELP emsesp_sensor_temperaturesensorreads temperatureSensorReads\\n# TYPE emsesp_sensor_temperaturesensorreads gauge\\nemsesp_sensor_temperaturesensorreads 0\\n# HELP emsesp_sensor_temperaturesensorfails temperatureSensorFails\\n# TYPE emsesp_sensor_temperaturesensorfails gauge\\nemsesp_sensor_temperaturesensorfails 0\\n# HELP emsesp_analog_enabled enabled\\n# TYPE emsesp_analog_enabled gauge\\nemsesp_analog_enabled 1\\n# HELP emsesp_analog_analogsensors analogSensors\\n# TYPE emsesp_analog_analogsensors gauge\\nemsesp_analog_analogsensors 5\\n# HELP emsesp_analog_analogsensorreads analogSensorReads\\n# TYPE emsesp_analog_analogsensorreads gauge\\nemsesp_analog_analogsensorreads 0\\n# HELP emsesp_analog_analogsensorfails analogSensorFails\\n# TYPE emsesp_analog_analogsensorfails gauge\\nemsesp_analog_analogsensorfails 0\\n# HELP emsesp_api_apicalls APICalls\\n# TYPE emsesp_api_apicalls gauge\\nemsesp_api_apicalls 0\\n# HELP emsesp_api_apifails APIFails\\n# TYPE emsesp_api_apifails gauge\\nemsesp_api_apifails 0\\n# HELP emsesp_bus_bustelegramsreceived busTelegramsReceived\\n# TYPE emsesp_bus_bustelegramsreceived gauge\\nemsesp_bus_bustelegramsreceived 8\\n# HELP emsesp_bus_busreads busReads\\n# TYPE emsesp_bus_busreads gauge\\nemsesp_bus_busreads 0\\n# HELP emsesp_bus_buswrites busWrites\\n# TYPE emsesp_bus_buswrites gauge\\nemsesp_bus_buswrites 0\\n# HELP emsesp_bus_busincompletetelegrams busIncompleteTelegrams\\n# TYPE emsesp_bus_busincompletetelegrams gauge\\nemsesp_bus_busincompletetelegrams 0\\n# HELP emsesp_bus_busreadsfailed busReadsFailed\\n# TYPE emsesp_bus_busreadsfailed gauge\\nemsesp_bus_busreadsfailed 0\\n# HELP emsesp_bus_buswritesfailed busWritesFailed\\n# TYPE emsesp_bus_buswritesfailed gauge\\nemsesp_bus_buswritesfailed 0\\n# HELP emsesp_bus_busrxlinequality busRxLineQuality\\n# TYPE emsesp_bus_busrxlinequality gauge\\nemsesp_bus_busrxlinequality 100\\n# HELP emsesp_bus_bustxlinequality busTxLineQuality\\n# TYPE emsesp_bus_bustxlinequality gauge\\nemsesp_bus_bustxlinequality 100\\n# HELP emsesp_bus_info info\\n# TYPE emsesp_bus_info gauge\\nemsesp_bus_info{busstatus=\\\"connected\\\", busprotocol=\\\"Buderus\\\"} 1\\n# HELP emsesp_settings_txmode txMode\\n# TYPE emsesp_settings_txmode gauge\\nemsesp_settings_txmode 5\\n# HELP emsesp_settings_emsbusid emsBusID\\n# TYPE emsesp_settings_emsbusid gauge\\nemsesp_settings_emsbusid 73\\n# HELP emsesp_settings_showertimer showerTimer\\n# TYPE emsesp_settings_showertimer gauge\\nemsesp_settings_showertimer 0\\n# HELP emsesp_settings_showerminduration showerMinDuration\\n# TYPE emsesp_settings_showerminduration gauge\\nemsesp_settings_showerminduration 180\\n# HELP emsesp_settings_showeralert showerAlert\\n# TYPE emsesp_settings_showeralert gauge\\nemsesp_settings_showeralert 0\\n# HELP emsesp_settings_hideled hideLed\\n# TYPE emsesp_settings_hideled gauge\\nemsesp_settings_hideled 0\\n# HELP emsesp_settings_notokenapi noTokenApi\\n# TYPE emsesp_settings_notokenapi gauge\\nemsesp_settings_notokenapi 0\\n# HELP emsesp_settings_readonlymode readonlyMode\\n# TYPE emsesp_settings_readonlymode gauge\\nemsesp_settings_readonlymode 0\\n# HELP emsesp_settings_fahrenheit fahrenheit\\n# TYPE emsesp_settings_fahrenheit gauge\\nemsesp_settings_fahrenheit 0\\n# HELP emsesp_settings_dallasparasite dallasParasite\\n# TYPE emsesp_settings_dallasparasite gauge\\nemsesp_settings_dallasparasite 0\\n# HELP emsesp_settings_boolformat boolFormat\\n# TYPE emsesp_settings_boolformat gauge\\nemsesp_settings_boolformat 1\\n# HELP emsesp_settings_booldashboard boolDashboard\\n# TYPE emsesp_settings_booldashboard gauge\\nemsesp_settings_booldashboard 1\\n# HELP emsesp_settings_enumformat enumFormat\\n# TYPE emsesp_settings_enumformat gauge\\nemsesp_settings_enumformat 1\\n# HELP emsesp_settings_analogenabled analogEnabled\\n# TYPE emsesp_settings_analogenabled gauge\\nemsesp_settings_analogenabled 1\\n# HELP emsesp_settings_telnetenabled telnetEnabled\\n# TYPE emsesp_settings_telnetenabled gauge\\nemsesp_settings_telnetenabled 1\\n# HELP emsesp_settings_maxweblogbuffer maxWebLogBuffer\\n# TYPE emsesp_settings_maxweblogbuffer gauge\\nemsesp_settings_maxweblogbuffer 25\\n# HELP emsesp_settings_modbusenabled modbusEnabled\\n# TYPE emsesp_settings_modbusenabled gauge\\nemsesp_settings_modbusenabled 0\\n# HELP emsesp_settings_forceheatingoff forceHeatingOff\\n# TYPE emsesp_settings_forceheatingoff gauge\\nemsesp_settings_forceheatingoff 0\\n# HELP emsesp_settings_developermode developerMode\\n# TYPE emsesp_settings_developermode gauge\\nemsesp_settings_developermode 0\\n# HELP emsesp_settings_info info\\n# TYPE emsesp_settings_info gauge\\nemsesp_settings_info{boardprofile=\\\"S32\\\", locale=\\\"en\\\"} 1\\n# HELP emsesp_device_productid productID\\n# TYPE emsesp_device_productid gauge\\nemsesp_device_productid{type=\\\"boiler\\\", name=\\\"My Custom Boiler\\\", deviceid=\\\"0x08\\\", version=\\\"01.00\\\"} 123\\n# HELP emsesp_device_entities entities\\n# TYPE emsesp_device_entities gauge\\nemsesp_device_entities{type=\\\"boiler\\\", name=\\\"My Custom Boiler\\\", deviceid=\\\"0x08\\\", version=\\\"01.00\\\"} 39\\nemsesp_device_productid{type=\\\"thermostat\\\", name=\\\"FW120\\\", deviceid=\\\"0x10\\\", version=\\\"01.00\\\"} 192\\nemsesp_device_entities{type=\\\"thermostat\\\", name=\\\"FW120\\\", deviceid=\\\"0x10\\\", version=\\\"01.00\\\"} 12\\nemsesp_device_entities{type=\\\"temperaturesensor\\\", name=\\\"temperaturesensor\\\"} 3\\nemsesp_device_entities{type=\\\"analogsensor\\\", name=\\\"analogsensor\\\"} 5\\nemsesp_device_entities{type=\\\"scheduler\\\", name=\\\"scheduler\\\"} 2\\nemsesp_device_entities{type=\\\"custom\\\", name=\\\"custom\\\"} 4\\n\"}]"; + auto expected_response = "[{\"api_data\":\"# HELP emsesp_system_uptimesec uptimeSec\\n# TYPE emsesp_system_uptimesec gauge\\nemsesp_system_uptimesec 0\\n# HELP emsesp_system_txpause txpause\\n# TYPE emsesp_system_txpause gauge\\nemsesp_system_txpause 0\\n# HELP emsesp_system_info info\\n# TYPE emsesp_system_info gauge\\nemsesp_system_info{version=\\\"dev\\\", resetreason=\\\"Unknown / Unknown\\\", gpios_allowed=\\\"0, 2, 5, 18, 23\\\", gpios_in_use=\\\"0, 2, 5, 18, 23\\\"} 1\\n# HELP emsesp_network_rssi RSSI\\n# TYPE emsesp_network_rssi gauge\\nemsesp_network_rssi -23\\n# HELP emsesp_network_txpowersetting TxPowerSetting\\n# TYPE emsesp_network_txpowersetting gauge\\nemsesp_network_txpowersetting 0\\n# HELP emsesp_network_staticip staticIP\\n# TYPE emsesp_network_staticip gauge\\nemsesp_network_staticip 0\\n# HELP emsesp_network_lowbandwidth lowBandwidth\\n# TYPE emsesp_network_lowbandwidth gauge\\nemsesp_network_lowbandwidth 0\\n# HELP emsesp_network_disablesleep disableSleep\\n# TYPE emsesp_network_disablesleep gauge\\nemsesp_network_disablesleep 1\\n# HELP emsesp_network_enablemdns enableMDNS\\n# TYPE emsesp_network_enablemdns gauge\\nemsesp_network_enablemdns 1\\n# HELP emsesp_network_enablecors enableCORS\\n# TYPE emsesp_network_enablecors gauge\\nemsesp_network_enablecors 0\\n# HELP emsesp_network_info info\\n# TYPE emsesp_network_info gauge\\nemsesp_network_info{network=\\\"WiFi\\\", hostname=\\\"ems-esp\\\"} 1\\n# HELP emsesp_ntp_enabled enabled\\n# TYPE emsesp_ntp_enabled gauge\\nemsesp_ntp_enabled 1\\n# HELP emsesp_ntp_info info\\n# TYPE emsesp_ntp_info gauge\\nemsesp_ntp_info{ntpstatus=\\\"disconnected\\\", server=\\\"pool.ntp.org\\\", tzlabel=\\\"Europe/London\\\"} 1\\n# HELP emsesp_ap_info info\\n# TYPE emsesp_ap_info gauge\\nemsesp_ap_info{provisionmode=\\\"always\\\", ssid=\\\"ems-esp\\\"} 1\\n# HELP emsesp_mqtt_mqttpublishes MQTTPublishes\\n# TYPE emsesp_mqtt_mqttpublishes gauge\\nemsesp_mqtt_mqttpublishes 0\\n# HELP emsesp_mqtt_mqttqueued MQTTQueued\\n# TYPE emsesp_mqtt_mqttqueued gauge\\nemsesp_mqtt_mqttqueued 0\\n# HELP emsesp_mqtt_mqttpublishfails MQTTPublishFails\\n# TYPE emsesp_mqtt_mqttpublishfails gauge\\nemsesp_mqtt_mqttpublishfails 0\\n# HELP emsesp_mqtt_mqttreconnects MQTTReconnects\\n# TYPE emsesp_mqtt_mqttreconnects gauge\\nemsesp_mqtt_mqttreconnects 0\\n# HELP emsesp_mqtt_enabled enabled\\n# TYPE emsesp_mqtt_enabled gauge\\nemsesp_mqtt_enabled 1\\n# HELP emsesp_mqtt_keepalive keepAlive\\n# TYPE emsesp_mqtt_keepalive gauge\\nemsesp_mqtt_keepalive 60\\n# HELP emsesp_mqtt_cleansession cleanSession\\n# TYPE emsesp_mqtt_cleansession gauge\\nemsesp_mqtt_cleansession 0\\n# HELP emsesp_mqtt_entityformat entityFormat\\n# TYPE emsesp_mqtt_entityformat gauge\\nemsesp_mqtt_entityformat 1\\n# HELP emsesp_mqtt_discoverytype discoveryType\\n# TYPE emsesp_mqtt_discoverytype gauge\\nemsesp_mqtt_discoverytype 0\\n# HELP emsesp_mqtt_nestedformat nestedFormat\\n# TYPE emsesp_mqtt_nestedformat gauge\\nemsesp_mqtt_nestedformat 1\\n# HELP emsesp_mqtt_haenabled haEnabled\\n# TYPE emsesp_mqtt_haenabled gauge\\nemsesp_mqtt_haenabled 1\\n# HELP emsesp_mqtt_mqttqos mqttQos\\n# TYPE emsesp_mqtt_mqttqos gauge\\nemsesp_mqtt_mqttqos 0\\n# HELP emsesp_mqtt_mqttretain mqttRetain\\n# TYPE emsesp_mqtt_mqttretain gauge\\nemsesp_mqtt_mqttretain 0\\n# HELP emsesp_mqtt_publishtimeheartbeat publishTimeHeartbeat\\n# TYPE emsesp_mqtt_publishtimeheartbeat gauge\\nemsesp_mqtt_publishtimeheartbeat 60\\n# HELP emsesp_mqtt_publishtimeboiler publishTimeBoiler\\n# TYPE emsesp_mqtt_publishtimeboiler gauge\\nemsesp_mqtt_publishtimeboiler 10\\n# HELP emsesp_mqtt_publishtimethermostat publishTimeThermostat\\n# TYPE emsesp_mqtt_publishtimethermostat gauge\\nemsesp_mqtt_publishtimethermostat 10\\n# HELP emsesp_mqtt_publishtimesolar publishTimeSolar\\n# TYPE emsesp_mqtt_publishtimesolar gauge\\nemsesp_mqtt_publishtimesolar 10\\n# HELP emsesp_mqtt_publishtimemixer publishTimeMixer\\n# TYPE emsesp_mqtt_publishtimemixer gauge\\nemsesp_mqtt_publishtimemixer 10\\n# HELP emsesp_mqtt_publishtimewater publishTimeWater\\n# TYPE emsesp_mqtt_publishtimewater gauge\\nemsesp_mqtt_publishtimewater 0\\n# HELP emsesp_mqtt_publishtimeother publishTimeOther\\n# TYPE emsesp_mqtt_publishtimeother gauge\\nemsesp_mqtt_publishtimeother 10\\n# HELP emsesp_mqtt_publishtimesensor publishTimeSensor\\n# TYPE emsesp_mqtt_publishtimesensor gauge\\nemsesp_mqtt_publishtimesensor 10\\n# HELP emsesp_mqtt_publishsingle publishSingle\\n# TYPE emsesp_mqtt_publishsingle gauge\\nemsesp_mqtt_publishsingle 0\\n# HELP emsesp_mqtt_publish2command publish2command\\n# TYPE emsesp_mqtt_publish2command gauge\\nemsesp_mqtt_publish2command 0\\n# HELP emsesp_mqtt_sendresponse sendResponse\\n# TYPE emsesp_mqtt_sendresponse gauge\\nemsesp_mqtt_sendresponse 0\\n# HELP emsesp_mqtt_info info\\n# TYPE emsesp_mqtt_info gauge\\nemsesp_mqtt_info{mqttstatus=\\\"disconnected\\\", clientid=\\\"ems-esp\\\", base=\\\"ems-esp\\\", discoveryprefix=\\\"homeassistant\\\"} 1\\n# HELP emsesp_syslog_enabled enabled\\n# TYPE emsesp_syslog_enabled gauge\\nemsesp_syslog_enabled 0\\n# HELP emsesp_modbus_enabled enabled\\n# TYPE emsesp_modbus_enabled gauge\\nemsesp_modbus_enabled 0\\n# HELP emsesp_sensor_temperaturesensors temperatureSensors\\n# TYPE emsesp_sensor_temperaturesensors gauge\\nemsesp_sensor_temperaturesensors 3\\n# HELP emsesp_sensor_temperaturesensorreads temperatureSensorReads\\n# TYPE emsesp_sensor_temperaturesensorreads gauge\\nemsesp_sensor_temperaturesensorreads 0\\n# HELP emsesp_sensor_temperaturesensorfails temperatureSensorFails\\n# TYPE emsesp_sensor_temperaturesensorfails gauge\\nemsesp_sensor_temperaturesensorfails 0\\n# HELP emsesp_analog_enabled enabled\\n# TYPE emsesp_analog_enabled gauge\\nemsesp_analog_enabled 1\\n# HELP emsesp_analog_analogsensors analogSensors\\n# TYPE emsesp_analog_analogsensors gauge\\nemsesp_analog_analogsensors 5\\n# HELP emsesp_analog_analogsensorreads analogSensorReads\\n# TYPE emsesp_analog_analogsensorreads gauge\\nemsesp_analog_analogsensorreads 0\\n# HELP emsesp_analog_analogsensorfails analogSensorFails\\n# TYPE emsesp_analog_analogsensorfails gauge\\nemsesp_analog_analogsensorfails 0\\n# HELP emsesp_api_apicalls APICalls\\n# TYPE emsesp_api_apicalls gauge\\nemsesp_api_apicalls 0\\n# HELP emsesp_api_apifails APIFails\\n# TYPE emsesp_api_apifails gauge\\nemsesp_api_apifails 0\\n# HELP emsesp_bus_bustelegramsreceived busTelegramsReceived\\n# TYPE emsesp_bus_bustelegramsreceived gauge\\nemsesp_bus_bustelegramsreceived 8\\n# HELP emsesp_bus_busreads busReads\\n# TYPE emsesp_bus_busreads gauge\\nemsesp_bus_busreads 0\\n# HELP emsesp_bus_buswrites busWrites\\n# TYPE emsesp_bus_buswrites gauge\\nemsesp_bus_buswrites 0\\n# HELP emsesp_bus_busincompletetelegrams busIncompleteTelegrams\\n# TYPE emsesp_bus_busincompletetelegrams gauge\\nemsesp_bus_busincompletetelegrams 0\\n# HELP emsesp_bus_busreadsfailed busReadsFailed\\n# TYPE emsesp_bus_busreadsfailed gauge\\nemsesp_bus_busreadsfailed 0\\n# HELP emsesp_bus_buswritesfailed busWritesFailed\\n# TYPE emsesp_bus_buswritesfailed gauge\\nemsesp_bus_buswritesfailed 0\\n# HELP emsesp_bus_busrxlinequality busRxLineQuality\\n# TYPE emsesp_bus_busrxlinequality gauge\\nemsesp_bus_busrxlinequality 100\\n# HELP emsesp_bus_bustxlinequality busTxLineQuality\\n# TYPE emsesp_bus_bustxlinequality gauge\\nemsesp_bus_bustxlinequality 100\\n# HELP emsesp_bus_info info\\n# TYPE emsesp_bus_info gauge\\nemsesp_bus_info{busstatus=\\\"connected\\\", busprotocol=\\\"Buderus\\\"} 1\\n# HELP emsesp_settings_txmode txMode\\n# TYPE emsesp_settings_txmode gauge\\nemsesp_settings_txmode 5\\n# HELP emsesp_settings_emsbusid emsBusID\\n# TYPE emsesp_settings_emsbusid gauge\\nemsesp_settings_emsbusid 73\\n# HELP emsesp_settings_showertimer showerTimer\\n# TYPE emsesp_settings_showertimer gauge\\nemsesp_settings_showertimer 0\\n# HELP emsesp_settings_showerminduration showerMinDuration\\n# TYPE emsesp_settings_showerminduration gauge\\nemsesp_settings_showerminduration 180\\n# HELP emsesp_settings_showeralert showerAlert\\n# TYPE emsesp_settings_showeralert gauge\\nemsesp_settings_showeralert 0\\n# HELP emsesp_settings_hideled hideLed\\n# TYPE emsesp_settings_hideled gauge\\nemsesp_settings_hideled 0\\n# HELP emsesp_settings_notokenapi noTokenApi\\n# TYPE emsesp_settings_notokenapi gauge\\nemsesp_settings_notokenapi 0\\n# HELP emsesp_settings_readonlymode readonlyMode\\n# TYPE emsesp_settings_readonlymode gauge\\nemsesp_settings_readonlymode 0\\n# HELP emsesp_settings_fahrenheit fahrenheit\\n# TYPE emsesp_settings_fahrenheit gauge\\nemsesp_settings_fahrenheit 0\\n# HELP emsesp_settings_dallasparasite dallasParasite\\n# TYPE emsesp_settings_dallasparasite gauge\\nemsesp_settings_dallasparasite 0\\n# HELP emsesp_settings_boolformat boolFormat\\n# TYPE emsesp_settings_boolformat gauge\\nemsesp_settings_boolformat 1\\n# HELP emsesp_settings_booldashboard boolDashboard\\n# TYPE emsesp_settings_booldashboard gauge\\nemsesp_settings_booldashboard 1\\n# HELP emsesp_settings_enumformat enumFormat\\n# TYPE emsesp_settings_enumformat gauge\\nemsesp_settings_enumformat 1\\n# HELP emsesp_settings_analogenabled analogEnabled\\n# TYPE emsesp_settings_analogenabled gauge\\nemsesp_settings_analogenabled 1\\n# HELP emsesp_settings_telnetenabled telnetEnabled\\n# TYPE emsesp_settings_telnetenabled gauge\\nemsesp_settings_telnetenabled 1\\n# HELP emsesp_settings_maxweblogbuffer maxWebLogBuffer\\n# TYPE emsesp_settings_maxweblogbuffer gauge\\nemsesp_settings_maxweblogbuffer 25\\n# HELP emsesp_settings_modbusenabled modbusEnabled\\n# TYPE emsesp_settings_modbusenabled gauge\\nemsesp_settings_modbusenabled 0\\n# HELP emsesp_settings_forceheatingoff forceHeatingOff\\n# TYPE emsesp_settings_forceheatingoff gauge\\nemsesp_settings_forceheatingoff 0\\n# HELP emsesp_settings_developermode developerMode\\n# TYPE emsesp_settings_developermode gauge\\nemsesp_settings_developermode 0\\n# HELP emsesp_settings_info info\\n# TYPE emsesp_settings_info gauge\\nemsesp_settings_info{boardprofile=\\\"S32\\\", locale=\\\"en\\\"} 1\\n# HELP emsesp_device_productid productID\\n# TYPE emsesp_device_productid gauge\\nemsesp_device_productid{type=\\\"boiler\\\", name=\\\"My Custom Boiler\\\", deviceid=\\\"0x08\\\", version=\\\"01.00\\\"} 123\\n# HELP emsesp_device_entities entities\\n# TYPE emsesp_device_entities gauge\\nemsesp_device_entities{type=\\\"boiler\\\", name=\\\"My Custom Boiler\\\", deviceid=\\\"0x08\\\", version=\\\"01.00\\\"} 39\\nemsesp_device_productid{type=\\\"thermostat\\\", name=\\\"FW120\\\", deviceid=\\\"0x10\\\", version=\\\"01.00\\\"} 192\\nemsesp_device_entities{type=\\\"thermostat\\\", name=\\\"FW120\\\", deviceid=\\\"0x10\\\", version=\\\"01.00\\\"} 12\\nemsesp_device_entities{type=\\\"temperaturesensor\\\", name=\\\"temperaturesensor\\\"} 3\\nemsesp_device_entities{type=\\\"analogsensor\\\", name=\\\"analogsensor\\\"} 5\\nemsesp_device_entities{type=\\\"scheduler\\\", name=\\\"scheduler\\\"} 2\\nemsesp_device_entities{type=\\\"commands\\\", name=\\\"commands\\\"} 3\\nemsesp_device_entities{type=\\\"custom\\\", name=\\\"custom\\\"} 4\\n\"}]"; TEST_ASSERT_EQUAL_STRING(expected_response, call_url("/api/system/metrics")); } @@ -140,12 +140,12 @@ void test_28() { } void test_29() { - auto expected_response = "[{\"test_scheduler1\":\"on\",\"test_scheduler2\":\"off\"}]"; + auto expected_response = "[{\"test_scheduler1\":\"on\",\"test_scheduler2\":\"on\"}]"; TEST_ASSERT_EQUAL_STRING(expected_response, call_url("/api/scheduler")); } void test_30() { - auto expected_response = "[{\"test_scheduler1\":\"on\",\"test_scheduler2\":\"off\"}]"; + auto expected_response = "[{\"test_scheduler1\":\"on\",\"test_scheduler2\":\"on\"}]"; TEST_ASSERT_EQUAL_STRING(expected_response, call_url("/api/scheduler/info")); } @@ -230,7 +230,7 @@ void test_46() { } void test_47() { - auto expected_response = "[{\"name\":\"test_scheduler2\",\"fullname\":\"test_scheduler2\",\"type\":\"boolean\",\"value\":\"off\",\"command\":\"system/message\",\"cmd_data\":\"20\",\"readable\":true,\"writeable\":true,\"visible\":true}]"; + auto expected_response = "[{\"name\":\"test_scheduler2\",\"fullname\":\"test_scheduler2\",\"type\":\"boolean\",\"active\":\"on\",\"timer\":\"01:00\",\"cmd_name\":\"send_message\"}]"; TEST_ASSERT_EQUAL_STRING(expected_response, call_url("/api/scheduler/test_scheduler2")); } @@ -240,7 +240,7 @@ void test_48() { } void test_49() { - auto expected_response = "[{\"message\":\"no attribute 'val2' in test_scheduler2\"}]"; + auto expected_response = "[{\"message\":\"Command test_scheduler2 failed (Error)\"}]"; TEST_ASSERT_EQUAL_STRING(expected_response, call_url("/api/scheduler/test_scheduler2/val2")); } From 8fb69826f980c143f52dac0405d56e7150ece332 Mon Sep 17 00:00:00 2001 From: proddy Date: Mon, 8 Jun 2026 20:54:43 +0200 Subject: [PATCH 21/44] comments --- src/core/emsesp.cpp | 9 ++++----- src/core/helpers.cpp | 5 +---- src/core/shuntingYard.cpp | 8 +++----- 3 files changed, 8 insertions(+), 14 deletions(-) diff --git a/src/core/emsesp.cpp b/src/core/emsesp.cpp index c536000e9..9753a5d38 100644 --- a/src/core/emsesp.cpp +++ b/src/core/emsesp.cpp @@ -51,13 +51,13 @@ uint32_t EMSESP::last_fetch_ = 0; AsyncWebServer webServer(80); #if defined(EMSESP_STANDALONE) -FS dummyFS; -auto& fsRef = dummyFS; +FS dummyFS; +auto & fsRef = dummyFS; #else -auto& fsRef = LittleFS; +auto & fsRef = LittleFS; #endif -ESP32React EMSESP::esp32React(&webServer, &fsRef); +ESP32React EMSESP::esp32React(&webServer, &fsRef); WebSettingsService EMSESP::webSettingsService = WebSettingsService(&webServer, &fsRef, EMSESP::esp32React.getSecurityManager()); WebCustomizationService EMSESP::webCustomizationService = WebCustomizationService(&webServer, &fsRef, EMSESP::esp32React.getSecurityManager()); WebSchedulerService EMSESP::webSchedulerService = WebSchedulerService(&webServer, &fsRef, EMSESP::esp32React.getSecurityManager()); @@ -919,7 +919,6 @@ std::string EMSESP::pretty_telegram(const std::shared_ptr & tele } } - // Optimized: Use stack buffer and build string once to avoid multiple temporary allocations char buf[250]; if (telegram->operation == Telegram::Operation::RX_READ) { auto pos = snprintf(buf, diff --git a/src/core/helpers.cpp b/src/core/helpers.cpp index 8098f93d8..52d37b50b 100644 --- a/src/core/helpers.cpp +++ b/src/core/helpers.cpp @@ -34,7 +34,6 @@ char * Helpers::hextoa(char * result, const uint8_t value) { } // same as hextoa but uses to a hex std::string -// Optimized: Avoid string concatenation to reduce temporary allocations std::string Helpers::hextoa(const uint8_t value, bool prefix) { if (prefix) { char buf[5]; // "0x" + 2 hex chars + null @@ -60,7 +59,6 @@ char * Helpers::hextoa(char * result, const uint16_t value) { } // same as above but to a hex string -// Optimized: Avoid string concatenation to reduce temporary allocations std::string Helpers::hextoa(const uint16_t value, bool prefix) { if (prefix) { char buf[7]; // "0x" + 4 hex chars + null @@ -114,7 +112,6 @@ char * Helpers::ultostr(char * ptr, uint32_t value, const uint8_t base) { // fast itoa returning a std::string // http://www.strudel.org.uk/itoa/ -// Optimized: Use stack buffer to avoid heap allocation, then create string once std::string Helpers::itoa(int16_t value) { // int16_t max: -32768 to 32767 = max 6 chars + null char buf[8]; @@ -140,7 +137,7 @@ std::string Helpers::itoa(int16_t value) { /* * fast itoa * written by Lukás Chmela, Released under GPLv3. http://www.strudel.org.uk/itoa/ version 0.4 - * optimized for ESP32 + * optimized for ESP32 for EMS-ESP */ char * Helpers::itoa(int32_t value, char * result, const uint8_t base) { // check that the base if valid diff --git a/src/core/shuntingYard.cpp b/src/core/shuntingYard.cpp index 9f833892a..7041ca49f 100644 --- a/src/core/shuntingYard.cpp +++ b/src/core/shuntingYard.cpp @@ -27,7 +27,7 @@ namespace emsesp { -// find tokens - optimized to reduce string allocations +// find tokens std::deque exprToTokens(const std::string & expr) { std::deque tokens; @@ -231,7 +231,7 @@ std::deque exprToTokens(const std::string & expr) { return tokens; } -// sort tokens to RPN form - optimized for memory usage +// sort tokens to RPN form std::deque shuntingYard(const std::deque & tokens) { std::deque queue; std::vector stack; @@ -347,7 +347,6 @@ bool isnum(const std::string & s) { std::string commands(std::string & expr, bool quotes) { auto expr_new = Helpers::toLower(expr); for (uint8_t device = 0; device < EMSdevice::DeviceType::UNKNOWN; device++) { - // Optimized: build string with reserve to avoid temporary allocations std::string d; d.reserve(32); // typical device name length + "/" d = EMSdevice::device_type_2_device_name(device); @@ -374,8 +373,7 @@ std::string commands(std::string & expr, bool quotes) { JsonDocument doc_in; JsonObject output = doc_out.to(); JsonObject input = doc_in.to(); - // Optimized: use stack buffer for small strings to avoid heap allocation - char cmd_s[COMMAND_MAX_LENGTH + 5]; // "api/" prefix + cmd + char cmd_s[COMMAND_MAX_LENGTH + 5]; // "api/" prefix + cmd snprintf(cmd_s, sizeof(cmd_s), "api/%s", cmd); auto return_code = Command::process(cmd_s, true, input, output); From ff90662be1f74d79f4cffcf0f31f4d166ea312c7 Mon Sep 17 00:00:00 2001 From: proddy Date: Mon, 8 Jun 2026 21:04:19 +0200 Subject: [PATCH 22/44] green execute button --- interface/src/app/main/Commands.tsx | 2 +- interface/src/app/main/DevicesDialog.tsx | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/interface/src/app/main/Commands.tsx b/interface/src/app/main/Commands.tsx index b734c6c36..4a20e1c39 100644 --- a/interface/src/app/main/Commands.tsx +++ b/interface/src/app/main/Commands.tsx @@ -131,7 +131,7 @@ const CommandsPage = () => { name: ci.name })) }); - toast.success(LL.UPDATED_OF(LL.COMMANDS(0))); + toast.success(LL.UPDATED_OF(LL.COMMANDS())); } catch (error: unknown) { const message = error instanceof Error ? error.message : String(error); toast.error(message); diff --git a/interface/src/app/main/DevicesDialog.tsx b/interface/src/app/main/DevicesDialog.tsx index 314476024..3b98822d8 100644 --- a/interface/src/app/main/DevicesDialog.tsx +++ b/interface/src/app/main/DevicesDialog.tsx @@ -2,6 +2,7 @@ import { useEffect, useState } from 'react'; import { toast } from 'react-toastify'; import CancelIcon from '@mui/icons-material/Cancel'; +import PlayArrowIcon from '@mui/icons-material/PlayArrow'; import WarningIcon from '@mui/icons-material/Warning'; import { Box, @@ -226,10 +227,12 @@ const DevicesDialog = ({ {LL.CANCEL()} From 4bff05a1c60d3c49a1bfe93d76363f7ba31e2f5e Mon Sep 17 00:00:00 2001 From: proddy Date: Mon, 8 Jun 2026 21:22:59 +0200 Subject: [PATCH 23/44] have to save before executing --- interface/src/app/main/CommandsDialog.tsx | 36 +++++++++++++++++------ 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/interface/src/app/main/CommandsDialog.tsx b/interface/src/app/main/CommandsDialog.tsx index 1d71995cc..ac8dd74ea 100644 --- a/interface/src/app/main/CommandsDialog.tsx +++ b/interface/src/app/main/CommandsDialog.tsx @@ -46,6 +46,7 @@ const CommandsDialog = ({ validator }: CommandsDialogProps) => { const { LL } = useI18nContext(); + const [hasChanges, setHasChanges] = useState(false); const [editItem, setEditItem] = useState(selectedItem); const [fieldErrors, setFieldErrors] = useState(); @@ -62,6 +63,17 @@ const CommandsDialog = ({ } }, [open, selectedItem]); + const hasChanged = (ci: CommandItem) => + ci.id !== ci.o_id || + (ci.name || '') !== (ci.o_name || '') || + ci.cmd !== ci.o_cmd || + ci.value !== ci.o_value || + ci.deleted !== ci.o_deleted; + + useEffect(() => { + setHasChanges(hasChanged(editItem)); + }, [editItem]); + const handleSave = async (itemToSave: CommandItem) => { try { setFieldErrors(undefined); @@ -69,6 +81,8 @@ const CommandsDialog = ({ onSave(itemToSave); } catch (error) { setFieldErrors((error as ValidationError).fieldErrors); + } finally { + setHasChanges(false); } }; @@ -162,15 +176,19 @@ const CommandsDialog = ({ > {LL.CANCEL()} - - {!creating && editItem.cmd !== '' && ( + + {hasChanges && ( + + )} + + {!creating && !hasChanges && editItem.cmd !== '' && (