001package jmri.jmrix.qsi.packetgen; 002 003import java.awt.Dimension; 004import javax.swing.BoxLayout; 005import jmri.jmrix.qsi.QsiMessage; 006import jmri.jmrix.qsi.QsiSystemConnectionMemo; 007 008/** 009 * Frame for user input of QSI messages. Input is a sequence of hex pairs, 010 * including the length, but not the lead 'A', checksum or final 'E'. 011 * 012 * @author Bob Jacobsen Copyright (C) 2007, 2008 013 */ 014public class PacketGenFrame extends jmri.util.JmriJFrame { 015 016 private QsiSystemConnectionMemo _memo = null; 017 018 // member declarations 019 javax.swing.JLabel jLabel1 = new javax.swing.JLabel(); 020 javax.swing.JButton sendButton = new javax.swing.JButton(); 021 javax.swing.JTextField packetTextField = new javax.swing.JTextField(12); 022 023 public PacketGenFrame(QsiSystemConnectionMemo memo) { 024 super(); 025 _memo = memo; 026 } 027 028 /** 029 * {@inheritDoc} 030 */ 031 @Override 032 public void initComponents() { 033 // the following code sets the frame's initial state 034 035 jLabel1.setText("Command:"); 036 jLabel1.setVisible(true); 037 038 sendButton.setText("Send"); 039 sendButton.setVisible(true); 040 sendButton.setToolTipText("Send packet"); 041 042 packetTextField.setText(""); 043 packetTextField.setToolTipText("Enter command as hex string"); 044 packetTextField.setMaximumSize( 045 new Dimension(packetTextField.getMaximumSize().width, 046 packetTextField.getPreferredSize().height 047 ) 048 ); 049 050 setTitle("Send QSI command"); 051 getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); 052 053 getContentPane().add(jLabel1); 054 getContentPane().add(packetTextField); 055 getContentPane().add(sendButton); 056 057 sendButton.addActionListener(this::sendButtonActionPerformed); 058 059 // pack for display 060 pack(); 061 } 062 063 public void sendButtonActionPerformed(java.awt.event.ActionEvent e) { 064 String input = packetTextField.getText(); 065 // TODO check input + feedback on error. Too easy to cause NPE 066 _memo.getQsiTrafficController().sendQsiMessage(createPacket(input), null); 067 } 068 069 /** 070 * Create a well-formed packet from a String 071 * 072 * @param s input contents 073 * @return The packet, with contents filled-in 074 */ 075 QsiMessage createPacket(String s) { 076 // gather bytes in result 077 byte b[] = jmri.util.StringUtil.bytesFromHexString(s); 078 if (b.length == 0) { 079 return null; // no such thing as a zero-length message 080 } 081 QsiMessage m = new QsiMessage(b.length); 082 for (int i = 0; i < b.length; i++) { 083 m.setElement(i, b[i]); 084 } 085 return m; 086 } 087 088}