alova implementation, testing

This commit is contained in:
proddy
2023-06-04 15:22:09 +02:00
parent 02c386d76f
commit 2e63d60273
11 changed files with 280 additions and 144 deletions

View File

@@ -0,0 +1,2 @@
VITE_ALOVA_TIPS=0
REACT_APP_ALOVA_TIPS=0

View File

@@ -19,6 +19,7 @@
"lint": "eslint . --cache --fix" "lint": "eslint . --cache --fix"
}, },
"dependencies": { "dependencies": {
"@alova/adapter-xhr": "^1.0.0",
"@emotion/react": "^11.11.0", "@emotion/react": "^11.11.0",
"@emotion/styled": "^11.11.0", "@emotion/styled": "^11.11.0",
"@mui/icons-material": "^5.11.16", "@mui/icons-material": "^5.11.16",
@@ -29,6 +30,7 @@
"@types/react": "^18.2.8", "@types/react": "^18.2.8",
"@types/react-dom": "^18.2.4", "@types/react-dom": "^18.2.4",
"@types/react-router-dom": "^5.3.3", "@types/react-router-dom": "^5.3.3",
"alova": "^2.5.4",
"async-validator": "^4.2.5", "async-validator": "^4.2.5",
"axios": "^1.4.0", "axios": "^1.4.0",
"history": "^5.3.0", "history": "^5.3.0",
@@ -47,7 +49,7 @@
"devDependencies": { "devDependencies": {
"@typescript-eslint/eslint-plugin": "^5.59.8", "@typescript-eslint/eslint-plugin": "^5.59.8",
"@typescript-eslint/parser": "^5.59.8", "@typescript-eslint/parser": "^5.59.8",
"@vitejs/plugin-react-swc": "^3.3.1", "@vitejs/plugin-react-swc": "^3.3.2",
"eslint": "^8.42.0", "eslint": "^8.42.0",
"eslint-config-airbnb": "^19.0.4", "eslint-config-airbnb": "^19.0.4",
"eslint-config-airbnb-typescript": "^17.0.0", "eslint-config-airbnb-typescript": "^17.0.0",

View File

@@ -8,7 +8,7 @@
font-style: normal; font-style: normal;
font-weight: 400; font-weight: 400;
/* src: url(https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu4mxK.woff2) format('woff2'); */ /* src: url(https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu4mxK.woff2) format('woff2'); */
src: local('Roboto'), local('Roboto-Regular'), url(../fonts/re.off2) format('woff2'); src: local('Roboto'), local('Roboto-Regular'), url(../fonts/re.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0104-0107, U+0118-0119, U+011E-011F, U+0130-0131, U+0141-0144, U+0152-0153, U+015A-015B, unicode-range: U+0000-00FF, U+0104-0107, U+0118-0119, U+011E-011F, U+0130-0131, U+0141-0144, U+0152-0153, U+015A-015B,
U+015E-015F, U+0179-017C, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+015E-015F, U+0179-017C, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193,
U+2212, U+2215, U+FEFF, U+FFFD; U+2212, U+2215, U+FEFF, U+FFFD;

View File

@@ -1,12 +1,18 @@
import { xhrRequestAdapter } from '@alova/adapter-xhr';
import { createAlova, useRequest } from 'alova';
import GlobalFetch from 'alova/GlobalFetch';
import ReactHook from 'alova/react';
import axios from 'axios'; import axios from 'axios';
import { unpack } from './unpack'; import { unpack } from './unpack';
import type { AxiosPromise, CancelToken, AxiosProgressEvent } from 'axios'; import type { AxiosPromise, CancelToken, AxiosProgressEvent } from 'axios';
export const WS_BASE_URL = '/ws/'; export const WS_BASE_URL = '/ws/';
export const API_BASE_URL = '/rest/';
export const ES_BASE_URL = '/es/'; export const ES_BASE_URL = '/es/';
export const EMSESP_API_BASE_URL = '/api/';
export const REST_BASE_URL = '/rest/';
export const API_BASE_URL = '/api/';
export const ACCESS_TOKEN = 'access_token'; export const ACCESS_TOKEN = 'access_token';
const location = window.location; const location = window.location;
@@ -14,8 +20,47 @@ const webProtocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
export const WEB_SOCKET_ROOT = webProtocol + '//' + location.host + WS_BASE_URL; export const WEB_SOCKET_ROOT = webProtocol + '//' + location.host + WS_BASE_URL;
export const EVENT_SOURCE_ROOT = location.protocol + '//' + location.host + ES_BASE_URL; export const EVENT_SOURCE_ROOT = location.protocol + '//' + location.host + ES_BASE_URL;
export const alovaInstance = createAlova({
baseURL: '/rest/',
statesHook: ReactHook,
requestAdapter: xhrRequestAdapter(),
// requestAdapter: GlobalFetch(),
beforeRequest(method) {
// TODO check if bearer works
if (localStorage.getItem(ACCESS_TOKEN)) {
method.config.headers.token = 'Bearer ' + localStorage.getItem(ACCESS_TOKEN);
}
},
responsed: (response) => response.data
// TODO add error handling for Push?
// return JSON.stringify(response.data);
// responded: {
// // When using the GlobalFetch request adapter, the first parameter receives the Response object
// // The second parameter is the method instance of the current request, you can use it to synchronize the configuration information before and after the request
// onSuccess: async (response, method) => {
// if (response.status >= 400) {
// throw new Error(response.statusText);
// }
// console.log('response', response);
// const json = await response.json();
// // The parsed response data will be passed to the transformData hook function of the method instance, and these functions will be explained later
// return json;
// },
// // Interceptor for request failure
// // This interceptor will be entered when the request is wrong.
// // The second parameter is the method instance of the current request, you can use it to synchronize the configuration information before and after the request
// onError: (error, method) => {
// alert(error.message);
// }
// }
});
export const AXIOS = axios.create({ export const AXIOS = axios.create({
baseURL: API_BASE_URL, baseURL: REST_BASE_URL,
headers: { headers: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}, },
@@ -35,7 +80,7 @@ export const AXIOS = axios.create({
}); });
export const AXIOS_API = axios.create({ export const AXIOS_API = axios.create({
baseURL: EMSESP_API_BASE_URL, baseURL: API_BASE_URL,
headers: { headers: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}, },
@@ -55,7 +100,7 @@ export const AXIOS_API = axios.create({
}); });
export const AXIOS_BIN = axios.create({ export const AXIOS_BIN = axios.create({
baseURL: API_BASE_URL, baseURL: REST_BASE_URL,
headers: { headers: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}, },
@@ -73,10 +118,11 @@ export const AXIOS_BIN = axios.create({
return JSON.stringify(data); return JSON.stringify(data);
} }
], ],
// transformResponse: [(data) => decode(data)] transformResponse: [(data) => unpack(data)]
transformResponse: [(data) => unpack(data)] // new using msgpackr
}); });
// TODO replace with alova
// TODO see https://alova.js.org/next-step/download-upload-progress
export interface FileUploadConfig { export interface FileUploadConfig {
cancelToken?: CancelToken; cancelToken?: CancelToken;
onUploadProgress?: (progressEvent: AxiosProgressEvent) => void; onUploadProgress?: (progressEvent: AxiosProgressEvent) => void;

View File

@@ -968,7 +968,6 @@ currentExtensions[0x69] = (data) => {
if (!referenceMap) referenceMap = new Map(); if (!referenceMap) referenceMap = new Map();
const token = src[position]; const token = src[position];
let target; let target;
// TODO: handle Maps, Sets, and other types that can cycle; this is complicated, because you potentially need to read
// ahead past references to record structure definitions // ahead past references to record structure definitions
if ((token >= 0x90 && token < 0xa0) || token == 0xdc || token == 0xdd) target = []; if ((token >= 0x90 && token < 0xa0) || token == 0xdc || token == 0xdd) target = [];
else target = {}; else target = {};
@@ -1041,7 +1040,6 @@ currentExtensions[0xff] = (data) => {
((data[3] & 0x3) * 0x100000000 + data[4] * 0x1000000 + (data[5] << 16) + (data[6] << 8) + data[7]) * 1000 ((data[3] & 0x3) * 0x100000000 + data[4] * 0x1000000 + (data[5] << 16) + (data[6] << 8) + data[7]) * 1000
); );
else if (data.length == 12) else if (data.length == 12)
// TODO: Implement support for negative
return new Date( return new Date(
((data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]) / 1000000 + ((data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]) / 1000000 +
((data[4] & 0x80 ? -0x1000000000000 : 0) + ((data[4] & 0x80 ? -0x1000000000000 : 0) +
@@ -1070,7 +1068,6 @@ function saveState(callback) {
const savedReferenceMap = referenceMap; const savedReferenceMap = referenceMap;
const savedBundledStrings = bundledStrings; const savedBundledStrings = bundledStrings;
// TODO: We may need to revisit this if we do more external calls to user code (since it could be slow)
const savedSrc = new Uint8Array(src.slice(0, srcEnd)); // we copy the data in case it changes while external data is processed const savedSrc = new Uint8Array(src.slice(0, srcEnd)); // we copy the data in case it changes while external data is processed
const savedStructures = currentStructures; const savedStructures = currentStructures;
const savedStructuresContents = currentStructures.slice(0, currentStructures.length); const savedStructuresContents = currentStructures.slice(0, currentStructures.length);

View File

@@ -30,6 +30,7 @@ import { useRowSelect } from '@table-library/react-table-library/select';
import { useSort, SortToggleType } from '@table-library/react-table-library/sort'; import { useSort, SortToggleType } from '@table-library/react-table-library/sort';
import { Table, Header, HeaderRow, HeaderCell, Body, Row, Cell } from '@table-library/react-table-library/table'; import { Table, Header, HeaderRow, HeaderCell, Body, Row, Cell } from '@table-library/react-table-library/table';
import { useTheme } from '@table-library/react-table-library/theme'; import { useTheme } from '@table-library/react-table-library/theme';
import { useRequest } from 'alova';
import { useState, useContext, useEffect, useCallback, useLayoutEffect } from 'react'; import { useState, useContext, useEffect, useCallback, useLayoutEffect } from 'react';
import { IconContext } from 'react-icons'; import { IconContext } from 'react-icons';
@@ -54,17 +55,45 @@ const DashboardDevices: FC = () => {
const [size, setSize] = useState([0, 0]); const [size, setSize] = useState([0, 0]);
const { me } = useContext(AuthenticatedContext); const { me } = useContext(AuthenticatedContext);
const { LL } = useI18nContext(); const { LL } = useI18nContext();
const [deviceData, setDeviceData] = useState<DeviceData>({ data: [] });
const [selectedDeviceValue, setSelectedDeviceValue] = useState<DeviceValue>(); const [selectedDeviceValue, setSelectedDeviceValue] = useState<DeviceValue>();
const [onlyFav, setOnlyFav] = useState(false); const [onlyFav, setOnlyFav] = useState(false);
const [deviceValueDialogOpen, setDeviceValueDialogOpen] = useState(false); const [deviceValueDialogOpen, setDeviceValueDialogOpen] = useState(false);
const [showDeviceInfo, setShowDeviceInfo] = useState<boolean>(false); const [showDeviceInfo, setShowDeviceInfo] = useState<boolean>(false);
const [selectedDevice, setSelectedDevice] = useState<number>(); const [selectedDevice, setSelectedDevice] = useState<number>();
const [coreData, setCoreData] = useState<CoreData>({
connected: true, // TODO remove
devices: [] // const [deviceData, setDeviceData] = useState<DeviceData>({ data: [] });
// const [coreData, setCoreData] = useState<CoreData>({
// connected: true,
// devices: []
// });
const { data: coreData, send: readCoreData } = useRequest(() => EMSESP.readCoreData(), {
initialData: {
connected: true,
devices: []
},
force: true,
immediate: false
}); });
// TODO prevent firing when page is loaded
const { data: deviceData, send: readDeviceData } = useRequest((id) => EMSESP.readDeviceData(id), {
initialData: {
data: []
},
force: true,
immediate: false
});
// TODO prevent firing when page is loaded
const { loading: submitting, send: writeDeviceValue } = useRequest(
(id: number, deviceValue: DeviceValue) => EMSESP.writeDeviceValue(id, deviceValue),
{
immediate: false
}
);
useLayoutEffect(() => { useLayoutEffect(() => {
function updateSize() { function updateSize() {
setSize([window.innerWidth, window.innerHeight]); setSize([window.innerWidth, window.innerHeight]);
@@ -212,19 +241,21 @@ const DashboardDevices: FC = () => {
} }
); );
const fetchDeviceData = async (id: number) => { // TODO remove
try { // const fetchDeviceData = async (id: number) => {
setDeviceData((await EMSESP.readDeviceData({ id })).data); // try {
} catch (error) { // setDeviceData((await EMSESP.readDeviceData({ id })).data);
toast.error(extractErrorMessage(error, LL.PROBLEM_LOADING())); // } catch (error) {
} // toast.error(extractErrorMessage(error, LL.PROBLEM_LOADING()));
}; // }
// };
function onSelectChange(action: any, state: any) { async function onSelectChange(action: any, state: any) {
setDeviceData({ data: [] }); // TODO check if still needed
// setDeviceData({ data: [] });
setSelectedDevice(state.id); setSelectedDevice(state.id);
if (action.type === 'ADD_BY_ID_EXCLUSIVELY') { if (action.type === 'ADD_BY_ID_EXCLUSIVELY') {
void fetchDeviceData(state.id); await readDeviceData(state.id);
} }
} }
@@ -257,27 +288,29 @@ const DashboardDevices: FC = () => {
}; };
}, [escFunction]); }, [escFunction]);
const fetchCoreData = useCallback(async () => { // TODO remove
try { // const fetchCoreData = useCallback(async () => {
setSelectedDevice(undefined); // try {
setCoreData((await EMSESP.readCoreData()).data); // setSelectedDevice(undefined);
} catch (error) { // setCoreData((await EMSESP.readCoreData()).data);
toast.error(extractErrorMessage(error, LL.PROBLEM_LOADING())); // } catch (error) {
} // toast.error(extractErrorMessage(error, LL.PROBLEM_LOADING()));
}, [LL]); // }
// }, [LL]);
useEffect(() => { // TODO remove
void fetchCoreData(); // useEffect(() => {
}, [fetchCoreData]); // void fetchCoreData2();
// }, [fetchCoreData2]);
const refreshData = () => { const refreshData = () => {
if (deviceValueDialogOpen) { if (deviceValueDialogOpen) {
return; return;
} }
if (selectedDevice) { if (selectedDevice) {
void fetchDeviceData(selectedDevice); void readDeviceData(selectedDevice);
} else { } else {
void fetchCoreData(); void readCoreData();
} }
}; };
@@ -348,25 +381,32 @@ const DashboardDevices: FC = () => {
const deviceValueDialogSave = async (dv: DeviceValue) => { const deviceValueDialogSave = async (dv: DeviceValue) => {
const selectedDeviceID = Number(device_select.state.id); const selectedDeviceID = Number(device_select.state.id);
try { // TODO For all Push, do error handling?
const response = await EMSESP.writeDeviceValue({ const response = await writeDeviceValue(selectedDeviceID, dv);
id: selectedDeviceID, console.log(response);
devicevalue: dv setDeviceValueDialogOpen(false);
}); await readDeviceData(selectedDeviceID);
if (response.status === 204) { setSelectedDeviceValue(undefined);
toast.error(LL.WRITE_CMD_FAILED());
} else if (response.status === 403) { // try {
toast.error(LL.ACCESS_DENIED()); // const response = await EMSESP.writeDeviceValue({
} else { // id: selectedDeviceID,
toast.success(LL.WRITE_CMD_SENT()); // devicevalue: dv
} // });
} catch (error) { // if (response.status === 204) {
toast.error(extractErrorMessage(error, LL.PROBLEM_UPDATING())); // toast.error(LL.WRITE_CMD_FAILED());
} finally { // } else if (response.status === 403) {
setDeviceValueDialogOpen(false); // toast.error(LL.ACCESS_DENIED());
await fetchDeviceData(selectedDeviceID); // } else {
setSelectedDeviceValue(undefined); // toast.success(LL.WRITE_CMD_SENT());
} // }
// } catch (error) {
// toast.error(extractErrorMessage(error, LL.PROBLEM_UPDATING()));
// } finally {
// setDeviceValueDialogOpen(false);
// await readDeviceData(selectedDeviceID);
// setSelectedDeviceValue(undefined);
// }
}; };
const renderDeviceDetails = () => { const renderDeviceDetails = () => {
@@ -457,7 +497,7 @@ const DashboardDevices: FC = () => {
}; };
const renderDeviceData = () => { const renderDeviceData = () => {
if (!selectedDevice) { if (!selectedDevice || deviceData.data === undefined) {
return; return;
} }
@@ -612,6 +652,7 @@ const DashboardDevices: FC = () => {
!hasMask(selectedDeviceValue.id, DeviceEntityMask.DV_READONLY) !hasMask(selectedDeviceValue.id, DeviceEntityMask.DV_READONLY)
} }
validator={deviceValueItemValidation(selectedDeviceValue)} validator={deviceValueItemValidation(selectedDeviceValue)}
progress={submitting}
/> />
)} )}
<ButtonRow> <ButtonRow>

View File

@@ -13,8 +13,10 @@ import {
FormHelperText, FormHelperText,
Grid, Grid,
Box, Box,
Typography Typography,
CircularProgress
} from '@mui/material'; } from '@mui/material';
import { green } from '@mui/material/colors';
import { useState, useEffect } from 'react'; import { useState, useEffect } from 'react';
import { DeviceValueUOM, DeviceValueUOM_s } from './types'; import { DeviceValueUOM, DeviceValueUOM_s } from './types';
@@ -22,7 +24,7 @@ import type { DeviceValue } from './types';
import type Schema from 'async-validator'; import type Schema from 'async-validator';
import type { ValidateFieldsError } from 'async-validator'; import type { ValidateFieldsError } from 'async-validator';
import { ValidatedTextField } from 'components'; import { ButtonRow, ValidatedTextField } from 'components';
import { useI18nContext } from 'i18n/i18n-react'; import { useI18nContext } from 'i18n/i18n-react';
import { updateValue } from 'utils'; import { updateValue } from 'utils';
@@ -35,6 +37,7 @@ type DashboardDevicesDialogProps = {
selectedItem: DeviceValue; selectedItem: DeviceValue;
writeable: boolean; writeable: boolean;
validator: Schema; validator: Schema;
progress: boolean;
}; };
const DashboarDevicesDialog = ({ const DashboarDevicesDialog = ({
@@ -43,7 +46,8 @@ const DashboarDevicesDialog = ({
onSave, onSave,
selectedItem, selectedItem,
writeable, writeable,
validator validator,
progress
}: DashboardDevicesDialogProps) => { }: DashboardDevicesDialogProps) => {
const { LL } = useI18nContext(); const { LL } = useI18nContext();
const [editItem, setEditItem] = useState<DeviceValue>(selectedItem); const [editItem, setEditItem] = useState<DeviceValue>(selectedItem);
@@ -184,14 +188,32 @@ const DashboarDevicesDialog = ({
<DialogActions> <DialogActions>
{writeable ? ( {writeable ? (
<> <Box
sx={{
'& button, & a, & .MuiCard-root': {
mx: 0.6
},
position: 'relative'
}}
>
<Button startIcon={<CancelIcon />} variant="outlined" onClick={close} color="secondary"> <Button startIcon={<CancelIcon />} variant="outlined" onClick={close} color="secondary">
{LL.CANCEL()} {LL.CANCEL()}
</Button> </Button>
<Button startIcon={<WarningIcon color="warning" />} variant="contained" onClick={save} color="info"> <Button startIcon={<WarningIcon color="warning" />} variant="contained" onClick={save} color="info">
{selectedItem.v === '' && selectedItem.c ? LL.EXECUTE() : LL.UPDATE()} {selectedItem.v === '' && selectedItem.c ? LL.EXECUTE() : LL.UPDATE()}
</Button> </Button>
</> {progress && (
<CircularProgress
size={24}
sx={{
color: green[500],
position: 'absolute',
right: '20%',
marginTop: '6px'
}}
/>
)}
</Box>
) : ( ) : (
<Button variant="outlined" onClick={close} color="secondary"> <Button variant="outlined" onClick={close} color="secondary">
{LL.CLOSE()} {LL.CLOSE()}

View File

@@ -1,3 +1,4 @@
import { unpack } from '../api/unpack';
import type { import type {
BoardProfile, BoardProfile,
BoardProfileName, BoardProfileName,
@@ -15,10 +16,28 @@ import type {
WriteAnalogSensor, WriteAnalogSensor,
SensorData, SensorData,
Schedule, Schedule,
Entities Entities,
DeviceValue
} from './types'; } from './types';
import type { AxiosPromise } from 'axios'; import type { AxiosPromise } from 'axios';
import { AXIOS, AXIOS_API, AXIOS_BIN } from 'api/endpoints'; import { AXIOS, AXIOS_API, AXIOS_BIN, alovaInstance } from 'api/endpoints';
export const readCoreData = () => alovaInstance.Get<CoreData>(`/coreData`);
// uses msgpack
export const readDeviceData = (id: number) =>
alovaInstance.Get<DeviceData>('/deviceData', {
params: { id },
responseType: 'arraybuffer',
transformData(data) {
return unpack(data);
}
});
export const writeDeviceValue = (id: number, devicevalue: DeviceValue) =>
alovaInstance.Post('/writeDeviceValue', { id, devicevalue });
// TODO to change to alova
export function restart(): AxiosPromise<void> { export function restart(): AxiosPromise<void> {
return AXIOS.post('/restart'); return AXIOS.post('/restart');
@@ -29,9 +48,10 @@ export function readSettings(): AxiosPromise<Settings> {
} }
export function writeSettings(settings: Settings): AxiosPromise<Settings> { export function writeSettings(settings: Settings): AxiosPromise<Settings> {
return AXIOS.post('/settings', settings); return AXIOS.post('/settings', settings); // call command
} }
// TODO change to GET
export function getBoardProfile(boardProfile: BoardProfileName): AxiosPromise<BoardProfile> { export function getBoardProfile(boardProfile: BoardProfileName): AxiosPromise<BoardProfile> {
return AXIOS.post('/boardProfile', boardProfile); return AXIOS.post('/boardProfile', boardProfile);
} }
@@ -40,26 +60,19 @@ export function readStatus(): AxiosPromise<Status> {
return AXIOS.get('/status'); return AXIOS.get('/status');
} }
export function readCoreData(): AxiosPromise<CoreData> {
return AXIOS.get('/coreData');
}
export function readDevices(): AxiosPromise<Devices> { export function readDevices(): AxiosPromise<Devices> {
return AXIOS.get('/devices'); return AXIOS.get('/devices');
} }
export function scanDevices(): AxiosPromise<void> { export function scanDevices(): AxiosPromise<void> {
return AXIOS.post('/scanDevices'); return AXIOS.post('/scanDevices'); // call command
}
export function readDeviceData(unique_id: UniqueID): AxiosPromise<DeviceData> {
return AXIOS_BIN.post('/deviceData', unique_id);
} }
export function readSensorData(): AxiosPromise<SensorData> { export function readSensorData(): AxiosPromise<SensorData> {
return AXIOS.get('/sensorData'); return AXIOS.get('/sensorData');
} }
// TODO change to GET
export function readDeviceEntities(unique_id: UniqueID): AxiosPromise<DeviceEntity[]> { export function readDeviceEntities(unique_id: UniqueID): AxiosPromise<DeviceEntity[]> {
return AXIOS_BIN.post('/deviceEntities', unique_id); return AXIOS_BIN.post('/deviceEntities', unique_id);
} }
@@ -68,10 +81,6 @@ export function writeCustomEntities(customEntities: CustomEntities): AxiosPromis
return AXIOS.post('/customEntities', customEntities); return AXIOS.post('/customEntities', customEntities);
} }
export function writeDeviceValue(dv: WriteDeviceValue): AxiosPromise<void> {
return AXIOS.post('/writeDeviceValue', dv);
}
export function writeTemperatureSensor(ts: WriteTemperatureSensor): AxiosPromise<void> { export function writeTemperatureSensor(ts: WriteTemperatureSensor): AxiosPromise<void> {
return AXIOS.post('/writeTemperatureSensor', ts); return AXIOS.post('/writeTemperatureSensor', ts);
} }
@@ -81,11 +90,11 @@ export function writeAnalogSensor(as: WriteAnalogSensor): AxiosPromise<void> {
} }
export function resetCustomizations(): AxiosPromise<void> { export function resetCustomizations(): AxiosPromise<void> {
return AXIOS.post('/resetCustomizations'); return AXIOS.post('/resetCustomizations'); // command
} }
export function API(apiCall: APIcall): AxiosPromise<void> { export function API(apiCall: APIcall): AxiosPromise<void> {
return AXIOS_API.post('/', apiCall); return AXIOS_API.post('/', apiCall); // command
} }
export function getSettings(): AxiosPromise<void> { export function getSettings(): AxiosPromise<void> {

View File

@@ -156,6 +156,7 @@ export interface CustomEntities {
entity_ids: string[]; entity_ids: string[];
} }
// TODO can be removed?
export interface UniqueID { export interface UniqueID {
id: number; id: number;
} }
@@ -279,6 +280,7 @@ export interface APIcall {
id: any; id: any;
} }
// TODO can be removed?
export interface WriteDeviceValue { export interface WriteDeviceValue {
id: number; id: number;
devicevalue: DeviceValue; devicevalue: DeviceValue;

View File

@@ -5,6 +5,13 @@ __metadata:
version: 6 version: 6
cacheKey: 8c0 cacheKey: 8c0
"@alova/adapter-xhr@npm:^1.0.0":
version: 1.0.0
resolution: "@alova/adapter-xhr@npm:1.0.0"
checksum: 87c8be0cbb4a110921811cd1d772b18d59c220d286aaae8f70977f4116422f5692b1fcacd7d6914134a62c0111ee8f9406ac99048186a648034a3e457dcbf055
languageName: node
linkType: hard
"@ampproject/remapping@npm:^2.2.0": "@ampproject/remapping@npm:^2.2.0":
version: 2.2.0 version: 2.2.0
resolution: "@ampproject/remapping@npm:2.2.0" resolution: "@ampproject/remapping@npm:2.2.0"
@@ -1101,90 +1108,90 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"@swc/core-darwin-arm64@npm:1.3.56": "@swc/core-darwin-arm64@npm:1.3.62":
version: 1.3.56 version: 1.3.62
resolution: "@swc/core-darwin-arm64@npm:1.3.56" resolution: "@swc/core-darwin-arm64@npm:1.3.62"
conditions: os=darwin & cpu=arm64 conditions: os=darwin & cpu=arm64
languageName: node languageName: node
linkType: hard linkType: hard
"@swc/core-darwin-x64@npm:1.3.56": "@swc/core-darwin-x64@npm:1.3.62":
version: 1.3.56 version: 1.3.62
resolution: "@swc/core-darwin-x64@npm:1.3.56" resolution: "@swc/core-darwin-x64@npm:1.3.62"
conditions: os=darwin & cpu=x64 conditions: os=darwin & cpu=x64
languageName: node languageName: node
linkType: hard linkType: hard
"@swc/core-linux-arm-gnueabihf@npm:1.3.56": "@swc/core-linux-arm-gnueabihf@npm:1.3.62":
version: 1.3.56 version: 1.3.62
resolution: "@swc/core-linux-arm-gnueabihf@npm:1.3.56" resolution: "@swc/core-linux-arm-gnueabihf@npm:1.3.62"
conditions: os=linux & cpu=arm conditions: os=linux & cpu=arm
languageName: node languageName: node
linkType: hard linkType: hard
"@swc/core-linux-arm64-gnu@npm:1.3.56": "@swc/core-linux-arm64-gnu@npm:1.3.62":
version: 1.3.56 version: 1.3.62
resolution: "@swc/core-linux-arm64-gnu@npm:1.3.56" resolution: "@swc/core-linux-arm64-gnu@npm:1.3.62"
conditions: os=linux & cpu=arm64 & libc=glibc conditions: os=linux & cpu=arm64 & libc=glibc
languageName: node languageName: node
linkType: hard linkType: hard
"@swc/core-linux-arm64-musl@npm:1.3.56": "@swc/core-linux-arm64-musl@npm:1.3.62":
version: 1.3.56 version: 1.3.62
resolution: "@swc/core-linux-arm64-musl@npm:1.3.56" resolution: "@swc/core-linux-arm64-musl@npm:1.3.62"
conditions: os=linux & cpu=arm64 & libc=musl conditions: os=linux & cpu=arm64 & libc=musl
languageName: node languageName: node
linkType: hard linkType: hard
"@swc/core-linux-x64-gnu@npm:1.3.56": "@swc/core-linux-x64-gnu@npm:1.3.62":
version: 1.3.56 version: 1.3.62
resolution: "@swc/core-linux-x64-gnu@npm:1.3.56" resolution: "@swc/core-linux-x64-gnu@npm:1.3.62"
conditions: os=linux & cpu=x64 & libc=glibc conditions: os=linux & cpu=x64 & libc=glibc
languageName: node languageName: node
linkType: hard linkType: hard
"@swc/core-linux-x64-musl@npm:1.3.56": "@swc/core-linux-x64-musl@npm:1.3.62":
version: 1.3.56 version: 1.3.62
resolution: "@swc/core-linux-x64-musl@npm:1.3.56" resolution: "@swc/core-linux-x64-musl@npm:1.3.62"
conditions: os=linux & cpu=x64 & libc=musl conditions: os=linux & cpu=x64 & libc=musl
languageName: node languageName: node
linkType: hard linkType: hard
"@swc/core-win32-arm64-msvc@npm:1.3.56": "@swc/core-win32-arm64-msvc@npm:1.3.62":
version: 1.3.56 version: 1.3.62
resolution: "@swc/core-win32-arm64-msvc@npm:1.3.56" resolution: "@swc/core-win32-arm64-msvc@npm:1.3.62"
conditions: os=win32 & cpu=arm64 conditions: os=win32 & cpu=arm64
languageName: node languageName: node
linkType: hard linkType: hard
"@swc/core-win32-ia32-msvc@npm:1.3.56": "@swc/core-win32-ia32-msvc@npm:1.3.62":
version: 1.3.56 version: 1.3.62
resolution: "@swc/core-win32-ia32-msvc@npm:1.3.56" resolution: "@swc/core-win32-ia32-msvc@npm:1.3.62"
conditions: os=win32 & cpu=ia32 conditions: os=win32 & cpu=ia32
languageName: node languageName: node
linkType: hard linkType: hard
"@swc/core-win32-x64-msvc@npm:1.3.56": "@swc/core-win32-x64-msvc@npm:1.3.62":
version: 1.3.56 version: 1.3.62
resolution: "@swc/core-win32-x64-msvc@npm:1.3.56" resolution: "@swc/core-win32-x64-msvc@npm:1.3.62"
conditions: os=win32 & cpu=x64 conditions: os=win32 & cpu=x64
languageName: node languageName: node
linkType: hard linkType: hard
"@swc/core@npm:^1.3.56": "@swc/core@npm:^1.3.61":
version: 1.3.56 version: 1.3.62
resolution: "@swc/core@npm:1.3.56" resolution: "@swc/core@npm:1.3.62"
dependencies: dependencies:
"@swc/core-darwin-arm64": 1.3.56 "@swc/core-darwin-arm64": 1.3.62
"@swc/core-darwin-x64": 1.3.56 "@swc/core-darwin-x64": 1.3.62
"@swc/core-linux-arm-gnueabihf": 1.3.56 "@swc/core-linux-arm-gnueabihf": 1.3.62
"@swc/core-linux-arm64-gnu": 1.3.56 "@swc/core-linux-arm64-gnu": 1.3.62
"@swc/core-linux-arm64-musl": 1.3.56 "@swc/core-linux-arm64-musl": 1.3.62
"@swc/core-linux-x64-gnu": 1.3.56 "@swc/core-linux-x64-gnu": 1.3.62
"@swc/core-linux-x64-musl": 1.3.56 "@swc/core-linux-x64-musl": 1.3.62
"@swc/core-win32-arm64-msvc": 1.3.56 "@swc/core-win32-arm64-msvc": 1.3.62
"@swc/core-win32-ia32-msvc": 1.3.56 "@swc/core-win32-ia32-msvc": 1.3.62
"@swc/core-win32-x64-msvc": 1.3.56 "@swc/core-win32-x64-msvc": 1.3.62
peerDependencies: peerDependencies:
"@swc/helpers": ^0.5.0 "@swc/helpers": ^0.5.0
dependenciesMeta: dependenciesMeta:
@@ -1211,7 +1218,7 @@ __metadata:
peerDependenciesMeta: peerDependenciesMeta:
"@swc/helpers": "@swc/helpers":
optional: true optional: true
checksum: c468e281f0249742bc0ba4b7cd4076cdbf87bfc82b8bd5ad1ca8940d36372ca22754df80ab54b22613121680718eab26b92c48c8c9f5f3abb24434f05e5e1ea0 checksum: aaa0827960f656c762733836938d31b2d596495b8430eb6feb0d1f6b1416b3444e7b59c326ae37ee410d8d3d25fff20ac8ff0f66ebe8a87e7fae1ca651aff915
languageName: node languageName: node
linkType: hard linkType: hard
@@ -1507,14 +1514,14 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"@vitejs/plugin-react-swc@npm:^3.3.1": "@vitejs/plugin-react-swc@npm:^3.3.2":
version: 3.3.1 version: 3.3.2
resolution: "@vitejs/plugin-react-swc@npm:3.3.1" resolution: "@vitejs/plugin-react-swc@npm:3.3.2"
dependencies: dependencies:
"@swc/core": ^1.3.56 "@swc/core": ^1.3.61
peerDependencies: peerDependencies:
vite: ^4 vite: ^4
checksum: 72ab0a72d41c949009a2f71836894fb0003939329a2d1bb59b1181b03d21fda5002ccd20b40b48ddc8f12511cc8717122141f49ac51e97263df3c3f3142ae937 checksum: 8544023de3dc605d00f66db10de085b2a90887111657db87dd192e02ffc1e4a191b09d58180b4ba498858f01e8861d15e216d744e0f6dfad2550065999890fb2
languageName: node languageName: node
linkType: hard linkType: hard
@@ -1522,6 +1529,7 @@ __metadata:
version: 0.0.0-use.local version: 0.0.0-use.local
resolution: "EMS-ESP@workspace:." resolution: "EMS-ESP@workspace:."
dependencies: dependencies:
"@alova/adapter-xhr": ^1.0.0
"@emotion/react": ^11.11.0 "@emotion/react": ^11.11.0
"@emotion/styled": ^11.11.0 "@emotion/styled": ^11.11.0
"@mui/icons-material": ^5.11.16 "@mui/icons-material": ^5.11.16
@@ -1534,7 +1542,8 @@ __metadata:
"@types/react-router-dom": ^5.3.3 "@types/react-router-dom": ^5.3.3
"@typescript-eslint/eslint-plugin": ^5.59.8 "@typescript-eslint/eslint-plugin": ^5.59.8
"@typescript-eslint/parser": ^5.59.8 "@typescript-eslint/parser": ^5.59.8
"@vitejs/plugin-react-swc": ^3.3.1 "@vitejs/plugin-react-swc": ^3.3.2
alova: ^2.5.4
async-validator: ^4.2.5 async-validator: ^4.2.5
axios: ^1.4.0 axios: ^1.4.0
eslint: ^8.42.0 eslint: ^8.42.0
@@ -1638,6 +1647,13 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"alova@npm:^2.5.4":
version: 2.5.4
resolution: "alova@npm:2.5.4"
checksum: f58698009419025a50653a9c64a0d497e3cd64448877bfa64f9907878a09eb9f965609fc5950c93b85e37c67099445c28e39ee677d98e6ec665eab5f66a359cd
languageName: node
linkType: hard
"ansi-regex@npm:^5.0.1": "ansi-regex@npm:^5.0.1":
version: 5.0.1 version: 5.0.1
resolution: "ansi-regex@npm:5.0.1" resolution: "ansi-regex@npm:5.0.1"

View File

@@ -11,6 +11,9 @@ rest_server.use(compression());
rest_server.use(express.static(path.join(__dirname, '../interface/build'))); rest_server.use(express.static(path.join(__dirname, '../interface/build')));
rest_server.use(express.json()); rest_server.use(express.json());
// FOR TESTING
const delay = (ms) => new Promise((res) => setTimeout(res, ms));
// endpoints // endpoints
const API_ENDPOINT_ROOT = '/api/'; const API_ENDPOINT_ROOT = '/api/';
const REST_ENDPOINT_ROOT = '/rest/'; const REST_ENDPOINT_ROOT = '/rest/';
@@ -2146,8 +2149,9 @@ rest_server.post(EMSESP_SCANDEVICES_ENDPOINT, (req, res) => {
rest_server.get(EMSESP_STATUS_ENDPOINT, (req, res) => { rest_server.get(EMSESP_STATUS_ENDPOINT, (req, res) => {
res.json(status); res.json(status);
}); });
rest_server.post(EMSESP_DEVICEDATA_ENDPOINT, (req, res) => {
const id = req.body.id; rest_server.get(EMSESP_DEVICEDATA_ENDPOINT, (req, res) => {
const id = Number(req.query.id);
console.log('send back device data for ' + id); console.log('send back device data for ' + id);
let data = {}; let data = {};
@@ -2204,7 +2208,6 @@ rest_server.post(EMSESP_DEVICEENTITIES_ENDPOINT, (req, res) => {
if (id === 7) { if (id === 7) {
data = emsesp_deviceentities_7; data = emsesp_deviceentities_7;
} }
res.write(msgpack.encode(data), 'binary'); res.write(msgpack.encode(data), 'binary');
res.end(null, 'binary'); res.end(null, 'binary');
}); });
@@ -2332,51 +2335,47 @@ rest_server.post(EMSESP_WRITE_ENTITIES_ENDPOINT, (req, res) => {
res.sendStatus(200); res.sendStatus(200);
}); });
rest_server.post(EMSESP_WRITE_VALUE_ENDPOINT, (req, res) => { rest_server.post(EMSESP_WRITE_VALUE_ENDPOINT, async (req, res) => {
const devicevalue = req.body.devicevalue; const devicevalue = req.body.devicevalue;
const id = req.body.id; const id = req.body.id;
console.log('Write device value for id : ' + id);
console.log(' devicedata: ' + JSON.stringify(devicevalue));
if (id === 1) { if (id === 1) {
console.log('Write device value for: ' + JSON.stringify(devicevalue));
objIndex = emsesp_devicedata_1.data.findIndex((obj) => obj.c == devicevalue.c); objIndex = emsesp_devicedata_1.data.findIndex((obj) => obj.c == devicevalue.c);
emsesp_devicedata_1.data[objIndex] = devicevalue; emsesp_devicedata_1.data[objIndex] = devicevalue;
} }
if (id === 2) { if (id === 2) {
console.log('Write device value for: ' + JSON.stringify(devicevalue));
objIndex = emsesp_devicedata_2.data.findIndex((obj) => obj.c == devicevalue.c); objIndex = emsesp_devicedata_2.data.findIndex((obj) => obj.c == devicevalue.c);
emsesp_devicedata_2.data[objIndex] = devicevalue; emsesp_devicedata_2.data[objIndex] = devicevalue;
} }
if (id === 3) { if (id === 3) {
console.log('Write device value for: ' + JSON.stringify(devicevalue));
objIndex = emsesp_devicedata_3.data.findIndex((obj) => obj.c == devicevalue.c); objIndex = emsesp_devicedata_3.data.findIndex((obj) => obj.c == devicevalue.c);
emsesp_devicedata_3.data[objIndex] = devicevalue; emsesp_devicedata_3.data[objIndex] = devicevalue;
} }
if (id === 4) { if (id === 4) {
console.log('Write device value for: ' + JSON.stringify(devicevalue));
objIndex = emsesp_devicedata_4.data.findIndex((obj) => obj.c == devicevalue.c); objIndex = emsesp_devicedata_4.data.findIndex((obj) => obj.c == devicevalue.c);
emsesp_devicedata_4.data[objIndex] = devicevalue; emsesp_devicedata_4.data[objIndex] = devicevalue;
} }
if (id === 5) { if (id === 5) {
console.log('Write device value for: ' + JSON.stringify(devicevalue));
objIndex = emsesp_devicedata_5.data.findIndex((obj) => obj.c == devicevalue.c); objIndex = emsesp_devicedata_5.data.findIndex((obj) => obj.c == devicevalue.c);
emsesp_devicedata_5.data[objIndex] = devicevalue; emsesp_devicedata_5.data[objIndex] = devicevalue;
} }
if (id === 6) { if (id === 6) {
console.log('Write device value for: ' + JSON.stringify(devicevalue));
objIndex = emsesp_devicedata_6.data.findIndex((obj) => obj.c == devicevalue.c); objIndex = emsesp_devicedata_6.data.findIndex((obj) => obj.c == devicevalue.c);
emsesp_devicedata_6.data[objIndex] = devicevalue; emsesp_devicedata_6.data[objIndex] = devicevalue;
} }
if (id === 7) { if (id === 7) {
console.log('Write device value for: ' + JSON.stringify(devicevalue));
objIndex = emsesp_devicedata_7.data.findIndex((obj) => obj.c == devicevalue.c); objIndex = emsesp_devicedata_7.data.findIndex((obj) => obj.c == devicevalue.c);
emsesp_devicedata_7.data[objIndex] = devicevalue; emsesp_devicedata_7.data[objIndex] = devicevalue;
} }
if (id === 99) { if (id === 99) {
console.log('Write device value for: ' + JSON.stringify(devicevalue));
objIndex = emsesp_devicedata_99.data.findIndex((obj) => obj.c == devicevalue.c); objIndex = emsesp_devicedata_99.data.findIndex((obj) => obj.c == devicevalue.c);
emsesp_devicedata_99.data[objIndex] = devicevalue; emsesp_devicedata_99.data[objIndex] = devicevalue;
} }
// await delay(2000); // wait 2 seconds to show spinner
res.sendStatus(200); res.sendStatus(200);
}); });