matterbridge 2.1.5-dev.2 → 2.1.5-dev.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -33,16 +33,25 @@ matterbridge-zigbee2mqtt v. 2.4.4
33
33
  matterbridge-somfy-tahoma v. 1.2.3
34
34
  matterbridge-hass v. 0.0.8
35
35
 
36
- ## [2.1.5] - 2025-02-08
36
+ ## [2.1.5] - 2025-02-09
37
37
 
38
38
  ### Added
39
39
 
40
+ - [frontend]: Frontend v.2.4.1.
41
+ - [frontend]: Optimized rendering of all pages.
42
+ - [frontend]: Added cpuUsed, rss and heapUsed to SystemInformation.
43
+ - [frontend]: Added UiProvider.
44
+ - [frontend]: Added wssSendCpuUpdate, wssSendMemoryUpdate and wssSendSnackbarMessage.
45
+
40
46
  ### Changed
41
47
 
42
48
  - [matterbridge]: Calls getNpmPackageVersion() instead of npm to get latest version.
49
+ - [matterbridge]: Memory optimization on MatterbridgeEndpoint.
43
50
 
44
51
  ### Fixed
45
52
 
53
+ - [matterbridge]: Refactor shutdown sequences for reset and factory reset.
54
+
46
55
  <a href="https://www.buymeacoffee.com/luligugithub">
47
56
  <img src="./yellow-button.png" alt="Buy me a coffee" width="120">
48
57
  </a>
package/dist/frontend.js CHANGED
@@ -7,12 +7,15 @@ import os from 'os';
7
7
  import path from 'path';
8
8
  import { promises as fs } from 'fs';
9
9
  import { AnsiLogger, CYAN, db, debugStringify, er, nf, rs, stringify, UNDERLINE, UNDERLINEOFF, wr, YELLOW } from './logger/export.js';
10
- import { createZip, getIntParameter, hasParameter, isValidNumber, isValidObject, isValidString } from './utils/utils.js';
10
+ import { createZip, deepCopy, getIntParameter, hasParameter, isValidNumber, isValidObject, isValidString } from './utils/utils.js';
11
11
  import { plg } from './matterbridgeTypes.js';
12
12
  import { MatterbridgeEndpoint } from './matterbridgeEndpoint.js';
13
13
  export const WS_ID_LOG = 0;
14
14
  export const WS_ID_REFRESH_NEEDED = 1;
15
15
  export const WS_ID_RESTART_NEEDED = 2;
16
+ export const WS_ID_CPU_UPDATE = 3;
17
+ export const WS_ID_MEMORY_UPDATE = 4;
18
+ export const WS_ID_SNACKBAR = 5;
16
19
  export class Frontend {
17
20
  matterbridge;
18
21
  log;
@@ -22,7 +25,8 @@ export class Frontend {
22
25
  httpServer;
23
26
  httpsServer;
24
27
  webSocketServer;
25
- prevCpus = os.cpus();
28
+ prevCpus = deepCopy(os.cpus());
29
+ lastCpuUsage = 0;
26
30
  memoryData = [];
27
31
  memoryInterval;
28
32
  memoryTimeout;
@@ -746,9 +750,11 @@ export class Frontend {
746
750
  }
747
751
  async stop() {
748
752
  if (hasParameter('memorycheck')) {
753
+ this.wssSendSnackbarMessage('Memory check started', getIntParameter('memorycheck') ?? 5 * 60 * 1000);
749
754
  await new Promise((resolve) => {
750
755
  this.log.debug(`***Memory check started for ${getIntParameter('memorycheck') ?? 5 * 60 * 1000} ms`);
751
756
  setTimeout(() => {
757
+ this.wssSendSnackbarMessage('Memory check stopped', 10);
752
758
  this.log.debug(`***Memory check stopped after ${getIntParameter('memorycheck') ?? 5 * 60 * 1000} ms`);
753
759
  resolve();
754
760
  }, getIntParameter('memorycheck') ?? 5 * 60 * 1000);
@@ -792,28 +798,61 @@ export class Frontend {
792
798
  }
793
799
  }
794
800
  formatMemoryUsage = (bytes) => {
795
- const kb = bytes / 1024;
796
- const mb = kb / 1024;
797
- return mb >= 1 ? `${mb.toFixed(2)} MB` : `${kb.toFixed(2)} KB`;
801
+ if (bytes >= 1024 ** 3) {
802
+ return `${(bytes / 1024 ** 3).toFixed(2)} GB`;
803
+ }
804
+ else if (bytes >= 1024 ** 2) {
805
+ return `${(bytes / 1024 ** 2).toFixed(2)} MB`;
806
+ }
807
+ else {
808
+ return `${(bytes / 1024).toFixed(2)} KB`;
809
+ }
810
+ };
811
+ formatOsUpTime = () => {
812
+ const seconds = os.uptime();
813
+ if (seconds >= 86400) {
814
+ const days = Math.floor(seconds / 86400);
815
+ return `${days} day${days !== 1 ? 's' : ''}`;
816
+ }
817
+ if (seconds >= 3600) {
818
+ const hours = Math.floor(seconds / 3600);
819
+ return `${hours} hour${hours !== 1 ? 's' : ''}`;
820
+ }
821
+ if (seconds >= 60) {
822
+ const minutes = Math.floor(seconds / 60);
823
+ return `${minutes} minute${minutes !== 1 ? 's' : ''}`;
824
+ }
825
+ return `${seconds} second${seconds !== 1 ? 's' : ''}`;
826
+ };
827
+ getCpuUsage = () => {
828
+ const currCpus = os.cpus();
829
+ if (currCpus.length !== this.prevCpus.length) {
830
+ this.prevCpus = deepCopy(currCpus);
831
+ this.log.debug(`***Cpu usage reset. Current cpus: ${currCpus.length}. Previous cpus: ${this.prevCpus.length}.`);
832
+ return this.lastCpuUsage.toFixed(2);
833
+ }
834
+ let totalIdle = 0, totalTick = 0;
835
+ this.prevCpus.forEach((prevCpu, i) => {
836
+ const currCpu = currCpus[i];
837
+ const idleDiff = currCpu.times.idle - prevCpu.times.idle;
838
+ const totalDiff = Object.keys(currCpu.times).reduce((acc, key) => acc + (currCpu.times[key] - prevCpu.times[key]), 0);
839
+ totalIdle += idleDiff;
840
+ totalTick += totalDiff;
841
+ });
842
+ const cpuUsage = 100 - (totalIdle / totalTick) * 100;
843
+ if (totalTick === 0 || isNaN(cpuUsage) || !isFinite(cpuUsage) || cpuUsage <= 0) {
844
+ this.log.debug('***Invalid cpu usage. Returning the previous one.');
845
+ return this.lastCpuUsage.toFixed(2);
846
+ }
847
+ this.prevCpus = deepCopy(currCpus);
848
+ this.lastCpuUsage = cpuUsage;
849
+ return cpuUsage.toFixed(2);
798
850
  };
799
851
  startCpuMemoryDump() {
800
852
  clearInterval(this.memoryInterval);
801
853
  clearTimeout(this.memoryTimeout);
802
854
  const interval = () => {
803
- const currCpus = os.cpus();
804
- if (currCpus.length !== this.prevCpus.length) {
805
- this.prevCpus = currCpus;
806
- }
807
- let totalIdle = 0, totalTick = 0;
808
- this.prevCpus.forEach((prevCpu, i) => {
809
- const currCpu = currCpus[i];
810
- const idleDiff = currCpu.times.idle - prevCpu.times.idle;
811
- const totalDiff = Object.keys(currCpu.times).reduce((acc, key) => acc + (currCpu.times[key] - prevCpu.times[key]), 0);
812
- totalIdle += idleDiff;
813
- totalTick += totalDiff;
814
- });
815
- const cpuUsage = (100 - (totalIdle / totalTick) * 100).toFixed(2);
816
- this.prevCpus = currCpus;
855
+ const cpuUsage = this.getCpuUsage();
817
856
  const memoryUsageRaw = process.memoryUsage();
818
857
  this.memoryData.push({ ...memoryUsageRaw, cpu: cpuUsage });
819
858
  const memoryUsage = {
@@ -824,6 +863,15 @@ export class Frontend {
824
863
  arrayBuffers: this.formatMemoryUsage(memoryUsageRaw.arrayBuffers),
825
864
  };
826
865
  this.log.debug(`***Cpu usage: ${CYAN}${cpuUsage.padStart(6, ' ')} %${db} - Memory usage: rss ${CYAN}${memoryUsage.rss}${db} heapTotal ${CYAN}${memoryUsage.heapTotal}${db} heapUsed ${CYAN}${memoryUsage.heapUsed}${db} external ${memoryUsage.external} arrayBuffers ${memoryUsage.arrayBuffers}`);
866
+ this.matterbridge.systemInformation.freeMemory = this.formatMemoryUsage(os.freemem());
867
+ this.matterbridge.systemInformation.totalMemory = this.formatMemoryUsage(os.totalmem());
868
+ this.matterbridge.systemInformation.systemUptime = this.formatOsUpTime();
869
+ this.matterbridge.systemInformation.cpuUsed = cpuUsage;
870
+ this.matterbridge.systemInformation.rss = this.formatMemoryUsage(process.memoryUsage().rss);
871
+ this.matterbridge.systemInformation.heapTotal = this.formatMemoryUsage(process.memoryUsage().heapTotal);
872
+ this.matterbridge.systemInformation.heapUsed = this.formatMemoryUsage(process.memoryUsage().heapUsed);
873
+ this.wssSendCpuUpdate(this.matterbridge.systemInformation.cpuUsed);
874
+ this.wssSendMemoryUpdate(this.matterbridge.systemInformation.freeMemory, this.matterbridge.systemInformation.totalMemory, this.matterbridge.systemInformation.systemUptime, this.matterbridge.systemInformation.rss, this.matterbridge.systemInformation.heapUsed, this.matterbridge.systemInformation.heapTotal);
827
875
  };
828
876
  interval();
829
877
  this.memoryInterval = setInterval(interval, getIntParameter('memoryinterval') ?? 1000);
@@ -852,8 +900,13 @@ export class Frontend {
852
900
  this.prevCpus = [];
853
901
  }
854
902
  async getApiSettings() {
903
+ this.matterbridge.systemInformation.totalMemory = this.formatMemoryUsage(os.totalmem());
904
+ this.matterbridge.systemInformation.freeMemory = this.formatMemoryUsage(os.freemem());
905
+ this.matterbridge.systemInformation.systemUptime = this.formatOsUpTime();
906
+ this.matterbridge.systemInformation.cpuUsed = this.getCpuUsage();
855
907
  this.matterbridge.systemInformation.rss = this.formatMemoryUsage(process.memoryUsage().rss);
856
- this.matterbridge.systemInformation.heap = this.formatMemoryUsage(process.memoryUsage().heapUsed) + ' / ' + this.formatMemoryUsage(process.memoryUsage().heapTotal);
908
+ this.matterbridge.systemInformation.heapTotal = this.formatMemoryUsage(process.memoryUsage().heapTotal);
909
+ this.matterbridge.systemInformation.heapUsed = this.formatMemoryUsage(process.memoryUsage().heapUsed);
857
910
  this.matterbridge.matterbridgeInformation.bridgeMode = this.matterbridge.bridgeMode;
858
911
  this.matterbridge.matterbridgeInformation.restartMode = this.matterbridge.restartMode;
859
912
  this.matterbridge.matterbridgeInformation.loggerLevel = this.matterbridge.log.logLevel;
@@ -1316,4 +1369,30 @@ export class Frontend {
1316
1369
  }
1317
1370
  });
1318
1371
  }
1372
+ wssSendCpuUpdate(cpuUsed) {
1373
+ this.log.debug('Sending a memory update message to all connected clients');
1374
+ this.matterbridge.matterbridgeInformation.restartRequired = true;
1375
+ this.webSocketServer?.clients.forEach((client) => {
1376
+ if (client.readyState === WebSocket.OPEN) {
1377
+ client.send(JSON.stringify({ id: WS_ID_CPU_UPDATE, src: 'Matterbridge', dst: 'Frontend', method: 'cpu_update', params: { cpuUsed } }));
1378
+ }
1379
+ });
1380
+ }
1381
+ wssSendMemoryUpdate(freeMemory, totalMemory, systemUptime, rss, heapUsed, heapTotal) {
1382
+ this.log.debug('Sending a cpu update message to all connected clients');
1383
+ this.matterbridge.matterbridgeInformation.restartRequired = true;
1384
+ this.webSocketServer?.clients.forEach((client) => {
1385
+ if (client.readyState === WebSocket.OPEN) {
1386
+ client.send(JSON.stringify({ id: WS_ID_MEMORY_UPDATE, src: 'Matterbridge', dst: 'Frontend', method: 'memory_update', params: { freeMemory, totalMemory, systemUptime, rss, heapUsed, heapTotal } }));
1387
+ }
1388
+ });
1389
+ }
1390
+ wssSendSnackbarMessage(message, timeout) {
1391
+ this.log.debug('Sending a snackbar message to all connected clients');
1392
+ this.webSocketServer?.clients.forEach((client) => {
1393
+ if (client.readyState === WebSocket.OPEN) {
1394
+ client.send(JSON.stringify({ id: WS_ID_SNACKBAR, src: 'Matterbridge', dst: 'Frontend', method: 'memory_update', params: { message, timeout } }));
1395
+ }
1396
+ });
1397
+ }
1319
1398
  }
@@ -35,8 +35,10 @@ export class Matterbridge extends EventEmitter {
35
35
  totalMemory: '',
36
36
  freeMemory: '',
37
37
  systemUptime: '',
38
+ cpuUsed: '',
38
39
  rss: '',
39
- heap: '',
40
+ heapTotal: '',
41
+ heapUsed: '',
40
42
  };
41
43
  matterbridgeInformation = {
42
44
  homeDirectory: '',
@@ -927,61 +929,9 @@ export class Matterbridge extends EventEmitter {
927
929
  await this.cleanup('unregistered all devices and shutting down...', false);
928
930
  }
929
931
  async shutdownProcessAndReset() {
930
- this.log.info('Resetting Matterbridge commissioning information...');
931
- await this.matterStorageManager?.createContext('events')?.clearAll();
932
- await this.matterStorageManager?.createContext('fabrics')?.clearAll();
933
- await this.matterStorageManager?.createContext('root')?.clearAll();
934
- await this.matterStorageManager?.createContext('sessions')?.clearAll();
935
- await this.matterbridgeContext?.clearAll();
936
- await this.stopMatterStorage();
937
- this.log.info('Matter storage reset done! Remove the bridge from the controller.');
938
932
  await this.cleanup('shutting down with reset...', false);
939
933
  }
940
934
  async shutdownProcessAndFactoryReset() {
941
- try {
942
- const file = path.join(this.matterbridgeDirectory, 'matterbridge' + (getParameter('profile') ? '.' + getParameter('profile') : '') + '.json');
943
- this.log.info(`Unlinking old matter storage file: ${file}`);
944
- await fs.unlink(file);
945
- const backup = path.join(this.matterbridgeDirectory, 'matterbridge' + (getParameter('profile') ? '.' + getParameter('profile') : '') + '.backup.json');
946
- this.log.info(`Unlinking old matter storage backup file: ${backup}`);
947
- await fs.unlink(backup);
948
- }
949
- catch (err) {
950
- if (err instanceof Error && err.code !== 'ENOENT') {
951
- this.log.error(`Error unlinking old matter storage file: ${err}`);
952
- }
953
- }
954
- try {
955
- const dir = path.join(this.matterbridgeDirectory, 'matterstorage' + (getParameter('profile') ? '.' + getParameter('profile') : ''));
956
- this.log.info(`Removing matter node storage directory: ${dir}`);
957
- await fs.rm(dir, { recursive: true });
958
- const backup = path.join(this.matterbridgeDirectory, 'matterstorage' + (getParameter('profile') ? '.' + getParameter('profile') : '') + '.backup');
959
- this.log.info(`Removing matter node storage backup directory: ${backup}`);
960
- await fs.rm(backup, { recursive: true });
961
- }
962
- catch (err) {
963
- if (err instanceof Error && err.code !== 'ENOENT') {
964
- this.log.error(`Error removing matter storage directory: ${err}`);
965
- }
966
- }
967
- try {
968
- const dir = path.join(this.matterbridgeDirectory, 'storage' + (getParameter('profile') ? '.' + getParameter('profile') : ''));
969
- this.log.info(`Removing storage directory: ${dir}`);
970
- await fs.rm(dir, { recursive: true });
971
- const backup = path.join(this.matterbridgeDirectory, 'storage' + (getParameter('profile') ? '.' + getParameter('profile') : '') + '.backup');
972
- this.log.info(`Removing storage backup directory: ${backup}`);
973
- await fs.rm(backup, { recursive: true });
974
- }
975
- catch (err) {
976
- if (err instanceof Error && err.code !== 'ENOENT') {
977
- this.log.error(`Error removing storage directory: ${err}`);
978
- }
979
- }
980
- this.log.info('Factory reset done! Remove all paired fabrics from the controllers.');
981
- this.nodeContext = undefined;
982
- this.nodeStorage = undefined;
983
- this.plugins.clear();
984
- this.devices.clear();
985
935
  await this.cleanup('shutting down with factory reset...', false);
986
936
  }
987
937
  async cleanup(message, restart = false) {
@@ -1034,6 +984,15 @@ export class Matterbridge extends EventEmitter {
1034
984
  }
1035
985
  }
1036
986
  this.log.notice('Stopped matter server nodes');
987
+ if (message === 'shutting down with reset...') {
988
+ this.log.info('Resetting Matterbridge commissioning information...');
989
+ await this.matterStorageManager?.createContext('events')?.clearAll();
990
+ await this.matterStorageManager?.createContext('fabrics')?.clearAll();
991
+ await this.matterStorageManager?.createContext('root')?.clearAll();
992
+ await this.matterStorageManager?.createContext('sessions')?.clearAll();
993
+ await this.matterbridgeContext?.clearAll();
994
+ this.log.info('Matter storage reset done! Remove the bridge from the controller.');
995
+ }
1037
996
  await this.stopMatterStorage();
1038
997
  await this.frontend.stop();
1039
998
  try {
@@ -1061,6 +1020,48 @@ export class Matterbridge extends EventEmitter {
1061
1020
  }
1062
1021
  this.plugins.clear();
1063
1022
  this.devices.clear();
1023
+ if (message === 'shutting down with factory reset...') {
1024
+ try {
1025
+ const file = path.join(this.matterbridgeDirectory, 'matterbridge' + (getParameter('profile') ? '.' + getParameter('profile') : '') + '.json');
1026
+ this.log.info(`Unlinking old matter storage file: ${file}`);
1027
+ await fs.unlink(file);
1028
+ const backup = path.join(this.matterbridgeDirectory, 'matterbridge' + (getParameter('profile') ? '.' + getParameter('profile') : '') + '.backup.json');
1029
+ this.log.info(`Unlinking old matter storage backup file: ${backup}`);
1030
+ await fs.unlink(backup);
1031
+ }
1032
+ catch (err) {
1033
+ if (err instanceof Error && err.code !== 'ENOENT') {
1034
+ this.log.error(`Error unlinking old matter storage file: ${err}`);
1035
+ }
1036
+ }
1037
+ try {
1038
+ const dir = path.join(this.matterbridgeDirectory, 'matterstorage' + (getParameter('profile') ? '.' + getParameter('profile') : ''));
1039
+ this.log.info(`Removing matter node storage directory: ${dir}`);
1040
+ await fs.rm(dir, { recursive: true });
1041
+ const backup = path.join(this.matterbridgeDirectory, 'matterstorage' + (getParameter('profile') ? '.' + getParameter('profile') : '') + '.backup');
1042
+ this.log.info(`Removing matter node storage backup directory: ${backup}`);
1043
+ await fs.rm(backup, { recursive: true });
1044
+ }
1045
+ catch (err) {
1046
+ if (err instanceof Error && err.code !== 'ENOENT') {
1047
+ this.log.error(`Error removing matter storage directory: ${err}`);
1048
+ }
1049
+ }
1050
+ try {
1051
+ const dir = path.join(this.matterbridgeDirectory, 'storage' + (getParameter('profile') ? '.' + getParameter('profile') : ''));
1052
+ this.log.info(`Removing storage directory: ${dir}`);
1053
+ await fs.rm(dir, { recursive: true });
1054
+ const backup = path.join(this.matterbridgeDirectory, 'storage' + (getParameter('profile') ? '.' + getParameter('profile') : '') + '.backup');
1055
+ this.log.info(`Removing storage backup directory: ${backup}`);
1056
+ await fs.rm(backup, { recursive: true });
1057
+ }
1058
+ catch (err) {
1059
+ if (err instanceof Error && err.code !== 'ENOENT') {
1060
+ this.log.error(`Error removing storage directory: ${err}`);
1061
+ }
1062
+ }
1063
+ this.log.info('Factory reset done! Remove all paired fabrics from the controllers.');
1064
+ }
1064
1065
  this.deregisterProcesslHandlers();
1065
1066
  if (restart) {
1066
1067
  if (message === 'updating...') {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "files": {
3
3
  "main.css": "./static/css/main.cf25d33e.css",
4
- "main.js": "./static/js/main.26dbf9b9.js",
4
+ "main.js": "./static/js/main.aeec898e.js",
5
5
  "static/js/453.abd36b29.chunk.js": "./static/js/453.abd36b29.chunk.js",
6
6
  "static/media/roboto-latin-700-normal.woff2": "./static/media/roboto-latin-700-normal.4535474e1cf8598695ad.woff2",
7
7
  "static/media/roboto-latin-500-normal.woff2": "./static/media/roboto-latin-500-normal.7077203b1982951ecf76.woff2",
@@ -61,11 +61,11 @@
61
61
  "static/media/roboto-greek-ext-400-normal.woff": "./static/media/roboto-greek-ext-400-normal.16eb83b4a3b1ea994243.woff",
62
62
  "index.html": "./index.html",
63
63
  "main.cf25d33e.css.map": "./static/css/main.cf25d33e.css.map",
64
- "main.26dbf9b9.js.map": "./static/js/main.26dbf9b9.js.map",
64
+ "main.aeec898e.js.map": "./static/js/main.aeec898e.js.map",
65
65
  "453.abd36b29.chunk.js.map": "./static/js/453.abd36b29.chunk.js.map"
66
66
  },
67
67
  "entrypoints": [
68
68
  "static/css/main.cf25d33e.css",
69
- "static/js/main.26dbf9b9.js"
69
+ "static/js/main.aeec898e.js"
70
70
  ]
71
71
  }
@@ -1 +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.26dbf9b9.js"></script><link href="./static/css/main.cf25d33e.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div></body></html>
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.aeec898e.js"></script><link href="./static/css/main.cf25d33e.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div></body></html>