IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Entrée/Sortie Java Discussion :

Communication port série


Sujet :

Entrée/Sortie Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre à l'essai
    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Juin 2008
    Messages
    3
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Bénin

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 3
    Par défaut Communication port série
    Bonjour a la communauté java

    je suis nouveau sur le forum

    aussi j'ai pas encore de solide bases en java mais je me debrouille bien dans les developpement d'application

    j'ai un projet en cour au service actuellement qui concerne la communication sur les ports serie*

    je ne saurait bien vous expliquer ce que je dois faire je vais donc vous presenter un document qui resume ce qu'il y a faire
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    package Formularios;
     
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javafx.application.Platform;
    import javafx.collections.FXCollections;
    import javafx.collections.ObservableList;
    import javax.swing.Action;
    import javax.swing.DefaultComboBoxModel;
    import javax.swing.ImageIcon;
    import javax.swing.JOptionPane;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    import jssc.SerialPort;
    import static jssc.SerialPort.MASK_RXCHAR;
    import jssc.SerialPortEvent;
    import jssc.SerialPortException;
    import jssc.SerialPortList;
     
    /**
     *
     * @author Onorio con hache
     */
    public class Principal extends javax.swing.JFrame {
     
        //Variables globales
        SerialPort sp = null;
        ObservableList<String> puertosDisponibles;
        int idPuerto;
        String nombrePuerto;
        int i;
     
        private void detectarPuertos(){
            // Cette fonction nous permet de détecter les ports COM disponibles sur notre PC
             // à ajouter plus tard à notre jListBox
             // Remarque: les ports COM peuvent être créés avec EltimaSerialPort
            puertosDisponibles = FXCollections.observableArrayList();
            String[] serialPortNames = SerialPortList.getPortNames();
            for(String name: serialPortNames){
                System.out.println(name);
                puertosDisponibles.add(name);
                listaPuertos.addItem(name);// Ici, nous ajoutons les éléments à notre jListBox
            }
        }
     
        public Principal() {
            initComponents();
            personalizarFormulario();
            detectarPuertos();
        }
     
        /**
         * This method is called from within the constructor to initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is always
         * regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
     
            jScrollPane1 = new javax.swing.JScrollPane();
            jTextArea1 = new javax.swing.JTextArea();
            listaPuertos = new javax.swing.JComboBox<>();
            botonConDes = new javax.swing.JButton();
            tx = new javax.swing.JTextField();
            botonEnviar = new javax.swing.JButton();
            jScrollPane2 = new javax.swing.JScrollPane();
            rx = new javax.swing.JTextArea();
     
            jTextArea1.setColumns(20);
            jTextArea1.setRows(5);
            jScrollPane1.setViewportView(jTextArea1);
     
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Comunicación serial");
     
            botonConDes.setText("Conectar");
            botonConDes.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    botonConDesActionPerformed(evt);
                }
            });
     
            botonEnviar.setText("Enviar");
            botonEnviar.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    botonEnviarActionPerformed(evt);
                }
            });
     
            rx.setColumns(20);
            rx.setRows(5);
            jScrollPane2.setViewportView(rx);
     
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(listaPuertos, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(botonConDes))
                        .addComponent(jScrollPane2)
                        .addComponent(tx))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(botonEnviar)
                    .addContainerGap(28, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(listaPuertos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(botonConDes))
                    .addGap(2, 2, 2)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(botonEnviar)
                        .addComponent(tx, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addContainerGap(24, Short.MAX_VALUE))
            );
     
            pack();
        }// </editor-fold>                        
     
     
        private void botonConDesActionPerformed(java.awt.event.ActionEvent evt) {                                            
     
            // Dans le cas de ce bouton, nous nous connectons au port COM sélectionné
            switch(botonConDes.getText()){
                case "Conectar":
                    idPuerto=listaPuertos.getSelectedIndex()+1;
                    nombrePuerto="COM"+String.valueOf(idPuerto);  
                    System.out.println(nombrePuerto);
                    boolean conn=ConectarHardware(nombrePuerto);// Si la variable "conn = true" est due au fait que la connexion a été établie
     
                    if (conn==true) {
                        botonConDes.setText("Desconectar");
                        listaPuertos.setEnabled(false);
     
                    } else {
                        botonConDes.setText("Conectar");
                        listaPuertos.setEnabled(true);
                    }
                    break;                
                case "Desconectar":
                    desconectar();
                    botonConDes.setText("Conectar");
                    listaPuertos.setEnabled(true);
                    break;
            }
        }                                           
     
        private void botonEnviarActionPerformed(java.awt.event.ActionEvent evt) {                                            
            // TODO add your handling code here:
            // Dans cet événement, nous écrivons sur le port série
            if(sp != null){// Nous vérifions que nous sommes connectés au port série
                try {
                    sp.writeString(tx.getText());// Ici, nous écrivons sur le port série
                     // Nous envoyons ce qu'il y a dans le jTextField, qui s'appelle tx
     
                } catch (SerialPortException ex) {
                    Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
                }
                        System.out.println("Se ha enviado el dato "+ tx.getText());
     
                    }else{
                        System.out.println("arduinoPort not connected!");
                    }
        }                                           
     
     
        public boolean ConectarHardware(String port){
            // C'est la fonction qui nous permet de nous connecter au port série,
             // pour cela, nous devons envoyer le nom du port sélectionné
            System.out.println("Conectado a el puerto:"+ " " + port);        
            boolean success = false;
     
            // Ici, nous configurons les paramètres du port série
            SerialPort serialPort = new SerialPort(port);
            try {
                serialPort.openPort();
                serialPort.setParams(
                        SerialPort.BAUDRATE_9600,
                        SerialPort.DATABITS_8,
                        SerialPort.STOPBITS_1,
                        SerialPort.PARITY_NONE);
                serialPort.setEventsMask(MASK_RXCHAR);
                serialPort.addEventListener((SerialPortEvent serialPortEvent) -> {
                    if(serialPortEvent.isRXCHAR()){
                        try {
                            // Ici, nous lisons le port COM
                            String st= serialPort.readString();
                                rx.setText(st);
                        } catch (SerialPortException ex) {
                            Logger.getLogger(Principal.class.getName())
                                    .log(Level.SEVERE, null, ex);
                            System.out.println("No se pudo recibir el dato");
                        }
                    }
                });
     
                sp = serialPort;
                success = true;
            } catch (SerialPortException ex) {
                Logger.getLogger(Principal.class.getName())
                        .log(Level.SEVERE, null, ex);
                System.out.println("Error al tratar de conectarse al puerto"+ port);
                JOptionPane.showMessageDialog(null,"No se pudo realizar la conexión, por favor seleccione otro puerto:"+ " " + port );
            }
            return success;
        }
     
        public void desconectar(){
            // Cette fonction est ce que nous utilisons pour nous déconnecter du port COM
            if(sp != null){// Nous vérifions si nous sommes connectés
                try {
                    sp.removeEventListener();
                    if(sp.isOpened()){
                        sp.closePort();
            System.out.println("Se ha desconectaro del puerto exitosamente");
                    }
     
                    sp = null;
                } catch (SerialPortException ex) {
                    Logger.getLogger(Principal.class.getName())
                            .log(Level.SEVERE, null, ex);
                }
            }
        }
     
        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
     
            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Principal().setVisible(true);
                }
            });
        }
     
        // Variables declaration - do not modify                     
        private javax.swing.JButton botonConDes;
        private javax.swing.JButton botonEnviar;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JScrollPane jScrollPane2;
        private javax.swing.JTextArea jTextArea1;
        private javax.swing.JComboBox<String> listaPuertos;
        private javax.swing.JTextArea rx;
        private javax.swing.JTextField tx;
        // End of variables declaration                   
     
        private void personalizarFormulario() {
        this.setLocationRelativeTo(null);
            setIconImage(new ImageIcon(getClass().getResource("/Recursos/usb.png")).getImage());
            try {
                //com.sun.java.swing.plaf.windows.WindowsLookAndFeel
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                SwingUtilities.updateComponentTreeUI(this);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
            } catch (UnsupportedLookAndFeelException ex) {
                Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    voila ce que j'ai deja reussir à faire
    je ne sais pas comment procéder pour faire ca
    aidez moi svp
    Images attachées Images attachées

  2. #2
    Membre Expert
    Avatar de yotta
    Homme Profil pro
    Technicien maintenance
    Inscrit en
    Septembre 2006
    Messages
    1 088
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 55
    Localisation : France, Bas Rhin (Alsace)

    Informations professionnelles :
    Activité : Technicien maintenance
    Secteur : Industrie

    Informations forums :
    Inscription : Septembre 2006
    Messages : 1 088
    Par défaut Demande de précisions
    Bonjour belgelino,
    Il faudrait que vous soyez clair.
    Voulez-vous que l'on vous explique dans le détail comment fonctionne ce code ?
    ou bien,
    Voulez-vous des explications sur l'utilisation de l'API jssc ?
    Merci de préciser.
    Une technologie n'est récalcitrante que par ce qu'on ne la connait et/ou comprend pas, rarement par ce qu'elle est mal faite.
    Et pour cesser de subir une technologie récalcitrante, n'hésitez surtout pas à visiter les Guides/Faq du site !

    Voici une liste non exhaustive des tutoriels qui me sont le plus familiers :
    Tout sur Java, du débutant au pro : https://java.developpez.com/cours/
    Tout sur les réseaux : https://reseau.developpez.com/cours/
    Tout sur les systèmes d'exploitation : https://systeme.developpez.com/cours/
    Tout sur le matériel : https://hardware.developpez.com/cours/

Discussions similaires

  1. Communication port série (RS232) avec VC++
    Par sanatou dans le forum Visual C++
    Réponses: 2
    Dernier message: 30/10/2006, 13h49
  2. Communication Port Série Internet
    Par psyckey dans le forum Hardware
    Réponses: 3
    Dernier message: 29/09/2006, 19h37
  3. [VB6] Probleme communication Port série
    Par Renard-fou dans le forum VB 6 et antérieur
    Réponses: 8
    Dernier message: 15/05/2006, 00h01
  4. Communication port série W2000/W98
    Par Fabsou dans le forum MFC
    Réponses: 4
    Dernier message: 24/10/2005, 19h57
  5. probleme de communication port série
    Par ben23 dans le forum MFC
    Réponses: 8
    Dernier message: 06/02/2004, 15h12

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo