alex1256
Messages postés10Date d'inscriptionlundi 16 février 2009StatutMembreDernière intervention23 mai 2012
-
7 janv. 2012 à 00:42
alex1256
Messages postés10Date d'inscriptionlundi 16 février 2009StatutMembreDernière intervention23 mai 2012
-
9 janv. 2012 à 04:40
Bonjour à tous,
je suis en train de développer un programme pour communiquer avec un capteur sans fil à l'aide d'un émetteur/récepteur en RS232 sur le schéma suivant:
Je réceptionne la bonne trame, seulement je reçois du décimal avec un signe négatif et à la conversion en hexa, cela ne donne pas la bonne trame.
Exemple de la trame reçu: -1 2 5 33 0 86 3 3 -1 2 17 48 11 25 16 48 5 39 -127 2 -128 1 79 79 -1 11 118 3
Convertie en hexa : ffffffff 2 11 30 b 19 10 30 5 27 ffffff81 2 ffffff80 1 4e 4f ffffffff ffffffd7 2c 3
La tram que je devrais obtenir: FF 02 11 30 0B 19 10 30 05 27 81 02 80 01 4E 4F FF D7 2C 03
Est-ce que'il y a une autre méthode pour la lecture des trames. C’est un problème de signed et unsigned char si je ne me trompe pas?
Voici mon code:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import javax.comm.CommPortIdentifier;
import javax.comm.SerialPort;
import com.sun.comm.Win32Driver;
/**
*/
public class RS232
{
private static final String appName = "Module wavenis"; // Application name that request opening the serial port.
private static final int openTimeOut = 5000; // 5seconds.
private CommPortIdentifier portId;
private DataInputStream in;
private DataOutputStream out;
private SerialPort serialPort;
//static String messageAenvoyer = "0B200B191030052701";
private static final int databits = SerialPort.DATABITS_8; // RS-232 configuration
private static final int stopbit = SerialPort.STOPBITS_1; // RS-232 configuration
private static final int parity = SerialPort.PARITY_NONE; // RS-232 configuration
private static final int flowctrl_out = SerialPort.FLOWCONTROL_NONE;
private static final int flowctrl_in = SerialPort.FLOWCONTROL_NONE;
private static final int baudrate = 9600; // RS-232 configuration
/**
* Constructor
*/
public RS232(String com, boolean listAvailablePorts)
{
Win32Driver w32Driver = new Win32Driver();
w32Driver.initialize();
try
{
// Listing or not available serial and parallel ports found...
if(listAvailablePorts) System.out.println(availableSerialCommPorts());//on affiche la liste de tous les ports dispo
// Opening com port...
System.out.println("Trying to open serial port '" + com + "'...");
portId = CommPortIdentifier.getPortIdentifier(com);//obtenir l'identifiant du port serie
serialPort = (SerialPort) portId.open(appName, openTimeOut);//on ouvre le port correspondant puis on le caste
System.out.println("Successfully opened serial port '" + serialPort.getName() + "'!");
// Setting the serial connection as requested...
serialPort.setSerialPortParams(baudrate, databits, stopbit, parity);//configure les params du port serie
serialPort.setFlowControlMode(flowctrl_in);
serialPort.setFlowControlMode(flowctrl_out);
in = new DataInputStream(serialPort.getInputStream());//initialisation du port d'entrée
out = new DataOutputStream(serialPort.getOutputStream());//initialisation du port de sortie
}
catch(Exception e)
{
System.out.println(e.getMessage());
System.exit(1); // sortie de l'appli
}
}
public void sendACK()
{
try
{
int data [] = {0xFF,0x02,0x04,0x56,0x02,0x03};
for(int i=0; i< data.length; i++)
{
out.writeInt(data[i]);
}
out.flush();//on vide le buffer
System.out.println("settings OK\n");
}
catch(Exception e)
{
System.out.println("Is port available and opened?\n"+e.getMessage());
System.exit(1);
}
}
/**
* Send a TRAM
**/
public void sendTram()
{
try
{
int data [] = {0xFF,0x02,0x0B,0x20,0x0B,0x19,0x10,0x30,0x05,0x27,0x01,0xC1,0xB0,0x03};
System.out.print("\nMessage envoyé: ");
for(int j=0; j<data.length; j++){
out.write(data[j]);
System.out.print(Integer.toHexString(data[j])+ " ");
}
out.flush();//on vide le buffer
System.out.println("msg OK");
}
catch(Exception e)
{
System.out.println("Is port available and opened?\n"+e.getMessage());
System.exit(1);
}
}
/**
* Close serial connection
*/
public void closeConnection()
{
try
{
in.close();
out.close();
}
catch (IOException e)
{
System.out.println("Cannot open and / or close serial connection!Details:\n"+e.getMessage());
System.exit(1);
}
}
/**
* List all the available serial and parallel communication ports
* @return the list of all available serial and parallel communication ports.
*/
@SuppressWarnings("unchecked")
public String availableSerialCommPorts()
{
System.err.println("Searching...");
String list = "";
Enumeration portList = CommPortIdentifier.getPortIdentifiers();
if (portList == null)// port(s) not found
{
System.err.println("No communication port detected!"); // notify it in the console
return null;
}
else // port(s) found
{
System.err.println("Detected serial communication ports !\nFound:\n");
while (portList.hasMoreElements())
{
portId = (CommPortIdentifier) portList.nextElement(); // get the found port
list += portId.getName()+"\n"; // add it in the String list
}
return list;// Return the full list
}
}
public byte[] readBytes() {
try {
byte buffer[] = new byte[25];
int n=0, offset=0, i=0;
while(true) {
i = in.available();//retourne le nb d'octets qui peut être lus
System.out.println("\noctets disponibles : " + i);
n = in.read(buffer, offset, i); //nb d'octets actuellement lus
if (n<=0 || n == i) break;
offset+=n;
}
return buffer;
} catch (IOException e) {
return null;
}
}
/**
*Main function
* @throws InterruptedException
*/
public static void main(String args[]) throws InterruptedException
{
RS232 donnee = new RS232("COM1", true); // Liste les ports et try une connection au port "COM1".
//Trame de commande
donnee.sendTram();
Thread.sleep(30);
byte[] buffer = donnee.readBytes();
for (int i =0; i<buffer.length; i++)
{
System.out.print(Integer.toHexString(buffer[i])+ " ");
}
//Envoi du ack
donnee.sendACK();
//Réception de la trame de donnée
Thread.sleep(3000);//sleep for 100 ms
byte[] buffer4 = donnee.readBytes();
for (int i =0; i<buffer4.length; i++)
{
System.out.print(Integer.toHexString(buffer4[i])+ " ");
}
donnee.sendACK();
donnee.closeConnection();
}
}
Ma méthode de lecture est assez statistique, pour une lecture événementielle, dois-je utiliser des threads?
alex1256
Messages postés10Date d'inscriptionlundi 16 février 2009StatutMembreDernière intervention23 mai 2012 9 janv. 2012 à 04:40
J'ai resolu une partie de mon problème en utilisant
String.format("%02x",buffer2)
A la place de:
Integer.toString((buffer2),16)
Par contre comment je peux faire poure réceptionner les données au moment ou elle arrive au récepteur et ce de facon continu?
J'ai pensé à une condition
ports = CommPortIdentifier.getPortIdentifiers();
while (ports.hasMoreElements()) {
if(in.available()>=0)
{...
}
}
Ou un threat contenant une boucle infini de detection?