rename allDevices endpoint to data. improve dallas sensor form

This commit is contained in:
proddy
2021-07-20 13:01:22 +02:00
parent 33adf518ae
commit ba295385ab
13 changed files with 140 additions and 145 deletions

View File

@@ -8,7 +8,7 @@ import { MenuAppBar } from '../components';
import { AuthenticatedRoute } from '../authentication'; import { AuthenticatedRoute } from '../authentication';
import EMSESPStatusController from './EMSESPStatusController'; import EMSESPStatusController from './EMSESPStatusController';
import EMSESPDevicesController from './EMSESPDevicesController'; import EMSESPDataController from './EMSESPDataController';
import EMSESPHelp from './EMSESPHelp'; import EMSESPHelp from './EMSESPHelp';
class EMSESP extends Component<RouteComponentProps> { class EMSESP extends Component<RouteComponentProps> {
@@ -24,18 +24,15 @@ class EMSESP extends Component<RouteComponentProps> {
onChange={(e, path) => this.handleTabChange(path)} onChange={(e, path) => this.handleTabChange(path)}
variant="fullWidth" variant="fullWidth"
> >
<Tab <Tab value={`/${PROJECT_PATH}/data`} label="Devices &amp; Sensors" />
value={`/${PROJECT_PATH}/devices`}
label="Devices &amp; Sensors"
/>
<Tab value={`/${PROJECT_PATH}/status`} label="EMS Status" /> <Tab value={`/${PROJECT_PATH}/status`} label="EMS Status" />
<Tab value={`/${PROJECT_PATH}/help`} label="EMS-ESP Help" /> <Tab value={`/${PROJECT_PATH}/help`} label="EMS-ESP Help" />
</Tabs> </Tabs>
<Switch> <Switch>
<AuthenticatedRoute <AuthenticatedRoute
exact exact
path={`/${PROJECT_PATH}/devices`} path={`/${PROJECT_PATH}/data`}
component={EMSESPDevicesController} component={EMSESPDataController}
/> />
<AuthenticatedRoute <AuthenticatedRoute
exact exact
@@ -47,7 +44,7 @@ class EMSESP extends Component<RouteComponentProps> {
path={`/${PROJECT_PATH}/help`} path={`/${PROJECT_PATH}/help`}
component={EMSESPHelp} component={EMSESPHelp}
/> />
<Redirect to={`/${PROJECT_PATH}/devices`} /> <Redirect to={`/${PROJECT_PATH}/data`} />
</Switch> </Switch>
</MenuAppBar> </MenuAppBar>
); );

View File

@@ -0,0 +1,35 @@
import React, { Component } from 'react';
import {
restController,
RestControllerProps,
RestFormLoader,
SectionContent
} from '../components';
import { ENDPOINT_ROOT } from '../api';
import EMSESPDataForm from './EMSESPDataForm';
import { EMSESPData } from './EMSESPtypes';
export const EMSESP_DATA_ENDPOINT = ENDPOINT_ROOT + 'data';
type EMSESPDataControllerProps = RestControllerProps<EMSESPData>;
class EMSESPDataController extends Component<EMSESPDataControllerProps> {
componentDidMount() {
this.props.loadData();
}
render() {
return (
<SectionContent title="Devices &amp; Sensors">
<RestFormLoader
{...this.props}
render={(formProps) => <EMSESPDataForm {...formProps} />}
/>
</SectionContent>
);
}
}
export default restController(EMSESP_DATA_ENDPOINT, EMSESPDataController);

View File

@@ -40,7 +40,7 @@ import {
import { RestFormProps, FormButton, extractEventValue } from '../components'; import { RestFormProps, FormButton, extractEventValue } from '../components';
import { import {
EMSESPDevices, EMSESPData,
EMSESPDeviceData, EMSESPDeviceData,
Device, Device,
DeviceValue, DeviceValue,
@@ -91,16 +91,16 @@ function compareDevices(a: Device, b: Device) {
return 0; return 0;
} }
interface EMSESPDevicesFormState { interface EMSESPDataFormState {
confirmScanDevices: boolean; confirmScanDevices: boolean;
processing: boolean; processing: boolean;
deviceData?: EMSESPDeviceData; deviceData?: EMSESPDeviceData;
selectedDevice?: number; selectedDevice?: number;
edit_devicevalue?: DeviceValue; edit_devicevalue?: DeviceValue;
edit_sensorname?: Sensor; edit_Sensor?: Sensor;
} }
type EMSESPDevicesFormProps = RestFormProps<EMSESPDevices> & type EMSESPDataFormProps = RestFormProps<EMSESPData> &
AuthenticatedContextProps & AuthenticatedContextProps &
WithWidthProps; WithWidthProps;
@@ -150,16 +150,16 @@ function formatValue(value: any, uom: number, digit: number) {
} }
} }
class EMSESPDevicesForm extends Component< class EMSESPDataForm extends Component<
EMSESPDevicesFormProps, EMSESPDataFormProps,
EMSESPDevicesFormState EMSESPDataFormState
> { > {
state: EMSESPDevicesFormState = { state: EMSESPDataFormState = {
confirmScanDevices: false, confirmScanDevices: false,
processing: false processing: false
}; };
handleValueChange = (name: keyof DeviceValue) => ( handleDeviceValueChange = (name: keyof DeviceValue) => (
event: React.ChangeEvent<HTMLInputElement> event: React.ChangeEvent<HTMLInputElement>
) => { ) => {
this.setState({ this.setState({
@@ -170,11 +170,11 @@ class EMSESPDevicesForm extends Component<
}); });
}; };
cancelEditingValue = () => { cancelEditingDeviceValue = () => {
this.setState({ edit_devicevalue: undefined }); this.setState({ edit_devicevalue: undefined });
}; };
doneEditingValue = () => { doneEditingDeviceValue = () => {
const { edit_devicevalue, selectedDevice } = this.state; const { edit_devicevalue, selectedDevice } = this.state;
redirectingAuthorizedFetch(WRITE_VALUE_ENDPOINT, { redirectingAuthorizedFetch(WRITE_VALUE_ENDPOINT, {
@@ -223,24 +223,24 @@ class EMSESPDevicesForm extends Component<
event: React.ChangeEvent<HTMLInputElement> event: React.ChangeEvent<HTMLInputElement>
) => { ) => {
this.setState({ this.setState({
edit_sensorname: { edit_Sensor: {
...this.state.edit_sensorname!, ...this.state.edit_Sensor!,
[name]: extractEventValue(event) [name]: extractEventValue(event)
} }
}); });
}; };
cancelEditingSensor = () => { cancelEditingSensor = () => {
this.setState({ edit_sensorname: undefined }); this.setState({ edit_Sensor: undefined });
}; };
doneEditingSensor = () => { doneEditingSensor = () => {
const { edit_sensorname } = this.state; const { edit_Sensor } = this.state;
redirectingAuthorizedFetch(WRITE_SENSOR_ENDPOINT, { redirectingAuthorizedFetch(WRITE_SENSOR_ENDPOINT, {
method: 'POST', method: 'POST',
body: JSON.stringify({ body: JSON.stringify({
sensorname: edit_sensorname sensor: edit_Sensor
}), }),
headers: { headers: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
@@ -248,11 +248,11 @@ class EMSESPDevicesForm extends Component<
}) })
.then((response) => { .then((response) => {
if (response.status === 200) { if (response.status === 200) {
this.props.enqueueSnackbar('Sensorname set', { this.props.enqueueSnackbar('Sensor updated', {
variant: 'success' variant: 'success'
}); });
} else if (response.status === 204) { } else if (response.status === 204) {
this.props.enqueueSnackbar('Sensorname not set', { this.props.enqueueSnackbar('Sensor change failed', {
variant: 'error' variant: 'error'
}); });
} else if (response.status === 403) { } else if (response.status === 403) {
@@ -269,13 +269,13 @@ class EMSESPDevicesForm extends Component<
}); });
}); });
if (edit_sensorname) { if (edit_Sensor) {
this.setState({ edit_sensorname: undefined }); this.setState({ edit_Sensor: undefined });
} }
}; };
sendSensor = (sn: Sensor) => { sendSensor = (sn: Sensor) => {
this.setState({ edit_sensorname: sn }); this.setState({ edit_Sensor: sn });
}; };
noDevices = () => { noDevices = () => {
@@ -386,7 +386,7 @@ class EMSESPDevicesForm extends Component<
<TableRow key={sensorData.no} hover> <TableRow key={sensorData.no} hover>
<TableCell padding="checkbox" style={{ width: 18 }}> <TableCell padding="checkbox" style={{ width: 18 }}>
{me.admin && ( {me.admin && (
<CustomTooltip title="change name" placement="left-end"> <CustomTooltip title="edit" placement="left-end">
<IconButton <IconButton
edge="start" edge="start"
size="small" size="small"
@@ -614,7 +614,7 @@ class EMSESPDevicesForm extends Component<
} }
render() { render() {
const { edit_devicevalue, edit_sensorname } = this.state; const { edit_devicevalue, edit_Sensor } = this.state;
return ( return (
<Fragment> <Fragment>
<br></br> <br></br>
@@ -648,14 +648,14 @@ class EMSESPDevicesForm extends Component<
{edit_devicevalue && ( {edit_devicevalue && (
<ValueForm <ValueForm
devicevalue={edit_devicevalue} devicevalue={edit_devicevalue}
onDoneEditing={this.doneEditingValue} onDoneEditing={this.doneEditingDeviceValue}
onCancelEditing={this.cancelEditingValue} onCancelEditing={this.cancelEditingDeviceValue}
handleValueChange={this.handleValueChange} handleValueChange={this.handleDeviceValueChange}
/> />
)} )}
{edit_sensorname && ( {edit_Sensor && (
<SensorForm <SensorForm
sensor={edit_sensorname} sensor={edit_Sensor}
onDoneEditing={this.doneEditingSensor} onDoneEditing={this.doneEditingSensor}
onCancelEditing={this.cancelEditingSensor} onCancelEditing={this.cancelEditingSensor}
handleSensorChange={this.handleSensorChange} handleSensorChange={this.handleSensorChange}
@@ -666,4 +666,4 @@ class EMSESPDevicesForm extends Component<
} }
} }
export default withAuthenticatedContext(withWidth()(EMSESPDevicesForm)); export default withAuthenticatedContext(withWidth()(EMSESPDataForm));

View File

@@ -1,35 +0,0 @@
import React, { Component } from 'react';
import {
restController,
RestControllerProps,
RestFormLoader,
SectionContent
} from '../components';
import { ENDPOINT_ROOT } from '../api';
import EMSESPDevicesForm from './EMSESPDevicesForm';
import { EMSESPDevices } from './EMSESPtypes';
export const EMSESP_DEVICES_ENDPOINT = ENDPOINT_ROOT + 'allDevices';
type EMSESPDevicesControllerProps = RestControllerProps<EMSESPDevices>;
class EMSESPDevicesController extends Component<EMSESPDevicesControllerProps> {
componentDidMount() {
this.props.loadData();
}
render() {
return (
<SectionContent title="Devices &amp; Sensors">
<RestFormLoader
{...this.props}
render={(formProps) => <EMSESPDevicesForm {...formProps} />}
/>
</SectionContent>
);
}
}
export default restController(EMSESP_DEVICES_ENDPOINT, EMSESPDevicesController);

View File

@@ -54,10 +54,11 @@ export interface Device {
export interface Sensor { export interface Sensor {
no: number; no: number;
id: string; id: string;
temp: string; temp: number;
offset: number;
} }
export interface EMSESPDevices { export interface EMSESPData {
devices: Device[]; devices: Device[];
sensors: Sensor[]; sensors: Sensor[];
analog: number; analog: number;

View File

@@ -23,7 +23,7 @@ class ProjectMenu extends Component<ProjectProps> {
to="/ems-esp/" to="/ems-esp/"
selected={ selected={
path.startsWith('/ems-esp/status') || path.startsWith('/ems-esp/status') ||
path.startsWith('/ems-esp/devices') || path.startsWith('/ems-esp/data') ||
path.startsWith('/ems-esp/help') path.startsWith('/ems-esp/help')
} }
button button

View File

@@ -6,7 +6,8 @@ import {
DialogContent, DialogContent,
DialogActions, DialogActions,
FormHelperText, FormHelperText,
OutlinedInput OutlinedInput,
InputAdornment
} from '@material-ui/core'; } from '@material-ui/core';
import { FormButton } from '../components'; import { FormButton } from '../components';
@@ -45,26 +46,27 @@ class SensorForm extends React.Component<SensorFormProps> {
open open
> >
<DialogTitle id="user-form-dialog-title"> <DialogTitle id="user-form-dialog-title">
Change Sensor Name Editing Sensor #{sensor.no}
</DialogTitle> </DialogTitle>
<DialogContent dividers> <DialogContent dividers>
<FormHelperText id="outlined-value-name-text"> <FormHelperText>Name (no spaces)</FormHelperText>
Name of sensor #{sensor.no}
</FormHelperText>
<OutlinedInput <OutlinedInput
id="outlined-adornment-value" id="id"
value={sensor.id} value={sensor.id}
autoFocus autoFocus
fullWidth fullWidth
onChange={handleSensorChange('id')} onChange={handleSensorChange('id')}
aria-describedby="outlined-value-name-text"
inputProps={{
'aria-label': 'id'
}}
/> />
<FormHelperText>
(optional 'offset' separated by space) <FormHelperText>Custom Offset</FormHelperText>
</FormHelperText> <OutlinedInput
id="offset"
value={sensor.offset}
fullWidth
type="number"
onChange={handleSensorChange('offset')}
endAdornment={<InputAdornment position="end">°C</InputAdornment>}
/>
</DialogContent> </DialogContent>
<DialogActions> <DialogActions>
<FormButton <FormButton

View File

@@ -278,7 +278,7 @@ const generate_token = { token: '1234' }
// EMS-ESP Project specific // EMS-ESP Project specific
const EMSESP_SETTINGS_ENDPOINT = REST_ENDPOINT_ROOT + 'emsespSettings' const EMSESP_SETTINGS_ENDPOINT = REST_ENDPOINT_ROOT + 'emsespSettings'
const EMSESP_ALLDEVICES_ENDPOINT = REST_ENDPOINT_ROOT + 'allDevices' const EMSESP_DATA_ENDPOINT = REST_ENDPOINT_ROOT + 'data'
const EMSESP_SCANDEVICES_ENDPOINT = REST_ENDPOINT_ROOT + 'scanDevices' const EMSESP_SCANDEVICES_ENDPOINT = REST_ENDPOINT_ROOT + 'scanDevices'
const EMSESP_DEVICEDATA_ENDPOINT = REST_ENDPOINT_ROOT + 'deviceData' const EMSESP_DEVICEDATA_ENDPOINT = REST_ENDPOINT_ROOT + 'deviceData'
const EMSESP_STATUS_ENDPOINT = REST_ENDPOINT_ROOT + 'emsespStatus' const EMSESP_STATUS_ENDPOINT = REST_ENDPOINT_ROOT + 'emsespStatus'
@@ -312,7 +312,7 @@ const emsesp_settings = {
bool_format: 1, bool_format: 1,
enum_format: 1, enum_format: 1,
} }
const emsesp_alldevices = { const emsesp_data = {
devices: [ devices: [
{ {
id: 1, id: 1,
@@ -343,10 +343,11 @@ const emsesp_alldevices = {
}, },
], ],
sensors: [ sensors: [
{ no: 1, id: '28-233D-9497-0C03', temp: '25.7' }, { no: 1, id: '28-233D-9497-0C03', temp: 25.7, offset: 12 },
{ no: 2, id: '28-243D-7437-1E3A', temp: '26.1' }, { no: 2, id: '28-243D-7437-1E3A', temp: 26.1, offset: 0 },
], ],
} }
const emsesp_status = { const emsesp_status = {
status: 0, status: 0,
rx_received: 344, rx_received: 344,
@@ -873,8 +874,8 @@ app.get(EMSESP_SETTINGS_ENDPOINT, (req, res) => {
app.post(EMSESP_SETTINGS_ENDPOINT, (req, res) => { app.post(EMSESP_SETTINGS_ENDPOINT, (req, res) => {
res.json(emsesp_settings) res.json(emsesp_settings)
}) })
app.get(EMSESP_ALLDEVICES_ENDPOINT, (req, res) => { app.get(EMSESP_DATA_ENDPOINT, (req, res) => {
res.json(emsesp_alldevices) res.json(emsesp_data)
}) })
app.post(EMSESP_SCANDEVICES_ENDPOINT, (req, res) => { app.post(EMSESP_SCANDEVICES_ENDPOINT, (req, res) => {
res.sendStatus(200) res.sendStatus(200)
@@ -904,7 +905,6 @@ app.post(EMSESP_DEVICEDATA_ENDPOINT, (req, res) => {
app.post(WRITE_VALUE_ENDPOINT, (req, res) => { app.post(WRITE_VALUE_ENDPOINT, (req, res) => {
const devicevalue = req.body.devicevalue const devicevalue = req.body.devicevalue
const id = req.body.id const id = req.body.id
console.log(id) console.log(id)
console.log(devicevalue) console.log(devicevalue)
@@ -912,12 +912,8 @@ app.post(WRITE_VALUE_ENDPOINT, (req, res) => {
}) })
app.post(WRITE_SENSOR_ENDPOINT, (req, res) => { app.post(WRITE_SENSOR_ENDPOINT, (req, res) => {
const sensorname = req.body.sensorname const sensor = req.body.sensor
const id = sensorname.id console.log(sensor)
const no = sensorname.no
console.log(id)
console.log(no)
res.sendStatus(200) res.sendStatus(200)
}) })

View File

@@ -38,7 +38,7 @@ WebSettingsService EMSESP::webSettingsService = WebSettingsService(&webServer, &
#endif #endif
WebStatusService EMSESP::webStatusService = WebStatusService(&webServer, EMSESP::esp8266React.getSecurityManager()); WebStatusService EMSESP::webStatusService = WebStatusService(&webServer, EMSESP::esp8266React.getSecurityManager());
WebDevicesService EMSESP::webDevicesService = WebDevicesService(&webServer, EMSESP::esp8266React.getSecurityManager()); WebDataService EMSESP::webDataService = WebDataService(&webServer, EMSESP::esp8266React.getSecurityManager());
WebAPIService EMSESP::webAPIService = WebAPIService(&webServer, EMSESP::esp8266React.getSecurityManager()); WebAPIService EMSESP::webAPIService = WebAPIService(&webServer, EMSESP::esp8266React.getSecurityManager());
WebLogService EMSESP::webLogService = WebLogService(&webServer, EMSESP::esp8266React.getSecurityManager()); WebLogService EMSESP::webLogService = WebLogService(&webServer, EMSESP::esp8266React.getSecurityManager());
@@ -363,8 +363,13 @@ void EMSESP::show_sensor_values(uuid::console::Shell & shell) {
shell.printfln(F("Dallas temperature sensors:")); shell.printfln(F("Dallas temperature sensors:"));
uint8_t i = 1; uint8_t i = 1;
char s[7]; char s[7];
char s2[7];
for (const auto & device : sensor_devices()) { for (const auto & device : sensor_devices()) {
shell.printfln(F(" Sensor %d, ID: %s, Temperature: %s °C"), i++, device.to_string().c_str(), Helpers::render_value(s, device.temperature_c, 10)); shell.printfln(F(" Sensor %d, ID: %s, Temperature: %s °C (offset %s)"),
i++,
device.to_string().c_str(),
Helpers::render_value(s, device.temperature_c, 10),
Helpers::render_value(s2, device.offset(), 10));
} }
shell.println(); shell.println();
} }

View File

@@ -36,7 +36,7 @@
#include <ESP8266React.h> #include <ESP8266React.h>
#include "web/WebStatusService.h" #include "web/WebStatusService.h"
#include "web/WebDevicesService.h" #include "web/WebDataService.h"
#include "web/WebSettingsService.h" #include "web/WebSettingsService.h"
#include "web/WebAPIService.h" #include "web/WebAPIService.h"
#include "web/WebLogService.h" #include "web/WebLogService.h"
@@ -220,7 +220,7 @@ class EMSESP {
static ESP8266React esp8266React; static ESP8266React esp8266React;
static WebSettingsService webSettingsService; static WebSettingsService webSettingsService;
static WebStatusService webStatusService; static WebStatusService webStatusService;
static WebDevicesService webDevicesService; static WebDataService webDataService;
static WebAPIService webAPIService; static WebAPIService webAPIService;
static WebLogService webLogService; static WebLogService webLogService;

View File

@@ -1 +1 @@
#define EMSESP_APP_VERSION "3.1.2b4" #define EMSESP_APP_VERSION "3.1.2b5"

View File

@@ -22,19 +22,19 @@ namespace emsesp {
using namespace std::placeholders; // for `_1` etc using namespace std::placeholders; // for `_1` etc
WebDevicesService::WebDevicesService(AsyncWebServer * server, SecurityManager * securityManager) WebDataService::WebDataService(AsyncWebServer * server, SecurityManager * securityManager)
: _device_dataHandler(DEVICE_DATA_SERVICE_PATH, : _device_dataHandler(DEVICE_DATA_SERVICE_PATH,
securityManager->wrapCallback(std::bind(&WebDevicesService::device_data, this, _1, _2), AuthenticationPredicates::IS_AUTHENTICATED)) securityManager->wrapCallback(std::bind(&WebDataService::device_data, this, _1, _2), AuthenticationPredicates::IS_AUTHENTICATED))
, _writevalue_dataHandler(WRITE_VALUE_SERVICE_PATH, , _writevalue_dataHandler(WRITE_VALUE_SERVICE_PATH,
securityManager->wrapCallback(std::bind(&WebDevicesService::write_value, this, _1, _2), AuthenticationPredicates::IS_ADMIN)) securityManager->wrapCallback(std::bind(&WebDataService::write_value, this, _1, _2), AuthenticationPredicates::IS_ADMIN))
, _writesensor_dataHandler(WRITE_SENSOR_SERVICE_PATH, , _writesensor_dataHandler(WRITE_SENSOR_SERVICE_PATH,
securityManager->wrapCallback(std::bind(&WebDevicesService::write_sensor, this, _1, _2), AuthenticationPredicates::IS_ADMIN)) { securityManager->wrapCallback(std::bind(&WebDataService::write_sensor, this, _1, _2), AuthenticationPredicates::IS_ADMIN)) {
server->on(EMSESP_DEVICES_SERVICE_PATH, server->on(EMSESP_DATA_SERVICE_PATH,
HTTP_GET, HTTP_GET,
securityManager->wrapRequest(std::bind(&WebDevicesService::all_devices, this, _1), AuthenticationPredicates::IS_AUTHENTICATED)); securityManager->wrapRequest(std::bind(&WebDataService::all_devices, this, _1), AuthenticationPredicates::IS_AUTHENTICATED));
server->on(SCAN_DEVICES_SERVICE_PATH, server->on(SCAN_DEVICES_SERVICE_PATH,
HTTP_GET, HTTP_GET,
securityManager->wrapRequest(std::bind(&WebDevicesService::scan_devices, this, _1), AuthenticationPredicates::IS_AUTHENTICATED)); securityManager->wrapRequest(std::bind(&WebDataService::scan_devices, this, _1), AuthenticationPredicates::IS_AUTHENTICATED));
_device_dataHandler.setMethod(HTTP_POST); _device_dataHandler.setMethod(HTTP_POST);
_device_dataHandler.setMaxContentLength(256); _device_dataHandler.setMaxContentLength(256);
@@ -49,12 +49,12 @@ WebDevicesService::WebDevicesService(AsyncWebServer * server, SecurityManager *
server->addHandler(&_writesensor_dataHandler); server->addHandler(&_writesensor_dataHandler);
} }
void WebDevicesService::scan_devices(AsyncWebServerRequest * request) { void WebDataService::scan_devices(AsyncWebServerRequest * request) {
EMSESP::scan_devices(); EMSESP::scan_devices();
request->send(200); request->send(200);
} }
void WebDevicesService::all_devices(AsyncWebServerRequest * request) { void WebDataService::all_devices(AsyncWebServerRequest * request) {
AsyncJsonResponse * response = new AsyncJsonResponse(false, EMSESP_JSON_SIZE_LARGE_DYN); AsyncJsonResponse * response = new AsyncJsonResponse(false, EMSESP_JSON_SIZE_LARGE_DYN);
JsonObject root = response->getRoot(); JsonObject root = response->getRoot();
@@ -75,14 +75,15 @@ void WebDevicesService::all_devices(AsyncWebServerRequest * request) {
JsonArray sensors = root.createNestedArray("sensors"); JsonArray sensors = root.createNestedArray("sensors");
if (EMSESP::have_sensors()) { if (EMSESP::have_sensors()) {
uint8_t i = 1; uint8_t i = 1;
char s[8];
for (const auto & sensor : EMSESP::sensor_devices()) { for (const auto & sensor : EMSESP::sensor_devices()) {
JsonObject obj = sensors.createNestedObject(); JsonObject obj = sensors.createNestedObject();
obj["no"] = i++; obj["no"] = i++;
obj["id"] = sensor.to_string(true); obj["id"] = sensor.to_string(true);
obj["temp"] = Helpers::render_value(s, sensor.temperature_c, 10); obj["temp"] = (float)(sensor.temperature_c) / 10;
obj["offset"] = (float)(sensor.offset()) / 10;
} }
} }
if (EMSESP::system_.analog_enabled()) { if (EMSESP::system_.analog_enabled()) {
root["analog"] = EMSESP::system_.analog(); root["analog"] = EMSESP::system_.analog();
} }
@@ -93,7 +94,7 @@ void WebDevicesService::all_devices(AsyncWebServerRequest * request) {
// The unique_id is the unique record ID from the Web table to identify which device to load // The unique_id is the unique record ID from the Web table to identify which device to load
// Compresses the JSON using MsgPack https://msgpack.org/index.html // Compresses the JSON using MsgPack https://msgpack.org/index.html
void WebDevicesService::device_data(AsyncWebServerRequest * request, JsonVariant & json) { void WebDataService::device_data(AsyncWebServerRequest * request, JsonVariant & json) {
if (json.is<JsonObject>()) { if (json.is<JsonObject>()) {
MsgpackAsyncJsonResponse * response = new MsgpackAsyncJsonResponse(false, EMSESP_JSON_SIZE_XXLARGE_DYN); MsgpackAsyncJsonResponse * response = new MsgpackAsyncJsonResponse(false, EMSESP_JSON_SIZE_XXLARGE_DYN);
for (const auto & emsdevice : EMSESP::emsdevices) { for (const auto & emsdevice : EMSESP::emsdevices) {
@@ -117,7 +118,7 @@ void WebDevicesService::device_data(AsyncWebServerRequest * request, JsonVariant
} }
// takes a command and its data value from a specific Device, from the Web // takes a command and its data value from a specific Device, from the Web
void WebDevicesService::write_value(AsyncWebServerRequest * request, JsonVariant & json) { void WebDataService::write_value(AsyncWebServerRequest * request, JsonVariant & json) {
if (json.is<JsonObject>()) { if (json.is<JsonObject>()) {
JsonObject dv = json["devicevalue"]; JsonObject dv = json["devicevalue"];
uint8_t id = json["id"]; uint8_t id = json["id"];
@@ -156,28 +157,21 @@ void WebDevicesService::write_value(AsyncWebServerRequest * request, JsonVariant
} }
// takes a sensorname and optional offset from the Web // takes a sensorname and optional offset from the Web
void WebDevicesService::write_sensor(AsyncWebServerRequest * request, JsonVariant & json) { void WebDataService::write_sensor(AsyncWebServerRequest * request, JsonVariant & json) {
bool ok = false; bool ok = false;
if (json.is<JsonObject>()) { if (json.is<JsonObject>()) {
JsonObject sn = json["sensorname"]; JsonObject sensor = json["sensor"];
std::string id = sn["id"];
uint8_t no = sn["no"];
char nostr[3];
char name[25];
int16_t offset = 0;
strlcpy(name, id.c_str(), sizeof(name)); // if valid add.
uint8_t no = sensor["no"];
if (no > 0 && no < 100) { if (no > 0 && no < 100) {
Helpers::itoa(nostr, no, 10); char name[25];
char * c = strchr(name, ' '); // find space std::string id = sensor["id"];
if (c != nullptr) { strlcpy(name, id.c_str(), sizeof(name));
*c = '\0'; float offset = sensor["offset"]; // this will be a float value. We'll convert it to int and * 10 it
float v; int16_t offset10 = offset * 10;
if (Helpers::value2float((c + 1), v)) { char idstr[3];
offset = v * 10; ok = EMSESP::dallassensor_.update(Helpers::itoa(idstr, no, 10), name, offset10);
}
}
ok = EMSESP::dallassensor_.add_name(nostr, name, offset);
} }
} }

View File

@@ -16,15 +16,15 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef WebDevicesService_h #ifndef WebDataService_h
#define WebDevicesService_h #define WebDataService_h
#include <ArduinoJson.h> #include <ArduinoJson.h>
#include <AsyncJson.h> #include <AsyncJson.h>
#include <ESPAsyncWebServer.h> #include <ESPAsyncWebServer.h>
#include <SecurityManager.h> #include <SecurityManager.h>
#define EMSESP_DEVICES_SERVICE_PATH "/rest/allDevices" #define EMSESP_DATA_SERVICE_PATH "/rest/data"
#define SCAN_DEVICES_SERVICE_PATH "/rest/scanDevices" #define SCAN_DEVICES_SERVICE_PATH "/rest/scanDevices"
#define DEVICE_DATA_SERVICE_PATH "/rest/deviceData" #define DEVICE_DATA_SERVICE_PATH "/rest/deviceData"
#define WRITE_VALUE_SERVICE_PATH "/rest/writeValue" #define WRITE_VALUE_SERVICE_PATH "/rest/writeValue"
@@ -32,9 +32,9 @@
namespace emsesp { namespace emsesp {
class WebDevicesService { class WebDataService {
public: public:
WebDevicesService(AsyncWebServer * server, SecurityManager * securityManager); WebDataService(AsyncWebServer * server, SecurityManager * securityManager);
private: private:
// GET // GET