Mega Code Archive
JModem - simple communications program
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.com/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Java, the Duke mascot, and all variants of Sun's Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun's, and James Gosling's,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
*
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.KeyEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Enumeration;
import java.util.HashMap;
import javax.comm.CommPortIdentifier;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;
import javax.comm.UnsupportedCommOperationException;
import javax.swing.ButtonGroup;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
/**
* JModem - simple communications program.
* WARNING this file was built with the NetBeans Developer IDE
* and parts of it should not be modified with a text editor.
* @author Ian F. Darwin, http://www.darwinsys.com/
* @version $Id: JModem.java,v 1.18 2004/04/11 23:50:40 ian Exp $
*/
public class JModem extends javax.swing.JFrame {
/** The Model. */
JMModel theModel;
/** The TextArea */
JTextArea theTextArea;
/** The courier font for the text areas and fields. */
protected Font plainFont;
/** The valid baud rates (actually BPS rates). */
private int[] baudot = { 9600, 19200, 38400, 57600, 115200 };
/** The types of remote systems. */
private String sysTypes[] = { "Unix", "DOS", "Other" };
private int M_RECEIVE = -1, M_SEND = +1;
private int xferDirection = M_RECEIVE;
/** Constructor */
public JModem() {
theModel = new JMModel(this);
initComponents();
finishConstructor();
pack();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the FormEditor.
*/
private void initComponents () {//GEN-BEGIN:initComponents
setTitle ("JModem");
addWindowListener (new java.awt.event.WindowAdapter () {
public void windowClosing (java.awt.event.WindowEvent evt) {
exitForm (evt);
}
}
);
getContentPane ().setLayout (new java.awt.BorderLayout ());
jMenuBar1 = new javax.swing.JMenuBar ();
fileMenu = new javax.swing.JMenu ();
fileMenu.setText ("File");
saveLogFileMenuItem = new javax.swing.JMenuItem ();
saveLogFileMenuItem.setText ("Save Log");
saveLogFileMenuItem.addActionListener (new java.awt.event.ActionListener () {
public void actionPerformed (java.awt.event.ActionEvent evt) {
saveLogFileMenuItemActionPerformed (evt);
}
}
);
fileMenu.add(saveLogFileMenuItem);
fileMenu.addSeparator();
exitMenuItem = new javax.swing.JMenuItem ();
exitMenuItem.setText ("Exit");
exitMenuItem.addActionListener (new java.awt.event.ActionListener () {
public void actionPerformed (java.awt.event.ActionEvent evt) {
exitMenuItemActionPerformed (evt);
}
}
);
fileMenu.add(exitMenuItem);
jMenuBar1.add(fileMenu);
helpMenu = new javax.swing.JMenu ();
helpMenu.setText ("Help");
helpAboutMenuItem = new javax.swing.JMenuItem ();
helpAboutMenuItem.setText ("Item");
helpAboutMenuItem.addActionListener (new java.awt.event.ActionListener () {
public void actionPerformed (java.awt.event.ActionEvent evt) {
helpAboutMenuItemActionPerformed (evt);
}
}
);
helpMenu.add(helpAboutMenuItem);
jMenuBar1.add(helpMenu);
setJMenuBar(jMenuBar1);
connectPanel = new javax.swing.JPanel ();
connectPanel.setLayout (new java.awt.FlowLayout ());
connectPanelLabel = new javax.swing.JLabel ();
connectPanelLabel.setText ("Connection");
connectPanelLabel.setForeground (java.awt.Color.red);
connectPanel.add (connectPanelLabel);
portsLabel = new javax.swing.JLabel ();
portsLabel.setText ("Port:");
connectPanel.add (portsLabel);
portsComboBox = new javax.swing.JComboBox ();
portsComboBox.addActionListener (new java.awt.event.ActionListener () {
public void actionPerformed (java.awt.event.ActionEvent evt) {
portsComboBoxActionPerformed (evt);
}
}
);
connectPanel.add (portsComboBox);
buadLabel = new javax.swing.JLabel ();
buadLabel.setText ("Speed");
connectPanel.add (buadLabel);
baudComboBox = new javax.swing.JComboBox ();
baudComboBox.addActionListener (new java.awt.event.ActionListener () {
public void actionPerformed (java.awt.event.ActionEvent evt) {
baudComboBoxActionPerformed (evt);
}
}
);
connectPanel.add (baudComboBox);
databitsPanel = new javax.swing.JPanel ();
databitsPanel.setPreferredSize (new java.awt.Dimension(50, 50));
databitsPanel.setMinimumSize (new java.awt.Dimension(0, 0));
databitsPanel.setLayout (new javax.swing.BoxLayout (databitsPanel, 1));
d7RadioButton = new javax.swing.JRadioButton ();
d7RadioButton.setText ("7");
databitsPanel.add (d7RadioButton);
d8RadioButton = new javax.swing.JRadioButton ();
d8RadioButton.setSelected (true);
d8RadioButton.setText ("8");
databitsPanel.add (d8RadioButton);
connectPanel.add (databitsPanel);
parityPanel = new javax.swing.JPanel ();
parityPanel.setPreferredSize (new java.awt.Dimension(50, 50));
parityPanel.setLayout (new javax.swing.BoxLayout (parityPanel, 1));
pNoneRadioButton = new javax.swing.JRadioButton ();
pNoneRadioButton.setSelected (true);
pNoneRadioButton.setText ("None");
pNoneRadioButton.addActionListener (new java.awt.event.ActionListener () {
public void actionPerformed (java.awt.event.ActionEvent evt) {
pNoneRadioButtonActionPerformed (evt);
}
}
);
parityPanel.add (pNoneRadioButton);
pEvenRadioButton = new javax.swing.JRadioButton ();
pEvenRadioButton.setText ("Even");
pEvenRadioButton.addActionListener (new java.awt.event.ActionListener () {
public void actionPerformed (java.awt.event.ActionEvent evt) {
evenRadioButtonActionPerformed (evt);
}
}
);
parityPanel.add (pEvenRadioButton);
pOddRadioButton = new javax.swing.JRadioButton ();
pOddRadioButton.setText ("Odd");
pOddRadioButton.addActionListener (new java.awt.event.ActionListener () {
public void actionPerformed (java.awt.event.ActionEvent evt) {
oddRadioButtonActionPerformed (evt);
}
}
);
parityPanel.add (pOddRadioButton);
connectPanel.add (parityPanel);
sysTypeLabel = new javax.swing.JLabel ();
sysTypeLabel.setText ("Remote:");
connectPanel.add (sysTypeLabel);
sysTypeComboBox = new javax.swing.JComboBox ();
sysTypeComboBox.addActionListener (new java.awt.event.ActionListener () {
public void actionPerformed (java.awt.event.ActionEvent evt) {
sysTypeComboBoxActionPerformed (evt);
}
}
);
connectPanel.add (sysTypeComboBox);
connectButton = new javax.swing.JButton ();
connectButton.setText ("Connect");
connectButton.addActionListener (new java.awt.event.ActionListener () {
public void actionPerformed (java.awt.event.ActionEvent evt) {
connectButtonActionPerformed (evt);
}
}
);
connectPanel.add (connectButton);
getContentPane().add(connectPanel, BorderLayout.NORTH);
xferPanel = new javax.swing.JPanel ();
xferPanel.setLayout (new java.awt.FlowLayout ());
xferPanelLabel = new javax.swing.JLabel ();
xferPanelLabel.setText ("File Transfer");
xferPanelLabel.setForeground (java.awt.Color.red);
xferPanel.add (xferPanelLabel);
jPanel6 = new javax.swing.JPanel ();
jPanel6.setLayout (new javax.swing.BoxLayout (jPanel6, 1));
sendRadioButton = new javax.swing.JRadioButton ();
sendRadioButton.setSelected (true);
sendRadioButton.setText ("Send");
sendRadioButton.addActionListener (new java.awt.event.ActionListener () {
public void actionPerformed (java.awt.event.ActionEvent evt) {
sendRadioButtonActionPerformed (evt);
}
}
);
jPanel6.add (sendRadioButton);
recvRadioButton = new javax.swing.JRadioButton ();
recvRadioButton.setText ("Receive");
recvRadioButton.addActionListener (new java.awt.event.ActionListener () {
public void actionPerformed (java.awt.event.ActionEvent evt) {
recvRadioButtonActionPerformed (evt);
}
}
);
jPanel6.add (recvRadioButton);
xferPanel.add (jPanel6);
xferFilenameLabel = new javax.swing.JLabel ();
xferFilenameLabel.setText ("Filename:");
xferPanel.add (xferFilenameLabel);
xferFileNameTF = new javax.swing.JTextField ();
xferFileNameTF.setPreferredSize (new java.awt.Dimension(100, 20));
xferPanel.add (xferFileNameTF);
jPanel7 = new javax.swing.JPanel ();
jPanel7.setLayout (new javax.swing.BoxLayout (jPanel7, 1));
xferModeTextRadioButton = new javax.swing.JRadioButton ();
xferModeTextRadioButton.setText ("Text");
jPanel7.add (xferModeTextRadioButton);
xferModeBinRadioButton = new javax.swing.JRadioButton ();
xferModeBinRadioButton.setSelected (true);
xferModeBinRadioButton.setText ("Binary");
jPanel7.add (xferModeBinRadioButton);
xferPanel.add (jPanel7);
xferButton = new javax.swing.JButton ();
xferButton.setText ("Transfer");
xferButton.addActionListener (new java.awt.event.ActionListener () {
public void actionPerformed (java.awt.event.ActionEvent evt) {
xferButtonActionPerformed (evt);
}
}
);
xferPanel.add (xferButton);
getContentPane ().add (xferPanel, BorderLayout.SOUTH);
}//GEN-END:initComponents
/** Save the session log to disk.
*/
private void saveLogFileMenuItemActionPerformed (java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveLogFileMenuItemActionPerformed
theModel.saveLogFile();
}//GEN-LAST:event_saveLogFileMenuItemActionPerformed
private void helpAboutMenuItemActionPerformed (java.awt.event.ActionEvent evt) {//GEN-FIRST:event_helpAboutMenuItemActionPerformed
note("JModem 0.0 (c) 2000 Ian F. Darwin\nhttp://www.darwinsys.com/");
}//GEN-LAST:event_helpAboutMenuItemActionPerformed
private void baudComboBoxActionPerformed (java.awt.event.ActionEvent evt) {
// Add your handling code here:
}
private void portsComboBoxActionPerformed (java.awt.event.ActionEvent evt) {//GEN-FIRST:event_portsComboBoxActionPerformed
// Add your handling code here:
}//GEN-LAST:event_portsComboBoxActionPerformed
/** A TextArea subclass with funky keypress forwarding: send to
* remote, not to local. This IS a terminal emulator, after all.
*/
class MyTextArea extends JTextArea {
MyTextArea(int r, int c) {
super(r, c);
}
/** Handle local KeyEvents: send KeyTyped to the remote. */
protected void processComponentKeyEvent(java.awt.event.KeyEvent evt) {
if (evt.getID() != KeyEvent.KEY_TYPED)
return;
// send keystrokes to remote, for processing.
// do nothing locally, to avoid user keystrokes appearing twice!
if (theModel.state != JMModel.S_CONNECTED) {
getToolkit().beep(); // or just connect()?
return;
}
char ch = evt.getKeyChar();
if (ch == '\n') { // XX if systemtype == dos
// sendChar('\r');
theModel.sendChar('\n');
return;
}
theModel.sendChar(ch);
}
}
/** Finish the initializations. */
private void finishConstructor() {
// Create the textarea with a JScrollpane wrapping it.
// Install it in Centre of the TextArea.
theTextArea = new MyTextArea(20, 80);
getContentPane().add(new JScrollPane(theTextArea), BorderLayout.CENTER);
plainFont = new Font("courier", Font.PLAIN, 13);
theTextArea.setFont(plainFont);
xferFileNameTF.setFont(plainFont);
theModel.populateComboBox();
portsComboBox.setSelectedIndex(0);
// Load up the baud rate combo box
for (int i=0; i " + ch);
try {
serialOutput.write(ch);
} catch (IOException e) {
theGUI.err("Output error on remote:\n" + e.toString() +
"\nClosing connection.");
disconnect();
}
}
/** Send a String of characters to the remote. */
private void sendString(String s) {
if (state != S_CONNECTED)
return;
try {
serialOutput.write(s.getBytes());
} catch (IOException e) {
theGUI.err("Output error on remote:\n" + e.toString() +
"\nClosing connection.");
disconnect();
}
}
/** Do one complete file transfer, using TModem */
public void xfer() {
if (state != S_CONNECTED) {
theGUI.err("Must be connected to do file transfers");
return;
}
if (xferProg == null) {
xferProg = new TModem(serialInput, serialOutput,
new PrintWriter(System.out)); // xerProg discarded in disconnect()
}
String fileName = theGUI.getXferFileName();
if (fileName.length() == 0) {
theGUI.err("Filename must be given");
return;
}
// Do the transfer! If we are sending, send a "tmodem -r" to
// the other side; if receiving, send "tmodem -s" to ask it
// to send the file.
try {
if (theGUI.isSend()) {
if (!new File(fileName).canRead()) {
theGUI.err("Can't read file " + fileName + ".");
return;
}
// Other end must "r"eceive what we send.
sendString("tmodem -r " + fileName + "\r\n");
delay(500); // let command echo back to us
submode = S_XFER;
xferProg.send(fileName);
} else {
// Other end must send for us to receive.
sendString("tmodem -s " + fileName + "\r\n");
delay(500); // let command echo back to us
submode = S_XFER;
xferProg.receive(fileName);
}
} catch (InterruptedException e) {
theGUI.err("Timeout");
return;
} catch (IOException e) {
theGUI.err("IO Exception in transfer:\n" + e);
return;
} catch (Exception ev) {
theGUI.err("Protocol failure:\n" + ev);
return;
} finally {
submode = S_INTERACT;
}
theGUI.note("File Transfer completed");
}
}
/**
* a tiny version of Ward Christensen's MODEM program for UNIX.
* Written ~ 1980 by Andrew Scott Beals. Last revised 1982.
* A.D. 2000 - dragged from the archives for use in Java Cookbook.
*
* @author C version by Andrew Scott Beals, sjobrg.andy%mit-oz@mit-mc.arpa.
* @author Java version by Ian F. Darwin, ian@darwinsys.com
* $Id: TModem.java,v 1.8 2000/03/02 03:40:50 ian Exp $
*/
class TModem {
protected final byte CPMEOF = 26; /* control/z */
protected final int MAXERRORS = 10; /* max times to retry one block */
protected final int SECSIZE = 128; /* cpm sector, transmission block */
protected final int SENTIMOUT = 30; /* timeout time in send */
protected final int SLEEP = 30; /* timeout time in recv */
/* Protocol characters used */
protected final byte SOH = 1; /* Start Of Header */
protected final byte EOT = 4; /* End Of Transmission */
protected final byte ACK = 6; /* ACKnowlege */
protected final byte NAK = 0x15; /* Negative AcKnowlege */
protected InputStream inStream;
protected OutputStream outStream;
protected PrintWriter errStream;
/** Construct a TModem */
public TModem(InputStream is, OutputStream os, PrintWriter errs) {
inStream = is;
outStream = os;
errStream = errs;
}
/** Construct a TModem with default files (stdin and stdout). */
public TModem() {
inStream = System.in;
outStream = System.out;
errStream = new PrintWriter(System.err);
}
/** A main program, for direct invocation. */
public static void main(String[] argv) throws
IOException, InterruptedException {
/* argc must == 2, i.e., `java TModem -s filename' */
if (argv.length != 2)
usage();
if (argv[0].charAt(0) != '-')
usage();
TModem tm = new TModem();
tm.setStandalone(true);
boolean OK = false;
switch (argv[0].charAt(1)){
case 'r':
OK = tm.receive(argv[1]);
break;
case 's':
OK = tm.send(argv[1]);
break;
default:
usage();
}
System.out.print(OK?"Done OK":"Failed");
System.exit(0);
}
/* give user minimal usage message */
protected static void usage()
{
System.err.println("usage: TModem -r/-s file");
// not errStream, not die(), since this is static.
System.exit(1);
}
/** If we're in a standalone app it is OK to System.exit() */
protected boolean standalone = false;
public void setStandalone(boolean is) {
standalone = is;
}
public boolean isStandalone() {
return standalone;
}
/** A flag used to communicate with inner class IOTimer */
protected boolean gotChar;
/** An inner class to provide a read timeout for alarms. */
class IOTimer extends Thread {
String message;
long milliseconds;
/** Construct an IO Timer */
IOTimer(long sec, String mesg) {
milliseconds = 1000 * sec;
message = mesg;
}
public void run() {
try {
Thread.sleep(milliseconds);
} catch (InterruptedException e) {
// can't happen
}
/** Implement the timer */
if (!gotChar)
errStream.println("Timed out waiting for " + message);
die(1);
}
}
/*
* send a file to the remote
*/
public boolean send(String tfile) throws IOException, InterruptedException
{
char checksum, index, blocknumber, errorcount;
byte character;
byte[] sector = new byte[SECSIZE];
int nbytes;
DataInputStream foo;
foo = new DataInputStream(new FileInputStream(tfile));
errStream.println( "file open, ready to send");
errorcount = 0;
blocknumber = 1;
// The C version uses "alarm()", a UNIX-only system call,
// to detect if the read times out. Here we do detect it
// by using a Thread, the IOTimer class defined above.
gotChar = false;
new IOTimer(SENTIMOUT, "NAK to start send").start();
do {
character = getchar();
gotChar = true;
if (character != NAK && errorcount < MAXERRORS)
++errorcount;
} while (character != NAK && errorcount < MAXERRORS);
errStream.println( "transmission beginning");
if (errorcount == MAXERRORS) {
xerror();
}
while ((nbytes=inStream.read(sector))!=0) {
if (nbytes