Skip to content
Merged
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
1 change: 0 additions & 1 deletion eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ const globalIgnores = [
];

export const typescriptRules = {
'@typescript-eslint/no-misused-promises': 'off',
'@typescript-eslint/no-redundant-type-constituents': 'off',
'@typescript-eslint/no-unnecessary-type-assertion': 'off',
'@typescript-eslint/no-unsafe-argument': 'off',
Expand Down
255 changes: 123 additions & 132 deletions packages/kboot/src/usb-peripheral.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,145 +55,136 @@ export class UsbPeripheral implements Peripheral {
}

async sendCommand(options: CommandOption): Promise<CommandResponse> {
return new Promise<CommandResponse>(async (resolve, reject) => {
try {
await this.open();
validateCommandParams(options.params);
const data = encodeCommandOption(options);
logger('send data %o', `<${convertToHexString(data)}>`);
await this._device.write(data);
const receivedData = await this._device.read(options.timeout || 2000);
logger('received data %o', `<${convertToHexString(receivedData)}>`);
const commandResponse = decodeCommandResponse(receivedData);
logger('command response: %o', commandResponse);
resolve(commandResponse);
} catch (err) {
logger('USB send command communication error %O', err);
try {
await this.open();
validateCommandParams(options.params);
const data = encodeCommandOption(options);
logger('send data %o', `<${convertToHexString(data)}>`);
await this._device.write(data);
const receivedData = await this._device.read(options.timeout || 2000);
logger('received data %o', `<${convertToHexString(receivedData)}>`);
const commandResponse = decodeCommandResponse(receivedData);
logger('command response: %o', commandResponse);
return commandResponse;
} catch (err) {
logger('USB send command communication error %O', err);

throw err;
}
}

return reject(err);
async writeMemory(option: DataOption): Promise<void> {
try {
const command: CommandOption = {
command: Commands.WriteMemory,
hasDataPhase: true,
params: [
...pack(option.startAddress, { bits: 32 }),
...pack(option.data.length, { bits: 32 })
]
};

const firsCommandResponse = await this.sendCommand(command);
if (firsCommandResponse.tag !== ResponseTags.Generic) {
logger('Invalid write memory response! %o', firsCommandResponse);
throw new Error('Invalid write memory response!');
}

if (firsCommandResponse.code !== 0) {
logger('Non zero write memory response! %o', firsCommandResponse);
throw new Error(`Non zero write memory response! Response code: ${firsCommandResponse.code}`);
}
});
}

writeMemory(option: DataOption): Promise<void> {
return new Promise<void>(async (resolve, reject) => {
try {
const command: CommandOption = {
command: Commands.WriteMemory,
hasDataPhase: true,
params: [
...pack(option.startAddress, { bits: 32 }),
...pack(option.data.length, { bits: 32 })
]
};

const firsCommandResponse = await this.sendCommand(command);
if (firsCommandResponse.tag !== ResponseTags.Generic) {
logger('Invalid write memory response! %o', firsCommandResponse);
return reject(new Error('Invalid write memory response!'));
}

if (firsCommandResponse.code !== 0) {
logger('Non zero write memory response! %o', firsCommandResponse);
return reject(new Error(`Non zero write memory response! Response code: ${firsCommandResponse.code}`));
}

for (let i = 0; i < option.data.length; i = i + WRITE_DATA_STREAM_PACKAGE_LENGTH) {
const slice = option.data.slice(i, i + WRITE_DATA_STREAM_PACKAGE_LENGTH);

const writeData = [
2, // USB channel
0,
slice.length,
0, // TODO: What is it?
...slice
];

logger('send data %o', convertToHexString(writeData));
await this._device.write(writeData);
// workaround to prevent main thread blocking
await snooze(1);
}

const receivedData = await this._device.read(option.timeout || 2000);
logger('write memory received data %o', `<${convertToHexString(receivedData)}>`);
const secondCommandResponse = decodeCommandResponse(receivedData);
logger('write memory response: %o', secondCommandResponse);

if (secondCommandResponse.tag !== ResponseTags.Generic) {
logger('Invalid write memory final response %o', secondCommandResponse);
return reject(new Error('Invalid write memory final response!'));
}

if (secondCommandResponse.code !== 0) {
logger('Non zero write memory final response %o', secondCommandResponse);
const msg = `Non zero write memory final response! Response code: ${secondCommandResponse.code}`;
return reject(new Error(msg));
}

resolve();
} catch (err) {
logger('Can not write memory data %O', err);
reject(err);
for (let i = 0; i < option.data.length; i = i + WRITE_DATA_STREAM_PACKAGE_LENGTH) {
const slice = option.data.slice(i, i + WRITE_DATA_STREAM_PACKAGE_LENGTH);

const writeData = [
2, // USB channel
0,
slice.length,
0, // TODO: What is it?
...slice
];

logger('send data %o', convertToHexString(writeData));
await this._device.write(writeData);
// workaround to prevent main thread blocking
await snooze(1);
}

});
const receivedData = await this._device.read(option.timeout || 2000);
logger('write memory received data %o', `<${convertToHexString(receivedData)}>`);
const secondCommandResponse = decodeCommandResponse(receivedData);
logger('write memory response: %o', secondCommandResponse);

if (secondCommandResponse.tag !== ResponseTags.Generic) {
logger('Invalid write memory final response %o', secondCommandResponse);
throw new Error('Invalid write memory final response!');
}

if (secondCommandResponse.code !== 0) {
logger('Non zero write memory final response %o', secondCommandResponse);
const msg = `Non zero write memory final response! Response code: ${secondCommandResponse.code}`;
throw new Error(msg);
}
} catch (err) {
logger('Can not write memory data %O', err);
throw err;
}
}

readMemory(startAddress: number, count: number): Promise<Buffer> {
return new Promise<Buffer>(async (resolve, reject) => {
try {
const command: CommandOption = {
command: Commands.ReadMemory,
params: [
...pack(startAddress, { bits: 32 }),
...pack(count, { bits: 32 })
]
};

const firsCommandResponse = await this.sendCommand(command);
if (firsCommandResponse.tag !== ResponseTags.ReadMemory) {
logger('Invalid read memory response %o', firsCommandResponse);
return reject(new Error('Invalid read memory response!'));
}

if (firsCommandResponse.code !== 0) {
logger('Non zero read memory response %o', firsCommandResponse);
return reject(new Error(`Non zero read memory response! Response code: ${firsCommandResponse.code}`));
}

const byte4Number = firsCommandResponse.raw.slice(12, 15);
const arrivingDataSize = convertLittleEndianNumber(byte4Number);
const memoryData: Array<number> = [];
while (memoryData.length < arrivingDataSize) {
const receivedData = await this._device.read(2000);
logger('received data %o', `<${convertToHexString(receivedData)}>`);
memoryData.push(...receivedData);
// workaround to prevent main thread blocking
await snooze(1);
}

const responseData = await this._device.read(2000);
logger('received data %o', `<${convertToHexString(responseData)}>`);

const secondCommandResponse = decodeCommandResponse(responseData);
if (secondCommandResponse.tag !== ResponseTags.Generic) {
logger('Invalid read memory final response %o', secondCommandResponse);
return reject(new Error('Invalid read memory final response!'));
}

if (secondCommandResponse.code !== 0) {
logger('Non zero read memory final response %o', secondCommandResponse);
const msg = `Non zero read memory final response! Response code: ${secondCommandResponse.code}`;
return reject(new Error(msg));
}

resolve(Buffer.from(memoryData));
} catch (error) {
logger('Read memory error %O', error);

reject(error);
async readMemory(startAddress: number, count: number): Promise<Buffer> {
try {
const command: CommandOption = {
command: Commands.ReadMemory,
params: [
...pack(startAddress, { bits: 32 }),
...pack(count, { bits: 32 })
]
};

const firsCommandResponse = await this.sendCommand(command);
if (firsCommandResponse.tag !== ResponseTags.ReadMemory) {
logger('Invalid read memory response %o', firsCommandResponse);
throw new Error('Invalid read memory response!');
}

if (firsCommandResponse.code !== 0) {
logger('Non zero read memory response %o', firsCommandResponse);
throw new Error(`Non zero read memory response! Response code: ${firsCommandResponse.code}`);
}

const byte4Number = firsCommandResponse.raw.slice(12, 15);
const arrivingDataSize = convertLittleEndianNumber(byte4Number);
const memoryData: Array<number> = [];
while (memoryData.length < arrivingDataSize) {
const receivedData = await this._device.read(2000);
logger('received data %o', `<${convertToHexString(receivedData)}>`);
memoryData.push(...receivedData);
// workaround to prevent main thread blocking
await snooze(1);
}

const responseData = await this._device.read(2000);
logger('received data %o', `<${convertToHexString(responseData)}>`);

const secondCommandResponse = decodeCommandResponse(responseData);
if (secondCommandResponse.tag !== ResponseTags.Generic) {
logger('Invalid read memory final response %o', secondCommandResponse);
throw new Error('Invalid read memory final response!');
}

if (secondCommandResponse.code !== 0) {
logger('Non zero read memory final response %o', secondCommandResponse);
const msg = `Non zero read memory final response! Response code: ${secondCommandResponse.code}`;
throw new Error(msg);
}
});

return Buffer.from(memoryData);
} catch (error) {
logger('Read memory error %O', error);

throw error;
}
}
}
61 changes: 38 additions & 23 deletions packages/uhk-agent/src/electron-main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,26 +135,11 @@ async function createWindow() {
});

// Emitted when the window is closed.
win.on('closed', async () => {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
logger.misc('[Electron Main] win closed');
win = null;
try {
await deviceService.close();
} catch (error) {
// TODO: Investigate it deeper. It happens on MacOs 15+ sometimes
logger.error('[Electron Main] Error while closing DeviceService when electron has been closed', error);
}
deviceService = null;
appUpdateService = null;
appService = null;
await uhkHidDeviceService.close();
uhkHidDeviceService = null;
sudoService = null;
await smartMacroDocService.stop();
smartMacroDocService = null;
win.on('closed', () => {
windowClosed()
.catch((error) => {
logger.error('[Electron Main] Error while closing window', error);
})
});

win.once('ready-to-show', () => {
Expand Down Expand Up @@ -200,6 +185,28 @@ async function createWindow() {
win.on('close', () => saveWindowState(win, logger));
}

async function windowClosed() {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
logger.misc('[Electron Main] win closed');
win = null;
try {
await deviceService.close();
} catch (error) {
// TODO: Investigate it deeper. It happens on MacOs 15+ sometimes
logger.error('[Electron Main] Error while closing DeviceService when electron has been closed', error);
}
deviceService = null;
appUpdateService = null;
appService = null;
await uhkHidDeviceService.close();
uhkHidDeviceService = null;
sudoService = null;
await smartMacroDocService.stop();
smartMacroDocService = null;
}

if (isSecondInstance) {
app.quit();
} else if (options['capture-oled']) {
Expand Down Expand Up @@ -254,7 +261,12 @@ if (isSecondInstance) {
// 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', createWindow);
app.on('ready', () => {
createWindow()
.catch((error) => {
logger.error('[Electron Main] when creating the window: ', error);
});
});

// Quit when all windows are closed.
app.on('window-all-closed', () => {
Expand All @@ -264,11 +276,14 @@ if (isSecondInstance) {
app.on('will-quit', () => {
});

app.on('activate', async () => {
app.on('activate', () => {
// On macOS 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 (win === null) {
await createWindow();
createWindow()
.catch((error) => {
logger.error('[Electron Main] when activating the app: ', error);
});
}
});

Expand Down
Loading
Loading