Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Plutotom/api #19

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
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 .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"trailingComma": "es5",
"tabWidth": 4,
"semi": false,
"singleQuote": true
}
187 changes: 67 additions & 120 deletions package-lock.json

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,12 @@
"style-loader": "^3.3.3",
"ts-loader": "^9.4.4",
"ts-node": "^10.9.1",
"typescript": "~4.5.4"
"typescript": "^5.7.3"
},
"dependencies": {
"electron-squirrel-startup": "^1.0.0",
"express": "^4.21.2",
"lodash": "^4.17.21",
"typed-emitter": "^2.1.0"
}
}
}
27 changes: 27 additions & 0 deletions src/api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const express = require('express')
const app = express()

let currentBatteryData = {} // Variable to store the latest battery data

app.get('/', (req, res) => {
res.send('Hello, world!' + new Date().toISOString())
})

app.get('/health', (req, res) => {
res.send('OK')
})

// Endpoint to get the current battery data
app.get('/battery', (req, res) => {
res.json(currentBatteryData)
})

app.listen(3001, () => {
console.log('Server is running on port 3001')
})

// Update the battery data when a message is received
process.on('message', (data) => {
console.log('Received data in api.js:', data)
currentBatteryData = data // Update the stored battery data
})
181 changes: 118 additions & 63 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,76 +1,131 @@
import { app, BrowserWindow, ipcMain } from 'electron';
import { RazerWatcher } from './watcher/razer_watcher';
import TrayManager from './tray_manager';
import { loadSettings, settingsChanges } from './settings_manager';
import {
app,
BrowserWindow,
ipcMain,
MessageChannelMain,
utilityProcess,
} from 'electron'
import { RazerWatcher } from './watcher/razer_watcher'
import TrayManager from './tray_manager'
import { loadSettings, settingsChanges } from './settings_manager'
import path from 'node:path'
import { fork } from 'child_process'

// This allows TypeScript to pick up the magic constants that's auto-generated by Forge's Webpack
// plugin that tells the Electron app where to look for the Webpack-bundled app code (depending on
// whether you're running in development or production).
declare const MAIN_WINDOW_WEBPACK_ENTRY: string;
declare const MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY: string;
declare const MAIN_WINDOW_WEBPACK_ENTRY: string
declare const MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY: string

let isIntentionalQuit = false;
let isIntentionalQuit = false

// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) {
quit();
quit()
}

app.on('will-quit', e => {
if (!isIntentionalQuit) {
e.preventDefault();
}
});
app.on('will-quit', (e) => {
if (!isIntentionalQuit) {
e.preventDefault()
}
})

const createSettingsWindow = (): void => {
// Focus current window if it is open already.
if (BrowserWindow.getAllWindows().length > 0) {
BrowserWindow.getAllWindows()[0].focus();
return;
}

// Create the browser window.
const settingsWindow = new BrowserWindow({
height: 600,
width: 800,
webPreferences: {
preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
},
resizable: false,
center: true,
fullscreenable: false,
});
settingsWindow.removeMenu();
// mainWindow.webContents.openDevTools();
settingsWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY);
};
// Focus current window if it is open already.
if (BrowserWindow.getAllWindows().length > 0) {
BrowserWindow.getAllWindows()[0].focus()
return
}

// Create the browser window.
const settingsWindow = new BrowserWindow({
height: 600,
width: 800,
webPreferences: {
preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
},
resizable: false,
center: true,
fullscreenable: false,
})
settingsWindow.removeMenu()
// mainWindow.webContents.openDevTools();
settingsWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY)
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
let razerWatcher: RazerWatcher = null;
ipcMain.handle('getDevices', () => { return razerWatcher.listDevices(); });
let razerWatcher: RazerWatcher = null
ipcMain.handle('getDevices', () => {
return razerWatcher.listDevices()
})

const child = fork(path.join(__dirname, 'api.js'))

// Add error handling for the child process
child.on('error', (err) => {
console.error('Child process error:', err)
})

const trayManager = new TrayManager([
// { label: 'Reconnect', type: 'normal', click: () => razerWatcher.stopAndStart() },
{ label: 'Settings', type: 'normal', click: () => createSettingsWindow() },
{ label: 'Quit', type: 'normal', click: () => quit() }
]);
child.on('disconnect', () => {
console.log('Child process disconnected')
})

let isFirstTimeLaunch = false;
settingsChanges.on('_defaultSettingsCreated', () => isFirstTimeLaunch = true);
settingsChanges.on('runAtStartup', async value => app.setLoginItemSettings({ openAtLogin: value }));
settingsChanges.on('displayChargingState', () => trayManager.updateTrayContents());
settingsChanges.on('showPercentage', () => trayManager.updateTrayContents());
await loadSettings();
const trayManager = new TrayManager(
[
{
label: 'Settings',
type: 'normal',
click: () => createSettingsWindow(),
},
{ label: 'Quit', type: 'normal', click: () => quit() },
],
(devices) => {
try {
if (child && !child.killed && child.connected) {
child.send({
type: 'deviceUpdate',
devices: Array.from(devices.values()),
})
}
} catch (error) {
console.error('Error sending message to child process:', error)
}
}
)

razerWatcher = new RazerWatcher(trayManager);
razerWatcher.initialize();
razerWatcher.stopAndStart();
// Add cleanup of child process on quit
app.on('before-quit', () => {
if (child && !child.killed) {
child.kill()
}
})

if (isFirstTimeLaunch) { createSettingsWindow(); }
});
let isFirstTimeLaunch = false
settingsChanges.on(
'_defaultSettingsCreated',
() => (isFirstTimeLaunch = true)
)

settingsChanges.on('runAtStartup', async (value) =>
app.setLoginItemSettings({ openAtLogin: value })
)
settingsChanges.on('displayChargingState', () => {
trayManager.updateTrayContents()
})
settingsChanges.on('showPercentage', () => trayManager.updateTrayContents())
await loadSettings()

razerWatcher = new RazerWatcher(trayManager)
razerWatcher.initialize()
razerWatcher.stopAndStart()

if (isFirstTimeLaunch) {
createSettingsWindow()
}
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
Expand All @@ -82,19 +137,19 @@ app.on('ready', async () => {
// });

app.on('activate', () => {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) {
createSettingsWindow();
}
});
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) {
createSettingsWindow()
}
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.

function quit() {
if (process.platform !== 'darwin') {
isIntentionalQuit = true;
app.quit();
}
}
if (process.platform !== 'darwin') {
isIntentionalQuit = true
}
app.quit()
}
Loading