_debug("Writing bytes from the input port to the serial port: "
+ inputLength);
}
for (int j = 0; j < inputLength; j++) {
UnsignedByteToken dataToken = (UnsignedByteToken) dataArrayToken
.getElement(j);
out.write(dataToken.byteValue());
}
out.flush();
}
InputStream in = _serialPort.getInputStream();
int bytesAvailable = in.available();
if (_debugging) {
_debug("Number of input bytes available on the serial port: "
+ bytesAvailable);
}
// NOTE: This needs _minimumOutputSize to be at least 1.
// FIXME: stopFire() is called if the serial port receives
// a byte while we are in the wait() (by the serialEvent()
// method, through fireAtCurrentTime(), I think). But we
// don't want to exit the loop if stopFire() is called for
// this reason. We want to continue waiting until there
// is enough input data. But this means that if stopFire()
// is called for some other reason, then this actor will
// ignore the call. This is not quite right, and could
// make the actor fail in domains where stopFire() is essential
// (are there any?).
while ((bytesAvailable < _minimumOutputSize) && _blocking
&& !_stopRequested /* && !_stopFireRequested */) {
try {
if (_debugging) {
_debug("Blocking waiting for minimum number of bytes: "
+ _minimumOutputSize);
}
PortListener.class.wait();
bytesAvailable = in.available();
if (_debugging) {
_debug("Number of input bytes available on the serial port: "
+ bytesAvailable);
}
} catch (InterruptedException ex) {
throw new IllegalActionException(this,
"Thread interrupted waiting for serial port data.");
}
}
if (_debugging) {
_debug("Number of input bytes available on the serial port: "
+ bytesAvailable);
}
if (bytesAvailable >= _minimumOutputSize) {
// Read only if at least desired amount of data is present.
if (_discardOldData
&& (bytesAvailable > _maximumOutputSize)) {
// Skip excess bytes.
int excess = bytesAvailable - _maximumOutputSize;
if (_debugging) {
_debug("Discarding input bytes: " + excess);
}
bytesAvailable -= (int) in.skip(excess);
}
int outputSize = bytesAvailable;
if (outputSize > _maximumOutputSize) {
outputSize = _maximumOutputSize;
}
byte[] dataBytes = new byte[outputSize];
if (_debugging) {
_debug("Reading bytes from the serial port: "
+ outputSize);
}
int bytesRead = in.read(dataBytes, 0, outputSize);
// FindBugs asks us to check the return value of in.read().
if (bytesRead != outputSize) {
throw new IllegalActionException(this, "Read only "
+ bytesRead + " bytes, expecting" + outputSize
+ " bytes.");
}
Token[] dataTokens = new Token[outputSize];
for (int j = 0; j < outputSize; j++) {
dataTokens[j] = new UnsignedByteToken(dataBytes[j]);
}
if (_debugging) {
_debug("Producing byte array on the output port.");
}