Cześć,
zaczyna się uczyć obsługi portu COM za pośrednictwem javy.
Wszystko fajnie ale kiedy wysyłam bajt danych, to wysypuje się port odbiorczy z nr błędy 103.
Testuję to tak, że mam po usb podłączone dwa sparowane ftdi. Komunikacja między dwoma instancja mi terminala COM jest bezproblemowa, natomiast jak wysyłam z alikacji w javie to terminal zgłasza błąd portu.
Jak to rozwiązać?
Używam PortableRXTX.jar pobranego z pierwszego posta http://forum.atnel.pl/topic6547.html
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Enumeration;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JSlider;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import gnu.io.CommPortIdentifier;
import javafx.scene.image.Image;
public class MainFrame extends JFrame implements ChangeListener, ActionListener{
private static final long serialVersionUID = -5780505145960057156L;
private JButton pbFrezeeMin;
private JButton pbFrezeeMax;
private JButton pbCheckCom;
private JSlider slider;
private JComboBox combo;
private JLabel labelCurrent;
private JLabel labelCom;
private int max = 255, min = 0;
private final String slCurrent = "Current value: ";
private COM communication = new COM();;
public MainFrame() {
// TODO Auto-generated constructor stub
super("TITLE");
labelCom = new JLabel("Port COM: ");
combo = new JComboBox();
combo.setPreferredSize(new Dimension(100, 20));
Enumeration ports = CommPortIdentifier.getPortIdentifiers();
while(ports.hasMoreElements())
combo.addItem(((CommPortIdentifier)ports.nextElement()).getName());
pbCheckCom = new JButton("Connect");
pbCheckCom.addActionListener(this);
slider = new JSlider(SwingConstants.HORIZONTAL, 0, 255, 1);
slider.setPreferredSize(new Dimension(500, 50));
slider.setMajorTickSpacing(15);
slider.setMinorTickSpacing(1);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.addChangeListener(this);
//slider.setValue(127);
pbFrezeeMax = new JButton("MAX: 255");
pbFrezeeMax.addActionListener(this);
pbFrezeeMin = new JButton("MIN: 0");
pbFrezeeMin.addActionListener(this);
labelCurrent = new JLabel(slCurrent + slider.getValue());
this.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(5,5,5,5);
c.gridx = 0; c.gridy = 0; c.anchor = GridBagConstraints.WEST;
this.add(labelCom, c);
c.gridx = 1; c.gridy = 0; c.anchor = GridBagConstraints.CENTER;
this.add(combo, c);
c.gridx = 2; c.gridy = 0; c.anchor = GridBagConstraints.EAST;
this.add(pbCheckCom, c);
c.gridx = 0; c.gridy = 1; c.anchor = GridBagConstraints.CENTER;
c.gridwidth = 3; c.fill = GridBagConstraints.HORIZONTAL;
this.add(slider, c);
c.gridwidth = 1; c.fill = GridBagConstraints.NONE;
c.gridx = 0; c.gridy = 2; c.anchor = GridBagConstraints.WEST;
this.add(pbFrezeeMin, c);
c.gridx = 1; c.gridy = 2; c.anchor = GridBagConstraints.CENTER;
this.add(labelCurrent, c);
c.gridx = 2; c.gridy = 2; c.anchor = GridBagConstraints.EAST;
this.add(pbFrezeeMax, c);
this.pack();
this.setResizable(false);
this.setLocation(450,450);
this.setVisible(true);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent we)
{
if( communication.isConnected() ) {
communication.setAlertsOff();
communication.disconnect();
}
System.exit(0);
/* String ObjButtons[] = {"Yes","No"};
int PromptResult = JOptionPane.showOptionDialog(null,"Are you sure you want to exit?","Online Examination System",JOptionPane.DEFAULT_OPTION,JOptionPane.WARNING_MESSAGE,null,ObjButtons,ObjButtons[1]);
if(PromptResult==JOptionPane.YES_OPTION)
{
if( communication.isConnected() ) {
communication.setAlertsOff();
communication.disconnect();
}
System.exit(0);
}*/
}
});
}
public static void main(String[] args) {
// TODO Auto-generated method stub
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
new MainFrame();
}
});
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Object sender = e.getSource();
if( sender == pbFrezeeMin )
{
min = slider.getValue();
pbFrezeeMin.setText("MIN: " + slider.getValue());
}
else if( sender == pbFrezeeMax )
{
max = slider.getValue();
pbFrezeeMax.setText("MAX: " + slider.getValue());
}
else if( sender == pbCheckCom )
{
slider.setValue(127);
if( !communication.isConnected() ) {
communication.Start(combo.getSelectedItem().toString());
}
else {
communication.disconnect();
}
if( communication.isConnected() ) {
pbCheckCom.setText("Disconnect");
pbCheckCom.setForeground(Color.RED);
}
else {
pbCheckCom.setText("Connect");
pbCheckCom.setForeground(Color.BLACK);
}
}
}
@Override
public void stateChanged(ChangeEvent e) {
Object sender = e.getSource();
if( sender == slider)
{
int val = slider.getValue();
labelCurrent.setText(slCurrent + val);
if( val > (min-1) && val < (max+1) )
{
communication.writeData((byte)slider.getValue());
}
}
}
}
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.TooManyListenersException;
import javax.swing.JOptionPane;
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
public class COM implements SerialPortEventListener{
private HashMap portMap = null;
private CommPortIdentifier selectedPortIdentifier = null;
private SerialPort serialPort = null;
private InputStream input = null;
private OutputStream output = null;
private boolean bConnected = false;
private boolean alertsOn = true;
final static int TIMEOUT = 2000;
public void Communication() {getComPortsNames();}
public boolean isConnected() { return bConnected; }
public List<String> getComPortsNames(){
List<String> portsNames = new ArrayList();
Enumeration ports = CommPortIdentifier.getPortIdentifiers();
while(ports.hasMoreElements())
{
portsNames.add(((CommPortIdentifier)ports.nextElement()).getName());
CommPortIdentifier curPort = (CommPortIdentifier)ports.nextElement();
portMap.put(curPort.getName(), curPort);
}
return portsNames;
}
public boolean Start(String portName) {
if ( bConnected ) disconnect();
if ( connect(portName) )
if ( initIOStream() )
if( initListener() )
{
popup("Connected to " + portName);
return true;
}
popup("Something goes wrong :(");
return false;
}
public boolean writeData(byte BYTE)
{
boolean success = false;
if( bConnected ) {
try
{
output.flush();
output.write(BYTE);
System.out.println(BYTE);
success = true;
}
catch (Exception e)
{
popup("Failed to write data. (" + e.toString() + ")");
}
}
//else popup("Port is not connected.");
return success;
}
public boolean disconnect()
{
try
{
serialPort.removeEventListener();
serialPort.close();
input.close();
output.close();
bConnected = false;
popup("Disconected");
}
catch (Exception e)
{
popup("Failed to close " + serialPort.getName() + "(" + e.toString() + ")");
}
return !bConnected;
}
private boolean connect(String port) {
CommPort commPort = null;
try {
selectedPortIdentifier = CommPortIdentifier.getPortIdentifier(port);
commPort = selectedPortIdentifier.open("TigerControlPanel", TIMEOUT);
serialPort = (SerialPort)commPort;
bConnected = true;
} catch (PortInUseException e) {
popup(port + " is currently in use.");
}
catch (Exception e)
{
popup("Can not open " + port +".");
}
return bConnected;
}
private boolean initIOStream() {
boolean success = false;
try {
input = serialPort.getInputStream();
output = serialPort.getOutputStream();
success = true;
}
catch (IOException e) {
popup("I/O Streams failed to open. (" + e.toString() + ")");
}
return success;
}
private boolean initListener()
{
try
{
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
return true;
}
catch (TooManyListenersException e)
{
popup("Too many listeners. (" + e.toString() + ")");
return false;
}
}
private void popup(String infoMessage)
{
if( alertsOn )
JOptionPane.showMessageDialog(null, infoMessage, "Communication", JOptionPane.INFORMATION_MESSAGE);
}
public void setAlertsOn() { alertsOn = true; }
public void setAlertsOff() { alertsOn = false; }
public boolean isAlertsOn() { return alertsOn; }
@Override
public void serialEvent(SerialPortEvent evt) {
if (evt.getEventType() == SerialPortEvent.DATA_AVAILABLE)
{
try
{
byte singleData = (byte)input.read();
popup("Read data: " + singleData);
}
catch (Exception e)
{
popup("Failed to read data. (" + e.toString() + ")");
}
}
}
}