Page 248 - The Unofficial Guide to Lego Mindstorms Robots
P. 248
237
private static final int kTimeOut = 800;
public Download(String filename, String portName)
throws NoSuchPortException, PortInUseException,
UnsupportedCommOperationException, IOException {
initialize(portName);
mFileIn = new FileReader (filename);
run();
}
protected void initialize(String portName)
throws NoSuchPortException, PortInUseException,
UnsupportedCommOperationException, IOException {
CommPortIdentifier id =
CommPortIdentifier.getPortIdentifier(portName);
mPort = (SerialPort)id.open("Download", 1000);
mPort.setSerialPortParams(
2400,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE
);
Reader in = new InputStreamReader(mPort.getInputStream());
mPortListener = new PortListener (in);
mOut = new OutputStreamWriter(mPort.getOutputStream());
}
public void run() {
int c, n = 1;
try {
sendReturn();
sendReturn();
while ((c = mFileIn.read()) != -1) {
if (c == '\r') {
sendReturn();
if (mPortListener.isComplete() == false) {
throw new DownloadException("Timed out waiting " +
"for a response from the RCX.");
}
else if (mPortListener.isError() == true) {
throw new DownloadException("Error: " +
mPortListener.getLastLine());
}
System.out.print(".");
n++;
}
else if (c != '\n') {
mPortListener.reset();
mOut.write(c);
mOut.flush();
Thread.sleep(kCharSleep);
}
}
sendReturn();