forked from qoire/ledger4j
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLedgerHIDAPI.java
More file actions
88 lines (74 loc) · 2.4 KB
/
LedgerHIDAPI.java
File metadata and controls
88 lines (74 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package org.aion.ledger;
import org.aion.ledger.exceptions.LedgerWriteException;
import org.hid4java.HidDevice;
import org.hid4java.HidManager;
import org.hid4java.HidServices;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.IOException;
import static org.aion.ledger.Constants.PACKET_SIZE;
public class LedgerHIDAPI extends LedgerDevice {
private HidDevice device;
public LedgerHIDAPI(@Nonnull final HidDevice device) {
this.device = device;
}
// TODO: what if this is called twice?
@Override
public void close() {
if (this.device.isOpen()) {
this.device.close();
}
}
/**
* Writes a chunk of 64-byte data out to the Ledger device.
* As best as I can tell this should be always formatted in 64 byte
* chunks.
*
* @implNote Note that there is no guarantee the data is actually written
* to the device, or when this data is written to the device.
*
* @param arg 64-byte chunk of data to be written to device.
*/
@Override
protected void write(@Nonnull final byte[] arg) throws LedgerWriteException {
this.device.write(arg, arg.length, (byte) 0x00);
}
/**
* Retrieves a 64-byte chunk of data from the device
* Note: this method should only be called from one thread
*
* @param waitPeriod how long to wait, <= 0 for indefinite blocking
* @return {@code 64-byte} chunk of data, returns {@code null} on any conditions failing
*/
@Nullable
@Override
protected byte[] read(final int waitPeriod) {
byte[] data = new byte[PACKET_SIZE];
int resp = this.device.read(data);
if (resp < 0) {
// TODO: should distinguish this state
return null;
}
return data;
}
@Override
protected void resetLedger() {
this.device.close();
HidServices services = HidManager.getHidServices();
services.scan();
try {
// TODO: violates abstraction
this.device = ((LedgerHIDAPI) LedgerUtilities.findLedgerDevice()).device;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
protected void setNonBlocking(boolean condition) {
this.device.setNonBlocking(condition);
}
@Override
public String toString() {
return this.device.toString();
}
}