Advertisement
Guest User

Communicator http://darylrobotproject.wordpress.com/

a guest
Oct 1st, 2012
1,750
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 11.44 KB | None | 0 0
  1. package com.daryl.ihm;
  2.  
  3. import gnu.io.*;
  4. import java.awt.Color;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.OutputStream;
  8. import java.util.Enumeration;
  9. import java.util.HashMap;
  10.  
  11. public class Communicator {
  12.    
  13.     //L'interface principale
  14.     Interface window = null;
  15.    
  16.     //Binding object
  17.     KeybindingController keyController = null;
  18.  
  19.     //Contient la liste des ports disponibles
  20.     private Enumeration<CommPortIdentifier> ports = null;
  21.     //Map le nom du port au CommPortIdentifiers
  22.     private HashMap<String, CommPortIdentifier> portMap = new HashMap<String, CommPortIdentifier>();
  23.  
  24.     //Contient le port ouvert
  25.     private CommPortIdentifier selectedPortIdentifier = null;
  26.     private SerialPort serialPort = null;
  27.  
  28.     //input et output streams pour envoyer et recevoir les données
  29.     private InputStream input = null;
  30.     private OutputStream output = null;
  31.  
  32.     //Pour connaitre si on est connecté ou non
  33.     private boolean bConnected = false;
  34.  
  35.     //timeout pour la connection avec le port
  36.     final static int TIMEOUT = 2000;
  37.    
  38.     //Le baud rate pour le port com
  39.     final static int BAUDRATE = 115200;
  40.    
  41.     //Pour ne pas prendre les 150 1er frames
  42.     final static int NOTTAKE = 150;
  43.  
  44.     //Tag de début et fin
  45.     final static String SERIAL_START_FLAG = "~";
  46.     final static String SERIAL_END_FLAG = "$";
  47.     final static String NEW_LINE = "\n";
  48.    
  49.     // Le compteur de frame
  50.     private int frameInnerCounter = 0;
  51.     private String serialData[] = new String[10];
  52.     private boolean readFrame = false;
  53.     private int serialFlag = 0;
  54.     private int sizeOfData = 0;
  55.     private int totalFrame = 0;
  56.  
  57.     //String pour le logger
  58.     String logText = "";
  59.    
  60.     //Thread de lecture
  61.     Thread serialReader = null;
  62.  
  63.     public Communicator(Interface window)
  64.     {
  65.         this.window = window;
  66.         keyController = new KeybindingController(window);
  67.        
  68.     }
  69.  
  70.     //On recherche les ports COM disponibles et on met à jour l'interface
  71.     @SuppressWarnings("unchecked")
  72.     public void searchForPorts()
  73.     {
  74.         ports = CommPortIdentifier.getPortIdentifiers();
  75.  
  76.         while (ports.hasMoreElements())
  77.         {
  78.             CommPortIdentifier curPort = ports.nextElement();
  79.  
  80.             if (curPort.getPortType() == CommPortIdentifier.PORT_SERIAL)
  81.             {
  82.                 window.getjComboBoxListePort().addItem(curPort.getName());
  83.                 portMap.put(curPort.getName(), curPort);
  84.             }
  85.         }
  86.     }
  87.  
  88.     //Connection au port sélectionné dans la cbBox
  89.     //Le port COM connecté est stocké dans commPort, sinon une exception est levée
  90.     public void connect()
  91.     {
  92.         String selectedPort = (String)window.getjComboBoxListePort().getSelectedItem();
  93.         selectedPortIdentifier = portMap.get(selectedPort);
  94.         CommPort commPort = null;
  95.  
  96.         try
  97.         {
  98.             //Retourne l'objet de type CommPort
  99.             commPort = selectedPortIdentifier.open("TigerControlPanel", TIMEOUT);
  100.             //On cast l'objet CommPort en objet SerialPort
  101.             serialPort = (SerialPort)commPort;
  102.             //On définie les paramêtres du port
  103.             serialPort.setSerialPortParams(BAUDRATE,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
  104.  
  105.             //for controlling GUI elements
  106.             setConnected(true);
  107.  
  108.             //On log
  109.             logText = selectedPort + " ouvert avec succès.";
  110.             window.getjTextAreaLogInput().setForeground(Color.black);
  111.             window.getjTextAreaLogInput().append(logText + "\n");
  112.  
  113.  
  114.         }
  115.         catch (PortInUseException e)
  116.         {
  117.             logText = selectedPort + " déjà en cours d'utilisation. (" + e.toString() + ")";
  118.            
  119.             window.getjTextAreaLogInput().setForeground(Color.RED);
  120.             window.getjTextAreaLogInput().append(logText + "\n");
  121.         }
  122.         catch (Exception e)
  123.         {
  124.             logText = "Impossible d'ouvrir de port " + selectedPort + "(" + e.toString() + ")";
  125.             window.getjTextAreaLogInput().append(logText + "\n");
  126.             window.getjTextAreaLogInput().setForeground(Color.RED);
  127.         }
  128.     }
  129.  
  130.     //Ouverture des streams input et output
  131.     //Initialisation des streams intput et output utilisées pour la communication
  132.     public boolean initIOStream()
  133.     {
  134.         //Pour savoir si l'ouverture de la stream est ok ou non
  135.         boolean successful = false;
  136.  
  137.         try {
  138.            
  139.             input = serialPort.getInputStream();
  140.             output = serialPort.getOutputStream();
  141.            
  142.             successful = true;
  143.             return successful;
  144.         }
  145.         catch (IOException e) {
  146.             logText = "Impossible d'ouvrir les streams I/O. (" + e.toString() + ")";
  147.             window.getjTextAreaLogInput().setForeground(Color.red);
  148.             window.getjTextAreaLogInput().append(logText + "\n");
  149.             return successful;
  150.         }
  151.     }
  152.  
  153.     //On met en place l'event listener permettant de savoir si il y a une donnée à lire
  154.     public void initListener()
  155.     {
  156.  
  157.             totalFrame = 0;
  158.             frameInnerCounter = 0;
  159.             serialData = new String[10];
  160.             readFrame = false;
  161.             serialFlag = 0;
  162.             sizeOfData = 0;
  163.             totalFrame = 0;
  164.             // On initialise et lance le thread de lecture continue
  165.             serialReader = new Thread(new SerialReader(this));
  166.             serialReader.start();
  167.            
  168.     }
  169.  
  170.     //Permet de déconnecter le port COM
  171.     @SuppressWarnings("deprecation")
  172.     public void disconnect()
  173.     {
  174.         try
  175.         {
  176.             //On stop de le thread et ferme le port COM
  177.             serialReader.stop();
  178.             serialPort.close();
  179.             input.close();
  180.             output.close();
  181.             setConnected(false);
  182.  
  183.             logText = "Déconnexion.";
  184.             window.getjTextAreaLogInput().setForeground(Color.red);
  185.             window.getjTextAreaLogInput().append(logText + "\n");
  186.         }
  187.         catch (Exception e)
  188.         {
  189.             logText = "Impossible de fermer le port " + serialPort.getName() + "(" + e.toString() + ")";
  190.             window.getjTextAreaLogInput().setForeground(Color.red);
  191.             window.getjTextAreaLogInput().append(logText + "\n");
  192.         }
  193.     }
  194.  
  195.     final public boolean getConnected()
  196.     {
  197.         return bConnected;
  198.     }
  199.  
  200.     public void setConnected(boolean bConnected)
  201.     {
  202.         this.bConnected = bConnected;
  203.     }
  204.    
  205.     public static class SerialReader implements Runnable
  206.     {
  207.         Communicator com;
  208.        
  209.         public SerialReader (Communicator com)
  210.         {
  211.             this.com = com;
  212.         }
  213.        
  214.         public void run ()
  215.         {
  216.             //On récupère 1 byte
  217.             byte[] buffer = new byte[1];
  218.             int len = -1;
  219.            
  220.             try
  221.             {
  222.                 //Si il y a bien quelque chose
  223.                 while ( ( len = com.input.read(buffer)) > -1 )
  224.                 {
  225.                    
  226.                     com.totalFrame++;
  227.  
  228.                     // On ne prend pas les X première frames pour éviter les données parasites du début de trame
  229.                     if (com.totalFrame>NOTTAKE) {
  230.  
  231.                         //On récupère la donnée
  232.                         String singleData = new String(buffer,0,len);
  233.  
  234.                         //Si on a un message complet on traite le message via le controler
  235.                         if(com.serialFlag==1) {  
  236.  
  237.                             com.serialFlag=0;
  238.                             com.keyController.bindKeys(com.serialData, com.sizeOfData);
  239.  
  240.                         }
  241.  
  242.                         //Si != de saut de line on traite
  243.                         if (!singleData.equals(NEW_LINE))
  244.                         {
  245.  
  246.                             /* S'il s'agit de la 1ére frame 0x7E (frame de début), on réinitialise à 0 la var frameInnerCounter
  247.                              * On positionne la var readFrame à true
  248.                              */
  249.                            
  250.                             if(singleData.equals(SERIAL_START_FLAG)){        
  251.                                 com.frameInnerCounter=0;
  252.                                 com.serialData[com.frameInnerCounter]=singleData;
  253.                                 com.readFrame=true;
  254.                             }
  255.  
  256.                             /* Si on a déjà passé la frame de début on
  257.                              * incrémente la var frameInnerCounter et on sauvegarde les données
  258.                              */
  259.                             else if(com.readFrame==true){
  260.                                 com.frameInnerCounter++;
  261.                                 com.serialData[com.frameInnerCounter]=singleData;
  262.  
  263.                                 /* S'il s'agit de la dernière frame 0xE7 (frame de fin),
  264.                                  * On positionne la var readFrame à false
  265.                                  * On positionne la var serialFlag à 1 pour indiquer qu'il y a un message à traiter
  266.                                  * On stock le nombre de frame réelle à traiter dans la var sizeOfData
  267.                                  */
  268.                                 if(singleData.equals(SERIAL_END_FLAG)) {
  269.                                     com.readFrame=false;
  270.                                     com.serialFlag=1;
  271.                                     com.sizeOfData=com.frameInnerCounter+1;
  272.                                 }
  273.  
  274.                             }
  275.  
  276.                         }
  277.                         else //On saute une ligne
  278.                         {
  279.                             com.window.getjTextAreaLogInput().append("\n");
  280.                             com.window.getjTextAreaLogInput().setCaretPosition(com.window.getjTextAreaLogInput().getText().length());
  281.                         }
  282.                     }
  283.                    
  284.                 }
  285.             }
  286.             catch ( IOException e )
  287.             {
  288.                 com.logText = "Erreur dans la lecture de la stream " + "(" + e.toString() + ")";
  289.                 com.window.getjTextAreaLogInput().setForeground(Color.red);
  290.                 com.window.getjTextAreaLogInput().append(com.logText + "\n");
  291.             }            
  292.         }
  293.     }
  294.  
  295.     //Call lorsque l'on a une donnée à envoyer
  296.     public void writeData(char flag, String valeur)
  297.     {
  298.         try
  299.         {      
  300.             if (valeur.length()==1) {
  301.                 valeur = "000"+ valeur;
  302.             } else if (valeur.length()==2) {
  303.                 valeur = "00"+ valeur;
  304.             } else if (valeur.length()==3) {
  305.                 valeur = "0"+ valeur;
  306.             }
  307.            
  308.             char[] valeurChar = valeur.toCharArray();
  309.            
  310.             //On envoi le message
  311.             char a = '~';
  312.             int c = a;
  313.             this.output.write(c);
  314.             output.flush();
  315.             a = flag;
  316.             c = a;
  317.             this.output.write(c);
  318.             output.flush();
  319.             a = valeurChar[0];
  320.             c = a;
  321.             this.output.write(c);
  322.             output.flush();
  323.             a = valeurChar[1];
  324.             c = a;
  325.             this.output.write(c);
  326.             output.flush();
  327.             a = valeurChar[2];
  328.             c = a;
  329.             this.output.write(c);
  330.             output.flush();
  331.             a = valeurChar[3];
  332.             c = a;
  333.             this.output.write(c);
  334.             output.flush();
  335.             a = '$';
  336.             c = a;
  337.             this.output.write(c);
  338.             output.flush();
  339.            
  340.             window.getjTextAreaLogOutput().append("Send data: " + SERIAL_START_FLAG + flag + valeur + SERIAL_END_FLAG + "\n");
  341.             window.getjTextAreaLogOutput().setCaretPosition(window.getjTextAreaLogOutput().getText().length());
  342.            
  343.         }
  344.         catch (Exception e)
  345.         {
  346.             logText = "Impossible d'écrire la donnée. (" + e.toString() + ")";
  347.             window.getjTextAreaLogInput().setForeground(Color.red);
  348.             window.getjTextAreaLogInput().append(logText + "\n");
  349.             e.printStackTrace();
  350.         }
  351.     }
  352.    
  353. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement