-
-
Notifications
You must be signed in to change notification settings - Fork 823
Expand file tree
/
Copy pathBufferedCommunicator.java
More file actions
408 lines (344 loc) · 13.1 KB
/
Copy pathBufferedCommunicator.java
File metadata and controls
408 lines (344 loc) · 13.1 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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
/*
Copyright 2012-2018 Will Winder
This file is part of Universal Gcode Sender (UGS).
UGS is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
UGS is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with UGS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.willwinder.universalgcodesender;
import static com.willwinder.universalgcodesender.AbstractCommunicator.SerialCommunicatorEvent.*;
import com.willwinder.universalgcodesender.connection.ConnectionDriver;
import com.willwinder.universalgcodesender.types.GcodeCommand;
import com.willwinder.universalgcodesender.utils.CommUtils;
import com.willwinder.universalgcodesender.utils.GcodeStreamReader;
import java.io.IOException;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* GRBL serial port interface class.
*
* @author wwinder
*/
public abstract class BufferedCommunicator extends AbstractCommunicator {
private static final Logger logger = Logger.getLogger(BufferedCommunicator.class.getName());
// Command streaming variables
private Boolean sendPaused = false;
private GcodeCommand nextCommand; // Cached command.
private GcodeStreamReader commandStream; // Arbitrary number of commands
private final LinkedBlockingDeque<String> commandBuffer; // Manually specified commands
private final LinkedBlockingDeque<GcodeCommand> activeCommandList; // Currently running commands
private int sentBufferSize = 0;
private Boolean singleStepModeEnabled = false;
private Boolean singleBlockModeEnabled = false;
abstract public int getBufferSize();
public BufferedCommunicator() {
this.commandBuffer = new LinkedBlockingDeque<>();
this.activeCommandList = new LinkedBlockingDeque<>();
}
public BufferedCommunicator(LinkedBlockingDeque<String> cb, LinkedBlockingDeque<GcodeCommand> asl) {
this.commandBuffer = cb;
this.activeCommandList = asl;
}
@Override
public void setSingleStepMode(boolean enable) {
this.singleStepModeEnabled = enable;
}
@Override
public boolean getSingleStepMode() {
return this.singleStepModeEnabled;
}
@Override
public void setSingleBlockMode(boolean enable) {
this.singleBlockModeEnabled = enable;
}
@Override
public boolean getSingleBlockMode() {
return this.singleBlockModeEnabled;
}
/**
* Add command to the command queue outside file mode. This is the only way
* to send a command to the comm port without being in file mode.
* These commands will be sent prior to any queued stream, they should
* typically be control commands calculated by the application.
*/
@Override
public void queueStringForComm(final String input) {
// Add command to queue
this.commandBuffer.add(input);
}
/**
* Arbitrary length of commands to send to the communicator.
* @param input
*/
@Override
public void queueStreamForComm(final GcodeStreamReader input) {
commandStream = input;
}
/*
// TODO: Figure out why this isn't working ...
boolean isCommPortOpen() throws NoSuchPortException {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(this.commPort.getName());
String owner = portIdentifier.getCurrentOwner();
String thisClass = this.getClass().getName();
return portIdentifier.isCurrentlyOwned() && owner.equals(thisClass);
}
*/
/** File Stream Methods. **/
@Override
public void resetBuffersInternal() {
if (activeCommandList != null) {
activeCommandList.clear();
}
}
@Override
public String activeCommandSummary() {
StringBuilder sb = new StringBuilder();
String comma = "";
for (GcodeCommand gc : activeCommandList) {
sb.append(comma).append(gc.getCommandString());
comma = ", ";
}
if (commandStream != null) {
sb.append(comma)
.append(commandStream.getNumRowsRemaining())
.append(" streaming commands.");
}
return sb.toString();
}
@Override
public boolean areActiveCommands() {
return numActiveCommands() > 0;
}
@Override
public int numActiveCommands() {
int streamingCount =
commandStream == null ? 0 : commandStream.getNumRowsRemaining();
int cachedCommand = nextCommand == null ? 0 : 1;
return this.activeCommandList.size() + streamingCount + cachedCommand;
}
public int numBufferedCommands() {
return commandBuffer.size();
}
// Helper for determining if commands should be throttled.
private boolean allowMoreCommands() {
if (this.singleStepModeEnabled) {
return this.activeCommandList.isEmpty();
}
return true;
}
/**
* THIS COMMAND CAN ONLY BE CALLED FROM streamCommands UNLESS
* THE nextCommand OBJECT IS SYNCHRONIZED.
*
* Returns the next command with the following priority:
* 1. nextCommand object if set.
* 2. Front of the commandBuffer collection.
* 3. Next line in the commandStream.
* @return the next command to be streamed
*/
private GcodeCommand getNextCommand() {
if (nextCommand != null) {
return nextCommand;
}
else if (!this.commandBuffer.isEmpty()) {
nextCommand = new GcodeCommand(commandBuffer.pop());
}
else try {
if (commandStream != null && commandStream.ready()) {
nextCommand = commandStream.getNextCommand();
}
} catch (IOException ignored) {
// Fall through to null handling.
}
if (nextCommand != null) {
if (nextCommand.getCommandString().endsWith("\n")) {
nextCommand.setCommand(nextCommand.getCommandString().trim());
}
return nextCommand;
}
return null;
}
private GcodeCommand peekNextCommand() {
GcodeCommand nc = null;
if (nextCommand != null) {
nc = nextCommand;
}
else if (!this.commandBuffer.isEmpty()) {
nc = new GcodeCommand(commandBuffer.peek());
}
else
try {
if (commandStream != null && commandStream.ready())
{
nc = commandStream.peekNextCommand();
}
} catch (IOException ignored) {
// Fall through to null handling.
}
if (nc != null && nc.getCommandString().endsWith("\n")) {
nc.setCommand(nextCommand.getCommandString().trim());
}
return nc;
}
/**
* Streams anything in the command buffer to the comm port.
* Synchronized to prevent commands from sending out of order.
*/
@Override
synchronized public void streamCommands() {
// If there are no commands to send, exit.
if (this.getNextCommand() == null) {
logger.log(Level.FINE, "There are no more commands to stream");
return;
}
// Send command if:
// There is room in the buffer.
// AND we are NOT paused
// AND We are NOT in single step mode.
// OR We are in single command mode and there are no active commands.
while (this.getNextCommand() != null &&
!isPaused() &&
CommUtils.checkRoomInBuffer(
this.sentBufferSize,
this.getNextCommand().getCommandString(),
this.getBufferSize())
&& allowMoreCommands()) {
GcodeCommand command = this.getNextCommand();
if (command.getCommandString().isEmpty()) {
dispatchListenerEvents(COMMAND_SKIPPED, command);
nextCommand = null;
continue;
}
String commandString = command.getCommandString().trim();
this.activeCommandList.add(command);
this.sentBufferSize += (commandString.length() + 1);
try {
this.sendingCommand(commandString);
conn.sendStringToComm(commandString + "\n");
dispatchListenerEvents(COMMAND_SENT, command);
nextCommand = null;
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
// Single block mode: pause after this command is sent
// iff the next command is from the commandStream
// (ie do not pause for commandBuffer commands)
if( this.getSingleBlockMode() &&
commandBuffer.isEmpty() &&
peekNextCommand() != null &&
!peekNextCommand().getCommandString().isEmpty() ) {
logger.log(Level.INFO, "singleBlockMode: pausing");
pauseSend();
}
}
}
@Override
public void pauseSend() {
this.sendPaused = true;
}
@Override
public void resumeSend() {
this.sendPaused = false;
this.streamCommands();
}
@Override
public boolean isPaused() {
return sendPaused;
}
@Override
public void cancelSend() {
this.nextCommand = null;
this.commandBuffer.clear();
this.activeCommandList.clear();
this.commandStream = null;
this.sendPaused = false;
}
/**
* This is to allow the GRBL Ctrl-C soft reset command.
*/
@Override
public void softReset() {
this.sentBufferSize = 0;
cancelSend();
}
/**
* Notifies the subclass that a command has been sent.
* @param command The command being sent.
*/
abstract protected void sendingCommand(String command);
/**
* Returns whether or not a command has been completed based on a response
* from the controller.
* @param response
* @return true if a command has completed.
*/
abstract protected boolean processedCommand(String response);
/**
* Returns whether or not a completed command had an error based on a
* response from the controller.
* @param response
* @return true if a command has completed.
*/
abstract protected boolean processedCommandIsError(String response);
/**
* Processes message from GRBL. This should only be called from the
* connection object.
* @param response
*/
@Override
public void responseMessage(String response) {
// Send this information back up to the Controller.
dispatchListenerEvents(SerialCommunicatorEvent.RAW_RESPONSE, response);
// Pause if there was an error and if there are more commands queued
if (processedCommandIsError(response) &&
(nextCommand != null // No cached command
|| (activeCommandList.size() > 1) // No more commands (except for the one being popped further down)
|| (commandStream != null && commandStream.getNumRowsRemaining() > 0) // No more rows in stream
|| (commandBuffer != null && commandBuffer.size() > 0))) { // No commands in buffer
pauseSend();
dispatchListenerEvents(PAUSED, "");
}
// Keep the data flow going in case of an "ok" or an "error".
if (processedCommand(response)) {
// Pop the front of the active list.
if (this.activeCommandList != null && this.activeCommandList.size() > 0) {
GcodeCommand command = this.activeCommandList.pop();
this.sentBufferSize -= (command.getCommandString().length() + 1);
if (!isPaused()) {
this.streamCommands();
}
}
}
}
@Override
public boolean openCommPort(ConnectionDriver connectionDriver, String name, int baud) throws Exception {
boolean ret = super.openCommPort(connectionDriver, name, baud);
if (ret) {
this.commandBuffer.clear();
this.activeCommandList.clear();
this.sentBufferSize = 0;
}
return ret;
}
@Override
public void closeCommPort() throws Exception {
this.cancelSend();
super.closeCommPort();
this.sendPaused = false;
this.commandBuffer.clear();
this.activeCommandList.clear();
}
@Override
public void sendByteImmediately(byte b) throws Exception {
conn.sendByteImmediately(b);
}
}