Javax.comm

16 respostas
L

Bom dia Pessoal,

estou tentando usar o javax.comm para acessar a serial, mas nao estou aprendendo e por isso estou com a seguinte dificulade.
No meu editor NetBeans , ele nao esta reconhecendo o pacote javax.com.*
eu digitei o seguinte :
import javax.comm.*;
e esta dando erro.
Obs: eu já copiei o comm.jar e javax.comm.properties para a pasta Lib domeu JDK e o Win32com.dll para o \bin

Alguem pode me ajudar a resolver este problema. Por fAvor ?

Agradeço pela atenção !

16 Respostas

W

Fala ai cara, blz?

Já ajudei um cara com duvida semelhante… dá uma olhada nesse tópico:

http://www.guj.com.br/posts/list/66915.java

Mas no demais, eu te aconselho a utilizar o RXTX http://www.rxtx.org/ ele é “baseado” na api de comm do java (com consertos…) e tem uma porrada de coisa nova e boa

A sun meio que deixou de lado a api de comunicação :frowning:

Abraços!

L

Obrigado Cara,

Como instalo e utilizo o rxtx.
ja procurei em varios lugares mas nao estou conseguindo.

N

Cara eu estou usando api communication para windows e não tive nenhum problema com isso, eu ate andei fazendo umas melhoras nela, se tu quiser eu posso te ajudar com isso.

L

Cara Se vc puder " me salvar ", eu agradeço.
O que eu preciso é apenas ler os dados recebidos na Com 2. Nem preciso enviar dados para serial, somente ler.
Grato pela ajuda e atenção

W

Primeiro passo é ler esse tutorial:

http://www.guj.com.br/java.tutorial.artigo.148.1.guj

Já leu?

Se sim, segundo passo é dar uma lida nas referências dele, principalmente neste pdf aqui:

http://java.sun.com/developer/Books/javaprogramming/cookbook/11.pdf

Blz?

Terceiro passo: grita aqui no fórum que alguém te ajuda :smiley:

A instalação do rxtx é bem parecida com a do javax.comm, se você conseguir instalar o javax.comm você consegue instalar o RXTX, estuda primeiro utilizando a comm e depois você migra pro RXTX pq no básico é a mesma coisa.

Falows!

N

se ta usando a commapi para windows?
descreva a sua configuração para mim poder te ajudar.

N

Uns daqueles tutoriais mostra como utilizar ela. é mais ou menos assim:

import javax.comm.<em>;

import java.util.</em>;

public class SerialCom extends Object

{

//variáveis para identificar portas

protected String[] portas;

protected Enumeration listaDePortas;

//construtor

public SerialCom()

{

listaDePortas = CommPortIdentifier.getPortIdentifiers();

}

//retorna as portas disponíveis

public String[] ObterPortas()

{

return portas;

}

//Copia portas para um Array

protected void ListarPortas()

{

int i = 0;

portas = new String[10];

while (listaDePortas.hasMoreElements())

{

CommPortIdentifier ips =

(CommPortIdentifier)listaDePortas.nextElement();

portas[i] = ips.getName();

i++;

}

}

//pesquisa se a Porta existe

public boolean PortaExiste(String COMp)

{

String temp;

boolean e = false;

while (listaDePortas.hasMoreElements())

{

CommPortIdentifier ips =

(CommPortIdentifier)listaDePortas.nextElement();

temp = ips.getName();

if (temp.equals(COMp)== true)

{

e = true;

};

}

return e;

}

protected void ImprimePortas()

{

for (int i = 0 ; i < portas.length ; i ++ )

{

if (portas[i] != null )

{

System.out.print(portas[i] + " “);

}

}

System.out.println(” ");

}

}//FIM DA CLASSE
N

aqui é outra classe:

import javax.comm.<em>;

import <a href="http://java.io">java.io</a>.</em>;

//classe Principal

public class SComm implements Runnable, SerialPortEventListener

{

//propriedades

private String Porta;

public String Dadoslidos;

public int nodeBytes;

private int baudrate;

private int timeout;

private CommPortIdentifier cp;

private SerialPort porta;

private OutputStream saida;

private InputStream entrada;

private Thread threadLeitura;

//indicadores

private boolean IDPortaOK; //true porta EXISTE

private boolean PortaOK;// true porta aberta

private boolean Leitura;

private boolean Escrita;
public static String mensagem;
//construtor default paridade : par
//baudrate: 9600 bps stopbits: 2 COM 1
public SComm() 
{
	Porta = "COM1";
	baudrate = 9600;
	timeout = 1000;
};
//um Objeto ComObj é passado ao construtor
//com detalhes de qual porta abrir
//e informações sobre configurações
public SComm( String p , int b , int t )
{
	this.Porta = p;
	this.baudrate = b;
	this.timeout = t;
};
//habilita escrita de dados
public void HabilitarEscrita()
{
	Escrita = true;
	Leitura = false;
}
//habilita leitura de dados
public void HabilitarLeitura()
{
	Escrita = false;
	Leitura = true;
}
//Obtém o ID da PORTA
public void ObterIdDaPorta()
{
	try 
	{
		cp = CommPortIdentifier.getPortIdentifier(Porta);
		if ( cp == null ) 
		{
			mensagem = "A " + Porta + " não existe!\nErro! Abortando...";
			Serial.status.append(mensagem+"\n");
			IDPortaOK = false;
			System.exit(1);
		}
		IDPortaOK = true;
	} catch (Exception e) 
	{
		mensagem = "Erro durante o procedimento. STATUS " + e;
		Serial.status.append(mensagem+"\n");
		IDPortaOK = false;
		System.exit(1);
	}
}
//Abre a comunicação da porta
public void AbrirPorta()
{
	try 
	{
		porta = (SerialPort)cp.open("SComm",timeout);
		PortaOK = true;
		mensagem = "Porta aberta com sucesso!";
		Serial.status.append(mensagem+"\n");
		
		//configurar parâmetros
		porta.setSerialPortParams(baudrate,
				porta.DATABITS_8,
				porta.STOPBITS_2,
				porta.PARITY_NONE);
	
	} 
	catch (Exception e) 
	{
		PortaOK = false;
		mensagem = "Erro ao abrir a porta! STATUS: " + e ;
		
		Serial.status.append(mensagem+"\n");
		System.exit(1);
	}
}
//função que envie um bit para a porta serial
public void EnviarUmaString(String msg)
{
	if (Escrita==true) 
	{
		try 
		{
			saida = porta.getOutputStream();
			mensagem = "FLUXO OK!";
			Serial.textAreaEnviados.append(mensagem+"\n");
		} 
		catch (Exception e) 
		{
			Serial.status.append("Erro.STATUS: " + e +"\n");
		}
		try 
		{
			Serial.textAreaEnviados.append("Enviando um byte para " + Porta +"\n");
			Serial.textAreaEnviados.append("Enviando: " + msg+"\n");
			saida.write(msg.getBytes());
			Thread.sleep(100);
			saida.flush();
		} 
		catch (Exception e) 
		{
			Serial.textAreaEnviados.append("Houve um erro durante o envio."+"\n");
			Serial.status.append("STATUS: " + e +"\n");
			System.exit(1);
		}
	} 
	else 
	{
		System.exit(1);
	}
}
//leitura de dados na serial
public void LerDados()
{
	if (Escrita == true)
	{
		try 
		{
			entrada = porta.getInputStream();
			Serial.textAreaRecebidos.append("FLUXO OK!"+"\n");
		}
		catch (Exception e) 
		{
			Serial.status.append("Erro.STATUS: " + e +"\n");
			System.exit(1);
		}
		try 
		{
			porta.addEventListener(this);
			Serial.textAreaRecebidos.append("SUCESSO. Porta aguardando..."+"\n");
		} 
		catch (Exception e) 
		{
			Serial.textAreaRecebidos.append("Erro ao criar listener: "+"\n");
			Serial.status.append("STATUS: " + e+"\n");
			System.exit(1);
		}
		porta.notifyOnDataAvailable(true);
		try 
		{
			threadLeitura = new Thread(this);
			threadLeitura.start();
		} 
		catch (Exception e) 
		{
			Serial.textAreaRecebidos.append("Erro ao iniciar leitura: " + e +"\n");
		}
	}
}//método RUN da thread de leitura
public void run()
{
	try 
	{
		Thread.sleep(5000);
	} 
	catch (Exception e) 
	{
		Serial.status.append("Erro. Status = " + e +"\n");
	}
}
//gerenciador de eventos de leitura na serial
public void serialEvent(SerialPortEvent ev)
{
	switch (ev.getEventType()) 
	{
		case SerialPortEvent.BI:
		case SerialPortEvent.OE:
		case SerialPortEvent.FE:
		case SerialPortEvent.PE:
		case SerialPortEvent.CD:
		case SerialPortEvent.CTS:
		case SerialPortEvent.DSR:
		case SerialPortEvent.RI:
		case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
			break;
		case SerialPortEvent.DATA_AVAILABLE:
			byte[] bufferLeitura = new byte[20];
			try 
			{
				while ( entrada.available() > 0 ) 
				{
					nodeBytes = entrada.read(bufferLeitura);
				}
				String Dadoslidos = new String(bufferLeitura);
				if (bufferLeitura.length == 0) 
				{
					Serial.status.append("Nada lido!"+"\n");
				} 
				else if (bufferLeitura.length == 1 )
				{
					Serial.status.append("Apenas um byte foi lido!"+"\n");
				} 
				else 
				{
					Serial.textAreaRecebidos.append(Dadoslidos+"\n");
				}
			} catch (Exception e) 
			{
				Serial.textAreaRecebidos.append("Erro durante a leitura: " + e +"\n");
			}
			Serial.textAreaRecebidos.append("n.o de bytes lidos : " + nodeBytes +"\n" );
		break;
	}
}
//função que fecha a conexão
public void FecharCom()
{

	try 
	{
		porta.close();
		Serial.status.append("CONEXAO FECHADA FIM..\n");
	}
	catch (Exception e) 
	{
		Serial.status.append("ERRO AO FECHAR. STATUS: " + e +"\n");
		System.exit(0);
	}
}
//Acessores
public String obterPorta()
{
	return Porta;
}
public int obterBaudrate()
{
	return baudrate;
}

}

N

Agora essa é a classe que vc vai rodar o programa, mas um detalhe, so que essa é um jdialog, e não meu Main. pois essa classe faz parte de um projeto que estou desenvolvendo.

import javax.swing.JPanel;

import java.awt.Frame;

import javax.swing.JDialog;

import java.awt.Dimension;

import javax.swing.JScrollPane;

import java.awt.Rectangle;

import javax.swing.JTextArea;

import javax.swing.BorderFactory;

import javax.swing.border.BevelBorder;

import javax.swing.border.TitledBorder;

import java.awt.SystemColor;

import java.awt.Font;

import java.awt.Point;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JButton;
import java.awt.GridLayout;

/**

  • Engenharia da Computação
  • Descrição:
  • Data: 25/08/2007
    */

/**

  • @author Nielsen

*/
public class Serial extends JDialog
{

private static final long serialVersionUID = 1L;
private JPanel jContentPane = null;
private JScrollPane jScrollPane = null;
private JScrollPane jScrollPane1 = null;
public static JTextArea textAreaEnviados = null;
public static JTextArea textAreaRecebidos = null;
private JButton btnRecebidos = null;
private JButton btnEnviados = null;
private JPanel panelStatus = null;
private JScrollPane jScrollPane2 = null;
public static JTextArea status = null;
/**
 * @param owner
 */
public Serial(Frame owner)
{
	super(owner);
	initialize();
}

/**
 * This method initializes this
 * 
 * @return void
 */
private void initialize()
{
	this.setSize(442, 378);
	this.setTitle("..:: Comunicação Serial ::..");
	this.setModal(true);
	this.setContentPane(getJContentPane());
}

/**
 * This method initializes jContentPane
 * 
 * @return javax.swing.JPanel
 */
private JPanel getJContentPane()
{
	if (jContentPane == null)
	{
		jContentPane = new JPanel();
		jContentPane.setLayout(null);
		jContentPane.add(getJScrollPane(), null);
		jContentPane.add(getJScrollPane1(), null);
		jContentPane.add(getBtnRecebidos(), null);
		jContentPane.add(getBtnEnviados(), null);
		jContentPane.add(getPanelStatus(), null);
	}
	return jContentPane;
}

/**
 * This method initializes jScrollPane	
 * 	
 * @return javax.swing.JScrollPane	
 */
private JScrollPane getJScrollPane()
{
	if (jScrollPane == null)
	{
		jScrollPane = new JScrollPane();
		jScrollPane.setBorder(BorderFactory.createTitledBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED), "Dados Recebidos", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font("Dialog", Font.BOLD, 12), SystemColor.activeCaption));
		jScrollPane.setLocation(new Point(6, 7));
		jScrollPane.setSize(new Dimension(422, 109));
		jScrollPane.setViewportView(getTextAreaRecebidos());
	}
	return jScrollPane;
}

/**
 * This method initializes jScrollPane1	
 * 	
 * @return javax.swing.JScrollPane	
 */
private JScrollPane getJScrollPane1()
{
	if (jScrollPane1 == null)
	{
		jScrollPane1 = new JScrollPane();
		jScrollPane1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED), "Dados Enviados", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font("Dialog", Font.BOLD, 12), SystemColor.activeCaption));
		jScrollPane1.setLocation(new Point(8, 146));
		jScrollPane1.setSize(new Dimension(421, 108));
		jScrollPane1.setViewportView(getTextAreaEnviados());
	}
	return jScrollPane1;
}

/**
 * This method initializes textAreaEnviados	
 * 	
 * @return javax.swing.JTextArea	
 */
private JTextArea getTextAreaEnviados()
{
	if (textAreaEnviados == null)
	{
		textAreaEnviados = new JTextArea();
		textAreaEnviados.setSize(new Dimension(333, 66));
	}
	return textAreaEnviados;
}

/**
 * This method initializes textAreaRecebidos	
 * 	
 * @return javax.swing.JTextArea	
 */
private JTextArea getTextAreaRecebidos()
{
	if (textAreaRecebidos == null)
	{
		textAreaRecebidos = new JTextArea();
		textAreaRecebidos.setSize(new Dimension(333, 66));
	}
	return textAreaRecebidos;
}

/**
 * This method initializes btnRecebidos	
 * 	
 * @return javax.swing.JButton	
 */
private JButton getBtnRecebidos()
{
	if (btnRecebidos == null)
	{
		btnRecebidos = new JButton();
		btnRecebidos.setBounds(new Rectangle(339, 120, 89, 19));
		btnRecebidos.setText("Receber");
		btnRecebidos.addActionListener(new ActionListener()
			{
				public void actionPerformed(ActionEvent e)
				{
					limpa();
					SerialCom sm = new SerialCom();
					if (sm.PortaExiste("COM1"))
					{
						textAreaRecebidos.append("Iniciando comunicação"+"\n");
						SComm scom = new SComm("COM1",9600,2000);
						scom.HabilitarLeitura();
						scom.ObterIdDaPorta();
						scom.AbrirPorta();
						scom.LerDados();
						textAreaRecebidos.append(scom.Dadoslidos+"\n");
						scom.FecharCom();
					}
				}
			}
		);
	}
	return btnRecebidos;
}

/**
 * This method initializes btnEnviados	
 * 	
 * @return javax.swing.JButton	
 */
private JButton getBtnEnviados()
{
	if (btnEnviados == null)
	{
		btnEnviados = new JButton();
		btnEnviados.setLocation(new Point(340, 258));
		btnEnviados.setText("Enviar");
		btnEnviados.setSize(new Dimension(89, 19));
		btnEnviados.addActionListener(new ActionListener()
			{
				public void actionPerformed(ActionEvent e)
				{
					limpa();
					
					SerialCom st = new SerialCom();
					if ( st.PortaExiste("COM1") == true) 
					{
						Serial.status.append("Iniciando Comunicação"+"\n");
						SComm sc = new SComm("COM1",9600,2000);
						sc.HabilitarEscrita();
						sc.ObterIdDaPorta();
						sc.AbrirPorta();
						sc.EnviarUmaString(textAreaEnviados.getText());
						sc.FecharCom();
					}
				}
			}
		);
	}
	return btnEnviados;
}

/**
 * This method initializes panelStatus	
 * 	
 * @return javax.swing.JPanel	
 */
private JPanel getPanelStatus()
{
	if (panelStatus == null)
	{
		GridLayout gridLayout = new GridLayout();
		gridLayout.setRows(1);
		panelStatus = new JPanel();
		panelStatus.setLayout(gridLayout);
		panelStatus.setBounds(new Rectangle(7, 288, 422, 56));
		panelStatus.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
		panelStatus.add(getJScrollPane2(), null);
	}
	return panelStatus;
}

/**
 * This method initializes jScrollPane2	
 * 	
 * @return javax.swing.JScrollPane	
 */
private JScrollPane getJScrollPane2()
{
	if (jScrollPane2 == null)
	{
		jScrollPane2 = new JScrollPane();
		jScrollPane2.setViewportView(getStatus());
	}
	return jScrollPane2;
}

/**
 * This method initializes status	
 * 	
 * @return javax.swing.JTextArea	
 */
private JTextArea getStatus()
{
	if (status == null)
	{
		status = new JTextArea();
		status.setFont(new Font("Dialog", Font.PLAIN, 10));
	}
	return status;
}
public void limpa()
{
	status.setText("");
}

} // @jve:decl-index=0:visual-constraint=“30,0”

N

Agora o proximo passo é sua configuração quero saber como vc configurou a com, os arquivos:win32com.dll, javax.comm.properties e comm.jar
Espero que lhe ajude!!!

J

Eu instalei a implementacao da sun em varios windows, porem no windows XP eu tive problemas
e entao resolvi usar o rxtx, e foi na primeira.

N

Rapaz eu estou usando no Xp SP2 eu não tenho nenhum problema funciona perfeito, o que eu estou fazendo o comunicando minha aplicação Java com um CLP (Controlador Lógico programavel).

L

eu copiei os arquivos
comm.jar
javax.comm.properties

para a pasta /lib no meu jdk

e para pasta /bin copiei
o win32com.dll

compilei estes exemplos que vc me passou, são os mesmos que estao na apostila que vc mandou.
mas quando ele é executado, ele nao exibe as portas disponiveis, não esta exibindo nada, nao da erro, mas nao exibe nada.
Vc sabe o que pode estar acontecendo.

Obs: eu peguei este exemplo abaixo, que so lista as portas :

package serial;

import java.util.Enumeration;

import java.util.HashMap;

import javax.comm.CommPortIdentifier;

public class MainClass

{

public MainClass()

{

int i =0;

Enumeration ListaDePortas;

ListaDePortas = CommPortIdentifier.getPortIdentifiers();
String portas[] = new String[10]; 

   while (ListaDePortas.hasMoreElements()) 
           { 
            CommPortIdentifier ips = (CommPortIdentifier)ListaDePortas.nextElement(); 
            portas[i] =(ips.getName()); 
            System.out.println("porta"); 
            System.out.println(portas[i]); 
            i++; 
     } 
    
--------------------------------------------------------------------

mas nao exibe nada.

=( ?

N

veja se vc ta enviando bytes para a porta, pegue um multimetro e coloque as pontas de prova no RS232:
3 - Vermelha e 5 preta (Enviando)
2 - Vermelha e 5 preta (Recebendo)

teste se vc (“Enviando”). a tensão fica em torno de -6v. Se essa tensão variar na hora que vc esta venviando byte é porque
a comunicação esta OK. Dai pode ser a rotina de Recebendo que ta errada. Se não der certo mande teu projeto pra mim que eu rodo na minha maquina
e vejo o problema aqui.

L

Esta dando este erro . Vc sabe o porque

java.lang.NoClassDefFoundError: serialteste/SimpleRead
Exception in thread “main”
Java Result: 1

B

Error loading SolarisSerial: java.lang.UnsatisfiedLinkError: no SolarisSerialParallel in java.library.path
Caught java.lang.UnsatisfiedLinkError: readRegistrySerial while loading driver com.sun.comm.SolarisDriver
Error loading SolarisSerial: java.lang.UnsatisfiedLinkError: no SolarisSerialParallel in java.library.path
Caught java.lang.UnsatisfiedLinkError: readRegistrySerial while loading driver com.sun.comm.SolarisDriver

De onde poderá vir este erro?? Já dei muitas voltas e não consigo resolver :frowning:

Alguem me ajude Please

Abraço e Muito Obrigado

Criado 30 de agosto de 2007
Ultima resposta 16 de jun. de 2008
Respostas 16
Participantes 5