Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,10 @@ LEARNING_PACKAGE_PATH="./learning-packages"
# Default to `false`
#AGGRESSIVE_DISCONNECT=false

# -------------------------------
# NUT (Network UPS Tools) Settings
# -------------------------------
# NUT_HOST=localhost
# NUT_PORT=3493
# NUT_UPS_NAME=myUps

66 changes: 27 additions & 39 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
"express": "^4.21.2",
"geoip-lite": "^1.4.10",
"i18next": "^23.15.1",
"nut-client": "^0.0.9",
"postcss": "^8.4.40",
"react": "^18.3.1",
"react-dom": "^18.3.1",
Expand Down
9 changes: 9 additions & 0 deletions src/api/core/Controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { AdbManager } from "../android/adb/AdbManager.ts";
import { useAdb, ENV_GAMALESS } from "../index.ts";
import { JsonPlayerAsk, JsonOutput } from "./Constants.ts";
// import {mDnsService} from "../infra/mDnsService.ts";
import { NutManager } from "../infra/nut/NutManager.ts";
import { getLogger } from "@logtape/logtape";

const logger = getLogger(["core", "Controller"]);
Expand All @@ -18,6 +19,7 @@ export class Controller {

adb_manager: AdbManager | undefined;
// mDnsService: mDnsService;
nut_manager: NutManager;


constructor(useAdb: boolean) {
Expand All @@ -36,12 +38,16 @@ export class Controller {
} else {
logger.warn("Couldn't find ADB working or started, cancelling ADB management")
}

this.nut_manager = new NutManager();
}

// Allow running init functions for some components needing it
async initialize() {
if (this.adb_manager)
await this.adb_manager.init();

await this.nut_manager.init();
}

async restart() {
Expand All @@ -67,6 +73,9 @@ export class Controller {

if (useAdb) this.adb_manager = new AdbManager(this);

this.nut_manager.close();
this.nut_manager = new NutManager();

await this.initialize();
}

Expand Down
6 changes: 6 additions & 0 deletions src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@ process.env.EXTRA_LEARNING_PACKAGE_PATH = process.env.EXTRA_LEARNING_PACKAGE_P
const ENV_AGGRESSIVE_DISCONNECT: boolean = process.env.AGGRESSIVE_DISCONNECT !== undefined ? ['true', '1', 'yes'].includes(process.env.AGGRESSIVE_DISCONNECT.toLowerCase()) : false;
// ! GAMA =====

// NUT (Network UPS Tools) =====
process.env.NUT_HOST = process.env.NUT_HOST || 'localhost';
process.env.NUT_PORT = process.env.NUT_PORT || '3493';
process.env.NUT_UPS_NAME = process.env.NUT_UPS_NAME || 'myUps';
// ! NUT =====

// Headsets =====
process.env.HEADSET_WS_PORT = process.env.HEADSET_WS_PORT || '8080';
// ! Headsets =====
Expand Down
136 changes: 136 additions & 0 deletions src/api/infra/nut/NutManager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import { NUTClient, Monitor } from 'nut-client';
import { getLogger } from '@logtape/logtape';

const logger = getLogger(["infra", "nut", "NutManager"]);

export class NutManager {
private client: NUTClient;
private monitor: Monitor | null = null;
private upsName: string;

Check warning on line 9 in src/api/infra/nut/NutManager.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Member 'upsName' is never reassigned; mark it as `readonly`.

See more on https://sonarcloud.io/project/issues?id=project-SIMPLE_simple.webplatform&issues=AZzR2ej8nXc0p40jpcPZ&open=AZzR2ej8nXc0p40jpcPZ&pullRequest=126

constructor() {
const host = process.env.NUT_HOST || 'localhost';
const port = parseInt(process.env.NUT_PORT || '3493', 10);

Check warning on line 13 in src/api/infra/nut/NutManager.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Prefer `Number.parseInt` over `parseInt`.

See more on https://sonarcloud.io/project/issues?id=project-SIMPLE_simple.webplatform&issues=AZzR2ej8nXc0p40jpcPa&open=AZzR2ej8nXc0p40jpcPa&pullRequest=126
this.upsName = process.env.NUT_UPS_NAME || 'myUps';

logger.info(`Initializing NUT Manager for UPS '${this.upsName}' at ${host}:${port}`);

this.client = new NUTClient(host, port);
}

public async init(): Promise<void> {
try {
// First check if UPS is available
const upses = await this.client.listUPS();
logger.debug(`Available UPSes: {upses}`, {upses});

if (!upses || Object.keys(upses).length === 0) {
logger.warn('No UPS available or listed. Disabling NUT integration and cleaning up.');
this.close();
return;
}

// Check if our configured UPS is in the list
if (!upses[this.upsName]) {
logger.warn(`Configured UPS '${this.upsName}' not found in the available list. Disabling NUT integration and cleaning up.`);
this.close();
return;
}

// Valid UPS found. Setup Monitor
logger.info(`UPS '${this.upsName}' found, setting up monitor...`);
this.monitor = new Monitor(this.client, this.upsName);

// Setup UPS Events

// Fired when UPS switches to battery power (e.g. unplugged)
this.monitor.on('ONBATT', () => {
logger.warn(`UPS '${this.upsName}' is ON BATTERY. Power has been lost!`);
this.handlePowerLoss();
});

// Fired when UPS is back on utility power (e.g. plugged back in)
this.monitor.on('ONLINE', () => {
logger.info(`UPS '${this.upsName}' is ONLINE. Utility power has been restored!`);
this.handlePowerRestored();
});

// Fired when UPS battery is low
this.monitor.on('LOWBATT', () => {
logger.warn(`UPS '${this.upsName}' has LOW BATTERY! Preparing for shutdown sequence...`);
this.handleLowBattery();
});

// Fired when battery needs replacement
this.monitor.on('REPLBATT', () => {
logger.warn(`UPS '${this.upsName}' needs battery replacement!`);
});

// Fired on UPS forced shutdown (FSD)
this.monitor.on('FSD', () => {
logger.warn(`UPS '${this.upsName}' forced shutdown initiated!`);
});

// (Optional) Catch-all for any event or specific variable changes
// this.monitor.on('*', (event: string, ...args) => {
// logger.trace(`UPS Event ${event}: {args}`, { args });
// });

await this.monitor.start();
logger.info('NUT Monitor started successfully.');

} catch (error) {
logger.error(`Failed to initialize NUT connection: {error}`, {error});
this.close();
}
}

private handlePowerLoss() {
// TODO: Handle Power Loss

Check warning on line 89 in src/api/infra/nut/NutManager.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Complete the task associated to this "TODO" comment.

See more on https://sonarcloud.io/project/issues?id=project-SIMPLE_simple.webplatform&issues=AZzR2ej8nXc0p40jpcPb&open=AZzR2ej8nXc0p40jpcPb&pullRequest=126
// Possible Features:
// - Broadcast warning to all connected clients.
// - Save state of the GAMA Simulation if supported.
// - Consider scheduling a graceful shutdown if power isn't restored within X minutes.
}

private handlePowerRestored() {
// TODO: Handle Power Restored

Check warning on line 97 in src/api/infra/nut/NutManager.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Complete the task associated to this "TODO" comment.

See more on https://sonarcloud.io/project/issues?id=project-SIMPLE_simple.webplatform&issues=AZzR2ej8nXc0p40jpcPc&open=AZzR2ej8nXc0p40jpcPc&pullRequest=126
// Possible Features:
// - Cancel any pending shutdowns.
// - Broadcast recovery message to clients.
}

private handleLowBattery() {
// TODO: Handle Low Battery Shutdown Sequence

Check warning on line 104 in src/api/infra/nut/NutManager.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Complete the task associated to this "TODO" comment.

See more on https://sonarcloud.io/project/issues?id=project-SIMPLE_simple.webplatform&issues=AZzR2ej8nXc0p40jpcPd&open=AZzR2ej8nXc0p40jpcPd&pullRequest=126
// Possible Features:
// - Turn off VR Headsets to avoid useless battery drain:
// - Retrieve `AdbManager` instance.
// - For each connected device, execute `adb shell reboot -p` to turn off the headset.
// - Turn off the main server (Mac Mini):
// - Execute system `shutdown` command (e.g., `sudo shutdown -h now` on macOS/Linux).
// - Log all actions meticulously.
}

public close() {
logger.debug('Cleaning up NUT Manager...');
if (this.monitor) {
try {
this.monitor.stop();
} catch (e) {
logger.warn('Failed to stop monitor smoothly: {e}', {e});
}
this.monitor = null;
}

try {
// We can't close client cleanly as per docs, but we can drop ref
// nut-client manages connections automatically
} catch (e) {
logger.trace('Error closing client {e}', {e});
}

this.client = null as any; // Allow GC
}
}

export default NutManager;