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 EMSESPStatusController from './EMSESPStatusController';
import EMSESPDevicesController from './EMSESPDevicesController';
import EMSESPDataController from './EMSESPDataController';
import EMSESPHelp from './EMSESPHelp';
class EMSESP extends Component<RouteComponentProps> {
@@ -24,18 +24,15 @@ class EMSESP extends Component<RouteComponentProps> {
onChange={(e, path) => this.handleTabChange(path)}
variant="fullWidth"
>
<Tab
value={`/${PROJECT_PATH}/devices`}
label="Devices &amp; Sensors"
/>
<Tab value={`/${PROJECT_PATH}/data`} label="Devices &amp; Sensors" />
<Tab value={`/${PROJECT_PATH}/status`} label="EMS Status" />
<Tab value={`/${PROJECT_PATH}/help`} label="EMS-ESP Help" />
</Tabs>
<Switch>
<AuthenticatedRoute
exact
path={`/${PROJECT_PATH}/devices`}
component={EMSESPDevicesController}
path={`/${PROJECT_PATH}/data`}
component={EMSESPDataController}
/>
<AuthenticatedRoute
exact
@@ -47,7 +44,7 @@ class EMSESP extends Component<RouteComponentProps> {
path={`/${PROJECT_PATH}/help`}
component={EMSESPHelp}
/>
<Redirect to={`/${PROJECT_PATH}/devices`} />
<Redirect to={`/${PROJECT_PATH}/data`} />
</Switch>
</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 {
EMSESPDevices,
EMSESPData,
EMSESPDeviceData,
Device,
DeviceValue,
@@ -91,16 +91,16 @@ function compareDevices(a: Device, b: Device) {
return 0;
}
interface EMSESPDevicesFormState {
interface EMSESPDataFormState {
confirmScanDevices: boolean;
processing: boolean;
deviceData?: EMSESPDeviceData;
selectedDevice?: number;
edit_devicevalue?: DeviceValue;
edit_sensorname?: Sensor;
edit_Sensor?: Sensor;
}
type EMSESPDevicesFormProps = RestFormProps<EMSESPDevices> &
type EMSESPDataFormProps = RestFormProps<EMSESPData> &
AuthenticatedContextProps &
WithWidthProps;
@@ -150,16 +150,16 @@ function formatValue(value: any, uom: number, digit: number) {
}
}
class EMSESPDevicesForm extends Component<
EMSESPDevicesFormProps,
EMSESPDevicesFormState
class EMSESPDataForm extends Component<
EMSESPDataFormProps,
EMSESPDataFormState
> {
state: EMSESPDevicesFormState = {
state: EMSESPDataFormState = {
confirmScanDevices: false,
processing: false
};
handleValueChange = (name: keyof DeviceValue) => (
handleDeviceValueChange = (name: keyof DeviceValue) => (
event: React.ChangeEvent<HTMLInputElement>
) => {
this.setState({
@@ -170,11 +170,11 @@ class EMSESPDevicesForm extends Component<
});
};
cancelEditingValue = () => {
cancelEditingDeviceValue = () => {
this.setState({ edit_devicevalue: undefined });
};
doneEditingValue = () => {
doneEditingDeviceValue = () => {
const { edit_devicevalue, selectedDevice } = this.state;
redirectingAuthorizedFetch(WRITE_VALUE_ENDPOINT, {
@@ -223,24 +223,24 @@ class EMSESPDevicesForm extends Component<
event: React.ChangeEvent<HTMLInputElement>
) => {
this.setState({
edit_sensorname: {
...this.state.edit_sensorname!,
edit_Sensor: {
...this.state.edit_Sensor!,
[name]: extractEventValue(event)
}
});
};
cancelEditingSensor = () => {
this.setState({ edit_sensorname: undefined });
this.setState({ edit_Sensor: undefined });
};
doneEditingSensor = () => {
const { edit_sensorname } = this.state;
const { edit_Sensor } = this.state;
redirectingAuthorizedFetch(WRITE_SENSOR_ENDPOINT, {
method: 'POST',
body: JSON.stringify({
sensorname: edit_sensorname
sensor: edit_Sensor
}),
headers: {
'Content-Type': 'application/json'
@@ -248,11 +248,11 @@ class EMSESPDevicesForm extends Component<
})
.then((response) => {
if (response.status === 200) {
this.props.enqueueSnackbar('Sensorname set', {
this.props.enqueueSnackbar('Sensor updated', {
variant: 'success'
});
} else if (response.status === 204) {
this.props.enqueueSnackbar('Sensorname not set', {
this.props.enqueueSnackbar('Sensor change failed', {
variant: 'error'
});
} else if (response.status === 403) {
@@ -269,13 +269,13 @@ class EMSESPDevicesForm extends Component<
});
});
if (edit_sensorname) {
this.setState({ edit_sensorname: undefined });
if (edit_Sensor) {
this.setState({ edit_Sensor: undefined });
}
};
sendSensor = (sn: Sensor) => {
this.setState({ edit_sensorname: sn });
this.setState({ edit_Sensor: sn });
};
noDevices = () => {
@@ -386,7 +386,7 @@ class EMSESPDevicesForm extends Component<
<TableRow key={sensorData.no} hover>
<TableCell padding="checkbox" style={{ width: 18 }}>
{me.admin && (
<CustomTooltip title="change name" placement="left-end">
<CustomTooltip title="edit" placement="left-end">
<IconButton
edge="start"
size="small"
@@ -614,7 +614,7 @@ class EMSESPDevicesForm extends Component<
}
render() {
const { edit_devicevalue, edit_sensorname } = this.state;
const { edit_devicevalue, edit_Sensor } = this.state;
return (
<Fragment>
<br></br>
@@ -648,14 +648,14 @@ class EMSESPDevicesForm extends Component<
{edit_devicevalue && (
<ValueForm
devicevalue={edit_devicevalue}
onDoneEditing={this.doneEditingValue}
onCancelEditing={this.cancelEditingValue}
handleValueChange={this.handleValueChange}
onDoneEditing={this.doneEditingDeviceValue}
onCancelEditing={this.cancelEditingDeviceValue}
handleValueChange={this.handleDeviceValueChange}
/>
)}
{edit_sensorname && (
{edit_Sensor && (
<SensorForm
sensor={edit_sensorname}
sensor={edit_Sensor}
onDoneEditing={this.doneEditingSensor}
onCancelEditing={this.cancelEditingSensor}
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 {
no: number;
id: string;
temp: string;
temp: number;
offset: number;
}
export interface EMSESPDevices {
export interface EMSESPData {
devices: Device[];
sensors: Sensor[];
analog: number;

View File

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

View File

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

View File

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

View File

@@ -37,10 +37,10 @@ ESP8266React EMSESP::esp8266React(&webServer, &LITTLEFS);
WebSettingsService EMSESP::webSettingsService = WebSettingsService(&webServer, &LITTLEFS, EMSESP::esp8266React.getSecurityManager());
#endif
WebStatusService EMSESP::webStatusService = WebStatusService(&webServer, EMSESP::esp8266React.getSecurityManager());
WebDevicesService EMSESP::webDevicesService = WebDevicesService(&webServer, EMSESP::esp8266React.getSecurityManager());
WebAPIService EMSESP::webAPIService = WebAPIService(&webServer, EMSESP::esp8266React.getSecurityManager());
WebLogService EMSESP::webLogService = WebLogService(&webServer, EMSESP::esp8266React.getSecurityManager());
WebStatusService EMSESP::webStatusService = WebStatusService(&webServer, EMSESP::esp8266React.getSecurityManager());
WebDataService EMSESP::webDataService = WebDataService(&webServer, EMSESP::esp8266React.getSecurityManager());
WebAPIService EMSESP::webAPIService = WebAPIService(&webServer, EMSESP::esp8266React.getSecurityManager());
WebLogService EMSESP::webLogService = WebLogService(&webServer, EMSESP::esp8266React.getSecurityManager());
using DeviceFlags = EMSdevice;
using DeviceType = EMSdevice::DeviceType;
@@ -363,8 +363,13 @@ void EMSESP::show_sensor_values(uuid::console::Shell & shell) {
shell.printfln(F("Dallas temperature sensors:"));
uint8_t i = 1;
char s[7];
char s2[7];
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();
}

View File

@@ -36,7 +36,7 @@
#include <ESP8266React.h>
#include "web/WebStatusService.h"
#include "web/WebDevicesService.h"
#include "web/WebDataService.h"
#include "web/WebSettingsService.h"
#include "web/WebAPIService.h"
#include "web/WebLogService.h"
@@ -220,7 +220,7 @@ class EMSESP {
static ESP8266React esp8266React;
static WebSettingsService webSettingsService;
static WebStatusService webStatusService;
static WebDevicesService webDevicesService;
static WebDataService webDataService;
static WebAPIService webAPIService;
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
WebDevicesService::WebDevicesService(AsyncWebServer * server, SecurityManager * securityManager)
WebDataService::WebDataService(AsyncWebServer * server, SecurityManager * securityManager)
: _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,
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,
securityManager->wrapCallback(std::bind(&WebDevicesService::write_sensor, this, _1, _2), AuthenticationPredicates::IS_ADMIN)) {
server->on(EMSESP_DEVICES_SERVICE_PATH,
securityManager->wrapCallback(std::bind(&WebDataService::write_sensor, this, _1, _2), AuthenticationPredicates::IS_ADMIN)) {
server->on(EMSESP_DATA_SERVICE_PATH,
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,
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.setMaxContentLength(256);
@@ -49,12 +49,12 @@ WebDevicesService::WebDevicesService(AsyncWebServer * server, SecurityManager *
server->addHandler(&_writesensor_dataHandler);
}
void WebDevicesService::scan_devices(AsyncWebServerRequest * request) {
void WebDataService::scan_devices(AsyncWebServerRequest * request) {
EMSESP::scan_devices();
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);
JsonObject root = response->getRoot();
@@ -75,14 +75,15 @@ void WebDevicesService::all_devices(AsyncWebServerRequest * request) {
JsonArray sensors = root.createNestedArray("sensors");
if (EMSESP::have_sensors()) {
uint8_t i = 1;
char s[8];
for (const auto & sensor : EMSESP::sensor_devices()) {
JsonObject obj = sensors.createNestedObject();
obj["no"] = i++;
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()) {
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
// 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>()) {
MsgpackAsyncJsonResponse * response = new MsgpackAsyncJsonResponse(false, EMSESP_JSON_SIZE_XXLARGE_DYN);
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
void WebDevicesService::write_value(AsyncWebServerRequest * request, JsonVariant & json) {
void WebDataService::write_value(AsyncWebServerRequest * request, JsonVariant & json) {
if (json.is<JsonObject>()) {
JsonObject dv = json["devicevalue"];
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
void WebDevicesService::write_sensor(AsyncWebServerRequest * request, JsonVariant & json) {
void WebDataService::write_sensor(AsyncWebServerRequest * request, JsonVariant & json) {
bool ok = false;
if (json.is<JsonObject>()) {
JsonObject sn = json["sensorname"];
std::string id = sn["id"];
uint8_t no = sn["no"];
char nostr[3];
char name[25];
int16_t offset = 0;
JsonObject sensor = json["sensor"];
strlcpy(name, id.c_str(), sizeof(name));
// if valid add.
uint8_t no = sensor["no"];
if (no > 0 && no < 100) {
Helpers::itoa(nostr, no, 10);
char * c = strchr(name, ' '); // find space
if (c != nullptr) {
*c = '\0';
float v;
if (Helpers::value2float((c + 1), v)) {
offset = v * 10;
}
}
ok = EMSESP::dallassensor_.add_name(nostr, name, offset);
char name[25];
std::string id = sensor["id"];
strlcpy(name, id.c_str(), sizeof(name));
float offset = sensor["offset"]; // this will be a float value. We'll convert it to int and * 10 it
int16_t offset10 = offset * 10;
char idstr[3];
ok = EMSESP::dallassensor_.update(Helpers::itoa(idstr, no, 10), name, offset10);
}
}

View File

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