-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathUsbScale.java
More file actions
218 lines (199 loc) · 6.07 KB
/
Copy pathUsbScale.java
File metadata and controls
218 lines (199 loc) · 6.07 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
package com.nighthacking.scales;
import java.util.List;
import java.util.concurrent.Phaser;
import java.util.function.DoublePredicate;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.usb.UsbConfiguration;
import javax.usb.UsbDevice;
import javax.usb.UsbDeviceDescriptor;
import javax.usb.UsbDisconnectedException;
import javax.usb.UsbEndpoint;
import javax.usb.UsbException;
import javax.usb.UsbHostManager;
import javax.usb.UsbHub;
import javax.usb.UsbInterface;
import javax.usb.UsbPipe;
import javax.usb.UsbServices;
import javax.usb.event.UsbPipeDataEvent;
import javax.usb.event.UsbPipeErrorEvent;
import javax.usb.event.UsbPipeListener;
/**
* @author Stephen Chin <steveonjava@gmail.com>
*/
public class UsbScale implements Scale, UsbPipeListener {
private final UsbDevice device;
private UsbInterface iface;
private UsbPipe pipe;
private final byte[] data = new byte[6];
private volatile boolean busy;
private volatile boolean closing;
private final Phaser scalePhaser = new Phaser(1);
private volatile int weight;
private volatile int scalingFactor;
private volatile boolean grams;
private volatile boolean negative;
private volatile boolean overweight;
private volatile boolean empty;
private final int[] pastWeights = new int[] {-1, -1};
private volatile boolean stable;
// todo: Put the right conversion value in here:
private static final double GRAMS_IN_OUNCE = 22;
private UsbScale(UsbDevice device) {
this.device = device;
}
public static Scale findScale() {
try {
UsbServices services = UsbHostManager.getUsbServices();
UsbHub rootHub = services.getRootUsbHub();
// Dymo M10 Scale:
UsbDevice device = findDevice(rootHub, (short) 0x0922, (short) 0x8003);
// Dymo M25 Scale:
if (device == null) {
device = findDevice(rootHub, (short) 0x0922, (short) 0x8004);
}
if (device == null) {
return null;
}
return new UsbScale(device);
} catch (UsbException ex) {
throw new IllegalStateException("Unable to find devices", ex);
}
}
private static UsbDevice findDevice(UsbHub hub, short vendorId, short productId) {
for (UsbDevice device : (List<UsbDevice>) hub.getAttachedUsbDevices()) {
UsbDeviceDescriptor desc = device.getUsbDeviceDescriptor();
if (desc.idVendor() == vendorId && desc.idProduct() == productId) {
return device;
}
if (device.isUsbHub()) {
device = findDevice((UsbHub) device, vendorId, productId);
if (device != null) {
return device;
}
}
}
return null;
}
private double scaleWeight() {
double decimalWeight = weight;
decimalWeight *= Math.pow(10, scalingFactor);
return decimalWeight;
}
@Override
public double getWeight() {
return negative ? -Double.MAX_VALUE
: overweight ? Double.MAX_VALUE
: empty ? 0
: grams ? scaleWeight()
: scaleWeight() / GRAMS_IN_OUNCE;
}
@Override
public boolean isStable() {
return stable;
}
@Override
public void tare() {
throw new UnsupportedOperationException();
}
@Override
public void connect() {
try {
open();
pipe.asyncSubmit(data);
busy = true;
} catch (UsbException ex) {
throw new IllegalStateException("Unable to connect to scale", ex);
}
}
private void open() throws UsbException {
UsbConfiguration configuration = device.getActiveUsbConfiguration();
iface = configuration.getUsbInterface((byte) 0);
// this allows us to steal the lock from the kernel
iface.claim(usbInterface -> true);
final List<UsbEndpoint> endpoints = iface.getUsbEndpoints();
pipe = endpoints.get(0).getUsbPipe(); // there is only 1 endpoint
pipe.addUsbPipeListener(this);
pipe.open();
}
@Override
public void waitFor(DoublePredicate condition) {
while (!condition.test(getWeight())) {
scalePhaser.awaitAdvance(scalePhaser.getPhase());
}
}
@Override
public void waitForStable(DoublePredicate condition) {
double lastWeight, currentWeight = getWeight();
do {
lastWeight = currentWeight;
while (!stable || empty || negative || lastWeight == currentWeight) {
scalePhaser.awaitAdvance(scalePhaser.getPhase());
currentWeight = getWeight();
}
} while (!condition.test(currentWeight));
}
@Override
public void errorEventOccurred(UsbPipeErrorEvent upee) {
busy = false;
Logger.getLogger(UsbScale.class.getName()).log(Level.SEVERE, "Scale malfunction, closing...", upee.getUsbException());
close();
System.exit(-1);
}
@Override
public void dataEventOccurred(UsbPipeDataEvent upde) {
empty = data[1] == 2;
overweight = data[1] == 6;
negative = data[1] == 5;
grams = data[2] == 2;
scalingFactor = data[3];
updateWeight((data[4] & 0xFF) + (data[5] << 8));
if (closing) {
busy = false;
} else {
try {
pipe.asyncSubmit(data);
} catch (UsbException ex) {
errorEventOccurred(new UsbPipeErrorEvent(upde.getUsbPipe(), ex));
}
}
scalePhaser.arrive();
}
private void updateWeight(int newWeight) {
boolean isStable = true;
for (int i = 0; i < pastWeights.length - 1; i++) {
pastWeights[i] = pastWeights[i + 1];
if (pastWeights[i] != weight) {
isStable = false;
}
}
pastWeights[pastWeights.length - 1] = weight;
if (weight != newWeight) {
isStable = false;
weight = newWeight;
}
stable = isStable;
}
@Override
public String toString() {
return "USB Scale reading: " + scaleWeight() + (grams ? "g" : "oz");
}
@Override
public void close() {
int phase = scalePhaser.getPhase();
closing = true;
while (busy) {
phase = scalePhaser.awaitAdvance(phase);
}
try {
if (pipe.isOpen()) {
pipe.close();
}
if (iface.isActive()) {
iface.release();
}
} catch (UsbException | UsbDisconnectedException ex) {
Logger.getLogger(UsbScale.class.getName()).log(Level.SEVERE, "Unable to close scale cleanly", ex);
}
}
}