i'm trying to develop an application for a universal keyboard which is for camera controlling. I'm able to communicate with device in some basic way on Linux over /dev/ttyACM0 pseudo terminal device. But as far as i know, this doesn't exist in Windows and i'm little bit confused when i examine the samples for comm API and rxtx library.
How can i communicate with this device like i can simply do on Linux? Here is the instractions manual for keyboard: http://www.videotec.com/dep/DCZ_1051.pdf
And here is the code:
Class1.java
package customkeyboard;
import java.io.FileInputStream;
import org.apache.commons.codec.binary.Hex;
public class CustomKeyboard {
public static void main(String[] args) {
// TODO code application logic here
FileInputStream in = null;
try {
in = new FileInputStream("/dev/ttyACM0");
int c = 0;
int streamCounter = 0;
String command = "";
CustomKeyboard2 key2 = new CustomKeyboard2();
key2.main(null);
while ((c = in.read()) != -1) {
if (streamCounter < 6) {
//System.out.print( + " - ");
command += Integer.toHexString(c);
streamCounter++;
if (streamCounter == 6) {
streamCounter = 0;
System.out.println(command);
byte[] bytes = Hex.decodeHex(command.toCharArray());
String deastranza = new String ( bytes, "UTF-8");
System.out.println(deastranza);
command = "";
}
} else {
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Class2.java
package customkeyboard;
import java.io.FileOutputStream;
import org.apache.commons.codec.binary.Hex;
public class CustomKeyboard2 {
public static void main(String[] args) {
try {
FileOutputStream out = null;
out = new FileOutputStream("/dev/ttyACM0");
String command = "[LedImmediate]";
byte[] message = command.getBytes("UTF-8");
out.write(message);
command = "[Led+45]";
message = command.getBytes();
out.write(message);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Related
Hello everyone, Java beginner here. I am trying to run some java code in eclipse IDE, and set my args x = 25 from
Run > Run Configurations > Arguments > Apply > Run. However, before I can get to Arguments, I get this error message (see photo below). Does anyone know what this means or why I am getting this? What does this specific '.metadata/.plugins/org.eclipse.debug.core' do?
MY CODE BELOW:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
public class IOTest {
public IOTest () {
}
public void readFile () {
try {
FileReader file = new FileReader("movies.txt");
BufferedReader br = new BufferedReader(file);
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
br.close();
} catch (Exception e) {
System.out.println("Unable to load file.");
}
}
public void writeFile () {
try {
FileWriter file = new FileWriter("tvshows.txt");
BufferedWriter bw = new BufferedWriter(file);
bw.write("Seinfeld\n");
bw.write("Breaking Bad\n");
bw.write("The Simpsons\n");
bw.write("Family Guy\n");
bw.close();
} catch (Exception e) {
System.out.println("Unable to load/create file.");
}
}
public static void main(String[] args) {
IOTest test = new IOTest();
test.readFile();
test.writeFile();
if (args.length == 1) {
// Do something.
int x = Integer.parseInt(args[0]);
System.out.println("x = " + x);
} else {
// Do something else.
}
}
}
I need some help with a IllegalStateException in Java.
I got a sourcecode that should read out Data from a USB Device.
That code is not finished yet, but I already got the following error report
Exception in thread "main" java.lang.IllegalStateException: default context is not initialized at org.usb4java.Libusb.exit(Native Method) at testnew.main(testnew.java:122)
Line 122 is LibUsb.exit(null)
Code is below
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import javax.usb.UsbConfiguration;
import javax.usb.UsbDevice;
import javax.usb.UsbDeviceDescriptor;
import javax.usb.UsbDisconnectedException;
import javax.usb.UsbException;
import javax.usb.UsbHostManager;
import javax.usb.UsbHub;
import javax.usb.UsbInterface;
import javax.usb.UsbInterfacePolicy;
import javax.usb.UsbNotActiveException;
import javax.usb.event.UsbPipeDataEvent;
import javax.usb.event.UsbPipeErrorEvent;
import javax.usb.event.UsbPipeListener;
import org.usb4java.BufferUtils;
import org.usb4java.DeviceHandle;
import org.usb4java.LibUsb;
import org.usb4java.LibUsbException;
public class testnew {
private final static short VENDOR_ID = 0x0403;
private final static short PRODUCT_ID = 0x6001;
private static byte IN_ENDPOINT = (byte) 0x81;
private static long TIMEOUT = 5000;
private final static int INTERFACE = 0;
private final static Object CONNECT_HEADER = 000;
private final static Object CONNECT_BODY = 000;
public static UsbDevice getHygrometerDevice(UsbHub hub) {
UsbDevice launcher = null;
for (Object object : hub.getAttachedUsbDevices()) {
UsbDevice device = (UsbDevice) object;
if (device.isUsbHub()) {
launcher = getHygrometerDevice((UsbHub) device);
if (launcher != null)
return launcher;
} else {
UsbDeviceDescriptor desc = device.getUsbDeviceDescriptor();
if (desc.idVendor() == VENDOR_ID && desc.idProduct() == PRODUCT_ID)
return device;
}
}
return null;
}
public static char readKey() {
try {
String line = new BufferedReader(new InputStreamReader(System.in)).readLine();
if (line.length() > 0)
return line.charAt(0);
return 0;
} catch (IOException e) {
throw new RuntimeException("Unable to read key", e);
}
}
public static ByteBuffer read(DeviceHandle handle, int size) {
ByteBuffer buffer = BufferUtils.allocateByteBuffer(size).order(ByteOrder.LITTLE_ENDIAN);
IntBuffer transferred = BufferUtils.allocateIntBuffer();
int result = LibUsb.bulkTransfer(handle, IN_ENDPOINT, buffer, transferred, TIMEOUT);
if (result != LibUsb.SUCCESS) {
throw new LibUsbException("Unable to read data", result);
}
System.out.println(transferred.get() + " bytes read from device");
return buffer;
}
public static void main(String[] args) {
// Search for the missile launcher USB device and stop when not found
UsbDevice device;
try {
device = getHygrometerDevice(UsbHostManager.getUsbServices().getRootUsbHub());
if (device == null) {
System.err.println("Missile launcher not found.");
System.exit(1);
return;
}
// Claim the interface
UsbConfiguration configuration = device.getUsbConfiguration((byte) 1);
UsbInterface iface = configuration.getUsbInterface((byte) INTERFACE);
iface.claim(new UsbInterfacePolicy() {
#Override
public boolean forceClaim(UsbInterface usbInterface) {
return true;
}
});
iface.getUsbEndpoint(IN_ENDPOINT).getUsbPipe().addUsbPipeListener(new UsbPipeListener() {
#Override
public void errorEventOccurred(UsbPipeErrorEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void dataEventOccurred(UsbPipeDataEvent arg0) {
for (byte b : arg0.getData())
System.out.print(b);
System.out.print("\n");
}
});
;
} catch (UsbNotActiveException | UsbDisconnectedException | UsbException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Deinitialize the libusb context
LibUsb.exit(null);
}
}
Any suggestions?
you did not initialize the context this is why you get the error when you try to deinitialize it, see http://www.programcreek.com/java-api-examples/index.php?api=org.usb4javaLibUsb example 17
public static void main(String[] args)
{
//Initialize the libusb context
int result = LibUsb.Init(null);
if (result != LibUsb.SUCCESS){
throw new LibUsbException("Unable to initialze libusb",result);
}
[...]
how to open the pipe depends on what transfer type you want to choose (bulk transfer, sychronous transfer, asynchronous transfer), see http://usb4java.org/quickstart/javax-usb.html
for synchronous transfer you can use (copied from http://usb4java.org/quickstart/javax-usb.html)
UsbEndpoint endpoint = iface.getUsbEndpoint((byte) 0x83);
UsbPipe pipe = endpoint.getUsbPipe();
pipe.open();
try
{
byte[] data = new byte[8];
int received = pipe.syncSubmit(data);
System.out.println(received + " bytes received");
}
finally
{
pipe.close();
}
There are IN endpoints and OUT endpoints, you write to OUT and read from IN. Control transfers go to EP0. All USB communication is initiated by the host device, meaning the USB device can not even initiate a communication.
for deeper information on USB protocol see http://www.beyondlogic.org/usbnutshell/usb1.shtml
I was testing a little piece of code that I need to implement in a Java school project.
public class Prova {
public static void main(String[] args){
System.out.println(args.length);
for(int i = 0; i < args.length; i++){
System.out.print(args[i]);
}
System.out.print("\nEnd!");
}
}
When I type in the console java Prova < test.dot while the content of the test.dot file is:
digraph G1 {
c -> e;
a -> e;
a -> f;
f -> b;
g;
}
I just get this:
C:\Users\Lorenzo\workspace\Progetto_ASD\bin>java Prova < test.dot
0
End!
I tryed java Prova > output.txt just to see if the pipe worked and it does (I get the same as above but in a file).
If I try type test.dot I get:
C:\Users\Lorenzo\workspace\Progetto_ASD\bin>type test.dot
digraph G1 {
c -> e;
a -> e;
a -> f;
f -> b;
g;
}
As I would expect.
I really don't know what's wrong with what I'm doing (I'm using Windows by the way).
You are mixing 2 different approaches:
args
You should run the program as java Prova arg1 arg2 ... argn:
java Prova "digraph G1 {" "c -> e;" "a -> e;" "a -> f;" "f -> b;" g; }
and probably you want to change
System.out.print(args[i]);
to
System.out.println(args[i]);
to have 7 different lines.
Redirection
This is equivalent to a program that accepts your input from keyboard. You can change your program to look like this:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Prova {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
try {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
and then call
java Prova < test.dot.
are you reading from a file ?
So you need to know more about the java.io.FileInputStream
this is an example of code can help you
https://www.mkyong.com/java/how-to-read-file-in-java-fileinputstream
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class ReadFileExample {
public static void main(String[] args) {
File file = new File("C:/robots.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
System.out.println("Total file size to read (in bytes) : "
+ fis.available());
int content;
while ((content = fis.read()) != -1) {
// convert to char and display it
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
ps: you need to close the stream and release any ressource for a good practice.
I am a student who is studying java.(Especially Raspberry pi) I have a question this multuthread. It can be compiled. But it doesn't work in my kit. If you don't mind guys, could you check my code and help me?
Thanks...
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.File;
import java.io.FileWriter;
public class RcvThread2 implements Runnable{
private static final int sizeBuf = 50;
private Socket clientSocket;
private Logger logger;
private SocketAddress clientAddress;
public RcvThread2(Socket clntSock, SocketAddress clientAddress, Logger logger) {
this.clientSocket = clntSock;
this.logger = logger;
this.clientAddress = clientAddress;
}
static class CloseExtends extends Thread {
static final String GPIO_OUT = "out";
static final String GPIO_ON = "1";
static final String GPIO_OFF = "0";
static final String[] GpioChannels = {"18"};
public static void main(String[] args) {
FileWriter[] commandChannels;
try {
FileWriter unexportFile = new FileWriter("sys/class/gpio/unexport");
FileWriter exportFile = new FileWriter("sys/class/gpio/gpio/export");
for(String gpioChannel : GpioChannels) {
System.out.println(gpioChannel);
File exportFileCheck =
new File("sys/class/gpio/gpio" +gpioChannel);
if(exportFileCheck.exists()) {
unexportFile.write(gpioChannel);
exportFile.flush();
}
exportFile.write(gpioChannel);
exportFile.flush();
FileWriter directionFile = new FileWriter("/sys/class/gpio/gpio" + gpioChannel + "/direction");
directionFile.write(GPIO_OUT);
directionFile.flush();
}
FileWriter commandChannel = new FileWriter("sys/class/gpio/gpio" + GpioChannels[0] + "/value");
int period = 20;
int repeatLoop = 25;
int counter;
while(true) {
for(counter = 0; counter < repeatLoop; counter++) {
commandChannel.write(GPIO_ON);
commandChannel.flush();
java.lang.Thread.sleep(2, 20000);
commandChannel.write(GPIO_OFF);
commandChannel.flush();
java.lang.Thread.sleep(period);
}
break;
}
} catch(Exception exception) {
exception.printStackTrace();
}
}
}
public void main(){
try {
InputStream ins = clientSocket.getInputStream();
OutputStream outs = clientSocket.getOutputStream();
int rcvBufSize;
byte[] rcvBuf = new byte[sizeBuf];
while ((rcvBufSize = ins.read(rcvBuf)) != -1) {
String rcvData = new String(rcvBuf, 0, rcvBufSize, "UTF-8");
if(rcvData.compareTo("MotorLock") == 0) {
CloseExtends te = new CloseExtends();
te.start();
}
if(rcvData.compareTo("MotorOpen") == 0) {
}
logger.info("Received data :" + rcvData + " (" + clientAddress + ")");
outs.write(rcvBuf, 0, rcvBufSize);
}
logger.info(clientSocket.getRemoteSocketAddress() + "Closed");
} catch (IOException ex) {
logger.log(Level.WARNING, "Exception in RcvThread", ex);
}finally {
try{
clientSocket.close();
System.out.println("Disconnected! Client IP :" + clientAddress);
} catch (IOException e) {}
}
}
}
The lower main method never gets called.
If you run your program it will execute the public static void main(String[] args) { method.
I think this is the method you want to run in the second thread?!
If you declare and run your new thread using
CloseExtends te = new CloseExtends();
te.start();
it will run the threads public void run() { method.
So if I understand your intention correctly you should change the name of the main method in the CloseExtends class to the threads run method and change the signature of the lower main method to the java programs main method public static void main(String[] args) {.
I would not name any other method "main" if it is not really a main method.
You can see an example of creating a new thread with the Runnable interface here: https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html
package com.intel.bluetooth.javadoc.ServicesSearch;
import java.io.IOException;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.obex.*;
//import java.util.Vector;
public class ObexPutClient {
public static void main(String[] args) throws IOException, InterruptedException {
String serverURL = null; // = "btgoep://0019639C4007:6";
if ((args != null) && (args.length > 0)) {
serverURL = args[0];
}
if (serverURL == null) {
String[] searchArgs = null;
// Connect to OBEXPutServer from examples
// searchArgs = new String[] { "11111111111111111111111111111123" };
**ServicesSearch**.main(searchArgs);
if (ServicesSearch.serviceFound.size() == 0) {
System.out.println("OBEX service not found");
return;
}
// Select the first service found
serverURL = (String)ServicesSearch.serviceFound.elementAt(0);
}
System.out.println("Connecting to " + serverURL);
ClientSession clientSession = (ClientSession) Connector.open(serverURL);
HeaderSet hsConnectReply = clientSession.connect(null);
if (hsConnectReply.getResponseCode() != ResponseCodes.OBEX_HTTP_OK) {
System.out.println("Failed to connect");
return;
}
HeaderSet hsOperation = clientSession.createHeaderSet();
hsOperation.setHeader(HeaderSet.NAME, "Hello.txt");
hsOperation.setHeader(HeaderSet.TYPE, "text");
//Create PUT Operation
Operation putOperation = clientSession.put(hsOperation);
// Send some text to server
byte data[] = "Hello world!".getBytes("iso-8859-1");
OutputStream os = putOperation.openOutputStream();
os.write(data);
os.close();
putOperation.close();
clientSession.disconnect(null);
clientSession.close();
}
}
Can anyone help me?The error is in bold letters.
Thank You
Do you have ServicesSearch created? Or included? and imported (in case it exists in some other package).
Show us the code, and tell us more.