Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.daryl.ihm;
- import gnu.io.*;
- import java.awt.Color;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.util.Enumeration;
- import java.util.HashMap;
- public class Communicator {
- //L'interface principale
- Interface window = null;
- //Binding object
- KeybindingController keyController = null;
- //Contient la liste des ports disponibles
- private Enumeration<CommPortIdentifier> ports = null;
- //Map le nom du port au CommPortIdentifiers
- private HashMap<String, CommPortIdentifier> portMap = new HashMap<String, CommPortIdentifier>();
- //Contient le port ouvert
- private CommPortIdentifier selectedPortIdentifier = null;
- private SerialPort serialPort = null;
- //input et output streams pour envoyer et recevoir les données
- private InputStream input = null;
- private OutputStream output = null;
- //Pour connaitre si on est connecté ou non
- private boolean bConnected = false;
- //timeout pour la connection avec le port
- final static int TIMEOUT = 2000;
- //Le baud rate pour le port com
- final static int BAUDRATE = 115200;
- //Pour ne pas prendre les 150 1er frames
- final static int NOTTAKE = 150;
- //Tag de début et fin
- final static String SERIAL_START_FLAG = "~";
- final static String SERIAL_END_FLAG = "$";
- final static String NEW_LINE = "\n";
- // Le compteur de frame
- private int frameInnerCounter = 0;
- private String serialData[] = new String[10];
- private boolean readFrame = false;
- private int serialFlag = 0;
- private int sizeOfData = 0;
- private int totalFrame = 0;
- //String pour le logger
- String logText = "";
- //Thread de lecture
- Thread serialReader = null;
- public Communicator(Interface window)
- {
- this.window = window;
- keyController = new KeybindingController(window);
- }
- //On recherche les ports COM disponibles et on met à jour l'interface
- @SuppressWarnings("unchecked")
- public void searchForPorts()
- {
- ports = CommPortIdentifier.getPortIdentifiers();
- while (ports.hasMoreElements())
- {
- CommPortIdentifier curPort = ports.nextElement();
- if (curPort.getPortType() == CommPortIdentifier.PORT_SERIAL)
- {
- window.getjComboBoxListePort().addItem(curPort.getName());
- portMap.put(curPort.getName(), curPort);
- }
- }
- }
- //Connection au port sélectionné dans la cbBox
- //Le port COM connecté est stocké dans commPort, sinon une exception est levée
- public void connect()
- {
- String selectedPort = (String)window.getjComboBoxListePort().getSelectedItem();
- selectedPortIdentifier = portMap.get(selectedPort);
- CommPort commPort = null;
- try
- {
- //Retourne l'objet de type CommPort
- commPort = selectedPortIdentifier.open("TigerControlPanel", TIMEOUT);
- //On cast l'objet CommPort en objet SerialPort
- serialPort = (SerialPort)commPort;
- //On définie les paramêtres du port
- serialPort.setSerialPortParams(BAUDRATE,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
- //for controlling GUI elements
- setConnected(true);
- //On log
- logText = selectedPort + " ouvert avec succès.";
- window.getjTextAreaLogInput().setForeground(Color.black);
- window.getjTextAreaLogInput().append(logText + "\n");
- }
- catch (PortInUseException e)
- {
- logText = selectedPort + " déjà en cours d'utilisation. (" + e.toString() + ")";
- window.getjTextAreaLogInput().setForeground(Color.RED);
- window.getjTextAreaLogInput().append(logText + "\n");
- }
- catch (Exception e)
- {
- logText = "Impossible d'ouvrir de port " + selectedPort + "(" + e.toString() + ")";
- window.getjTextAreaLogInput().append(logText + "\n");
- window.getjTextAreaLogInput().setForeground(Color.RED);
- }
- }
- //Ouverture des streams input et output
- //Initialisation des streams intput et output utilisées pour la communication
- public boolean initIOStream()
- {
- //Pour savoir si l'ouverture de la stream est ok ou non
- boolean successful = false;
- try {
- input = serialPort.getInputStream();
- output = serialPort.getOutputStream();
- successful = true;
- return successful;
- }
- catch (IOException e) {
- logText = "Impossible d'ouvrir les streams I/O. (" + e.toString() + ")";
- window.getjTextAreaLogInput().setForeground(Color.red);
- window.getjTextAreaLogInput().append(logText + "\n");
- return successful;
- }
- }
- //On met en place l'event listener permettant de savoir si il y a une donnée à lire
- public void initListener()
- {
- totalFrame = 0;
- frameInnerCounter = 0;
- serialData = new String[10];
- readFrame = false;
- serialFlag = 0;
- sizeOfData = 0;
- totalFrame = 0;
- // On initialise et lance le thread de lecture continue
- serialReader = new Thread(new SerialReader(this));
- serialReader.start();
- }
- //Permet de déconnecter le port COM
- @SuppressWarnings("deprecation")
- public void disconnect()
- {
- try
- {
- //On stop de le thread et ferme le port COM
- serialReader.stop();
- serialPort.close();
- input.close();
- output.close();
- setConnected(false);
- logText = "Déconnexion.";
- window.getjTextAreaLogInput().setForeground(Color.red);
- window.getjTextAreaLogInput().append(logText + "\n");
- }
- catch (Exception e)
- {
- logText = "Impossible de fermer le port " + serialPort.getName() + "(" + e.toString() + ")";
- window.getjTextAreaLogInput().setForeground(Color.red);
- window.getjTextAreaLogInput().append(logText + "\n");
- }
- }
- final public boolean getConnected()
- {
- return bConnected;
- }
- public void setConnected(boolean bConnected)
- {
- this.bConnected = bConnected;
- }
- public static class SerialReader implements Runnable
- {
- Communicator com;
- public SerialReader (Communicator com)
- {
- this.com = com;
- }
- public void run ()
- {
- //On récupère 1 byte
- byte[] buffer = new byte[1];
- int len = -1;
- try
- {
- //Si il y a bien quelque chose
- while ( ( len = com.input.read(buffer)) > -1 )
- {
- com.totalFrame++;
- // On ne prend pas les X première frames pour éviter les données parasites du début de trame
- if (com.totalFrame>NOTTAKE) {
- //On récupère la donnée
- String singleData = new String(buffer,0,len);
- //Si on a un message complet on traite le message via le controler
- if(com.serialFlag==1) {
- com.serialFlag=0;
- com.keyController.bindKeys(com.serialData, com.sizeOfData);
- }
- //Si != de saut de line on traite
- if (!singleData.equals(NEW_LINE))
- {
- /* S'il s'agit de la 1ére frame 0x7E (frame de début), on réinitialise à 0 la var frameInnerCounter
- * On positionne la var readFrame à true
- */
- if(singleData.equals(SERIAL_START_FLAG)){
- com.frameInnerCounter=0;
- com.serialData[com.frameInnerCounter]=singleData;
- com.readFrame=true;
- }
- /* Si on a déjà passé la frame de début on
- * incrémente la var frameInnerCounter et on sauvegarde les données
- */
- else if(com.readFrame==true){
- com.frameInnerCounter++;
- com.serialData[com.frameInnerCounter]=singleData;
- /* S'il s'agit de la dernière frame 0xE7 (frame de fin),
- * On positionne la var readFrame à false
- * On positionne la var serialFlag à 1 pour indiquer qu'il y a un message à traiter
- * On stock le nombre de frame réelle à traiter dans la var sizeOfData
- */
- if(singleData.equals(SERIAL_END_FLAG)) {
- com.readFrame=false;
- com.serialFlag=1;
- com.sizeOfData=com.frameInnerCounter+1;
- }
- }
- }
- else //On saute une ligne
- {
- com.window.getjTextAreaLogInput().append("\n");
- com.window.getjTextAreaLogInput().setCaretPosition(com.window.getjTextAreaLogInput().getText().length());
- }
- }
- }
- }
- catch ( IOException e )
- {
- com.logText = "Erreur dans la lecture de la stream " + "(" + e.toString() + ")";
- com.window.getjTextAreaLogInput().setForeground(Color.red);
- com.window.getjTextAreaLogInput().append(com.logText + "\n");
- }
- }
- }
- //Call lorsque l'on a une donnée à envoyer
- public void writeData(char flag, String valeur)
- {
- try
- {
- if (valeur.length()==1) {
- valeur = "000"+ valeur;
- } else if (valeur.length()==2) {
- valeur = "00"+ valeur;
- } else if (valeur.length()==3) {
- valeur = "0"+ valeur;
- }
- char[] valeurChar = valeur.toCharArray();
- //On envoi le message
- char a = '~';
- int c = a;
- this.output.write(c);
- output.flush();
- a = flag;
- c = a;
- this.output.write(c);
- output.flush();
- a = valeurChar[0];
- c = a;
- this.output.write(c);
- output.flush();
- a = valeurChar[1];
- c = a;
- this.output.write(c);
- output.flush();
- a = valeurChar[2];
- c = a;
- this.output.write(c);
- output.flush();
- a = valeurChar[3];
- c = a;
- this.output.write(c);
- output.flush();
- a = '$';
- c = a;
- this.output.write(c);
- output.flush();
- window.getjTextAreaLogOutput().append("Send data: " + SERIAL_START_FLAG + flag + valeur + SERIAL_END_FLAG + "\n");
- window.getjTextAreaLogOutput().setCaretPosition(window.getjTextAreaLogOutput().getText().length());
- }
- catch (Exception e)
- {
- logText = "Impossible d'écrire la donnée. (" + e.toString() + ")";
- window.getjTextAreaLogInput().setForeground(Color.red);
- window.getjTextAreaLogInput().append(logText + "\n");
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement