serial port how do I? - java

Hi I am using Netbeans as my IDE. I want to play a little bit with the serial port. I am using an FTDI cable in my laptop that converts usb port to RS232 serial port.
I have found these interesting sites:
http://www.embeddedunveiled.com/
https://github.com/RishiGupta12/serial-communication-manager
I have written this piece of code taken from first link
under
Example usage
•How to find serial ports available on system is here.
code:
package findserialports;
import com.embeddedunveiled.serial.SerialComManager;
/**
*
* #author Alexandros
*/
public class FindSerialPorts {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try {
SerialComManager scm = new SerialComManager();
String[] ports = scm.listAvailableComPorts();
for(String port: ports){
System.out.println(port);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
There is an error in code in statement
import com.embeddedunveiled.serial.SerialComManager;
Also it says on site second link
that The folder prebuilt contains ready-to-use jar file (scm-1.0.3.jar) that can be imported in any project and referenced right away.
Where do I find the prebuild folder?
thanks
----------Second Post----------------------------------------------
Moving on I have following code:
package serialportftdi;
import com.embeddedunveiled.serial.SerialComManager;
import com.embeddedunveiled.serial.SerialComManager.BAUDRATE;
import com.embeddedunveiled.serial.SerialComManager.DATABITS;
import com.embeddedunveiled.serial.SerialComManager.FLOWCONTROL;
import com.embeddedunveiled.serial.SerialComManager.PARITY;
import com.embeddedunveiled.serial.SerialComManager.STOPBITS;
/**
*
* #author Alexandros
*/
public class SerialPortFTDI {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try {
SerialComManager scm = new SerialComManager();
long handle = scm.openComPort("/dev/ttyUSB1", true, true, false); scm.configureComPortData(handle, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0);
scm.configureComPortControl(handle, FLOWCONTROL.NONE, 'x', 'x', false, false);
scm.writeString(handle, "testing hello", 0) == true);
String data = scm.readString(handle);
System.out.println("data read is :" + data);
scm.closeComPort(handle);
}catch (Exception e) {
e.printStackTrace();
}
}
}
An error occurs at line : scm.writeString(handle, "testing hello", 0) == true);
C:\Users\Alexandros\Documents\NetBeansProjects\SerialPortFTDI\src\serialportftdi\SerialPortFTDI.java:31: error: not a statement
scm.writeString(handle, "testing hello", 0) == true);
^
C:\Users\Alexandros\Documents\NetBeansProjects\SerialPortFTDI\src\serialportftdi\SerialPortFTDI.java:31: error: ';' expected
scm.writeString(handle, "testing hello", 0) == true);
^
2 errors
C:\Users\Alexandros\Documents\NetBeansProjects\SerialPortFTDI\nbproject\build-impl.xml:923: The following error occurred while executing this line:
C:\Users\Alexandros\Documents\NetBeansProjects\SerialPortFTDI\nbproject\build-impl.xml:263: Compile failed; see the compiler error output for details.
BUILD FAILED (total time: 3 seconds)
Also I am trying to understand the code but I don't understand what 'handle' does. Is this a handle as in C++? If yes then what exactly does? I was trying to find info about it in Java Deitel and wrox books but no info.

Ok! I played a little bit with code and now it works fine. Bare in mind that the ftdi cable must be inserted to the usb port that is found as being connected to COM4 serial port.
Code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package serialportftdi;
import com.embeddedunveiled.serial.SerialComManager;
import com.embeddedunveiled.serial.SerialComManager.BAUDRATE;
import com.embeddedunveiled.serial.SerialComManager.DATABITS;
import com.embeddedunveiled.serial.SerialComManager.FLOWCONTROL;
import com.embeddedunveiled.serial.SerialComManager.PARITY;
import com.embeddedunveiled.serial.SerialComManager.STOPBITS;
/**
*
* #author Alexandros
*/
public class SerialPortFTDI {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try {
SerialComManager scm = new SerialComManager();
long handle = scm.openComPort("COM4", true, true, true);
scm.configureComPortData(handle, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0);
scm.configureComPortControl(handle, FLOWCONTROL.NONE, 'x', 'x', false, false);
scm.writeString(handle, "testing hello", 0); //== true);
String data = scm.readString(handle);
System.out.println("data read is :" + data);
scm.closeComPort(handle);
}catch (Exception e) {
e.printStackTrace();
}
}
}

Related

I have a problem with the java SSHClient class, specifically the Expect method does not return data as espected, what could be happening?

I have used the SSHClient class of java to connect to a Juniper router, when entering the console in the putty console it returns the result without problem, but when doing it from the Java code it does not save what is returned by the command, or does not print it, Could you tell me what to do?
I share the ssh class that I am using to guide you in case you encounter any problems:
package com.mycompany;
import static net.sf.expectit.matcher.Matchers.contains;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.connection.channel.direct.Session.Shell;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;
import net.sf.expectit.Expect;
import net.sf.expectit.ExpectBuilder;
public class sshj {
/**
* Launch Commands to Provisioning
*
* #param host
* #param port
* #param user
* #param password
* #param commands
* #param splitBy
* #return result
*/
public static String launchCommands(String host, Integer port, String user, String password, String commands,
String commandsSplitBy, String expectSplitBy, Integer timeoutInSeconds) {
String result = "";
StringBuilder wholeBuffer = new StringBuilder();
SSHClient mSSSHClient = new SSHClient();
mSSSHClient.addHostKeyVerifier(new PromiscuousVerifier());
Session mSession = null;
Shell mShell = null;
Expect mExpect = null;
String[] splitCommands = commands.split(commandsSplitBy);
try {
mSSSHClient.connect(host, port);
mSSSHClient.authPassword(user, password);
mSession = mSSSHClient.startSession();
mShell = mSession.startShell();
mExpect = new ExpectBuilder()
.withOutput(mShell.getOutputStream())
.withInputs(mShell.getInputStream())
.withEchoInput(wholeBuffer)
.withEchoOutput(wholeBuffer)
// .withEchoInput(System.out)
// .withEchoOutput(System.err)
.withExceptionOnFailure()
.withTimeout(timeoutInSeconds, TimeUnit.SECONDS).build();
// When expectSplitBy is equals to ""
if ("".equalsIgnoreCase(expectSplitBy)) {
for (String commandExpect : splitCommands) {
mExpect.sendLine(commandExpect);
}
} else { // When expectSplitBy is not equals to ""
for (String commandExpect : splitCommands) {
String[] commandExpectSplit = commandExpect.split(expectSplitBy);
mExpect.sendLine(commandExpectSplit[0]);
mExpect.expect(contains(commandExpectSplit[1]));
}
}
mShell.close();
mSession.close();
mSSSHClient.disconnect();
result = wholeBuffer.toString();
} catch (IOException e) {
result = wholeBuffer.toString().concat(" The Exception is> ").concat(e.toString());
e.printStackTrace();
try {
mExpect.sendLine("exit");
mShell.close();
mSession.close();
mSSSHClient.disconnect();
} catch (IOException e1) {
e1.printStackTrace();
}
}
return result;
}
}
I found the problem, is that the command sent contains some strange characters at the beginning that look like a blank space, and I could eliminate them and the functionality of the class is executed without problem.
I tagged mule because it's where I'm working with this class, which I know is from a third party, that's why I shared all the code so you could do tests. I am very sorry if you do not find my question clear.

Extension of `MavenProjectWizard` possible?

What I want: I have an editor plug-in for my custom DSL. I want to offer the user to set up a new DSL project with a project wizard. Normally these projects are Maven projects, so I want to provide setting up the project directly as a Maven project. To do that I want to extend the class MavenProjectWizardin the package org.eclipse.m2e.core.ui.internal.wizards.MavenProjectWizard and then add another wizard page with the details regarding the DSL project.
What I have: This is my try to do it at the moment:
/*
* Copyright (c) 2017 RWTH Aachen. All rights reserved.
*
* http://www.se-rwth.de/
*/
package de.se_rwth.transformationeditor.wizard;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.m2e.core.ui.internal.wizards.MavenProjectWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard;
import jline.internal.Log;
/**
* Offers a wizard to create a new Transformation project
*
* #author (last commit) $Philipp Nolte$
* #version $Revision$, $12.1.2017$
* #since 0.0.3
*/
#SuppressWarnings("restriction")
public class CDProjectWizard extends MavenProjectWizard{
protected CDWizardPageOne one;
protected WizardPage currentPage;
private IWorkbench workbench;
public CDProjectWizard() {
super();
}
/**
* #see org.eclipse.jface.wizard.IWizard#addPages()
*/
#Override
public void addPages() {
one = new CDWizardPageOne();
addPage(one);
super.addPages();
}
/**
* #see org.eclipse.ui.wizards.newresource.BasicNewProjectResourceWizard#init(org.eclipse.ui.IWorkbench,
* org.eclipse.jface.viewers.IStructuredSelection)
*/
#Override
public void init(IWorkbench workbench, IStructuredSelection selection) {
super.init(workbench, selection);
this.workbench = workbench;
}
/**
* #see org.eclipse.jface.wizard.IWizard#getWindowTitle()
*/
#Override
public String getWindowTitle() {
return "New Class Diagram Transformation Project";
}
/**
* Creates a new Transformation project with the project name given in the
* wizard. Inside this project a new folder named "Transformations" is
* created. If a project with the same name already exists, an error window is
* shown. In addition to that, checks if user wants to create CD or MA xample
* files and creates them if wanted.
*
* #see org.eclipse.jface.wizard.IWizard#performFinish()
*/
#Override
public boolean performFinish() {
if (this.canFinish()) {
// Create new project
String projectName = this.one.getProjectNameText();
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IProject project = root.getProject(projectName);
try {
if (!project.exists()) {
project.create(null);
}
else {
project.refreshLocal(IResource.DEPTH_INFINITE, null);
MessageDialog.openError(this.workbench.getActiveWorkbenchWindow().getShell(),
"Project creation error", "Project with this name already exists");
return false;
}
if (!project.isOpen()) {
project.open(null);
}
String transformationFolderName = "Transformations";
// Check subfolder name
if (!one.getRootFolderText().isEmpty()) {
transformationFolderName = one.getRootFolderText();
}
IFolder binFolder = project.getFolder(transformationFolderName);
if (!binFolder.exists()) {
one.createNewFolder(binFolder, false, true, null);
// Checks if user wants to create a CD example file
if (one.createCDExampleFile()) {
InputStream demoFileContents = null;
try {
// If the user wants to, an example file is created
URL url = new URL("platform:/plugin/cdtrans-editor/src/main/resources/exampleFiles/RefactorCDs");
InputStream inputStream = url.openConnection().getInputStream();
binFolder.getFile("RefactorCDs.cdtr").create(inputStream, true, null);
}
catch (IOException e) {
Log.error("TransProjectWizard: Error while creating Demo file", e);
MessageDialog.openError(this.workbench.getActiveWorkbenchWindow().getShell(),
"Example file creation error", "There was an error while creating the example file");
}
finally {
if (demoFileContents != null) {
try {
demoFileContents.close();
}
catch (IOException e) {
Log.error("TransProjectWizard: Error while closing file stream", e);
}
}
}
}
BasicNewResourceWizard.selectAndReveal(binFolder, this.workbench.getActiveWorkbenchWindow());
}
}
catch (CoreException e) {
Log.error("TransProjectWizard: Error while creating new Project", e);
}
}
return true;
}
}
But if I start this there is a runtime error if I try to open the wizard which says:
I already tried to export the plug-in and install it in a fresh Eclipse installation, where the m2e package is installed, but with the same result.
Any thoughts on how to fix it?

Why isn't this Java jar working?

When I run the code below I get the following error.
C:\Documents and Settings\BOS\Desktop\test>java -jar test.jar
Exception in thread "main" java.lang.NullPointerException
at sun.launcher.LauncherHelper.getMainClassFromJar(Unknown Source)
at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
I've got these files in \test directory = crimson.jar robosuite-api.jar and test.jar.
Here is the example they give to launch a robot?
import com.kapowtech.robosuite.api.java.rql.*;
public class SimpleRunRobot {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: RunRobot <robotURL>");
System.exit(1);
}
try {
// Run the robot
RQLResult result =
RobotExecutor.getRobotExecutor().execute(args[0]);
// Output the results
System.out.println(result);
}
catch (RQLException e) {
System.out.println("An error occurred: " + e);
}
}
}
Why is this giving me that Unknown Source error?
package robosuite.robots;
import com.kapowtech.robosuite.api.java.rql.RQLException;
import com.kapowtech.robosuite.api.java.rql.RQLResult;
import com.kapowtech.robosuite.api.java.rql.RobotExecutor;
import com.kapowtech.robosuite.api.java.rql.construct.RQLObjects;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
*
* <p>
* This is an autogenerated class. It has been generated from the
* <code>library:/test.robot</code> file.
*
* #author RoboSuite
*/
public class Test {
// ----------------------------------------------------------------------
// Class fields
// ----------------------------------------------------------------------
private static final String ROBOT_URL = "library:/test.robot";
private static final RobotExecutor ROBOT_EXECUTOR = RobotExecutor.getRobotExecutor(SingletonRQLEngine.getInstance());
private static final Converter CONVERTER = Converter.getInstance();
// ----------------------------------------------------------------------
// Constructors
// ----------------------------------------------------------------------
/**
* Creates a new Test instance that can be used to execute the
* <code>library:/test.robot</code>.
*/
public Test() {
}
// ----------------------------------------------------------------------
// Instance methods
// ----------------------------------------------------------------------
/**
* Executes this robot.
*
* #param test an input object to the robot.
* #return an array of output objects.
* #throws java.io.IOException if the execution fails for some reason.
*/
public Testst[] run(Test0 test) throws java.io.IOException {
try {
// Prepare input objects
List parameters = new ArrayList();
parameters.add(test);
RQLObjects inputObjects = CONVERTER.convertBeansToRQLObjects(parameters);
// Run robot
RQLResult rqlResult = ROBOT_EXECUTOR.execute(ROBOT_URL, inputObjects);
// Extract output objects
RQLObjects outputObjects = rqlResult.getOutputObjects();
List result = CONVERTER.convertRQLObjectsToBeans(outputObjects);
return (Testst[]) result.toArray(new Testst[result.size()]);
} catch (RQLException e) {
throw new IOException(e.toString());
}
}
/* ------------------------------------------------------------------- */
}
If your using Java 7, Read this.
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7067922
Try
java -cp test.jar
include your other .jar files also
If you are using a manifest file make sure you have defined your main class.
for e.g.
Main-Class: test.MyApp
You have to add the name of the class having main() method in META-INF/manifest file.
Here is the link with more information :
http://java.sun.com/developer/Books/javaprogramming/JAR/basics/manifest.html
Thanks.
Why is this giving me that Unknown Source error?
The "unknown source" messages are not an error. It is the JVM telling you that the code that you are executing was compiled without any debug information; e.g. with the -gLnone option. As a result, the source file names and line numbers that would normally be included in the stacktrace are not available.
In this case, the code is some platform specific stuff that is internal to the JVM. Don't worry about it ...

Start/Stop services using JNA

I am writing a utility to start and stop windows services. The program will be distributed across many computers with differing levels of user privileges so I don't want to use the command line. I've tried using JNA,
import com.sun.jna.platform.win32.W32Service;
import com.sun.jna.platform.win32.W32ServiceManager;
import com.sun.jna.platform.win32.Winsvc;
/**
*
* #author
*/
public class WindowsServices {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try
{
// TODO code application logic here
W32ServiceManager serviceManager = new W32ServiceManager();
W32Service service = serviceManager.openService("uvnc_service", Winsvc.SERVICE_ACCEPT_STOP);
service.stopService();
service.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
When I run the program I get the following error
com.sun.jna.platform.win32.Win32Exception: The handle is invalid.
at com.sun.jna.platform.win32.W32ServiceManager.openService(W32ServiceManager.java:77)
at windowsservices.WindowsServices.main(WindowsServices.java:26)
Any suggestions would be most helpful.
Thanks for the suggestion the author of the question found the error.
import com.sun.jna.platform.win32.W32Service;
import com.sun.jna.platform.win32.W32ServiceManager;
import com.sun.jna.platform.win32.Winsvc;
/**
*
* #author
*/
public class WindowsServices {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try
{
W32ServiceManager serviceManager = new W32ServiceManager();
serviceManager.open(Winsvc.SC_MANAGER_ALL_ACCESS);
W32Service service = serviceManager.openService("uvnc_service", Winsvc.SC_MANAGER_ALL_ACCESS);
service.startService();
service.close();
} catch (Exception ex)
{
ex.printStackTrace();
}
}
}
The error was that the code didn't open the Service Control Manager. I was looking on MSDN and found the process that I needed to follow. I also chanced the permission value, that might also of caused a failure.
We use Runtime.getRuntime().exec(command) and then execute the command
cmd /c net start
to start services and
cmd /c net stop
to stop services.
Of course you have to know the service names (and in our case it is DB2 we are after). But this has worked for us.

Error importing classes for RDF crawler

I'm using a rdf crawler, in that I had a class named as:
import edu.unika.aifb.rdf.crawler.*;
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.util.FileManager;
These are class file termed as error, and I try with jena packages but I had attached, it does not make any changes.
Update:
Full SampleCrawl.java class content:
import java.util.*;
import edu.unika.aifb.rdf.crawler.*;
/**
* Call this class with 3 arguments - URL to crawl to,
* depth and time in seconds
*/
public class SampleCrawl {
/**
* #param uRI
* #param depth
* #param time
*/
#SuppressWarnings("rawtypes")
public SampleCrawl(Vector uRI, Vector hf, int depth, int time){
// Initialize Crawling parameters
CrawlConsole c = new CrawlConsole(uRI,hf,depth,time);
// get an ontology file from its local location
// (OPTIONAL)
c.setLocalNamespace("http://www.daml.org/2000/10/daml-ont","c:\\temp\\rdf\\schemas\\daml-ont.rdf");
// set all the paths to get all the results
c.setLogPath("c:\\temp\\crawllog.xml");
c.setCachePath("c:\\temp\\crawlcache.txt");
c.setModelPath("c:\\temp\\crawlmodel.rdf");
try{
// crawl and get RDF model
c.start();
// This writes all three result files out
c.writeResults();
}catch(Exception e){
}
}
/**
* #param args
* #throws Exception
*/
#SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) throws Exception {
if (args.length != 3) {
System.err.println("Usage: java -cp [JARs] SampleCrawl [URL] [depth:int] [time:int]");
System.exit(0);
}
Vector uris = new Vector();
uris.add(args[0]);
// no host filtering - crawl to all hosts
Vector hostfilter = null;
/* You may want to do something else to enable host filtering:
* Vector hostfilter = new Vector();
* hostfilter.add("http://www.w3.org");
*/
int depth = 2;
int time = 60;
try {
depth = Integer.parseInt(args[1]);
time = Integer.parseInt(args[2]);
}
catch (Exception e) {
System.err.println("Illegal argument types:");
System.err.println("Argument list: URI:String depth:int time(s):int");
System.exit(0);
}
new SampleCrawl(uris,hostfilter,depth,time);
}
}
Question:
How to add import edu.unika.aifb.rdf.crawler.; error occurs here
I googled the package that you're trying to import, and it appears that you're using Kaon. Assuming that's so, you have made an error in your import declaration. You have:
import edu.unika.aifb.rdf.crawler.*;
whereas the download available on SourceForge would require:
import edu.unika.aifb.rdf.rdfcrawler.*;
As an aside, it would be helpful if you would include information, such as "I'm trying to use Kaon's rdfcrawler from ..." in your question. Otherwise, we have to try to guess important details in your setup.

Categories

Resources