Created
January 5, 2012 14:24
-
-
Save nsi4927/1565470 to your computer and use it in GitHub Desktop.
RS232 Send by Stop And Wait & Selective Repeat. Using Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.awt.BorderLayout; | |
import java.awt.Color; | |
import java.awt.Container; | |
import java.awt.GridLayout; | |
import java.awt.event.ActionEvent; | |
import java.awt.event.ActionListener; | |
import java.awt.event.ItemEvent; | |
import java.awt.event.ItemListener; | |
import java.io.BufferedReader; | |
import java.io.File; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.InputStreamReader; | |
import java.io.PrintStream; | |
import java.util.Enumeration; | |
import java.util.HashMap; | |
import java.util.ArrayList; | |
import javax.comm.*; | |
import javax.swing.JButton; | |
import javax.swing.JComboBox; | |
import javax.swing.JDialog; | |
import javax.swing.JFileChooser; | |
import javax.swing.JFrame; | |
import javax.swing.JLabel; | |
import javax.swing.JList; | |
import javax.swing.JOptionPane; | |
import javax.swing.JPanel; | |
import javax.swing.JScrollBar; | |
import javax.swing.JScrollPane; | |
import javax.swing.event.AncestorEvent; | |
import javax.swing.event.AncestorListener; | |
/** | |
* Open a serial port using Java Communications. | |
* | |
* @author Ian F. Darwin, http://www.darwinsys.com/ | |
*/ | |
/* | |
* Define ArrayList for keep data packet | |
*/ | |
public class CommPortOpen { | |
/** How long to wait for the open to finish up. */ | |
public static final int TIMEOUTSECONDS = 30; | |
/** The baud rate to use. */ | |
public static final int BAUD = 9600; | |
/** The parent JFrame, for the chooser. */ | |
protected JFrame parent; | |
/** The input stream */ | |
protected BufferedReader is; | |
/** The output stream */ | |
protected PrintStream os; | |
/** The interrupt send files */ | |
protected InterrupSender intSend; | |
/** The interrupt wait-time for re-send packet */ | |
protected WaitTime initWaitTime; | |
/**/ | |
protected static PortChooser layout; | |
/** The chosen Port Identifier */ | |
CommPortIdentifier thePortID; | |
/** The process receive event */ | |
CommPortReceiver comProReceive; | |
/** The chosen Port itself */ | |
CommPort thePort; | |
SerialPort myPort; | |
CommPortReceiver comreciever; | |
/** Transfer mode */ | |
protected char Tmode; | |
final static char RECEIV_ = 'R'; | |
final static char SEND_ = 'S'; | |
final static char ACK_ = 'A'; | |
final static char NAK_ = 'N'; | |
final static String ChkEnd = "1111111111FF"; | |
final static String SW = "Stop And Wait"; | |
final static String SR = "Selective Repeat"; | |
protected static ArrayList<String> datapacket; | |
protected static ArrayList<String> datapacketBuff; | |
protected int currentPackNo = 0, currentDiff = 0, currentSuc = -1, | |
currentSendPacket = 0; | |
protected static boolean[] packetStatus = new boolean[5000]; | |
public static void main(String[] argv) throws IOException, | |
NoSuchPortException, PortInUseException, | |
UnsupportedCommOperationException { | |
// Clear packet | |
datapacket = new ArrayList<String>(); | |
// new CommPortOpen(null).converse(); | |
CommPortOpen app = new CommPortOpen(); | |
layout = new PortChooser(); | |
datapacket = layout.datapacket; | |
layout.setVisible(true); | |
app.updateStatus(); | |
} | |
public void updateStatus() { | |
layout.status.setListData(layout.statusTxt.toArray()); | |
} | |
public void createCrateEvent(PortChooser c) throws IOException, | |
NoSuchPortException, PortInUseException, | |
UnsupportedCommOperationException { | |
String portName = null; | |
// Dialog done. Get the port name. | |
portName = c.getSelectedName(); | |
if (portName == null) { | |
System.out.println("No port selected. Try again.\n"); | |
} else { | |
thePortID = c.getSelectedIdentifier(); | |
switch (thePortID.getPortType()) { | |
case CommPortIdentifier.PORT_SERIAL: | |
thePort = thePortID.open("DarwinSys DataComm", | |
TIMEOUTSECONDS * 1000); | |
myPort = (SerialPort) thePort; | |
// set up the serial port | |
myPort.setSerialPortParams(BAUD, SerialPort.DATABITS_8, | |
SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); | |
break; | |
default: // Neither parallel nor serial?? | |
throw new IllegalStateException("Unknown port type " | |
+ thePortID); | |
} | |
} | |
// System.exit(0); | |
if (c.actionChoice.getSelectedItem().equals("Sender") | |
&& c.mode.getSelectedItem().equals(SW)) { | |
try { | |
Packet packet = new Packet(); | |
datapacket = packet.getPacket(new InputStreamFile() | |
.getData(c.path_)); | |
layout.statusTxt.clear(); | |
for (int i = 0; i < datapacket.size(); i++) { | |
layout.statusTxt.add("Send Package number: " + i); | |
// System.out.println(datapacket.get(i)+"["+datapacket.get(i).length()+"]"); | |
} | |
updateStatus(); | |
stopAndwait(); | |
try { | |
Tmode = SEND_; | |
comProReceive = new CommPortReceiver( | |
myPort.getInputStream(), this, Tmode, layout.mode | |
.getSelectedItem().toString()); | |
comProReceive.start(); | |
} catch (Exception e) { | |
} | |
} catch (Exception ee) { | |
ee.printStackTrace(); | |
} | |
} else if (c.actionChoice.getSelectedItem().equals("Receiver")) { | |
layout.statusTxt.clear(); | |
layout.statusTxt.add("Receiving....."); | |
updateStatus(); | |
try { | |
Tmode = RECEIV_; | |
comProReceive = new CommPortReceiver(myPort.getInputStream(), | |
this, Tmode, layout.mode.getSelectedItem().toString()); | |
comProReceive.start(); | |
} catch (Exception e) { | |
} | |
} else if (c.actionChoice.getSelectedItem().equals("Sender") | |
&& c.mode.getSelectedItem().equals(SR)) { | |
try { | |
datapacket = new Packet().getPacket(new InputStreamFile() | |
.getData(c.path_)); | |
layout.statusTxt.clear(); | |
for (int i = 0; i < datapacket.size(); i++) { | |
layout.statusTxt.add("Send Package number: " + i); | |
// System.out.println(datapacket.get(i)+"["+datapacket.get(i).length()+"]"); | |
} | |
updateStatus(); | |
// selectiveRepeat(""); | |
intSend = new InterrupSender(this); | |
try { | |
Tmode = SEND_; | |
new CommPortReceiver(myPort.getInputStream(), this, Tmode, | |
layout.mode.getSelectedItem().toString()).start(); | |
} catch (Exception e) { | |
} | |
// selectiveRepeat(""); | |
} catch (Exception ee) { | |
ee.printStackTrace(); | |
} | |
} | |
} | |
/* Constructor */ | |
public void getCommPortOpen(JFrame f) throws IOException, | |
NoSuchPortException, PortInUseException, | |
UnsupportedCommOperationException { | |
} | |
/** | |
* This method will be overridden by non-trivial subclasses to hold a | |
* conversation. | |
*/ | |
protected void converse() throws IOException { | |
System.out.println("Ready to read and write port."); | |
// Input/Output code not written -- must subclass. | |
// Finally, clean up. | |
if (is != null) | |
is.close(); | |
os.close(); | |
} | |
public boolean stopAndwait() { | |
if (datapacket.isEmpty()) | |
return false; | |
try { | |
write(datapacket.get(0)); | |
// Set new interrupt for wait time | |
initWaitTime = new WaitTime(this); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
return true; | |
} | |
public boolean selectiveRepeat(String strIndex) { | |
int index = 0; | |
if (!strIndex.isEmpty()) { | |
index = Integer.parseInt(strIndex); | |
// if(datapacket.isEmpty()) return false; | |
if (index == datapacket.size() - 1) | |
return false; | |
} | |
try { | |
for (int i = 0; i < index; i++) { | |
if (!packetStatus[i]) { | |
write(datapacket.get(i)); | |
} | |
} | |
// /datapacket.remove(Integer.parseInt(strIndex)); | |
packetStatus[index] = true; | |
if (currentSuc < index) | |
currentSuc = index; | |
intSend = new InterrupSender(this); | |
// currentPackNo--; | |
} catch (Exception e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
return true; | |
} | |
protected ArrayList<String> chkRemove(ArrayList<String> src, String key, | |
int init) { | |
if (init > src.size() - 1) { | |
init = src.size() - 1; | |
} | |
for (int i = init; i >= 0; i--) { | |
if (src.get(i).equals(key)) { | |
src.remove(i); | |
} | |
} | |
return src; | |
} | |
protected void write(String src) throws IOException { | |
// TEST FOR SEND | |
CommPortSender.setWriterStream(myPort.getOutputStream()); | |
CommPortSender.send(src.getBytes()); | |
} | |
} | |
class PortChooser extends JFrame implements ItemListener { | |
final static String Appname = "RS232 NetWork Proj. V 1.0"; | |
/** A mapping from names to CommPortIdentifiers. */ | |
protected HashMap map = new HashMap(); | |
/** The name of the choice the user made. */ | |
protected String selectedPortName; | |
/** The CommPortIdentifier the user chose. */ | |
protected CommPortIdentifier selectedPortIdentifier; | |
/** The JComboBox for serial ports */ | |
protected JComboBox serialPortsChoice; | |
/** The JComboBox for parallel ports */ | |
protected JComboBox actionChoice; | |
/** The JComboBox for anything else */ | |
protected JComboBox mode; | |
/** | |
* The time for wail send/ | |
*/ | |
protected JComboBox timewait; | |
/** The file chose */ | |
protected JFileChooser fileselect; | |
/** The SerialPort object */ | |
protected SerialPort ttya; | |
/** To display the chosen */ | |
protected JLabel choice; | |
/* | |
* For button choose file | |
*/ | |
protected JButton Choosefile; | |
/* The status send and receive */ | |
protected JButton processButton, about; | |
protected JList status; | |
/** Scrollbar */ | |
protected JScrollPane jscollBar; | |
protected JLabel aboutl; | |
/** | |
* Status contain/ | |
* | |
*/ | |
protected ArrayList<String> statusTxt = new ArrayList<String>(); | |
protected ArrayList<String> datapacket; | |
/** Padding in the GUI */ | |
protected final int PAD = 5; | |
// Path file from select | |
protected String path_ = "", filename = ""; | |
protected Object oj; | |
protected CommPortOpen commportOpen; | |
/** | |
* This will be called from either of the JComboBoxen when the user selects | |
* any given item. | |
*/ | |
public void itemStateChanged(ItemEvent e) { | |
String choose = (String) ((JComboBox) e.getSource()).getSelectedItem(); | |
// Get the name | |
if (choose.contains("COM")) { | |
selectedPortName = choose; | |
// Get the given CommPortIdentifier | |
selectedPortIdentifier = (CommPortIdentifier) map | |
.get(selectedPortName); | |
} | |
if (actionChoice.getSelectedItem().equals("Receiver") | |
|| mode.getSelectedItem().equals(commportOpen.SR)) { | |
timewait.setEnabled(false); | |
} else { | |
timewait.setEnabled(true); | |
} | |
} | |
/* The public "getter" to retrieve the chosen port by name. */ | |
public String getSelectedName() { | |
return selectedPortName; | |
} | |
/* The public "getter" to retrieve the selection by CommPortIdentifier. */ | |
public CommPortIdentifier getSelectedIdentifier() { | |
return selectedPortIdentifier; | |
} | |
/** | |
* Construct a PortChooser --make the GUI and populate the ComboBoxes. | |
*/ | |
public PortChooser() { | |
super(Appname); | |
makeGUI(); | |
populate(); | |
finishGUI(); | |
commportOpen = new CommPortOpen(); | |
oj = this; | |
} | |
/** | |
* Build the GUI. You can ignore this for now if you have not yet worked | |
* through the GUI chapter. Your mileage may vary. | |
*/ | |
protected void makeGUI() { | |
Container cp = getContentPane(); | |
JPanel northPanel = new JPanel(); | |
JPanel bottom = new JPanel(); | |
JPanel center = new JPanel(); | |
cp.add(BorderLayout.NORTH, northPanel); | |
cp.add(BorderLayout.CENTER, center); | |
cp.add(BorderLayout.SOUTH, bottom); | |
northPanel.setLayout(new GridLayout(0, 2, PAD, PAD)); | |
bottom.setLayout(new GridLayout(0, 1, PAD, PAD)); | |
center.setLayout(new GridLayout(0, 1, PAD, PAD)); | |
northPanel.add(new JLabel("Serial Ports", JLabel.RIGHT)); | |
serialPortsChoice = new JComboBox(); | |
serialPortsChoice.addItem(""); | |
northPanel.add(serialPortsChoice); | |
northPanel.add(new JLabel("Action", JLabel.RIGHT)); | |
actionChoice = new JComboBox(); | |
actionChoice.addItem("Sender"); | |
actionChoice.addItem("Receiver"); | |
northPanel.add(actionChoice); | |
northPanel.add(about = new JButton("ABOUT")); | |
about.addActionListener(new ActionListener() { | |
@Override | |
public void actionPerformed(ActionEvent arg0) { | |
// TODO Auto-generated method stub | |
JOptionPane | |
.showMessageDialog( | |
new JFrame(), | |
"DEVELOPER\n\tMr.Narong Intiruk\n\n" | |
+ Appname | |
+ "\n2012@copyrigth \n\nwww.facebook.com/dotnetz", | |
"About of Applications", | |
JOptionPane.INFORMATION_MESSAGE); | |
} | |
}); | |
fileselect = new JFileChooser(); | |
fileselect.setCurrentDirectory(new File(".")); | |
northPanel.add(Choosefile = new JButton("Choose File Location")); | |
Choosefile.addActionListener(new ActionListener() { | |
public void actionPerformed(ActionEvent e) { | |
int select; | |
if (actionChoice.getSelectedItem().equals("Receiver")) { | |
select = fileselect.showSaveDialog(new JFrame()); | |
} else { | |
select = fileselect.showOpenDialog(new JFrame()); | |
} | |
if (select == JFileChooser.APPROVE_OPTION) { | |
// fileselect | |
File path = fileselect.getSelectedFile(); | |
path_ = path.getAbsolutePath(); | |
filename = path.getName(); | |
} | |
} | |
}); | |
// Select Mode | |
northPanel.add(new JLabel("Use Mode:", JLabel.RIGHT)); | |
mode = new JComboBox(); | |
mode.addItem("Stop And Wait"); | |
mode.addItem("Selective Repeat"); | |
northPanel.add(mode); | |
// Time wait selection | |
northPanel.add(new JLabel("Time Wait(Sec.)", JLabel.RIGHT)); | |
timewait = new JComboBox(); | |
for (int i = 1; i < 10; i++) { | |
timewait.addItem(i); | |
} | |
northPanel.add(timewait); | |
center.add(BorderLayout.NORTH, processButton = new JButton( | |
" << Processes >> ")); | |
processButton.addActionListener(new ActionListener() { | |
public void actionPerformed(ActionEvent e) { | |
if (checkError()) { | |
if (processButton.getText().equals(" << Processes >> ")) { | |
try { | |
commportOpen.createCrateEvent((PortChooser) oj); | |
} catch (IOException e1) { | |
// TODO Auto-generated catch block | |
e1.printStackTrace(); | |
} catch (NoSuchPortException e1) { | |
// TODO Auto-generated catch block | |
e1.printStackTrace(); | |
} catch (PortInUseException e1) { | |
// TODO Auto-generated catch block | |
e1.printStackTrace(); | |
} catch (UnsupportedCommOperationException e1) { | |
// TODO Auto-generated catch block | |
e1.printStackTrace(); | |
} | |
setDisableLayout(); | |
processButton.setText(" << Stop >> "); | |
} else if (processButton.getText().equals( | |
" << Stop >> ")) { | |
try { | |
// Clear interrupt and close port. | |
commportOpen.myPort.close(); | |
commportOpen.thePort.close(); | |
if (commportOpen.comProReceive != null) { | |
commportOpen.comProReceive.stop(); | |
} | |
if (commportOpen.initWaitTime != null) { | |
commportOpen.initWaitTime.stop(); | |
} | |
if (commportOpen.intSend != null) { | |
commportOpen.intSend.stop(); | |
} | |
} catch (Exception e1) { | |
e1.printStackTrace(); | |
} | |
// Enable menu | |
setEnableLayout(); | |
processButton.setText(" << Processes >> "); | |
if (actionChoice.getSelectedItem().equals("Receiver") | |
|| mode.getSelectedItem().equals( | |
commportOpen.SR)) { | |
timewait.setEnabled(false); | |
statusTxt.clear(); | |
commportOpen.updateStatus(); | |
} | |
} | |
} | |
} | |
}); | |
center.add(BorderLayout.CENTER, new JLabel("{ Package Status }")); | |
status = new JList(statusTxt.toArray()); | |
status.setBackground(Color.black); | |
status.setSelectionBackground(Color.YELLOW); | |
status.setForeground(Color.BLUE); | |
status.setVisibleRowCount(17); | |
jscollBar = new JScrollPane(status); | |
bottom.add(BorderLayout.CENTER, jscollBar); | |
} | |
public void setDisableLayout() { | |
serialPortsChoice.setEnabled(false); | |
actionChoice.setEnabled(false); | |
mode.setEnabled(false); | |
timewait.setEnabled(false); | |
Choosefile.setEnabled(false); | |
// processButton.setEnabled(false); | |
} | |
public void setEnableLayout() { | |
serialPortsChoice.setEnabled(true); | |
actionChoice.setEnabled(true); | |
mode.setEnabled(true); | |
timewait.setEnabled(true); | |
Choosefile.setEnabled(true); | |
processButton.setEnabled(true); | |
processButton.setText(" << Processes >> "); | |
} | |
/** | |
* Populate the ComboBoxes by asking the Java Communications API what ports | |
* it has. Since the initial information comes from a Properties file, it | |
* may not exactly reflect your hardware. | |
*/ | |
protected void populate() { | |
// get list of ports available on this particular computer, | |
// by calling static method in CommPortIdentifier. | |
Enumeration pList = CommPortIdentifier.getPortIdentifiers(); | |
// Process the list, putting serial and parallel into ComboBoxes | |
while (pList.hasMoreElements()) { | |
CommPortIdentifier cpi = (CommPortIdentifier) pList.nextElement(); | |
// System.out.println("Port " + cpi.getName()); | |
map.put(cpi.getName(), cpi); | |
if (cpi.getPortType() == CommPortIdentifier.PORT_SERIAL) { | |
serialPortsChoice.setEnabled(true); | |
serialPortsChoice.addItem(cpi.getName()); | |
} | |
} | |
} | |
protected void finishGUI() { | |
serialPortsChoice.addItemListener(this); | |
actionChoice.addItemListener(this); | |
mode.addItemListener(this); | |
pack(); | |
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
} | |
public boolean checkError() { | |
if (serialPortsChoice.getSelectedIndex() < 1) { | |
JOptionPane.showMessageDialog(this, | |
"Plaese select the Serialport number.", "Error Checking", | |
JOptionPane.ERROR_MESSAGE); | |
return false; | |
} else if (path_.isEmpty()) { | |
if (actionChoice.getSelectedItem().equals("Sender")) { | |
JOptionPane.showMessageDialog(this, | |
"Plaese select your file to send.", "Error Checking", | |
JOptionPane.ERROR_MESSAGE); | |
return false; | |
} | |
} | |
return true; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.ByteArrayInputStream; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.math.BigInteger; | |
import java.util.ArrayList; | |
import java.util.zip.Adler32; | |
import java.util.zip.CheckedInputStream; | |
public class CommPortReceiver extends Thread { | |
InputStream in; | |
String dataPacket = ""; | |
String dataBuff, StrchkSUM, datafilename, mode; | |
StringBuilder dataComplate = new StringBuilder(); | |
CommPortOpen commPort; | |
Protocol protocol = new ProtocolImpl(); | |
int packetNo = 0; | |
int cntPN = 4; | |
int cntPL = 2; | |
int timeCnt = 0; | |
int cntSum = 8; | |
int cntdot = 0; | |
int filenameL; | |
int packetNO, dataLength; | |
boolean chkH = false; | |
boolean chkPN = false; | |
boolean chkPL = false; | |
boolean chkData = false; | |
boolean chkSum = false; | |
boolean chkdot = false; | |
boolean chkfilename = false; | |
boolean chkfilename_ = false; | |
char Tmode, chBuff; | |
public CommPortReceiver(InputStream in, CommPortOpen commPort, char Tmode, | |
String mode) { | |
this.in = in; | |
this.commPort = commPort; | |
this.Tmode = Tmode; | |
this.mode = mode; | |
} | |
public void run() { | |
try { | |
int b; | |
while (true) { | |
// if stream is not bound in.read() method returns -1 | |
while ((b = in.read()) != -1) { | |
protocol.onReceive((byte) b); | |
chBuff = ((char) (byte) b); | |
if (mode.equals(commPort.SW)) { | |
if (Tmode == commPort.RECEIV_) { | |
readReceiver(chBuff); | |
} else if (Tmode == commPort.SEND_) { | |
// System.out.println("buffer "+chBuff); | |
readSendSW(chBuff); | |
} | |
} else if (mode.equals(commPort.SR)) { | |
if (Tmode == commPort.RECEIV_) { | |
readReceiver(chBuff); | |
} else if (Tmode == commPort.SEND_) { | |
// System.out.println(chBuff+"SEND"); | |
// System.out.println("buffer "+chBuff); | |
readSendSR(chBuff); | |
} | |
} | |
} | |
// commPort.stopAndwait(Integer.parseInt(strTm)); | |
protocol.onStreamClosed(); | |
// wait 10ms when stream is broken and check again | |
sleep(10); | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
public boolean readSendSR(char cBuff) { | |
dataPacket += cBuff; | |
if (commPort.currentSuc < 9) { | |
commPort.intSend.interrupt(); | |
commPort.intSend.stop(); | |
commPort.selectiveRepeat(dataPacket); | |
// Update status | |
commPort.layout.statusTxt = commPort.chkRemove( | |
commPort.layout.statusTxt, "Send Package number: " | |
+ dataPacket, Integer.parseInt(dataPacket)); | |
commPort.updateStatus(); | |
dataPacket = ""; | |
} else if ((commPort.currentSuc >= 9) && dataPacket.length() == 2) { | |
System.out.println(dataPacket + "Send"); | |
// Set interrupt for receive | |
commPort.intSend.interrupt(); | |
// Update status | |
commPort.layout.statusTxt = commPort.chkRemove( | |
commPort.layout.statusTxt, "Send Package number: " | |
+ dataPacket, Integer.parseInt(dataPacket)); | |
commPort.updateStatus(); | |
if (Integer.parseInt(dataPacket) == commPort.datapacket.size() - 1) { | |
commPort.layout.statusTxt.clear(); | |
commPort.layout.statusTxt.add("Send is finish"); | |
commPort.updateStatus(); | |
String tm = new Packet() | |
.packageFilename(commPort.layout.filename); | |
try { | |
commPort.write(tm); | |
} catch (IOException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
commPort.layout.setEnableLayout(); | |
commPort.myPort.close(); | |
commPort.thePort.close(); | |
this.stop(); | |
} | |
dataPacket = ""; | |
} else { | |
commPort.selectiveRepeat(""); | |
} | |
// System.out.println(chBuff); | |
return true; | |
} | |
public void readSendSW(char str) { | |
// System.out.println(str + "" + commPort.currentPackNo | |
// + commPort.datapacket.size()); | |
if (str == commPort.ACK_) { | |
// Set Interrupt for read ACK. | |
commPort.initWaitTime.interrupt(); | |
if (commPort.datapacket.size() != 0) { | |
commPort.datapacket.remove(0); | |
commPort.layout.statusTxt.remove(0); | |
commPort.updateStatus(); | |
commPort.stopAndwait(); | |
if (commPort.layout.statusTxt.isEmpty()) { | |
commPort.layout.statusTxt.add("Send is finish."); | |
commPort.updateStatus(); | |
try { | |
// Write for end data | |
String tm = new Packet() | |
.packageFilename(commPort.layout.filename); | |
commPort.write(tm); | |
commPort.layout.setEnableLayout(); | |
commPort.myPort.close(); | |
commPort.thePort.close(); | |
this.stop(); | |
} catch (IOException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
} | |
} | |
} else if (str == commPort.NAK_) { | |
commPort.stopAndwait(); | |
} else { | |
} | |
} | |
public void readReceiver(char str) { | |
// System.out.println(str); | |
if (dataPacket.toString().equals("7E") && !(chkPL)) { | |
chkH = true; | |
dataPacket = ""; | |
} | |
if (chkH) { | |
dataPacket += str; | |
if (dataPacket.length() == 4) { | |
packetNo = Integer.parseInt(dataPacket, 16); | |
dataPacket = ""; | |
chkPN = true; | |
chkH = false; | |
} | |
} else if (chkPN) { | |
dataPacket += str; | |
if (dataPacket.length() == 2) { | |
dataLength = Integer.parseInt(dataPacket, 16); | |
dataPacket = ""; | |
chkPL = true; | |
chkPN = false; | |
} | |
} else if (chkPL) { // Check packet length | |
dataPacket += str; | |
if (dataPacket.length() == dataLength * 2) { | |
dataBuff = dataPacket; | |
dataPacket = ""; | |
chkData = true; | |
chkPL = false; | |
} | |
} else if (chkData) { // Check data from packet | |
dataPacket += str; | |
if (dataPacket.length() == 8) { | |
StrchkSUM = dataPacket; | |
dataPacket = ""; | |
chkData = false; | |
showDataPacket(); | |
} | |
} else { | |
// System.out.println(dataPacket); | |
dataPacket += str; | |
} | |
if (dataPacket.equals(commPort.ChkEnd)) { // Check end of packet | |
// Decode filename | |
chkfilename = true; | |
dataPacket = ""; | |
} else if (chkfilename && dataPacket.length() == 1) { | |
// Decode filename length | |
filenameL = Integer.parseInt(dataPacket, 16); | |
chkfilename_ = true; | |
chkfilename = false; | |
dataPacket = ""; | |
} else if (chkfilename_ && dataPacket.length() == (filenameL * 2)) { | |
datafilename = Hex2Str(dataPacket); | |
// Tempt for keep filename | |
String temp = commPort.layout.path_; | |
boolean isHasDot = false; | |
if (!temp.isEmpty()) { | |
if (temp.contains(".")) | |
datafilename = temp; | |
else { | |
datafilename = temp | |
+ datafilename.substring(datafilename.indexOf(".")); | |
} | |
} | |
try { | |
new InputStreamFile().fileWriter(builFile(), datafilename); | |
// System.out.println(datafilename); | |
} catch (IOException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
commPort.layout.setEnableLayout(); | |
commPort.layout.timewait.setEnabled(false); | |
commPort.myPort.close(); | |
commPort.thePort.close(); | |
this.stop(); | |
} | |
} | |
public String builFile() { | |
String buil = Hex2Str(dataComplate.toString()); | |
return buil; | |
} | |
public void showDataPacket() { | |
String chkSum = chkSum(dataBuff); | |
int tm = chkSum.length(); | |
tm = 8 - tm; | |
while (true) { | |
if (tm < 1) | |
break; | |
chkSum = "0" + chkSum; | |
tm--; | |
} | |
if (chkSum.equals(StrchkSUM)) { | |
// System.out.println(dataBuff); | |
dataComplate.append(dataBuff); | |
try { | |
commPort.layout.statusTxt.add("Receive package number:" | |
+ packetNo); | |
commPort.updateStatus(); | |
if (mode.equals(commPort.SW)) { | |
commPort.write("A"); | |
} else if (mode.equals(commPort.SR)) { | |
// System.out.println("packetNo"+Integer.toString(packetNo)); | |
commPort.write(Integer.toString(packetNo)); | |
} | |
} catch (Exception e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
} else { | |
try { | |
commPort.write("N"); | |
} catch (IOException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
} | |
} | |
public static String Hex2Str(String src) { | |
StringBuilder str = new StringBuilder(); | |
int lengthOfStr = src.length(); | |
String tm; | |
for (int i = 0; i < lengthOfStr; i += 2) { | |
tm = src.substring(0, 2); | |
if (src.length() > 0) { | |
src = src.substring(2); | |
} | |
// Convert hex to character | |
str.append((char) (Integer.parseInt(tm, 16))); | |
} | |
return str.toString(); | |
} | |
public static String chkSum(String data) { | |
String chk = ""; | |
try { | |
String string = new String(data); | |
byte buffer[] = string.getBytes(); | |
ByteArrayInputStream bais = new ByteArrayInputStream(buffer); | |
CheckedInputStream cis = new CheckedInputStream(bais, new Adler32()); | |
byte readBuffer[] = new byte[5]; | |
while (cis.read(readBuffer) >= 0) { | |
long value = cis.getChecksum().getValue(); | |
chk = Long.toString(value); | |
} | |
} catch (Exception e) { | |
System.out.println("Exception has been caught" + e); | |
return null; | |
} | |
Object[] arg = { new BigInteger(chk) }; | |
return String.format("%x", arg); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.io.OutputStream; | |
public class CommPortSender { | |
static OutputStream out; | |
public static void setWriterStream(OutputStream out) { | |
CommPortSender.out = out; | |
} | |
public static void send(byte[] bytes) { | |
try { | |
if (out != null) { | |
out.write(bytes); | |
out.flush(); | |
} | |
} catch (IOException e) { | |
// e.printStackTrace(); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.math.BigInteger; | |
public class InputStreamFile { | |
public String getData(String path) { | |
final String filename = path.substring(0, path.indexOf(".")); | |
final String dot = path.substring(path.indexOf(".") + 1); | |
System.out.println(filename + "." + dot); | |
try { | |
File f = new File("outFile." + dot); | |
File fout = new File("outFile.out"); | |
File facii = new File("outAcii.out"); | |
InputStream inputStream = new FileInputStream(filename + "." + dot); | |
byte buf[] = new byte[5000]; | |
int len; | |
String data = ""; | |
while ((len = inputStream.read(buf)) > 0) { | |
data += Str2H(buf, len); | |
} | |
inputStream.close(); | |
return data; | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
return ""; | |
} | |
public String Str2H(byte[] str, int len) | |
throws UnsupportedEncodingException { | |
// byte n = str.getBytes("UTF-8"); | |
Object[] arg = { new BigInteger(str) }; | |
String buff = String.format("%x", arg); | |
return buff.substring(0, len * 2); | |
} | |
/* | |
* change integer to hex base | |
*/ | |
public String Int2H(String src) { | |
Object[] arg = { src }; | |
return String.format("%x", arg); | |
} | |
public void fileWriter(String src, String filename) throws IOException { | |
System.out.println(filename); | |
int len; | |
byte[] buf = new byte[5000]; | |
buf = src.getBytes(); | |
InputStream in = new StringBufferInputStream(src); | |
File facii = new File(filename); | |
OutputStream out2 = new FileOutputStream(facii); | |
while ((len = in.read(buf)) > 0) { | |
out2.write(buf, 0, len); | |
} | |
out2.close(); | |
in.close(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.util.ArrayList; | |
public class InterrupSender extends Thread implements Runnable { | |
CommPortOpen commPort; | |
public void run() { | |
while (commPort.currentSendPacket < commPort.datapacket.size()) { | |
try { | |
Thread.sleep(1); | |
try { | |
commPort.write(commPort.datapacket | |
.get(commPort.currentSendPacket++)); | |
} catch (IOException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
} catch (InterruptedException x) { | |
this.stop(); | |
return; | |
} | |
} | |
// System.out.println("in run() - leaving normally"); | |
} | |
public InterrupSender(CommPortOpen commPort) { | |
this.commPort = commPort; | |
this.start(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.ByteArrayInputStream; | |
import java.io.UnsupportedEncodingException; | |
import java.math.BigInteger; | |
import java.util.zip.Adler32; | |
import java.util.zip.CheckedInputStream; | |
import java.util.*; | |
public class Packet { | |
/** | |
* @param args | |
*/ | |
final static String OPCODE = "7E"; | |
static private BigInteger _RUNN; | |
static private BigInteger _LENGTH; | |
static private BigInteger _CRC; | |
static private String MLSB; | |
static private String _MSB; | |
static private String _LSB; | |
static private String _LENG; | |
static private String _DATA = ""; | |
static private String _CRCDATA; | |
static private String Sep_ = ""; | |
static private StringBuilder _PACKET; | |
public Packet() { | |
_RUNN = new BigInteger("0"); | |
_LENGTH = new BigInteger("148"); | |
_CRC = new BigInteger("0"); | |
_PACKET = new StringBuilder(); | |
} | |
public ArrayList<String> getPacket(String SRCh) { | |
ArrayList<String> datapacket = new ArrayList<String>(); | |
while (true) { | |
try { | |
// Start create packet | |
_PACKET.append(OPCODE); // Add opcode to head | |
if (SRCh.length() < _LENGTH.intValue() * 2) | |
_LENGTH = new BigInteger( | |
Integer.toString(SRCh.length() / 2)); | |
// Section of data | |
_DATA = SRCh.substring(0, _LENGTH.intValue() * 2); | |
// Check for data | |
if (_DATA.length() <= 0) | |
break; | |
// Set MSB and LSB | |
MLSB = Int2H(_RUNN).toString(); | |
// Check for length and add digits to msb/lsb | |
switch (MLSB.length()) { | |
case 1: | |
MLSB = "000" + MLSB; | |
break; | |
case 2: | |
MLSB = "00" + MLSB; | |
break; | |
case 3: | |
MLSB = "0" + MLSB; | |
break; | |
} | |
// Check for digits of Length data | |
_LENG = Int2H(_LENGTH).toString(); | |
if (_LENG.length() == 1) | |
_LENG = "0" + _LENG; | |
// Select MSB/LSB and add to frame | |
_MSB = MLSB.substring(0, 2); | |
_LSB = MLSB.substring(2); | |
_PACKET.append(Sep_ + _MSB + _LSB); | |
// Update MSB/LSB Length packet | |
_RUNN = _RUNN.add(new BigInteger("1")); | |
// Cal CRC | |
// _CRC = getCRC(_DATA,Bi2Dec(GenCode)); | |
try { | |
_PACKET.append(Sep_ + _LENG); // Add length of data | |
_PACKET.append(Sep_ + _DATA); // Add Data to packet | |
_CRC = new BigInteger(chkSum(_DATA)); | |
_CRCDATA = Int2H(_CRC); | |
int tm = _CRCDATA.length(); | |
tm = 8 - tm; | |
while (true) { | |
if (tm < 1) | |
break; | |
_CRCDATA = "0" + _CRCDATA; | |
tm--; | |
} | |
_PACKET.append(Sep_ + _CRCDATA); // Add CRC | |
// Update Data tmp | |
SRCh = SRCh.substring(_LENGTH.intValue() * 2); | |
datapacket.add(_PACKET.toString()); | |
} catch (Exception e) { | |
System.out.println("ERROR"); | |
e.printStackTrace(); | |
break; | |
} | |
// System.out.println(Hex2Str(getData(_PACKET.toString()))); | |
_PACKET = new StringBuilder(); | |
} catch (Exception e) { | |
System.out.println("ERROR1"); | |
e.printStackTrace(); | |
} | |
} | |
return datapacket; | |
} | |
public static String Str2H(String str) throws UnsupportedEncodingException { | |
Object[] arg = { new BigInteger(str.getBytes("UTF-8")) }; | |
return String.format("%x", arg); | |
} | |
/* | |
* change integer to hex base | |
*/ | |
public static String Int2H(BigInteger src) { | |
Object[] arg = { src }; | |
return String.format("%x", arg); | |
} | |
public static String Hex2Dec(String src) { | |
return Integer.toString(Integer.parseInt(src, 16)); | |
} | |
public static String Hex2Bi(String src) { | |
return Integer.toString(Integer.parseInt(src, 16)); | |
} | |
public static String Dec2Bi(String src) { | |
return Integer.toBinaryString(Integer.parseInt(src)); | |
} | |
public static String Bi2Dec(String src) { | |
return Integer.toString(Integer.parseInt(src, 2)); | |
} | |
public static String Hex2Str(String src) { | |
StringBuilder str = new StringBuilder(); | |
int lengthOfStr = src.length(); | |
String tm; | |
for (int i = 0; i < lengthOfStr; i += 2) { | |
tm = src.substring(0, 2); | |
if (src.length() > 0) { | |
src = src.substring(2); | |
} | |
// Convert hex to character | |
str.append((char) (Integer.parseInt(tm, 16))); | |
} | |
return str.toString(); | |
} | |
public static String getData(String src) { | |
// Keep data | |
StringBuilder str = new StringBuilder(); | |
// Get length of data string. | |
int lengthOfData = Integer.parseInt(src.substring(6, 8), 16); | |
// get data from packet | |
// System.out.println("AA"+lengthOfData*2+"AA"+src.length()); | |
// Double to get in half byte | |
lengthOfData *= 2; | |
src = src.substring(8, 8 + lengthOfData); | |
// System.out.println("<< "+lengthOfData+">>"+src.length()); | |
// Loop for get the data | |
// Must divide 4 because real length unit in byte | |
for (int i = 0; i < lengthOfData; i++) { | |
str.append(src.charAt(i)); | |
} | |
return str.toString(); | |
} | |
public static String chkSum(String data) { | |
String chk = ""; | |
try { | |
String string = new String(data); | |
byte buffer[] = string.getBytes(); | |
ByteArrayInputStream bais = new ByteArrayInputStream(buffer); | |
CheckedInputStream cis = new CheckedInputStream(bais, new Adler32()); | |
byte readBuffer[] = new byte[5]; | |
while (cis.read(readBuffer) >= 0) { | |
long value = cis.getChecksum().getValue(); | |
chk = Long.toString(value); | |
} | |
} catch (Exception e) { | |
System.out.println("Exception has been caught" + e); | |
return null; | |
} | |
return chk; | |
} | |
public String packageFilename(String src) { | |
String str = ""; | |
String tm; | |
str += "1111111111FF"; | |
str += Int2H(new BigInteger(Integer.toString(src.length()))); | |
try { | |
str += Str2H(src); | |
} catch (UnsupportedEncodingException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
return str; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface Protocol { | |
// protocol manager handles each received byte | |
void onReceive(byte b); | |
// protocol manager handles broken stream | |
void onStreamClosed(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ProtocolImpl implements Protocol { | |
byte[] buffer = new byte[1000000]; | |
int tail = 0; | |
public void onReceive(byte b) { | |
// simple protocol: each message ends with new line | |
if (b == '\n') { | |
onMessage(); | |
} else { | |
buffer[tail] = b; | |
tail++; | |
} | |
} | |
public void onStreamClosed() { | |
onMessage(); | |
} | |
/* | |
* When message is recognized onMessage is invoked | |
*/ | |
private void onMessage() { | |
if (tail != 0) { | |
// constructing message | |
String message = getMessage(buffer, tail); | |
System.out.println("RECEIVED MESSAGE: " + message); | |
// this logic should be placed in some kind of | |
// message interpreter class not here | |
if ("HELO".equals(message)) { | |
CommPortSender.send(getMessage("OK")); | |
} else if ("OK".equals(message)) { | |
CommPortSender.send(getMessage("OK ACK")); | |
} | |
tail = 0; | |
} | |
} | |
// helper methods | |
public byte[] getMessage(String message) { | |
return (message + "\n").getBytes(); | |
} | |
public String getMessage(byte[] buffer, int len) { | |
return new String(buffer, 0, tail); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.FileFilter; | |
import javax.swing.JFileChooser; | |
import java.io.File; | |
public class WaitTime extends Thread implements Runnable { | |
CommPortOpen commPort; | |
public void run() { | |
// while(true){ | |
try { | |
// Sleep for wait time follow user select and by 1000 | |
// This is get value from index of Selection because we can get | |
// Integer | |
Thread.sleep(1000 * (commPort.layout.timewait.getSelectedIndex() + 1)); | |
//System.out.println("Send Repeat"); | |
commPort.stopAndwait(); | |
} catch (InterruptedException e) { | |
this.stop(); | |
return; | |
} | |
// } | |
} | |
public WaitTime(CommPortOpen commPort) { | |
this.commPort = commPort; | |
this.start(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment