simplified SerialUI implementation: code was both complex, buggy and contained unused broken functionality (slip, tos mode)

This commit is contained in:
Fredrik Osterlind 2012-06-07 12:33:29 +02:00
parent 6da3c03884
commit 019b984b7a

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2007, Swedish Institute of Computer Science. * Copyright (c) 2012, Swedish Institute of Computer Science.
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
@ -44,8 +44,6 @@ import java.util.Observable;
import java.util.Observer; import java.util.Observer;
import javax.swing.JButton; import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane; import javax.swing.JOptionPane;
import javax.swing.JPanel; import javax.swing.JPanel;
import javax.swing.JScrollPane; import javax.swing.JScrollPane;
@ -58,161 +56,165 @@ import org.jdom.Element;
import se.sics.cooja.Mote; import se.sics.cooja.Mote;
import se.sics.cooja.interfaces.Log; import se.sics.cooja.interfaces.Log;
import se.sics.cooja.interfaces.SerialPort; import se.sics.cooja.interfaces.SerialPort;
import se.sics.cooja.plugins.SLIP;
public abstract class SerialUI extends Log implements SerialPort { public abstract class SerialUI extends Log implements SerialPort {
private static Logger logger = Logger.getLogger(SerialUI.class); private static Logger logger = Logger.getLogger(SerialUI.class);
private final static byte SLIP_END = (byte)0300;
private final static byte SLIP_ESC = (byte)0333;
private final static byte SLIP_ESC_END = (byte)0334;
private final static byte SLIP_ESC_ESC = (byte)0335;
private final static int MAX_LENGTH = 1024; private final static int MAX_LENGTH = 1024;
private String lastLogMessage = ""; private byte lastSerialData = 0; /* SerialPort */
private StringBuilder newMessage = new StringBuilder(); private String lastLogMessage = ""; /* Log */
private StringBuilder newMessage = new StringBuilder(); /* Log */
private JTextArea logTextPane = null; /* Command history */
private JTextField commandField; private final static int HISTORY_SIZE = 15;
private JCheckBox slipCheckbox; private ArrayList<String> history = new ArrayList<String>();
private String[] history = new String[50]; private int historyPos = -1;
private int historyPos = 0;
private int historyCount = 0;
private class SerialDataObservable extends Observable { /* Log */
private void notifyNewData() { public String getLastLogMessage() {
return lastLogMessage;
}
/* SerialPort */
private abstract class SerialDataObservable extends Observable {
public abstract void notifyNewData();
}
private SerialDataObservable serialDataObservable = new SerialDataObservable() {
public void notifyNewData() {
if (this.countObservers() == 0) { if (this.countObservers() == 0) {
return; return;
} }
setChanged(); setChanged();
notifyObservers(SerialUI.this); notifyObservers(SerialUI.this);
} }
} };
private SerialDataObservable serialDataObservable = new SerialDataObservable();
private byte lastSerialData = 0;
public String getLastLogMessage() {
return lastLogMessage;
}
public abstract Mote getMote();
public void addSerialDataObserver(Observer o) { public void addSerialDataObserver(Observer o) {
serialDataObservable.addObserver(o); serialDataObservable.addObserver(o);
} }
public void deleteSerialDataObserver(Observer o) { public void deleteSerialDataObserver(Observer o) {
serialDataObservable.deleteObserver(o); serialDataObservable.deleteObserver(o);
} }
public byte getLastSerialData() { public byte getLastSerialData() {
return lastSerialData; return lastSerialData;
} }
public void dataReceived(int data) {
public JPanel getInterfaceVisualizer() { if (data == '\n') {
JPanel panel = new JPanel(); /* Notify observers of new log */
panel.setLayout(new BorderLayout()); lastLogMessage = newMessage.toString();
lastLogMessage = lastLogMessage.replaceAll("[^\\p{Print}]", "");
if (logTextPane == null) { newMessage.setLength(0);
logTextPane = new JTextArea(); this.setChanged();
} this.notifyObservers(getMote());
} else {
// Send RS232 data visualizer newMessage.append((char) data);
JPanel sendPane = new JPanel(new BorderLayout()); if (newMessage.length() > MAX_LENGTH) {
commandField = new JTextField(15); /*logger.warn("Dropping too large log message (>" + MAX_LENGTH + " bytes).");*/
JButton sendButton = new JButton("Send data"); lastLogMessage = "# [1024 bytes binary data]";
ActionListener action = new ActionListener() { newMessage.setLength(0);
this.setChanged();
public void actionPerformed(ActionEvent e) { this.notifyObservers(getMote());
String command = trim(commandField.getText()); }
if (command != null) { }
try {
int previous = historyCount - 1; /* Notify observers of new serial character */
if (previous < 0) { lastSerialData = (byte) data;
previous += history.length; serialDataObservable.notifyNewData();
} }
if (!command.equals(history[previous])) {
history[historyCount] = command;
historyCount = (historyCount + 1) % history.length; /* Mote interface visualizer */
} public JPanel getInterfaceVisualizer() {
historyPos = historyCount; JPanel panel = new JPanel(new BorderLayout());
JPanel commandPane = new JPanel(new BorderLayout());
if (slipCheckbox.isSelected()) {
addToLog("SLIP> " + command); final JTextArea logTextPane = new JTextArea();
command += "\n"; final JTextField commandField = new JTextField(15);
writeArray(SLIP.asSlip(command.getBytes())); JButton sendButton = new JButton("Send data");
ActionListener sendCommandAction = new ActionListener() {
public void actionPerformed(ActionEvent e) {
final String command = trim(commandField.getText());
if (command == null) {
commandField.getToolkit().beep();
return;
}
try {
/* Add to history */
if (history.size() > 0 && command.equals(history.get(0))) {
/* Ignored */
} else {
history.add(0, command);
while (history.size() > HISTORY_SIZE) {
history.remove(HISTORY_SIZE-1);
}
}
historyPos = -1;
appendToTextArea(logTextPane, "> " + command);
commandField.setText("");
if (getMote().getSimulation().isRunning()) {
getMote().getSimulation().invokeSimulationThread(new Runnable() {
public void run() {
writeString(command);
}
});
} else { } else {
addToLog("> " + command);
writeString(command); writeString(command);
} }
commandField.setText("");
} catch (Exception ex) { } catch (Exception ex) {
System.err.println("could not send '" + command + "':"); System.err.println("could not send '" + command + "':");
ex.printStackTrace(); ex.printStackTrace();
JOptionPane.showMessageDialog(logTextPane, JOptionPane.showMessageDialog(
"could not send '" + command + "':\n" logTextPane,
+ ex, "ERROR", "Could not send '" + command + "':\n" + ex.getMessage(), "Error sending message",
JOptionPane.ERROR_MESSAGE); JOptionPane.ERROR_MESSAGE);
} }
} else {
commandField.getToolkit().beep();
} }
}
}; };
commandField.addActionListener(sendCommandAction);
sendButton.addActionListener(sendCommandAction);
/* History */
commandField.addKeyListener(new KeyAdapter() { commandField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) { public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) { switch (e.getKeyCode()) {
case KeyEvent.VK_UP: { case KeyEvent.VK_UP: {
int nextPos = (historyPos + history.length - 1) % history.length; historyPos++;
if (nextPos == historyCount || history[nextPos] == null) { if (historyPos >= history.size()) {
historyPos = history.size() - 1;
commandField.getToolkit().beep(); commandField.getToolkit().beep();
} else {
String cmd = trim(commandField.getText());
if (cmd != null) {
history[historyPos] = cmd;
} }
historyPos = nextPos; if (historyPos >= 0 && historyPos < history.size()) {
commandField.setText(history[historyPos]); commandField.setText(history.get(historyPos));
} else {
commandField.setText("");
} }
break; break;
} }
case KeyEvent.VK_DOWN: { case KeyEvent.VK_DOWN: {
int nextPos = (historyPos + 1) % history.length; historyPos--;
if (nextPos == historyCount) { if (historyPos < 0) {
historyPos = nextPos; historyPos = -1;
commandField.setText(""); commandField.setText("");
} else if (historyPos == historyCount || history[nextPos] == null) {
commandField.getToolkit().beep(); commandField.getToolkit().beep();
} else { break;
String cmd = trim(commandField.getText());
if (cmd != null) {
history[historyPos] = cmd;
} }
historyPos = nextPos; if (historyPos >= 0 && historyPos < history.size()) {
commandField.setText(history[historyPos]); commandField.setText(history.get(historyPos));
} else {
commandField.setText("");
} }
break; break;
} }
} }
} }
}); });
slipCheckbox = new JCheckBox("", false); commandPane.add(BorderLayout.CENTER, commandField);
slipCheckbox.setToolTipText("Wrap data as SLIP"); commandPane.add(BorderLayout.EAST, sendButton);
commandField.addActionListener(action);
sendButton.addActionListener(action);
sendPane.add(BorderLayout.WEST, slipCheckbox);
sendPane.add(BorderLayout.CENTER, commandField);
sendPane.add(BorderLayout.EAST, sendButton);
// Receive RS232 data visualizer
logTextPane.setOpaque(false); logTextPane.setOpaque(false);
logTextPane.setEditable(false); logTextPane.setEditable(false);
logTextPane.addKeyListener(new KeyAdapter() { logTextPane.addKeyListener(new KeyAdapter() {
@ -223,52 +225,28 @@ public abstract class SerialUI extends Log implements SerialPort {
commandField.requestFocusInWindow(); commandField.requestFocusInWindow();
} }
}); });
if (getLastLogMessage() == null) {
logTextPane.setText("");
} else {
logTextPane.append(getLastLogMessage());
}
/* Mote interface observer */
Observer observer; Observer observer;
this.addObserver(observer = new Observer() { this.addObserver(observer = new Observer() {
public void update(Observable obs, Object obj) { public void update(Observable obs, Object obj) {
final String logMessage = getLastLogMessage(); final String logMessage = getLastLogMessage();
EventQueue.invokeLater(new Runnable() { EventQueue.invokeLater(new Runnable() {
public void run() { public void run() {
addToLog(logMessage); appendToTextArea(logTextPane, logMessage);
} }
}); });
} }
}); });
// Saving observer reference for releaseInterfaceVisualizer
panel.putClientProperty("intf_obs", observer); panel.putClientProperty("intf_obs", observer);
JScrollPane scrollPane = new JScrollPane(logTextPane); JScrollPane scrollPane = new JScrollPane(logTextPane);
scrollPane.setPreferredSize(new Dimension(100, 100)); scrollPane.setPreferredSize(new Dimension(100, 100));
panel.add(BorderLayout.NORTH, new JLabel("Last serial data:"));
panel.add(BorderLayout.CENTER, scrollPane); panel.add(BorderLayout.CENTER, scrollPane);
panel.add(BorderLayout.SOUTH, sendPane); panel.add(BorderLayout.SOUTH, commandPane);
return panel; return panel;
} }
protected void addToLog(String text) {
String current = logTextPane.getText();
int len = current.length();
if (len > 8192) {
current = current.substring(len - 8192);
}
current = len > 0 ? (current + '\n' + text) : text;
logTextPane.setText(current);
logTextPane.setCaretPosition(current.length());
Rectangle visRect = logTextPane.getVisibleRect();
if (visRect.x > 0) {
visRect.x = 0;
logTextPane.scrollRectToVisible(visRect);
}
}
public void releaseInterfaceVisualizer(JPanel panel) { public void releaseInterfaceVisualizer(JPanel panel) {
Observer observer = (Observer) panel.getClientProperty("intf_obs"); Observer observer = (Observer) panel.getClientProperty("intf_obs");
if (observer == null) { if (observer == null) {
@ -279,13 +257,14 @@ public abstract class SerialUI extends Log implements SerialPort {
this.deleteObserver(observer); this.deleteObserver(observer);
} }
private static final String HISTORY_SEPARATOR = "~;";
public Collection<Element> getConfigXML() { public Collection<Element> getConfigXML() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (String s: history) { for (String s: history) {
if (s == null) { if (s == null) {
continue; continue;
} }
sb.append(s + "~;"); sb.append(s + HISTORY_SEPARATOR);
} }
if (sb.length() == 0) { if (sb.length() == 0) {
return null; return null;
@ -302,101 +281,42 @@ public abstract class SerialUI extends Log implements SerialPort {
public void setConfigXML(Collection<Element> configXML, boolean visAvailable) { public void setConfigXML(Collection<Element> configXML, boolean visAvailable) {
for (Element element : configXML) { for (Element element : configXML) {
if (element.getName().equals("history")) { if (element.getName().equals("history")) {
String[] history = element.getText().split("~;"); String[] history = element.getText().split(HISTORY_SEPARATOR);
System.arraycopy(history, 0, this.history, 0, history.length); for (String h: history) {
historyCount = history.length; this.history.add(h);
historyPos = historyCount; }
historyPos = -1;
} }
} }
} }
private int tosChars = 0;
boolean tosMode = false;
private int tosPos = 0;
private int tosLen = 0;
private int slipCounter = 0;
private int totalTOSChars = 0;
public void dataReceived(int data) {
if (data == SLIP_END || data == SLIP_ESC) {
slipCounter++;
}
if (tosMode) {
int tmpData = data;
/* needs to add checks to CRC */
// System.out.println("Received: " + Integer.toString(data, 16) + " = " + (char) data + " tosPos: " + tosPos);
if (data == 0x7e) {
if (tosPos > 6) {
lastLogMessage = "TinyOS: " + newMessage.toString();
newMessage.setLength(0);
this.setChanged();
this.notifyObservers(getMote());
// System.out.println("*** Printing TOS String: " + lastLogMessage);
tosPos = 0;
tosLen = 0;
} else {
/* start of new message! */
tosPos = 0;
tosLen = 0;
}
}
if (tosPos == 7) {
tosLen = data;
// System.out.println("TOS Payload len: " + tosLen);
}
if (tosPos > 9 && tosPos < 10 + tosLen) {
if (data < 32) {
tmpData = 32;
}
newMessage.append((char) tmpData);
}
} else {
if (data == 0x7e) {
tosChars++;
totalTOSChars = 0; /* XXX Disabled TOS mode due to error */
totalTOSChars++;
if (tosChars == 2) {
if (totalTOSChars > slipCounter) {
tosMode = true;
tosMode = false; /* XXX Disabled TOS mode due to error */
/* already read one char here */
tosPos = 1;
} else {
tosChars = 0;
}
}
} else {
tosChars = 0;
}
if (data == '\n') {
lastLogMessage = newMessage.toString();
lastLogMessage = lastLogMessage.replaceAll("[^\\p{Print}]", "");
newMessage.setLength(0);
this.setChanged();
this.notifyObservers(getMote());
} else {
newMessage.append((char) data);
if (newMessage.length() > MAX_LENGTH) {
/*logger.warn("Dropping too large log message (>" + MAX_LENGTH + " bytes).");*/
lastLogMessage = "# [1024 bytes binary data]";
this.setChanged();
this.notifyObservers(getMote());
newMessage.setLength(0);
}
}
}
lastSerialData = (byte) data;
serialDataObservable.notifyNewData();
}
public void close() { public void close() {
} }
public void flushInput() { public void flushInput() {
} }
private String trim(String text) { public abstract Mote getMote();
protected static void appendToTextArea(JTextArea textArea, String text) {
String current = textArea.getText();
int len = current.length();
if (len > 8192) {
current = current.substring(len - 8192);
}
current = len > 0 ? (current + '\n' + text) : text;
textArea.setText(current);
textArea.setCaretPosition(current.length());
Rectangle visRect = textArea.getVisibleRect();
if (visRect.x > 0) {
visRect.x = 0;
textArea.scrollRectToVisible(visRect);
}
}
private static String trim(String text) {
return (text != null) && ((text = text.trim()).length() > 0) ? text : null; return (text != null) && ((text = text.trim()).length() > 0) ? text : null;
} }
} }