Skip to content

Commit

Permalink
Add debug flag to App.js
Browse files Browse the repository at this point in the history
  • Loading branch information
Luligu committed Jan 7, 2025
1 parent 518857e commit 74ab22f
Show file tree
Hide file tree
Showing 9 changed files with 47 additions and 41 deletions.
6 changes: 3 additions & 3 deletions frontend/build/asset-manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"files": {
"main.css": "./static/css/main.24deed52.css",
"main.js": "./static/js/main.0f6c6492.js",
"main.js": "./static/js/main.c12f124b.js",
"static/js/453.abd36b29.chunk.js": "./static/js/453.abd36b29.chunk.js",
"static/media/roboto-latin-700-normal.woff2": "./static/media/roboto-latin-700-normal.4535474e1cf8598695ad.woff2",
"static/media/roboto-latin-500-normal.woff2": "./static/media/roboto-latin-500-normal.7077203b1982951ecf76.woff2",
Expand Down Expand Up @@ -61,11 +61,11 @@
"static/media/roboto-greek-ext-400-normal.woff": "./static/media/roboto-greek-ext-400-normal.16eb83b4a3b1ea994243.woff",
"index.html": "./index.html",
"main.24deed52.css.map": "./static/css/main.24deed52.css.map",
"main.0f6c6492.js.map": "./static/js/main.0f6c6492.js.map",
"main.c12f124b.js.map": "./static/js/main.c12f124b.js.map",
"453.abd36b29.chunk.js.map": "./static/js/453.abd36b29.chunk.js.map"
},
"entrypoints": [
"static/css/main.24deed52.css",
"static/js/main.0f6c6492.js"
"static/js/main.c12f124b.js"
]
}
2 changes: 1 addition & 1 deletion frontend/build/index.html
Original file line number Diff line number Diff line change
@@ -1 +1 @@
<!doctype html><html lang="en"><head><meta charset="utf-8"/><base href="./"><link rel="icon" href="./matterbridge 32x32.png"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="theme-color" content="#000000"/><title>Matterbridge</title><link rel="manifest" href="./manifest.json"/><script defer="defer" src="./static/js/main.0f6c6492.js"></script><link href="./static/css/main.24deed52.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div></body></html>
<!doctype html><html lang="en"><head><meta charset="utf-8"/><base href="./"><link rel="icon" href="./matterbridge 32x32.png"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="theme-color" content="#000000"/><title>Matterbridge</title><link rel="manifest" href="./manifest.json"/><script defer="defer" src="./static/js/main.c12f124b.js"></script><link href="./static/css/main.24deed52.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div></body></html>
1 change: 0 additions & 1 deletion frontend/build/static/js/main.0f6c6492.js.map

This file was deleted.

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions frontend/build/static/js/main.c12f124b.js.map

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions frontend/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import Logs from './components/Logs';
import { WebSocketProvider } from './components/WebSocketProvider';
import { createMuiTheme, getCssVariable } from './components/muiTheme';

export const debug = false;

// Create a context for the authentication state
const AuthContext = createContext();

Expand Down
49 changes: 24 additions & 25 deletions frontend/src/components/Test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,8 @@ import DialogActions from '@mui/material/DialogActions';
import Button from '@mui/material/Button';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import FormGroup from '@mui/material/FormGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';
import IconButton from '@mui/material/IconButton';
import Tooltip from '@mui/material/Tooltip';

// @mui/icons-material
import SettingsIcon from '@mui/icons-material/Settings';
import Battery4BarIcon from '@mui/icons-material/Battery4Bar';
import ElectricalServicesIcon from '@mui/icons-material/ElectricalServices';
import WifiIcon from '@mui/icons-material/Wifi';
Expand All @@ -29,17 +23,16 @@ import LightModeIcon from '@mui/icons-material/LightMode';
import FilterDramaIcon from '@mui/icons-material/FilterDrama'; // Cloud for weather
import ThermostatIcon from '@mui/icons-material/Thermostat'; // Temperature
import WaterDropIcon from '@mui/icons-material/WaterDrop'; // Humidity
import ThermostatAutoIcon from '@mui/icons-material/ThermostatAuto'; // ThermostatAuto for heating
import LightbulbIcon from '@mui/icons-material/Lightbulb';
import OutletIcon from '@mui/icons-material/Outlet';
import ToggleOnIcon from '@mui/icons-material/ToggleOn';
import BlindsIcon from '@mui/icons-material/Blinds';
import PowerIcon from '@mui/icons-material/Power';

// Frontend
import { WebSocketContext } from './WebSocketProvider';
import { Connecting } from './Connecting';

const debug = true;
import { debug } from '../App';

function Test() {
// WebSocket context
Expand All @@ -58,29 +51,29 @@ function Test() {
const handleWebSocketMessage = (msg) => {
if (msg.src === 'Matterbridge' && msg.dst === 'Frontend') {
if (msg.method === 'refresh_required') {
console.log('Test received refresh_required and sending api requests');
if(debug) console.log('Test received refresh_required and sending api requests');
sendMessage({ method: "/api/settings", src: "Frontend", dst: "Matterbridge", params: {} });
sendMessage({ method: "/api/plugins", src: "Frontend", dst: "Matterbridge", params: {} });
sendMessage({ method: "/api/devices", src: "Frontend", dst: "Matterbridge", params: {} });
}
if (msg.method === '/api/settings' && msg.response) {
console.log('Test received settings:', msg.response);
if(debug) console.log('Test received settings:', msg.response);
setSettings(msg.response);
}
if (msg.method === '/api/plugins' && msg.response) {
console.log('Test received plugins:', msg.response);
if(debug) console.log('Test received plugins:', msg.response);
setPlugins(msg.response);
}
if (msg.method === '/api/devices' && msg.response) {
console.log(`Test received ${msg.response.length} devices:`, msg.response);
if(debug) console.log(`Test received ${msg.response.length} devices:`, msg.response);
setDevices(msg.response);
for(let device of msg.response) {
console.log('Test sending /api/clusters');
if(debug) console.log('Test sending /api/clusters');
sendMessage({ method: "/api/clusters", src: "Frontend", dst: "Matterbridge", params: { plugin: device.pluginName, endpoint: device.endpoint } });
}
}
if (msg.method === '/api/clusters' && msg.response) {
console.log(`Test received for device "${msg.deviceName}" serial "${msg.serialNumber}" deviceType ${msg.deviceTypes.join(' ')} clusters (${msg.response.length}):`, msg.response);
if(debug) console.log(`Test received for device "${msg.deviceName}" serial "${msg.serialNumber}" deviceType ${msg.deviceTypes.join(' ')} clusters (${msg.response.length}):`, msg.response);
if(msg.response.length === 0) return;
const serial = msg.serialNumber;
endpoints[serial] = [];
Expand All @@ -90,40 +83,40 @@ function Test() {
if(!endpoints[serial].find((e) => e.endpoint === cluster.endpoint)) {
endpoints[serial].push({ endpoint: cluster.endpoint, id: cluster.id, deviceTypes: cluster.deviceTypes });
}
if(['FixedLabel', 'Descriptor', 'Identify', 'Groups', 'PowerTopology', 'ElectricalPowerMeasurement', 'ElectricalEnergyMeasurement'].includes(cluster.clusterName)) continue;
if(['FixedLabel', 'Descriptor', 'Identify', 'Groups', 'PowerTopology', 'ElectricalPowerMeasurement'].includes(cluster.clusterName)) continue;
clusters[serial].push(cluster);
}
setEndpoints({ ...endpoints });
setdDeviceTypes({ ...deviceTypes });
setClusters({ ...clusters });
console.log(`Test endpoints for "${serial}":`, endpoints[serial]);
console.log(`Test deviceTypes for "${serial}":`, deviceTypes[serial]);
console.log(`Test clusters for "${serial}":`, clusters[serial]);
if(debug) console.log(`Test endpoints for "${serial}":`, endpoints[serial]);
if(debug) console.log(`Test deviceTypes for "${serial}":`, deviceTypes[serial]);
if(debug) console.log(`Test clusters for "${serial}":`, clusters[serial]);
}
}
};

addListener(handleWebSocketMessage);
console.log('Test useEffect webSocket mounted');
if(debug) console.log('Test useEffect webSocket mounted');

return () => {
removeListener(handleWebSocketMessage);
console.log('Test useEffect webSocket unmounted');
if(debug) console.log('Test useEffect webSocket unmounted');
};
}, []);

useEffect(() => {
console.log('Test useEffect online mounting');
if(debug) console.log('Test useEffect online mounting');
if(online) {
console.log('Test useEffect online sending api requests');
if(debug) console.log('Test useEffect online sending api requests');
sendMessage({ method: "/api/settings", src: "Frontend", dst: "Matterbridge", params: {} });
sendMessage({ method: "/api/plugins", src: "Frontend", dst: "Matterbridge", params: {} });
sendMessage({ method: "/api/devices", src: "Frontend", dst: "Matterbridge", params: {} });
}
console.log('Test useEffect online mounted');
if(debug) console.log('Test useEffect online mounted');

return () => {
console.log('Test useEffect online unmounted');
if(debug) console.log('Test useEffect online unmounted');
};
}, [online, sendMessage]);

Expand Down Expand Up @@ -288,6 +281,12 @@ function Device({ device, endpoint, id, deviceType, clusters }) {
<RenderValueUnit cluster={cluster} value={Math.round(Math.pow(10, cluster.attributeValue / 10000))} unit='lx' />
</Box>
))}
{deviceType===0x0510 && clusters.filter(cluster => cluster.clusterName === 'ElectricalEnergyMeasurement' && cluster.attributeName === 'cumulativeEnergyImported').map(cluster => (
<Box sx={valueBoxSx}>
<PowerIcon sx={iconSx} />
<RenderValueUnit cluster={cluster} value={Math.round(cluster.attributeLocalValue?.energy / 1000000)} unit='kwh' />
</Box>
))}
<Box sx={{ display: 'flex', gap: '2px', justifyContent: 'center', width: '100%', height: '18px' }}>
<Typography sx={detailsSx}>{details}</Typography>
</Box>
Expand Down
19 changes: 12 additions & 7 deletions frontend/src/components/WebSocketProvider.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
// React
import React, { useEffect, useRef, useState, useCallback, useMemo, createContext } from 'react';

// Local modules
import { debug } from '../App';

/**
* Websocket message IDs taken from matterbridgeWebsocket.ts
*/
Expand Down Expand Up @@ -54,7 +57,7 @@ export function WebSocketProvider({ children }) {
if(message.id===undefined) message.id = uniqueIdRef.current;
const msg = JSON.stringify(message);
wsRef.current.send(msg);
console.log(`WebSocket sent message:`, message);
if(debug) console.log(`WebSocket sent message:`, message);
} catch (error) {
// eslint-disable-next-line no-console
console.error(`WebSocket error sending message: ${error}`);
Expand All @@ -78,13 +81,13 @@ export function WebSocketProvider({ children }) {
const addListener = useCallback((listener) => {
// console.log(`WebSocket addListener:`, listener);
listenersRef.current = [...listenersRef.current, listener];
console.log(`WebSocket addListener total listeners:`, listenersRef.current.length);
if(debug) console.log(`WebSocket addListener total listeners:`, listenersRef.current.length);
}, []);

const removeListener = useCallback((listener) => {
// console.log(`WebSocket removeListener:`, listener);
listenersRef.current = listenersRef.current.filter(l => l !== listener);
console.log(`WebSocket removeListener total listeners:`, listenersRef.current.length);
if(debug) console.log(`WebSocket removeListener total listeners:`, listenersRef.current.length);
}, []);

const connectWebSocket = useCallback(() => {
Expand All @@ -105,12 +108,12 @@ export function WebSocketProvider({ children }) {
if(msg.id===undefined) {
return; // Ignore messages without an ID
} else if(msg.id===WS_ID_REFRESH_NEEDED) {
console.log(`WebSocket WS_ID_REFRESH_NEEDED message:`, msg, 'listeners:', listenersRef.current.length);
if(debug) console.log(`WebSocket WS_ID_REFRESH_NEEDED message:`, msg, 'listeners:', listenersRef.current.length);
setRefresh(true);
listenersRef.current.forEach(listener => listener(msg)); // Notify all listeners
return;
} else if(msg.id===WS_ID_RESTART_NEEDED) {
console.log(`WebSocket WS_ID_RESTART_NEEDED message:`, msg, 'listeners:', listenersRef.current.length);
if(debug) console.log(`WebSocket WS_ID_RESTART_NEEDED message:`, msg, 'listeners:', listenersRef.current.length);
setRestart(true);
listenersRef.current.forEach(listener => listener(msg)); // Notify all listeners
return;
Expand Down Expand Up @@ -141,7 +144,6 @@ export function WebSocketProvider({ children }) {

setMessages(prevMessages => {
// Create new array with new message
// const timeString = `${now.getHours().toString().padStart(2,'0')}:${now.getMinutes().toString().padStart(2,'0')}:${now.getSeconds().toString().padStart(2,'0')}.${now.getMilliseconds().toString().padStart(3,'0')}`;
const timeString = `<span style="color: #505050;">[${msg.time}]</span>`;
const getsubTypeMessageBgColor = (level) => {
switch (level.toLowerCase()) {
Expand Down Expand Up @@ -195,13 +197,15 @@ export function WebSocketProvider({ children }) {
sendMessage({ id: uniqueIdRef.current, method: "ping", src: "Frontend", dst: "Matterbridge", params: {} });
clearTimeout(offlineTimeoutRef.current);
offlineTimeoutRef.current = setTimeout(() => {
console.error(`WebSocketUse: No pong response received from WebSocket: ${wssHost}`);
logMessage('WebSocket', `No pong response received from WebSocket: ${wssHost}`);
setOnline(false);
}, 1000 * offlineTimeoutSeconds);
}, 1000 * pingIntervalSeconds);
};

wsRef.current.onclose = () => {
console.error(`WebSocketUse: Disconnected from WebSocket: ${wssHost}`);
logMessage('WebSocket', `Disconnected from WebSocket: ${wssHost}`);
setOnline(false);
clearTimeout(offlineTimeoutRef.current);
Expand All @@ -214,12 +218,13 @@ export function WebSocketProvider({ children }) {
};

wsRef.current.onerror = (error) => {
console.error(`WebSocketUse: WebSocket error connecting to ${wssHost}:`, error);
logMessage('WebSocket', `WebSocket error connecting to ${wssHost}`);
};
}, [wssHost]);

const attemptReconnect = useCallback(() => {
console.log(`WebSocket attemptReconnect ${retryCountRef.current}/${maxRetries} to:`, wssHost);
if(debug) console.log(`WebSocket attemptReconnect ${retryCountRef.current}/${maxRetries} to:`, wssHost);
connectWebSocket();
}, [connectWebSocket]);

Expand Down

0 comments on commit 74ab22f

Please sign in to comment.