Solved

How to share a com port using java.

Posted on 2002-06-18
10
546 Views
Last Modified: 2008-02-01
hi techies!
I'm making a application which would allow me share a single com port for two hardware devices which are sending messgaes to my pc,and i'm replying to both the devices.(communication is asynchronous type).so i need to send device specific messages.please help, can this be done using any java api.

pls help.
0
Comment
Question by:informvinay
10 Comments
 
LVL 16

Expert Comment

by:heyhey_
ID: 7092156
have you tried JavaComm ?
0
 
LVL 2

Expert Comment

by:vasan_sr
ID: 7095255
Hi.....as heyhey said u can use comm api for that....it just works fine...

VasanS
0
 

Accepted Solution

by:
vijaywadnere earned 50 total points
ID: 7111551
Yup! the required thing can be done with the help of JavaComm API.

You can open the specific COM port using a call to
CommPortIdentifier.open() method (pls refer the javax.comm API).

As your requirement, you can open same COM port in TWO different threads (even programs), the only thing to remember is, while opening a COM port you've to provide the application's name. In your case you've to put the same name in both the calls to the 'open' method.

Now the InputStream/OutputStream can be obtained and redaing/writing can be done.

Further, I can provide you a simple code if required.

0
 

Author Comment

by:informvinay
ID: 7112783
Hey Vijay
Can u please provide me a simple code.

Regards
Vinay
0
 

Expert Comment

by:vijaywadnere
ID: 7114490
Well its not possible to put the code right here!!

why dont u send me an email and i'll send u a working code for COM port communication.

Infact, if anybody needs the code pls mail me at:

vijay2903@yahoo.com

best wishes.

...and, thanx for the points!! :)
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 5

Expert Comment

by:Netminder
ID: 7120097
vijaywadnere and informvinay,

I note that you're both relatively new members here, so I'm going to give you a break for what might seem like an innocuous event, but which in fact is a serious violation of the membership agreement.

In addition to being a site where you can get answers to questions fairly quickly, and assistance from top-notch experts in a wide range of fields, Experts Exchange is a repository for future users. By using email to communicate answers to questions outside of EE, you violate the Exchange of information. Such actions will not be tolerated, and future occurrences will result in points being removed from your accounts, and can lead to further actions by Administration.

vijaywadnere,

Please post the code here; I've seen some fairly sophisticated posts in other questions.

Thanks to both of you,

Netminder
CS Moderator

0
 

Expert Comment

by:vijaywadnere
ID: 7122720
Netminder,i think its all cause we want to run before we can walk!!

InformVinay, here's the required code in Java. You'll need to plug your MODEM and keep it ON to run the program. Alt. you can use a NULL MODEM at your COM port.

Command Line:>> java Main COM1
(COM1 or COM2 depends on what port you are using)
(do not mind the GUI, i'm really bad at it)

If everything goes well, whatever typed at lefthand textfield, will be displayed in the righthand textarea.

*******************************************
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.comm.*;
import java.util.*;
public class Main extends Frame implements ActionListener {
        TextArea status;
        Thread recvThread;
        Receiver recv;
        Transmitter tran;
        CommPortIdentifier portId;
        CommPort cp;
        boolean okay, opened;
        Panel initP;
        Button initB, exit;
        public Main(String port) {
                super("My Serial Communicator");
                status = new TextArea();
                status.setEditable(false);
                add(status, "North");
                try {
                        portId = CommPortIdentifier.getPortIdentifier(port);
                        cp = portId.open("Main", 5000);
                        okay = true;
                        opened = true;
                } catch(NoSuchPortException e){
                        status.append("No Such Port: "+port+"\n");
                        okay = false;
                } catch(PortInUseException e) {
                        status.append("Port ["+port+"] in Use by ["+ portId.getCurrentOwner() +"]\n" );
                        okay = false;
                }
                setSize(800, 600);
                initP = new Panel();
                initB = new Button("Init");
                initB.addActionListener(this);
                initP.add(initB);
                add(initP, "Center");
                exit = new Button("Exit");
                exit.addActionListener(this);
                add(exit, "South");
                this.validate();
                setVisible(true);
        }
        protected void init() {
                if(okay) {
                        recv = new Receiver(this, cp);
                        recvThread = new Thread(recv);
                        tran = new Transmitter(this, cp);
                        add(tran, "West");
                        add(recv, "East");
                        recvThread.start();
                        remove(initP);
                        this.validate();
                }
        }
        public void actionPerformed(ActionEvent e) {
                if( e.getSource() == exit ) {
                        if(okay) {
                                //close the port;
                                recvThread = null;
                                try {
                                        opened = false;
                                        recv.close();
                                        tran.close();
                                        cp.close();
                                        System.out.println("Comm Port Closed.");
                                } catch(Exception ee) {
                                        System.out.println("Execption while closing port:");
                                        System.out.println(ee);
                                }
                        }
                        this.dispose();
                        System.exit(0);
                }
                if( e.getSource() == initB ) {
                        init();
                }
        }
        public static void main(String[] arg) {
                Main m = new Main( arg[0] );
        }
}
class Transmitter extends TextField implements ActionListener {
        Main owner;
        CommPort cp;
        boolean okay;
        OutputStream os;
        public Transmitter(Main o, CommPort c) {
                super(20);
                owner  = o;
                cp = c;
                try {
                        os = cp.getOutputStream();
                        okay = true;
                } catch(Exception e) {
                        okay = false;
                        owner.status.append(e+"\n");
                }
                addActionListener(this);
        }
        public void actionPerformed(ActionEvent e) {
                String str = getText();
                if(okay) {
                        if(str.length()>0) {
                                try {
                                        os.write( str.getBytes() );
                                        setText("");
                                } catch(Exception ee) {
                                        owner.status.append(ee+"\n");
                                }
                        }
                } else {
                        owner.status.append("Could Not Transmit\n");
                }
        }
        public void close() {
                owner = null;
                cp = null;
                if(okay) {
                        try {
                                os.close();
                                System.out.println("Output Stream Closed.");
                        } catch(Exception e) {
                                System.out.println("Exception while closing transmitter:");
                                System.out.println(e);
                        }
                }
        }
}
class Receiver extends TextArea implements Runnable {
        Main owner;
        CommPort cp;
        boolean okay;
        InputStream is;
        byte buffer[];
        public Receiver(Main o, CommPort c) {
                super();
                owner = o;
                cp = c;
                buffer = new byte[2048];
                setEditable(false);
                try {
                        is = cp.getInputStream();
                        okay = true;
                } catch(Exception e) {
                        okay = false;
                        owner.status.append(e+"\n");
                }
        }
        public void run() {
                while(owner.opened) {
                        System.out.print(".");
                        try {
                                while ( owner.opened && is.available()>0) {
                                        int bytes = is.read(buffer);
                                        System.out.print("~");
                                        if(bytes>0) {
                                                this.append( new String(buffer,0,bytes) + "\n");
                                        }
                                }
                        } catch(Exception e) {
                                owner.status.append(e+"\n");
                        }
                        try {
                                synchronized(this) {
                                        wait(500);
                                }
                        } catch(InterruptedException e) {}
                }
        }
        public void close() {
                owner = null;
                cp = null;
                if(okay) {
                        try {
                                is.close();
                                System.out.println("InputStream closed.");
                        } catch(Exception e) {
                                System.out.println("Exception while closing Receiver:");
                                System.out.println(e);
                        }
                }
        }
}
*******************************************
0
 

Expert Comment

by:r4yb
ID: 7442247
hi vijay!

i have been doing a class to send a string to com port, i read your example for read the port.. but i cant read ... the program say's no such port... i have a printer connected to a com1 port... i cant detect her... if you can help me.. i apreciate... thnks ;)
0
 

Expert Comment

by:vijaywadnere
ID: 7444663
hi All,

I've received a mail similar to the question arised by r4yb.
I thought it would be beneficial for all if it is answered here.

the javacomm api contains 3 main things.
1. win32comm.DLL (must be in jdk1.3/bin folder)
2. javax.com.properties (must be in jdk1.3/lib folder)
3. comm.jar (should be in classpath)

now, to access/handle a hardware that is connected to a port, one should know the proper sequence to data/commands that is to be sent to the corresponding port. simply writing 'bytes' to a printer port will NOT actually print them on printer.

I've never seen a Printer attached on a COM port, it should be on a parallel port (LPT). though I never programmed a parallel port, but the same procedure may be applied and it should work if both the terminals (PC & Hardware attached at port) understands a common protocol.

in addition to it, one may paste his/her code over here, and we can try to make it work.

regards all,
- Vijay Wadnere
0
 

Expert Comment

by:r4yb
ID: 7447588
hi all,

thnks Vijay.

.:: Sory my bad English :/ ::.

i've realy a printer connected to a com port, i never see one like this.... it's very weird, it's a "Star SP300".

code :

****************
void jButton2_actionPerformed(ActionEvent e) {

  String port = "COM2";

  try {
 
    System.out.println("before port id");
    portId = CommPortIdentifier.getPortIdentifier(port);
    System.out.println("after port id");
    cp = portId.open("testeApp",5000);
    System.out.println(" cp : " + cp);
  } catch(NoSuchPortException np){
    System.out.println("No Such Port: "+port+"\n");
  } catch(PortInUseException up) {
    System.out.println("Port ["+port+"] in Use by ["+ portId.getCurrentOwner() +"]\n" );
  }

    System.out.println("get port identifiers : " + CommPortIdentifier.getPortIdentifiers());
    System.out.println("get port serial  : " + CommPortIdentifier.PORT_SERIAL);
    System.out.println("get port paralel : " + CommPortIdentifier.PORT_PARALLEL);

}

**************


In this part i only test the port.
the program passed for first "System.out" and after he detects an exception (NoSuchPortException).

I'm doing something wrong?

thnks
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now