JAVA RMI get pass ArrayList element - java

I have a server that contains an ArrayList in " ServerInfo " and when I try to take from ClientRMI an element of the ArrayList(in ServerInfo) for example adf.getSGM ( 0 ).incrementCount( ) ;
"count" does not increase it's as if every time I call it instantiates a new class SGM
in a few words I want to interact from ClientRMI with ArrayList that is on ServerInfo (SORRY FOR ENGLISH)
Hear are the classes :
SERVER
public class ServerRMI {
public static void main(String[] args) {
Registry registry = null;
String name = "ServerInfo";
try {
System.out.println("Init RMI");
ServerInfoInterface sir = ServerInfo.getInstance();
ServerInfoInterface stub = (ServerInfoInterface) UnicastRemoteObject.exportObject(sir, 0);
registry = LocateRegistry.createRegistry(9000);
registry.bind(name, stub);
System.out.println("RMI OK");
System.out.println("Init SGM...");
for(int i=0;i<3;i++){
ServerInfo.getInstance().addSGM(new SGM());
}
System.out.println("Init SGM OK");
} catch (Exception e) {
System.out.println("RMI Error"+e.toString());
registry = null;
}
}
}
public class ServerInfo implements ServerInfoInterface{
private ArrayList<SGM> sgmHandler = new ArrayList<SGM>();
// Singleton pattern
private static ServerInfo instance;
// Singleton pattern
public static ServerInfo getInstance() {
if (instance == null){
System.out.println("ServerInfo new instance");
instance = new ServerInfo();
}
return instance;
}
#Override
public synchronized void addSGM(SGM sgm) throws RemoteException {
sgmHandler.add(sgm);
}
#Override
public synchronized SGM getSGM(int i) throws RemoteException {
return sgmHandler.get(i);
}
}
public interface ServerInfoInterface extends Remote{
public void addSGM(SGM sgm) throws RemoteException;
public SGM getSGM(int i) throws RemoteException;
}
public class SGM implements Serializable{
/**
*
*/
private static final long serialVersionUID = -4756606091542270097L;
private int count=0;
public void incrementCount(){
count++;
}
public void decrementCount(){
count--;
}
public int getCount(){
return count;
}
}
CLIENT
public class ClientRMI {
private ServerInfoInterface sgmInterface;
public void startServer() {
String name = "ServerInfo";
Registry registry;
try {
registry = LocateRegistry.getRegistry(9000);
try {
sgmInterface = (ServerInfoInterface) registry.lookup(name);
sgmInterface.getSGM(0).incrementCount();
System.out.println(sgmInterface.getSGM(0).getCount()); // always 0
} catch (AccessException e) {
System.out.println("RIM AccessException"+ e.toString());
} catch (RemoteException e) {
System.out.println("RIM RemoteException"+ e.toString());
} catch (NotBoundException e) {
System.out.println("RIM NotBoundException"+ e.toString());
}
} catch (RemoteException e) {
System.out.println("RIM RemoteException registry"+ e.toString());
}
}
}

You're creating an SGM at the server, passing it via Serialization to the client, incrementing its count at the client, and then expecting that count to be magically increased at the server.
It can't work.
You will have to make SGM a remote object, with its own remote interface, or else provide a remote method in the original remote interface to increment the count of a GSM, specified by index.

Related

App for external barcode scanner(use USB port)

Update: came up with new error about the provided java class
I have a tutorial for building an app for an external barcode scanner(use USB port) by using Java + provided Jar Library. I'm trying to build the same app by using the Xamarin.Forms and that Jar Library(through BindingsLibrary Project). However, I got an error
"Java.Lang.NoClassDefFoundError: " when I compiled my code. Does anybody have an idea about what I'm doing wrong?
This my java classes:
The USBScanFactory
package com.unistrong.qrcode;
import com.unistrong.pin.GOPOManager;
public class USBQRscanFactory {
private static USBQRscanFactory factory = new USBQRscanFactory();
static boolean mIsScanContinue = false;
private GOPOManager mGopoManager = GOPOManager.getInstance();
private OnScanListener mScanListener;
private QRScanManagerJNI qrScanManagerJNI;
private USBQRscanFactory() {
}
public static USBQRscanFactory createInstance() {
return factory;
}
public void init(OnScanListener onScanListener) {
this.mGopoManager.Pin11_High();
this.qrScanManagerJNI = new QRScanManagerJNI(onScanListener);
this.qrScanManagerJNI.callbackInit();
}
public void enableAddKeyValue(int i) {
QRScanManagerJNI.AddKeyValue(i);
}
public void open() {
this.mGopoManager.Pin11_Low();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
QRScanManagerJNI.OpenDev();
}
public void powerOn() {
this.mGopoManager.Pin11_High();
this.mGopoManager.openPower5V_3V3();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void powerOff() {
this.mGopoManager.Pin11_High();
this.mGopoManager.closePower5V_3V3();
}
public void scan_start() {
QRScanManagerJNI.QRScan();
}
On ScanListener:
package com.unistrong.qrcode;
public interface OnScanListener {
void scanReport(byte[] bArr);
void statusReport(int i);
}
And here is my code on Xamain:
public class OnScanListener : Java.Lang.Object, IOnScanListener
{
H myH = new H();
public void ScanReport(byte[] byteArray)
{
lock (myH)
{
if (null != byteArray && byteArray.Length > 0)
{
myH.SendMessage(myH.ObtainMessage(0, byteArray));
}
}
}
public void StatusReport(int i)
{
lock (myH)
{
myH.SendEmptyMessage(i);
}
}
}
#endregion
public MainPage()
{
usbScan = USBQRscanFactory.CreateInstance();
InitializeComponent();
}
int count = 0;
private void scanBtn_Clicked(object sender, EventArgs e)
{
count++;
//usbScan.Init(OnScanListener);
OnScanListener myOnScanListener = new OnScanListener();
usbScan.PowerOn();
usbScan.Init(myOnScanListener);
Barcode.Text = "";
openScanner(true);
usbScan.Scan_start();
}
//Open Scanner
private void openScanner(bool open)
{
if (open == mWorkingStateFlag) return;
if (open)
{
try
{
Java.Lang.Thread.Sleep(50);
usbScan.Open();
usbScan.EnableAddKeyValue(0);
}
catch (Java.Lang.InterruptedException e)
{
// TODO Auto-generated catch block
e.PrintStackTrace();
}
}
}

How can the RMI registry be stopped programatically? [duplicate]

A RMI server which works fine without the stopServer functionality.
public class HelloServer extends UnicastRemoteObject implements HelloInterface
{
private final static int PORT=1102;
private final String serverName="server";
private Timer timer;
public HelloServer() throws RemoteException
{
timer = new Timer(); //At this line a new Thread will be created
timer.schedule(new StopServerTask(), 5000);
}
#Override
public String serverResponse(String request) throws RemoteException
{
return "Hello"+request;
}
public static void main(String[] args)
{
try
{
HelloServer skeleton=new HelloServer();
System.out.println("Starting server");
skeleton.startServer();
System.out.println("Server started");
}
catch (RemoteException ex)
{
ex.printStackTrace();
}
}
public void startServer()
{
try {
HelloServer skeleton=new HelloServer();
Registry reg=LocateRegistry.createRegistry(PORT);
reg.rebind(serverName, skeleton);
System.out.println("Server is ready");
} catch (RemoteException ex)
{
Logger.getLogger(HelloInterface.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void stopServer()
{
System.out.println("Stopping server");
try {
Registry rmiRegistry = LocateRegistry.getRegistry(PORT);
HelloInterface myService = (HelloInterface) rmiRegistry.lookup(serverName);
rmiRegistry.unbind(serverName);
UnicastRemoteObject.unexportObject(rmiRegistry, true);
} catch (NoSuchObjectException e)
{
e.printStackTrace();
} catch (NotBoundException e)
{
e.printStackTrace();
} catch (RemoteException ex) {
Logger.getLogger(HelloServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
class StopServerTask extends TimerTask
{
#Override
public void run()
{
stopServer();
}
}
}
Whenever stopServer() in invoked exception is thrown at
UnicastRemoteObject.unexportObject(rmiRegistry, true);
Here is the stack Trace
java.rmi.NoSuchObjectException: object not exported
at sun.rmi.transport.ObjectTable.unexportObject(ObjectTable.java:153)
at java.rmi.server.UnicastRemoteObject.unexportObject(UnicastRemoteObject.java:297)
at rmi.HelloServer.stopServer(HelloServer.java:84)
Things are same even when I clean the service object by using
UnicastRemoteObject.unexportObject(myService, true);
Could someone suggest a clean way to stop the server which also releases the port for reuse.
You need to store the result of LocateRegistry.createRegistry(), and unexport that. At present you're trying to unexport a stub.
I implemented a shutdown-service in my rmi-server. If I want to shut it down, I call it with a password. Simple Example:
public interface ShutdownInterface extends Remote {
public void shutdownService(String password) throws RemoteException;
}
The serverside implementation can look something like:
public class ShutdownService extends UnicastRemoteObject implements ShutdownInterface {
private static final long serialVersionUID = 1L;
private boolean doShutdown = false;
public ShutdownService() throws RemoteException {
super();
}
#Override
public void shutdownService(String password) throws RemoteException {
if ("abcde12345".equals(password)) {
System.out.println("shutdown requested.");
this.doShutdown = true;
} else {
System.out.println("wrong pwd for shutdown");
}
}
public boolean isDoShutdown() {
return this.doShutdown;
}
}
Now the server itself keeps a reference to this:
public class BackendServer {
public final static int RMI_PORT = 1974;
private Registry registry = null;
private ShutdownService shutdownService = null;
public BackendServer() throws RemoteException {
registry = LocateRegistry.createRegistry(RMI_PORT);
this.shutdownService = new ShutdownService();
}
public void initialize() throws AccessException, RemoteException, AlreadyBoundException {
shutdownService = new ShutdownService();
registry.bind("ShutdownService", shutdownService);
registry.bind("MyDataService", new MyDataService());
}
public void stop() throws NoSuchObjectException {
System.out.println("stopping rmi server.");
UnicastRemoteObject.unexportObject(registry, true);
System.exit(0);
}
public boolean shouldStop() {
return this.shutdownService.isDoShutdown();
}
public static void main(String args[]) {
try {
BackendServer bs = new BackendServer();
bs.initialize();
System.out.println("Server ready.");
while (!bs.shouldStop()) {
Thread.sleep(1000);
}
bs.stop();
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
Of course, this can be realized in a more beautiful way, but this should give you an idea of how to easily implement a shutdown yourself. You can call it from the main client or from a small commandline-tool you code for your server.

Clean way to stop RMI server

A RMI server which works fine without the stopServer functionality.
public class HelloServer extends UnicastRemoteObject implements HelloInterface
{
private final static int PORT=1102;
private final String serverName="server";
private Timer timer;
public HelloServer() throws RemoteException
{
timer = new Timer(); //At this line a new Thread will be created
timer.schedule(new StopServerTask(), 5000);
}
#Override
public String serverResponse(String request) throws RemoteException
{
return "Hello"+request;
}
public static void main(String[] args)
{
try
{
HelloServer skeleton=new HelloServer();
System.out.println("Starting server");
skeleton.startServer();
System.out.println("Server started");
}
catch (RemoteException ex)
{
ex.printStackTrace();
}
}
public void startServer()
{
try {
HelloServer skeleton=new HelloServer();
Registry reg=LocateRegistry.createRegistry(PORT);
reg.rebind(serverName, skeleton);
System.out.println("Server is ready");
} catch (RemoteException ex)
{
Logger.getLogger(HelloInterface.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void stopServer()
{
System.out.println("Stopping server");
try {
Registry rmiRegistry = LocateRegistry.getRegistry(PORT);
HelloInterface myService = (HelloInterface) rmiRegistry.lookup(serverName);
rmiRegistry.unbind(serverName);
UnicastRemoteObject.unexportObject(rmiRegistry, true);
} catch (NoSuchObjectException e)
{
e.printStackTrace();
} catch (NotBoundException e)
{
e.printStackTrace();
} catch (RemoteException ex) {
Logger.getLogger(HelloServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
class StopServerTask extends TimerTask
{
#Override
public void run()
{
stopServer();
}
}
}
Whenever stopServer() in invoked exception is thrown at
UnicastRemoteObject.unexportObject(rmiRegistry, true);
Here is the stack Trace
java.rmi.NoSuchObjectException: object not exported
at sun.rmi.transport.ObjectTable.unexportObject(ObjectTable.java:153)
at java.rmi.server.UnicastRemoteObject.unexportObject(UnicastRemoteObject.java:297)
at rmi.HelloServer.stopServer(HelloServer.java:84)
Things are same even when I clean the service object by using
UnicastRemoteObject.unexportObject(myService, true);
Could someone suggest a clean way to stop the server which also releases the port for reuse.
You need to store the result of LocateRegistry.createRegistry(), and unexport that. At present you're trying to unexport a stub.
I implemented a shutdown-service in my rmi-server. If I want to shut it down, I call it with a password. Simple Example:
public interface ShutdownInterface extends Remote {
public void shutdownService(String password) throws RemoteException;
}
The serverside implementation can look something like:
public class ShutdownService extends UnicastRemoteObject implements ShutdownInterface {
private static final long serialVersionUID = 1L;
private boolean doShutdown = false;
public ShutdownService() throws RemoteException {
super();
}
#Override
public void shutdownService(String password) throws RemoteException {
if ("abcde12345".equals(password)) {
System.out.println("shutdown requested.");
this.doShutdown = true;
} else {
System.out.println("wrong pwd for shutdown");
}
}
public boolean isDoShutdown() {
return this.doShutdown;
}
}
Now the server itself keeps a reference to this:
public class BackendServer {
public final static int RMI_PORT = 1974;
private Registry registry = null;
private ShutdownService shutdownService = null;
public BackendServer() throws RemoteException {
registry = LocateRegistry.createRegistry(RMI_PORT);
this.shutdownService = new ShutdownService();
}
public void initialize() throws AccessException, RemoteException, AlreadyBoundException {
shutdownService = new ShutdownService();
registry.bind("ShutdownService", shutdownService);
registry.bind("MyDataService", new MyDataService());
}
public void stop() throws NoSuchObjectException {
System.out.println("stopping rmi server.");
UnicastRemoteObject.unexportObject(registry, true);
System.exit(0);
}
public boolean shouldStop() {
return this.shutdownService.isDoShutdown();
}
public static void main(String args[]) {
try {
BackendServer bs = new BackendServer();
bs.initialize();
System.out.println("Server ready.");
while (!bs.shouldStop()) {
Thread.sleep(1000);
}
bs.stop();
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
Of course, this can be realized in a more beautiful way, but this should give you an idea of how to easily implement a shutdown yourself. You can call it from the main client or from a small commandline-tool you code for your server.

Decision to make a class static

I have the server project that I have seperated into 6 different classes:
ServerConnectionManager - is class is ment to be the hub for all other classes
Connection - This object is the created whenever a client connects and also starts a Thread
ServerListner - This is the Thread class that listens to input from the user
ServerSender - This is the class that sends messages to one or more users
ServerInformation - this class contains two list one of chat persons and one of connections this class also allows you to search through the list to find a specefic person and or connection
ChatPerson - This object is to contain the username of each person who connects to the server
As you no-doubt have guessed by now this is a server for a chat program!
My question to you is:
I want to use the Design patteren (Mediator) on this project and therefore the ServerConnectionManager contains all the key methods that each of the classes use. for example adding a connection to the connection list in the ServerInformation class.
But since the ServerInformation class cannot be called an object seeing as it only have alot of methods (functions) and no real purpose other than storing and searching Data would it be a good idea to make it static? or should i stick to the plan and make everything go through the ServerConnectionManager?
Here is a sample of my code:
ServerConnectionManager
public class ServerConnectionManager {
private static ServerSocket server;
private static Socket connection;
private static ServerInformation ai = new ServerInformation();
private static boolean connected = false;
private static final int portNumber = 7070;
private static int backLog = 100;
/**
* This method launches the server (and the application)!
* #param args
*/
public static void main(String[] args){
startServer();
waitForConnection();
}
/**
*This method sets the serverSocket to portNumber and also adds the backLog.
*/
private static void startServer() {
try {
server = new ServerSocket(portNumber, backLog);
connected = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* This method waits for a connection aslong as the serverSocket is connected.
* When a new client connects it creates an Object of the connection and starts the individual procedure.
*/
private static void waitForConnection() {
while (connected) {
try {
connection = server.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection c = new Connection(connection);
addConnection(c);
waitForConnection();
}
}
public static void closeMe(Socket con) {
for (Connection conn : ai.getConnectionList()) {
if (conn.getConnection() == con) {
ai.getList().remove(ai.getList().indexOf(ai.getChatPersonByConnection(con)));
ai.getConnectionList().remove(conn);
System.out.println(ai.getList());
System.out.println(ai.getConnectionList());
conn.close();
break;
}
}
}
public static void addConnection(Connection con){
ai.addToConnectionList(con);
}
public static void addChatPerson(ChatPerson p){
ai.add(p);
System.out.println(ai.getList());
}
}
Connection
public class Connection{
private Socket connection;
public Connection(Socket connection){
this.connection = connection;
ServerListner cl = new ServerListner(Connection.this);
cl.start();
}
public Socket getConnection(){
return this.connection;
}
public void close() {
try {
connection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
ServerListner
public class ServerListner extends Thread {
private Socket connection;
private BufferedReader br;
private ChatPerson person;
private Connection con;
private ServerInformation ai = new ServerInformation();
private ServerSender sender = new ServerSender();
public ServerListner(Connection con){
this.con = con;
connection = con.getConnection();
try {
br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Socket getConnection(){
return this.connection;
}
public void run(){
System.out.println(con.getConnection().isConnected());
try {
String inString;
while ((inString = br.readLine()) != null) {
if (inString.equalsIgnoreCase("Disconnect")) {
System.out.println(inString);
break;
}else {
processInput(inString);
}
}
ServerConnectionManager.closeMe(connection);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void processInput(String input){
if (input.equalsIgnoreCase("Connect")) {
sender.sendMessageToConnection(this.connection, "Accepted");
}
if (input.equalsIgnoreCase("UserInformation")) {
try {
String username = br.readLine();
person = new ChatPerson(username, connection);
ServerConnectionManager.addChatPerson(person);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (input.equalsIgnoreCase("SearchByCon")) {
String name = ai.searchByConnection(connection);
System.out.println(name);
}
}
}
ServerSender
public class ServerSender {
private PrintWriter pw;
private ServerInformation ai = new ServerInformation();
public void addToList(){
}
public void sendToAll(String message){
for (Connection c : ai.getConnectionList()) {
try {
pw = new PrintWriter(c.getConnection().getOutputStream());
pw.print(message);
pw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
*
* #param con
* #param message
*/
/*
* Note - Denne metode gør også at jeg kan hviske til folk!:)
*/
public void sendMessageToConnection(Socket con, String message){
try {
PrintWriter print = new PrintWriter(con.getOutputStream());
print.println(message);
print.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
ServerInformation
public class ServerInformation{
private ArrayList<Connection> connectedClients = new ArrayList<Connection>();
private ArrayList<ChatPerson> list = new ArrayList<ChatPerson>();
public ArrayList<Connection> getConnectionList(){
return connectedClients;
}
public void addToConnectionList(Connection con){
connectedClients.add(con);
}
public String searchByConnection(Socket myConnection){
for (ChatPerson p : list) {
if (p.getConnection() == myConnection) {
return p.getName();
}
}
/*
* If none found!
*/
return null;
}
public ChatPerson getChatPersonByConnection(Socket myConnection){
for (ChatPerson p : list) {
if (p.getConnection() == myConnection) {
return p;
}
}
return null;
}
public void add(ChatPerson p){
list.add(p);
}
public void removeByName(String name){
for (ChatPerson p : list) {
if (p.getName().equalsIgnoreCase(name)) {
list.remove(p);
}
}
}
public String searchList(String name){
for (ChatPerson p : list) {
if (p.getName().equalsIgnoreCase(name)) {
return p.getName();
}
}
return null;
}
public ArrayList<ChatPerson>getList(){
return list;
}
}
ChatPerson
public class ChatPerson {
private String chatName;
private Socket connection;
/*
* This is for furture development
* private Integer adminLevel;
*/
public ChatPerson(String name, Socket connection){
this.chatName = name;
this.connection = connection;
}
public void setName(String name){
this.chatName = name;
}
public String getName(){
return chatName;
}
public String toString(){
return "Username: "+chatName;
}
public Socket getConnection(){
return connection;
}
}
Thank you in advance, by the way since i am a student it would be nice if you had time to rate my code aswell and come with suggestions on how i can improve (if there are any :))
You probably meant class with only static methods, not static class. Static inner classes are something different (you can google it).
Advantages of having non-static methods in your manager:
You can easily mock them with frameworks like Mockito during testing.
You can pull them up to some interface during refactoring of your code.
Using static methods is not object-oriented-programming as such method invocations are not associated with any instance (object) of your class.

java - implement interfaces for threads

I am trying to "connect" two classes together, MyJFrame and MySerialPort, using the interface SerialPortListener, but I am clueless as how to do it. The reason I am doing this is because yesterday I had a problem assigning data from a serial port buffer to a global String (finalString), in the MySerialPort class. This string should be returned to MyJFrame where a label displays it. The problem was that my label would display finalString before anything
was assigned to finalString, since classes were running in different threads. I posted the question on the forum and received a suggestion to use interface to connect their threads, and I modified the code according. Where do I use the keyword implements SerialPortListener and how do I get the value?
SerialPortListener Interface code
public interface SerialPortListener {
void stringReveivedFromSerialPort(String s);
}
MyJFrame class code
public class MyJFrame extends JFrame{
public MySerialPorts msp = new MySerialPorts();
public MyJFrame(){
initComponents();//draws GUI components
initSerialPorts();//initializes serial ports
}
private void initSerialPorts(){
msp.getPortName();//gets serial port's name (in this example COM1)
msp.openPort();//opens the communication for port COM1
}
private String firmwareVersion(){
//This is the method I call when I want to get the Firmware Version
msp.getFirmwareVersion();//sends command to receive reply from serial device
lblFirmwareVersion.setText();//label that prints the firmware version String
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new MainJFrame().setVisible(true);
}
});
}
private JLabel lblFirmwareVersion;
}
MySerialPort class code
public class MySerialPort {
//this method is using the jSSC API (java simple serial connector)
//http://code.google.com/p/java-simple-serial-connector/
private SerialPort serialPort;
private int iBaudRate = SerialPort.BAUDRATE_57600;
private int iDataBits = SerialPort.DATABITS_8;
private int iStopBits = SerialPort.STOPBITS_1;
private int iParity = SerialPort.PARITY_NONE;
private String portName = "";
// private String finalString = "";
// private StringBuilder sbBuffer = new StringBuilder();
private List<SerialPortListener> portListeners = new ArrayList<SerialPortListenerInterface>();
public void addMyPortListener(SerialPortListener listener) {
portListeners.add(listener);
}
public void removeMyPortListener(SerialPortListener listener) {
portListeners.remove(listener);
}
public void getFirmwareVersion() {
sendPortCommand("<VersFV1A2>\r\n");
}
// public String returnFinalString() {
// return finalString;
// }
public void getPortName() {
String[] ports = SerialPortList.getPortNames();
portName = ports[0];
}
public void openPort() {
serialPort = new SerialPort(portName);
try {
if (serialPort.openPort()) {
if (serialPort.setParams(iBaudRate, iDataBits, iStopBits, iParity)) {
serialPort.addEventListener(new Reader(), SerialPort.MASK_RXCHAR
| SerialPort.MASK_RXFLAG
| SerialPort.MASK_CTS
| SerialPort.MASK_DSR
| SerialPort.MASK_RLSD);
} else {
//Error Message - Can't set selected port parameters!
serialPort.closePort();
}
} else {
//Error Message - Can't open port!
}
} catch (SerialPortException | HeadlessException ex) {
//Error Message - Can't open port! - Do nothing
}
}
private void sendPortCommand(String sSendPortCommand) {
if (sSendPortCommand.length() > 0) {
try {
serialPort.writeBytes(sSendPortCommand.getBytes());
} catch (Exception ex) {
//Error Message - Error occured while sending data!
}
}
}
private class Reader implements SerialPortEventListener {
private String sBuffer = "";
#Override
public void serialEvent(SerialPortEvent spe) {
if (spe.isRXCHAR() || spe.isRXFLAG()) {
if (spe.getEventValue() > 0) {
try {
//Read chars from buffer
byte[] bBuffer = serialPort.readBytes(spe.getEventValue());
sBuffer = new String(bBuffer);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
for (SerialPortListenerInterface listener : portListeners) {
listener.stringReveivedFromSerialPort(sBuffer);
}
}
});
// The following is the code I had prior to suggestion of using invokeLater instead of invokeAndWait
//
// sbBuffer.setLength(0);
//
// SwingUtilities.invokeAndWait(
// new Runnable() {
//
// #Override
// public void run() {
// sbBuffer.append(sBuffer);
// }
// });
//
// finalString = new String(sbBuffer);
} catch (Exception ex) {
}
}
}
}
}
}
Here's some code that you could add to your initSerialPorts() method, and which would open a dialog box displaying the text received from the serial port:
msp.addMyPortListener(new SerialPortListener() {
#Override
public void stringReveivedFromSerialPort(String s) {
JOptionPane.showMessageDialog(MyJFrame.this, s);
}
});
It creates an anonymous SerialPortListener instance, which displays a dialog box containing the received text as message, and adds it to your MySerialPort msp instance.
I believe that you want your MyJFrame class to implement SerialPortListener:
public class MyJFrame extends JFrame implements SerialPortListener {
/* blah */
#Override
public void stringReveivedFromSerialPort(String s) {
lblFirmwareVersion.setText(s);
}
/* blah */
}

Categories