Comment transférer des données sur un port série?

Je sais que dans J2ME CommConnection est la connexion à utiliser lorsque vous travaillez avec serial port . Je sais qu’il existe des méthodes openInputStream et openOutputStream , mais en fait, je ne sais pas comment transférer des données de mon MIDLet vers le port COM (le port USB dans lequel le câble du téléphone est inséré, le téléphone est Alcatel OT-806D). Par exemple, je veux envoyer le texte “Hello world”. Comment y parvenir?

Voici les codes:

J2ME:

 import java.io.IOException; import java.io.OutputStream; import javax.microedition.io.CommConnection; import javax.microedition.io.Connector; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.Form; import javax.microedition.midlet.*; public class SerialPortMidlet extends MIDlet implements CommandListener, Runnable { private Command upload = new Command("upload", Command.SCREEN, 0); private Command exit = new Command("exit", Command.SCREEN, 1); private Form f = new Form("test serial port"); private Thread uploadThread; private CommConnection com; private OutputStream os; public SerialPortMidlet() { f.addCommand(upload); f.addCommand(exit); f.setCommandListener(this); uploadThread = new Thread(this); } public void startApp() { Display.getDisplay(this).setCurrent(f); } public void pauseApp() { } public void destroyApp(boolean unconditional) { notifyDestroyed(); } public void commandAction(Command c, Displayable d) { if (c == upload) { uploadThread.start(); f.removeCommand(upload); } else if (c == exit) { if (uploadThread.isAlive()) { uploadThread.interrupt(); try { uploadThread.join(); } catch (InterruptedException ex) { ex.printStackTrace(); } } destroyApp(true); } } public void run() { try { Ssortingng s = new Ssortingng("andrana mandefa lavaka"); com = (CommConnection) Connector.open("comm:COM4"); os = com.openOutputStream(); os.write(s.getBytes()); os.close(); } catch (IOException ex) { ex.printStackTrace(); } } } 

J2SE: (Eclipse)

 import gnu.io.CommPort; import gnu.io.CommPortIdentifier; import gnu.io.SerialPort; import gnu.io.SerialPortEvent; import gnu.io.SerialPortEventListener; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class TwoWaySerialComm { public TwoWaySerialComm() { super(); } void connect ( Ssortingng portName ) throws Exception { CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName); if ( portIdentifier.isCurrentlyOwned() ) { System.out.println("Error: Port is currently in use"); } else { CommPort commPort = portIdentifier.open(this.getClass().getName(),2000); if ( commPort instanceof SerialPort ) { SerialPort serialPort = (SerialPort) commPort; serialPort.setSerialPortParams(57600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE); InputStream in = serialPort.getInputStream(); OutputStream out = serialPort.getOutputStream(); (new Thread(new SerialWriter(out))).start(); serialPort.addEventListener(new SerialReader(in)); serialPort.notifyOnDataAvailable(true); } else { System.out.println("Error: Only serial ports are handled by this example."); } } } public static class SerialReader implements SerialPortEventListener { private InputStream in; private byte[] buffer = new byte[1024]; public SerialReader ( InputStream in ) { this.in = in; } public void serialEvent(SerialPortEvent arg0) { int data; try { int len = 0; while ( ( data = in.read()) > -1 ) { if ( data == '\n' ) { break; } buffer[len++] = (byte) data; } System.out.print(new Ssortingng(buffer,0,len)); } catch ( IOException e ) { e.printStackTrace(); System.exit(-1); } } } public static class SerialWriter implements Runnable { OutputStream out; public SerialWriter ( OutputStream out ) { this.out = out; } public void run () { try { int c = 0; while ( ( c = System.in.read()) > -1 ) { this.out.write(c); } } catch ( IOException e ) { e.printStackTrace(); System.exit(-1); } } } /** * @param args */ public static void main(Ssortingng[] args) { // TODO Auto-generated method stub try { (new TwoWaySerialComm()).connect("COM1"); } catch ( Exception e ) { // TODO Auto-generated catch block e.printStackTrace(); } } } 

Je lance le programme J2SE, j’ai inséré le câble du téléphone portable dans l’ordinateur (dans la fente USB), j’ai cliqué sur la commande de upload dans l’application J2ME, mais il n’ya rien dans l’écran de sortie de l’éclipse!

Donc quel est le problème ?

Je lance ce code J2SE pour détecter le port sur lequel se trouve le câble du téléphone:

 import gnu.io.*; public class SerialPortLister { /** * @param args */ public static void main(Ssortingng[] args) { // TODO Auto-generated method stub listPorts(); } private static void listPorts() { @SuppressWarnings("unchecked") java.util.Enumeration portEnum = CommPortIdentifier.getPortIdentifiers(); while ( portEnum.hasMoreElements() ) { CommPortIdentifier portIdentifier = portEnum.nextElement(); System.out.println(portIdentifier.getName() + " - " + getPortTypeName(portIdentifier.getPortType()) ); } } private static Ssortingng getPortTypeName ( int portType ) { switch ( portType ) { case CommPortIdentifier.PORT_I2C: return "I2C"; case CommPortIdentifier.PORT_PARALLEL: return "Parallel"; case CommPortIdentifier.PORT_RAW: return "Raw"; case CommPortIdentifier.PORT_RS485: return "RS485"; case CommPortIdentifier.PORT_SERIAL: return "Serial"; default: return "unknown type"; } } } 

Et il affiche COM4 car lorsque je détache le câble, seuls COM1 et LPT1 sont affichés.

Donc quel est le problème ?

Votre téléphone semble être bien détecté par l’ordinateur, car il est connecté sur le port COM virtuel 4. Cependant, cela ne me dit pas que vous devez utiliser le protocole de port COM du côté du téléphone pour communiquer avec l’ordinateur. Il est parfaitement possible qu’il y ait simplement une mémoire tampon sur le téléphone, qui une fois remplie sera livrée sur le port USB.

Je ne connais pas votre téléphone mais j’ai déjà programmé un microcontrôleur. Là, je n’utilisais jamais le protocole du port COM et je réussissais à communiquer avec un ordinateur doté d’un pilote de port virtuel.

Pour mieux comprendre mon propos, vous pouvez probablement vous reporter à la documentation du microcontrôleur présent sur votre téléphone.