Skip to content

Commit

Permalink
fix(transport): UdpApi trigger transport-interface-change
Browse files Browse the repository at this point in the history
fix missing device disconnect or late device connect events
  • Loading branch information
szymonlesisz committed Aug 29, 2024
1 parent cb1857f commit 0138949
Showing 1 changed file with 22 additions and 3 deletions.
25 changes: 22 additions & 3 deletions packages/transport/src/api/udp.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
import UDP from 'dgram';
import { isNotUndefined } from '@trezor/utils';
import { isNotUndefined, arrayPartition } from '@trezor/utils';

import {
AbstractApi,
AbstractApiAwaitedResult,
AbstractApiConstructorParams,
DEVICE_TYPE,
} from './abstract';

import { DescriptorApiLevel } from '../types';
import * as ERRORS from '../errors';

export class UdpApi extends AbstractApi {
chunkSize = 64;

protected devices: DescriptorApiLevel[] = [];
protected interface = UDP.createSocket('udp4');
protected communicating = false;

Expand All @@ -33,13 +34,31 @@ export class UdpApi extends AbstractApi {
if (!this.listening) return;

this.enumerationTimeout = setTimeout(() => {
this.enumerate(this.enumerateAbortController.signal).finally(enumerateRecursive);
this.enumerate(this.enumerateAbortController.signal)
.then(r => this.handleEnumerate(r))
.finally(enumerateRecursive);
}, 500);
};

enumerateRecursive();
}

private handleEnumerate(result: Awaited<ReturnType<typeof this.enumerate>>) {
if (result.success) {
const [known, unknown] = arrayPartition(result.payload, device =>
this.devices.includes(device),
);

if (known.length !== this.devices.length || unknown.length > 0) {
this.devices = result.payload;
this.emit('transport-interface-change', this.devices);
}
} else if (this.devices.length > 0) {
this.devices = [];
this.emit('transport-interface-change', this.devices);
}
}

public write(path: string, buffer: Buffer, signal?: AbortSignal) {
const [hostname, port] = path.split(':');

Expand Down

0 comments on commit 0138949

Please sign in to comment.